diff --git a/.agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.i18n.yaml index e0839bb6aa..c36ec1d89f 100644 --- a/.agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.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-16-explicit-turn-cancellation.md: b8cf16f1ae6a8430ae47f0f548d8aae1355a536d -2026-07-16-explicit-turn-cancellation.zh.md: ad6944cb88a253580dc8b2c217a2b9116419f926 +2026-07-16-explicit-turn-cancellation.md: 2803d140256a7a65f901e7c61d8cef32091e7cc9 +2026-07-16-explicit-turn-cancellation.zh.md: 3bebe8642ee65f91e6eb12447b2f732418906dca diff --git a/.agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.md b/.agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.md index b8cf16f1ae..2803d14025 100644 --- a/.agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.md +++ b/.agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.md @@ -12,15 +12,15 @@ The [initiating Agent scope decision](2026-07-15-agent-initiator-scope.md) inten ## Decision -Agent owns the runtime-only `AgentCancelCause` union `{ kind: 'user' } | { kind: 'parent' }`; `agent.cancel()` defaults to `user`. The normalization boundary accepts only an exact ordinary or null-prototype object with one supported `kind`, then returns a detached frozen value for the current turn signal. Strings, extra or symbol fields, unknown kinds, arrays, class instances, `Error`, and `AbortSignal` are rejected synchronously even when the Agent is idle. +Agent owns the runtime-only `AgentCancelCause` union `{ kind: 'user' } | { kind: 'parent' }`; `agent.cancel()` defaults to `user`. TypeScript enforces that vocabulary at this typed same-process seam, with no runtime validator, fallback, or special compatibility contract for untyped callers. An active `TurnCancellation` copies the typed discriminant into a fresh frozen signal reason; idle cancellation has no holder to mutate and does not arm later work. -An interrupted live turn ends with the coarse durable `{ kind: 'aborted' }` outcome. The terminal event records what happened to the turn, while the runtime signal identifies who requested cancellation; it does not duplicate `user` or `parent` into replay. A future audit requirement uses a separate control-request event so a request and its eventual outcome remain distinct. Durable events contain no stack, signal, error object, free-form cancellation text, or backend-private detail. +An interrupted live turn ends with the coarse durable `{ kind: 'aborted' }` outcome. The terminal event records what happened to the turn, while the runtime signal identifies who requested cancellation; it does not duplicate `user` or `parent` into replay. Session seed/load rejects legacy aborted records with a reason or any other extra field, so replay cannot reintroduce caller-owned cancellation detail. A future audit requirement uses a separate control-request event so a request and its eventual outcome remain distinct. Durable events contain no stack, signal, error object, free-form cancellation text, or backend-private detail. -AgentLoop privately owns one `TurnCancellation` per prospective turn. It installs the holder before notifying `agent/status = running`, retains its single `AbortController` through prompt processing, prompt assembly, every step, model and tool execution, continuation, `agent/turn-stop`, `turn/end`, and durability flush, then clears it. Every participating method, event, and request value receives that same explicit signal; the next turn receives a fresh signal. +AgentLoop privately owns one `TurnCancellation` per prospective turn. It installs the holder before notifying `agent/status = running`, retains its single `AbortController` through prompt processing, prompt assembly, every step, model and tool execution, continuation, and `agent/turn-stop`, then clears the exact holder immediately before publishing `turn/end`. Terminal event observers and the following durability flush therefore cannot cancel already-completed turn work even though driver status may remain `running` until the flush settles. Every participating method, event, and request value receives that same explicit signal; the next turn receives a fresh signal. The driver keeps only a cause-less pre-run marker for queued work cancelled before a turn is claimed. It clears the queued and steering work that existed when `cancel()` ran without arming cancellation for future prompts. If a `running` listener synchronously cancels old work and sends a replacement, the driver discards the aborted holder and creates a fresh one for the replacement. Repeated cancellation is first-wins for the active holder, while later calls may still clear newly queued pending work. -The explicit event signatures keep their positional form and place `signal` immediately before a waterfall's final `next`. Prompt submission, request configuration, step-result processing, continuation, and terminal stop join the pre-existing explicit signal seams for pre-step, session prefix, model generation, tool execution, approval, and subagent or workflow requests. `SystemPrompt.assemble()` carries `signal?: AbortSignal` in `AssembleContext` because that object is an explicit request value. Listeners may cooperate with the signal but must not retain it to control another turn. +The explicit event signatures keep their positional form and place `signal` immediately before a waterfall's final `next`. Prompt submission, request configuration, step-result processing, continuation, and terminal stop join the pre-existing explicit signal seams for pre-step, session prefix, model generation, tool execution, approval, and subagent or workflow requests. Hook bridges must also supply `RunHookOptions.signal`, so a turn cancellation reaches the bash executor's process-group kill and join boundary. `SystemPrompt.assemble()` carries `signal?: AbortSignal` in `AssembleContext` because that object is an explicit request value that can also represent signal-less assembly outside a turn. Listeners may cooperate with the signal but must not retain it to control another turn. `ctx.agents` continues to carry only the initiating Agent. Ambient Agent presence does not imply liveness, a current turn, or cancellation authority, and `agentInterruptReasonOf(signal)` reads only its explicit argument. Concurrent Agents isolate both their initiator identities and their turn signals; a child driver shadows the parent initiator while its parent request signal still travels through the subagent seam. @@ -30,7 +30,7 @@ Cancellation remains cooperative. The loop checks interruption before and after ## Verification -Contract tests verify strict runtime cause validation, frozen detachment, default and first-wins behavior, the coarse Session JSON round trip, ACP `user`, in-process subagent `parent`, and disposal precedence. Loop tests make cooperative listeners wait on the signal at prompt submission, system-prompt assembly, session prefix, pre-step, request, model stream, step result, tool execution, continuation, and terminal stop; they assert one signal within a turn and a fresh signal across turns. +Contract tests verify the typed caller union, frozen detachment, default and first-wins behavior, the coarse Session JSON round trip and legacy-record rejection, ACP `user`, in-process subagent `parent`, and disposal precedence. Loop tests make cooperative listeners wait on the signal at prompt submission, system-prompt assembly, session prefix, pre-step, request, model stream, step result, tool execution, continuation, and terminal stop; they assert one signal within a turn, a fresh signal across turns, and no cancellation authority during terminal publication or a blocked durability flush. A real hook bridge test cancels and reaps a blocked prompt hook before idle. Initiator-scope tests assert that every hook still observes the exact Agent and no ambient turn signal, concurrent Agents retain independent identities and signals, and a nested child driver shadows only identity. Race tests cover idle cancellation, pre-run cancellation, replacement submission from a `running` listener, repeated cancellation, and cancel-versus-dispose quiescence. @@ -50,6 +50,6 @@ Initiator-scope tests assert that every hook still observes the exact Agent and ## Consequences -Cancellation has one runtime owner, one signal per turn, and one typed runtime caller vocabulary. Session retains the coarse `aborted` outcome that its consumers actually use, stays isolated from runtime objects, and no longer needs cancellation-specific canonicalization. Cooperative cancellation reaches every asynchronous turn seam, including work before the first step and after the last one. +Cancellation has one runtime owner, one signal per live turn, and one typed runtime caller vocabulary. Session retains the coarse `aborted` outcome that its consumers actually use, rejects reason-bearing legacy forms, and stays isolated from runtime objects. Cooperative cancellation reaches every asynchronous turn seam, including work before the first step and after the last one, while terminal publication and persistence remain outside its authority. The explicit signal adds parameters to several public events and requires plugins to forward cancellation deliberately. This is intentional: authority is visible at the call boundary, lifetime matches the turn, and stale ambient descendants cannot acquire control. Uncooperative in-process work may delay cancellation, but the reported quiescent state remains truthful. diff --git a/.agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.zh.md b/.agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.zh.md index ad6944cb88..3bebe8642e 100644 --- a/.agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.zh.md @@ -12,15 +12,15 @@ Status: implemented ## 决策 -Agent 拥有仅用于运行时的 `AgentCancelCause` 联合类型 `{ kind: 'user' } | { kind: 'parent' }`;`agent.cancel()` 默认使用 `user`。规范化边界只接受恰好包含一个受支持 `kind` 的普通对象或原型为 null 的对象,并返回供当前轮次 signal 使用的、与调用方分离且已冻结的值。即使 Agent 处于空闲状态,字符串、额外字段或符号字段、未知 kind、数组、类实例、`Error` 和 `AbortSignal` 也会被同步拒绝。 +Agent 拥有仅用于运行时的 `AgentCancelCause` 联合类型 `{ kind: 'user' } | { kind: 'parent' }`;`agent.cancel()` 默认使用 `user`。TypeScript 在这份类型化同进程契约中强制执行该词汇,不提供运行时校验器、后备行为,也不为无类型调用方提供特殊兼容性契约。活跃的 `TurnCancellation` 会把类型化判别字段复制为一个全新且已冻结的 signal 原因;空闲状态下没有可修改的持有者,也不会让后续工作预先进入取消状态。 -正在运行的轮次被中断后,以粗粒度的持久化结果 `{ kind: 'aborted' }` 结束。终态事件记录轮次发生了什么,运行时 signal 标识谁请求了取消;回放不会重复保存 `user` 或 `parent`。未来若有审计需求,应使用独立的控制请求事件,让请求与最终结果保持为两项事实。持久化事件不包含调用栈、signal、错误对象、自由文本取消原因或后端私有细节。 +正在运行的轮次被中断后,以粗粒度的持久化结果 `{ kind: 'aborted' }` 结束。终态事件记录轮次发生了什么,运行时 signal 标识谁请求了取消;回放不会重复保存 `user` 或 `parent`。Session seed/load 会拒绝携带取消原因或任何其他额外字段的旧式中止记录,因此回放无法重新引入由调用方持有的取消细节。未来若有审计需求,应使用独立的控制请求事件,让请求与最终结果保持为两项事实。持久化事件不包含调用栈、signal、错误对象、自由文本取消原因或后端私有细节。 -AgentLoop 为每个待启动轮次私有地持有一个 `TurnCancellation`。它在通知 `agent/status = running` 前安装该持有者,使其中唯一的 `AbortController` 持续覆盖提示词处理、提示词组装、每个步骤、模型与工具执行、继续决策、`agent/turn-stop`、`turn/end` 和持久化刷新,随后清除该持有者。所有参与的方法、事件和请求值都会收到同一个显式 signal;下一个轮次会收到全新的 signal。 +AgentLoop 为每个待启动轮次私有地持有一个 `TurnCancellation`。它在通知 `agent/status = running` 前安装该持有者,使其中唯一的 `AbortController` 持续覆盖提示词处理、提示词组装、每个步骤、模型与工具执行、继续决策和 `agent/turn-stop`;随后在发布 `turn/end` 前立即清除所安装的那个持有者。因此,即使驱动器状态可能在持久化刷新结算前保持 `running`,终态事件观察者及其后的持久化刷新也无法取消已完成的轮次工作。所有参与的方法、事件和请求值都会收到同一个显式 signal;下一个轮次会收到全新的 signal。 对于轮次被认领前已取消的排队工作,驱动器只保留一个不携带取消原因的运行前标记。它会清除 `cancel()` 调用时已存在的排队工作和 steering(中途引导)工作,但不会预先取消未来的提示词。若 `running` 监听器同步取消旧工作并发送替代提示词,驱动器会丢弃已中止的持有者,并为替代提示词创建全新的持有者。同一活跃持有者上的重复取消遵循首次请求优先,后续调用仍可清除新入队的待处理工作。 -显式事件签名保留位置参数形式,并把 `signal` 放在 waterfall(瀑布式事件)的最后一个参数 `next` 之前。提示词提交、请求配置、步骤结果处理、继续决策和终止停止加入已有的步骤前处理、会话前缀、模型生成、工具执行、审批以及 subagent 或工作流请求的显式 signal seam。`SystemPrompt.assemble()` 在 `AssembleContext` 中携带 `signal?: AbortSignal`,因为该对象是显式请求值。监听器可以配合该 signal 取消,但不得保留它来控制其他轮次。 +显式事件签名保留位置参数形式,并把 `signal` 放在 waterfall(瀑布式事件)的最后一个参数 `next` 之前。提示词提交、请求配置、步骤结果处理、继续决策和终止停止加入已有的步骤前处理、会话前缀、模型生成、工具执行、审批以及 subagent 或工作流请求的显式 signal seam。钩子桥接器也必须提供 `RunHookOptions.signal`,使轮次取消能够到达 Bash 执行器终止进程组并等待其退出的边界。`SystemPrompt.assemble()` 在 `AssembleContext` 中携带 `signal?: AbortSignal`,因为该对象是显式请求值,也可表示轮次之外不携带 signal 的组装。监听器可以配合该 signal 取消,但不得保留它来控制其他轮次。 `ctx.agents` 仍只携带发起 Agent。环境中的 Agent 并不代表存活、当前轮次或取消权限,`agentInterruptReasonOf(signal)` 也只读取其显式参数。并发 Agent 会同时隔离各自的发起方身份和轮次 signal;子驱动会遮蔽父发起方,而父请求 signal 仍通过 subagent seam 传递。 @@ -30,7 +30,7 @@ Agent dispose(资源释放)会在活跃持有者上请求仅用于运行时 ## 验证 -契约测试验证严格的运行时取消原因校验、冻结且与调用方分离、默认行为与首次请求优先行为、粗粒度的会话 JSON 往返、ACP `user`、进程内 subagent `parent` 以及 dispose 优先级。AgentLoop 测试让协作式监听器在提示词提交、系统提示词组装、会话前缀、步骤前处理、请求、模型流、步骤结果、工具执行、继续决策和终止停止处等待 signal;并断言同一轮次使用一个 signal,不同轮次使用全新的 signal。 +契约测试验证类型化调用方联合类型、冻结且与调用方分离、默认行为与首次请求优先行为、粗粒度的会话 JSON 往返与旧式记录拒绝、ACP `user`、进程内 subagent `parent` 以及 dispose 优先级。AgentLoop 测试让协作式监听器在提示词提交、系统提示词组装、会话前缀、步骤前处理、请求、模型流、步骤结果、工具执行、继续决策和终止停止处等待 signal;并断言同一轮次使用一个 signal,不同轮次使用全新的 signal,终态发布期间和持久化刷新受阻期间不存在取消权限。真实钩子桥接器测试会在报告空闲状态前取消并回收受阻的提示词钩子。 发起方作用域测试断言所有钩子仍观察到同一个 Agent 且没有环境中的轮次 signal,并发 Agent 保持独立的身份与 signal,嵌套子驱动只遮蔽身份。竞态测试覆盖空闲状态取消、运行前取消、从 `running` 监听器提交替代提示词、重复取消以及取消与 dispose 竞争下的静止状态。 @@ -50,6 +50,6 @@ Agent dispose(资源释放)会在活跃持有者上请求仅用于运行时 ## 后果 -取消拥有一个运行时归属方、每个轮次一个 signal,以及一套类型化的运行时调用方词汇。会话保留其消费方实际使用的粗粒度 `aborted` 结果,与运行时对象保持隔离,也不再需要取消专用的规范化逻辑。协作式取消覆盖每个异步轮次 seam,包括第一个步骤之前和最后一个步骤之后的工作。 +取消拥有一个运行时归属方、每个活跃轮次一个 signal,以及一套类型化的运行时调用方词汇。会话保留其消费方实际使用的粗粒度 `aborted` 结果,拒绝携带原因的旧式形式,并与运行时对象保持隔离。协作式取消覆盖每个异步轮次 seam,包括第一个步骤之前和最后一个步骤之后的工作,而终态发布和持久化仍在其权限范围之外。 显式 signal 会给多个公开事件增加参数,并要求插件有意识地转发取消。这是有意设计:权限在调用边界可见,生命周期与轮次匹配,陈旧的环境异步后代无法获得控制能力。不协作的进程内工作可能延迟取消,但所报告的静止状态仍然真实。 diff --git a/docs/architecture.md b/docs/architecture.md index f378774f4c..647c631eab 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -117,7 +117,7 @@ Pruning precedes summaries; overflow retries require durable progress. Bounded t The turn contains failures. Adapter failures close the step before `agent/request-error`, which receives exact `Error`, `LlmFailure`, and history. Retry opens another step; success clears history; exhaustion stores failure on `turn/end`. Failed chunks commit no message/tool. -Others use `agent/error`. Cancellation/disposal beat recovery; undispatched calls get synthetic `tool/call` plus `ABORTED_BEFORE_DISPATCH` results before `turn/end`. One turn-wide `AbortSignal` covers stages. `cancel()` validates `user | parent`, clears queues, and aborts it; durability records `aborted`. Disposal quiesces before unregistering ([decision](../.agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.md)). +Others use `agent/error`. Cancellation/disposal beat recovery; undispatched calls get synthetic `tool/call`/`ABORTED_BEFORE_DISPATCH` pairs. The signal spans stages until retirement before `turn/end`; typed `cancel()` clears queues and aborts it with `user | parent`. Durability records `aborted`; disposal quiesces before unregistering ([decision](../.agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.md)). Every session event is turn-enclosed. Reloading preserves an interrupted tail and closes it with a synthetic `interrupted` turn end. Failures after durable turn close report only through `agent/error` because no safe in-turn position remains. Each turn has one `TurnEndReason`; [TurnEndReasonMap](core-data-structures/session.md#why-a-turn-ended-turnendreasonmap) owns the variants. diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index ecd88171fb..dd0c9aeb02 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -832,7 +832,7 @@ fork(source: SessionForkSource, boundary?: number, childSessionId?: SessionId): Types: [CreateSessionOptions](../core-data-structures/persistence.md) · [Session](../core-data-structures/session.md) · [SessionId](../core-data-structures/core.md) -Source: [`packages/core/session/src/index.ts:553`](../../packages/core/session/src/index.ts) +Source: [`packages/core/session/src/index.ts:570`](../../packages/core/session/src/index.ts) ## `ctx.skills` — `SkillService` diff --git a/docs/core-data-structures/core.md b/docs/core-data-structures/core.md index fd8a7d3192..e657516427 100644 --- a/docs/core-data-structures/core.md +++ b/docs/core-data-structures/core.md @@ -397,8 +397,8 @@ interface Agent { * Clear all queued and steering work, including items waiting to start, and * abort the active turn. The first cause wins for that turn, and `whenIdle()` * resolves after cancellation reaches quiescence. Omission means - * `{ kind: 'user' }`; invalid causes throw synchronously even while idle. - * Idle cancellation is a no-op after validation and does not arm a later cancel. + * `{ kind: 'user' }`. Idle cancellation is a no-op and does not arm a later + * cancel. The active turn snapshots and freezes the typed cause. * @param cause - the stable caller intent carried by the current turn signal. */ cancel(cause?: AgentCancelCause): void @@ -411,7 +411,7 @@ interface Agent { `AgentStatus` is `'idle' | 'running' | 'disposed'`, and `SessionId` is branded. `running` describes the driver-wide drain interval, which can span turn close, its durability checkpoint, and consecutive queued turns; it does not prove a turn is still open. `AgentOptions` is merge-extensible and currently includes `provider?` and `model?`; dispatch requires both after `agent/request`. Persona belongs to `dsh-system-prompt`: an agent-scoped `deployment:persona` may shadow the global default. -The cause is runtime-only and becomes `AbortSignal.reason` on the turn's explicit signal. `agentInterruptReasonOf(signal)` recognizes `user`, `parent`, and lifecycle-only `disposed` without consulting ambient initiator state. Durable `turn/end` retains the coarse `{ kind: 'aborted' }` outcome; request provenance would require a separate durable event rather than overloading the terminal result. +The cause is a TypeScript-enforced same-process input. An active holder copies its discriminant into the runtime-only `AbortSignal.reason`; it is retired before `turn/end` publication. `agentInterruptReasonOf(signal)` recognizes `user`, `parent`, and lifecycle-only `disposed` without consulting ambient initiator state. Durable `turn/end` retains the coarse `{ kind: 'aborted' }` outcome; request provenance would require a separate durable event rather than overloading the terminal result. The [event taxonomy](../architecture.md#event) owns the `agent/*` lifecycle, checkpoint, and waterfall contracts. Turn and step boundaries are durable session events rather than agent emits. diff --git a/packages/core/agent-loop/README.md b/packages/core/agent-loop/README.md index fab6abb97b..4c92b460ff 100644 --- a/packages/core/agent-loop/README.md +++ b/packages/core/agent-loop/README.md @@ -56,7 +56,7 @@ The driver owns one agent for its lifetime and runs inside `ctx.agents.withIniti Every provider call that reaches a successful finish appends exactly one `assistant/message` completion anchor, including content-less calls and `max-tokens` finishes. A successful `agent/step-result` stores its transformed content; a rejected result records empty content before the original failure continues. The anchor retains exact chunk provenance (`[]` for a stream with no chunks) and usage when available, while empty content stays out of derived message history. -Plugin failure ends the current turn, not the loop. Only final adapter dispatch/iteration failures and terminal in-band error or aborted finishes enter `agent/request-error`; middleware, result processing, tools, and `agent/post-step` remain ordinary turn failures. Recovery receives the exact live error, immutable provider facts, and immutable prior failures after the failed step closes. A retry rebuilds from the durable log in a new numbered step, success clears the consecutive history, and exhaustion records the structured failure once on `turn/end`. AgentLoop privately owns one cancellation holder whose explicit signal spans prompt policy, assembly, every step, model and tool work, recovery, continuation, terminal stop, turn close, and flush; the next turn gets a fresh signal. `cancel()` strictly normalizes a runtime-only `user | parent` cause, clears pending work, and cooperatively aborts the holder without leaking to the next prompt; durable `turn/end` remains coarse `aborted`, and undispatched model tool calls receive synthetic `tool/call` and `ABORTED_BEFORE_DISPATCH` result pairs. Disposal wins terminal classification, and work that ignores the signal must settle before quiescence. The [explicit-cancellation decision](../../../.agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.md) owns the lifecycle and race contract. Terminal continuation stops remain authoritative through turn close and durability flush. +Plugin failure ends the current turn, not the loop. Only final adapter dispatch/iteration failures and terminal in-band error or aborted finishes enter `agent/request-error`; middleware, result processing, tools, and `agent/post-step` remain ordinary turn failures. Recovery receives the exact live error, immutable provider facts, and immutable prior failures after the failed step closes. A retry rebuilds from the durable log in a new numbered step, success clears the consecutive history, and exhaustion records the structured failure once on `turn/end`. AgentLoop privately owns one cancellation holder whose explicit signal spans prompt policy, assembly, every step, model and tool work, recovery, continuation, and terminal stop; it retires the holder immediately before publishing `turn/end`, while the driver may remain `running` through the durability flush. `cancel()` accepts the typed runtime-only `user | parent` cause, clears pending work, and cooperatively aborts the holder without leaking to the next prompt; durable `turn/end` remains coarse `aborted`, and undispatched model tool calls receive synthetic `tool/call` and `ABORTED_BEFORE_DISPATCH` result pairs. Disposal wins terminal classification, and work that ignores the signal must settle before quiescence. The [explicit-cancellation decision](../../../.agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.md) owns the lifecycle and race contract. Terminal continuation stops remain authoritative through turn close and durability flush. Within a step, exclusive calls form barriers; parallel-safe calls use a bounded rolling pool and are reclassified before start. Only dispatch/body overlaps. Policy, durable results, and result context remain model-ordered. Abort stops new calls, drains started results, then drains accepted batch context before the turn closes through the normal abort path. diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index b13c1f1aca..3bad874d4a 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -7,7 +7,7 @@ */ import type { Context } from 'cordis' -import { agentEvents, normalizeAgentCancelCause } from '@deepseek-ai/dsh-agent' +import { agentEvents } from '@deepseek-ai/dsh-agent' import type { AgentCancelCause, AgentOptions, AgentStatus, HookContext, InjectOptions, SendOptions } from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import { deepFreeze, errorChain } from '@deepseek-ai/dsh-llm' @@ -325,7 +325,7 @@ export class ReactLoopAgent implements Agent { } cancel(cause?: AgentCancelCause): void { - const normalized = normalizeAgentCancelCause(cause ?? { kind: 'user' }) + const reason = cause ?? { kind: 'user' } const cancellation = this.turnCancellation const preRun = cancellation === undefined && (this.#inbox.hasQueued || this.#inbox.hasSteering) if (preRun) { @@ -334,7 +334,7 @@ export class ReactLoopAgent implements Agent { // Clear work already present before abort observers run. A replacement // synchronously enqueued by an observer belongs to the next turn. this.#inbox.clear() - cancellation?.request(normalized) + cancellation?.request(reason) } /** diff --git a/packages/core/agent-loop/src/cancellation.ts b/packages/core/agent-loop/src/cancellation.ts index e4054d8262..c3f5430a20 100644 --- a/packages/core/agent-loop/src/cancellation.ts +++ b/packages/core/agent-loop/src/cancellation.ts @@ -20,12 +20,12 @@ export class TurnCancellation { /** * Abort the turn once. - * @param reason - a validated caller cause or lifecycle disposal marker. + * @param reason - a typed caller cause or lifecycle disposal marker. * @returns whether this request established the signal reason. */ request(reason: AgentCancelCause | typeof DISPOSED_INTERRUPT_REASON): boolean { if (this.signal.aborted) return false - this.#controller.abort(reason) + this.#controller.abort(Object.freeze({ kind: reason.kind })) return true } } diff --git a/packages/core/agent-loop/src/loop.ts b/packages/core/agent-loop/src/loop.ts index d6eec0a8c8..5961a60b15 100644 --- a/packages/core/agent-loop/src/loop.ts +++ b/packages/core/agent-loop/src/loop.ts @@ -124,7 +124,7 @@ export interface LoopHandle { setStatus(status: 'idle' | 'running'): void /** Install a fresh active-turn owner before the running notification. */ installTurnCancellation(): TurnCancellation - /** Clear only the exact owner whose turn and durability flush settled. */ + /** Clear only the exact owner whose turn reached its terminal event boundary. */ clearTurnCancellation(cancellation: TurnCancellation): void /** Resolves when the agent is disposed — unblocks the idle wait. */ disposed: Promise @@ -209,7 +209,7 @@ export async function runLoop(ctx: Context, handle: LoopHandle): Promise { const turn = lastTurnNumber(session) + 1 let terminalStopped = false try { - terminalStopped = await runTurn(ctx, events, handle, turn, transmission, cancellation.signal) + terminalStopped = await runTurn(ctx, events, handle, turn, transmission, cancellation) } catch (error: unknown) { // Pre-turn failure has no durable boundary to close; report it without appending outside a turn. const err = toError(error) @@ -232,10 +232,11 @@ export async function runLoop(ctx: Context, handle: LoopHandle): Promise { async function runTurn( ctx: Context, events: AgentEventDispatch, handle: LoopHandle, turn: number, transmission: TransmissionLog, - signal: AbortSignal, + cancellation: TurnCancellation, ): Promise { const agent = ctx.agents.requireInitiator() const { session } = agent + const { signal } = cancellation const drainSteering = (): boolean => { const messages = handle.inbox.drainSteering() for (const message of messages) { @@ -279,8 +280,11 @@ async function runTurn( } } - // Pre-commit validation failure escapes rather than masquerading as a committed boundary. + // Retire cancellation authority before publishing the terminal event. The + // following durability flush is quiescent turn work, but no longer part of + // the cancellable turn lifetime. const closeTurn = (): void => { + handle.clearTurnCancellation(cancellation) session.append('turn/end', { turn, reason }) } diff --git a/packages/core/agent-loop/tests/cancel.spec.ts b/packages/core/agent-loop/tests/cancel.spec.ts index b722a5312d..ec94b5fc59 100644 --- a/packages/core/agent-loop/tests/cancel.spec.ts +++ b/packages/core/agent-loop/tests/cancel.spec.ts @@ -779,30 +779,43 @@ describe('Agent.cancel()', () => { expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'aborted' }) }) - it('rejects invalid causes synchronously while idle and running', async () => { - class Cause { - readonly kind = 'user' - } - const adapter = new MockAdapter(['hang']) + it('retires turn cancellation before terminal publication and a blocked durability flush', async () => { + const adapter = new MockAdapter([textResponse('done')]) const ctx = await harness(adapter) - const agent = ctx.agentLoop.create(SessionId('invalid-cause'), { provider: 'mock', model: 'mock' }) - const controller = new AbortController() - const invalid: unknown[] = [ - 'user', - { kind: 'timeout' }, - { kind: 'user', detail: 'extra' }, - new Error('cancelled'), - controller.signal, - new Cause(), - ] - for (const value of invalid) expect(() => { agent.cancel(value as never) }).toThrow(TypeError) + const agent = ctx.agentLoop.create(SessionId('terminal-cancellation-authority'), { provider: 'mock', model: 'mock' }) + const flushStarted = Promise.withResolvers() + const releaseFlush = Promise.withResolvers() + let abortedDuringTurnEnd: boolean | undefined - send(agent, 'go') - await expect.poll(() => adapter.requests.length).toBe(1) - for (const value of invalid) expect(() => { agent.cancel(value as never) }).toThrow(TypeError) - expect(agent.status).toBe('running') - agent.cancel() - await waitForIdle(ctx, agent) + ctx.on('session/event', (session, event) => { + if (session !== agent.session || event.type !== 'turn/end') return + const signal = adapter.requests[0]?.signal + if (signal === undefined) throw new Error('model request omitted its turn signal') + agent.cancel({ kind: 'user' }) + abortedDuringTurnEnd = signal.aborted + }) + ctx.on('session/flush', async (session) => { + if (session !== agent.session) return + flushStarted.resolve(undefined) + await releaseFlush.promise + }) + + send(agent, 'finish before persistence drains') + await flushStarted.promise + const signal = adapter.requests[0]?.signal + if (signal === undefined) throw new Error('model request omitted its turn signal') + const idle = agent.whenIdle() + agent.cancel({ kind: 'user' }) + + expect(abortedDuringTurnEnd).toBe(false) + expect(signal.aborted).toBe(false) + expect(agent.session.events.findLast(event => event.type === 'turn/end')).toMatchObject({ + data: { reason: { kind: 'completed' } }, + }) + + releaseFlush.resolve(undefined) + await idle + expect(agent.status).toBe('idle') }) it('records disposed when lifecycle teardown races an already-requested cancel', async () => { diff --git a/packages/core/agent/README.md b/packages/core/agent/README.md index 3c5fa3111c..8ae1bc71e9 100644 --- a/packages/core/agent/README.md +++ b/packages/core/agent/README.md @@ -44,7 +44,7 @@ Agent *creation* is provided by the plugin implementing `AgentFactory` (`dsh-age The lifecycle edges have two important local caveats. `agent/created` runs after scoped setup and after both session and agent registry entries exist. Setup is trusted composition-only code; the immediately following non-vetoing `agent/session-start` notification is the first supported startup injection point. `agent/disposed` always means the exact agent has left the registry. AgentLoop emits it after its driver is quiescent, while ordered teardown may still be detaching the session and unwinding the scope; custom agents registered directly own any stronger driver-ordering contract themselves. -Most interception points are cooperative waterfalls returning seam-specific decisions. Turn-scoped asynchronous seams receive one explicit `AbortSignal`, with `signal` immediately before a waterfall's final `next`; listeners may cooperate but must not retain it as authority over another turn. `agent/pre-step` and `agent/post-step` are serial checkpoints around a step's durable work, while `agent/request-error` is the failed-model-request recovery waterfall: it receives the exact error, normalized failure facts, immutable prior-retried facts, and signal after the failed step closes; a retry opens a new numbered step. `agent/turn-stop` is the terminal serial fold: it runs after ordinary continuation and steering folding, and a returned stop remains in force through turn close and flush so later steering cannot create an extra step or turn. Ordinary queued prompts remain intact. The [explicit-cancellation decision](../../../.agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.md) owns signal lifetime; the [agent-scope runtime-design Agent Note](../../../.agents/notes/implemented/architecture/2026-07-12-agent-scope-runtime-design.md#three-execution-boundaries-are-deliberately-one-way) owns scoped dispatch and terminal settlement. +Most interception points are cooperative waterfalls returning seam-specific decisions. Turn-scoped asynchronous seams receive one explicit `AbortSignal`, with `signal` immediately before a waterfall's final `next`; listeners may cooperate but must not retain it as authority over another turn. The signal remains authoritative through terminal policy and is retired immediately before `turn/end` publication, so terminal observers and the following durability flush cannot cancel completed turn work. `agent/pre-step` and `agent/post-step` are serial checkpoints around a step's durable work, while `agent/request-error` is the failed-model-request recovery waterfall: it receives the exact error, normalized failure facts, immutable prior-retried facts, and signal after the failed step closes; a retry opens a new numbered step. `agent/turn-stop` is the terminal serial fold: it runs after ordinary continuation and steering folding, and a returned stop remains in force through turn close and flush so later steering cannot create an extra step or turn. Ordinary queued prompts remain intact. The [explicit-cancellation decision](../../../.agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.md) owns signal lifetime; the [agent-scope runtime-design Agent Note](../../../.agents/notes/implemented/architecture/2026-07-12-agent-scope-runtime-design.md#three-execution-boundaries-are-deliberately-one-way) owns scoped dispatch and terminal settlement. `PromptDecision.additionalContexts` is an array so every injected context keeps its own source and metadata. A `ContinuationDecision` reason is narrower: it becomes a `steering/message`, not a `context/message`, and therefore carries only content and source. @@ -57,7 +57,7 @@ The handle every plugin programs against: - `agent.send(content, options?)` — queue one independent FIFO item. If claimed, that item becomes the sole ordinary message in its turn; a claimed FIFO successor waits for that turn's checkpoint to settle. Broad cancellation, disposal, or a pre-start failure may instead drop it without a turn. Content and resolved source become one detached, deeply frozen lossless-JSON record before `agent/queued` and enqueue; invalid data throws synchronously, and caller or notification-listener in-place mutation cannot change the log or model input (`agent/prompt-submit` still rewrites by returning replacement content). The [one-send-one-turn Agent Note](../../../.agents/notes/implemented/simplification/2026-07-17-one-send-one-turn.md) owns the rationale. - `agent.steer(content, options?)` — submit steering while the agent is `running`. An open turn records it at the next steering checkpoint before a request or continuation decision; policy can still stop before another step. After turn close and its checkpoint, remaining steering becomes later queued input unless terminal turn policy, cancellation, or disposal discards it. The method uses the same synchronous snapshot-and-validation boundary as `send` and delegates to `send` when idle - `agent.inject(content, options?)` — accept detached in-session context without running the model; the next request sees its `context/message` with `content` rendered verbatim as a user-role message. `options.meta` persists opaque JSON state without rendering it. While a turn is open it joins that turn, deferring FIFO while the current tool batch executes and draining before turn close if execution is interrupted; while idle it is wrapped in a one-shot `injection` turn and durability checkpoint ([the turn-enclosure invariant](../../../.agents/notes/implemented/architecture/2026-06-15-turn-enclosure-invariant.md)). -- `agent.cancel(cause?)` — cancel ALL pending work: an omitted cause means `{ kind: 'user' }`; the exact `user | parent` object is validated, detached, and frozen before queues are cleared and the current turn's shared signal is aborted. Invalid causes throw synchronously, repeated active-turn cancellation is first-wins, and idle cancellation is a safe no-op that does not arm the next turn. ACP maps to `user`, while in-process parent propagation maps to `parent`. The cause is runtime-only; durable `turn/end` stays coarse `aborted`. +- `agent.cancel(cause?)` — cancel ALL pending work: an omitted cause means `{ kind: 'user' }`; TypeScript restricts callers to the `user | parent` union, and an active holder copies its discriminant into a detached frozen signal reason before aborting. The same-process typed seam adds no runtime validation or compatibility fallback for untyped callers. Repeated active-turn cancellation is first-wins, and idle cancellation is a safe no-op that does not arm the next turn. ACP maps to `user`, while in-process parent propagation maps to `parent`. The cause is runtime-only; durable `turn/end` stays coarse `aborted`. - `agent.whenIdle()` — resolve once the agent reaches quiescence after settling out of `running` (idle → immediately; disposed → awaits the loop exit). A non-owner's quiescence-observation hook: it observes the work settling WITHOUT tearing the agent down. Teardown is separate — a lifecycle owner stops and unregisters via `AgentHandle.dispose()`, which awaits the loop exit directly. - `agent.session`, `agent.status`, `agent.options`, `agent.id` diff --git a/packages/core/agent/src/cancellation.ts b/packages/core/agent/src/cancellation.ts index 75a099f1c9..708009b456 100644 --- a/packages/core/agent/src/cancellation.ts +++ b/packages/core/agent/src/cancellation.ts @@ -1,35 +1,6 @@ -/** Public normalization helpers for explicit turn cancellation. @module @deepseek-ai/dsh-agent/cancellation */ +/** Runtime reason inspection for explicit turn cancellation. @module @deepseek-ai/dsh-agent/cancellation */ -import type { AgentCancelCause, AgentInterruptReason } from './types.ts' - -/** - * Validate and detach a caller-supplied Agent cancellation cause. - * @param value - the candidate cancellation cause. - * @returns a fresh frozen cause suitable for the current turn signal. - * @throws {TypeError} when the value is not an exact supported cause. - */ -export function normalizeAgentCancelCause(value: unknown): AgentCancelCause { - if (typeof value !== 'object' || value === null || Array.isArray(value)) { - throw new TypeError('agent cancel cause must be an exact plain object with kind "user" or "parent"') - } - const prototype = Object.getPrototypeOf(value) as unknown - if (prototype !== Object.prototype && prototype !== null) { - throw new TypeError('agent cancel cause must be an exact plain object with kind "user" or "parent"') - } - const keys = Reflect.ownKeys(value) - if (keys.length !== 1 || keys[0] !== 'kind') { - throw new TypeError('agent cancel cause must contain exactly one field: kind') - } - const kind = (value as { readonly kind?: unknown }).kind - switch (kind) { - case 'user': - return Object.freeze({ kind: 'user' }) - case 'parent': - return Object.freeze({ kind: 'parent' }) - default: - throw new TypeError(`unsupported agent cancel cause kind: ${String(kind)}`) - } -} +import type { AgentInterruptReason } from './types.ts' /** * Read a supported agent interruption from an explicitly supplied signal. @@ -41,19 +12,19 @@ export function normalizeAgentCancelCause(value: unknown): AgentCancelCause { export function agentInterruptReasonOf(signal: AbortSignal): AgentInterruptReason | undefined { if (!signal.aborted) return undefined const reason: unknown = signal.reason - if (typeof reason === 'object' && reason !== null && !Array.isArray(reason)) { - const prototype = Object.getPrototypeOf(reason) as unknown - const keys = Reflect.ownKeys(reason) - if ((prototype === Object.prototype || prototype === null) - && keys.length === 1 && keys[0] === 'kind' - && (reason as { readonly kind?: unknown }).kind === 'disposed') { + if (typeof reason !== 'object' || reason === null || Array.isArray(reason)) return undefined + const prototype = Object.getPrototypeOf(reason) as unknown + const keys = Reflect.ownKeys(reason) + if ((prototype !== Object.prototype && prototype !== null) + || keys.length !== 1 || keys[0] !== 'kind') return undefined + switch ((reason as { readonly kind?: unknown }).kind) { + case 'user': + return Object.freeze({ kind: 'user' }) + case 'parent': + return Object.freeze({ kind: 'parent' }) + case 'disposed': return Object.freeze({ kind: 'disposed' }) - } - } - try { - return normalizeAgentCancelCause(reason) - } catch (error: unknown) { - if (error instanceof TypeError) return undefined - throw error + default: + return undefined } } diff --git a/packages/core/agent/src/index.ts b/packages/core/agent/src/index.ts index 506e630f82..2f5b525525 100644 --- a/packages/core/agent/src/index.ts +++ b/packages/core/agent/src/index.ts @@ -15,7 +15,7 @@ import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session' import type { Agent, AgentOptions } from './types.ts' export * from './types.ts' -export { agentInterruptReasonOf, normalizeAgentCancelCause } from './cancellation.ts' +export { agentInterruptReasonOf } from './cancellation.ts' export { agentEvents, assembleContextFor } from './dispatch.ts' export type { AgentEventDispatch, AgentSubjectEvent } from './dispatch.ts' diff --git a/packages/core/agent/src/types.ts b/packages/core/agent/src/types.ts index e1258af3ac..15e3316a33 100644 --- a/packages/core/agent/src/types.ts +++ b/packages/core/agent/src/types.ts @@ -132,8 +132,8 @@ export interface Agent { * Clear all queued and steering work, including items waiting to start, and * abort the active turn. The first cause wins for that turn, and `whenIdle()` * resolves after cancellation reaches quiescence. Omission means - * `{ kind: 'user' }`; invalid causes throw synchronously even while idle. - * Idle cancellation is a no-op after validation and does not arm a later cancel. + * `{ kind: 'user' }`. Idle cancellation is a no-op and does not arm a later + * cancel. The active turn snapshots and freezes the typed cause. * @param cause - the stable caller intent carried by the current turn signal. */ cancel(cause?: AgentCancelCause): void diff --git a/packages/core/agent/tests/agent.spec.ts b/packages/core/agent/tests/agent.spec.ts index b36c92c73f..5e3336b3d4 100644 --- a/packages/core/agent/tests/agent.spec.ts +++ b/packages/core/agent/tests/agent.spec.ts @@ -5,10 +5,9 @@ import { Session, SessionId } from '@deepseek-ai/dsh-session' import AgentRegistry, { agentEvents, agentInterruptReasonOf, - normalizeAgentCancelCause, } from '@deepseek-ai/dsh-agent' -import type { Agent, AgentFactory, ContinuationStop, CreateAgentOptions, ResumeAgentOptions } from '@deepseek-ai/dsh-agent' +import type { Agent, AgentCancelCause, AgentFactory, ContinuationStop, CreateAgentOptions, ResumeAgentOptions } from '@deepseek-ai/dsh-agent' function stubAgent(rawId: string): Agent { const id = SessionId(rawId) @@ -187,41 +186,21 @@ describe('agentEvents()', () => { }) describe('explicit cancellation helpers', () => { - it('normalizes exact causes into detached frozen values', () => { - const user = { kind: 'user' as const } - const parent = Object.assign(Object.create(null) as object, { kind: 'parent' }) - - const normalizedUser = normalizeAgentCancelCause(user) - const normalizedParent = normalizeAgentCancelCause(parent) - - expect(normalizedUser).toEqual({ kind: 'user' }) - expect(normalizedUser).not.toBe(user) - expect(Object.isFrozen(normalizedUser)).toBe(true) - expect(normalizedParent).toEqual({ kind: 'parent' }) - expect(Object.getPrototypeOf(normalizedParent)).toBe(Object.prototype) - expect(Object.isFrozen(normalizedParent)).toBe(true) - }) - - it.each([ - undefined, - null, - 'user', - [], - new Error('user'), - { kind: 'user', detail: true }, - Object.assign({ kind: 'user' }, { [Symbol('extra')]: true }), - { kind: 'timeout' }, - ])('rejects unsupported cancellation cause %#', (cause) => { - expect(() => normalizeAgentCancelCause(cause)).toThrow(TypeError) + it('exposes the closed typed cancellation cause at the Agent seam', () => { + expectTypeOf[0]>().toEqualTypeOf() }) it('reads only supported reasons from an explicit signal', () => { + const read = (reason: unknown) => { + const controller = new AbortController() + controller.abort(reason) + return agentInterruptReasonOf(controller.signal) + } const live = new AbortController() expect(agentInterruptReasonOf(live.signal)).toBeUndefined() - const user = new AbortController() - user.abort({ kind: 'user' }) - expect(agentInterruptReasonOf(user.signal)).toEqual({ kind: 'user' }) + expect(read({ kind: 'user' })).toEqual({ kind: 'user' }) + expect(read({ kind: 'parent' })).toEqual({ kind: 'parent' }) const disposed = new AbortController() disposed.abort(Object.assign(Object.create(null) as object, { kind: 'disposed' })) @@ -229,29 +208,13 @@ describe('explicit cancellation helpers', () => { expect(disposedReason).toEqual({ kind: 'disposed' }) expect(Object.isFrozen(disposedReason)).toBe(true) - const unsupported = new AbortController() - unsupported.abort(new Error('private runtime reason')) - expect(agentInterruptReasonOf(unsupported.signal)).toBeUndefined() - - const primitive = new AbortController() - primitive.abort('private runtime reason') - expect(agentInterruptReasonOf(primitive.signal)).toBeUndefined() - }) - - it('does not swallow non-validation failures while reading a cause', () => { - let reads = 0 - const reason = Object.defineProperty({}, 'kind', { - enumerable: true, - get() { - reads += 1 - if (reads === 1) return 'user' - throw new Error('kind getter failed') - }, - }) - const controller = new AbortController() - controller.abort(reason) - - expect(() => agentInterruptReasonOf(controller.signal)).toThrow('kind getter failed') + expect(read(null)).toBeUndefined() + expect(read([])).toBeUndefined() + expect(read('private runtime reason')).toBeUndefined() + expect(read(new Error('private runtime reason'))).toBeUndefined() + expect(read({ kind: 'user', detail: true })).toBeUndefined() + expect(read({ other: 'user' })).toBeUndefined() + expect(read({ kind: 'timeout' })).toBeUndefined() }) }) diff --git a/packages/core/session/README.md b/packages/core/session/README.md index df635f0085..f848909444 100644 --- a/packages/core/session/README.md +++ b/packages/core/session/README.md @@ -80,7 +80,7 @@ Every `SessionEvent` carries two optional top-level fields (structural metadata) ### Extension points - Persistence plugins: subscribe to `session/event` (write-behind) and drain on `session/flush` (awaited) and fiber dispose. A durable backend reads the log and reloads it into a live session; the metadata seam (`SessionHeader`, `session.header`) is what such a backend stores beside the log. -- Replay/fork: `create(id, { seed })` validates and freezes a contiguous current-format log and rebuilds its surface; request headers require provider/model and assistant messages require provider/model provenance. `fork(source, boundary?, childSessionId?)` selects a completed-turn prefix and records lineage. +- Replay/fork: `create(id, { seed })` validates and freezes a contiguous current-format log and rebuilds its surface; request headers require provider/model, assistant messages require provider/model provenance, and a coarse aborted outcome must contain only `{ kind: 'aborted' }` (legacy reason-bearing records are rejected). `fork(source, boundary?, childSessionId?)` selects a completed-turn prefix and records lineage. - Compaction: `dsh-compact-basic` appends a `user/message` replacement for summary checkpoints, while `dsh-compact-tool-result-prune` appends a content-only `tool/result` replacement. Tool-pairing boundary policy and its cache belong to the [`dsh-compact` seam](../../compact/compact/README.md), while this package owns ordered surface membership, replacement validation, and `replaceGeneration`. ## Model Experience diff --git a/packages/core/session/src/index.ts b/packages/core/session/src/index.ts index 9b2eb74a37..4a8963bb4c 100644 --- a/packages/core/session/src/index.ts +++ b/packages/core/session/src/index.ts @@ -137,6 +137,7 @@ function assertSessionEventEnvelope(value: Record, index: numbe throw new Error(`seed event at index ${index} has an invalid event envelope`) } assertCurrentLlmShape(event, index) + assertCurrentTurnEndShape(event, index) } /** Reject pre-provider request headers and assistant messages at the seed/load boundary. */ @@ -154,6 +155,22 @@ function assertCurrentLlmShape(event: Record, index: number): v } } +/** Reject legacy aborted outcomes that persisted caller-owned reason detail. */ +function assertCurrentTurnEndShape(event: Record, index: number): void { + if (event['type'] !== 'turn/end') return + const data = event['data'] + /* v8 ignore next -- this migration recognizes only the legacy object shape; format-wide payload validation is separate. */ + if (typeof data !== 'object' || data === null) return + const reason = (data as Record)['reason'] + /* v8 ignore next -- non-object reasons cannot carry the legacy aborted detail this migration removes. */ + if (typeof reason !== 'object' || reason === null || Array.isArray(reason)) return + const record = reason as Record + if (record['kind'] === 'aborted' + && (Object.keys(record).length !== 1 || !Object.hasOwn(record, 'kind'))) { + throw new Error(`seed turn/end at index ${index} uses unsupported reason-bearing aborted format`) + } +} + /** Whether an unknown value carries the current provider/model pair. */ function hasProviderModel(value: unknown): boolean { if (typeof value !== 'object' || value === null) return false diff --git a/packages/core/session/tests/session.spec.ts b/packages/core/session/tests/session.spec.ts index fa0afc20e1..0aef29b9a9 100644 --- a/packages/core/session/tests/session.spec.ts +++ b/packages/core/session/tests/session.spec.ts @@ -58,6 +58,22 @@ describe('Session', () => { expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'aborted' }) }) + it('rejects legacy reason-bearing aborted outcomes at the seed/load boundary', () => { + const legacy = [ + { + type: 'turn/start', seq: 0, time: 1, + data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } }, + }, + { + type: 'turn/end', seq: 1, time: 2, + data: { turn: 1, reason: { kind: 'aborted', reason: 'legacy cancellation detail' } }, + }, + ] as unknown as SessionEvent[] + + expect(() => new Session(SessionId('legacy-aborted'), legacy)) + .toThrow('seed turn/end at index 1 uses unsupported reason-bearing aborted format') + }) + it('renders context and steering messages as plain user content', () => { const session = new Session(SessionId('s2')) session.append('context/message', { diff --git a/packages/hooks/hook-protocol/README.md b/packages/hooks/hook-protocol/README.md index cae3f5e6b6..42a642caf0 100644 --- a/packages/hooks/hook-protocol/README.md +++ b/packages/hooks/hook-protocol/README.md @@ -18,7 +18,7 @@ Why a shared lib at all: Codex deliberately reimplements a *subset* of the Claud ## Primitives - **`matchesMatcher(matcher, query, mode)`** — match-all on absent/`''`/`'*'`; `claude` mode treats a pure `[A-Za-z0-9_|]+` pattern as a literal (pipe = exact-match alternation) and anything else as a regex; `codex` mode is always an unanchored regex. An invalid regex matches nothing (never throws). -- **`runHook(bash, hook, options, now)`** — serialize `options.payload` to the hook's stdin (with a trailing newline iff `options.trailingNewline`), merge `options.env` after the executor's credential scrub (the `dsh-bash` trusted-plugin surface), honor the hook's `timeoutSec` (else `options.defaultTimeoutMs` — the bridge owns the default, its config defaulting to the lib's `DEFAULT_HOOK_TIMEOUT_MS` 10-minute reference), and decode the result (threading `options.expectedEventName` to the codec). Never throws: an executor rejection (infra fault) becomes a `HookOutput` with `exitCode: undefined` (a non-blocking error). `now` is injected for testable durations. +- **`runHook(bash, hook, options, now)`** — require and forward the caller-owned `options.signal`, serialize `options.payload` to the hook's stdin (with a trailing newline iff `options.trailingNewline`), merge `options.env` after the executor's credential scrub (the `dsh-bash` trusted-plugin surface), honor the hook's `timeoutSec` (else `options.defaultTimeoutMs` — the bridge owns the default, its config defaulting to the lib's `DEFAULT_HOOK_TIMEOUT_MS` 10-minute reference), and decode the result (threading `options.expectedEventName` to the codec). Cancellation therefore reaches the executor's process-group kill and join boundary. Never throws: an executor rejection (infra fault) becomes a `HookOutput` with `exitCode: undefined` (a non-blocking error). `now` is injected for testable durations. - **`parseHookOutput(exitCode, stdout, stderr, expectedEventName?)`** decodes exit status and structured stdout. Exit 2 blocks with stderr; other failures are non-blocking. A matching hook-specific permission decision overrides the legacy top-level decision; mismatched or missing event discriminators suppress only event-specific fields. Top-level fields remain event-agnostic, and successful non-JSON output is left to the bridge. - **`mergeHookOutputs(outputs)`** — fold the results of every hook that matched one point: permission precedence **deny > ask > allow**, halt sticky on the first `continue:false`, block reasons joined with `\n\n`, `additionalContext`/`systemMessages` accumulated in order. - **`createDetachedRuns()`** — quiescence tracking for the emit-shaped points, which run detached (no seam awaits them). The bridge tracks each run chain — the hook run PLUS its continuation — and registers `drain()` as its effect disposer: drain fires the tracker's abort `signal` (so a still-running hook process is killed via `runHook`, not awaited out to its timeout), then resolves once every tracked chain has settled. `fiber.dispose()` resolving therefore means no detached hook work is left to fire into a disposed context ([defensive patterns](../../../docs/defensive-patterns.md): dispose must reach quiescence). diff --git a/packages/hooks/hook-protocol/src/runner.ts b/packages/hooks/hook-protocol/src/runner.ts index 1e7de698d0..802022085e 100644 --- a/packages/hooks/hook-protocol/src/runner.ts +++ b/packages/hooks/hook-protocol/src/runner.ts @@ -28,7 +28,7 @@ export interface RunHookOptions { /** Working directory for the hook (defaults to the executor's own default when omitted). */ cwd?: string /** Explicit owning-operation signal; firing it cancels the hook run. */ - signal?: AbortSignal + readonly signal: AbortSignal /** Whether to append a trailing newline to the stdin payload (CC yes, Codex no). */ trailingNewline: boolean /** @@ -78,9 +78,9 @@ export async function runHook( command: hook.command, timeoutMs, stdin, + signal: options.signal, ...options.cwd !== undefined ? { workdir: options.cwd } : {}, ...options.env !== undefined ? { env: options.env } : {}, - ...options.signal ? { signal: options.signal } : {}, } try { diff --git a/packages/hooks/hook-protocol/tests/runner.spec.ts b/packages/hooks/hook-protocol/tests/runner.spec.ts index c2990e10be..09e0e65275 100644 --- a/packages/hooks/hook-protocol/tests/runner.spec.ts +++ b/packages/hooks/hook-protocol/tests/runner.spec.ts @@ -1,6 +1,7 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, expectTypeOf, it } from 'vitest' import type { BashExecRequest, BashExecSpec, BashExecutor, BashRunResult } from '@deepseek-ai/dsh-bash' import { DEFAULT_HOOK_TIMEOUT_MS, runHook } from '@deepseek-ai/dsh-hook-protocol' +import type { RunHookOptions } from '@deepseek-ai/dsh-hook-protocol' /** * A minimal stand-in for the bits of {@link BashExecutor} that {@link runHook} @@ -51,12 +52,18 @@ function result(over: Partial = {}): BashRunResult { } const clock = () => { let t = 0; return () => (t += 5) } // +5ms per call → duration 5 +const testSignal = (): AbortSignal => new AbortController().signal describe('runHook — payload + env + stdin plumbing', () => { + it('requires an explicit caller-owned abort signal', () => { + expectTypeOf().toEqualTypeOf() + }) + it('serializes the payload to stdin (with trailing newline when requested)', async () => { const { bash, specs } = recordingBash(async () => result({ stdout: { text: '', truncated: false } })) await runHook(bash, { command: 'my-hook.sh' }, { payload: { hook_event_name: 'PreToolUse', tool_name: 'Bash' }, + signal: testSignal(), defaultTimeoutMs: 60000, trailingNewline: true, }, clock()) @@ -66,14 +73,14 @@ describe('runHook — payload + env + stdin plumbing', () => { it('omits the trailing newline when trailingNewline is false (Codex)', async () => { const { bash, specs } = recordingBash(async () => result()) - await runHook(bash, { command: 'h' }, { payload: { a: 1 }, defaultTimeoutMs: 1000, trailingNewline: false }, clock()) + await runHook(bash, { command: 'h' }, { payload: { a: 1 }, signal: testSignal(), defaultTimeoutMs: 1000, trailingNewline: false }, clock()) expect(specs[0]!.stdin).toBe('{"a":1}') }) it('threads env and cwd into the request', async () => { const { bash, specs } = recordingBash(async () => result()) await runHook(bash, { command: 'h' }, { - payload: {}, env: { CLAUDE_PROJECT_DIR: '/proj' }, cwd: '/work', + payload: {}, env: { CLAUDE_PROJECT_DIR: '/proj' }, cwd: '/work', signal: testSignal(), defaultTimeoutMs: 1000, trailingNewline: true, }, clock()) expect(specs[0]!.env).toEqual({ CLAUDE_PROJECT_DIR: '/proj' }) @@ -82,13 +89,13 @@ describe('runHook — payload + env + stdin plumbing', () => { it('a per-hook timeoutSec (seconds) overrides the default (ms)', async () => { const { bash, specs } = recordingBash(async () => result()) - await runHook(bash, { command: 'h', timeoutSec: 3 }, { payload: {}, defaultTimeoutMs: 60000, trailingNewline: true }, clock()) + await runHook(bash, { command: 'h', timeoutSec: 3 }, { payload: {}, signal: testSignal(), defaultTimeoutMs: 60000, trailingNewline: true }, clock()) expect(specs[0]!.timeoutMs).toBe(3000) }) it('falls back to the default timeout when the hook sets none', async () => { const { bash, specs } = recordingBash(async () => result()) - await runHook(bash, { command: 'h' }, { payload: {}, defaultTimeoutMs: 60000, trailingNewline: true }, clock()) + await runHook(bash, { command: 'h' }, { payload: {}, signal: testSignal(), defaultTimeoutMs: 60000, trailingNewline: true }, clock()) expect(specs[0]!.timeoutMs).toBe(60000) expect(DEFAULT_HOOK_TIMEOUT_MS).toBe(600_000) // the CC/Codex reference default (10 minutes) }) @@ -106,7 +113,7 @@ describe('runHook — outcome decoding + duration', () => { const { bash } = recordingBash(async () => result({ exitCode: 0, stdout: { text: JSON.stringify({ decision: 'block', reason: 'no' }), truncated: false }, })) - const { output, durationMs } = await runHook(bash, { command: 'h' }, { payload: {}, defaultTimeoutMs: 1000, trailingNewline: true }, clock()) + const { output, durationMs } = await runHook(bash, { command: 'h' }, { payload: {}, signal: testSignal(), defaultTimeoutMs: 1000, trailingNewline: true }, clock()) expect(output.decision).toBe('block') expect(output.reason).toBe('no') expect(durationMs).toBe(5) @@ -114,7 +121,7 @@ describe('runHook — outcome decoding + duration', () => { it('a signal death (exitCode null) decodes as undefined exit (non-blocking error)', async () => { const { bash } = recordingBash(async () => result({ exitCode: null, signal: 'SIGKILL', stderr: { text: 'killed', truncated: false } })) - const { output } = await runHook(bash, { command: 'h' }, { payload: {}, defaultTimeoutMs: 1000, trailingNewline: true }, clock()) + const { output } = await runHook(bash, { command: 'h' }, { payload: {}, signal: testSignal(), defaultTimeoutMs: 1000, trailingNewline: true }, clock()) expect(output.exitCode).toBeUndefined() expect(output.decision).toBeUndefined() expect(output.stderr).toBe('killed') @@ -122,7 +129,7 @@ describe('runHook — outcome decoding + duration', () => { it('an executor rejection (infra fault) becomes a non-blocking error, never throws', async () => { const { bash } = recordingBash(async () => { throw new Error('bad workdir: ENOENT') }) - const { output } = await runHook(bash, { command: 'h' }, { payload: {}, defaultTimeoutMs: 1000, trailingNewline: true }, clock()) + const { output } = await runHook(bash, { command: 'h' }, { payload: {}, signal: testSignal(), defaultTimeoutMs: 1000, trailingNewline: true }, clock()) expect(output.exitCode).toBeUndefined() expect(output.stderr).toBe('bad workdir: ENOENT') expect(output.decision).toBeUndefined() @@ -130,7 +137,7 @@ describe('runHook — outcome decoding + duration', () => { it('a non-Error rejection is stringified onto stderr', async () => { const { bash } = recordingBash(async () => { throw 'plain string fault' }) - const { output } = await runHook(bash, { command: 'h' }, { payload: {}, defaultTimeoutMs: 1000, trailingNewline: true }, clock()) + const { output } = await runHook(bash, { command: 'h' }, { payload: {}, signal: testSignal(), defaultTimeoutMs: 1000, trailingNewline: true }, clock()) expect(output.stderr).toBe('plain string fault') }) @@ -140,7 +147,7 @@ describe('runHook — outcome decoding + duration', () => { stdout: { text: JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny' } }), truncated: false }, })) const { output } = await runHook(bash, { command: 'h' }, { - payload: {}, defaultTimeoutMs: 1000, trailingNewline: true, expectedEventName: 'Stop', + payload: {}, signal: testSignal(), defaultTimeoutMs: 1000, trailingNewline: true, expectedEventName: 'Stop', }, clock()) // A PreToolUse block on a Stop hook is malformed → its decision is discarded. expect(output.hookEventName).toBe('PreToolUse') diff --git a/packages/hooks/hooks-codex/tests/bridge.spec.ts b/packages/hooks/hooks-codex/tests/bridge.spec.ts index 2cb4cb0bc5..684650104a 100644 --- a/packages/hooks/hooks-codex/tests/bridge.spec.ts +++ b/packages/hooks/hooks-codex/tests/bridge.spec.ts @@ -105,6 +105,32 @@ describe('hooks-codex bridge', () => { expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('keep going: address the goal') }) + it('turn cancellation aborts and reaps a running UserPromptSubmit hook before idle', async () => { + const dir = configDir() + const pidFile = join(dir, 'pid') + const marker = join(dir, 'started') + const slow = script(dir, 'slow-prompt.sh', `#!/usr/bin/env bash\necho $$ > "${pidFile}"\ntouch "${marker}"\nsleep 30\n`) + writeHooks(dir, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: slow }] }] }) + + const adapter = new MockAdapter([textResponse('must not run')]) + const ctx = await harness(dir, adapter) + const agent = ctx.agentLoop.create(SessionId('cancel-prompt-hook'), { provider: 'mock', model: 'mock' }) + agent.send([{ type: 'text', text: 'cancel the hook' }]) + await waitFor(() => existsSync(marker)) + const pid = Number(readFileSync(pidFile, 'utf8').trim()) + + const idle = agent.whenIdle() + agent.cancel({ kind: 'user' }) + await idle + + expect(() => process.kill(pid, 0)).toThrow() + expect(adapter.requests).toHaveLength(0) + expect(events(agent).findLast(event => event.type === 'turn/end')).toMatchObject({ + data: { reason: { kind: 'aborted' } }, + }) + expect(events(agent).some(event => event.type === 'hook/result' && event.data.point === 'UserPromptSubmit')).toBe(true) + }) + it('only the five bridge-supported Codex events are honored — a SubagentStop entry is ignored', async () => { const dir = configDir() const s = script(dir, 'x.sh', '#!/usr/bin/env bash\nexit 2\n')