本计划只基于当前 worktree,不参考其他分支。目标不是重新实现 subagent,而是在现有 Agent / profile loader / child runtime / RuntimeTaskRegistry 基础上修复 background subagent 的完成唤醒问题,并补齐 foreground subagent 超时自动转后台的核心机制。
期望行为:
Agent(run_in_background=true) 返回 async_launched 后,main agent 可以正常 finish/idle。<task-notification> 作为 background_task synthetic user input 注入 provider request,让 main agent 继续处理结果。这些能力当前已经存在或不属于本轮修复,不放进 P0:
Agent tool 或 Claude Code 兼容的 Task alias。.zcode/agents Markdown 加载、插件 agent 加载。Explore 设为默认 agent。当前省略 subagent_type 时默认 general-purpose;Explore 只是 specialized built-in。general-purpose / Explore built-in profile、child runtime 创建、artifact 写入、SendMessage。TaskCreate / TaskList / TaskUpdate。P1 再考虑:
background_tasks control request / Ctrl+B 等 UI 或 SDK 入口。TaskStop / TaskOutput 兼容面。apps/zcode-cli/packages/core/src/tool/handlers/agent.ts 中 parsed.subagent_type ?? AgentType.GeneralPurpose,省略时默认 general-purpose。apps/zcode-cli/packages/core/src/subagent/profile.ts 中 DEFAULT_SUBAGENT_TYPE = GENERAL_PURPOSE_AGENT_TYPE,normalizeAgentProfiles() 先注册 built-in general-purpose,再注册 built-in Explore,最后覆盖用户/项目/插件 profile。apps/zcode-cli/packages/bootstrap/src/subagents.ts 已加载用户级 ~/.zcode/agents、项目级 .zcode/agents、插件 agents/*.md,并保留 general-purpose / Explore reserved name。apps/zcode-cli/packages/contracts/src/tools/agent.ts 已有 run_in_background,输出包含 completed 和 async_launched 两种状态。apps/zcode-cli/packages/core/src/subagent/runner.ts 里的 createExploreSubagentPort 名字仍偏旧,但实际是 profile-backed port。launch() 根据 runInBackground 或 profile background 决定走 start() 还是 run()。start() 已能直接后台启动:注册 local_agent task,返回 async_launched,子 runtime 异步跑完后调用 finalizeBackgroundCompletion() / finalizeBackgroundFailure()。run() 已能前台转后台:注册 isBackgrounded=false task 后,把 runAgentToCompletion() 和 RuntimeTaskRegistry.waitForBackgroundRequest(agentId) 做 race;如果收到 background request,就立即返回 async_launched,同一个 child completion promise 继续在后台完成。RuntimeTaskRegistry.requestBackground(id) 已能把非 terminal task 标成 isBackgrounded=true 并 resolve waiters。requestBackground() 的 timer 和 lifecycle cleanup。apps/zcode-cli/packages/core/src/runtime/agent-runtime.ts 中 pendingBackgroundTaskNotifications 是 AgentRuntime 私有内存数组。apps/zcode-cli/packages/core/src/runtime/methods/subagent.ts 中 enqueueParentNotification 只是 push({ queuedAt, text, traceContext })。apps/zcode-cli/packages/core/src/runtime/methods/background-notifications.ts 的 drain 会把 notification 写入 messageHistory.addUser(...),并持久化为 source: "background_task"。executeTurn() 和 runRegularTurnLoop() 会在已有 turn/request 前调用 drain,所以“下一次显式用户输入”或“active turn 下一次 model request”能看到 <task-notification>。ExecuteTurnOptions 已支持 inputVisibility: "model-only" 和 inputSource: "background_task",可以作为 idle wake 的最小实现基座。apps/zcode-cli/packages/core/tests/subagent-explore.test.ts 已覆盖默认 general-purpose、background launch、completion 在“后续显式 turn”中被 drain。runtime.executeTurn("continue"),因此没有覆盖“父 turn 已 idle 后自动 wake”。inputVisibility / inputSource。P0 差距:
pendingBackgroundTaskNotifications 是数组,没有 idempotency、claim、batch、wake scheduled / skipped / drained 的状态和日志。requestBackground() 和 foreground race 已有,但没有受配置开关控制的 120000ms timer,也没有完成/失败/取消时取消 timer 的边界。tool_uses,但需要补测试覆盖,防止 background metadata / notification 中 tool_uses 回到 0。参考失败形态:
sess_bc1e9c8a-80a0-4bda-a927-6fde7ec6dc4c 的父 turn 已 finish,子 session 后续正常完成并写出 output,但父 session 没有新的 model request,也没有 background_task synthetic notice。这符合“completion 入队后无人 wake”的根因。把 pendingBackgroundTaskNotifications: PendingBackgroundTaskNotification[] 封装成 runtime 内部 queue API。P0 不引入 SQLite outbox,仍是进程内运行态。
队列设计一开始就按多 runtime task source 预留:本轮优先让 local_agent background subagent 跑通;最后一个 phase 再把 local_bash 和 monitor_mcp 接到同一 queue/wake 设计里。也就是说,API 和幂等字段不要写死 subagent,但前几个 phase 的实现和验收不被 Bash/monitor 拖住。
建议数据形状:
interface PendingBackgroundTaskNotification {
id: string;
taskId?: string;
toolUseId?: string;
source: "local_agent" | "local_bash" | "monitor_mcp";
text: string;
traceContext: TraceContext;
queuedAt: Date;
}
建议 API:
enqueueBackgroundTaskNotification(notification): "queued" | "duplicate";
drainBackgroundTaskNotificationsForActiveTurn(traceContext): PendingBackgroundTaskNotification[];
claimBackgroundTaskNotificationsForIdleWake(): PendingBackgroundTaskNotification[];
hasPendingBackgroundTaskNotifications(): boolean;
scheduleBackgroundTaskNotificationWake(reason): void;
关键约束:
taskId + toolUseId + terminal status 或 notification id 做幂等,避免 completion/failure path 重复入队。task-notification,一次 claim 快照内全部同优先级 task-notification,按 queuedAt/admission 顺序合成一个 batch input:持久化消息的每个文本块是一条通知,这一轮的输入文本(TurnStarted.input)仍按空行相连。task-notification mode;prompt、target-continuation 与 subagent-message 保持各自消费语义。若同优先级队列以 notification 开头,可以跨过其它 mode 收集同 mode 项;若先选中其它 mode,则先执行该 command。background_task / model-only synthetic user message;每个 notification ledger 输入独立结算并共同指向该 message,避免 cold hydration 把一批结果重建成多个空 turn。originMeta,继续复用普通 BackgroundResultOriginMeta:backgroundSource/workId 取 admission 最早成员作为展示追踪锚点,title 按 admission 顺序合成;最多展示前三个 title,剩余项追加 · +N。持久化 synthetic message 与 live turn 必须复用同一个合成对象。任一成员缺少结构化 metadata 时不从 <task-notification> 文本反向解析,整批保持无 originMeta 的兼容路径。在 AgentRuntime 内增加一个轻量 scheduler,而不是新增 app stdio 协议。
触发点:
enqueueBackgroundTaskNotification() 成功入队后调用 scheduleBackgroundTaskNotificationWake("enqueue")。finishActiveTurn() 清掉 active turn 后,如果 queue 仍有 pending,再调用 scheduleBackgroundTaskNotificationWake("turn_finished")。这覆盖“notification 到达时父 turn 还 active,但最后一个 model request 已经结束”的竞态。执行逻辑:
activeTurn 存在,记录 debug/info 后退出;等待 active drain 或 finishActiveTurn() 再调度。executeTurn(batchText, undefined, { inputVisibility: "model-only", inputSource: "background_task", displayInput: "Background task completed", inputId: "background-task:<first-id>", traceContext })。<task-notification>;UI-facing snapshot 不应新增真实用户气泡。注意:
recordExternalUserPrompt,避免把 background completion 误记为用户输入。finalizeBackgroundCompletion() / finalizeBackgroundFailure() 继续负责:
metadata.json / output.txt / task.output / transcript artifact。RuntimeTaskRegistry terminal 状态、notified: true、usage。SubagentStopped / BackgroundTaskCompleted 等事件。但投递 notification 时改为调用 queue API:
source: "local_agent"。id 使用 task/agent id 加 terminal status,确保幂等。taskId 使用 agentId / backgroundTaskId。toolUseId 使用 parent tool call id。text 继续由 formatTaskNotification() 生成,保持 user-like <task-notification>。在现有 foreground run() 路径补 timer,不重启 child,不改变 start() 直接后台路径。
配置建议:
AgentRuntimeConfig.subagents.autoBackgroundMs?: number。0 或 undefined,即关闭。120000;后续如有产品 beta flag 再接同一字段。生命周期:
run() 注册 task 后,如果 autoBackgroundMs > 0,启动 timer。registry.requestBackground(lifecycle.agentId)。waitForBackgroundRequest() 分支,返回 async_launched,child completion promise 继续后台 finalize。日志使用 runtime/core logger:
info:notification queued、idle wake started/completed、auto-background triggered。这些是低频生命周期事件。debug:wake skipped because active/no pending、duplicate ignored、batch size 等排查细节。warn:wake turn 启动失败、claim 后需要 requeue、timer 触发但 task 不存在或已 terminal。不要把每个 streaming chunk / tool delta 打成 info。
重构 queue 边界
PendingBackgroundTaskNotification 的 id/source/task metadata。pendingBackgroundTaskNotifications.push/splice 收敛到 queue API。补 idle wake
finishActiveTurn() 后调度 wake。executeTurn(..., { inputVisibility: "model-only", inputSource: "background_task" }) 进入现有 loop。补 auto-background
subagents.autoBackgroundMs 配置字段。run() 注册/清理 timer。RuntimeTaskRegistry.requestBackground(),复用现有 foreground-to-background race。补 usage 防回归
totalToolUseCount、event payload、metadata、<usage><tool_uses> 来自 child runtime 真实事件聚合。补测试
Agent(run_in_background=true),父 turn finish 后释放 child,断言自动出现第 3/4 次父模型请求且包含 <task-notification>。source === "background_task"、visibility === "model-only",UI 不出现真实用户气泡。async_launched,child completion 后 notification wake。autoBackgroundMs 时 foreground Agent 不自动后台化。最后 phase:统一其他 background runtime task
local_bash / monitor_mcp 纳入同一 queue/wake 机制。local_bash 当前已有 BackgroundTaskTracker completion enqueue 基础;这个 phase 先让它复用新的 claim / idle wake / 幂等队列,不急着改 provider-visible XML shape。monitor_mcp 需要先确认当前 runtime task 来源和 completion 入口;只有入口明确后再接入同一 source metadata。local_agent / local_bash / monitor_mcp,但 implementation order 仍以 local_agent 为先。Agent(run_in_background=true) 的父 turn 可以先成功 finish;子任务完成后不需要用户再输入,父 runtime 会自动发起一个 model-only continuation request。<task-notification>,不含 <system-reminder> 包裹,不含额外真实用户文本。source: "background_task" 的 synthetic notice;UI-facing projection 不把它渲染成用户手发消息。async_launched,完成后走同一 completion notification/wake path。general-purpose 仍是默认 agent,Explore 不变成默认。pnpm lint 和 pnpm typecheck 通过;如有环境既有失败,需要在提交说明中写明具体失败文件和原因。activeTurn 和 finishActiveTurn() 双重 guard 控制。