feat(server): W2-D agent assembly, session API, runAgent/resolveDecision and backend e2e

- Capabilities: all 14 registered (AO: inventory.query, download.plan/submit, organize.plan/execute,
  policy.preview/apply; agent: task.inspect/retry/cancel); startup asserts count == 14.
  Registry injects server-side authorize (automation_grant by action/scope/policy version/budget,
  one-shot approval bound to plan id + payload hash + revision + expiry; model claims ignored;
  automation switch), audit_event, server idempotency keys and a capability_invocation op ledger
  (migration 0021) used for crash reconciliation. download.plan creates draft plans only;
  download.submit promotes draft -> reserved after authorization.
- Agent session API: POST/GET /agent/runs, GET /agent/runs/{id} (events by seq, messages, report),
  POST .../messages (wake), POST .../abort; automation-grants, approvals, capabilities invoke, tasks.
- runAgent task: Pi or fake provider from settings (apiKey via secrets), events persisted to
  agent_run_event then published, resume + ledger reconciliation when pendingOperations > 0,
  waits for goal-linked downloads/imports and reports from business tables (submitted != imported).
- Background triggers: decision.created -> bounded plan_only investigation (dedupe per decision);
  decision.updated(resolved) -> resolveDecision executes chosen option.
- W2 closure: all OpenAPI routes registered in contracts api.ts (+ subset test); TMDB key from
  settings secret_ref with env fallback; PUT /sites/{id}/credentials documented as alias of
  /site-accounts; completion events documented as existing status events.
- e2e (real PG + OpenWorkflow + testkit mocks): RSS->library, agent delegation with grant/deny,
  background continuation, worker kill -9 recovery (single qB add), auto investigation dedupe.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
rootandClaude Opus 5.5 committed 2026-09-27 20:52:12 +08:00
1 parent 0dec0854df
commit 6280d52ec3
46 files changed
+5133 -111

No files matched your search

+130
View File
@@ -1,4 +1,6 @@
import { z } from "zod";
import { AgentRunEventRow } from "./agent-events.ts";
import { KnownCapabilityId } from "./capability.ts";
import { EntityBase, Id, JsonObject, NonNegInt, SERVER_MANAGED, Timestamp } from "./common.ts";
// 人工/AI 域:Agent 运行、证据/计划产物、待处理事项、审批、持续授权(REQ §10、§11.3、§11.4)
@@ -15,6 +17,9 @@ export const AgentRunStatus = z.enum([
"budget_exceeded",
]);
export type AgentRunStatus = z.infer<typeof AgentRunStatus>;
/** execute:授权范围内边执行边汇报;plan_only:"先给方案",只允许 read/preview/propose 类能力 */
export const AgentRunMode = z.enum(["execute", "plan_only"]);
export type AgentRunMode = z.infer<typeof AgentRunMode>;
/** 单次运行预算(调用次数/token/时长/费用,REQ §10.5) */
export const AgentBudget = z.object({
@@ -60,6 +65,9 @@ export const AgentRun = EntityBase.extend({
startedAt: Timestamp.nullable(),
finishedAt: Timestamp.nullable(),
createdBy: z.string().nullable(),
mode: AgentRunMode,
/** 后台触发按根因去重(如 investigate:<decisionId>);用户委托为 null */
dedupeKey: z.string().nullable(),
});
export type AgentRun = z.infer<typeof AgentRun>;
export const AgentRunCreate = AgentRun.pick({
@@ -283,3 +291,125 @@ export const AutomationGrantUpdate = z.object({
reason: z.string().max(2000).optional(),
});
export type AutomationGrantUpdate = z.infer<typeof AutomationGrantUpdate>;
// ── Agent 会话 API(W2-D) ──
/** POST /agent/runs:建 agent_run + 入队持久任务 runAgent(不在 HTTP 请求里跑模型) */
export const AgentRunStartInput = z.object({
goal: z.string().trim().min(1).max(8000),
mode: AgentRunMode.default("execute"),
/** 能力白名单(缺省按模式给全部可用能力);plan_only 下超出 read/preview/propose 的会被拒绝 */
capabilityAllowlist: z.array(KnownCapabilityId).min(1).max(50).optional(),
});
export type AgentRunStartInput = z.infer<typeof AgentRunStartInput>;
export const AgentRunMessageInput = z.object({ text: z.string().trim().min(1).max(8000) });
export type AgentRunMessageInput = z.infer<typeof AgentRunMessageInput>;
export const AgentRunAbortInput = z.object({ reason: z.string().max(500).optional() });
export type AgentRunAbortInput = z.infer<typeof AgentRunAbortInput>;
export const AgentRunListQuery = z.object({
cursor: z.string().min(1).optional(),
limit: z.coerce.number().int().min(1).max(200).default(50),
status: AgentRunStatus.optional(),
trigger: AgentTrigger.optional(),
});
export type AgentRunListQuery = z.infer<typeof AgentRunListQuery>;
/** 详情里的事件分页:afterSeq(不含)之后按 seq 升序;断线后按最后收到的 runSeq 补读 */
export const AgentRunDetailQuery = z.object({
afterSeq: z.coerce.number().int().min(-1).default(-1),
limit: z.coerce.number().int().min(1).max(1000).default(200),
});
export type AgentRunDetailQuery = z.infer<typeof AgentRunDetailQuery>;
/**
* 目标完成度汇报:由服务端从业务表汇总(下载计划 → 下载任务 → 整理记录),不采信模型文本。
* "已提交"只代表进入下载器;只有整理记录 succeeded 才算入库。
*/
export const AgentGoalReport = z.object({
state: z.enum(["no_actions", "waiting", "completed", "partial", "failed"]),
summary: z.string(),
submitted: NonNegInt,
imported: NonNegInt,
inProgress: NonNegInt,
failed: NonNegInt,
plans: z.array(z.object({ planId: Id, status: z.string(), slotId: Id.nullable(), sourceReleaseId: Id.nullable() })),
downloads: z.array(
z.object({ downloadTaskId: Id, planId: Id.nullable(), status: z.string(), name: z.string().nullable() }),
),
organization: z.array(
z.object({
recordId: Id,
status: z.string(),
downloadTaskId: Id.nullable(),
mediaEntityId: Id.nullable(),
targetPath: z.string().nullable(),
}),
),
/** 模型最终文本(仅供参考,不作为完成依据) */
modelText: z.string().nullable(),
generatedAt: Timestamp,
});
export type AgentGoalReport = z.infer<typeof AgentGoalReport>;
export const AgentRunMessageStatus = z.enum(["pending", "consumed"]);
export type AgentRunMessageStatus = z.infer<typeof AgentRunMessageStatus>;
/** 追加到会话的用户消息(纠正/补充);runAgent 任务按创建顺序消费 */
export const AgentRunMessage = EntityBase.extend({
runId: Id,
text: z.string(),
status: AgentRunMessageStatus,
createdBy: z.string().nullable(),
consumedAt: Timestamp.nullable(),
});
export type AgentRunMessage = z.infer<typeof AgentRunMessage>;
export const AgentRunDetail = z.object({
run: AgentRun,
events: z.array(AgentRunEventRow),
/** 下一页起点(传给 afterSeq);null 表示已到最新 */
nextAfterSeq: z.number().int().nullable(),
messages: z.array(AgentRunMessage),
report: AgentGoalReport.nullable(),
});
export type AgentRunDetail = z.infer<typeof AgentRunDetail>;
/** 单次审批的创建:服务端从计划读取 payloadHash / expectedRevision,调用方只给计划 */
export const ApprovalRequest = z.object({
planType: z.enum(["acquisition_plan", "organize_plan", "policy_revision"]),
planId: Id,
expiresInSec: z
.number()
.int()
.min(60)
.max(30 * 86400)
.default(86400),
reason: z.string().max(2000).optional(),
});
export type ApprovalRequest = z.infer<typeof ApprovalRequest>;
export const CapabilityInvocationStatus = z.enum(["running", "succeeded", "failed"]);
export type CapabilityInvocationStatus = z.infer<typeof CapabilityInvocationStatus>;
/**
* 有副作用能力的操作账本(capability_invocation):幂等键由服务端生成且唯一;succeeded 直接返回记录的输出,
* running(调用中崩溃)按同一幂等键重跑处理器对账。
*/
export const CapabilityInvocation = EntityBase.extend({
idempotencyKey: z.string().min(1),
capabilityId: z.string().min(1),
capabilityVersion: z.number().int().min(1),
agentRunId: Id.nullable(),
actorId: z.string(),
source: z.string(),
status: CapabilityInvocationStatus,
input: JsonObject,
output: JsonObject.nullable(),
error: JsonObject.nullable(),
grantId: Id.nullable(),
approvalId: Id.nullable(),
attempts: NonNegInt,
finishedAt: Timestamp.nullable(),
});
export type CapabilityInvocation = z.infer<typeof CapabilityInvocation>;