- settings.agent.autoInvestigateMode investigate|recover, investigateMaxAttempts, recoverVerifySec - new capability download.recheck (execute, replay never): qB force recheck / resume, no source swap/delete - autoInvestigate moves to agent/investigate.ts: recover mode runs execute with a recovery allowlist only when an active grant (published policy if bound) covers the recovery actions; otherwise degrades to read-only investigation and leaves suggestion + recheck option on the decision - runAgent verifies recovery against business facts (download_task/task/source_release) before finalize; verified -> decision resolved by system:auto-recover, run summary '已恢复(系统核实)'; otherwise stays awaiting_user; per-root-cause attempt cap - e2e E6: missingFiles -> download_failed -> recheck -> verified; no grant degrades; swap rejected; dedupe; attempts exhausted; budget exceeded keeps attention Co-Authored-By: Claude Opus 5.5 <[email protected]>
247 lines
10 KiB
TypeScript
247 lines
10 KiB
TypeScript
import { z } from "zod";
|
|
import { Id, Timestamp } from "./common.ts";
|
|
|
|
// 全局设置:存于 settings 表(key → jsonb)。每个顶层分组对应一个 settings.key。
|
|
// schema 本身不带 .default()(zod 4 在 partial 里仍会套默认值,会让 PATCH 覆盖现值);
|
|
// 缺省值统一放在 DEFAULT_SETTINGS,服务端读取时 `{ ...DEFAULT_SETTINGS[key], ...stored }` 后再 parse。
|
|
|
|
const Percent = z.number().min(1).max(100);
|
|
|
|
export const AutomationSettings = z.object({
|
|
/** 自动化总开关:关闭后所有自动收录/下载/整理停止,只读查询与手动操作可用 */
|
|
enabled: z.boolean(),
|
|
/** 恢复后的只读对账模式(REQ §8.5):开启时禁止自动写入 */
|
|
readOnlyReconcile: z.boolean(),
|
|
});
|
|
export type AutomationSettings = z.infer<typeof AutomationSettings>;
|
|
|
|
const CacheShape = z.object({
|
|
/** 缓存卷使用率硬阈值:达到即停止新增下载并暂停纳管下载中任务 */
|
|
hardThresholdPercent: Percent,
|
|
/** 恢复水位:降到此值以下恢复因阈值暂停的任务 */
|
|
resumePercent: Percent,
|
|
checkIntervalSec: z.number().int().min(10).max(3600),
|
|
/** 缓存清理的目标使用率(低水位) */
|
|
cleanupTargetPercent: Percent,
|
|
});
|
|
/** 下载缓存卷硬阈值与恢复水位(REQ §8.4.1) */
|
|
export const CacheSettings = CacheShape.refine((v) => v.resumePercent < v.hardThresholdPercent, {
|
|
message: "恢复水位必须低于硬阈值",
|
|
}).refine((v) => v.cleanupTargetPercent <= v.resumePercent, { message: "清理目标不得高于恢复水位" });
|
|
export type CacheSettings = z.infer<typeof CacheSettings>;
|
|
|
|
export const OrganizeMode = z.enum(["copy", "move"]);
|
|
export type OrganizeMode = z.infer<typeof OrganizeMode>;
|
|
export const OrganizeSettings = z.object({
|
|
defaultMode: OrganizeMode,
|
|
/** 跨卷 Move 采用 Copy→核验→删源;EXDEV 不静默降级 */
|
|
allowCrossVolumeMove: z.boolean(),
|
|
});
|
|
export type OrganizeSettings = z.infer<typeof OrganizeSettings>;
|
|
|
|
export const RetentionSettings = z.object({
|
|
/** Copy 入库后下载源在缓存中至少保留的天数(与 H&R 要求分开判断) */
|
|
seedRetentionDays: z.number().int().min(0).max(365),
|
|
/** 观察/日志类数据保留天数 */
|
|
logRetentionDays: z.number().int().min(1).max(3650),
|
|
});
|
|
export type RetentionSettings = z.infer<typeof RetentionSettings>;
|
|
|
|
export const ThinkingLevel = z.enum(["off", "minimal", "low", "medium", "high", "xhigh"]);
|
|
export type ThinkingLevel = z.infer<typeof ThinkingLevel>;
|
|
|
|
/** Pi Agent 设置(REQ §10.5):上游/模型/思考档位/上下文预算/压缩/子代理;密钥只存 secret 引用 */
|
|
export const PiSettings = z.object({
|
|
provider: z.string().min(1),
|
|
baseUrl: z.url().nullable(),
|
|
model: z.string().min(1).nullable(),
|
|
thinkingLevel: ThinkingLevel,
|
|
/** 上下文预算(token) */
|
|
contextBudget: z.number().int().min(4096).max(2_000_000),
|
|
compaction: z.object({
|
|
enabled: z.boolean(),
|
|
/** 达到上下文预算的该比例时触发压缩 */
|
|
thresholdRatio: z.number().min(0.3).max(0.95),
|
|
}),
|
|
subagentsEnabled: z.boolean(),
|
|
apiKeySecretRef: Id.nullable(),
|
|
});
|
|
export type PiSettings = z.infer<typeof PiSettings>;
|
|
|
|
/**
|
|
* Agent 运行参数(REQ §10.5、§10.7):单次运行预算、后台自动调查、fake 演示脚本。
|
|
* 上游/模型/思考档位在 pi 分组;pi.provider = "fake" 时使用脚本化假模型(不联网,演示与 e2e 用)。
|
|
*/
|
|
export const AgentRuntimeSettings = z.object({
|
|
/** 识别歧义 / 下载失败诊断等待处理事项创建时,自动发起有界调查 */
|
|
autoInvestigate: z.boolean(),
|
|
/**
|
|
* 自动调查的模式:investigate = 只读调查,结论交还人工;
|
|
* recover = 在已发布策略 / 持续授权范围内可执行恢复类能力(task.retry、download.recheck、identity.resolve),
|
|
* 换源、删除、清理始终排除;没有覆盖的授权时自动降级为 investigate。
|
|
*/
|
|
autoInvestigateMode: z.enum(["investigate", "recover"]),
|
|
/** 同一根因(decision 去重键)最多自动恢复几次;用尽后只交还人工,不再唤醒模型 */
|
|
investigateMaxAttempts: z.number().int().min(1).max(10),
|
|
/** 恢复动作后等待业务事实(下载状态 / 任务状态)核实的最长时间(秒) */
|
|
recoverVerifySec: z
|
|
.number()
|
|
.int()
|
|
.min(5)
|
|
.max(24 * 3600),
|
|
/** 单次运行:工具调用次数上限 */
|
|
maxToolCalls: z.number().int().min(1).max(500),
|
|
/** 单次运行:时长上限(秒) */
|
|
maxDurationSec: z
|
|
.number()
|
|
.int()
|
|
.min(10)
|
|
.max(24 * 3600),
|
|
/** 单次运行:token 上限(null = 不限) */
|
|
maxTokensPerRun: z.number().int().positive().nullable(),
|
|
/** 单次运行:费用上限(美元,null = 不限) */
|
|
maxCostUsdPerRun: z.number().positive().nullable(),
|
|
/** 后台自动调查的工具调用上限(比用户委托更小) */
|
|
investigateMaxToolCalls: z.number().int().min(1).max(100),
|
|
/** 等待目标关联的下载/入库结束时的轮询间隔(秒) */
|
|
goalPollSec: z.number().int().min(1).max(3600),
|
|
/** 等待目标完成的最长时间(小时),超时后以"仍在等待"汇报结束 */
|
|
goalWaitHours: z
|
|
.number()
|
|
.min(0)
|
|
.max(24 * 30),
|
|
/** fake 模式脚本(JSON,FakeScript 的可序列化子集);null 用内置演示脚本 */
|
|
fakeScript: z.string().max(100_000).nullable(),
|
|
/**
|
|
* Agent JSONL 会话目录(绝对路径,api 与 worker 进程都要能读写);
|
|
* null = 部署默认(环境变量 AGENT_SESSION_DIR,缺省 DATA_DIR/agent-sessions)
|
|
*/
|
|
sessionDir: z.string().max(1024).regex(/^\//, "必须是绝对路径").nullable(),
|
|
});
|
|
export type AgentRuntimeSettings = z.infer<typeof AgentRuntimeSettings>;
|
|
|
|
/** 元数据源(TMDB):密钥只存 secret 引用;未配置时回退环境变量 TMDB_API_KEY / TMDB_ACCESS_TOKEN */
|
|
export const MetadataSettings = z.object({
|
|
tmdbApiKeySecretRef: Id.nullable(),
|
|
/** 自建反代或测试 mock;null 用官方地址 */
|
|
tmdbBaseUrl: z.url().nullable(),
|
|
});
|
|
export type MetadataSettings = z.infer<typeof MetadataSettings>;
|
|
|
|
/** 每日预算与并发(REQ §6.4、§10.5) */
|
|
export const BudgetSettings = z.object({
|
|
maxNewTitlesPerDay: z.number().int().min(0),
|
|
maxDownloadBytesPerDay: z.number().int().min(0),
|
|
maxConcurrentDownloads: z.number().int().min(1).max(100),
|
|
agentMaxRunsPerDay: z.number().int().min(0),
|
|
agentMaxCostUsdPerDay: z.number().min(0),
|
|
});
|
|
export type BudgetSettings = z.infer<typeof BudgetSettings>;
|
|
|
|
export const GlobalSettings = z.object({
|
|
automation: AutomationSettings,
|
|
cache: CacheSettings,
|
|
organize: OrganizeSettings,
|
|
retention: RetentionSettings,
|
|
pi: PiSettings,
|
|
budget: BudgetSettings,
|
|
agent: AgentRuntimeSettings,
|
|
metadata: MetadataSettings,
|
|
});
|
|
export type GlobalSettings = z.infer<typeof GlobalSettings>;
|
|
|
|
/** settings 表的合法 key */
|
|
export const SettingsKey = GlobalSettings.keyof();
|
|
export type SettingsKey = z.infer<typeof SettingsKey>;
|
|
|
|
/** 缺省设置(settings 表缺 key 或缺字段时使用) */
|
|
export const DEFAULT_SETTINGS: GlobalSettings = {
|
|
automation: { enabled: true, readOnlyReconcile: false },
|
|
cache: { hardThresholdPercent: 90, resumePercent: 85, checkIntervalSec: 60, cleanupTargetPercent: 80 },
|
|
organize: { defaultMode: "copy", allowCrossVolumeMove: true },
|
|
retention: { seedRetentionDays: 7, logRetentionDays: 180 },
|
|
pi: {
|
|
provider: "anthropic",
|
|
baseUrl: null,
|
|
model: null,
|
|
thinkingLevel: "medium",
|
|
contextBudget: 128_000,
|
|
compaction: { enabled: true, thresholdRatio: 0.8 },
|
|
subagentsEnabled: false,
|
|
apiKeySecretRef: null,
|
|
},
|
|
budget: {
|
|
maxNewTitlesPerDay: 20,
|
|
maxDownloadBytesPerDay: 500 * 1024 ** 3,
|
|
maxConcurrentDownloads: 5,
|
|
agentMaxRunsPerDay: 50,
|
|
agentMaxCostUsdPerDay: 5,
|
|
},
|
|
agent: {
|
|
autoInvestigate: false,
|
|
autoInvestigateMode: "investigate",
|
|
investigateMaxAttempts: 2,
|
|
recoverVerifySec: 600,
|
|
maxToolCalls: 40,
|
|
maxDurationSec: 900,
|
|
maxTokensPerRun: null,
|
|
maxCostUsdPerRun: null,
|
|
investigateMaxToolCalls: 8,
|
|
goalPollSec: 60,
|
|
goalWaitHours: 72,
|
|
fakeScript: null,
|
|
sessionDir: null,
|
|
},
|
|
metadata: { tmdbApiKeySecretRef: null, tmdbBaseUrl: null },
|
|
};
|
|
|
|
/** PATCH /settings:按分组部分更新;服务端与现值合并后用 GlobalSettings 整体再校验 */
|
|
export const GlobalSettingsUpdate = z.object({
|
|
automation: AutomationSettings.partial().optional(),
|
|
cache: CacheShape.partial().optional(),
|
|
organize: OrganizeSettings.partial().optional(),
|
|
retention: RetentionSettings.partial().optional(),
|
|
pi: PiSettings.omit({ apiKeySecretRef: true })
|
|
.partial()
|
|
.extend({
|
|
compaction: PiSettings.shape.compaction.partial().optional(),
|
|
/** 只写:明文上游密钥,服务端存为 secret 并回填 apiKeySecretRef;传 null 表示清除 */
|
|
apiKey: z.string().min(1).max(4096).nullable().optional(),
|
|
})
|
|
.optional(),
|
|
budget: BudgetSettings.partial().optional(),
|
|
agent: AgentRuntimeSettings.partial().optional(),
|
|
metadata: MetadataSettings.omit({ tmdbApiKeySecretRef: true })
|
|
.partial()
|
|
.extend({
|
|
/** 只写:TMDB API Key(v3 key 或 v4 read token),服务端存为 secret 并回填 tmdbApiKeySecretRef;null 清除 */
|
|
tmdbApiKey: z.string().min(1).max(4096).nullable().optional(),
|
|
})
|
|
.optional(),
|
|
});
|
|
export type GlobalSettingsUpdate = z.infer<typeof GlobalSettingsUpdate>;
|
|
|
|
/** 合并部分更新(纯函数,web 乐观更新与 server 共用) */
|
|
export function mergeSettings(current: GlobalSettings, patch: GlobalSettingsUpdate): GlobalSettings {
|
|
const { apiKey: _apiKey, compaction, ...pi } = patch.pi ?? {};
|
|
const { tmdbApiKey: _tmdbApiKey, ...metadata } = patch.metadata ?? {};
|
|
return {
|
|
automation: { ...current.automation, ...patch.automation },
|
|
cache: { ...current.cache, ...patch.cache },
|
|
organize: { ...current.organize, ...patch.organize },
|
|
retention: { ...current.retention, ...patch.retention },
|
|
pi: { ...current.pi, ...pi, compaction: { ...current.pi.compaction, ...compaction } },
|
|
budget: { ...current.budget, ...patch.budget },
|
|
agent: { ...current.agent, ...patch.agent },
|
|
metadata: { ...current.metadata, ...metadata },
|
|
};
|
|
}
|
|
|
|
/** settings 表行 */
|
|
export const SettingEntry = z.object({
|
|
key: SettingsKey,
|
|
value: z.unknown(),
|
|
updatedAt: Timestamp,
|
|
});
|
|
export type SettingEntry = z.infer<typeof SettingEntry>;
|