diff --git a/.agents/notes/implemented/feature/2026-07-21-continuable-background-subagents.i18n.yaml b/.agents/notes/implemented/feature/2026-07-21-continuable-background-subagents.i18n.yaml index 26572951a6..a4bc2722c2 100644 --- a/.agents/notes/implemented/feature/2026-07-21-continuable-background-subagents.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-21-continuable-background-subagents.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write -2026-07-21-continuable-background-subagents.md: 287239a22c440eb4758a8dab5621406246a7e0b7 -2026-07-21-continuable-background-subagents.zh.md: 36b28581e1bf05144e9ffd5de136983eff8fdabc +2026-07-21-continuable-background-subagents.md: af7ef5c18c2af925e64b309d76e31ee079360b81 +2026-07-21-continuable-background-subagents.zh.md: 0c9e2e4d87e50ebb02cafe8f2333dca81ef8c5da diff --git a/.agents/notes/implemented/feature/2026-07-21-continuable-background-subagents.md b/.agents/notes/implemented/feature/2026-07-21-continuable-background-subagents.md index 287239a22c..af7ef5c18c 100644 --- a/.agents/notes/implemented/feature/2026-07-21-continuable-background-subagents.md +++ b/.agents/notes/implemented/feature/2026-07-21-continuable-background-subagents.md @@ -29,7 +29,7 @@ The low-level `ctx.subagents` seam stays collection-, Task-, and persistence-agn ### Task and cancellation ownership -The initial background delegation asks the control service to start the child and register its Task. Task settlement awaits the result, calls `run.dispose()` (through the control service's `settleRun`), and only then records the `TaskOutcome`; `task_kill` aborts the active run, whose settlement path still disposes it. A terminal Task therefore leaves the durable child session but no live child Agent. +The initial background delegation asks the control service to start the child and register its Task. A continuable provider confirms the activation's final session state durable before fulfilling a successful run result. Task settlement awaits that result, calls `run.dispose()` (through the control service's `settleRun`), and only then records the `TaskOutcome`; `task_kill` aborts the active run, whose settlement path still disposes it. A terminal Task therefore leaves the durable child session but no live child Agent. A failed required durability checkpoint rejects the run with stable code `DURABILITY_FAILED` and the backend failure as its cause; the control service records a failed Task whose detail explains that the latest state was not confirmed persisted and may be unavailable or stale on resume. Every later turn creates another Task. Its producer resources cover only that activation, never the child session. It reaches one terminal status, has one result, and is never reopened. The exact live parent Agent remains the Task registry owner: disposing that instance cancels, awaits, and removes its Tasks. Task APIs authorize a caller whose session id matches that owner, but a same-id replacement does not become the notification or teardown target. This preserves the `settleRun()` contract and bounds Task-owned live children by concurrent work rather than historical session count. @@ -77,7 +77,7 @@ Cold resume cannot depend on an optional method of the old `SubagentRun`, becaus `SubagentControlService`'s resume path loads the known child session, folds its descriptor, authorizes the persisted `parentSession`, and runs inside the Task it creates. It passes a fully resolved request, including the Task-owned cancellation signal, to the low-level `SubagentService.resume(provider, request)`, whose only responsibility is capability-checked provider dispatch and the ordinary run lifecycle observation used by `start`. The selected `SubagentProvider.resume?()` owns transport-specific reconstruction (in-process: `parent.ctx.agents.resume` under the currently loaded parent scope) and returns a fresh run. Presence of the provider method is the continuation capability, so no redundant capability flag exists. `SubagentControlService.sendMessage()` chooses between the associated run's `steer?()` operation and this cold-resume path. Neither the low-level service nor a provider enumerates durable children or associates Tasks. -The background tool validates and snapshots descriptor inputs before calling `TaskService.start()`. A synchronous validation failure rejects the tool call and creates no Task. The tool otherwise returns the child and Task ids immediately, without waiting for child publication or descriptor durability. Child creation, first-turn persistence, or descriptor persistence failure disposes any published run and settles the already-created Task as `failed`; the model observes that failure through the ordinary Task completion or `task_output` path. In-process spawn and fork reconstruct composition under the currently loaded parent scope. A fork resume loads the child's own persisted transcript, which already contains the completed-turn prefix captured at initial creation; it never forks the parent's newer history again. Resuming a parent does not eagerly resume its children. +The background tool validates and snapshots descriptor inputs before calling `TaskService.start()`. A synchronous validation failure rejects the tool call and creates no Task. The tool otherwise returns the child and Task ids immediately, without waiting for child publication or descriptor durability. In-process continuable providers perform a final session flush after the child becomes idle and before reading the result; this retries a failed loop checkpoint while the child is still live. If the final confirmation fails, the provider rejects instead of returning unconfirmed output, the control service disposes the run, and the already-created Task settles as `failed` with the durability diagnosis in its detail. Foreground one-shot runs retain the loop's best-effort checkpoint behavior. In-process spawn and fork reconstruct composition under the currently loaded parent scope. A fork resume loads the child's own persisted transcript, which already contains the completed-turn prefix captured at initial creation; it never forks the parent's newer history again. Resuming a parent does not eagerly resume its children. TODO (ACP continuation): persist the remote ACP session id as provider-specific descriptor data and implement `AcpProvider.resume?()` as spawn, initialize, `loadSession`, then prompt. The initial ACP run must verify `initialize.agentCapabilities.loadSession`, and every resumed process must use the same durable backend; replayed history from `loadSession` must not be collected as the new activation's output. Because ACP load support is negotiated per child rather than established solely by the provider method's presence, this follow-up must also define how a start result advertises child-specific continuation before ACP children enter the durable catalog. @@ -107,10 +107,10 @@ Task records and active-run associations are process-local. Persistence makes th ## Testing -- `packages/subagent/subagent-control/tests/subagent-control.spec.ts` drives the real stack (agent loop, JSONL persistence, spawn/fork providers, Task service and surface, control service) keylessly: initial and resumed activations create fresh Tasks and dispose their runs before terminal; the descriptor event is turn-enclosed, model-hidden, versioned, and durable under the control-allocated child id; `task_kill` during a run or during cold-resume lookup settles `killed` after quiescence with no child work; steering joins the running Task without a second Task; cold follow-ups accumulate turns in one durable transcript with the declared composition reconstructed; fork resume keeps the persisted seed boundary and never re-forks newer parent history; resumed depth uses the persisted header floor; foreign-parent, descriptor-less, and unmaterialized ids fail their started Task with the id unavailable; ownership conflicts and steering-settlement races report not-delivered without cold-resume fallthrough; competing sends during resume load are admitted once. +- `packages/subagent/subagent-inprocess/tests/subagent-inprocess.spec.ts` pins the continuable durability boundary: a permanent flush failure rejects with `DURABILITY_FAILED` and its cause, a transient loop-checkpoint failure can succeed on the final confirmation, resume also confirms durability, and foreground runs remain best-effort. `packages/subagent/subagent-control/tests/subagent-control.spec.ts` drives the real stack (agent loop, JSONL persistence, spawn/fork providers, Task service and surface, control service) keylessly: initial and resumed activations create fresh Tasks and dispose their runs before terminal; the descriptor event is turn-enclosed, model-hidden, versioned, and durable under the control-allocated child id; `task_kill` during a run or during cold-resume lookup settles `killed` after quiescence with no child work; steering joins the running Task without a second Task; cold follow-ups accumulate turns in one durable transcript with the declared composition reconstructed; fork resume keeps the persisted seed boundary and never re-forks newer parent history; resumed depth uses the persisted header floor; foreign-parent, descriptor-less, and unmaterialized ids fail their started Task with the id unavailable; ownership conflicts and steering-settlement races report not-delivered without cold-resume fallthrough; competing sends during resume load are admitted once. - `packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts` pins the `send_message` schema, both route renderings, the not-delivered failure, the no-agent rejection, and HMR disposal. - `packages/subagent/tool-subagent/tests/tool-subagent.spec.ts` covers the capability-branched background route: a resumable provider returns both ids through the control service and advertises `send_message`, a one-shot provider keeps the plain task acknowledgement, and a resumable provider without the control service fails loud. -- The keyless ACP snapshot scenario `subagent-continuable` (examples/acp-agent) pins the model-visible transcript: the two-id acknowledgement, `task_output` collection, and a `send_message` follow-up whose started Task fails with the id unavailable. +- The keyless ACP snapshot scenario `subagent-continuable` (examples/acp-agent) pins the model-visible transcript: the two-id acknowledgement, a final durability-confirmation failure rendered through `task_output` without unconfirmed child output, and a `send_message` follow-up whose started Task fails with the id unavailable. ## Consequences @@ -119,6 +119,6 @@ Task records and active-run associations are process-local. Persistence makes th - Driving a continuable child through the ordinary Agent API bypasses its Task association. The control service rejects that live child as an ownership conflict; adapters must display persisted transcripts without loading an Agent and submit human input through `SubagentControlService.sendMessage()`. - The active-run association coordinates only one runtime. Concurrent resume from multiple processes is not serialized; that deployment requires a persistence-level lease or compare-and-set operation. - Human interaction requires the exact parent Agent instance to remain live because owner disposal cancels and removes its Tasks. It also requires an attached Task control surface. Standalone child interaction requires a future separation between Task access ownership and durable notification targeting. -- The background tool returns child and Task ids before child publication and descriptor durability. Startup failure, persistence failure, or process exit before the first child flush may leave an unmaterialized child id; by-id control reports it as unavailable and durable enumeration omits it rather than retroactively changing the tool result. +- The background tool returns child and Task ids before child publication and descriptor durability. Startup failure, a failed final durability confirmation, or process exit before the first child flush leaves the Task failed and may leave an unmaterialized or stale child id; by-id control reports missing state as unavailable rather than retroactively changing the tool acknowledgement. - Persisting explicit composition fields in the child log makes their lossless-JSON and compatibility contract part of resume. Later support for another composition input requires a deliberate descriptor-version change rather than implicitly persisting merge-extensible `AgentOptions` fields. - Task records and active-run associations are process-local even though child sessions are durable. Restart recovers the session, not in-flight work or its Task notification. diff --git a/.agents/notes/implemented/feature/2026-07-21-continuable-background-subagents.zh.md b/.agents/notes/implemented/feature/2026-07-21-continuable-background-subagents.zh.md index 36b28581e1..0c9e2e4d87 100644 --- a/.agents/notes/implemented/feature/2026-07-21-continuable-background-subagents.zh.md +++ b/.agents/notes/implemented/feature/2026-07-21-continuable-background-subagents.zh.md @@ -29,7 +29,7 @@ durable child Session ### Task 与取消的所有权 -初始后台委派请求控制服务启动 child 并注册其 Task。Task 结算流程等待结果,调用 `run.dispose()`(经由控制服务的 `settleRun`),然后才记录 `TaskOutcome`;`task_kill` 中止活跃 run,其结算路径仍会 dispose 该 run。因此,终态 Task 会留下持久化 child 会话,但不会留下存活的 child agent。 +初始后台委派请求控制服务启动 child 并注册其 Task。可继续提供方只有在确认本次激活的最终会话状态已持久化后,才会返回成功的 run 结果。Task 结算流程等待该结果,调用 `run.dispose()`(经由控制服务的 `settleRun`),然后才记录 `TaskOutcome`;`task_kill` 中止活跃 run,其结算路径仍会 dispose 该 run。因此,终态 Task 会留下持久化 child 会话,但不会留下存活的 child agent。必需的持久性检查点失败时,run 会以稳定错误码 `DURABILITY_FAILED` 拒绝,并将后端失败保留为失败原因;控制服务会记录失败的 Task,其详情说明最新状态未确认已持久化,因此恢复时可能不可用或已陈旧。 后续每个轮次都会创建另一个 Task。该轮 producer 持有的执行资源仅服务于这次激活,不属于 child 会话。它只会到达一次终态、只产生一个结果,也不会重新打开。Task 注册表中当前注册的那个存活 parent agent 实例仍是其 owner:dispose 该实例会取消、等待并移除其 Task。Task API 会授权 session id 与该 owner 匹配的调用方,但 id 相同的替代实例不会成为通知或资源清理目标。这一设计保留 `settleRun()` 契约,并使 Task 所拥有的存活 child 数量受并发工作量限制,而不是随历史会话数量增长。 @@ -77,7 +77,7 @@ durable child Session `SubagentControlService` 的恢复路径会加载已知 child 会话、归并其描述符、根据持久化的 `parentSession` 鉴权,并在其创建的 Task 内部运行。它向底层 `SubagentService.resume(provider, request)` 传递完全解析的请求,其中包含由 Task 持有的取消信号;后者只负责检查提供方功能后进行分发,并执行 `start` 所使用的普通 run 生命周期观察。选中的 `SubagentProvider.resume?()` 负责传输相关的重建(进程内:在当前加载的 parent 作用域下执行 `parent.ctx.agents.resume`),并返回一个新 run。提供方是否存在该方法本身就是继续执行功能,无需额外功能标志。`SubagentControlService.sendMessage()` 在关联 run 的 `steer?()` 操作与该持久化恢复路径之间做出选择。底层服务和提供方都不会枚举持久化 child 或关联 Task。 -后台工具会在调用 `TaskService.start()` 前校验描述符输入并建立快照。同步校验失败会拒绝工具调用,且不会创建 Task。除此之外,工具会立即返回 child id 和 Task id,不等待 child 发布或描述符持久化完成。child 创建、首轮持久化或描述符持久化失败时,系统会 dispose 所有已发布的 run,并将已经创建的 Task 结算为 `failed`;模型通过普通 Task 完成通知或 `task_output` 路径观察该失败。进程内 spawn 和 fork 会在当前已加载的 parent 作用域下重建组合配置。恢复 fork 时只加载 child 自己的持久化 transcript,其中已经包含初始创建时捕获的已完成轮次前缀;系统绝不会再次 fork parent 更新后的历史。恢复 parent 不会立即恢复其 child。 +后台工具会在调用 `TaskService.start()` 前校验描述符输入并建立快照。同步校验失败会拒绝工具调用,且不会创建 Task。除此之外,工具会立即返回 child id 和 Task id,不等待 child 发布或描述符持久化完成。进程内可继续提供方会在 child 进入 idle 后、读取结果之前执行最终会话 flush;此操作会在 child 仍存活时重试循环中失败的检查点。如果最终确认失败,提供方会拒绝而不返回未经确认的输出,控制服务会 dispose 该 run,已经创建的 Task 会结算为 `failed`,其详情包含持久性诊断。前台一次性运行仍保留循环仅尽力执行检查点的行为。进程内 spawn 和 fork 会在当前已加载的 parent 作用域下重建组合配置。恢复 fork 时只加载 child 自己的持久化 transcript,其中已经包含初始创建时捕获的已完成轮次前缀;系统绝不会再次 fork parent 更新后的历史。恢复 parent 不会立即恢复其 child。 TODO(ACP 继续执行):将远端 ACP session id 作为提供方专用描述符数据持久化,并实现 `AcpProvider.resume?()`,依次执行 spawn、initialize、`loadSession` 和 prompt。初始 ACP run 必须检查 `initialize.agentCapabilities.loadSession`,恢复后的每个进程必须使用同一个持久化后端;`loadSession` 回放的历史消息不得计入新激活的输出。由于 ACP 的加载支持是按 child 协商的,不能仅根据提供方是否存在该方法来确定,因此该后续工作还必须定义 start 结果如何声明单个 child 支持继续执行,之后才能将 ACP child 写入持久化目录。 @@ -107,10 +107,10 @@ Task 记录和活跃 run 关联都位于进程内。持久化使 child 会话可 ## 测试 -- `packages/subagent/subagent-control/tests/subagent-control.spec.ts` 以无密钥方式驱动真实栈(agent loop、JSONL 持久化、spawn/fork 提供方、Task 服务与控制面、控制服务):初始及恢复后的激活都会创建新 Task,并在进入终态前 dispose 各自的 run;描述符事件位于轮次内、对模型隐藏、带版本,并在控制服务分配的 child id 下持久化;在 run 运行期间或 cold resume 查找期间执行 `task_kill`,会在完全停稳后结算为 `killed`,且不产生任何 child 工作;steering 会加入运行中的 Task,而不创建第二个 Task;cold follow-up 会在一份持久化 transcript 中累积轮次,并重建声明的组合配置;恢复 fork 会保持持久化 seed 边界,绝不重新 fork parent 更新后的历史;恢复后的深度以持久化 header 为下界;外来 parent、无描述符及 unmaterialized 的 id 会带着「id 不可用」使其已启动的 Task 失败;所有权冲突和 steering 与结算的竞态会报告未送达,且不改用从持久化存储恢复路径;resume 加载期间竞争的发送只准入一次。 +- `packages/subagent/subagent-inprocess/tests/subagent-inprocess.spec.ts` 固定可继续执行的持久性边界:flush 持续失败时会以 `DURABILITY_FAILED` 拒绝并保留失败原因,循环检查点的瞬时失败可在最终确认成功后继续完成,resume 同样会确认持久性,而前台运行仍采用尽力而为策略。`packages/subagent/subagent-control/tests/subagent-control.spec.ts` 以无密钥方式驱动真实栈(agent loop、JSONL 持久化、spawn/fork 提供方、Task 服务与控制面、控制服务):初始及恢复后的激活都会创建新 Task,并在进入终态前 dispose 各自的 run;描述符事件位于轮次内、对模型隐藏、带版本,并在控制服务分配的 child id 下持久化;在 run 运行期间或 cold resume 查找期间执行 `task_kill`,会在完全停稳后结算为 `killed`,且不产生任何 child 工作;steering 会加入运行中的 Task,而不创建第二个 Task;cold follow-up 会在一份持久化 transcript 中累积轮次,并重建声明的组合配置;恢复 fork 会保持持久化 seed 边界,绝不重新 fork parent 更新后的历史;恢复后的深度以持久化 header 为下界;外来 parent、无描述符及 unmaterialized 的 id 会带着「id 不可用」使其已启动的 Task 失败;所有权冲突和 steering 与结算的竞态会报告未送达,且不改用从持久化存储恢复路径;resume 加载期间竞争的发送只准入一次。 - `packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts` 固定 `send_message` 的 schema、两种路由渲染、未送达失败、无 agent 时的拒绝,以及 HMR(热模块替换)dispose。 - `packages/subagent/tool-subagent/tests/tool-subagent.spec.ts` 覆盖按功能分支的后台路由:可恢复的提供方会通过控制服务返回两个 id 并公开 `send_message`,一次性提供方保持普通的 task 确认消息,而缺少控制服务的可恢复提供方会明确失败。 -- 无密钥 ACP 快照场景 `subagent-continuable`(examples/acp-agent)固定模型可见的 transcript:双 id 确认消息、`task_output` 结果收集,以及一次 `send_message` 后续操作——其已启动的 Task 会带着「id 不可用」失败。 +- 无密钥 ACP 快照场景 `subagent-continuable`(examples/acp-agent)固定模型可见的 transcript:双 id 确认消息、最终持久性确认失败(该失败通过 `task_output` 呈现,且不包含未经确认的 child 输出),以及一次 `send_message` 后续操作——其已启动的 Task 会带着「id 不可用」失败。 ## 影响 @@ -119,6 +119,6 @@ Task 记录和活跃 run 关联都位于进程内。持久化使 child 会话可 - 通过普通 Agent API 驱动可继续 child 会绕过其 Task 关联。控制服务会将该存活 child 视为所有权冲突并拒绝;适配器必须在不加载 Agent 的情况下展示持久化 transcript,并通过 `SubagentControlService.sendMessage()` 提交用户输入。 - 活跃 run 关联只能协调一个运行时。多个进程同时恢复时不会串行化;此类部署需要持久化层的租约或 compare-and-set 操作。 - 用户交互要求作为 owner 的那个精确 parent Agent 实例保持存活,因为 dispose owner 会取消并移除其 Task。用户交互还要求附加 Task 控制面。若要单独与 child 交互,后续必须将 Task 访问所有权与持久化通知目标分离。 -- 后台工具会在 child 发布和描述符持久化之前返回 child id 和 Task id。启动失败、持久化失败,或进程在 child 首次 flush 之前退出,都可能留下 unmaterialized child id;按 id 的控制操作会报告该 id 不可用,持久化枚举也不会列出它,而不会追溯修改工具返回结果。 +- 后台工具会在 child 发布和描述符持久化之前返回 child id 和 Task id。启动失败、最终持久性确认失败,或进程在 child 首次 flush 之前退出,都会使 Task 失败,并可能留下 unmaterialized 或陈旧的 child id;按 id 的控制操作会将缺失状态报告为不可用,而不会追溯修改工具确认消息。 - 将显式组合字段持久化到 child 日志后,其无损 JSON 与兼容性契约便成为恢复契约的一部分。后续如需支持其他组合配置输入,必须明确更改描述符版本,不能隐式持久化可通过声明合并扩展的 `AgentOptions` 字段。 - Task 记录和活跃 run 关联位于进程内,而 child 会话具有持久性。重启会恢复会话,但不会恢复进行中的工作或其 Task 通知。 diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index 9028df3814..e73ce42c82 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -1988,7 +1988,7 @@ sendMessage(parent: Agent, childId: SessionId, message: ContentBlock[]): SendMes Types: [Agent](../core-data-structures/core.md) · [ContentBlock](../core-data-structures/core.md) · [ContinuableStart](../core-data-structures/subagent.md) · [ContinuableStartSpec](../core-data-structures/subagent.md) · [SendMessageResult](../core-data-structures/subagent.md) · [SessionId](../core-data-structures/core.md) -Source: [`packages/subagent/subagent-control/src/index.ts:156`](../../packages/subagent/subagent-control/src/index.ts) +Source: [`packages/subagent/subagent-control/src/index.ts:163`](../../packages/subagent/subagent-control/src/index.ts) ## `ctx.subagents` — `SubagentService` diff --git a/docs/core-data-structures/subagent.md b/docs/core-data-structures/subagent.md index b5ec558351..b547305e8d 100644 --- a/docs/core-data-structures/subagent.md +++ b/docs/core-data-structures/subagent.md @@ -203,7 +203,7 @@ interface SubagentStopReasonMap { ## A live run: `SubagentRun` -`SubagentRun` is the consumer-owned handle for a ready child — one disposable activation, never a durable child handle. Consumers await `result` and always dispose the run to reach quiescence. Child failures resolve with a non-completed stop reason; only unrepresentable infrastructure faults reject. The optional strict `steer` method advertises live delivery by presence; cold resume deliberately does NOT live here (a disposed run cannot be reconstructed after restart) — it is `SubagentProvider.resume`. +`SubagentRun` is the consumer-owned handle for a ready child — one disposable activation, never a durable child handle. Consumers await `result` and always dispose the run to reach quiescence. Child failures resolve with a non-completed stop reason; only unrepresentable infrastructure faults reject. A completed continuable result additionally means the provider confirmed the activation's final state durable; a failed required checkpoint rejects. The optional strict `steer` method advertises live delivery by presence; cold resume deliberately does NOT live here (a disposed run cannot be reconstructed after restart) — it is `SubagentProvider.resume`. ```ts type-equiv /** @@ -228,8 +228,10 @@ interface SubagentRun { * Resolves with the child's terminal {@link SubagentResult} when the run * settles. Does NOT reject on a child-level failure — a model/transport * failure resolves with `stopReason: 'error'` so the consumer maps it to an - * `isError` tool result. Rejects only on an infrastructure fault the seam - * cannot represent as a stop reason. + * `isError` tool result. For a continuable activation, a completed result + * also means the provider confirmed the activation's final state durable. + * Rejects on an infrastructure fault the seam cannot represent as a stop + * reason, including a failed required durability checkpoint. */ readonly result: Promise /** diff --git a/examples/acp-agent/subagent-durability-failure.cordis.snapshot.yml b/examples/acp-agent/subagent-durability-failure.cordis.snapshot.yml new file mode 100644 index 0000000000..7ce0733e53 --- /dev/null +++ b/examples/acp-agent/subagent-durability-failure.cordis.snapshot.yml @@ -0,0 +1,45 @@ +# Keyless counterpart to subagent-durability-failure.cordis.yml: replace the +# live adapter with replay and fail the provider-owned final child checkpoint. +- id: base + name: '@cordisjs/plugin-include' + config: + path: ./cordis.yml + patches: + - id: llm-deepseek + name: '@deepseek-ai/dsh-llm-deepseek' + disabled: true + - id: acp-agent + name: '@deepseek-ai/dsh-acp-demo' + config: + provider: deepseek-official + model: deepseek-v4-flash + persistenceRoot: !!js process.env.DSH_SNAPSHOT_SESSIONS_ROOT ?? './.sessions' + persistenceCompression: none + workspaceContext: + maxBytes: 65536 + persona: | + You are a coding assistant powered by the {{model}} model. Your working directory is {{cwd}}. Your bash tool runs under a file sandbox — a `[sandbox: file access denied …]` result is policy, not a command bug. + + Verify your work by running the code or tests. Keep answers brief and factual. + - id: sandbox + name: '@deepseek-ai/dsh-sandbox-local' + config: + runnerCommand: + - bash + - -c + - while [ "$1" != "--" ]; do shift; done; shift; exec "$@" + - passthrough-runner + runnerFailureSignatures: + - 'passthrough-runner: profile rejected' + - insert: + - id: llm-replay + name: '@deepseek-ai/dsh-llm-replay' + config: + providers: + - id: deepseek-official + name: DeepSeek + models: + - id: deepseek-v4-flash + - id: deepseek-v4-pro + - id: subagent-durability-failure + name: './tests/fixtures/subagent-durability-failure.ts' diff --git a/examples/acp-agent/subagent-durability-failure.cordis.yml b/examples/acp-agent/subagent-durability-failure.cordis.yml new file mode 100644 index 0000000000..c033c323dc --- /dev/null +++ b/examples/acp-agent/subagent-durability-failure.cordis.yml @@ -0,0 +1,10 @@ +# Snapshot-only durability-failure overlay. The child turn's ordinary flush +# succeeds; the provider-owned final confirmation fails deterministically. +- id: base + name: '@cordisjs/plugin-include' + config: + path: ./cordis.yml + patches: + - insert: + - id: subagent-durability-failure + name: './tests/fixtures/subagent-durability-failure.ts' diff --git a/examples/acp-agent/tests/acp.snapshot.ts b/examples/acp-agent/tests/acp.snapshot.ts index aa4bad392c..c2e0328fab 100644 --- a/examples/acp-agent/tests/acp.snapshot.ts +++ b/examples/acp-agent/tests/acp.snapshot.ts @@ -41,6 +41,9 @@ const DEPTH_TWO_CONFIG = fileURLToPath(new URL('../depth-two.cordis.yml', import const SESSION_SANDBOX_ROOT_CONFIG = fileURLToPath(new URL('../session-sandbox-root.cordis.yml', import.meta.url)) const RETRY_CONFIG = fileURLToPath(new URL('../retry.cordis.yml', import.meta.url)) const SESSION_TITLE_CONFIG = fileURLToPath(new URL('../session-title.cordis.yml', import.meta.url)) +const SUBAGENT_DURABILITY_FAILURE_CONFIG = fileURLToPath( + new URL('../subagent-durability-failure.cordis.yml', import.meta.url), +) const LSP_CONFIG = fileURLToPath(new URL('./lsp.cordis.yml', import.meta.url)) const WEB_CONFIG = fileURLToPath(new URL('../web.cordis.yml', import.meta.url)) const FS_SEARCH_CONFIG = fileURLToPath(new URL('./fs-search.cordis.yml', import.meta.url)) @@ -214,10 +217,15 @@ const SCENARIOS: Scenario[] = [ { name: 'subagent-fork', hasModelTurn: true, recorded: true }, { name: 'subagent-mixed', hasModelTurn: true, recorded: true }, // Authored continuable-subagent transcript: a background delegation returns - // both the durable subagent id and its task id, task_output collects the - // child result after settlement, and send_message to an unknown subagent id - // starts a follow-up task that settles failed with the id unavailable. - { name: 'subagent-continuable', hasModelTurn: true, recorded: false }, + // both the durable subagent id and its task id, a failed final durability + // confirmation reaches task_output with its diagnosis, and send_message to + // an unknown subagent id starts a follow-up task that settles unavailable. + { + name: 'subagent-continuable', + hasModelTurn: true, + recorded: false, + configPath: SUBAGENT_DURABILITY_FAILURE_CONFIG, + }, { name: 'subagent-depth-two-rejection', hasModelTurn: true, diff --git a/examples/acp-agent/tests/fixtures/subagent-durability-failure.ts b/examples/acp-agent/tests/fixtures/subagent-durability-failure.ts new file mode 100644 index 0000000000..5d0137911d --- /dev/null +++ b/examples/acp-agent/tests/fixtures/subagent-durability-failure.ts @@ -0,0 +1,14 @@ +import type { Context } from 'cordis' + +export const name = 'subagent-durability-failure' + +/** Fail a continuable child's provider-owned final durability confirmation. */ +export function apply(ctx: Context): void { + const flushedTurnEnds = new WeakSet() + ctx.on('session/flush', (session) => { + if (session.header.parentSession === undefined) return + if (session.events.at(-1)?.type !== 'turn/end') return + if (flushedTurnEnds.has(session)) throw new Error('snapshot disk full') + flushedTurnEnds.add(session) + }) +} diff --git a/examples/acp-agent/tests/snapshots/subagent-continuable/session.jsonl b/examples/acp-agent/tests/snapshots/subagent-continuable/session.jsonl index e9e859d905..1b6e576b54 100644 --- a/examples/acp-agent/tests/snapshots/subagent-continuable/session.jsonl +++ b/examples/acp-agent/tests/snapshots/subagent-continuable/session.jsonl @@ -23,7 +23,7 @@ {"type":"assistant/chunk","seq":21,"time":1785517567391,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":22,"time":1785517567392,"data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_collect_1","name":"task_output","arguments":"{\"task_id\": \"subagent-1\", \"wait\": true}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"3fcea712-0e14-4f2d-909c-f7de70018053"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[17,18,19,20,21],"surfaceOp":"append"} {"type":"tool/call","seq":23,"time":1785517567392,"data":{"turn":1,"step":2,"callId":"call_collect_1","name":"task_output","arguments":"{\"task_id\": \"subagent-1\", \"wait\": true}"}} -{"type":"tool/result","seq":24,"time":1785517567419,"data":{"turn":1,"step":2,"message":{"source":{"kind":"tool","callId":"call_collect_1"},"content":[{"type":"tool-result","toolCallId":"call_collect_1","content":[{"type":"text","text":"CHILD_OK\n[status: completed]"}],"isError":false}],"role":"user","id":"ae79571a-fa78-4de0-9614-a10b5223230c"}},"sourceEventSeqs":[23],"surfaceOp":"append"} +{"type":"tool/result","seq":24,"time":1785517567419,"data":{"turn":1,"step":2,"message":{"source":{"kind":"tool","callId":"call_collect_1"},"content":[{"type":"tool-result","toolCallId":"call_collect_1","content":[{"type":"text","text":"(no new output)\n[status: failed, subagent \"33333333-3333-4333-8333-333333333333\" durability checkpoint failed; the latest child state was not confirmed persisted and may be unavailable or stale on resume: snapshot disk full]"}],"isError":false}],"role":"user","id":"ae79571a-fa78-4de0-9614-a10b5223230c"}},"sourceEventSeqs":[23],"surfaceOp":"append"} {"type":"step/end","seq":25,"time":1785517567419,"data":{"turn":1,"step":2}} {"type":"step/start","seq":26,"time":1785517567425,"data":{"turn":1,"step":3}} {"type":"assistant/chunk","seq":27,"time":1789000000026,"data":{"turn":1,"step":3,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} diff --git a/knip.json b/knip.json index 43102b0b0d..9f2c7db4a3 100644 --- a/knip.json +++ b/knip.json @@ -41,6 +41,7 @@ "headless-agent/tests/fixtures/telemetry-otel-driver.ts", "headless-agent/tests/fixtures/telemetry-redact-rule.ts", "acp-agent/tests/snapshots/lsp-definition/workspace/subject.ts", + "acp-agent/tests/fixtures/subagent-durability-failure.ts", "acp-agent/tests/fixtures/subagent/subagent-acp/mock-delegating-llm.ts", "acp-agent/tests/fixtures/subagent/subagent-acp/driver.ts", "jsonrpc-agent/tests/fixtures/subagent/subagent-dsh-sdk/driver.ts", diff --git a/packages/subagent/subagent-control/README.md b/packages/subagent/subagent-control/README.md index 002613d508..e65c6dcf1c 100644 --- a/packages/subagent/subagent-control/README.md +++ b/packages/subagent/subagent-control/README.md @@ -4,7 +4,7 @@ The continuable-subagent control service (`ctx.subagentControl`): the one orches ## Activation lifecycle -A continuable background subagent is a durable child session with a series of Task-backed activations. `startContinuable()` allocates the stable child session id before Task creation, snapshots the descriptor inputs (a non-JSON input throws with no Task), and registers the initial activation's Task; the provider publishes exactly that child id and appends the versioned `subagent/descriptor` event inside the child's first turn. Every activation — initial or resumed — creates a fresh Task whose settlement awaits the child result, disposes the run, and only then records the `TaskOutcome`: a terminal Task leaves the durable child session but no live child Agent. +A continuable background subagent is a durable child session with a series of Task-backed activations. `startContinuable()` allocates the stable child session id before Task creation, snapshots the descriptor inputs (a non-JSON input throws with no Task), and registers the initial activation's Task; the provider publishes exactly that child id and appends the versioned `subagent/descriptor` event inside the child's first turn. Every activation — initial or resumed — creates a fresh Task whose settlement awaits the provider's durability-confirmed child result, disposes the run, and only then records the `TaskOutcome`: a terminal Task leaves the durable child session but no live child Agent. A provider rejection with `DURABILITY_FAILED` settles the Task as `failed` and copies the error message into `detail`, so `task_output` reports the failed checkpoint and resumability risk without exposing unconfirmed output. `sendMessage(parent, childId, message)` owns steer-or-resume routing. A running activation receives live delivery through the run's strict `steer` capability and returns the existing Task id (`steered`); an absent activation starts a fresh Task that loads the persisted child, authorizes the recorded `parentSession` as the direct parent, folds the descriptor, and dispatches `SubagentService.resume()` (`started`). Failure throws and means the message was not delivered: losing a strict-steering race with Task settlement never falls through to cold resume within the same call, and a live registry Agent outside the activation association is an ownership conflict rather than an adoption target. diff --git a/packages/subagent/subagent-control/src/index.ts b/packages/subagent/subagent-control/src/index.ts index f8c161bcb8..ab0fab6d9d 100644 --- a/packages/subagent/subagent-control/src/index.ts +++ b/packages/subagent/subagent-control/src/index.ts @@ -116,6 +116,13 @@ export function runOutcome(result: SubagentResult): TaskOutcome { } } +/** Render infrastructure failure detail without hiding a durability diagnosis. */ +function runFailureDetail(error: unknown): string { + return error instanceof HarnessError && error.code === 'DURABILITY_FAILED' + ? error.message + : String(error) +} + /** * Await the child result, dispose the run, then return its task outcome. Result * and disposal failures become `failed`; when both fail, both details survive. @@ -127,7 +134,7 @@ export async function settleRun(run: SubagentRun): Promise { try { outcome = runOutcome(await run.result) } catch (error: unknown) { - outcome = { status: 'failed', detail: String(error) } + outcome = { status: 'failed', detail: runFailureDetail(error) } } try { await run.dispose() diff --git a/packages/subagent/subagent-control/tests/subagent-control.spec.ts b/packages/subagent/subagent-control/tests/subagent-control.spec.ts index 97adf790a6..458e6a6960 100644 --- a/packages/subagent/subagent-control/tests/subagent-control.spec.ts +++ b/packages/subagent/subagent-control/tests/subagent-control.spec.ts @@ -16,7 +16,7 @@ import { TaskId } from '@deepseek-ai/dsh-tasks' import LocalTaskService from '@deepseek-ai/dsh-tasks-local' import * as ToolTasks from '@deepseek-ai/dsh-tool-tasks' import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm' -import { createUserMessage, LlmAdapter } from '@deepseek-ai/dsh-llm' +import { createUserMessage, HarnessError, LlmAdapter } from '@deepseek-ai/dsh-llm' import { MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' import SubagentControlService, { runOutcome, settleRun, SubagentControlError } from '../src/index.ts' @@ -685,16 +685,29 @@ describe('outcome mapping helpers', () => { expect(failed).toEqual({ status: 'failed', detail: 'Error: transport gone' }) expect(disposed).toBe(true) - const disposeFailed = await settleRun({ + const durabilityMessage = 'subagent "child-3" durability checkpoint failed; latest state unavailable: disk full' + const durabilityFailed = await settleRun({ id: SessionId('child-3'), localAgent: undefined, + result: Promise.reject(new HarnessError( + durabilityMessage, + 'DURABILITY_FAILED', + { cause: new Error('disk full') }, + )), + dispose: () => Promise.resolve(), + }) + expect(durabilityFailed).toEqual({ status: 'failed', detail: durabilityMessage }) + + const disposeFailed = await settleRun({ + id: SessionId('child-4'), + localAgent: undefined, result: Promise.resolve({ output: [], stopReason: 'completed' }), dispose: () => Promise.reject(new Error('reap failed')), }) expect(disposeFailed).toEqual({ status: 'failed', detail: 'dispose failed: Error: reap failed' }) const bothFailed = await settleRun({ - id: SessionId('child-4'), + id: SessionId('child-5'), localAgent: undefined, result: Promise.reject(new Error('result failed')), dispose: () => Promise.reject(new Error('reap failed')), diff --git a/packages/subagent/subagent-inprocess/README.i18n.yaml b/packages/subagent/subagent-inprocess/README.i18n.yaml index bd951115d2..2b5ea80435 100644 --- a/packages/subagent/subagent-inprocess/README.i18n.yaml +++ b/packages/subagent/subagent-inprocess/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subagent/subagent-inprocess/README.md -README.md: 7587b6dfc44bef90756c9f2aba96d54872935fee -README.zh.md: 751e745c6c7a64831debd2df58ed8c3d7861f84d +README.md: eb5d973566f01c05b43f4f56eff746b7af93f60b +README.zh.md: 5be640f9b6da6402ece0e1d15997d9e2970a7d1c diff --git a/packages/subagent/subagent-inprocess/README.md b/packages/subagent/subagent-inprocess/README.md index 526b237efa..eb5d973566 100644 --- a/packages/subagent/subagent-inprocess/README.md +++ b/packages/subagent/subagent-inprocess/README.md @@ -12,9 +12,10 @@ The driver follows this sequence: 1. Validate the parent depth and optional absolute `maxDepth`, then derive child depth as parent depth plus one and persist it in the child session header. 2. Call `parent.ctx.agents.create` directly, passing the required request signal into the factory's creation transaction. A continuable request publishes exactly `request.continuation.sessionId` instead of an internally minted id. -3. During that transaction's unpublished setup window, install the requested persona, tool restriction, structured-output runtime, and — for a continuable request — the one-shot `agent/pre-step` contribution that appends the `subagent/descriptor` event after the initial `turn/start` and before the first request, so the descriptor reaches persistence with that turn's flush. +3. During that transaction's unpublished setup window, install the requested persona, tool restriction, structured-output runtime, and — for a continuable request — the one-shot `agent/step` contribution that appends the `subagent/descriptor` event after the initial `turn/start` and before the first request, so the descriptor reaches persistence with that turn's flush. 4. Publish the child, retain the returned `AgentHandle`, and drive one task with `child.followup(prompt)` followed by `child.whenIdle()`. -5. Read the child's own last assistant message and latest message-triggered turn reason, excluding any fork seed and later plugin-owned zero-step turns. +5. For a continuable start or resume, call `child.ctx.sessions.flush(child.session)` again before returning the result. This final confirmation retries events retained after a failed turn checkpoint; if it still fails, `result` rejects with `SubagentError.code === 'DURABILITY_FAILED'`, retains the backend failure as `cause`, and names the resumability risk in its message. Foreground runs keep the loop's best-effort checkpoint behavior. +6. Read the child's own last assistant message and latest message-triggered turn reason, excluding any fork seed and later plugin-owned between-turn records. The child gets the parent's working-directory/session lineage and inherits the parent provider, model, and output-token cap unless `request.agentOptions` overrides them. It gets a fresh flat registration scope: parent ownership does not import parent tool restrictions or establish an authority subset. @@ -22,7 +23,7 @@ When the optional sandbox-policy or approval service is composed, the driver sna ## Cold resume -`resumeInProcessRun(request): Promise` reconstructs a persisted continuable child under the live parent's scope: `parent.ctx.agents.resume` loads the child's own transcript through persistence (a fork child's log already contains its seed prefix, so resume never re-forks current parent history), the descriptor's persona and tool filter are reapplied in the unpublished setup window, and the descriptor's `agentProvider`/`agentModel` become the runtime options. The persisted header stays authoritative for lineage and the delegation-depth floor. The activation's result boundary is the resumed log length: only this follow-up turn's output becomes the run result. Publication, abort handoff, and disposal follow the same contract as start. +`resumeInProcessRun(request): Promise` reconstructs a persisted continuable child under the live parent's scope: `parent.ctx.agents.resume` loads the child's own transcript through persistence (a fork child's log already contains its seed prefix, so resume never re-forks current parent history), the descriptor's persona and tool filter are reapplied in the unpublished setup window, and the descriptor's `agentProvider`/`agentModel` become the runtime options. The persisted header stays authoritative for lineage and the delegation-depth floor. The activation's result boundary is the resumed log length: only this follow-up turn's output becomes the run result. Publication, final durability confirmation, abort handoff, and disposal follow the same contract as a continuable start. ## Cancellation and ownership @@ -30,7 +31,7 @@ The required request signal covers both startup and the live run. Before publica After fulfillment, the caller owns the run. Provider-plugin unload does not revoke it. `dispose()` removes the live abort listener, records cancellation, and delegates to the returned `AgentHandle.dispose()`, whose memoized quiescence transaction stops the loop, removes the agent and session, and unwinds scoped registrations. Cancellation owns every non-completed in-flight outcome and reports `aborted`; an already-completed turn remains completed. -Runs expose the strict `steer` capability: the synchronous checks and the `Agent.steer()` call share one frame, so delivery joins the observed turn or throws. Delivery requires `AgentStatus.running`, an open turn in the child log (status stays `running` through a closed turn's durability flush, where the loop would strand the message), an open step (between steps the loop may sit at its continuation/turn-stop checkpoints, where steering was already folded and a terminal stop discards a later arrival; a message accepted during an open step is recorded at that step's settlement before any terminal decision), and no committed structured capture (whose terminal stop makes the loop discard late steering). The Agent-level idle fallback (queue and start a new turn) is deliberately not reachable through the run — that would start an untracked turn after the run's result was read. +Runs expose the strict `steer` capability: the synchronous checks and the `Agent.trySteer()` call share one frame, so delivery joins the observed step or throws. Delivery requires `AgentStatus.running`, an open turn and step in the child log, no committed structured capture, and acceptance before that step's final drain begins. Admission, between-step processing such as `agent/turn-stopping`, and a closed turn's durability flush all reject delivery. The Agent-level idle fallback (queue and start a new turn) is deliberately not reachable through the run — that would start an untracked turn after the run's result was read. ## Spawn and fork inputs diff --git a/packages/subagent/subagent-inprocess/README.zh.md b/packages/subagent/subagent-inprocess/README.zh.md index 751e745c6c..5be640f9b6 100644 --- a/packages/subagent/subagent-inprocess/README.zh.md +++ b/packages/subagent/subagent-inprocess/README.zh.md @@ -12,9 +12,10 @@ 1. 校验父 agent 深度和可选的绝对 `maxDepth`,然后把子 agent 深度推导为父 agent 深度加一,并将其持久化到子 agent 会话 header。 2. 直接调用 `parent.ctx.agents.create`,把必需的请求信号传入工厂的创建事务。可继续请求会精确发布 `request.continuation.sessionId`,而不是内部生成的 ID。 -3. 在该事务未发布的设置窗口中,安装请求的 persona、工具限制和结构化输出运行时;对于可继续请求,还会安装一次性的 `agent/pre-step` 贡献,在初始 `turn/start` 之后、首次请求之前追加 `subagent/descriptor` 事件,使描述符随该轮次的 flush 到达持久化层。 +3. 在该事务未发布的设置窗口中,安装请求的 persona、工具限制和结构化输出运行时;对于可继续请求,还会安装一次性的 `agent/step` 贡献,在初始 `turn/start` 之后、首次请求之前追加 `subagent/descriptor` 事件,使描述符随该轮次的 flush 到达持久化层。 4. 发布子 agent,保留返回的 `AgentHandle`,并通过先调用 `child.followup(prompt)`、再调用 `child.whenIdle()` 来驱动一项任务。 -5. 读取子 agent 自身最后一条 assistant 消息,以及由消息触发的最新轮次原因;排除任何 fork 初始内容和后续由插件拥有的零步骤轮次。 +5. 对于可继续的启动或恢复,在返回结果前再次调用 `child.ctx.sessions.flush(child.session)`。这次最终确认会重试轮次检查点失败后保留的事件;若仍然失败,`result` 会以 `SubagentError.code === 'DURABILITY_FAILED'` 拒绝,保留后端失败作为 `cause`,并在消息中指出可恢复性风险。前台运行仍采用循环的尽力而为检查点行为。 +6. 读取子 agent 自身最后一条 assistant 消息,以及由消息触发的最新轮次原因;排除任何 fork 初始内容和后续由插件拥有的轮次间记录。 子 agent 会获得父 agent 的工作目录/会话谱系;除非 `request.agentOptions` 覆盖,否则还会继承父 agent 的提供方、模型和输出 token 上限。它获得全新的扁平注册作用域:父级所有权不会导入父 agent 的工具限制,也不会建立权限子集。 @@ -22,7 +23,7 @@ ## 冷恢复 -`resumeInProcessRun(request): Promise` 会在当前父级作用域下重建持久化的可继续子 agent:`parent.ctx.agents.resume` 通过持久化层加载子 agent 自身的 transcript(文本记录;fork 子 agent 的日志已经包含初始前缀,因此恢复绝不会再次 fork 当前父级历史),在未发布的设置窗口中重新应用描述符中的 persona 和工具过滤器,并把描述符中的 `agentProvider` / `agentModel` 作为运行时选项。持久化 header 对谱系和委派深度下限保持权威性。activation 的结果边界是恢复后日志的长度:只有此次后续轮次的输出会成为运行结果。发布、中止交接和 dispose 遵循与启动相同的契约。 +`resumeInProcessRun(request): Promise` 会在当前父级作用域下重建持久化的可继续子 agent:`parent.ctx.agents.resume` 通过持久化层加载子 agent 自身的 transcript(文本记录;fork 子 agent 的日志已经包含初始前缀,因此恢复绝不会再次 fork 当前父级历史),在未发布的设置窗口中重新应用描述符中的 persona 和工具过滤器,并把描述符中的 `agentProvider` / `agentModel` 作为运行时选项。持久化 header 对谱系和委派深度下限保持权威性。activation 的结果边界是恢复后日志的长度:只有此次后续轮次的输出会成为运行结果。发布、最终持久性确认、中止交接和 dispose 遵循与可继续启动相同的契约。 ## 取消与所有权 @@ -30,7 +31,7 @@ 兑现后,调用方拥有该运行。提供方插件卸载不会撤销它。`dispose()` 会移除实时中止监听器、记录取消,并委托给返回的 `AgentHandle.dispose()`;后者通过可复用的完全停稳事务停止循环、移除 agent 和会话,并展开有作用域的注册。取消决定所有尚未完成的进行中结果,并将其报告为 `aborted`;已经完成的轮次仍保持完成状态。 -运行公开严格的 `steer` 功能:同步的 `AgentStatus.running` 检查与 `Agent.steer()` 调用位于同一个调用栈帧中,因此消息要么加入观察到的轮次,要么抛错。运行不会触达 Agent 层在空闲时排队并启动新轮次的 fallback;否则会在运行结果读取后启动一个未被跟踪的轮次。 +运行公开严格的 `steer` 功能:同步检查与 `Agent.trySteer()` 调用位于同一个调用栈帧中,因此消息要么加入观察到的步骤,要么抛错。交付要求 `AgentStatus.running`、子 agent 日志中有开放的轮次和步骤、没有已提交的结构化捕获,并且在该步骤的最终 drain 开始前获接纳。提示词接纳、`agent/turn-stopping` 等步骤间处理,以及已关闭轮次的持久性 flush 都会拒绝交付。运行不会触达 Agent 层在空闲时排队并启动新轮次的 fallback;否则会在运行结果读取后启动一个未被跟踪的轮次。 ## Spawn 与 fork 输入 diff --git a/packages/subagent/subagent-inprocess/src/index.ts b/packages/subagent/subagent-inprocess/src/index.ts index a71ee4a05b..aaad34ccf8 100644 --- a/packages/subagent/subagent-inprocess/src/index.ts +++ b/packages/subagent/subagent-inprocess/src/index.ts @@ -11,8 +11,8 @@ import { randomUUID } from 'node:crypto' import type { Context } from 'cordis' import type { Agent, AgentHandle, AgentOptions } from '@deepseek-ai/dsh-agent' import { findLastMessageTurnEnd, SessionId, type SessionEvent, type TurnEndReason } from '@deepseek-ai/dsh-session' -import { createUserMessage, type ContentBlock } from '@deepseek-ai/dsh-llm' -import { assertSubagentMaxDepth, delegationDepthOf } from '@deepseek-ai/dsh-subagent' +import { createUserMessage, errorChain, type ContentBlock } from '@deepseek-ai/dsh-llm' +import { assertSubagentMaxDepth, delegationDepthOf, SubagentError } from '@deepseek-ai/dsh-subagent' import type { SubagentDescriptorData, SubagentResult, @@ -67,6 +67,9 @@ export interface InProcessRunOptions { readonly seed?: SessionEvent[] } +/** Whether one activation must prove its final state durable before success. */ +type Durability = 'best-effort' | 'required' + /** Error used when cancellation wins before the child publication boundary. */ function prePublicationAbort(): Error { return new Error('subagent request was aborted before child publication') @@ -168,7 +171,15 @@ export async function startInProcessRun( signal: request.signal, setup, }) - return driveTurn(handle, request.signal, request.prompt, childId, seedLength, structured) + return driveTurn( + handle, + request.signal, + request.prompt, + childId, + seedLength, + request.continuation === undefined ? 'best-effort' : 'required', + structured, + ) } /** @@ -203,14 +214,15 @@ export async function resumeInProcessRun(request: SubagentResumeRequest): Promis // The result boundary is this activation's own work: everything already in // the resumed transcript belongs to earlier turns. const resumePoint = handle.agent.session.events.length - return driveTurn(handle, request.signal, request.prompt, request.sessionId, resumePoint) + return driveTurn(handle, request.signal, request.prompt, request.sessionId, resumePoint, 'required') } /** * Drive one activation turn on a published child and wrap it as a run. The * caller has already created or resumed the agent; this owns the * signal-handoff race, the live abort listener, result collection past - * `boundary`, strict steering, and disposal. + * `boundary`, the continuable-run durability confirmation, strict steering, + * and disposal. */ function driveTurn( handle: AgentHandle, @@ -218,6 +230,7 @@ function driveTurn( prompt: ContentBlock[], childId: SessionId, boundary: number, + durability: Durability, structured?: StructuredAttachment, ): SubagentRun | Promise { const child = handle.agent @@ -238,6 +251,17 @@ function driveTurn( try { child.followup(createUserMessage({ content: prompt, source: { kind: 'user' } })) await child.whenIdle() + if (durability === 'required') { + try { + await child.ctx.sessions.flush(child.session) + } catch (error: unknown) { + throw new SubagentError( + `subagent "${childId}" durability checkpoint failed; the latest child state was not confirmed persisted and may be unavailable or stale on resume: ${errorChain(error)}`, + 'DURABILITY_FAILED', + { cause: error }, + ) + } + } return readResult( child, boundary, diff --git a/packages/subagent/subagent-inprocess/tests/subagent-inprocess.spec.ts b/packages/subagent/subagent-inprocess/tests/subagent-inprocess.spec.ts index aaa4ac82d4..bcec292d93 100644 --- a/packages/subagent/subagent-inprocess/tests/subagent-inprocess.spec.ts +++ b/packages/subagent/subagent-inprocess/tests/subagent-inprocess.spec.ts @@ -9,7 +9,7 @@ import InvariantService from '@deepseek-ai/dsh-invariants' import * as SessionInvariant from '@deepseek-ai/dsh-session/invariant' import * as AgentInvariant from '@deepseek-ai/dsh-agent/invariant' import * as AgentLoopInvariant from '@deepseek-ai/dsh-agent-loop/invariant' -import SubagentService, { SUBAGENT_DESCRIPTOR_VERSION } from '@deepseek-ai/dsh-subagent' +import SubagentService, { SUBAGENT_DESCRIPTOR_VERSION, SubagentError } from '@deepseek-ai/dsh-subagent' import { maxTokensResponse, MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' import { resumeInProcessRun, startInProcessRun } from '../src/index.ts' @@ -38,6 +38,22 @@ function request(parent: Agent, signal = new AbortController().signal) { return { prompt: [{ type: 'text' as const, text: 'child task' }], parent, signal } } +function continuableRequest(parent: Agent) { + const sessionId = SessionId('continuable-child') + return { + ...request(parent), + continuation: { + sessionId, + descriptor: { + version: SUBAGENT_DESCRIPTOR_VERSION, + provider: 'spawn', + agentProvider: 'mock', + agentModel: 'mock', + }, + }, + } +} + function text(blocks: readonly { type: string; text?: string }[]): string { return blocks.filter(block => block.type === 'text').map(block => block.text).join('') } @@ -56,6 +72,59 @@ describe('startInProcessRun', () => { expect(ctx.agents.get(run.id)).toBeUndefined() }) + it('requires a final durability checkpoint for a continuable child', async () => { + const { ctx, parent } = await setup([textResponse('driver answer')]) + const failure = new Error('disk full') + let flushes = 0 + ctx.on('session/flush', (session) => { + if (session.header.parentSession === undefined) return + flushes++ + throw failure + }) + + const run = await startInProcessRun(continuableRequest(parent), {}) + const caught: unknown = await run.result.catch((error: unknown) => error) + expect(caught).toBeInstanceOf(SubagentError) + const durabilityError = caught as SubagentError + expect(durabilityError.code).toBe('DURABILITY_FAILED') + expect(durabilityError.cause).toBe(failure) + expect(durabilityError.message).toContain( + 'the latest child state was not confirmed persisted and may be unavailable or stale on resume: disk full', + ) + expect(flushes).toBe(2) + await run.dispose() + }) + + it('completes a continuable child when the final checkpoint retries a transient flush failure', async () => { + const { ctx, parent } = await setup([textResponse('driver answer')]) + let flushes = 0 + ctx.on('session/flush', (session) => { + if (session.header.parentSession === undefined) return + flushes++ + if (flushes === 1) throw new Error('temporary append failure') + }) + + const run = await startInProcessRun(continuableRequest(parent), {}) + await expect(run.result).resolves.toMatchObject({ stopReason: 'completed' }) + expect(flushes).toBe(2) + await run.dispose() + }) + + it('keeps foreground runs best-effort when their turn checkpoint fails', async () => { + const { ctx, parent } = await setup([textResponse('driver answer')]) + let flushes = 0 + ctx.on('session/flush', (session) => { + if (session.header.parentSession === undefined) return + flushes++ + throw new Error('disk full') + }) + + const run = await startInProcessRun(request(parent), {}) + await expect(run.result).resolves.toMatchObject({ stopReason: 'completed' }) + expect(flushes).toBe(1) + await run.dispose() + }) + it('reports the message-turn outcome when a later non-message turn completes during flush', async () => { const { ctx, parent } = await setup([maxTokensResponse('partial answer')]) let injected = false @@ -201,13 +270,21 @@ describe('startInProcessRun', () => { it('resumes without inventing undeclared agent model options', async () => { const childId = SessionId('resumed-child') + let flushes = 0 const child = { id: childId, options: {}, session: new Session(childId), status: 'idle', acceptsNextStep: false, - ctx: new Context(), + ctx: { + sessions: { + flush: () => { + flushes++ + return Promise.resolve() + }, + }, + } as unknown as Context, send(): void {}, reserveTurnAdmission: () => undefined, updateInbox: () => 'not-found', @@ -238,6 +315,7 @@ describe('startInProcessRun', () => { }) expect(resumedOptions).toEqual({}) await expect(run.result).resolves.toMatchObject({ stopReason: 'error' }) + expect(flushes).toBe(1) await run.dispose() }) diff --git a/packages/subagent/subagent/README.md b/packages/subagent/subagent/README.md index c7bf9af45a..68003363cd 100644 --- a/packages/subagent/subagent/README.md +++ b/packages/subagent/subagent/README.md @@ -49,7 +49,7 @@ Runtime features are optional methods whose presence is the capability check: `S ## The durable descriptor -The seam owns the versioned `subagent/descriptor` session event vocabulary (`src/descriptor.ts`): `snapshotSubagentDescriptor()` validates and detaches the declared composition before any Task exists, and `foldSubagentDescriptor()` recovers it from a loaded child log. The payload records the provider name, resolved child `agentOptions.provider`/`model`, and optional `persona`/`toolFilter` — explicit fields, never the merge-extensible `AgentOptions` object, so an unrelated extension value cannot break continuation. It omits `subagentDepth` (the persisted header's `delegationDepth` is the monotone floor) and `outputSchema` (an activation's result contract). The event is log-only: no `surfaceOp`, absent from model history, and retained by the append-only log across compaction. +The seam owns the versioned `subagent/descriptor` session event vocabulary (`src/descriptor.ts`): `snapshotSubagentDescriptor()` validates and detaches the declared composition before any Task exists, and `foldSubagentDescriptor()` validates the complete current-version payload before recovering it from a loaded child log. Malformed current-version payloads fail before provider dispatch; unsupported versions make the child non-resumable. The payload records the provider name, resolved child `agentOptions.provider`/`model`, and optional `persona`/`toolFilter` — explicit fields, never the merge-extensible `AgentOptions` object, so an unrelated extension value cannot break continuation. It omits `subagentDepth` (the persisted header's `delegationDepth` is the monotone floor) and `outputSchema` (an activation's result contract). The event is log-only: no `surfaceOp`, absent from model history, and retained by the append-only log across compaction. ## Delegation depth @@ -61,7 +61,7 @@ The seam owns the depth vocabulary shared by implementations and consumers: the `provider.start(request): Promise` is the ownership-transfer boundary. Before fulfillment, the provider owns setup and must cancel, roll back, and quiesce partial resources on every failure. After fulfillment, the caller owns the run and must call `dispose()` on every path. `provider.resume?(request)` shares the same contract for a resumed activation. -`SubagentRun.result` resolves to `{ output, structured?, stopReason }`. Child-level failures resolve with a non-`completed` reason; only an infrastructure fault that the seam cannot represent may reject. `dispose()` is idempotent, cancels remaining work, and waits for the child resources to quiesce. +`SubagentRun.result` resolves to `{ output, structured?, stopReason }`. Child-level failures resolve with a non-`completed` reason; only an infrastructure fault that the seam cannot represent may reject. For a continuable activation, a completed result also confirms that the provider made its final state durable; a failed required checkpoint rejects as infrastructure rather than publishing unconfirmed output. `dispose()` is idempotent, cancels remaining work, and waits for the child resources to quiesce. A local run publishes an ordinary child agent/session before `start()` fulfills, returns that shared session id as `SubagentRun.id`, exposes the exact child as `SubagentRun.localAgent`, and records `request.parent.session.id` in the child's `parentSession` header. A continuable start publishes exactly the control-allocated `continuation.sessionId`. Remote providers instead mint a parent-scoped lifecycle id and return `localAgent: undefined`. diff --git a/packages/subagent/subagent/src/descriptor.ts b/packages/subagent/subagent/src/descriptor.ts index c837a696b8..00942ca448 100644 --- a/packages/subagent/subagent/src/descriptor.ts +++ b/packages/subagent/subagent/src/descriptor.ts @@ -71,6 +71,102 @@ export interface SubagentDescriptorInput { readonly toolFilter?: ToolRestriction } +const DESCRIPTOR_KEYS = new Set([ + 'version', + 'provider', + 'agentProvider', + 'agentModel', + 'persona', + 'toolFilter', +]) +const TOOL_FILTER_KEYS = new Set(['allow', 'deny']) + +/** Whether a persisted JSON value is an object record. */ +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +/** Reject fields outside one versioned record's declared schema. */ +function assertKnownKeys(value: Record, keys: ReadonlySet, path: string): void { + const unknown = Object.keys(value).find(key => !keys.has(key)) + if (unknown !== undefined) { + throw new Error(`persisted subagent descriptor ${path} has unknown field "${unknown}"`) + } +} + +/** Read one optional string field from a persisted descriptor record. */ +function optionalString(value: Record, key: string): string | undefined { + if (!Object.hasOwn(value, key)) return undefined + const field = value[key] + if (typeof field !== 'string') { + throw new Error(`persisted subagent descriptor ${key} must be a string`) + } + return field +} + +/** Read one optional string-array field from a persisted tool restriction. */ +function optionalStringArray(value: Record, key: string): string[] | undefined { + if (!Object.hasOwn(value, key)) return undefined + const field = value[key] + if (!Array.isArray(field)) { + throw new Error(`persisted subagent descriptor toolFilter.${key} must be an array of strings`) + } + const items: unknown[] = field + if (items.some(item => typeof item !== 'string')) { + throw new Error(`persisted subagent descriptor toolFilter.${key} must be an array of strings`) + } + return items as string[] +} + +/** Validate and reconstruct a persisted tool restriction. */ +function parseToolFilter(value: unknown): ToolRestriction { + if (!isRecord(value)) { + throw new Error('persisted subagent descriptor toolFilter must be an object') + } + assertKnownKeys(value, TOOL_FILTER_KEYS, 'toolFilter') + const allow = optionalStringArray(value, 'allow') + const deny = optionalStringArray(value, 'deny') + if (allow === undefined && deny === undefined) { + throw new Error('persisted subagent descriptor toolFilter must declare allow and/or deny') + } + return { + ...allow !== undefined ? { allow } : {}, + ...deny !== undefined ? { deny } : {}, + } +} + +/** Validate one persisted descriptor payload for the current runtime. */ +function parseSubagentDescriptor(value: unknown): SubagentDescriptorData | undefined { + if (!isRecord(value)) { + throw new Error('persisted subagent descriptor payload must be an object') + } + const version = value['version'] + if (typeof version !== 'number') { + throw new Error('persisted subagent descriptor version must be a number') + } + if (version !== SUBAGENT_DESCRIPTOR_VERSION) return undefined + + assertKnownKeys(value, DESCRIPTOR_KEYS, 'payload') + const provider = value['provider'] + if (typeof provider !== 'string') { + throw new Error('persisted subagent descriptor provider must be a string') + } + const agentProvider = optionalString(value, 'agentProvider') + const agentModel = optionalString(value, 'agentModel') + const persona = optionalString(value, 'persona') + const toolFilter = Object.hasOwn(value, 'toolFilter') + ? parseToolFilter(value['toolFilter']) + : undefined + return { + version: SUBAGENT_DESCRIPTOR_VERSION, + provider, + ...agentProvider !== undefined ? { agentProvider } : {}, + ...agentModel !== undefined ? { agentModel } : {}, + ...persona !== undefined ? { persona } : {}, + ...toolFilter !== undefined ? { toolFilter } : {}, + } +} + /** * Validate and detach descriptor inputs into the durable payload, before any * Task or provider work begins — the same detached lossless-JSON boundary the @@ -105,12 +201,13 @@ export function snapshotSubagentDescriptor(input: SubagentDescriptorInput): Suba * @returns the descriptor, or `undefined` when the log has none or its * version is not {@link SUBAGENT_DESCRIPTOR_VERSION} (the child is not * resumable by this runtime). + * @throws when a current-version persisted payload does not match its complete + * declared schema. */ export function foldSubagentDescriptor(events: readonly SessionEvent[]): SubagentDescriptorData | undefined { const event = events.find( (candidate): candidate is SessionEvent<'subagent/descriptor'> => candidate.type === 'subagent/descriptor', ) if (event === undefined) return undefined - if (event.data.version !== SUBAGENT_DESCRIPTOR_VERSION) return undefined - return event.data + return parseSubagentDescriptor(event.data) } diff --git a/packages/subagent/subagent/src/types.ts b/packages/subagent/subagent/src/types.ts index 8cc88eb0c2..0b76723e26 100644 --- a/packages/subagent/subagent/src/types.ts +++ b/packages/subagent/subagent/src/types.ts @@ -207,8 +207,10 @@ export interface SubagentRun { * Resolves with the child's terminal {@link SubagentResult} when the run * settles. Does NOT reject on a child-level failure — a model/transport * failure resolves with `stopReason: 'error'` so the consumer maps it to an - * `isError` tool result. Rejects only on an infrastructure fault the seam - * cannot represent as a stop reason. + * `isError` tool result. For a continuable activation, a completed result + * also means the provider confirmed the activation's final state durable. + * Rejects on an infrastructure fault the seam cannot represent as a stop + * reason, including a failed required durability checkpoint. */ readonly result: Promise /** diff --git a/packages/subagent/subagent/tests/service.spec.ts b/packages/subagent/subagent/tests/service.spec.ts index 1c5889bdc2..d04599a4d2 100644 --- a/packages/subagent/subagent/tests/service.spec.ts +++ b/packages/subagent/subagent/tests/service.spec.ts @@ -274,15 +274,68 @@ describe('SubagentService', () => { }) describe('subagent descriptors', () => { - it('omits absent model selectors and rejects unsupported versions', () => { - expect(snapshotSubagentDescriptor({ provider: 'spawn' })).toEqual({ + const event = (data: unknown): SessionEvent<'subagent/descriptor'> => ({ + type: 'subagent/descriptor', + data, + } as unknown as SessionEvent<'subagent/descriptor'>) + + it('omits absent fields, recovers a complete payload, and rejects unsupported versions', () => { + expect(foldSubagentDescriptor([])).toBeUndefined() + const minimal = snapshotSubagentDescriptor({ provider: 'spawn' }) + expect(minimal).toEqual({ version: SUBAGENT_DESCRIPTOR_VERSION, provider: 'spawn', }) - const unsupported = { - type: 'subagent/descriptor', - data: { version: SUBAGENT_DESCRIPTOR_VERSION + 1, provider: 'spawn' }, - } as unknown as SessionEvent<'subagent/descriptor'> - expect(foldSubagentDescriptor([unsupported])).toBeUndefined() + expect(foldSubagentDescriptor([event(minimal)])).toEqual(minimal) + const complete = { + version: SUBAGENT_DESCRIPTOR_VERSION, + provider: 'spawn', + agentProvider: 'deepseek', + agentModel: 'chat', + persona: 'reviewer', + toolFilter: { allow: ['read'], deny: ['bash'] }, + } + expect(snapshotSubagentDescriptor({ + provider: complete.provider, + agentProvider: complete.agentProvider, + agentModel: complete.agentModel, + persona: complete.persona, + toolFilter: complete.toolFilter, + })).toEqual(complete) + expect(foldSubagentDescriptor([event(complete)])).toEqual(complete) + expect(foldSubagentDescriptor([ + event({ version: SUBAGENT_DESCRIPTOR_VERSION, provider: 'spawn', toolFilter: { allow: ['read'] } }), + ])).toMatchObject({ toolFilter: { allow: ['read'] } }) + expect(foldSubagentDescriptor([ + event({ version: SUBAGENT_DESCRIPTOR_VERSION, provider: 'spawn', toolFilter: { deny: ['bash'] } }), + ])).toMatchObject({ toolFilter: { deny: ['bash'] } }) + expect(foldSubagentDescriptor([ + event({ version: SUBAGENT_DESCRIPTOR_VERSION + 1, provider: 'spawn' }), + ])).toBeUndefined() + expect(() => snapshotSubagentDescriptor({ + provider: 'spawn', + toolFilter: { deny: [Symbol('not-json')] as unknown as string[] }, + })).toThrow('not losslessly JSON-serializable') + }) + + it.each([ + ['string payload', 'invalid', 'payload must be an object'], + ['null payload', null, 'payload must be an object'], + ['array payload', [], 'payload must be an object'], + ['missing version', { provider: 'spawn' }, 'version must be a number'], + ['string version', { version: '1', provider: 'spawn' }, 'version must be a number'], + ['unknown payload field', { version: 1, provider: 'spawn', extra: true }, 'payload has unknown field "extra"'], + ['missing provider', { version: 1 }, 'provider must be a string'], + ['invalid provider', { version: 1, provider: 7 }, 'provider must be a string'], + ['invalid agent provider', { version: 1, provider: 'spawn', agentProvider: 7 }, 'agentProvider must be a string'], + ['invalid agent model', { version: 1, provider: 'spawn', agentModel: [] }, 'agentModel must be a string'], + ['invalid persona', { version: 1, provider: 'spawn', persona: {} }, 'persona must be a string'], + ['non-object tool filter', { version: 1, provider: 'spawn', toolFilter: [] }, 'toolFilter must be an object'], + ['unknown tool-filter field', { version: 1, provider: 'spawn', toolFilter: { except: ['bash'] } }, 'toolFilter has unknown field "except"'], + ['empty tool filter', { version: 1, provider: 'spawn', toolFilter: {} }, 'toolFilter must declare allow and/or deny'], + ['non-array allow list', { version: 1, provider: 'spawn', toolFilter: { allow: 'read' } }, 'toolFilter.allow must be an array of strings'], + ['non-string deny item', { version: 1, provider: 'spawn', toolFilter: { deny: [7] } }, 'toolFilter.deny must be an array of strings'], + ])('rejects a malformed persisted descriptor: %s', (_case, data, detail) => { + expect(() => foldSubagentDescriptor([event(data)])).toThrow(detail) }) })