diff --git a/.agents/notes/implemented/architecture/2026-06-18-agent-lifecycle-and-ownership-seams.md b/.agents/notes/implemented/architecture/2026-06-18-agent-lifecycle-and-ownership-seams.md index ef5bb5847a..3d84c8074b 100644 --- a/.agents/notes/implemented/architecture/2026-06-18-agent-lifecycle-and-ownership-seams.md +++ b/.agents/notes/implemented/architecture/2026-06-18-agent-lifecycle-and-ownership-seams.md @@ -10,9 +10,9 @@ Several ACP and tool-bash limitations were symptoms of the same missing seam: pl Three seams: the queue-aware cancel, the `AgentHandle` disposer, and the bash owner token. -### 1. Queue-aware `Agent.cancel(reason?)` +### 1. Queue-aware `Agent.cancel(cause?)` -A new `cancel()` verb on the `Agent` interface — the single public stop primitive. (It originally shipped alongside a narrower step-only `abort()`; that verb was later removed as unused, leaving `cancel()` the only public way to stop work.) It clears the inbox's queued + steering FIFOs, aborts the in-flight step if any, and drives a **turn-scoped cancellation marker** the driver loop checks at every turn-decision point — so a prompt that is queued-but-not-yet-started never runs, a cancel landing in the pre-step / continuation window drops the about-to-run turn (ending it `aborted`), and a later accepted prompt remains an independent queued turn. `whenIdle()` reaches post-cancel quiescence. ACP `session/cancel` maps to `cancel()`. The marker is armed ONLY when there is something to cancel, so an idle no-op cancel cannot strand the next prompt. +A new `cancel()` verb on the `Agent` interface — the single public stop primitive. (It originally shipped alongside a narrower step-only `abort()`; that verb was later removed as unused, leaving `cancel()` the only public way to stop work.) It clears the inbox's queued + steering FIFOs, aborts the active turn if any, and keeps a cause-less pre-run marker so a prompt cancelled before claim never runs while a later prompt remains independent. An effective call emits `agent/cancel-requested` with the typed `user | parent` cause before clearing or aborting; idle cancellation emits nothing and cannot strand the next prompt. `whenIdle()` reaches post-cancel quiescence, and ACP `session/cancel` maps to `user`. The [explicit turn-cancellation decision](2026-07-16-explicit-turn-cancellation.md) owns the current cause, signal-lifetime, and cooperative-settlement contract. ### 2. `AgentHandle` async disposer 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 new file mode 100644 index 0000000000..158a78acd8 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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: 7ac743221084e663294954bfd048ba7ef1114f60 +2026-07-16-explicit-turn-cancellation.zh.md: 3dca6339787ebef749c0d6a15609376ede994a97 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 new file mode 100644 index 0000000000..7ac7432210 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.md @@ -0,0 +1,55 @@ +# Agent Note: Explicit turn cancellation capability + +Status: implemented + +English | [中文](2026-07-16-explicit-turn-cancellation.zh.md) + +## Problem + +Cancellation is a control capability with a shorter lifetime than an Agent driver. A free-form string cannot distinguish callers exhaustively, and a step-local controller cannot interrupt prompt submission, prompt assembly, continuation, or terminal turn policy. Storing `Error`, `AbortSignal.reason`, or backend-private objects would also expose unstable runtime details to durable replay. + +The [initiating Agent scope decision](2026-07-15-agent-initiator-scope.md) intentionally carries only the exact Agent through AsyncLocalStorage. Adding turn, step, or signal state to that driver-lifetime boundary would make stale asynchronous descendants appear to retain authority over later turns. Cancellation therefore needs one turn owner and explicit propagation without creating another ambient context or public turn wrapper. + +## Decision + +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. Session seed/load rejects legacy aborted records with a reason or any other extra field, so replay cannot reintroduce caller-owned cancellation detail. The process-local `agent/cancel-requested` notification is not durable; a future audit requirement uses a separate durable 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, 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. An effective `cancel()` emits the observe-only `agent/cancel-requested` notification with its resolved typed cause before clearing queued and steering work or aborting the holder; notification failures cannot veto the stop, and an idle call emits nothing. Work synchronously queued by a notification observer is included in that clear, while work queued by a later signal abort observer belongs to the next turn. 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. 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. + +Agent disposal requests the runtime-only `{ kind: 'disposed' }` interruption on the active holder. If cancellation already won the controller reason, the reason cannot be rewritten, so terminal classification first checks lifecycle state: disposed wins, then a supported `user` or `parent` cause becomes the coarse aborted outcome, and unrelated exceptions retain the existing error path. ACP cancellation maps to `user`; in-process spawn and fork propagation map to `parent`. Remote ACP subagents retain their existing wire protocol. + +Cancellation remains cooperative. The loop checks interruption before and after awaited boundaries but does not use `Promise.race` to abandon an in-process listener, adapter, or tool Promise. Work that ignores the signal must settle before `whenIdle()`, handle disposal, and scope teardown report quiescence. + +## Verification + +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. + +## Alternatives considered + +**Store the signal in ALS.** ALS follows asynchronous descendants for the entire driver lifetime, while cancellation authority ends with one turn. A leaked callback could observe a stale signal or require mutable ambient state, so the initiator scope continues to carry only the Agent and control remains explicit. + +**Persist a free-form string reason.** Strings admit spelling drift, prevent exhaustive switching, and encourage consumers to parse presentation text. The runtime uses a closed discriminated union, while the terminal record needs only the stable aborted outcome. + +**Persist the typed caller cause in `turn/end`.** No production replay, UI, ACP, telemetry, or workflow consumer distinguishes `user` from `parent`. Copying the request source into the terminal result would conflate two facts and add Session-specific validation without a consumer; a future audit surface can record a separate cancellation-request event. + +**Define speculative `superseded`, `timeout`, and `shutdown` variants now.** No current Agent cancellation producer implements those semantics. `shutdown` is already lifecycle disposal, and timeout or supersession should enter the union only with an owning policy and unique terminal meaning. + +**Expose public turn or step context wrappers.** Existing positional seams already identify Agent, turn, and step. A wrapper would widen every API, duplicate ownership, and tempt callers to treat a captured object as durable authority. + +**Abandon uncooperative work after a grace period.** Returning idle while same-process work still runs breaks teardown and resource-ownership guarantees. Hard termination requires a worker or process isolation boundary and is outside this control seam. + +## Consequences + +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 new file mode 100644 index 0000000000..3dca633978 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.zh.md @@ -0,0 +1,55 @@ +# Agent Note:显式轮次取消能力 + +Status: implemented + +[English](2026-07-16-explicit-turn-cancellation.md) | 中文 + +## 问题 + +取消是一种生命周期短于 Agent(智能体)驱动器的控制能力。自由文本字符串无法穷尽地区分调用方,步骤级控制器也无法中断提示词提交、提示词组装、继续决策或轮次终止策略。持久化 `Error`、`AbortSignal.reason` 或后端私有对象还会向持久化回放暴露不稳定的运行时细节。 + +[发起 Agent 作用域决策](2026-07-15-agent-initiator-scope.md)有意让 AsyncLocalStorage 只携带同一个 Agent。若把轮次、步骤或 signal 状态加入这个与驱动器同生命周期的边界,陈旧的异步后代就会看似仍对后续轮次拥有权限。因此,取消需要一个轮次归属方并显式传播,且不创建另一套环境上下文或公开的轮次包装层。 + +## 决策 + +Agent 拥有仅用于运行时的 `AgentCancelCause` 联合类型 `{ kind: 'user' } | { kind: 'parent' }`;`agent.cancel()` 默认使用 `user`。TypeScript 在这份类型化同进程契约中强制执行该词汇,不提供运行时校验器、后备行为,也不为无类型调用方提供特殊兼容性契约。活跃的 `TurnCancellation` 会把类型化判别字段复制为一个全新且已冻结的 signal 原因;空闲状态下没有可修改的持有者,也不会让后续工作预先进入取消状态。 + +正在运行的轮次被中断后,以粗粒度的持久化结果 `{ kind: 'aborted' }` 结束。终态事件记录轮次发生了什么,运行时 signal 标识谁请求了取消;回放不会重复保存 `user` 或 `parent`。Session seed/load 会拒绝携带取消原因或任何其他额外字段的旧式中止记录,因此回放无法重新引入由调用方持有的取消细节。仅限进程内的 `agent/cancel-requested` 通知不会持久化;未来若有审计需求,应使用独立的持久化控制请求事件,让请求与最终结果保持为两项事实。持久化事件不包含调用栈、signal、错误对象、自由文本取消原因或后端私有细节。 + +AgentLoop 为每个待启动轮次私有地持有一个 `TurnCancellation`。它在通知 `agent/status = running` 前安装该持有者,使其中唯一的 `AbortController` 持续覆盖提示词处理、提示词组装、每个步骤、模型与工具执行、继续决策和 `agent/turn-stop`;随后在发布 `turn/end` 前立即清除所安装的那个持有者。因此,即使驱动器状态可能在持久化刷新结算前保持 `running`,终态事件观察者及其后的持久化刷新也无法取消已完成的轮次工作。所有参与的方法、事件和请求值都会收到同一个显式 signal;下一个轮次会收到全新的 signal。 + +对于轮次被认领前已取消的排队工作,驱动器只保留一个不携带取消原因的运行前标记。实际生效的 `cancel()` 会先发出仅供观察的 `agent/cancel-requested` 通知并携带最终确定的类型化取消原因,然后才清除排队工作和 steering(中途引导)工作或中止持有者;通知失败不能阻止此次停止,空闲状态下调用则不发出任何通知。通知观察者同步加入队列的工作也会被这次清除,而稍后由 signal 中止观察者加入队列的工作属于下一个轮次。若 `running` 监听器同步取消旧工作并发送替代提示词,驱动器会丢弃已中止的持有者,并为替代提示词创建全新的持有者。同一活跃持有者上的重复取消遵循首次请求优先,后续调用仍可清除新入队的待处理工作。 + +显式事件签名保留位置参数形式,并把 `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 传递。 + +Agent dispose(资源释放)会在活跃持有者上请求仅用于运行时的 `{ kind: 'disposed' }` 中断。若取消已经先占用控制器的中断原因,该原因便无法改写,因此终态分类会先检查生命周期状态:资源释放结果优先,之后受支持的 `user` 或 `parent` 取消原因形成粗粒度的中止结果,其他异常保留现有错误路径。ACP(Agent Client Protocol)取消映射为 `user`;进程内 spawn 和 fork 的传播映射为 `parent`。远程 ACP subagent 保持现有协议。 + +取消仍然是协作式的。AgentLoop 会在异步等待边界前后检查中断,但不会用 `Promise.race` 放弃进程内监听器、适配器或工具 Promise。忽略 signal 的工作必须真正结算,`whenIdle()`、句柄 dispose 和作用域清理才会报告静止状态。 + +## 验证 + +契约测试验证类型化调用方联合类型、冻结且与调用方分离、默认行为与首次请求优先行为、粗粒度的会话 JSON 往返与旧式记录拒绝、ACP `user`、进程内 subagent `parent` 以及 dispose 优先级。AgentLoop 测试让协作式监听器在提示词提交、系统提示词组装、会话前缀、步骤前处理、请求、模型流、步骤结果、工具执行、继续决策和终止停止处等待 signal;并断言同一轮次使用一个 signal,不同轮次使用全新的 signal,终态发布期间和持久化刷新受阻期间不存在取消权限。真实钩子桥接器测试会在报告空闲状态前取消并回收受阻的提示词钩子。 + +发起方作用域测试断言所有钩子仍观察到同一个 Agent 且没有环境中的轮次 signal,并发 Agent 保持独立的身份与 signal,嵌套子驱动只遮蔽身份。竞态测试覆盖空闲状态取消、运行前取消、从 `running` 监听器提交替代提示词、重复取消以及取消与 dispose 竞争下的静止状态。 + +## 考虑过的替代方案 + +**把 signal 存入 ALS。** ALS 会在整个驱动器生命周期内跟随异步后代,而取消权限在一个轮次结束时就已终止。泄漏的回调可能观察到陈旧 signal,或者迫使实现使用可变的环境状态,因此发起方作用域继续只携带 Agent,控制能力继续显式传递。 + +**持久化自由文本原因。** 字符串允许拼写漂移、阻碍穷尽分支判断,还会鼓励消费方解析展示文本。运行时使用封闭的可辨识联合类型,终态记录只需要稳定的中止结果。 + +**在 `turn/end` 中持久化类型化调用方取消原因。** 当前没有任何生产环境中的回放、UI、ACP、遥测或工作流消费方区分 `user` 与 `parent`。把请求来源复制到终态结果会混淆两项事实,还会在没有消费方的情况下引入会话特有校验;未来的审计接口可以记录独立的取消请求事件。 + +**现在就定义推测性的 `superseded`、`timeout` 和 `shutdown` 变体。** 当前没有 Agent 取消生产方实现这些语义。`shutdown` 已经属于生命周期 dispose;超时或替代只有在拥有明确归属策略和唯一终态含义时才应进入联合类型。 + +**公开轮次或步骤上下文包装类型。** 现有位置参数 seam 已经标识 Agent、轮次和步骤。包装类型会加宽所有 API、重复归属,并诱导调用方把捕获的对象当成持久权限。 + +**在宽限期后放弃不协作的工作。** 同进程工作仍在运行时就报告空闲状态,会破坏资源清理与资源归属保证。硬终止需要 worker 或进程隔离边界,不属于该控制 seam。 + +## 后果 + +取消拥有一个运行时归属方、每个活跃轮次一个 signal,以及一套类型化的运行时调用方词汇。会话保留其消费方实际使用的粗粒度 `aborted` 结果,拒绝携带原因的旧式形式,并与运行时对象保持隔离。协作式取消覆盖每个异步轮次 seam,包括第一个步骤之前和最后一个步骤之后的工作,而终态发布和持久化仍在其权限范围之外。 + +显式 signal 会给多个公开事件增加参数,并要求插件有意识地转发取消。这是有意设计:权限在调用边界可见,生命周期与轮次匹配,陈旧的环境异步后代无法获得控制能力。不协作的进程内工作可能延迟取消,但所报告的静止状态仍然真实。 diff --git a/.agents/notes/implemented/feature/2026-06-30-interception-seams.md b/.agents/notes/implemented/feature/2026-06-30-interception-seams.md index b00b96c406..08edfae386 100644 --- a/.agents/notes/implemented/feature/2026-06-30-interception-seams.md +++ b/.agents/notes/implemented/feature/2026-06-30-interception-seams.md @@ -14,7 +14,7 @@ The canonical surface separates transformable policy, around-dispatch control, a **Agent events** (`dsh-agent`): - `agent/session-start(agent, source)` — emit, once before turn 1, carrying a `SessionStartSource` (`startup` for a fresh/forked create, `resume` for a reloaded persisted session; `clear`/`compact` reserved). A pure notification — it CANNOT block startup (a deliberate gap: a bridge logs/injects, it does not gate startup). A listener seeds context via `agent.inject()`. -- `agent/prompt-submit(agent, content, source, next) → PromptDecision` — waterfall, fired for the turn's single claimed queued message before the `user/message` append. `allow` optionally rewrites the prompt `content` or attaches separately sourced `additionalContexts[]`; `block` appends a durable `prompt/blocked` and rejects that zero-step turn. +- `agent/prompt-submit(agent, content, source, signal, next) → PromptDecision` — waterfall, fired for the turn's single claimed queued message before the `user/message` append. The explicit turn signal is placed before the final `next`; `allow` optionally rewrites the prompt `content` or attaches separately sourced `additionalContexts[]`, while `block` appends a durable `prompt/blocked` and rejects that zero-step turn. **`agent/turn-continuation`** receives and returns a `ContinuationDecision`. A `{action:'continue', reason?}` may carry model-facing content and source recorded as next-step steering in the same turn — the typed twin of the `/goal` step-end-steer pattern. It is not a `context/message`, so its type does not offer durable context metadata. diff --git a/.agents/notes/implemented/simplification/2026-06-20-public-agent-stop-surface.md b/.agents/notes/implemented/simplification/2026-06-20-public-agent-stop-surface.md index c85f644853..824efc804c 100644 --- a/.agents/notes/implemented/simplification/2026-06-20-public-agent-stop-surface.md +++ b/.agents/notes/implemented/simplification/2026-06-20-public-agent-stop-surface.md @@ -6,19 +6,19 @@ Status: implemented ## Problem -The public `Agent` handle exposed two overlapping ways to stop in-flight work: `abort(reason?)` and `cancel(reason?)`. `abort()` killed only the in-flight step and left queued work alone; `cancel()` clears queued and steering work, aborts the running step, and handles the pre-step race. In production, ACP uses `cancel()` for `session/cancel`, while lifecycle owners tear down agents through `AgentHandle.dispose()`. No production caller needed bare `abort()`. +The public `Agent` handle exposed two overlapping ways to stop in-flight work: step-only `abort()` and queue-aware `cancel()`. The former preserved queued input while the latter clears queued and steering work and aborts the active turn. In production, ACP uses `cancel()` for `session/cancel`, while lifecycle owners tear down agents through `AgentHandle.dispose()`. No production caller needs a bare step-only abort. -The `abort()`/`cancel()` distinction is real — `abort()` preserves queued prompts and steering while `cancel()` drops them — but no shipping code called the public `abort()` verb. The loop's own stop paths (`cancel()` and disposal) abort the current `AbortController` directly rather than routing through `Agent.abort()`. Most tests that called `abort()` interrupt an empty queue and switch to `cancel(reason)`; the steering re-delivery test that deliberately depends on queue preservation drives the in-flight `AbortController` directly, because `cancel()` would drop the queued steering it is trying to prove survives a step abort. The no-argument `abort()` default reason (`'aborted'`) is deleted with the verb rather than preserved by accident; `cancel()` keeps its own `'cancelled'` default. +The behavioral distinction is real, but no shipping code needs the narrower operation. AgentLoop instead owns one private cancellation holder for the whole turn. `cancel(cause?)` carries a typed `user` or `parent` cause, defaults to `user`, and drops pending input; disposal remains a separate lifecycle interruption. The complete ownership and propagation contract lives in the [explicit turn cancellation RFC](../architecture/2026-07-16-explicit-turn-cancellation.md). The extra surface area made the loop carry a public verb that is mostly a teardown internal: `abort()` had to be documented as distinct from queue-aware cancellation even though a UI cancellation almost always wants the broader operation. ## Decision -`cancel()` is the only public *stop* primitive on `Agent`. Lifecycle owners use `AgentHandle.dispose()` to stop and unregister an agent; non-owners use `cancel()` to abandon current and queued work. The implementation keeps a private abort controller, but it is not part of the plugin-facing `Agent` contract. +`cancel()` is the only public *stop* primitive on `Agent`. Lifecycle owners use `AgentHandle.dispose()` to stop and unregister an agent; non-owners use `cancel()` to abandon current and queued work. The implementation keeps a private turn cancellation holder, but it is not part of the plugin-facing `Agent` contract. `whenIdle()` is **retained** as the public quiescence-observation primitive (resolve once the agent settles out of `running`, resolve immediately when already idle, await the loop exit when disposed). It is not a stop verb; it is how a non-owner observes the stop *completing* without disposing the agent. Its live consumers are ACP and agent tests that await settlement through this public seam (`packages/ui/acp/tests`, `packages/core/agent-loop/tests`); the production ACP bridge owns its agents and tears them down through `AgentHandle.dispose()`, so `packages/ui/acp/src` itself has no `whenIdle()` call. -Public `abort()` is deleted, with the tests that exercised it as standalone API and the docs that described step-only abort as an embedding feature. Empty-queue abort tests migrated to `cancel(reason)` where they still prove cancellation behavior; tests whose subject is the loop's internal `AbortController` drive that controller directly via an in-package typed cast to the private field; tests that only pinned the removed no-arg `abort()` default went with the method. The disposer remains async and still waits for the loop to stop. +Public `abort()` is absent, and the disposer remains async and waits for the loop to stop. Tests exercise cancellation through the public typed cause and explicit signal seams rather than reaching into the holder. ## Alternatives considered diff --git a/docs/architecture.md b/docs/architecture.md index fdc1c49f2b..88c0803e09 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -116,9 +116,9 @@ Pruning precedes summaries; overflow retries require durable progress. Bounded t ### Failure Boundaries -The turn is the containment boundary. Adapter failures close the step, entering `agent/request-error` with the exact `Error`, `LlmFailure`, and retry history. Retry opens a numbered step; success clears history; exhaustion stores the failure on `turn/end`. Failed chunks commit no message or tool. +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. -Other failures use `agent/error`. Cancellation and disposal beat recovery; undispatched model tool calls receive synthetic `tool/call` and `ABORTED_BEFORE_DISPATCH` result pairs before `turn/end`. Effective `cancel()` emits `agent/cancel-requested` before queue clearing or abort; observers cannot veto it, and idle calls emit nothing. Disposal awaits quiescence before unregistering. +Other failures use `agent/error`. Cancellation and disposal beat recovery; undispatched model tool calls receive synthetic `tool/call` and `ABORTED_BEFORE_DISPATCH` result pairs. One signal spans the turn until retirement before `turn/end`. Effective `cancel()` emits its typed `user | parent` cause before clearing queues and aborting; observers cannot veto it, idle calls emit nothing, and durability records only `aborted`. Disposal awaits quiescence 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. @@ -128,7 +128,7 @@ Every session event is turn-enclosed. Reloading preserves an interrupted tail an ### Agent Scope -Every live agent owns a scoped `agent.ctx`. Its registrations shadow globals, receive only that agent's dispatches, and unwind with it; async effects such as background-task cleanup are awaited. `CreateAgentOptions.setup(agentCtx)` composes the scope before publication. Typed resolvers derive carrier checks from merged `Events` signatures and `scopeTarget` ([semantic gates](../.agents/notes/implemented/process/2026-07-14-typescript-program-backed-semantic-gates.md)). See [agent scope](../.agents/notes/implemented/architecture/2026-07-08-agent-scope-contexts.md) and [subagent composition controls](../.agents/notes/implemented/feature/2026-07-12-subagent-persona-tool-filter-and-depth.md). `AgentLoop` runs drivers inside `ctx.agents.withInitiator()`; private orchestration derives `agent.session`; other identities stay explicit ([decision](../.agents/notes/implemented/architecture/2026-07-15-agent-initiator-scope.md)). +Every live agent owns a scoped `agent.ctx`. Its registrations shadow globals, receive only that agent's dispatches, and unwind with it; async effects such as background-task cleanup are awaited. `CreateAgentOptions.setup(agentCtx)` composes the scope before publication. Typed resolvers derive carrier checks from merged `Events` signatures and `scopeTarget` ([semantic gates](../.agents/notes/implemented/process/2026-07-14-typescript-program-backed-semantic-gates.md)). See [agent scope](../.agents/notes/implemented/architecture/2026-07-08-agent-scope-contexts.md) and [subagent composition controls](../.agents/notes/implemented/feature/2026-07-12-subagent-persona-tool-filter-and-depth.md). `AgentLoop` runs drivers inside `ctx.agents.withInitiator()`; private orchestration derives `agent.session`; turn, step, signal, cwd, and authority stay explicit ([decision](../.agents/notes/implemented/architecture/2026-07-15-agent-initiator-scope.md)). ## State diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 1a03014389..fed81b1f96 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1019,7 +1019,7 @@ export interface Config { } ``` -Source: [`packages/core/system-prompt/src/index.ts:143`](../packages/core/system-prompt/src/index.ts) +Source: [`packages/core/system-prompt/src/index.ts:147`](../packages/core/system-prompt/src/index.ts) ## `@deepseek-ai/dsh-time-context` diff --git a/docs/cordis-catalog/events.md b/docs/cordis-catalog/events.md index 3cbe2e3d1c..543a8cc885 100644 --- a/docs/cordis-catalog/events.md +++ b/docs/cordis-catalog/events.md @@ -15,24 +15,24 @@ Dispatch modes: **emit** (fire-and-forget), **waterfall** (each listener gets `n ### `agent/cancel-requested` — emit -Effective broad cancellation was requested, before queued/steering work is cleared or the active step is aborted. This observe-only notification cannot veto cancellation; listener failures are contained. +Effective broad cancellation was requested, before queued/steering work is cleared or the active turn is aborted. This observe-only notification cannot veto cancellation; listener failures are contained. ```ts cordis-catalog /** * Effective broad cancellation was requested, before queued/steering work - * is cleared or the active step is aborted. This observe-only notification + * is cleared or the active turn is aborted. This observe-only notification * cannot veto cancellation; listener failures are contained. * @param agent - the agent whose current work is being cancelled. - * @param reason - resolved cancellation reason, including the default. + * @param cause - resolved typed cancellation cause, including the default. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. * @mode emit */ -'agent/cancel-requested'(this: Scoped, agent: Agent, reason: string): void +'agent/cancel-requested'(this: Scoped, agent: Agent, cause: AgentCancelCause): void ``` -Types: [Agent](../core-data-structures/core.md) · [Scoped](../core-data-structures/scope.md) +Types: [Agent](../core-data-structures/core.md) · [AgentCancelCause](../core-data-structures/core.md) · [Scoped](../core-data-structures/scope.md) -Source: [`packages/core/agent/src/types.ts:191`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:201`](../../packages/core/agent/src/types.ts) ### `agent/created` — emit @@ -54,7 +54,7 @@ A fully configured agent and live session were published. Setup is composition-o Types: [Agent](../core-data-structures/core.md) · [Scoped](../core-data-structures/scope.md) -Source: [`packages/core/agent/src/types.ts:153`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:163`](../../packages/core/agent/src/types.ts) ### `agent/disposed` — emit @@ -74,7 +74,7 @@ An agent left the registry; AgentLoop emits this after driver quiescence but bef Types: [Agent](../core-data-structures/core.md) · [Scoped](../core-data-structures/scope.md) -Source: [`packages/core/agent/src/types.ts:162`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:172`](../../packages/core/agent/src/types.ts) ### `agent/error` — emit @@ -96,7 +96,7 @@ A step or turn errored. The loop reports a failure here (plus the logger) even w Types: [Agent](../core-data-structures/core.md) · [Scoped](../core-data-structures/scope.md) -Source: [`packages/core/agent/src/types.ts:328`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:346`](../../packages/core/agent/src/types.ts) ### `agent/post-step` — serial @@ -119,7 +119,7 @@ Awaited serial checkpoint after the response, real or synthetic tool results, in Types: [Agent](../core-data-structures/core.md) · [Scoped](../core-data-structures/scope.md) -Source: [`packages/core/agent/src/types.ts:280`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:296`](../../packages/core/agent/src/types.ts) ### `agent/pre-step` — serial @@ -142,28 +142,31 @@ Awaited serial checkpoint before `step/start`; appends land outside the pending Types: [Agent](../core-data-structures/core.md) · [Scoped](../core-data-structures/scope.md) -Source: [`packages/core/agent/src/types.ts:220`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:230`](../../packages/core/agent/src/types.ts) ### `agent/prompt-submit` — waterfall -Allow, rewrite, or block one claimed prompt before it becomes a user message. Call `next()` for the unchanged default. +Allow, rewrite, or block one claimed prompt before it becomes a user message. Call `next()` for the unchanged default. The signal controls only this turn; listeners may cooperate with it but must not retain it to control another turn. ```ts cordis-catalog /** * Allow, rewrite, or block one claimed prompt before it becomes a user - * message. Call `next()` for the unchanged default. + * message. Call `next()` for the unchanged default. The signal controls only + * this turn; listeners may cooperate with it but must not retain it to + * control another turn. * @param agent - the agent whose turn claimed the message. * @param content - the claimed message's blocks, as queued. * @param source - the message's resolved source. + * @param signal - the current turn's explicit abort signal. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. * @mode waterfall */ -'agent/prompt-submit'(this: Scoped, agent: Agent, content: ContentBlock[], source: MessageSource, next: () => Promise): Promise +'agent/prompt-submit'(this: Scoped, agent: Agent, content: ContentBlock[], source: MessageSource, signal: AbortSignal, next: () => Promise): Promise ``` Types: [Agent](../core-data-structures/core.md) · [ContentBlock](../core-data-structures/core.md) · [MessageSource](../core-data-structures/core.md) · [PromptDecision](../core-data-structures/core.md) · [Scoped](../core-data-structures/scope.md) -Source: [`packages/core/agent/src/types.ts:230`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:243`](../../packages/core/agent/src/types.ts) ### `agent/queued` — emit @@ -184,7 +187,7 @@ Detached, frozen content entered the agent's inbox. Source defaults have already Types: [Agent](../core-data-structures/core.md) · [ContentBlock](../core-data-structures/core.md) · [MessageSource](../core-data-structures/core.md) · [Scoped](../core-data-structures/scope.md) -Source: [`packages/core/agent/src/types.ts:181`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:191`](../../packages/core/agent/src/types.ts) ### `agent/request` — waterfall @@ -199,15 +202,17 @@ Replace the frozen call configuration. Model-visible content must use logged cha * @param turn - the open turn number. * @param step - the step whose request this is. * @param config - the config the loop would use (frozen); return a replacement to switch. + * @param signal - the current turn's explicit abort signal; ambient + * initiator identity does not imply liveness or cancellation authority. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. * @mode waterfall */ -'agent/request'(this: Scoped, agent: Agent, turn: number, step: number, config: LlmCallConfig, next: () => Promise): Promise +'agent/request'(this: Scoped, agent: Agent, turn: number, step: number, config: LlmCallConfig, signal: AbortSignal, next: () => Promise): Promise ``` Types: [Agent](../core-data-structures/core.md) · [LlmCallConfig](../core-data-structures/core.md) · [Scoped](../core-data-structures/scope.md) -Source: [`packages/core/agent/src/types.ts:242`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:257`](../../packages/core/agent/src/types.ts) ### `agent/request-error` — waterfall @@ -233,7 +238,7 @@ Recover a model-request failure after its failed step has closed. `retry` opens Types: [Agent](../core-data-structures/core.md) · [LlmFailure](../core-data-structures/llm-streaming.md) · [RequestError](../core-data-structures/core.md) · [RequestErrorDecision](../core-data-structures/core.md) · [Scoped](../core-data-structures/scope.md) -Source: [`packages/core/agent/src/types.ts:295`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:311`](../../packages/core/agent/src/types.ts) ### `agent/session-prefix` — waterfall @@ -251,7 +256,7 @@ Compose request-only messages placed before derived history. The frozen result i * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. * @param agent - the agent whose session prefix is being composed. * @param prefix - the frozen seed; return an extended replacement. - * @param signal - aborts composition when the step is torn down. + * @param signal - the current turn's explicit abort signal. * @mode waterfall */ 'agent/session-prefix'(this: Scoped, agent: Agent, prefix: Message[], signal: AbortSignal, next: () => Promise): Promise @@ -259,7 +264,7 @@ Compose request-only messages placed before derived history. The frozen result i Types: [Agent](../core-data-structures/core.md) · [Message](../core-data-structures/core.md) · [Scoped](../core-data-structures/scope.md) -Source: [`packages/core/agent/src/types.ts:257`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:272`](../../packages/core/agent/src/types.ts) ### `agent/session-start` — emit @@ -281,7 +286,7 @@ The session lifecycle began, once before the first turn. Use `agent.inject()` to Types: [Agent](../core-data-structures/core.md) · [Scoped](../core-data-structures/scope.md) · [SessionStartSource](../core-data-structures/core.md) -Source: [`packages/core/agent/src/types.ts:204`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:214`](../../packages/core/agent/src/types.ts) ### `agent/status` — emit @@ -301,7 +306,7 @@ Agent status changed (`idle` ⇄ `running`, or → `disposed`). `send()` does no Types: [Agent](../core-data-structures/core.md) · [AgentStatus](../core-data-structures/core.md) · [Scoped](../core-data-structures/scope.md) -Source: [`packages/core/agent/src/types.ts:171`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:181`](../../packages/core/agent/src/types.ts) ### `agent/step-result` — waterfall @@ -315,15 +320,16 @@ Waterfall: post-process the assembled assistant Message before tool dispatch (va * @param turn - the open turn number. * @param step - the step that produced the message. * @param message - the assistant message as assembled from the stream. + * @param signal - the current turn's explicit abort signal. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. * @mode waterfall */ -'agent/step-result'(this: Scoped, agent: Agent, turn: number, step: number, message: Message, next: () => Promise): Promise +'agent/step-result'(this: Scoped, agent: Agent, turn: number, step: number, message: Message, signal: AbortSignal, next: () => Promise): Promise ``` Types: [Agent](../core-data-structures/core.md) · [Message](../core-data-structures/core.md) · [Scoped](../core-data-structures/scope.md) -Source: [`packages/core/agent/src/types.ts:268`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:284`](../../packages/core/agent/src/types.ts) ### `agent/turn-continuation` — waterfall @@ -336,15 +342,16 @@ Override whether the turn continues. The default continues after tool calls or s * @param agent - the agent deciding whether to run another step. * @param turn - the turn being continued or stopped. * @param defaultDecision - what the loop would do absent an override. + * @param signal - the current turn's explicit abort signal. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. * @mode waterfall */ -'agent/turn-continuation'(this: Scoped, agent: Agent, turn: number, defaultDecision: ContinuationDecision, next: () => Promise): Promise +'agent/turn-continuation'(this: Scoped, agent: Agent, turn: number, defaultDecision: ContinuationDecision, signal: AbortSignal, next: () => Promise): Promise ``` Types: [Agent](../core-data-structures/core.md) · [ContinuationDecision](../core-data-structures/core.md) · [Scoped](../core-data-structures/scope.md) -Source: [`packages/core/agent/src/types.ts:305`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:322`](../../packages/core/agent/src/types.ts) ### `agent/turn-stop` — serial @@ -357,15 +364,16 @@ Monotonic terminal-stop checkpoint after continuation and steering are folded; a * steering queued in that window is discarded, while ordinary sends survive. * @param agent - the agent whose composed continuation outcome may be stopped. * @param turn - the turn at its terminal-stop checkpoint. + * @param signal - the current turn's explicit abort signal. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. * @mode serial */ -'agent/turn-stop'(this: Scoped, agent: Agent, turn: number): ContinuationStop | undefined +'agent/turn-stop'(this: Scoped, agent: Agent, turn: number, signal: AbortSignal): Promise | ContinuationStop | undefined ``` Types: [Agent](../core-data-structures/core.md) · [ContinuationStop](../core-data-structures/core.md) · [Scoped](../core-data-structures/scope.md) -Source: [`packages/core/agent/src/types.ts:315`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:333`](../../packages/core/agent/src/types.ts) ## `agent-loop/*` @@ -708,13 +716,15 @@ Source: [`packages/subagent/subagent/src/index.ts:130`](../../packages/subagent/ ### `system-prompt/assemble` — waterfall -Expert waterfall over the assembled sections, tools, and variables. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): scoped listeners receive only that scope's assemblies. The returned value is authoritative. +Expert waterfall over the assembled sections, tools, and variables. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): scoped listeners receive only that scope's assemblies. The returned value is authoritative. A supplied signal controls only this explicit assembly request and must not be retained to control later turns. ```ts cordis-catalog /** * Expert waterfall over the assembled sections, tools, and variables. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): scoped listeners * receive only that scope's assemblies. The returned value is authoritative. + * A supplied signal controls only this explicit assembly request and must not + * be retained to control later turns. * @param assembly - the mutable assembly built from registered providers. * @param context - the caller's per-assembly context. * @mode waterfall @@ -724,7 +734,7 @@ Expert waterfall over the assembled sections, tools, and variables. Scope-filter Types: [AssembleContext](../core-data-structures/system-prompt.md) · [Scoped](../core-data-structures/scope.md) · [SystemPrompt](../core-data-structures/system-prompt.md) -Source: [`packages/core/system-prompt/src/index.ts:27`](../../packages/core/system-prompt/src/index.ts) +Source: [`packages/core/system-prompt/src/index.ts:29`](../../packages/core/system-prompt/src/index.ts) ### `system-prompt/change` — emit @@ -739,7 +749,7 @@ Emitted when any prompt provider changes. This registry notification is unfilter 'system-prompt/change'(): void ``` -Source: [`packages/core/system-prompt/src/index.ts:33`](../../packages/core/system-prompt/src/index.ts) +Source: [`packages/core/system-prompt/src/index.ts:35`](../../packages/core/system-prompt/src/index.ts) ## `tools/*` diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index f05e68e2ec..f8711210c9 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -216,7 +216,7 @@ roots(): Agent[] Types: [Agent](../core-data-structures/core.md) · [SessionId](../core-data-structures/core.md) -Source: [`packages/core/agent/src/index.ts:223`](../../packages/core/agent/src/index.ts) +Source: [`packages/core/agent/src/index.ts:224`](../../packages/core/agent/src/index.ts) ## `ctx.approval` — `ApprovalService` @@ -960,7 +960,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` @@ -1122,7 +1122,7 @@ async assemble(context: AssembleContext = {}): Promise Types: [AssembleContext](../core-data-structures/system-prompt.md) · [PromptSection](../core-data-structures/system-prompt.md) · [ToolProviderResult](../core-data-structures/system-prompt.md) -Source: [`packages/core/system-prompt/src/index.ts:209`](../../packages/core/system-prompt/src/index.ts) +Source: [`packages/core/system-prompt/src/index.ts:213`](../../packages/core/system-prompt/src/index.ts) ## `ctx.tasks` — `TaskService` diff --git a/docs/core-data-structures/core.md b/docs/core-data-structures/core.md index dfdc258cb0..d886bd408a 100644 --- a/docs/core-data-structures/core.md +++ b/docs/core-data-structures/core.md @@ -350,6 +350,13 @@ interface InjectOptions extends SendOptions { } ``` +```ts type-equiv +/** Stable runtime cause accepted by {@link Agent.cancel}. */ +type AgentCancelCause = + | { readonly kind: 'user' } + | { readonly kind: 'parent' } +``` + ```ts type-equiv /** Public agent handle; its concrete implementation is internal to `@deepseek-ai/dsh-agent-loop`. */ interface Agent { @@ -390,12 +397,14 @@ interface Agent { /** * Clear all queued and steering work, including items waiting to start, and - * abort the active step. An effective call first emits `agent/cancel-requested` - * with the resolved reason. That reason is preserved across pre-step and active - * cancellation windows, and `whenIdle()` resolves after cancellation reaches - * quiescence. Idle cancellation is a no-op and does not arm a later cancel. + * abort the active turn. An effective call first emits + * `agent/cancel-requested` with the resolved typed cause. The first cause wins + * for the active turn, and `whenIdle()` resolves after cancellation reaches + * quiescence. Omission means `{ kind: 'user' }`. Idle cancellation is a no-op + * and does not arm later work. The active turn snapshots and freezes the cause. + * @param cause - the stable caller intent carried by the current turn signal. */ - cancel(reason?: string): void + cancel(cause?: AgentCancelCause): void /** Resolve at idle quiescence; disposal waits for driver exit rather than only the status transition. */ whenIdle(): Promise @@ -405,6 +414,8 @@ 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 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. ## Initiating Agent diff --git a/docs/core-data-structures/session.md b/docs/core-data-structures/session.md index 8650688222..b65d25f7ae 100644 --- a/docs/core-data-structures/session.md +++ b/docs/core-data-structures/session.md @@ -463,13 +463,16 @@ interface TurnTriggerMap { ## Why a turn ended: `TurnEndReasonMap` +`aborted` is intentionally a coarse durable outcome: it records that cancellation interrupted the live turn, not which runtime caller requested it. The runtime-only caller vocabulary belongs to [`AgentCancelCause`](core.md#the-agent-handle); a future audit requirement would use a separate control-request event rather than overloading the terminal result. + ```ts type-equiv /** * Why a turn ended. Merge-extensible sum type. */ interface TurnEndReasonMap { completed: { kind: 'completed' } - aborted: { kind: 'aborted'; reason?: string } + /** A cancellation request interrupted the live turn. */ + aborted: { kind: 'aborted' } /** * The turn failed: a step threw or the model reported a failure. `step` is the * step number the failure occurred on (the operational error's location — the diff --git a/docs/core-data-structures/system-prompt.md b/docs/core-data-structures/system-prompt.md index 04c86aabe6..85a974e6df 100644 --- a/docs/core-data-structures/system-prompt.md +++ b/docs/core-data-structures/system-prompt.md @@ -6,7 +6,7 @@ Source: [`packages/core/system-prompt/src/index.ts`](../../packages/core/system- ## Assembly context -`AssembleContext` identifies the scope layer one assembly resolves. It is merge-extensible: `dsh-agent` adds the optional live `agent` field, and `assembleContextFor(agent)` sets that field and `scope` together. +`AssembleContext` identifies the scope layer one assembly resolves and may carry the explicit control signal for that request. It is merge-extensible: `dsh-agent` adds the optional live `agent` field, and `assembleContextFor(agent, signal)` sets the explicit fields together. A bare assembly has neither scope nor signal. ```ts type-equiv /** Merge-extensible context for one prompt assembly. */ @@ -16,6 +16,8 @@ interface AssembleContext { * only global providers and subject-less listeners participate. */ scope?: ScopeKey + /** Explicit control signal for the turn that requested this assembly, when any. */ + signal?: AbortSignal } ``` diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 16f550ead1..34684c6f0e 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -8,22 +8,22 @@ This matrix shows which packages dispatch each harness-owned event and which pac | Event | Mode | Declared in | Dispatchers | Listeners | | --- | --- | --- | --- | --- | | `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:353`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | [`tui`](../packages/ui/tui) | -| `agent/cancel-requested` | `emit` | [`packages/core/agent/src/types.ts:191`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-session`](../packages/goal/goal-session) | -| `agent/created` | `emit` | [`packages/core/agent/src/types.ts:153`](../packages/core/agent/src/types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`goal-session`](../packages/goal/goal-session), [`tui`](../packages/ui/tui) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/types.ts:162`](../packages/core/agent/src/types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), [`goal-session`](../packages/goal/goal-session), [`tui`](../packages/ui/tui) | -| `agent/error` | `emit` | [`packages/core/agent/src/types.ts:328`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-session`](../packages/goal/goal-session), [`tui`](../packages/ui/tui) | -| `agent/post-step` | `serial` | [`packages/core/agent/src/types.ts:280`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`compact-basic`](../packages/compact/compact-basic) | -| `agent/pre-step` | `serial` | [`packages/core/agent/src/types.ts:220`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`time-context`](../packages/context/time-context), [`user-approval`](../packages/ui/user-approval) | -| `agent/prompt-submit` | `waterfall` | [`packages/core/agent/src/types.ts:230`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`acp`](../packages/ui/acp), [`goal-session`](../packages/goal/goal-session), [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex), [`repeat-tool-guard`](../packages/guard/repeat-tool-guard) | -| `agent/queued` | `emit` | [`packages/core/agent/src/types.ts:181`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-session`](../packages/goal/goal-session) | -| `agent/request` | `waterfall` | [`packages/core/agent/src/types.ts:242`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`acp`](../packages/ui/acp) | -| `agent/request-error` | `waterfall` | [`packages/core/agent/src/types.ts:295`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compact-basic`](../packages/compact/compact-basic), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/session-prefix` | `waterfall` | [`packages/core/agent/src/types.ts:257`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`tool-skill`](../packages/skill/tool-skill), [`workspace-context`](../packages/context/workspace-context) | -| `agent/session-start` | `emit` | [`packages/core/agent/src/types.ts:204`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal`](../packages/goal/goal), [`goal-session`](../packages/goal/goal-session), [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex) | -| `agent/status` | `emit` | [`packages/core/agent/src/types.ts:171`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-session`](../packages/goal/goal-session), [`invariants`](../packages/support/invariants), [`tui`](../packages/ui/tui) | -| `agent/step-result` | `waterfall` | [`packages/core/agent/src/types.ts:268`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | - | -| `agent/turn-continuation` | `waterfall` | [`packages/core/agent/src/types.ts:305`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex) | -| `agent/turn-stop` | `serial` | [`packages/core/agent/src/types.ts:315`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`subagent-inprocess`](../packages/subagent/subagent-inprocess), [`tool-goal`](../packages/goal/tool-goal) | +| `agent/cancel-requested` | `emit` | [`packages/core/agent/src/types.ts:201`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-session`](../packages/goal/goal-session) | +| `agent/created` | `emit` | [`packages/core/agent/src/types.ts:163`](../packages/core/agent/src/types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`goal-session`](../packages/goal/goal-session), [`tui`](../packages/ui/tui) | +| `agent/disposed` | `emit` | [`packages/core/agent/src/types.ts:172`](../packages/core/agent/src/types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), [`goal-session`](../packages/goal/goal-session), [`tui`](../packages/ui/tui) | +| `agent/error` | `emit` | [`packages/core/agent/src/types.ts:346`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-session`](../packages/goal/goal-session), [`tui`](../packages/ui/tui) | +| `agent/post-step` | `serial` | [`packages/core/agent/src/types.ts:296`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`compact-basic`](../packages/compact/compact-basic) | +| `agent/pre-step` | `serial` | [`packages/core/agent/src/types.ts:230`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`time-context`](../packages/context/time-context), [`user-approval`](../packages/ui/user-approval) | +| `agent/prompt-submit` | `waterfall` | [`packages/core/agent/src/types.ts:243`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`acp`](../packages/ui/acp), [`goal-session`](../packages/goal/goal-session), [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex), [`repeat-tool-guard`](../packages/guard/repeat-tool-guard) | +| `agent/queued` | `emit` | [`packages/core/agent/src/types.ts:191`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-session`](../packages/goal/goal-session) | +| `agent/request` | `waterfall` | [`packages/core/agent/src/types.ts:257`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`acp`](../packages/ui/acp) | +| `agent/request-error` | `waterfall` | [`packages/core/agent/src/types.ts:311`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compact-basic`](../packages/compact/compact-basic), [`llm-retry`](../packages/llm/llm-retry) | +| `agent/session-prefix` | `waterfall` | [`packages/core/agent/src/types.ts:272`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`tool-skill`](../packages/skill/tool-skill), [`workspace-context`](../packages/context/workspace-context) | +| `agent/session-start` | `emit` | [`packages/core/agent/src/types.ts:214`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal`](../packages/goal/goal), [`goal-session`](../packages/goal/goal-session), [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex) | +| `agent/status` | `emit` | [`packages/core/agent/src/types.ts:181`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-session`](../packages/goal/goal-session), [`invariants`](../packages/support/invariants), [`tui`](../packages/ui/tui) | +| `agent/step-result` | `waterfall` | [`packages/core/agent/src/types.ts:284`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | - | +| `agent/turn-continuation` | `waterfall` | [`packages/core/agent/src/types.ts:322`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex) | +| `agent/turn-stop` | `serial` | [`packages/core/agent/src/types.ts:333`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`subagent-inprocess`](../packages/subagent/subagent-inprocess), [`tool-goal`](../packages/goal/tool-goal) | | `approval/request` | `waterfall` | [`packages/ui/user-approval/src/index.ts:31`](../packages/ui/user-approval/src/index.ts) | [`user-approval`](../packages/ui/user-approval) (`waterfall`) | [`acp`](../packages/ui/acp) | | `commands/change` | `emit` | [`packages/ui/commands/src/index.ts:83`](../packages/ui/commands/src/index.ts) | [`commands`](../packages/ui/commands) (`events.dispatch`) | [`acp`](../packages/ui/acp), [`tui`](../packages/ui/tui) | | `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:62`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-policy`](../packages/fs/fs-policy) | @@ -39,8 +39,8 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `subagent/provider-added` | `emit` | [`packages/subagent/subagent/src/index.ts:113`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`emit`) | [`tool-subagent`](../packages/subagent/tool-subagent) | | `subagent/provider-removed` | `emit` | [`packages/subagent/subagent/src/index.ts:119`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`tool-subagent`](../packages/subagent/tool-subagent) | | `subagent/start` | `emit` | [`packages/subagent/subagent/src/index.ts:130`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude`](../packages/hooks/hooks-claude) | -| `system-prompt/assemble` | `waterfall` | [`packages/core/system-prompt/src/index.ts:27`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | [`acp`](../packages/ui/acp) | -| `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:33`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - | +| `system-prompt/assemble` | `waterfall` | [`packages/core/system-prompt/src/index.ts:29`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | [`acp`](../packages/ui/acp) | +| `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:35`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - | | `tools/change` | `emit` | [`packages/core/tools/src/index.ts:123`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`emit`) | - | | `tools/execute` | `waterfall` | [`packages/core/tools/src/index.ts:93`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`timeout-policy`](../packages/timeout/timeout-policy) | | `tools/post-execute` | `waterfall` | [`packages/core/tools/src/index.ts:105`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex), [`repeat-tool-guard`](../packages/guard/repeat-tool-guard), [`spill-policy`](../packages/spill/spill-policy), [`workspace-context`](../packages/context/workspace-context) | diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 80b0b7196d..7f4392709f 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -79,7 +79,7 @@ export type SessionEvent = { }[T] ``` -Sources: [`packages/core/session/src/types.ts:267`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:274`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:304`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:336`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:268`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:275`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:305`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:337`](../packages/core/session/src/types.ts) ## Events @@ -151,7 +151,7 @@ Source: [`packages/ui/user-approval/src/index.ts:68`](../packages/ui/user-approv Types: [StreamChunk](core-data-structures/llm-streaming.md) -Source: [`packages/core/session/src/types.ts:231`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:232`](../packages/core/session/src/types.ts) #### `assistant/message` — surface @@ -167,7 +167,7 @@ Source: [`packages/core/session/src/types.ts:231`](../packages/core/session/src/ Types: [ContentBlock](core-data-structures/core.md) · [TokenUsage](core-data-structures/llm-streaming.md) -Source: [`packages/core/session/src/types.ts:238`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:239`](../packages/core/session/src/types.ts) ### `compact/*` @@ -246,7 +246,7 @@ Source: [`packages/compact/compact/src/types.ts:22`](../packages/compact/compact Types: [ContentBlock](core-data-structures/core.md) · [MessageSource](core-data-structures/core.md) -Source: [`packages/core/session/src/types.ts:225`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:226`](../packages/core/session/src/types.ts) ### `hook/*` @@ -342,7 +342,7 @@ Source: [`packages/ui/permission/src/index.ts:36`](../packages/ui/permission/src Types: [ContentBlock](core-data-structures/core.md) · [MessageSource](core-data-structures/core.md) -Source: [`packages/core/session/src/types.ts:213`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:214`](../packages/core/session/src/types.ts) ### `request/*` @@ -356,7 +356,7 @@ Source: [`packages/core/session/src/types.ts:213`](../packages/core/session/src/ 'request/header': { header: EpochHeader; reason: RequestHeaderReason } ``` -Source: [`packages/core/session/src/types.ts:263`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:264`](../packages/core/session/src/types.ts) ### `sandbox/*` @@ -387,7 +387,7 @@ Source: [`packages/sandbox/sandbox-policy/src/session-mode.ts:34`](../packages/s Types: [ContentBlock](core-data-structures/core.md) · [MessageSource](core-data-structures/core.md) -Source: [`packages/core/session/src/types.ts:256`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:257`](../packages/core/session/src/types.ts) ### `step/*` @@ -398,7 +398,7 @@ Source: [`packages/core/session/src/types.ts:256`](../packages/core/session/src/ 'step/end': { turn: number; step: number } ``` -Source: [`packages/core/session/src/types.ts:206`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:207`](../packages/core/session/src/types.ts) #### `step/start` — log-only @@ -407,7 +407,7 @@ Source: [`packages/core/session/src/types.ts:206`](../packages/core/session/src/ 'step/start': { turn: number; step: number } ``` -Source: [`packages/core/session/src/types.ts:204`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:205`](../packages/core/session/src/types.ts) ### `todo/*` @@ -420,7 +420,7 @@ Source: [`packages/core/session/src/types.ts:204`](../packages/core/session/src/ Types: [TodoItem](core-data-structures/session.md) -Source: [`packages/core/session/src/types.ts:258`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:259`](../packages/core/session/src/types.ts) ### `tool/*` @@ -437,7 +437,7 @@ Source: [`packages/core/session/src/types.ts:258`](../packages/core/session/src/ Types: [CallId](core-data-structures/core.md) -Source: [`packages/core/session/src/types.ts:244`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:245`](../packages/core/session/src/types.ts) #### `tool/code-dispatch` — log-only @@ -481,7 +481,7 @@ Source: [`packages/core/tools/src/code-mode.ts:34`](../packages/core/tools/src/c Types: [CallId](core-data-structures/core.md) · [ContentBlock](core-data-structures/core.md) -Source: [`packages/core/session/src/types.ts:254`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:255`](../packages/core/session/src/types.ts) ### `turn/*` @@ -499,7 +499,7 @@ Source: [`packages/core/session/src/types.ts:254`](../packages/core/session/src/ Types: [TurnEndReason](core-data-structures/session.md) -Source: [`packages/core/session/src/types.ts:202`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:203`](../packages/core/session/src/types.ts) #### `turn/start` — log-only @@ -515,7 +515,7 @@ Source: [`packages/core/session/src/types.ts:202`](../packages/core/session/src/ Types: [TurnTrigger](core-data-structures/session.md) -Source: [`packages/core/session/src/types.ts:195`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:196`](../packages/core/session/src/types.ts) ### `user/*` @@ -528,4 +528,4 @@ Source: [`packages/core/session/src/types.ts:195`](../packages/core/session/src/ Types: [ContentBlock](core-data-structures/core.md) · [MessageSource](core-data-structures/core.md) -Source: [`packages/core/session/src/types.ts:208`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:209`](../packages/core/session/src/types.ts) diff --git a/examples/acp-agent/tests/goal-snapshots/goal-session/session.expected.jsonl b/examples/acp-agent/tests/goal-snapshots/goal-session/session.expected.jsonl index 3129ceead5..9a792c3849 100644 --- a/examples/acp-agent/tests/goal-snapshots/goal-session/session.expected.jsonl +++ b/examples/acp-agent/tests/goal-snapshots/goal-session/session.expected.jsonl @@ -50,4 +50,4 @@ {"type":"assistant/chunk","seq":48,"time":0,"data":{"turn":3,"step":1,"chunk":{"type":"text-delta","index":0,"text":"partial"}}} {"type":"context/message","seq":49,"time":0,"data":{"content":[{"type":"text","text":"{\"goal\":{\"id\":\"goal-{{sessionId}}\",\"revision\":2,\"objective\":\"Finish the ACP goal-session snapshot proof\",\"phase\":\"paused\",\"maxGoalRounds\":2},\"roundsStarted\":2,\"createdAt\":0,\"updatedAt\":0}"}],"source":{"kind":"goal","goalId":"goal-{{sessionId}}","revision":2,"round":0},"meta":{"kind":"goal/change","version":1,"operation":"pause","goal":{"id":"goal-{{sessionId}}","revision":2,"objective":"Finish the ACP goal-session snapshot proof","phase":"paused","maxGoalRounds":2},"roundsStarted":2,"createdAt":0,"updatedAt":0}},"surfaceOp":"append"} {"type":"step/end","seq":50,"time":0,"data":{"turn":3,"step":1}} -{"type":"turn/end","seq":51,"time":0,"data":{"turn":3,"reason":{"kind":"aborted","reason":"session/cancel"}}} +{"type":"turn/end","seq":51,"time":0,"data":{"turn":3,"reason":{"kind":"aborted"}}} diff --git a/examples/acp-agent/tests/snapshots/cancel-tool-calls/session.jsonl b/examples/acp-agent/tests/snapshots/cancel-tool-calls/session.jsonl index a52a633c85..e9b2467385 100644 --- a/examples/acp-agent/tests/snapshots/cancel-tool-calls/session.jsonl +++ b/examples/acp-agent/tests/snapshots/cancel-tool-calls/session.jsonl @@ -17,4 +17,4 @@ {"type":"tool/call","seq":15,"time":1784437195089,"data":{"turn":1,"step":1,"callId":"call_skipped","name":"bash","arguments":"{\"command\":\"printf skipped > skipped.txt\",\"description\":\"Write skipped marker\"}"}} {"type":"tool/result","seq":16,"time":1784437195089,"data":{"turn":1,"step":1,"callId":"call_skipped","content":[{"type":"text","text":"Error: tool call aborted before dispatch"}],"isError":true,"error":{"name":"AbortError","code":"ABORTED_BEFORE_DISPATCH"}},"sourceEventSeqs":[15],"surfaceOp":"append"} {"type":"step/end","seq":17,"time":1784437195090,"data":{"turn":1,"step":1}} -{"type":"turn/end","seq":18,"time":1784437195090,"data":{"turn":1,"reason":{"kind":"aborted","reason":"session/cancel"}}} +{"type":"turn/end","seq":18,"time":1784437195090,"data":{"turn":1,"reason":{"kind":"aborted"}}} diff --git a/examples/acp-agent/tests/snapshots/cancel/session.jsonl b/examples/acp-agent/tests/snapshots/cancel/session.jsonl index 44e8ac136c..3fcf779321 100644 --- a/examples/acp-agent/tests/snapshots/cancel/session.jsonl +++ b/examples/acp-agent/tests/snapshots/cancel/session.jsonl @@ -6,4 +6,4 @@ {"type":"assistant/chunk","seq":4,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} {"type":"assistant/chunk","seq":5,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":0,"text":"partial"}}} {"type":"step/end","seq":6,"time":0,"data":{"turn":1,"step":1}} -{"type":"turn/end","seq":7,"time":0,"data":{"turn":1,"reason":{"kind":"aborted","reason":"session/cancel"}}} +{"type":"turn/end","seq":7,"time":0,"data":{"turn":1,"reason":{"kind":"aborted"}}} diff --git a/examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/session.jsonl b/examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/session.jsonl index 495cb719b3..fbc6851750 100644 --- a/examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/session.jsonl +++ b/examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/session.jsonl @@ -10,7 +10,7 @@ {"type":"assistant/chunk","seq":8,"time":1783951000009,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":9,"time":1784449176722,"data":{"turn":1,"step":1,"content":[{"type":"tool-call","id":"inspect-tools-api","name":"cordis_inspect","arguments":"{\"what\":\"api\",\"name\":\"tools\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[4,5,6,7,8],"surfaceOp":"append"} {"type":"tool/call","seq":10,"time":1784449176722,"data":{"turn":1,"step":1,"callId":"inspect-tools-api","name":"cordis_inspect","arguments":"{\"what\":\"api\",\"name\":\"tools\"}"}} -{"type":"tool/result","seq":11,"time":1784449176732,"data":{"turn":1,"step":1,"callId":"inspect-tools-api","content":[{"type":"text","text":"## api\n- tools — Tool registry and execution pipeline.\n /**\n * Register globally or in the calling agent scope. Scoped tools shadow\n * globals; duplicates within one layer and the reserved `run_code` name fail.\n * @param definition - the tool schema, execution, and optional presentation functions.\n * @returns the exact disposer that unregisters the tool.\n */\n register(definition: ToolDefinition): () => void\n /**\n * Restrict global tools for the calling agent scope. Empty filters, unknown\n * names, scope-local names, and reserved transport names fail. Restrictions\n * intersect; scoped registrations remain visible.\n * @param filter - global-surface mask: `allow` (keep only) and/or `deny` (remove).\n * @returns the exact disposer that lifts this restriction.\n */\n restrict(filter: ToolRestriction): () => void\n /**\n * Register a monotonic guard after the extensible `tools/pre-execute`\n * waterfall. A plain-context guard applies globally; one registered through\n * `agent.ctx` applies only to that agent. Any matching guard may deny by\n * returning a reason, while no guard can force-allow a call another guard\n * denied. The exact effect disposer is returned for ordered ownership and\n * HMR cleanup.\n * @param guard - synchronous check; a returned string denies the execution.\n * @returns the exact disposer that unregisters the guard.\n */\n guard(guard: ToolGuard): () => void\n /**\n * Look up a tool as one scope sees it (scoped\n * shadows global; a restricted-away global reads as absent). Presenters pass\n * the calling agent so the rendered card matches the definition that\n * actually executed.\n * @param name - the tool name as registered.\n * @param scope - the viewing scope (the agent); omitted = the global view.\n * @returns the definition the scope resolves, or undefined when none is visible.\n */\n get(name: string, scope?: ScopeKey): ToolDefinition | undefined\n /**\n * Project visible definitions onto the allowlisted model-facing schema fields,\n * excluding execution and presentation callbacks.\n * @param scope - the viewing scope (the agent); omitted = the global view.\n * @returns one deep-cloned schema per visible tool.\n */\n schemas(scope?: ScopeKey): ToolSchema[]\n /**\n * Classify a pending call through the caller's visible tool definition. Only\n * an exact `true` is parallel; unknown, hidden, undeclared, invalid, or\n * throwing classifiers are exclusive.\n * @param exec - call name, parsed arguments, and optional agent scope.\n * @returns the fail-closed scheduling mode.\n */\n executionMode(exec: ToolExecutionInput): ToolExecutionMode\n /**\n * Execute through pre-policy, guards, around-dispatch, post-policy, and final\n * notification. Tool and listener failures resolve as materialized error\n * results; an invisible tool reports `UNKNOWN_TOOL`. The returned outcome is\n * the same lossless, frozen snapshot final observers receive. Cancellation\n * arriving after entry and before final result materialization skips a\n * not-yet-started body with `ABORTED_BEFORE_DISPATCH` or replaces a\n * successful started outcome with `ABORTED`; already-started work is still\n * drained and may retain a tool-owned structured error.\n * @param exec - the typed same-process call input. The registry assigns its\n * correlation token before policy begins.\n * @returns the materialized final result.\n */\n async execute(exec: ToolExecutionInput): Promise\ntype shapes (referenced by the signatures above — read these before assuming a field is a string):\n export interface Agent {\n readonly id: SessionId;\n readonly options: AgentOptions;\n readonly session: Session;\n readonly status: AgentStatus;\n readonly ctx: Context;\n send(content: ContentBlock[], options?: SendOptions): void;\n steer(content: ContentBlock[], options?: SendOptions): void;\n inject(content: ContentBlock[], options?: InjectOptions): void;\n cancel(reason?: string): void;\n whenIdle(): Promise;\n }\n export interface AgentOptions {\n provider?: string;\n model?: string;\n }\n export type AgentStatus = 'idle' | 'running' | 'disposed';\n export type Branded = string & {\n readonly [BRAND]: B;\n };\n export type CallId = Branded<'CallId'>;\n export interface DiffCallView {\n card: 'diff';\n title: string;\n diffs: FileDiff[];\n locations?: FileLocation[];\n }\n export interface DiffResultView {\n card: 'diff';\n title?: string;\n diffs: FileDiff[];\n }\n export interface FileDiff {\n path: string;\n oldText: string | null;\n newText: string;\n }\n export interface FileLocation {\n path: string;\n line?: number;\n }\n export interface GenericCallView {\n card: 'generic';\n title: string;\n kind?: ToolCallKind;\n rawInput?: unknown;\n content?: ContentBlock[];\n locations?: FileLocation[];\n }\n export interface GenericResultView {\n card: 'generic';\n title?: string;\n content?: ContentBlock[];\n }\n export interface HookContext {\n content: ContentBlock[];\n source: MessageSource;\n meta?: JsonValue;\n }\n export interface InjectOptions extends SendOptions {\n meta?: JsonValue;\n }\n export type JsonValue = null | boolean | number | string | JsonValue[] | {\n [key: string]: JsonValue;\n };\n export type MessageSource = MessageSourceMap[keyof MessageSourceMap];\n export interface MessageSourceMap {\n user: {\n kind: 'user';\n };\n plugin: {\n kind: 'plugin';\n plugin: string;\n };\n }\n export type ScopeKey = object;\n export interface SendOptions {\n source?: MessageSource;\n }\n export type SessionId = Branded<'SessionId'>;\n export interface TerminalCallView {\n card: 'terminal';\n title: string;\n description?: string;\n cwd?: string;\n }\n export interface TerminalResultView {\n card: 'terminal';\n title?: string;\n output?: string;\n exitCode?: number;\n signal?: string;\n }\n export type ToolCallKind = 'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'fetch' | 'other';\n export type ToolCallView = GenericCallView | TerminalCallView | DiffCallView;\n export interface ToolDefinition extends ToolSchema {\n execute(args: unknown, exec: ToolRunContext): Promise;\n timeoutMs?: number;\n isConcurrencySafe?(args: unknown): boolean;\n presentCall?(args: unknown): ToolCallView | undefined;\n presentResult?(args: unknown, result: ToolResult): ToolResultView | undefined;\n }\n export interface ToolErrorInfo {\n name: string;\n code: string;\n }\n export type ToolExecuteReturn = ContentBlock[] | {\n content: ContentBlock[];\n meta?: unknown;\n };\n export interface ToolExecution extends ToolExecutionInput {\n readonly token: ToolExecutionToken;\n }\n export interface ToolExecutionInput {\n readonly callId: CallId;\n readonly name: string;\n readonly arguments: unknown;\n readonly agent?: Agent;\n readonly parent?: ToolExecutionToken;\n readonly signal: AbortSignal;\n }\n export type ToolExecutionMode = {\n kind: 'parallel';\n } | {\n kind: 'exclusive';\n };\n export interface ToolExecutionResult {\n content: ContentBlock[];\n isError: boolean;\n error?: ToolErrorInfo;\n additionalContexts?: HookContext[];\n meta?: unknown;\n }\n export type ToolExecutionToken = symbol & {\n readonly [toolExecutionTokenBrand]: true;\n };\n export type ToolGuard = (execution: Readonly) => string | undefined;\n export interface ToolRestriction {\n readonly allow?: readonly string[];\n readonly deny?: readonly string[];\n }\n export interface ToolResult {\n content: ContentBlock[];\n isError: boolean;\n meta?: unknown;\n }\n export type ToolResultView = GenericResultView | TerminalResultView | DiffResultView;\n export interface ToolRunContext extends ToolExecution {\n deferContext(context: HookContext): void;\n }\n export interface ToolSchema {\n name: string;\n description: string;\n parameters: Record;\n }"}],"isError":false},"sourceEventSeqs":[10],"surfaceOp":"append"} +{"type":"tool/result","seq":11,"time":1784449176732,"data":{"turn":1,"step":1,"callId":"inspect-tools-api","content":[{"type":"text","text":"## api\n- tools — Tool registry and execution pipeline.\n /**\n * Register globally or in the calling agent scope. Scoped tools shadow\n * globals; duplicates within one layer and the reserved `run_code` name fail.\n * @param definition - the tool schema, execution, and optional presentation functions.\n * @returns the exact disposer that unregisters the tool.\n */\n register(definition: ToolDefinition): () => void\n /**\n * Restrict global tools for the calling agent scope. Empty filters, unknown\n * names, scope-local names, and reserved transport names fail. Restrictions\n * intersect; scoped registrations remain visible.\n * @param filter - global-surface mask: `allow` (keep only) and/or `deny` (remove).\n * @returns the exact disposer that lifts this restriction.\n */\n restrict(filter: ToolRestriction): () => void\n /**\n * Register a monotonic guard after the extensible `tools/pre-execute`\n * waterfall. A plain-context guard applies globally; one registered through\n * `agent.ctx` applies only to that agent. Any matching guard may deny by\n * returning a reason, while no guard can force-allow a call another guard\n * denied. The exact effect disposer is returned for ordered ownership and\n * HMR cleanup.\n * @param guard - synchronous check; a returned string denies the execution.\n * @returns the exact disposer that unregisters the guard.\n */\n guard(guard: ToolGuard): () => void\n /**\n * Look up a tool as one scope sees it (scoped\n * shadows global; a restricted-away global reads as absent). Presenters pass\n * the calling agent so the rendered card matches the definition that\n * actually executed.\n * @param name - the tool name as registered.\n * @param scope - the viewing scope (the agent); omitted = the global view.\n * @returns the definition the scope resolves, or undefined when none is visible.\n */\n get(name: string, scope?: ScopeKey): ToolDefinition | undefined\n /**\n * Project visible definitions onto the allowlisted model-facing schema fields,\n * excluding execution and presentation callbacks.\n * @param scope - the viewing scope (the agent); omitted = the global view.\n * @returns one deep-cloned schema per visible tool.\n */\n schemas(scope?: ScopeKey): ToolSchema[]\n /**\n * Classify a pending call through the caller's visible tool definition. Only\n * an exact `true` is parallel; unknown, hidden, undeclared, invalid, or\n * throwing classifiers are exclusive.\n * @param exec - call name, parsed arguments, and optional agent scope.\n * @returns the fail-closed scheduling mode.\n */\n executionMode(exec: ToolExecutionInput): ToolExecutionMode\n /**\n * Execute through pre-policy, guards, around-dispatch, post-policy, and final\n * notification. Tool and listener failures resolve as materialized error\n * results; an invisible tool reports `UNKNOWN_TOOL`. The returned outcome is\n * the same lossless, frozen snapshot final observers receive. Cancellation\n * arriving after entry and before final result materialization skips a\n * not-yet-started body with `ABORTED_BEFORE_DISPATCH` or replaces a\n * successful started outcome with `ABORTED`; already-started work is still\n * drained and may retain a tool-owned structured error.\n * @param exec - the typed same-process call input. The registry assigns its\n * correlation token before policy begins.\n * @returns the materialized final result.\n */\n async execute(exec: ToolExecutionInput): Promise\ntype shapes (referenced by the signatures above — read these before assuming a field is a string):\n export interface Agent {\n readonly id: SessionId;\n readonly options: AgentOptions;\n readonly session: Session;\n readonly status: AgentStatus;\n readonly ctx: Context;\n send(content: ContentBlock[], options?: SendOptions): void;\n steer(content: ContentBlock[], options?: SendOptions): void;\n inject(content: ContentBlock[], options?: InjectOptions): void;\n cancel(cause?: AgentCancelCause): void;\n whenIdle(): Promise;\n }\n export type AgentCancelCause = {\n readonly kind: 'user';\n } | {\n readonly kind: 'parent';\n };\n export interface AgentOptions {\n provider?: string;\n model?: string;\n }\n export type AgentStatus = 'idle' | 'running' | 'disposed';\n export type Branded = string & {\n readonly [BRAND]: B;\n };\n export type CallId = Branded<'CallId'>;\n export interface DiffCallView {\n card: 'diff';\n title: string;\n diffs: FileDiff[];\n locations?: FileLocation[];\n }\n export interface DiffResultView {\n card: 'diff';\n title?: string;\n diffs: FileDiff[];\n }\n export interface FileDiff {\n path: string;\n oldText: string | null;\n newText: string;\n }\n export interface FileLocation {\n path: string;\n line?: number;\n }\n export interface GenericCallView {\n card: 'generic';\n title: string;\n kind?: ToolCallKind;\n rawInput?: unknown;\n content?: ContentBlock[];\n locations?: FileLocation[];\n }\n export interface GenericResultView {\n card: 'generic';\n title?: string;\n content?: ContentBlock[];\n }\n export interface HookContext {\n content: ContentBlock[];\n source: MessageSource;\n meta?: JsonValue;\n }\n export interface InjectOptions extends SendOptions {\n meta?: JsonValue;\n }\n export type JsonValue = null | boolean | number | string | JsonValue[] | {\n [key: string]: JsonValue;\n };\n export type MessageSource = MessageSourceMap[keyof MessageSourceMap];\n export interface MessageSourceMap {\n user: {\n kind: 'user';\n };\n plugin: {\n kind: 'plugin';\n plugin: string;\n };\n }\n export type ScopeKey = object;\n export interface SendOptions {\n source?: MessageSource;\n }\n export type SessionId = Branded<'SessionId'>;\n export interface TerminalCallView {\n card: 'terminal';\n title: string;\n description?: string;\n cwd?: string;\n }\n export interface TerminalResultView {\n card: 'terminal';\n title?: string;\n output?: string;\n exitCode?: number;\n signal?: string;\n }\n export type ToolCallKind = 'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'fetch' | 'other';\n export type ToolCallView = GenericCallView | TerminalCallView | DiffCallView;\n export interface ToolDefinition extends ToolSchema {\n execute(args: unknown, exec: ToolRunContext): Promise;\n timeoutMs?: number;\n isConcurrencySafe?(args: unknown): boolean;\n presentCall?(args: unknown): ToolCallView | undefined;\n presentResult?(args: unknown, result: ToolResult): ToolResultView | undefined;\n }\n export interface ToolErrorInfo {\n name: string;\n code: string;\n }\n export type ToolExecuteReturn = ContentBlock[] | {\n content: ContentBlock[];\n meta?: unknown;\n };\n export interface ToolExecution extends ToolExecutionInput {\n readonly token: ToolExecutionToken;\n }\n export interface ToolExecutionInput {\n readonly callId: CallId;\n readonly name: string;\n readonly arguments: unknown;\n readonly agent?: Agent;\n readonly parent?: ToolExecutionToken;\n readonly signal: AbortSignal;\n }\n export type ToolExecutionMode = {\n kind: 'parallel';\n } | {\n kind: 'exclusive';\n };\n export interface ToolExecutionResult {\n content: ContentBlock[];\n isError: boolean;\n error?: ToolErrorInfo;\n additionalContexts?: HookContext[];\n meta?: unknown;\n }\n export type ToolExecutionToken = symbol & {\n readonly [toolExecutionTokenBrand]: true;\n };\n export type ToolGuard = (execution: Readonly) => string | undefined;\n export interface ToolRestriction {\n readonly allow?: readonly string[];\n readonly deny?: readonly string[];\n }\n export interface ToolResult {\n content: ContentBlock[];\n isError: boolean;\n meta?: unknown;\n }\n export type ToolResultView = GenericResultView | TerminalResultView | DiffResultView;\n export interface ToolRunContext extends ToolExecution {\n deferContext(context: HookContext): void;\n }\n export interface ToolSchema {\n name: string;\n description: string;\n parameters: Record;\n }"}],"isError":false},"sourceEventSeqs":[10],"surfaceOp":"append"} {"type":"step/end","seq":12,"time":1784449176732,"data":{"turn":1,"step":1}} {"type":"step/start","seq":13,"time":1784449176733,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":14,"time":1783951000015,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} diff --git a/examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/stdout.expected.jsonl index fe8a582690..e6fc1ad3cc 100644 --- a/examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/stdout.expected.jsonl @@ -2,7 +2,7 @@ {"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[|clear|edit |pause|resume]"}}]}}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"inspect-tools-api","title":"Inspect cordis runtime: api: tools","kind":"read","status":"in_progress"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"inspect-tools-api","status":"completed","content":[{"type":"content","content":{"type":"text","text":"## api\n- tools — Tool registry and execution pipeline.\n /**\n * Register globally or in the calling agent scope. Scoped tools shadow\n * globals; duplicates within one layer and the reserved `run_code` name fail.\n * @param definition - the tool schema, execution, and optional presentation functions.\n * @returns the exact disposer that unregisters the tool.\n */\n register(definition: ToolDefinition): () => void\n /**\n * Restrict global tools for the calling agent scope. Empty filters, unknown\n * names, scope-local names, and reserved transport names fail. Restrictions\n * intersect; scoped registrations remain visible.\n * @param filter - global-surface mask: `allow` (keep only) and/or `deny` (remove).\n * @returns the exact disposer that lifts this restriction.\n */\n restrict(filter: ToolRestriction): () => void\n /**\n * Register a monotonic guard after the extensible `tools/pre-execute`\n * waterfall. A plain-context guard applies globally; one registered through\n * `agent.ctx` applies only to that agent. Any matching guard may deny by\n * returning a reason, while no guard can force-allow a call another guard\n * denied. The exact effect disposer is returned for ordered ownership and\n * HMR cleanup.\n * @param guard - synchronous check; a returned string denies the execution.\n * @returns the exact disposer that unregisters the guard.\n */\n guard(guard: ToolGuard): () => void\n /**\n * Look up a tool as one scope sees it (scoped\n * shadows global; a restricted-away global reads as absent). Presenters pass\n * the calling agent so the rendered card matches the definition that\n * actually executed.\n * @param name - the tool name as registered.\n * @param scope - the viewing scope (the agent); omitted = the global view.\n * @returns the definition the scope resolves, or undefined when none is visible.\n */\n get(name: string, scope?: ScopeKey): ToolDefinition | undefined\n /**\n * Project visible definitions onto the allowlisted model-facing schema fields,\n * excluding execution and presentation callbacks.\n * @param scope - the viewing scope (the agent); omitted = the global view.\n * @returns one deep-cloned schema per visible tool.\n */\n schemas(scope?: ScopeKey): ToolSchema[]\n /**\n * Classify a pending call through the caller's visible tool definition. Only\n * an exact `true` is parallel; unknown, hidden, undeclared, invalid, or\n * throwing classifiers are exclusive.\n * @param exec - call name, parsed arguments, and optional agent scope.\n * @returns the fail-closed scheduling mode.\n */\n executionMode(exec: ToolExecutionInput): ToolExecutionMode\n /**\n * Execute through pre-policy, guards, around-dispatch, post-policy, and final\n * notification. Tool and listener failures resolve as materialized error\n * results; an invisible tool reports `UNKNOWN_TOOL`. The returned outcome is\n * the same lossless, frozen snapshot final observers receive. Cancellation\n * arriving after entry and before final result materialization skips a\n * not-yet-started body with `ABORTED_BEFORE_DISPATCH` or replaces a\n * successful started outcome with `ABORTED`; already-started work is still\n * drained and may retain a tool-owned structured error.\n * @param exec - the typed same-process call input. The registry assigns its\n * correlation token before policy begins.\n * @returns the materialized final result.\n */\n async execute(exec: ToolExecutionInput): Promise\ntype shapes (referenced by the signatures above — read these before assuming a field is a string):\n export interface Agent {\n readonly id: SessionId;\n readonly options: AgentOptions;\n readonly session: Session;\n readonly status: AgentStatus;\n readonly ctx: Context;\n send(content: ContentBlock[], options?: SendOptions): void;\n steer(content: ContentBlock[], options?: SendOptions): void;\n inject(content: ContentBlock[], options?: InjectOptions): void;\n cancel(reason?: string): void;\n whenIdle(): Promise;\n }\n export interface AgentOptions {\n provider?: string;\n model?: string;\n }\n export type AgentStatus = 'idle' | 'running' | 'disposed';\n export type Branded = string & {\n readonly [BRAND]: B;\n };\n export type CallId = Branded<'CallId'>;\n export interface DiffCallView {\n card: 'diff';\n title: string;\n diffs: FileDiff[];\n locations?: FileLocation[];\n }\n export interface DiffResultView {\n card: 'diff';\n title?: string;\n diffs: FileDiff[];\n }\n export interface FileDiff {\n path: string;\n oldText: string | null;\n newText: string;\n }\n export interface FileLocation {\n path: string;\n line?: number;\n }\n export interface GenericCallView {\n card: 'generic';\n title: string;\n kind?: ToolCallKind;\n rawInput?: unknown;\n content?: ContentBlock[];\n locations?: FileLocation[];\n }\n export interface GenericResultView {\n card: 'generic';\n title?: string;\n content?: ContentBlock[];\n }\n export interface HookContext {\n content: ContentBlock[];\n source: MessageSource;\n meta?: JsonValue;\n }\n export interface InjectOptions extends SendOptions {\n meta?: JsonValue;\n }\n export type JsonValue = null | boolean | number | string | JsonValue[] | {\n [key: string]: JsonValue;\n };\n export type MessageSource = MessageSourceMap[keyof MessageSourceMap];\n export interface MessageSourceMap {\n user: {\n kind: 'user';\n };\n plugin: {\n kind: 'plugin';\n plugin: string;\n };\n }\n export type ScopeKey = object;\n export interface SendOptions {\n source?: MessageSource;\n }\n export type SessionId = Branded<'SessionId'>;\n export interface TerminalCallView {\n card: 'terminal';\n title: string;\n description?: string;\n cwd?: string;\n }\n export interface TerminalResultView {\n card: 'terminal';\n title?: string;\n output?: string;\n exitCode?: number;\n signal?: string;\n }\n export type ToolCallKind = 'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'fetch' | 'other';\n export type ToolCallView = GenericCallView | TerminalCallView | DiffCallView;\n export interface ToolDefinition extends ToolSchema {\n execute(args: unknown, exec: ToolRunContext): Promise;\n timeoutMs?: number;\n isConcurrencySafe?(args: unknown): boolean;\n presentCall?(args: unknown): ToolCallView | undefined;\n presentResult?(args: unknown, result: ToolResult): ToolResultView | undefined;\n }\n export interface ToolErrorInfo {\n name: string;\n code: string;\n }\n export type ToolExecuteReturn = ContentBlock[] | {\n content: ContentBlock[];\n meta?: unknown;\n };\n export interface ToolExecution extends ToolExecutionInput {\n readonly token: ToolExecutionToken;\n }\n export interface ToolExecutionInput {\n readonly callId: CallId;\n readonly name: string;\n readonly arguments: unknown;\n readonly agent?: Agent;\n readonly parent?: ToolExecutionToken;\n readonly signal: AbortSignal;\n }\n export type ToolExecutionMode = {\n kind: 'parallel';\n } | {\n kind: 'exclusive';\n };\n export interface ToolExecutionResult {\n content: ContentBlock[];\n isError: boolean;\n error?: ToolErrorInfo;\n additionalContexts?: HookContext[];\n meta?: unknown;\n }\n export type ToolExecutionToken = symbol & {\n readonly [toolExecutionTokenBrand]: true;\n };\n export type ToolGuard = (execution: Readonly) => string | undefined;\n export interface ToolRestriction {\n readonly allow?: readonly string[];\n readonly deny?: readonly string[];\n }\n export interface ToolResult {\n content: ContentBlock[];\n isError: boolean;\n meta?: unknown;\n }\n export type ToolResultView = GenericResultView | TerminalResultView | DiffResultView;\n export interface ToolRunContext extends ToolExecution {\n deferContext(context: HookContext): void;\n }\n export interface ToolSchema {\n name: string;\n description: string;\n parameters: Record;\n }"}}]}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"inspect-tools-api","status":"completed","content":[{"type":"content","content":{"type":"text","text":"## api\n- tools — Tool registry and execution pipeline.\n /**\n * Register globally or in the calling agent scope. Scoped tools shadow\n * globals; duplicates within one layer and the reserved `run_code` name fail.\n * @param definition - the tool schema, execution, and optional presentation functions.\n * @returns the exact disposer that unregisters the tool.\n */\n register(definition: ToolDefinition): () => void\n /**\n * Restrict global tools for the calling agent scope. Empty filters, unknown\n * names, scope-local names, and reserved transport names fail. Restrictions\n * intersect; scoped registrations remain visible.\n * @param filter - global-surface mask: `allow` (keep only) and/or `deny` (remove).\n * @returns the exact disposer that lifts this restriction.\n */\n restrict(filter: ToolRestriction): () => void\n /**\n * Register a monotonic guard after the extensible `tools/pre-execute`\n * waterfall. A plain-context guard applies globally; one registered through\n * `agent.ctx` applies only to that agent. Any matching guard may deny by\n * returning a reason, while no guard can force-allow a call another guard\n * denied. The exact effect disposer is returned for ordered ownership and\n * HMR cleanup.\n * @param guard - synchronous check; a returned string denies the execution.\n * @returns the exact disposer that unregisters the guard.\n */\n guard(guard: ToolGuard): () => void\n /**\n * Look up a tool as one scope sees it (scoped\n * shadows global; a restricted-away global reads as absent). Presenters pass\n * the calling agent so the rendered card matches the definition that\n * actually executed.\n * @param name - the tool name as registered.\n * @param scope - the viewing scope (the agent); omitted = the global view.\n * @returns the definition the scope resolves, or undefined when none is visible.\n */\n get(name: string, scope?: ScopeKey): ToolDefinition | undefined\n /**\n * Project visible definitions onto the allowlisted model-facing schema fields,\n * excluding execution and presentation callbacks.\n * @param scope - the viewing scope (the agent); omitted = the global view.\n * @returns one deep-cloned schema per visible tool.\n */\n schemas(scope?: ScopeKey): ToolSchema[]\n /**\n * Classify a pending call through the caller's visible tool definition. Only\n * an exact `true` is parallel; unknown, hidden, undeclared, invalid, or\n * throwing classifiers are exclusive.\n * @param exec - call name, parsed arguments, and optional agent scope.\n * @returns the fail-closed scheduling mode.\n */\n executionMode(exec: ToolExecutionInput): ToolExecutionMode\n /**\n * Execute through pre-policy, guards, around-dispatch, post-policy, and final\n * notification. Tool and listener failures resolve as materialized error\n * results; an invisible tool reports `UNKNOWN_TOOL`. The returned outcome is\n * the same lossless, frozen snapshot final observers receive. Cancellation\n * arriving after entry and before final result materialization skips a\n * not-yet-started body with `ABORTED_BEFORE_DISPATCH` or replaces a\n * successful started outcome with `ABORTED`; already-started work is still\n * drained and may retain a tool-owned structured error.\n * @param exec - the typed same-process call input. The registry assigns its\n * correlation token before policy begins.\n * @returns the materialized final result.\n */\n async execute(exec: ToolExecutionInput): Promise\ntype shapes (referenced by the signatures above — read these before assuming a field is a string):\n export interface Agent {\n readonly id: SessionId;\n readonly options: AgentOptions;\n readonly session: Session;\n readonly status: AgentStatus;\n readonly ctx: Context;\n send(content: ContentBlock[], options?: SendOptions): void;\n steer(content: ContentBlock[], options?: SendOptions): void;\n inject(content: ContentBlock[], options?: InjectOptions): void;\n cancel(cause?: AgentCancelCause): void;\n whenIdle(): Promise;\n }\n export type AgentCancelCause = {\n readonly kind: 'user';\n } | {\n readonly kind: 'parent';\n };\n export interface AgentOptions {\n provider?: string;\n model?: string;\n }\n export type AgentStatus = 'idle' | 'running' | 'disposed';\n export type Branded = string & {\n readonly [BRAND]: B;\n };\n export type CallId = Branded<'CallId'>;\n export interface DiffCallView {\n card: 'diff';\n title: string;\n diffs: FileDiff[];\n locations?: FileLocation[];\n }\n export interface DiffResultView {\n card: 'diff';\n title?: string;\n diffs: FileDiff[];\n }\n export interface FileDiff {\n path: string;\n oldText: string | null;\n newText: string;\n }\n export interface FileLocation {\n path: string;\n line?: number;\n }\n export interface GenericCallView {\n card: 'generic';\n title: string;\n kind?: ToolCallKind;\n rawInput?: unknown;\n content?: ContentBlock[];\n locations?: FileLocation[];\n }\n export interface GenericResultView {\n card: 'generic';\n title?: string;\n content?: ContentBlock[];\n }\n export interface HookContext {\n content: ContentBlock[];\n source: MessageSource;\n meta?: JsonValue;\n }\n export interface InjectOptions extends SendOptions {\n meta?: JsonValue;\n }\n export type JsonValue = null | boolean | number | string | JsonValue[] | {\n [key: string]: JsonValue;\n };\n export type MessageSource = MessageSourceMap[keyof MessageSourceMap];\n export interface MessageSourceMap {\n user: {\n kind: 'user';\n };\n plugin: {\n kind: 'plugin';\n plugin: string;\n };\n }\n export type ScopeKey = object;\n export interface SendOptions {\n source?: MessageSource;\n }\n export type SessionId = Branded<'SessionId'>;\n export interface TerminalCallView {\n card: 'terminal';\n title: string;\n description?: string;\n cwd?: string;\n }\n export interface TerminalResultView {\n card: 'terminal';\n title?: string;\n output?: string;\n exitCode?: number;\n signal?: string;\n }\n export type ToolCallKind = 'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'fetch' | 'other';\n export type ToolCallView = GenericCallView | TerminalCallView | DiffCallView;\n export interface ToolDefinition extends ToolSchema {\n execute(args: unknown, exec: ToolRunContext): Promise;\n timeoutMs?: number;\n isConcurrencySafe?(args: unknown): boolean;\n presentCall?(args: unknown): ToolCallView | undefined;\n presentResult?(args: unknown, result: ToolResult): ToolResultView | undefined;\n }\n export interface ToolErrorInfo {\n name: string;\n code: string;\n }\n export type ToolExecuteReturn = ContentBlock[] | {\n content: ContentBlock[];\n meta?: unknown;\n };\n export interface ToolExecution extends ToolExecutionInput {\n readonly token: ToolExecutionToken;\n }\n export interface ToolExecutionInput {\n readonly callId: CallId;\n readonly name: string;\n readonly arguments: unknown;\n readonly agent?: Agent;\n readonly parent?: ToolExecutionToken;\n readonly signal: AbortSignal;\n }\n export type ToolExecutionMode = {\n kind: 'parallel';\n } | {\n kind: 'exclusive';\n };\n export interface ToolExecutionResult {\n content: ContentBlock[];\n isError: boolean;\n error?: ToolErrorInfo;\n additionalContexts?: HookContext[];\n meta?: unknown;\n }\n export type ToolExecutionToken = symbol & {\n readonly [toolExecutionTokenBrand]: true;\n };\n export type ToolGuard = (execution: Readonly) => string | undefined;\n export interface ToolRestriction {\n readonly allow?: readonly string[];\n readonly deny?: readonly string[];\n }\n export interface ToolResult {\n content: ContentBlock[];\n isError: boolean;\n meta?: unknown;\n }\n export type ToolResultView = GenericResultView | TerminalResultView | DiffResultView;\n export interface ToolRunContext extends ToolExecution {\n deferContext(context: HookContext): void;\n }\n export interface ToolSchema {\n name: string;\n description: string;\n parameters: Record;\n }"}}]}}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"inspect-tools-event","title":"Inspect cordis runtime: events: tools/pre-execute","kind":"read","status":"in_progress"}}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"inspect-tools-event","status":"completed","content":[{"type":"content","content":{"type":"text","text":"## events\n- tools/pre-execute [waterfall] — Allow, deny, or ask before dispatch.\n /**\n * Allow, deny, or ask before dispatch. `next()` delegates to allow; missing\n * approval support turns `ask` into denial. Async gates must observe\n * `exec.signal`; the registry rechecks cancellation after they settle but\n * never abandons their promise.\n * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent's calls.\n * @param exec - the pending call (name, parsed arguments, caller agent).\n * @mode waterfall\n */\n 'tools/pre-execute'(this: Scoped, exec: ToolExecution, next: () => Promise): Promise\nwaterfall listeners receive a trailing next() and MUST call it to delegate — returning without next() vetoes the chain."}}]}}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"CORDIS_INSPECT_JSDOC_OK"}}}} diff --git a/packages/context/time-context/tests/time-context.spec.ts b/packages/context/time-context/tests/time-context.spec.ts index 06ae13818d..e8eb13b950 100644 --- a/packages/context/time-context/tests/time-context.spec.ts +++ b/packages/context/time-context/tests/time-context.spec.ts @@ -368,7 +368,7 @@ describe('real agent-loop request history', () => { ctx.on('agent/pre-step', (subject) => { laterSawReading = contextTexts(subject.session).length === 1 if (mode === 'throws') throw new Error('later pre-step failure') - subject.cancel('later pre-step cancellation') + subject.cancel({ kind: 'user' }) }) const agent = ctx.agentLoop.create(SessionId(`late-${mode}`), { provider: 'mock', model: 'mock' }) diff --git a/packages/context/workspace-context/tests/workspace-context.spec.ts b/packages/context/workspace-context/tests/workspace-context.spec.ts index 55b4e0bf00..895f715960 100644 --- a/packages/context/workspace-context/tests/workspace-context.spec.ts +++ b/packages/context/workspace-context/tests/workspace-context.spec.ts @@ -1620,7 +1620,7 @@ describe('dynamic nested workspace context injection', () => { description: 'Abort the current test step.', parameters: {}, async execute() { - ;(agent as unknown as { currentAbort?: AbortController }).currentAbort?.abort('test abort') + agent.cancel({ kind: 'user' }) return [{ type: 'text', text: 'aborted' }] }, })) diff --git a/packages/cordis/tool-cordis/src/api-catalog.ts b/packages/cordis/tool-cordis/src/api-catalog.ts index 79690c9ffb..098153dc35 100644 --- a/packages/cordis/tool-cordis/src/api-catalog.ts +++ b/packages/cordis/tool-cordis/src/api-catalog.ts @@ -703,9 +703,9 @@ export const EVENT_API: readonly EventApiEntry[] = [ { name: 'agent/cancel-requested', mode: 'emit', - signature: '\'agent/cancel-requested\'(this: Scoped, agent: Agent, reason: string): void', - jsDoc: '/**\n * Effective broad cancellation was requested, before queued/steering work\n * is cleared or the active step is aborted. This observe-only notification\n * cannot veto cancellation; listener failures are contained.\n * @param agent - the agent whose current work is being cancelled.\n * @param reason - resolved cancellation reason, including the default.\n * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.\n * @mode emit\n */', - summary: 'Effective broad cancellation was requested, before queued/steering work is cleared or the active step is aborted.', + signature: '\'agent/cancel-requested\'(this: Scoped, agent: Agent, cause: AgentCancelCause): void', + jsDoc: '/**\n * Effective broad cancellation was requested, before queued/steering work\n * is cleared or the active turn is aborted. This observe-only notification\n * cannot veto cancellation; listener failures are contained.\n * @param agent - the agent whose current work is being cancelled.\n * @param cause - resolved typed cancellation cause, including the default.\n * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.\n * @mode emit\n */', + summary: 'Effective broad cancellation was requested, before queued/steering work is cleared or the active turn is aborted.', }, { name: 'agent/created', @@ -745,8 +745,8 @@ export const EVENT_API: readonly EventApiEntry[] = [ { name: 'agent/prompt-submit', mode: 'waterfall', - signature: '\'agent/prompt-submit\'(this: Scoped, agent: Agent, content: ContentBlock[], source: MessageSource, next: () => Promise): Promise', - jsDoc: '/**\n * Allow, rewrite, or block one claimed prompt before it becomes a user\n * message. Call `next()` for the unchanged default.\n * @param agent - the agent whose turn claimed the message.\n * @param content - the claimed message\'s blocks, as queued.\n * @param source - the message\'s resolved source.\n * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.\n * @mode waterfall\n */', + signature: '\'agent/prompt-submit\'(this: Scoped, agent: Agent, content: ContentBlock[], source: MessageSource, signal: AbortSignal, next: () => Promise): Promise', + jsDoc: '/**\n * Allow, rewrite, or block one claimed prompt before it becomes a user\n * message. Call `next()` for the unchanged default. The signal controls only\n * this turn; listeners may cooperate with it but must not retain it to\n * control another turn.\n * @param agent - the agent whose turn claimed the message.\n * @param content - the claimed message\'s blocks, as queued.\n * @param source - the message\'s resolved source.\n * @param signal - the current turn\'s explicit abort signal.\n * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.\n * @mode waterfall\n */', summary: 'Allow, rewrite, or block one claimed prompt before it becomes a user message.', }, { @@ -759,8 +759,8 @@ export const EVENT_API: readonly EventApiEntry[] = [ { name: 'agent/request', mode: 'waterfall', - signature: '\'agent/request\'(this: Scoped, agent: Agent, turn: number, step: number, config: LlmCallConfig, next: () => Promise): Promise', - jsDoc: '/**\n * Replace the frozen call configuration. Model-visible content must use\n * logged channels; this seam cannot mutate messages. Injection here joins\n * the next request because the current step boundary is already fixed.\n * @param agent - the agent making the model call.\n * @param turn - the open turn number.\n * @param step - the step whose request this is.\n * @param config - the config the loop would use (frozen); return a replacement to switch.\n * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.\n * @mode waterfall\n */', + signature: '\'agent/request\'(this: Scoped, agent: Agent, turn: number, step: number, config: LlmCallConfig, signal: AbortSignal, next: () => Promise): Promise', + jsDoc: '/**\n * Replace the frozen call configuration. Model-visible content must use\n * logged channels; this seam cannot mutate messages. Injection here joins\n * the next request because the current step boundary is already fixed.\n * @param agent - the agent making the model call.\n * @param turn - the open turn number.\n * @param step - the step whose request this is.\n * @param config - the config the loop would use (frozen); return a replacement to switch.\n * @param signal - the current turn\'s explicit abort signal; ambient\n * initiator identity does not imply liveness or cancellation authority.\n * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.\n * @mode waterfall\n */', summary: 'Replace the frozen call configuration.', }, { @@ -774,7 +774,7 @@ export const EVENT_API: readonly EventApiEntry[] = [ name: 'agent/session-prefix', mode: 'waterfall', signature: '\'agent/session-prefix\'(this: Scoped, agent: Agent, prefix: Message[], signal: AbortSignal, next: () => Promise): Promise', - jsDoc: '/**\n * Compose request-only messages placed before derived history. The frozen\n * result is computed once per loop instance, logged on its anchoring request\n * header, and reused so the provider prefix remains stable. Interrupted\n * composition is discarded. Composition precedes the first `agent/pre-step`\n * and request boundary, so listener appends join the current request.\n * Changing context belongs in history; contributors should prepend to\n * `await next()` to preserve registration order.\n * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.\n * @param agent - the agent whose session prefix is being composed.\n * @param prefix - the frozen seed; return an extended replacement.\n * @param signal - aborts composition when the step is torn down.\n * @mode waterfall\n */', + jsDoc: '/**\n * Compose request-only messages placed before derived history. The frozen\n * result is computed once per loop instance, logged on its anchoring request\n * header, and reused so the provider prefix remains stable. Interrupted\n * composition is discarded. Composition precedes the first `agent/pre-step`\n * and request boundary, so listener appends join the current request.\n * Changing context belongs in history; contributors should prepend to\n * `await next()` to preserve registration order.\n * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.\n * @param agent - the agent whose session prefix is being composed.\n * @param prefix - the frozen seed; return an extended replacement.\n * @param signal - the current turn\'s explicit abort signal.\n * @mode waterfall\n */', summary: 'Compose request-only messages placed before derived history.', }, { @@ -794,22 +794,22 @@ export const EVENT_API: readonly EventApiEntry[] = [ { name: 'agent/step-result', mode: 'waterfall', - signature: '\'agent/step-result\'(this: Scoped, agent: Agent, turn: number, step: number, message: Message, next: () => Promise): Promise', - jsDoc: '/**\n * Waterfall: post-process the assembled assistant {@link Message} before\n * tool dispatch (validation, content rewriting, …).\n * @param agent - the agent that received the step\'s response.\n * @param turn - the open turn number.\n * @param step - the step that produced the message.\n * @param message - the assistant message as assembled from the stream.\n * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.\n * @mode waterfall\n */', + signature: '\'agent/step-result\'(this: Scoped, agent: Agent, turn: number, step: number, message: Message, signal: AbortSignal, next: () => Promise): Promise', + jsDoc: '/**\n * Waterfall: post-process the assembled assistant {@link Message} before\n * tool dispatch (validation, content rewriting, …).\n * @param agent - the agent that received the step\'s response.\n * @param turn - the open turn number.\n * @param step - the step that produced the message.\n * @param message - the assistant message as assembled from the stream.\n * @param signal - the current turn\'s explicit abort signal.\n * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.\n * @mode waterfall\n */', summary: 'Waterfall: post-process the assembled assistant Message before tool dispatch (validation, content rewriting, …).', }, { name: 'agent/turn-continuation', mode: 'waterfall', - signature: '\'agent/turn-continuation\'(this: Scoped, agent: Agent, turn: number, defaultDecision: ContinuationDecision, next: () => Promise): Promise', - jsDoc: '/**\n * Override whether the turn continues. The default continues after tool\n * calls or steering and stops otherwise; a continue reason becomes steering.\n * @param agent - the agent deciding whether to run another step.\n * @param turn - the turn being continued or stopped.\n * @param defaultDecision - what the loop would do absent an override.\n * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.\n * @mode waterfall\n */', + signature: '\'agent/turn-continuation\'(this: Scoped, agent: Agent, turn: number, defaultDecision: ContinuationDecision, signal: AbortSignal, next: () => Promise): Promise', + jsDoc: '/**\n * Override whether the turn continues. The default continues after tool\n * calls or steering and stops otherwise; a continue reason becomes steering.\n * @param agent - the agent deciding whether to run another step.\n * @param turn - the turn being continued or stopped.\n * @param defaultDecision - what the loop would do absent an override.\n * @param signal - the current turn\'s explicit abort signal.\n * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.\n * @mode waterfall\n */', summary: 'Override whether the turn continues.', }, { name: 'agent/turn-stop', mode: 'serial', - signature: '\'agent/turn-stop\'(this: Scoped, agent: Agent, turn: number): ContinuationStop | undefined', - jsDoc: '/**\n * Monotonic terminal-stop checkpoint after continuation and steering are\n * folded; a stop remains authoritative through turn close and flush:\n * steering queued in that window is discarded, while ordinary sends survive.\n * @param agent - the agent whose composed continuation outcome may be stopped.\n * @param turn - the turn at its terminal-stop checkpoint.\n * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.\n * @mode serial\n */', + signature: '\'agent/turn-stop\'(this: Scoped, agent: Agent, turn: number, signal: AbortSignal): Promise | ContinuationStop | undefined', + jsDoc: '/**\n * Monotonic terminal-stop checkpoint after continuation and steering are\n * folded; a stop remains authoritative through turn close and flush:\n * steering queued in that window is discarded, while ordinary sends survive.\n * @param agent - the agent whose composed continuation outcome may be stopped.\n * @param turn - the turn at its terminal-stop checkpoint.\n * @param signal - the current turn\'s explicit abort signal.\n * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.\n * @mode serial\n */', summary: 'Monotonic terminal-stop checkpoint after continuation and steering are folded; a stop remains authoritative through turn close and flush: steering queued in that window is discarded, while ordinary sends survive.', }, { @@ -921,7 +921,7 @@ export const EVENT_API: readonly EventApiEntry[] = [ name: 'system-prompt/assemble', mode: 'waterfall', signature: '\'system-prompt/assemble\'(this: Scoped, assembly: PromptAssembly, context: AssembleContext, next: () => Promise): Promise', - jsDoc: '/**\n * Expert waterfall over the assembled sections, tools, and variables.\n * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): scoped listeners\n * receive only that scope\'s assemblies. The returned value is authoritative.\n * @param assembly - the mutable assembly built from registered providers.\n * @param context - the caller\'s per-assembly context.\n * @mode waterfall\n */', + jsDoc: '/**\n * Expert waterfall over the assembled sections, tools, and variables.\n * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): scoped listeners\n * receive only that scope\'s assemblies. The returned value is authoritative.\n * A supplied signal controls only this explicit assembly request and must not\n * be retained to control later turns.\n * @param assembly - the mutable assembly built from registered providers.\n * @param context - the caller\'s per-assembly context.\n * @mode waterfall\n */', summary: 'Expert waterfall over the assembled sections, tools, and variables.', }, { @@ -1014,7 +1014,11 @@ export const EVENT_API: readonly EventApiEntry[] = [ export const TYPE_API: readonly TypeApiEntry[] = [ { name: 'Agent', - declaration: 'export interface Agent {\n readonly id: SessionId;\n readonly options: AgentOptions;\n readonly session: Session;\n readonly status: AgentStatus;\n readonly ctx: Context;\n send(content: ContentBlock[], options?: SendOptions): void;\n steer(content: ContentBlock[], options?: SendOptions): void;\n inject(content: ContentBlock[], options?: InjectOptions): void;\n cancel(reason?: string): void;\n whenIdle(): Promise;\n}', + declaration: 'export interface Agent {\n readonly id: SessionId;\n readonly options: AgentOptions;\n readonly session: Session;\n readonly status: AgentStatus;\n readonly ctx: Context;\n send(content: ContentBlock[], options?: SendOptions): void;\n steer(content: ContentBlock[], options?: SendOptions): void;\n inject(content: ContentBlock[], options?: InjectOptions): void;\n cancel(cause?: AgentCancelCause): void;\n whenIdle(): Promise;\n}', + }, + { + name: 'AgentCancelCause', + declaration: 'export type AgentCancelCause = {\n readonly kind: \'user\';\n} | {\n readonly kind: \'parent\';\n};', }, { name: 'AgentFactory', @@ -1066,7 +1070,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'AssembleContext', - declaration: 'export interface AssembleContext {\n scope?: ScopeKey;\n}', + declaration: 'export interface AssembleContext {\n scope?: ScopeKey;\n signal?: AbortSignal;\n}', }, { name: 'AssembledSection', @@ -1742,7 +1746,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'TurnEndReasonMap', - declaration: 'export interface TurnEndReasonMap {\n completed: {\n kind: \'completed\';\n };\n aborted: {\n kind: \'aborted\';\n reason?: string;\n };\n error: {\n kind: \'error\';\n step: number;\n } & ({\n failure: LlmFailure;\n message?: never;\n code?: never;\n } | {\n message: string;\n code?: string;\n failure?: never;\n });\n disposed: {\n kind: \'disposed\';\n };\n \'max-tokens\': {\n kind: \'max-tokens\';\n };\n rejected: {\n kind: \'rejected\';\n reason: string;\n };\n interrupted: {\n kind: \'interrupted\';\n };\n}', + declaration: 'export interface TurnEndReasonMap {\n completed: {\n kind: \'completed\';\n };\n aborted: {\n kind: \'aborted\';\n };\n error: {\n kind: \'error\';\n step: number;\n } & ({\n failure: LlmFailure;\n message?: never;\n code?: never;\n } | {\n message: string;\n code?: string;\n failure?: never;\n });\n disposed: {\n kind: \'disposed\';\n };\n \'max-tokens\': {\n kind: \'max-tokens\';\n };\n rejected: {\n kind: \'rejected\';\n reason: string;\n };\n interrupted: {\n kind: \'interrupted\';\n };\n}', }, { name: 'TurnTrigger', diff --git a/packages/core/agent-loop/README.md b/packages/core/agent-loop/README.md index 319a98871c..963a057cf1 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`. Effective cancellation resolves its reason and emits `agent/cancel-requested` before clearing pending work or aborting the current step; notification failures are contained, queued work added by an observer is included in the same broad clear, and idle cancellation emits nothing. Undispatched model tool calls receive synthetic `tool/call` and `ABORTED_BEFORE_DISPATCH` result pairs. 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. An effective `cancel()` emits the typed runtime-only `user | parent` cause before clearing pending work and cooperatively aborting the holder; notification failures cannot veto cancellation, work queued by a notification observer is cleared, work queued by a later abort observer belongs to the next turn, and idle cancellation emits nothing. Durable `turn/end` remains coarse `aborted`; 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 847a15d64f..78f39a7df4 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -8,11 +8,12 @@ import type { Context } from 'cordis' import { agentEvents } from '@deepseek-ai/dsh-agent' -import type { AgentOptions, AgentStatus, HookContext, InjectOptions, SendOptions } 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' import type { ContentBlock, MessageSource } from '@deepseek-ai/dsh-llm' import { snapshotJsonValue, type Session, type SessionId } from '@deepseek-ai/dsh-session' +import { DISPOSED_INTERRUPT_REASON, TurnCancellation } from './cancellation.ts' import { Inbox, type InboxMessage } from './inbox.ts' import { isTurnOpen, lastTurnNumber, runLoop } from './loop.ts' @@ -95,7 +96,7 @@ export function bindReactLoopAgentContext(agent: ReactLoopAgent, ctx: Context): /** * The concrete {@link Agent} implementation owned by the agent-loop plugin. * - * Owns the inbox (queued + steering FIFOs), the per-step AbortController, and + * Owns the inbox (queued + steering FIFOs), turn cancellation, and * the loop driver. Everything observable happens through session events and * the agent/* event taxonomy — plugins never need this class. */ @@ -120,21 +121,14 @@ export class ReactLoopAgent implements Agent { } private _status: AgentStatus = 'idle' - private currentAbort: AbortController | undefined + /** Active turn owner from pre-running publication through durability settlement. */ + private turnCancellation: TurnCancellation | undefined /** Whether runLoop has been installed into {@link done}. */ private driverStarted = false /** Whether registry publication began and status disposal is externally visible. */ private published = false - /** - * Turn-scoped cancel marker, set by {@link cancel} and read/cleared by the - * driver loop (via the LoopHandle) at every point a turn could start or - * continue. Armed ONLY when there is something to cancel (a running turn, an - * in-flight step, or queued/steering work), so an idle no-op cancel cannot - * leave it set to wrongly drop a later prompt. - */ - private cancelRequested = false - /** Pending cancellation reason, preserved even outside an active step signal. */ - private cancelReason = 'cancelled' + /** Cause-less marker for queued work cancelled before the driver installs a turn owner. */ + private preRunCancelled = false private disposed: Promise private resolveDisposed!: () => void /** Resolves when the driver loop has fully exited (tests/disposal). */ @@ -330,29 +324,21 @@ export class ReactLoopAgent implements Agent { } } - cancel(reason?: string): void { - const resolvedReason = reason ?? 'cancelled' - // Arm only for current work; an idle marker would cancel the next prompt. - if (this._status === 'running' || this.currentAbort !== undefined || this.#inbox.hasQueued || this.#inbox.hasSteering) { - this.cancelRequested = true - // Capture the resolved reason for the marker-only windows (pre-step / - // continuation). The mid-step path reads it from abort.signal.reason - // below; the marker path reads it via the LoopHandle's cancelReason(). - this.cancelReason = resolvedReason + cancel(cause?: AgentCancelCause): void { + const resolvedCause = cause ?? { kind: 'user' } + const cancellation = this.turnCancellation + const preRun = cancellation === undefined && (this.#inbox.hasQueued || this.#inbox.hasSteering) + if (cancellation !== undefined || preRun) { + if (preRun) this.preRunCancelled = true // Coordination consumers must update their own state before this call - // clears the inbox or aborts the step. Notification failures are + // clears the inbox or aborts the turn. Notification failures are // contained by the fused dispatcher and cannot veto cancellation. - agentEvents(this.loopCtx, this).emit('agent/cancel-requested', resolvedReason) + agentEvents(this.loopCtx, this).emit('agent/cancel-requested', resolvedCause) } - // Drop all pending queued + steering work (un-started prompts never run; the - // cancelled turn's steering is not re-enqueued). Cleared directly even when - // the loop is parked in waitForQueued — there is no turn to stop and nothing - // left for the parked loop to run, so no wake is needed. + // Clear work already present before abort observers run. A replacement + // synchronously enqueued by an observer belongs to the next turn. this.#inbox.clear() - // Interrupt an in-flight step immediately (the running turn observes the - // abort and ends `aborted`). The marker covers the windows where no step is - // running (pre-step, continuation). - this.currentAbort?.abort(resolvedReason) + cancellation?.request(resolvedCause) } /** @@ -394,14 +380,21 @@ export class ReactLoopAgent implements Agent { inbox: this.#inbox, maxParallelToolCalls: this.maxParallelToolCalls, setStatus: (status) => { this.setStatus(status) }, - setAbort: controller => void (this.currentAbort = controller), + installTurnCancellation: () => { + const cancellation = new TurnCancellation() + this.turnCancellation = cancellation + return cancellation + }, + clearTurnCancellation: (cancellation) => { + /* v8 ignore else -- the driver clears only the exact owner returned by its latest install. */ + if (this.turnCancellation === cancellation) this.turnCancellation = undefined + }, disposed: this.disposed, isDisposed: () => this._status === 'disposed', - isCancelled: () => this.cancelRequested, - cancelReason: () => this.cancelReason, - clearCancel: () => { this.cancelRequested = false }, + isPreRunCancelled: () => this.preRunCancelled, + clearPreRunCancel: () => { this.preRunCancelled = false }, withToolBatch: run => this.withToolBatch(run), - // Pre-start cancellation settles queued-work waiters before publishing idle. + // Pre-run cancellation settles queued-work waiters before publishing idle. settleIdle: () => { this.settleIdleWaiters() }, })) } @@ -419,7 +412,7 @@ export class ReactLoopAgent implements Agent { // internal state that must settle even if a listener throws below. Each // waiter chains `done`, so it resolves only once the loop actually exits. this.settleIdleWaiters() - this.currentAbort?.abort('disposed') + this.turnCancellation?.request(DISPOSED_INTERRUPT_REASON) // An unpublished rollback has no public status lifecycle to announce. // Once publication begins, disposed is part of the agent/status contract. if (this.published) { diff --git a/packages/core/agent-loop/src/cancellation.ts b/packages/core/agent-loop/src/cancellation.ts new file mode 100644 index 0000000000..c3f5430a20 --- /dev/null +++ b/packages/core/agent-loop/src/cancellation.ts @@ -0,0 +1,31 @@ +/** Turn-scoped cancellation ownership for the concrete AgentLoop driver. @module dsh-agent-loop/cancellation */ + +import type { AgentCancelCause } from '@deepseek-ai/dsh-agent' + +/** Stable runtime-only reason used when lifecycle teardown interrupts a turn. */ +export const DISPOSED_INTERRUPT_REASON = Object.freeze({ kind: 'disposed' } as const) + +/** + * Owns the single controller shared by every asynchronous boundary of one turn. + * The first request wins because a later caller must not rewrite the cause + * observed by earlier listeners. + */ +export class TurnCancellation { + readonly #controller = new AbortController() + + /** The explicit signal passed through this turn's execution boundaries. */ + get signal(): AbortSignal { + return this.#controller.signal + } + + /** + * Abort the turn once. + * @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(Object.freeze({ kind: reason.kind })) + return true + } +} diff --git a/packages/core/agent-loop/src/inbox.ts b/packages/core/agent-loop/src/inbox.ts index b26a79a1ef..72c51e44fb 100644 --- a/packages/core/agent-loop/src/inbox.ts +++ b/packages/core/agent-loop/src/inbox.ts @@ -29,7 +29,7 @@ export class Inbox { return this.queuedMessages.length > 0 } - /** True while steering messages are pending — read by `cancel()`'s arm gate and the loop's stop-override check. */ + /** True while steering messages are pending — read by cancellation and the loop's stop-override check. */ get hasSteering(): boolean { return this.steeringMessages.length > 0 } diff --git a/packages/core/agent-loop/src/loop.ts b/packages/core/agent-loop/src/loop.ts index 97a32e2f38..5961a60b15 100644 --- a/packages/core/agent-loop/src/loop.ts +++ b/packages/core/agent-loop/src/loop.ts @@ -9,7 +9,7 @@ import type { Context } from 'cordis' import type { ContentBlock, FinishReason, GenerateOptions, LlmCallConfig, LlmFailure, Message } from '@deepseek-ai/dsh-llm' import { isDeepStrictEqual } from 'node:util' import { BlockAssembler, HarnessError, LlmError, assertNever, deepFreeze, errorChain, llmFailureOf } from '@deepseek-ai/dsh-llm' -import { agentEvents, assembleContextFor } from '@deepseek-ai/dsh-agent' +import { agentEvents, agentInterruptReasonOf, assembleContextFor } from '@deepseek-ai/dsh-agent' import type { AgentEventDispatch, ContinuationDecision, HookContext, PromptDecision, RequestError, RequestErrorDecision } from '@deepseek-ai/dsh-agent' import { canonicalHeader } from '@deepseek-ai/dsh-session' import type { Session, TurnEndReason, TurnTrigger } from '@deepseek-ai/dsh-session' @@ -20,6 +20,7 @@ import type { PromptAssembly } from '@deepseek-ai/dsh-system-prompt' import type {} from '@deepseek-ai/dsh-tools' import { executeToolCalls } from './tool-calls.ts' import type { Inbox } from './inbox.ts' +import type { TurnCancellation } from './cancellation.ts' /** Normalize thrown values while preserving an existing error code. */ function toError(error: unknown): RequestError { @@ -88,6 +89,32 @@ function stepFinishReason(finish: FinishReason): TurnEndReason | undefined { } } +/** Internal control-flow sentinel; durable classification comes only from the turn signal. */ +const TURN_INTERRUPTED = new Error('turn interrupted') + +/** Stop at an explicit cooperative boundary without stringifying the runtime reason. */ +function interruptionCheckpoint(signal: AbortSignal): void { + if (signal.aborted) throw TURN_INTERRUPTED +} + +/** Classify a supported turn interruption, with lifecycle disposal taking precedence. */ +function interruptionTurnEndReason(handle: LoopHandle, signal: AbortSignal): TurnEndReason | undefined { + if (handle.isDisposed()) return { kind: 'disposed' } + const reason = agentInterruptReasonOf(signal) + if (reason === undefined) return undefined + switch (reason.kind) { + case 'user': + case 'parent': + return { kind: 'aborted' } + /* v8 ignore next 2 -- the private holder requests disposed only after lifecycle state flips, which returns above. */ + case 'disposed': + return { kind: 'disposed' } + /* v8 ignore next 2 -- AgentInterruptReason is closed and the public helper filters unsupported reasons. */ + default: + return assertNever(reason, 'AgentInterruptReason') + } +} + /** Mutable agent controls supplied to the loop driver. */ export interface LoopHandle { /** Native-private agent inbox handed to the driver only at internal startup. */ @@ -95,16 +122,17 @@ export interface LoopHandle { /** Maximum parallel-safe calls allowed in one step. */ readonly maxParallelToolCalls: number setStatus(status: 'idle' | 'running'): void - setAbort(controller: AbortController | undefined): void + /** Install a fresh active-turn owner before the running notification. */ + installTurnCancellation(): TurnCancellation + /** 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 isDisposed(): boolean - /** Whether cancellation is pending for the current loop iteration. */ - isCancelled(): boolean - /** Resolved pending-cancellation reason; meaningful only while {@link isCancelled} is true. */ - cancelReason(): string - /** Clear the cancel marker (called once per iteration after the turn returns). */ - clearCancel(): void + /** Whether queued work was cancelled before an active turn owner existed. */ + isPreRunCancelled(): boolean + /** Clear the cause-less pre-run marker without affecting replacement work. */ + clearPreRunCancel(): void /** Settle idle waiters before pre-running cancellation publishes idle. */ settleIdle(): void /** Run an active tool-call batch, accepting post-tool context into the FIFO drained before settlement. */ @@ -119,7 +147,7 @@ export interface LoopHandle { * @param ctx - the plugin context the loop reaches its initiating Agent, * events (agent/…, session/flush), and services (systemPrompt, llm, tools) * through. - * @param handle - the bridge to the agent's mutable state: status/abort setters plus the disposal and cancel-marker reads. + * @param handle - the bridge to status, turn cancellation ownership, disposal, and pre-run cancellation state. * @throws when no initiating Agent is active. */ export async function runLoop(ctx: Context, handle: LoopHandle): Promise { @@ -134,8 +162,8 @@ export async function runLoop(ctx: Context, handle: LoopHandle): Promise { while (!handle.isDisposed()) { // An idle listener can enqueue and cancel replacement work before the next // wait is installed. Consume that empty marker before parking the driver. - if (handle.isCancelled()) { - handle.clearCancel() + if (handle.isPreRunCancelled()) { + handle.clearPreRunCancel() if (!handle.inbox.hasQueued) { handle.settleIdle() handle.setStatus('idle') @@ -148,8 +176,8 @@ export async function runLoop(ctx: Context, handle: LoopHandle): Promise { // Cancellation between wake and `running` skips only the cancelled work; // a replacement prompt still runs before the eventual idle transition. - if (handle.isCancelled()) { - handle.clearCancel() + if (handle.isPreRunCancelled()) { + handle.clearPreRunCancel() if (!handle.inbox.hasQueued) { // Settle before publishing idle: the already-idle path has no status // transition, while an idle listener can register waiters for new work. @@ -159,24 +187,29 @@ export async function runLoop(ctx: Context, handle: LoopHandle): Promise { } } + let cancellation = handle.installTurnCancellation() handle.setStatus('running') - if (handle.isDisposed()) break + if (handle.isDisposed()) { + handle.clearTurnCancellation(cancellation) + break + } // A synchronous `running` listener can cancel before `runTurn`; balance the // status only when no replacement prompt was queued by that listener. - if (handle.isCancelled()) { - handle.clearCancel() + if (cancellation.signal.aborted) { + handle.clearTurnCancellation(cancellation) if (!handle.inbox.hasQueued) { handle.setStatus('idle') continue } + cancellation = handle.installTurnCancellation() } // Idle injection can add a turn, so derive the next number from the log. const turn = lastTurnNumber(session) + 1 let terminalStopped = false try { - terminalStopped = await runTurn(ctx, events, handle, turn, transmission) + 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) @@ -184,11 +217,10 @@ export async function runLoop(ctx: Context, handle: LoopHandle): Promise { try { events.emit('agent/error', turn, 0, err) } catch { /* contained: a throwing agent/error listener must not kill the driver */ } + } finally { + handle.clearTurnCancellation(cancellation) } - // Reset per iteration, including when a prompt arrives during the flush window. - handle.clearCancel() - // Late steering becomes queued input unless terminal policy stopped the turn. for (const message of handle.inbox.drainSteering()) { if (!terminalStopped) handle.inbox.enqueue(message) @@ -200,9 +232,11 @@ export async function runLoop(ctx: Context, handle: LoopHandle): Promise { async function runTurn( ctx: Context, events: AgentEventDispatch, handle: LoopHandle, turn: number, transmission: TransmissionLog, + 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) { @@ -246,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 }) } @@ -256,15 +293,17 @@ async function runTurn( // matter what throws below; the catch + closeTurn guarantee it. A pre-commit // veto leaves no turn/start in the log and therefore owes no turn/end. session.append('turn/start', { turn, trigger }) + interruptionCheckpoint(signal) // The claimed message runs the `agent/prompt-submit` waterfall before it // becomes a `user/message` — a hook can rewrite the prompt or block it. // Recorded INSIDE the turn (after turn/start) so every event is turn-enclosed; // turn/end is now owed, so a throwing prompt-submit listener (the waterfall // throws) is caught below and the turn still closes. const promptDecision = await events.waterfall( - 'agent/prompt-submit', message.content, message.source, + 'agent/prompt-submit', message.content, message.source, signal, () => Promise.resolve({ kind: 'allow' }), ) + interruptionCheckpoint(signal) if (promptDecision.kind === 'block') { session.append('prompt/blocked', { content: message.content, source: message.source, reason: promptDecision.reason }) reason = { kind: 'rejected', reason: promptDecision.reason } @@ -292,53 +331,28 @@ async function runTurn( // the request. drainSteering() - // The step's AbortController exists BEFORE any async pre-step work so a - // dispose() or cancel() — in a synchronous turn-start listener or an - // async listener whose effect fires before we block — always has an armed - // abort to cancel against. isDisposed below covers disposal, which does - // NOT set the cancel marker. Cleared on every exit path below. - const abort = new AbortController() - handle.setAbort(abort) - // Assemble once before pre-step so listener work and the request share one prompt value. - const assembly = await ctx.systemPrompt.assemble(assembleContextFor(agent)) + const assembly = await ctx.systemPrompt.assemble(assembleContextFor(agent, signal)) + interruptionCheckpoint(signal) const fullSystemPrompt = renderPrompt(assembly) - // Cancellation or disposal during assembly ends the turn before any step opens. - if (handle.isCancelled() || handle.isDisposed()) { - handle.setAbort(undefined) - reason = handle.isDisposed() ? { kind: 'disposed' } : { kind: 'aborted', reason: handle.cancelReason() } - break - } - // Compose the request-only prefix once per loop instance before the first // request boundary. It precedes all derived history and is recorded only // in the request header, not as session history. if (transmission.sessionPrefix === undefined) { const emptyPrefix: Message[] = deepFreeze([]) const composed = await events.waterfall( - 'agent/session-prefix', emptyPrefix, abort.signal, + 'agent/session-prefix', emptyPrefix, signal, () => Promise.resolve(emptyPrefix), ) - // Never cache an interrupted composition; the next turn recomposes it. - if (handle.isCancelled() || handle.isDisposed()) { - handle.setAbort(undefined) - reason = handle.isDisposed() ? { kind: 'disposed' } : { kind: 'aborted', reason: handle.cancelReason() } - break - } + interruptionCheckpoint(signal) transmission.sessionPrefix = deepFreeze(structuredClone(composed)) } // Await surface mutations outside the step before snapshotting history. - await events.serial('agent/pre-step', turn, step, abort.signal) - - // Interruption landing during the pre-step seam: do not open an empty step. - if (handle.isCancelled() || handle.isDisposed()) { - handle.setAbort(undefined) - reason = handle.isDisposed() ? { kind: 'disposed' } : { kind: 'aborted', reason: handle.cancelReason() } - break - } + await events.serial('agent/pre-step', turn, step, signal) + interruptionCheckpoint(signal) // Snapshot the exact log prefix before step/start: the reconstruction // boundary. Appends after this synchronous snapshot join the next request. @@ -350,16 +364,8 @@ async function runTurn( // are contained inside Session.append(). stepOpen = true - // Cancel landing in the step-start window: a synchronous `session/event` - // step/start listener can cancel after the step is already open. Check - // AFTER the step/start append and before `runStep`: drop the step, end the - // turn accordingly. closeStep balances the already-appended step/start. - if (handle.isCancelled() || handle.isDisposed()) { - handle.setAbort(undefined) - reason = handle.isDisposed() ? { kind: 'disposed' } : { kind: 'aborted', reason: handle.cancelReason() } - closeStep() - break - } + // A synchronous step/start observer can cancel after the step opened. + interruptionCheckpoint(signal) let stepOutcome: | { hadToolCalls: boolean; finish: FinishReason } @@ -367,7 +373,7 @@ async function runTurn( | { error: RequestError } try { stepOutcome = await runStep( - ctx, events, handle, turn, step, assembly, fullSystemPrompt, boundaryMessages, transmission, abort.signal) + ctx, events, handle, turn, step, assembly, fullSystemPrompt, boundaryMessages, transmission, signal) } catch (error: unknown) { if (error instanceof TerminalModelRequestFailure) { stepOutcome = { requestError: error.requestError, failure: error.failure } @@ -380,11 +386,9 @@ async function runTurn( // Recovery observes a balanced failed step and the original provider // error while the failed step's signal remains the active owner. closeStep() - if (handle.isDisposed() || abort.signal.aborted) { - handle.setAbort(undefined) - reason = handle.isDisposed() - ? { kind: 'disposed' } - : { kind: 'aborted', reason: String(abort.signal.reason) } + const interrupted = interruptionTurnEndReason(handle, signal) + if (interrupted !== undefined) { + reason = interrupted break } @@ -393,7 +397,7 @@ async function runTurn( try { recoveryDecision = await events.waterfall( 'agent/request-error', turn, step, stepOutcome.requestError, - stepOutcome.failure, requestFailureHistory, abort.signal, + stepOutcome.failure, requestFailureHistory, signal, () => Promise.resolve(defaultDecision), ) } catch (recoveryError: unknown) { @@ -401,15 +405,11 @@ async function runTurn( `agent "${agent.id}": request recovery failed at turn ${turn}, step ${step}: ${errorChain(recoveryError)}`, ) } - handle.setAbort(undefined) - // Cancellation and disposal always win over either a recovery decision // or a recovery-listener failure. - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (handle.isDisposed() || abort.signal.aborted) { - reason = handle.isDisposed() - ? { kind: 'disposed' } - : { kind: 'aborted', reason: String(abort.signal.reason) } + const recoveryInterrupted = interruptionTurnEndReason(handle, signal) + if (recoveryInterrupted !== undefined) { + reason = recoveryInterrupted break } switch (recoveryDecision.action) { @@ -431,17 +431,10 @@ async function runTurn( // runLoop re-enqueues it as a queued message, so an abort-then-steer // starts a fresh turn instead of being silently consumed. closeStep() - handle.setAbort(undefined) const { error } = stepOutcome - /* v8 ignore next -- narrow race: disposal while non-request step work throws. */ - if (handle.isDisposed()) { - reason = { kind: 'disposed' } - } else if (abort.signal.aborted) { - /* v8 ignore next -- signal.reason always set: cancel()/disposal provide a default */ - reason = { kind: 'aborted', reason: String(abort.signal.reason ?? 'aborted') } - } else { - failTurn(error) - } + const interrupted = interruptionTurnEndReason(handle, signal) + if (interrupted === undefined) failTurn(error) + else reason = interrupted break } @@ -455,48 +448,40 @@ async function runTurn( const steered = drainSteering() try { - await events.serial('agent/post-step', turn, step, abort.signal) + await events.serial('agent/post-step', turn, step, signal) } catch (error: unknown) { stepOutcome = { error: toError(error) } } if ('error' in stepOutcome) { closeStep() - handle.setAbort(undefined) - /* v8 ignore next -- narrow race: disposal while a post-step listener throws. */ - if (handle.isDisposed()) { - reason = { kind: 'disposed' } - } else if (abort.signal.aborted) { - /* v8 ignore next -- signal.reason always set by cancellation or disposal. */ - reason = { kind: 'aborted', reason: String(abort.signal.reason ?? 'aborted') } - } else { - failTurn(stepOutcome.error) - } + const interrupted = interruptionTurnEndReason(handle, signal) + if (interrupted === undefined) failTurn(stepOutcome.error) + else reason = interrupted break } - if (handle.isDisposed() || abort.signal.aborted) { - reason = handle.isDisposed() - ? { kind: 'disposed' } - : { kind: 'aborted', reason: String(abort.signal.reason) } + const postStepInterrupted = interruptionTurnEndReason(handle, signal) + if (postStepInterrupted !== undefined) { + reason = postStepInterrupted closeStep() - handle.setAbort(undefined) break } closeStep() - handle.setAbort(undefined) const defaultDecision: ContinuationDecision = { action: stepOutcome.hadToolCalls || steered ? 'continue' : 'stop' } let decision: ContinuationDecision try { decision = await events.waterfall( - 'agent/turn-continuation', turn, defaultDecision, + 'agent/turn-continuation', turn, defaultDecision, signal, () => Promise.resolve(defaultDecision), ) + interruptionCheckpoint(signal) } catch (error: unknown) { - // A broken continuation plugin ends the turn, not the loop. - failTurn(toError(error)) + const interrupted = interruptionTurnEndReason(handle, signal) + if (interrupted === undefined) failTurn(toError(error)) + else reason = interrupted break } @@ -512,12 +497,15 @@ async function runTurn( // Terminal policy is monotonic and runs after ordinary continuation folding. let terminalStop = false try { - const stop = await events.serial('agent/turn-stop', turn) + const stop = await events.serial('agent/turn-stop', turn, signal) + interruptionCheckpoint(signal) terminalStop = stop !== undefined } catch (error: unknown) { // A broken terminal policy is an ordinary continuation failure: fail // this turn closed while leaving the driver alive for later turns. - failTurn(toError(error)) + const interrupted = interruptionTurnEndReason(handle, signal) + if (interrupted === undefined) failTurn(toError(error)) + else reason = interrupted break } if (terminalStop) { @@ -527,17 +515,7 @@ async function runTurn( shouldContinue = false } - // The marker catches cancellation after the step controller was cleared. - if (handle.isCancelled()) { - reason = { kind: 'aborted', reason: handle.cancelReason() } - break - } - - if (!shouldContinue || handle.isDisposed()) { - /* v8 ignore next -- disposal during continuation-decision window is a narrow race; error-path disposal is covered elsewhere */ - if (handle.isDisposed()) reason = { kind: 'disposed' } - break - } + if (!shouldContinue) break } // Normal / inline-error loop exit: close the turn. @@ -547,12 +525,9 @@ async function runTurn( const turnStartLogged = session.events.some(e => e.type === 'turn/start' && e.data.turn === turn) if (!turnStartLogged) throw error closeStep() - // Preserve an established disposal reason; otherwise report the failure. - if (handle.isDisposed() && !errorReported) { // eslint-disable-line @typescript-eslint/no-unnecessary-condition - reason = { kind: 'disposed' } - } else { - failTurn(toError(error)) - } + const interrupted = interruptionTurnEndReason(handle, signal) + if (interrupted === undefined) failTurn(toError(error)) + else reason = interrupted closeTurn() } @@ -601,7 +576,10 @@ async function runStep( : { provider: options.provider ?? '', model: options.model ?? '' })) // Listener replacements are recorded in the request header before dispatch. - const config = await events.waterfall('agent/request', turn, step, seedConfig, () => Promise.resolve(seedConfig)) + const config = await events.waterfall( + 'agent/request', turn, step, seedConfig, signal, () => Promise.resolve(seedConfig), + ) + interruptionCheckpoint(signal) if (!config.provider || !config.model) { throw new Error(`agent "${agent.id}" has no provider/model: set AgentOptions.provider and AgentOptions.model or supply both via the agent/request waterfall`) } @@ -638,8 +616,7 @@ async function runStep( const stream = ctx.llm.stream(request) try { for await (const chunk of stream) { - /* v8 ignore next -- signal.reason always set: cancel()/disposal provide a default */ - if (signal.aborted) throw new Error(String(signal.reason ?? 'aborted')) + interruptionCheckpoint(signal) const chunkEvent = session.append('assistant/chunk', { turn, step, chunk }) chunkSeqs.push(chunkEvent.seq) assembler.push(chunk) @@ -649,6 +626,7 @@ async function runStep( if (failure !== undefined && error instanceof Error) throw new TerminalModelRequestFailure(error, failure) throw error } + interruptionCheckpoint(signal) // Normalize failure finish chunks into the same path as thrown stream errors. const stepError = finishError(assembler.finish) @@ -679,9 +657,11 @@ async function runStep( // A rejected result still records the successful provider call without retaining rejected output. const processStepResult = async (assembledContent: ContentBlock[], message: Message): Promise => { try { - return await events.waterfall( - 'agent/step-result', turn, step, message, () => Promise.resolve(message), + const processed = await events.waterfall( + 'agent/step-result', turn, step, message, signal, () => Promise.resolve(message), ) + interruptionCheckpoint(signal) + return processed } catch (error: unknown) { recordAssistantMessage(assembledContent, { ...message, content: [] }, false) throw error diff --git a/packages/core/agent-loop/tests/agent-initiator.spec.ts b/packages/core/agent-loop/tests/agent-initiator.spec.ts index 2946cd23a8..70c02bbeed 100644 --- a/packages/core/agent-loop/tests/agent-initiator.spec.ts +++ b/packages/core/agent-loop/tests/agent-initiator.spec.ts @@ -144,6 +144,80 @@ describe('AgentLoop initiator scope', () => { await ctx.fiber.dispose() }) + it('keeps initiator identity minimal while one explicit signal spans each turn seam', async () => { + const adapter = new MockAdapter([ + toolCallResponse('observe-call', 'observe', {}), + textResponse('first done'), + textResponse('second done'), + ]) + const { ctx } = await harness(adapter) + const agent = ctx.agentLoop.create(SessionId('signal-owner'), { provider: 'mock', model: 'mock' }) + let signals: AbortSignal[] = [] + const capture = (signal: AbortSignal | undefined): void => { + if (signal === undefined) throw new Error('turn seam omitted its explicit signal') + expect(ctx.agents.requireInitiator()).toBe(agent) + signals.push(signal) + } + + ctx.on('system-prompt/assemble', async (_assembly, context, next) => { + if (context.agent === agent) capture(context.signal) + return next() + }) + ctx.on('agent/prompt-submit', async (subject, _content, _source, signal, next) => { + if (subject === agent) capture(signal) + return next() + }) + ctx.on('agent/session-prefix', async (subject, _prefix, signal, next) => { + if (subject === agent) capture(signal) + return next() + }) + ctx.on('agent/pre-step', (subject, _turn, _step, signal) => { + if (subject === agent) capture(signal) + }) + ctx.on('agent/request', async (subject, _turn, _step, _config, signal, next) => { + if (subject === agent) capture(signal) + return next() + }) + ctx.on('agent/step-result', async (subject, _turn, _step, _message, signal, next) => { + if (subject === agent) capture(signal) + return next() + }) + ctx.on('agent/turn-continuation', async (subject, _turn, _decision, signal, next) => { + if (subject === agent) capture(signal) + return next() + }) + ctx.on('agent/turn-stop', (subject, _turn, signal) => { + if (subject === agent) capture(signal) + }) + ctx.tools.register(defineTool({ + name: 'observe', + description: 'observe explicit turn state', + parameters: {}, + execute: async (_args, exec) => { + capture(exec.signal) + return [{ type: 'text', text: 'observed' }] + }, + })) + + const firstIdle = waitForIdle(ctx, agent) + send(agent, 'first') + await firstIdle + const firstSignal = signals[0] + expect(firstSignal).toBeDefined() + expect(new Set([...signals, ...adapter.requests.slice(0, 2).map(request => request.signal!)])).toEqual(new Set([firstSignal])) + + signals = [] + const secondIdle = waitForIdle(ctx, agent) + send(agent, 'second') + await secondIdle + const secondSignal = signals[0] + expect(secondSignal).toBeDefined() + expect(new Set([...signals, adapter.requests[2]!.signal!])).toEqual(new Set([secondSignal])) + expect(secondSignal).not.toBe(firstSignal) + expect(ctx.agents.currentInitiator()).toBeUndefined() + await ctx.fiber.dispose() + }) + it('keeps child setup under the parent boundary and restores the parent while the child driver remains active', async () => { const adapter = new MockAdapter([ toolCallResponse('spawn', 'spawn-child', {}), diff --git a/packages/core/agent-loop/tests/agent.spec.ts b/packages/core/agent-loop/tests/agent.spec.ts index d23b69efb7..2cb3191f83 100644 --- a/packages/core/agent-loop/tests/agent.spec.ts +++ b/packages/core/agent-loop/tests/agent.spec.ts @@ -345,7 +345,7 @@ describe('Agent', () => { expect(settled).toBe(false) await waitForStatus(ctx, agent, 'running') - agent.cancel('done') + agent.cancel({ kind: 'user' }) await idle expect(settled).toBe(true) expect(agent.status).toBe('idle') diff --git a/packages/core/agent-loop/tests/cancel.spec.ts b/packages/core/agent-loop/tests/cancel.spec.ts index 4ab3b009f2..162d3b552a 100644 --- a/packages/core/agent-loop/tests/cancel.spec.ts +++ b/packages/core/agent-loop/tests/cancel.spec.ts @@ -1,9 +1,8 @@ /** * Tests for the queue-aware `Agent.cancel()` primitive. `cancel()` is the broad verb — it - * clears queued + steering work, aborts an in-flight step, and drops a turn about to start — - * whereas a bare step abort (the loop's private `AbortController`) kills only the current step - * and leaves the queue intact. The suite covers every landing window plus marker - * reset and `whenIdle()` quiescence. + * clears queued + steering work, aborts the active turn, and drops work not yet claimed by the + * driver without leaking cancellation into a replacement prompt. The suite covers every landing + * window plus signal reset and `whenIdle()` quiescence. * @module dsh-agent-loop/tests/cancel */ @@ -61,22 +60,22 @@ describe('Agent.cancel()', () => { const agent = ctx.agentLoop.create(SessionId('cancel-event'), { provider: 'mock', model: 'mock' }) const warned = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {}) const seen: string[] = [] - ctx.on('agent/cancel-requested', (subject, reason) => { + ctx.on('agent/cancel-requested', (subject, cause) => { if (subject !== agent) return - seen.push(`first:${reason}`) + seen.push(`first:${cause.kind}`) subject.send([{ type: 'text', text: 'queued by cancel observer' }]) throw new Error('observer failed') }) - ctx.on('agent/cancel-requested', (subject, reason) => { - if (subject === agent) seen.push(`second:${reason}`) + ctx.on('agent/cancel-requested', (subject, cause) => { + if (subject === agent) seen.push(`second:${cause.kind}`) }) send(agent, 'drop me') agent.cancel() await new Promise(resolve => setTimeout(resolve, 30)) - agent.cancel('idle no-op') + agent.cancel({ kind: 'parent' }) - expect(seen).toEqual(['first:cancelled', 'second:cancelled']) + expect(seen).toEqual(['first:user', 'second:user']) expect(userTexts(agent)).toEqual([]) expect(adapter.requests).toHaveLength(0) expect(warned).toHaveBeenCalledWith(expect.stringContaining('agent/cancel-requested')) @@ -89,7 +88,7 @@ describe('Agent.cancel()', () => { // The loop is parked at the idle wait with nothing queued. A cancel here must // NOT arm the marker — otherwise the next legitimate prompt would be dropped. - agent.cancel('nothing to cancel') + agent.cancel({ kind: 'user' }) send(agent, 'real prompt') await waitForIdle(ctx, agent) @@ -108,7 +107,7 @@ describe('Agent.cancel()', () => { // resumed). Cancel in that pre-step window: the queued turn must not run. send(agent, 'drop me first') send(agent, 'drop me second') - agent.cancel('pre-step') + agent.cancel({ kind: 'user' }) // Give the loop a chance to wake and process the cancel. await new Promise(r => setTimeout(r, 30)) @@ -157,7 +156,7 @@ describe('Agent.cancel()', () => { // drops the turn before it runs; the skip path must settle it directly. send(agent, 'q') const idle = agent.whenIdle() - agent.cancel('pre-step') + agent.cancel({ kind: 'user' }) // Must resolve (not hang). A timeout makes the failure a clear test failure. await Promise.race([ @@ -186,7 +185,7 @@ describe('Agent.cancel()', () => { // before its resolved waitForQueued continuation checks cancellation. queueMicrotask(() => { queueMicrotask(() => { - agent.cancel('between turns') + agent.cancel({ kind: 'user' }) cancelled.resolve(undefined) }) }) @@ -236,7 +235,7 @@ describe('Agent.cancel()', () => { ctx.on('agent/error', (subject, _turn, _step, error) => { if (subject !== agent || error.message !== 'first flush failed') return queueMicrotask(() => { - queueMicrotask(() => { agent.cancel('between turns') }) + queueMicrotask(() => { agent.cancel({ kind: 'user' }) }) }) }) @@ -277,7 +276,7 @@ describe('Agent.cancel()', () => { requests: adapter.requests.length, turns: agent.session.events.filter(event => event.type === 'turn/start').length, })) - agent.cancel('idle listener') + agent.cancel({ kind: 'user' }) replacementRegistered.resolve(undefined) }) @@ -307,7 +306,7 @@ describe('Agent.cancel()', () => { ctx.on('agent/status', (subject, status) => { if (subject !== agent || status !== 'idle' || replacementIdle !== undefined) return send(agent, 'cancelled replacement') - agent.cancel('idle listener') + agent.cancel({ kind: 'user' }) send(agent, 'surviving replacement') replacementIdle = agent.whenIdle() replacementRegistered.resolve(undefined) @@ -334,16 +333,16 @@ describe('Agent.cancel()', () => { await new Promise(r => setTimeout(r, 30)) expect(agent.status).toBe('running') send(agent, 'queued tail') - agent.cancel('mid-step') + agent.cancel({ kind: 'user' }) await waitForIdle(ctx, agent) - expect(reasons).toEqual([{ kind: 'aborted', reason: 'mid-step' }]) + expect(reasons).toEqual([{ kind: 'aborted' }]) expect(userTexts(agent)).toEqual(['go']) expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(1) expect(adapter.requests).toHaveLength(1) }) - it('cancel() with no reason defaults to "cancelled" when aborting an in-flight step', async () => { + it('cancel() with no cause defaults to user when aborting an active turn', async () => { const adapter = new MockAdapter(['hang']) const ctx = await harness(adapter) const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) @@ -353,10 +352,10 @@ describe('Agent.cancel()', () => { send(agent, 'go') await new Promise(r => setTimeout(r, 30)) - agent.cancel() // no reason → default 'cancelled' + agent.cancel() await waitForIdle(ctx, agent) - expect(reasons).toEqual([{ kind: 'aborted', reason: 'cancelled' }]) + expect(reasons).toEqual([{ kind: 'aborted' }]) }) it('cancel from an assistant/message observer skips execution but balances replay', async () => { @@ -378,7 +377,7 @@ describe('Agent.cancel()', () => { const agent = ctx.agentLoop.create(SessionId('cancel-after-assistant-message'), { provider: 'mock', model: 'mock' }) const dispose = ctx.on('session/event', (session, event) => { if (session === agent.session && event.type === 'assistant/message') { - agent.cancel('cancelled after assistant message') + agent.cancel({ kind: 'user' }) } }) @@ -390,7 +389,7 @@ describe('Agent.cancel()', () => { dispose() expect(executions).toBe(0) - expect(reasons).toEqual([{ kind: 'aborted', reason: 'cancelled after assistant message' }]) + expect(reasons).toEqual([{ kind: 'aborted' }]) const call = agent.session.events.find(event => event.type === 'tool/call') const result = agent.session.events.find(event => event.type === 'tool/result') expect(call?.type === 'tool/call' ? call.data.callId : undefined).toBe('c1') @@ -407,7 +406,7 @@ describe('Agent.cancel()', () => { .find(block => block.type === 'tool-result') expect(replayedResult).toMatchObject({ toolCallId: 'c1', isError: true }) expect(reasons).toEqual([ - { kind: 'aborted', reason: 'cancelled after assistant message' }, + { kind: 'aborted' }, { kind: 'completed' }, ]) }) @@ -420,7 +419,7 @@ describe('Agent.cancel()', () => { // First turn hangs; cancel it mid-step. send(agent, 'first') await new Promise(r => setTimeout(r, 30)) - agent.cancel('cancel first') + agent.cancel({ kind: 'user' }) await waitForIdle(ctx, agent) // The marker must have been reset after the cancelled turn — a fresh prompt @@ -445,7 +444,7 @@ describe('Agent.cancel()', () => { let streamed = false ctx.on('session/event', (_s, event) => { if (event.type === 'assistant/chunk') streamed = true }) ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next) => { - agent.cancel('from prefix composition') + agent.cancel({ kind: 'user' }) return next() }) @@ -456,7 +455,7 @@ describe('Agent.cancel()', () => { await waitForIdle(ctx, agent) expect(streamed).toBe(false) - expect(reasons).toEqual([{ kind: 'aborted', reason: 'from prefix composition' }]) + expect(reasons).toEqual([{ kind: 'aborted' }]) }) it('disposal from inside the agent/session-prefix waterfall ends the turn disposed (prefix-composition window)', async () => { @@ -508,7 +507,7 @@ describe('Agent.cancel()', () => { ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next): Promise => { compositions += 1 if (compositions === 1) { - agent.cancel('mid-composition') + agent.cancel({ kind: 'user' }) return next() } return [opener, ...await next()] @@ -536,7 +535,7 @@ describe('Agent.cancel()', () => { let streamed = false ctx.on('session/event', (_s, event) => { if (event.type === 'assistant/chunk') streamed = true }) const dispose = ctx.on('session/event', (session, event) => { - if (session === agent.session && event.type === 'turn/start') agent.cancel('from turn-start') + if (session === agent.session && event.type === 'turn/start') agent.cancel({ kind: 'user' }) }) const reasons: TurnEndReason[] = [] @@ -547,10 +546,10 @@ describe('Agent.cancel()', () => { dispose() // No step streamed (the model never ran), and the turn ended aborted with - // the CALLER's reason — the marker carries `cancel(reason)` through even + // the caller's cause — the marker carries `cancel(cause)` through even // though no AbortController observed it in this window. expect(streamed).toBe(false) - expect(reasons).toEqual([{ kind: 'aborted', reason: 'from turn-start' }]) + expect(reasons).toEqual([{ kind: 'aborted' }]) }) it('cancel from a synchronous step/start session-event listener drops the step (post-step-start window)', async () => { @@ -565,7 +564,7 @@ describe('Agent.cancel()', () => { let streamed = false ctx.on('session/event', (_s, event) => { if (event.type === 'assistant/chunk') streamed = true }) const dispose = ctx.on('session/event', (session, event) => { - if (session === agent.session && event.type === 'step/start') agent.cancel('from step-start') + if (session === agent.session && event.type === 'step/start') agent.cancel({ kind: 'user' }) }) const reasons: TurnEndReason[] = [] @@ -575,10 +574,10 @@ describe('Agent.cancel()', () => { await waitForIdle(ctx, agent) dispose() - // No step streamed, the turn ended aborted with the caller's reason, and the + // No step streamed, the turn ended with the coarse aborted outcome, and the // log is balanced (the open step was closed by the cancel branch). expect(streamed).toBe(false) - expect(reasons).toEqual([{ kind: 'aborted', reason: 'from step-start' }]) + expect(reasons).toEqual([{ kind: 'aborted' }]) const types = agent.session.events.map(e => e.type) expect(types.filter(t => t === 'step/start').length).toBe(types.filter(t => t === 'step/end').length) }) @@ -636,11 +635,11 @@ describe('Agent.cancel()', () => { }) let continued = false - ctx.on('agent/turn-continuation', async (subject, _turn, _default, next) => { + ctx.on('agent/turn-continuation', async (subject, _turn, _default, _signal, next) => { if (subject === agent && !continued) { continued = true - agent.cancel('from continuation') - return { action: 'continue' as const } // vote to continue — the post-waterfall marker check must override + agent.cancel({ kind: 'user' }) + return { action: 'continue' as const } } return next() }) @@ -649,10 +648,9 @@ describe('Agent.cancel()', () => { await waitForIdle(ctx, agent) // Only ONE step ran (the second was cancelled in the continuation window), - // and the turn ended aborted with the CALLER's reason (carried by the - // marker, since the finished step's AbortController was already cleared). + // and the shared turn signal classified the durable outcome as aborted. expect(steps).toBe(1) - expect(reasons).toEqual([{ kind: 'aborted', reason: 'from continuation' }]) + expect(reasons).toEqual([{ kind: 'aborted' }]) }) it('cancel from a synchronous agent/status(running) listener drops the turn (window 2)', async () => { @@ -665,7 +663,7 @@ describe('Agent.cancel()', () => { let streamed = false ctx.on('session/event', (_s, event) => { if (event.type === 'assistant/chunk') streamed = true }) const dispose = ctx.on('agent/status', (subject, status) => { - if (subject === agent && status === 'running') agent.cancel('from running listener') + if (subject === agent && status === 'running') agent.cancel({ kind: 'user' }) }) send(agent, 'go') @@ -688,7 +686,7 @@ describe('Agent.cancel()', () => { const dispose = ctx.on('agent/status', (subject, status) => { if (subject !== agent || status !== 'running' || replaced) return replaced = true - agent.cancel('drop A') + agent.cancel({ kind: 'user' }) send(agent, 'B') }) @@ -713,7 +711,7 @@ describe('Agent.cancel()', () => { send(agent, 'A') // queues A (status still idle, loop microtask pending) const idle = agent.whenIdle() // registers a waiter (idle + hasQueued → no fast path) - agent.cancel('drop A') // arms marker, clears A + agent.cancel({ kind: 'user' }) // arms marker, clears A send(agent, 'B') // B races in before the loop resumes // whenIdle() must resolve only after B's turn fully ran — by which point B's user message @@ -736,7 +734,7 @@ describe('Agent.cancel()', () => { // Steer (joins the running turn's steering FIFO), then cancel: the steering // must be dropped, NOT re-enqueued as a new queued turn. agent.steer([{ type: 'text', text: 'steer text' }]) - agent.cancel('cancel with steering') + agent.cancel({ kind: 'user' }) await waitForIdle(ctx, agent) // After the cancelled turn settles, the agent is idle with NO follow-up turn @@ -752,4 +750,228 @@ describe('Agent.cancel()', () => { .flatMap(b => b.type === 'text' ? [b.text] : []) expect(flat).not.toContain('steer text') }) + + it('keeps replacement work queued synchronously by an abort observer', async () => { + const adapter = new MockAdapter(['hang', textResponse('replacement reply')]) + const ctx = await harness(adapter) + const agent = ctx.agentLoop.create(SessionId('abort-observer-replacement'), { provider: 'mock', model: 'mock' }) + + send(agent, 'original') + await expect.poll(() => adapter.requests.length).toBe(1) + const signal = adapter.requests[0]?.signal + if (signal === undefined) throw new Error('model request omitted its turn signal') + signal.addEventListener('abort', () => { send(agent, 'replacement') }, { once: true }) + const idle = waitForIdle(ctx, agent) + agent.cancel({ kind: 'user' }) + await Promise.race([ + idle, + new Promise((_resolve, reject) => { + setTimeout(() => { + reject(new Error(`replacement did not settle: ${JSON.stringify({ + status: agent.status, + requests: adapter.requests.length, + users: userTexts(agent), + events: agent.session.events.map(event => event.type), + })}`)) + }, 1000) + }), + ]) + + expect(adapter.requests).toHaveLength(2) + expect(userTexts(agent)).toEqual(['original', 'replacement']) + const reasons = agent.session.events + .filter(event => event.type === 'turn/end') + .map(event => event.type === 'turn/end' ? event.data.reason : undefined) + expect(reasons).toEqual([{ kind: 'aborted' }, { kind: 'completed' }]) + }) + + it('keeps the first typed cause for an active turn and detaches the runtime reason', async () => { + const adapter = new MockAdapter(['hang']) + const ctx = await harness(adapter) + const agent = ctx.agentLoop.create(SessionId('typed-first-wins'), { provider: 'mock', model: 'mock' }) + const supplied: { kind: 'parent' | 'user' } = { kind: 'parent' } + + send(agent, 'go') + await expect.poll(() => adapter.requests.length).toBe(1) + agent.cancel(supplied) + supplied.kind = 'user' + agent.cancel({ kind: 'user' }) + await waitForIdle(ctx, agent) + + const runtimeReason: unknown = adapter.requests[0]?.signal?.reason + expect(runtimeReason).toEqual({ kind: 'parent' }) + expect(runtimeReason).not.toBe(supplied) + expect(Object.isFrozen(runtimeReason)).toBe(true) + const turnEnd = agent.session.events.findLast(event => event.type === 'turn/end') + expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'aborted' }) + }) + + 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('terminal-cancellation-authority'), { provider: 'mock', model: 'mock' }) + const flushStarted = Promise.withResolvers() + const releaseFlush = Promise.withResolvers() + let abortedDuringTurnEnd: boolean | undefined + let cancelNotifications = 0 + + ctx.on('agent/cancel-requested', (subject) => { + if (subject === agent) cancelNotifications += 1 + }) + 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(cancelNotifications).toBe(0) + 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 () => { + const adapter = new MockAdapter(['hang']) + const ctx = await harness(adapter) + const handle = await ctx.agents.create({ + sessionId: SessionId('cancel-dispose-race'), + agentOptions: { provider: 'mock', model: 'mock' }, + }) + const { agent } = handle + + send(agent, 'go') + await expect.poll(() => adapter.requests.length).toBe(1) + agent.cancel({ kind: 'user' }) + await handle.dispose() + + const turnEnd = agent.session.events.findLast(event => event.type === 'turn/end') + expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'disposed' }) + }) + + it.each([ + 'prompt-submit', + 'system-prompt', + 'session-prefix', + 'pre-step', + 'request', + 'step-result', + 'post-step', + 'turn-continuation', + 'turn-stop', + 'tool', + ] as const)('lets a cooperative %s boundary settle from the explicit turn signal', async (stage) => { + const adapter = new MockAdapter(stage === 'tool' + ? [toolCallResponse('blocked-tool', 'blocked', {})] + : [textResponse('done')]) + const ctx = await harness(adapter) + const agent = ctx.agentLoop.create(SessionId(`cooperative-${stage}`), { provider: 'mock', model: 'mock' }) + const started = Promise.withResolvers() + const blockUntilAbort = async (signal: AbortSignal): Promise => { + started.resolve(undefined) + if (signal.aborted) return + await new Promise((resolve) => { + signal.addEventListener('abort', () => { resolve() }, { once: true }) + }) + } + + switch (stage) { + case 'prompt-submit': + ctx.on('agent/prompt-submit', async (subject, _content, _source, signal, next) => { + if (subject === agent) await blockUntilAbort(signal) + return next() + }) + break + case 'system-prompt': + ctx.on('system-prompt/assemble', async (_assembly, context, next) => { + if (context.agent === agent) { + if (context.signal === undefined) throw new Error('turn assembly omitted its signal') + await blockUntilAbort(context.signal) + } + return next() + }) + break + case 'session-prefix': + ctx.on('agent/session-prefix', async (subject, _prefix, signal, next) => { + if (subject === agent) await blockUntilAbort(signal) + return next() + }) + break + case 'pre-step': + ctx.on('agent/pre-step', async (subject, _turn, _step, signal) => { + if (subject === agent) await blockUntilAbort(signal) + }) + break + case 'request': + ctx.on('agent/request', async (subject, _turn, _step, _config, signal, next) => { + if (subject === agent) await blockUntilAbort(signal) + return next() + }) + break + case 'step-result': + ctx.on('agent/step-result', async (subject, _turn, _step, _message, signal, next) => { + if (subject === agent) await blockUntilAbort(signal) + return next() + }) + break + case 'post-step': + ctx.on('agent/post-step', async (subject, _turn, _step, signal) => { + if (subject !== agent) return + await blockUntilAbort(signal) + throw new Error('post-step failed after cancellation') + }) + break + case 'turn-continuation': + ctx.on('agent/turn-continuation', async (subject, _turn, _decision, signal, next) => { + if (subject === agent) await blockUntilAbort(signal) + return next() + }) + break + case 'turn-stop': + ctx.on('agent/turn-stop', async (subject, _turn, signal) => { + if (subject === agent) await blockUntilAbort(signal) + }) + break + case 'tool': + ctx.tools.register(defineTool({ + name: 'blocked', + description: 'wait for cancellation', + parameters: {}, + execute: async (_args, exec) => { + if (exec.signal === undefined) throw new Error('tool execution omitted its signal') + await blockUntilAbort(exec.signal) + return [{ type: 'text', text: 'cancelled' }] + }, + })) + break + } + + send(agent, 'go') + await started.promise + const idle = waitForIdle(ctx, agent) + agent.cancel({ kind: 'user' }) + await idle + const turnEnd = agent.session.events.findLast(event => event.type === 'turn/end') + expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'aborted' }) + await ctx.fiber.dispose() + }) }) diff --git a/packages/core/agent-loop/tests/contract-regressions.spec.ts b/packages/core/agent-loop/tests/contract-regressions.spec.ts index 3a2ef2c55f..ee69866ea7 100644 --- a/packages/core/agent-loop/tests/contract-regressions.spec.ts +++ b/packages/core/agent-loop/tests/contract-regressions.spec.ts @@ -63,7 +63,7 @@ describe('session log records what agent/step-result actually produced', () => { // Plugin rewrites the message: replaces the text AND adds a tool call. let rewritten = false - ctx.on('agent/step-result', async (_agent, _turn, _step, _message, next) => { + ctx.on('agent/step-result', async (_agent, _turn, _step, _message, _signal, next) => { if (rewritten) return next() rewritten = true return { @@ -204,7 +204,7 @@ describe('successful provider completion survives agent/step-result failure', () }) describe('abort during tool execution ends the turn', () => { - it('balances an aborted tool batch through context, steering, and post-step before closing', async () => { + it('balances a cancelled tool batch through context and post-step before closing', async () => { const adapter = new MockAdapter([ // model asks for two tool calls in one step [ @@ -229,8 +229,7 @@ describe('abort during tool execution ends the turn', () => { [{ type: 'text', text: 'steering before abort' }], { source: { kind: 'plugin', plugin: 'abort-test' } }, ) - // Exercise bare step abort without `cancel()` clearing queued work. - ;(agent as unknown as { currentAbort?: AbortController }).currentAbort?.abort('user interrupt') + agent.cancel({ kind: 'user' }) return [{ type: 'text', text: 'done' }] }, })) @@ -297,12 +296,11 @@ describe('abort during tool execution ends the turn', () => { 'tool/call:c2', 'tool/result:c2:aborted', 'context/message', - 'steering/message', 'agent/post-step', 'step/end', 'turn/end:aborted', ]) - expect(reasons).toEqual([{ kind: 'aborted', reason: 'user interrupt' }]) + expect(reasons).toEqual([{ kind: 'aborted' }]) const calls = agent.session.events.filter(event => event.type === 'tool/call') const results = agent.session.events.filter(event => event.type === 'tool/result') expect(calls.map(event => event.data.callId)).toEqual([CallId('c1'), CallId('c2')]) @@ -330,7 +328,7 @@ describe('abort during tool execution ends the turn', () => { parameters: {}, async execute() { agent.inject([{ type: 'text', text: 'accepted before abort' }], { source: { kind: 'plugin', plugin: 'test' } }) - ;(agent as unknown as { currentAbort?: AbortController }).currentAbort?.abort('user interrupt') + agent.cancel({ kind: 'user' }) return [{ type: 'text', text: 'done' }] }, })) @@ -383,7 +381,7 @@ describe('abort during tool execution ends the turn', () => { description: '', parameters: {}, async execute() { - ;(agent as unknown as { currentAbort?: AbortController }).currentAbort?.abort('user interrupt') + agent.cancel({ kind: 'user' }) return [{ type: 'text', text: 'aborted' }] }, })) @@ -476,7 +474,7 @@ describe('abort during tool execution ends the turn', () => { description: '', parameters: {}, async execute() { - ;(agent as unknown as { currentAbort?: AbortController }).currentAbort?.abort('user interrupt') + agent.cancel({ kind: 'user' }) return [{ type: 'text', text: 'done' }] }, })) @@ -515,7 +513,7 @@ describe('steering from late extension points is never stranded', () => { const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) let steeredOnce = false - ctx.on('agent/turn-continuation', async (_agent, _turn, _decision, next) => { + ctx.on('agent/turn-continuation', async (_agent, _turn, _decision, _signal, next) => { if (!steeredOnce) { steeredOnce = true agent.steer([{ type: 'text', text: 'one more thing' }]) @@ -589,26 +587,6 @@ describe('steering from late extension points is never stranded', () => { expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('too late for this turn') }) - it('steering queued during an aborted step is re-delivered, not silently consumed', async () => { - const adapter = new MockAdapter(['hang', textResponse('recovered')]) - const ctx = await harness(adapter) - const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) - - send(agent, 'go') - await new Promise(r => setTimeout(r, 30)) - agent.steer([{ type: 'text', text: 'redirect' }]) - // Abort ONLY the in-flight step, via its AbortController directly — NOT - // cancel(), which clears the inbox and would drop the queued steering this - // test proves survives a step abort. There is no public step-only abort - // verb (cancel() is the only public stop primitive), so reach the private - // controller the loop registered. - ;(agent as unknown as { currentAbort?: AbortController }).currentAbort?.abort('user interrupt') - await waitForIdle(ctx, agent) - - // a new turn ran with the steering content delivered as a message - expect(adapter.requests).toHaveLength(2) - expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('redirect') - }) }) describe('plugin exceptions are contained', () => { @@ -1582,7 +1560,7 @@ describe('disposal and cancellation during pre-step assembly', () => { send(agent, 'go') await new Promise(r => setTimeout(r, 50)) - agent.cancel('user cancelled during assembly') + agent.cancel({ kind: 'user' }) releaseAssemble() await waitForIdle(ctx, agent) @@ -1594,15 +1572,12 @@ describe('disposal and cancellation during pre-step assembly', () => { expect(e.filter(x => x.type === 'turn/start')).toHaveLength(1) expect(e.filter(x => x.type === 'turn/end')).toHaveLength(1) const turnEnd = e.findLast(x => x.type === 'turn/end') - expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ - kind: 'aborted', - reason: 'user cancelled during assembly', - }) + expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'aborted' }) expect(e.some(x => x.type === 'step/start')).toBe(false) expect(e.some(x => x.type === 'assistant/chunk')).toBe(false) expect(e.some(x => x.type === 'assistant/message')).toBe(false) expect(adapter.requests).toHaveLength(0) - expect(reasons).toEqual([{ kind: 'aborted', reason: 'user cancelled during assembly' }]) + expect(reasons).toEqual([{ kind: 'aborted' }]) }) it('disposal during agent/pre-step seam ends the turn disposed', { timeout: 15000 }, async () => { @@ -1687,7 +1662,7 @@ describe('disposal and cancellation during pre-step assembly', () => { send(agent, 'go') await new Promise(r => setTimeout(r, 30)) - agent.cancel('user cancelled') + agent.cancel({ kind: 'user' }) releasePreStep() await waitForIdle(ctx, agent) @@ -1698,10 +1673,10 @@ describe('disposal and cancellation during pre-step assembly', () => { expect(e.filter(x => x.type === 'turn/start')).toHaveLength(1) expect(e.filter(x => x.type === 'turn/end')).toHaveLength(1) const turnEnd = e.findLast(x => x.type === 'turn/end') - expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'aborted', reason: 'user cancelled' }) + expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'aborted' }) expect(e.some(x => x.type === 'step/start')).toBe(false) expect(e.some(x => x.type === 'assistant/chunk')).toBe(false) - expect(reasons).toEqual([{ kind: 'aborted', reason: 'user cancelled' }]) + expect(reasons).toEqual([{ kind: 'aborted' }]) }) it('disposal during assembly does not leak an LLM call or append assistant/chunk', { timeout: 15000 }, async () => { diff --git a/packages/core/agent-loop/tests/coverage-edges.spec.ts b/packages/core/agent-loop/tests/coverage-edges.spec.ts index ac7f301525..7d4e79238e 100644 --- a/packages/core/agent-loop/tests/coverage-edges.spec.ts +++ b/packages/core/agent-loop/tests/coverage-edges.spec.ts @@ -170,7 +170,7 @@ describe('toError normalization', () => { const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) let threwOnce = false - ctx.on('agent/request', async (_agent, _turn, _step, _options, _next) => { + ctx.on('agent/request', async (_agent, _turn, _step, _options, _signal, _next) => { if (!threwOnce) { threwOnce = true throw { code: 500 } // non-Error throw, goes through runStep catch @@ -200,7 +200,7 @@ describe('coded error data emission', () => { const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) let threwOnce = false - ctx.on('agent/request', async (_agent, _turn, _step, _options, next) => { + ctx.on('agent/request', async (_agent, _turn, _step, _options, _signal, next) => { if (!threwOnce) { threwOnce = true throw new LlmError('server overloaded', 'RATE_LIMIT') diff --git a/packages/core/agent-loop/tests/interception.spec.ts b/packages/core/agent-loop/tests/interception.spec.ts index 83b156b0ef..131c6ffb2d 100644 --- a/packages/core/agent-loop/tests/interception.spec.ts +++ b/packages/core/agent-loop/tests/interception.spec.ts @@ -56,7 +56,7 @@ describe('agent/prompt-submit', () => { const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) const seen: string[] = [] - ctx.on('agent/prompt-submit', async (_agent, content, _source, next) => { + ctx.on('agent/prompt-submit', async (_agent, content, _source, _signal, next) => { seen.push(content.map(b => (b.type === 'text' ? b.text : '')).join('')) return next() }) @@ -182,7 +182,7 @@ describe('agent/prompt-submit', () => { const ctx = await harness(adapter) const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) - ctx.on('agent/prompt-submit', async (_agent, content, _source, next): Promise => { + ctx.on('agent/prompt-submit', async (_agent, content, _source, _signal, next): Promise => { const text = content.map(b => (b.type === 'text' ? b.text : '')).join('') return text === 'secret' ? { kind: 'block', reason: 'policy: no secrets' } : next() }) @@ -497,7 +497,7 @@ describe('agent/turn-continuation (ContinuationDecision)', () => { const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) let forced = false - ctx.on('agent/turn-continuation', async (_agent, _turn, _default, next): Promise => { + ctx.on('agent/turn-continuation', async (_agent, _turn, _default, _signal, next): Promise => { if (!forced) { forced = true return { action: 'continue', reason: { content: [{ type: 'text', text: 'keep going on the goal' }], source: { kind: 'plugin', plugin: 'goal' } } } @@ -662,7 +662,7 @@ describe('worked example: a native hook plugin is just a cordis plugin on the se ) }) // 2. PromptSubmit: block a forbidden prompt, annotate the rest. - ctx.on('agent/prompt-submit', async (_agent, content, _source, next): Promise => { + ctx.on('agent/prompt-submit', async (_agent, content, _source, _signal, next): Promise => { const text = content.map(b => (b.type === 'text' ? b.text : '')).join('') if (text.includes('rm -rf')) return { kind: 'block', reason: 'destructive prompt blocked' } return next() diff --git a/packages/core/agent-loop/tests/loop.spec.ts b/packages/core/agent-loop/tests/loop.spec.ts index dd686edfcb..5eaaa2ea5a 100644 --- a/packages/core/agent-loop/tests/loop.spec.ts +++ b/packages/core/agent-loop/tests/loop.spec.ts @@ -231,7 +231,7 @@ describe('agent loop', () => { assembly.variables['model'] = 'mock' return next() }) - ctx.on('agent/request', async (_agent, _turn, _step, config, _next) => { + ctx.on('agent/request', async (_agent, _turn, _step, config, _signal, _next) => { return { ...config, provider: 'mock', model: 'mock' } }) const agent = ctx.agentLoop.create(SessionId('a-late-model'), {}) @@ -527,7 +527,7 @@ describe('agent loop', () => { let steps = 0 ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ }) - ctx.on('agent/turn-continuation', async (_agent, _turn, _defaultDecision, next) => { + ctx.on('agent/turn-continuation', async (_agent, _turn, _defaultDecision, _signal, next) => { if (steps < 3) return { action: 'continue' as const } return next() }) @@ -566,7 +566,7 @@ describe('agent loop', () => { const ctx = await harness(adapter) const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) - ctx.on('agent/request', async (_agent, _turn, _step, config, _next) => { + ctx.on('agent/request', async (_agent, _turn, _step, config, _signal, _next) => { // The seed is frozen — config is not a mutable per-call knob; a switch // is proposed by returning a replacement, and the loop logs it. expect(Object.isFrozen(config)).toBe(true) @@ -692,10 +692,10 @@ describe('agent loop', () => { // wait until the stream is hanging, then cancel await new Promise(r => setTimeout(r, 30)) expect(agent.status).toBe('running') - agent.cancel('user interrupt') + agent.cancel({ kind: 'user' }) await waitForIdle(ctx, agent) - expect(reasons).toEqual([{ kind: 'aborted', reason: 'user interrupt' }]) + expect(reasons).toEqual([{ kind: 'aborted' }]) }) it('surfaces max-tokens as the turn-end reason when the last step is cut off', async () => { @@ -732,7 +732,7 @@ describe('agent loop', () => { ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ }) // Force exactly one continuation (step 1 → step 2), then defer to default // (step 2 is a plain stop with no tool calls → stops). - ctx.on('agent/turn-continuation', async (_agent, _turn, _defaultDecision, next) => { + ctx.on('agent/turn-continuation', async (_agent, _turn, _defaultDecision, _signal, next) => { if (steps < 2) return { action: 'continue' as const } return next() }) @@ -884,7 +884,7 @@ describe('agent loop', () => { ]]) const ctx = await harness(adapter) let stepResults = 0 - ctx.on('agent/step-result', async (_agent, _turn, _step, message, next) => { + ctx.on('agent/step-result', async (_agent, _turn, _step, message, _signal, next) => { stepResults += 1 expect(message.content).toEqual([{ type: 'text', text: 'partial text' }]) return next() diff --git a/packages/core/agent-loop/tests/request-reconstruction.spec.ts b/packages/core/agent-loop/tests/request-reconstruction.spec.ts index 46cfe3eb56..aad90a7dde 100644 --- a/packages/core/agent-loop/tests/request-reconstruction.spec.ts +++ b/packages/core/agent-loop/tests/request-reconstruction.spec.ts @@ -167,7 +167,7 @@ describe('request stability across the loop', () => { const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) let injected = false - ctx.on('agent/request', async (_agent, _turn, _step, _config, next) => { + ctx.on('agent/request', async (_agent, _turn, _step, _config, _signal, next) => { if (!injected) { injected = true agent.inject([{ type: 'text', text: '[late context]' }], { source: { kind: 'plugin', plugin: 'test' } }) @@ -243,7 +243,7 @@ describe('request stability across the loop', () => { const ctx = await harness(adapter) const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) - ctx.on('agent/request', async (_agent, _turn, _step, _config, next) => { + ctx.on('agent/request', async (_agent, _turn, _step, _config, _signal, next) => { const config = await next() // next() resolves the SAME frozen seed — in-place shaping after // delegation is unrepresentable, so a "mutate what next() returned" @@ -280,7 +280,7 @@ describe('request stability across the loop', () => { send(agent, 'go') await waitForIdle(ctx, agent) ctx.systemPrompt.section({ name: 'extra', order: 2, text: 'now with guidance' }) - ctx.on('agent/request', async (_agent, _turn, _step, config, _next) => ({ ...config, temperature: 0.5, maxTokens: 99, stop: [''] })) + ctx.on('agent/request', async (_agent, _turn, _step, config, _signal, _next) => ({ ...config, temperature: 0.5, maxTokens: 99, stop: [''] })) send(agent, 'again') await waitForIdle(ctx, agent) diff --git a/packages/core/agent-loop/tests/request-recovery.spec.ts b/packages/core/agent-loop/tests/request-recovery.spec.ts index cf87d376ef..1e6bc14548 100644 --- a/packages/core/agent-loop/tests/request-recovery.spec.ts +++ b/packages/core/agent-loop/tests/request-recovery.spec.ts @@ -204,7 +204,7 @@ describe('agent post-step and request-error lifecycle', () => { send(agent) const idle = waitForIdle(ctx, agent) await postStepEntered - agent.cancel('cancelled during max-tokens post-step') + agent.cancel({ kind: 'user' }) await idle expect(agent.session.events.find(event => event.type === 'assistant/message')).toMatchObject({ @@ -212,7 +212,7 @@ describe('agent post-step and request-error lifecycle', () => { }) expect(agent.session.events.at(-1)).toMatchObject({ type: 'turn/end', - data: { reason: { kind: 'aborted', reason: 'cancelled during max-tokens post-step' } }, + data: { reason: { kind: 'aborted' } }, }) }) @@ -587,7 +587,7 @@ describe('agent post-step and request-error lifecycle', () => { const idle = waitForIdle(ctx, agent) await recoveryEntered if (action === 'cancel') { - agent.cancel('cancelled during recovery') + agent.cancel({ kind: 'user' }) await idle } else { await ctx.fiber.dispose() @@ -596,7 +596,7 @@ describe('agent post-step and request-error lifecycle', () => { expect(adapter.requests).toHaveLength(1) expect(agent.session.events.at(-1)).toMatchObject({ type: 'turn/end', - data: { reason: action === 'cancel' ? { kind: 'aborted', reason: 'cancelled during recovery' } : { kind: 'disposed' } }, + data: { reason: action === 'cancel' ? { kind: 'aborted' } : { kind: 'disposed' } }, }) }) }) diff --git a/packages/core/agent-loop/tests/resume.spec.ts b/packages/core/agent-loop/tests/resume.spec.ts index 0547388d96..ed81db1293 100644 --- a/packages/core/agent-loop/tests/resume.spec.ts +++ b/packages/core/agent-loop/tests/resume.spec.ts @@ -193,7 +193,7 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume', order.push('agent/created') }) ctx.on('agent/session-start', (agent) => { - expect(() => { agent.cancel('now live') }).not.toThrow() + expect(() => { agent.cancel({ kind: 'user' }) }).not.toThrow() order.push('agent/session-start') }) diff --git a/packages/core/agent-loop/tests/tool-calls.spec.ts b/packages/core/agent-loop/tests/tool-calls.spec.ts index 9619171a21..35985c9185 100644 --- a/packages/core/agent-loop/tests/tool-calls.spec.ts +++ b/packages/core/agent-loop/tests/tool-calls.spec.ts @@ -461,7 +461,7 @@ describe('tool-call scheduler: abort handling', () => { const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) ctx.on('session/event', (session, event) => { if (session === agent.session && event.type === 'assistant/message') { - ;(agent as unknown as { currentAbort?: AbortController }).currentAbort?.abort('already aborted') + agent.cancel({ kind: 'user' }) } }) @@ -492,7 +492,7 @@ describe('tool-call scheduler: abort handling', () => { const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) ctx.on('tools/pre-execute', async (exec, next): Promise => { if (exec.callId === CallId('c1')) { - ;(agent as unknown as { currentAbort?: AbortController }).currentAbort?.abort('pre cancelled') + agent.cancel({ kind: 'user' }) } return next() }) @@ -529,7 +529,7 @@ describe('tool-call scheduler: abort handling', () => { agent.send([{ type: 'text', text: 'go' }]) await until(() => gated.started.length === 2) - ;(agent as unknown as { currentAbort?: AbortController }).currentAbort?.abort('stop now') + agent.cancel({ kind: 'user' }) gated.release('1') gated.release('2') await waitForIdle(ctx, agent) @@ -575,7 +575,7 @@ describe('tool-call scheduler: abort handling', () => { agent.send([{ type: 'text', text: 'go' }]) await until(() => gated.started.length === 2) - ;(agent as unknown as { currentAbort?: AbortController }).currentAbort?.abort('stop before barrier') + agent.cancel({ kind: 'user' }) gated.release('1') gated.release('2') await waitForIdle(ctx, agent) diff --git a/packages/core/agent-loop/tests/turn-stop.spec.ts b/packages/core/agent-loop/tests/turn-stop.spec.ts index 355e1e8e3d..7632a247ef 100644 --- a/packages/core/agent-loop/tests/turn-stop.spec.ts +++ b/packages/core/agent-loop/tests/turn-stop.spec.ts @@ -50,7 +50,7 @@ describe('agent/turn-stop', () => { agent.ctx.on('agent/turn-stop', (): ContinuationStop => ({ action: 'stop' })) let steered = false - ctx.on('agent/turn-continuation', async (subject, _turn, _default, next) => { + ctx.on('agent/turn-continuation', async (subject, _turn, _default, _signal, next) => { const downstream = await next() if (subject === agent && !steered) { steered = true diff --git a/packages/core/agent/README.md b/packages/core/agent/README.md index 72de35107b..137e14495c 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. `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. Effective broad cancellation first emits the observe-only `agent/cancel-requested` with its resolved reason, then clears queues and aborts; notification failures are contained and cannot veto the stop. The full rationale for scoped dispatch and terminal settlement is in 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). +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. Effective broad cancellation first emits the observe-only `agent/cancel-requested` with its resolved typed cause, then clears queues and aborts; notification failures are contained and cannot veto the stop. 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. Omitting `options.source` attests direct human input as `{ kind: 'user' }` and may authorize policy consumers, so plugins, schedulers, and other non-human producers provide their own source. 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(reason?)` — cancel ALL pending work: an effective call emits `agent/cancel-requested` before it clears the queued + steering FIFOs, aborts the in-flight step, and drops a turn about to start (the pre-step window). Observers may synchronize their own state but cannot veto cancellation. A UI/ACP `session/cancel` maps to this. The single public stop primitive. Idle with nothing pending → a safe no-op with no notification. +- `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. An effective call emits `agent/cancel-requested` with the cause before clearing queued and steering work; observers may synchronize state but cannot veto cancellation. The same-process typed seam adds no runtime validation or compatibility fallback for untyped callers. Repeated active-turn cancellation is first-wins for the signal, and idle cancellation is a safe no-op with no notification. 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 new file mode 100644 index 0000000000..708009b456 --- /dev/null +++ b/packages/core/agent/src/cancellation.ts @@ -0,0 +1,30 @@ +/** Runtime reason inspection for explicit turn cancellation. @module @deepseek-ai/dsh-agent/cancellation */ + +import type { AgentInterruptReason } from './types.ts' + +/** + * Read a supported agent interruption from an explicitly supplied signal. + * Unknown reasons return `undefined`; ambient initiator identity does not grant + * cancellation authority. + * @param signal - the current turn's explicit control signal. + * @returns its canonical reason, or `undefined` while live or unsupported. + */ +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)) 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' }) + default: + return undefined + } +} diff --git a/packages/core/agent/src/dispatch.ts b/packages/core/agent/src/dispatch.ts index 9d024d36be..8ce018c16b 100644 --- a/packages/core/agent/src/dispatch.ts +++ b/packages/core/agent/src/dispatch.ts @@ -115,8 +115,9 @@ export function agentEvents(ctx: Context, agent: Agent): AgentEventDispatch { * Build the prompt assembly context with agent and scope set together, so * agent-scoped prompt and tool contributions cannot be silently omitted. * @param agent - the agent the assembly is for. + * @param signal - the current turn's explicit control signal, when assembly belongs to a turn. * @returns the context to pass to `assemble()`. */ -export function assembleContextFor(agent: Agent): AssembleContext { - return { agent, scope: agent } +export function assembleContextFor(agent: Agent, signal?: AbortSignal): AssembleContext { + return { agent, scope: agent, ...signal === undefined ? {} : { signal } } } diff --git a/packages/core/agent/src/index.ts b/packages/core/agent/src/index.ts index 061ddae53f..2f5b525525 100644 --- a/packages/core/agent/src/index.ts +++ b/packages/core/agent/src/index.ts @@ -15,6 +15,7 @@ import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session' import type { Agent, AgentOptions } from './types.ts' export * from './types.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 e0ba54a60d..e653c315b5 100644 --- a/packages/core/agent/src/types.ts +++ b/packages/core/agent/src/types.ts @@ -86,6 +86,14 @@ export type ContinuationStop = Extract /** Why a session lifecycle began; seeded creates are `startup`, while persisted loads are `resume`. */ export type SessionStartSource = 'startup' | 'resume' | 'clear' | 'compact' +/** Stable runtime cause accepted by {@link Agent.cancel}. */ +export type AgentCancelCause = + | { readonly kind: 'user' } + | { readonly kind: 'parent' } + +/** Runtime reason carried by the signal that controls one live turn. */ +export type AgentInterruptReason = AgentCancelCause | { readonly kind: 'disposed' } + /** Public agent handle; its concrete implementation is internal to `@deepseek-ai/dsh-agent-loop`. */ export interface Agent { /** The single identity shared with {@link session}. */ @@ -125,12 +133,14 @@ export interface Agent { /** * Clear all queued and steering work, including items waiting to start, and - * abort the active step. An effective call first emits `agent/cancel-requested` - * with the resolved reason. That reason is preserved across pre-step and active - * cancellation windows, and `whenIdle()` resolves after cancellation reaches - * quiescence. Idle cancellation is a no-op and does not arm a later cancel. + * abort the active turn. An effective call first emits + * `agent/cancel-requested` with the resolved typed cause. The first cause wins + * for the active turn, and `whenIdle()` resolves after cancellation reaches + * quiescence. Omission means `{ kind: 'user' }`. Idle cancellation is a no-op + * and does not arm later work. The active turn snapshots and freezes the cause. + * @param cause - the stable caller intent carried by the current turn signal. */ - cancel(reason?: string): void + cancel(cause?: AgentCancelCause): void /** Resolve at idle quiescence; disposal waits for driver exit rather than only the status transition. */ whenIdle(): Promise @@ -181,14 +191,14 @@ declare module 'cordis' { 'agent/queued'(this: Scoped, agent: Agent, content: ContentBlock[], info: { source: MessageSource; steering: boolean }): void /** * Effective broad cancellation was requested, before queued/steering work - * is cleared or the active step is aborted. This observe-only notification + * is cleared or the active turn is aborted. This observe-only notification * cannot veto cancellation; listener failures are contained. * @param agent - the agent whose current work is being cancelled. - * @param reason - resolved cancellation reason, including the default. + * @param cause - resolved typed cancellation cause, including the default. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. * @mode emit */ - 'agent/cancel-requested'(this: Scoped, agent: Agent, reason: string): void + 'agent/cancel-requested'(this: Scoped, agent: Agent, cause: AgentCancelCause): void // ---- session lifecycle (emit) ---- /** @@ -220,14 +230,17 @@ declare module 'cordis' { 'agent/pre-step'(this: Scoped, agent: Agent, turn: number, step: number, signal: AbortSignal): Promise | void /** * Allow, rewrite, or block one claimed prompt before it becomes a user - * message. Call `next()` for the unchanged default. + * message. Call `next()` for the unchanged default. The signal controls only + * this turn; listeners may cooperate with it but must not retain it to + * control another turn. * @param agent - the agent whose turn claimed the message. * @param content - the claimed message's blocks, as queued. * @param source - the message's resolved source. + * @param signal - the current turn's explicit abort signal. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. * @mode waterfall */ - 'agent/prompt-submit'(this: Scoped, agent: Agent, content: ContentBlock[], source: MessageSource, next: () => Promise): Promise + 'agent/prompt-submit'(this: Scoped, agent: Agent, content: ContentBlock[], source: MessageSource, signal: AbortSignal, next: () => Promise): Promise /** * Replace the frozen call configuration. Model-visible content must use * logged channels; this seam cannot mutate messages. Injection here joins @@ -236,10 +249,12 @@ declare module 'cordis' { * @param turn - the open turn number. * @param step - the step whose request this is. * @param config - the config the loop would use (frozen); return a replacement to switch. + * @param signal - the current turn's explicit abort signal; ambient + * initiator identity does not imply liveness or cancellation authority. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. * @mode waterfall */ - 'agent/request'(this: Scoped, agent: Agent, turn: number, step: number, config: LlmCallConfig, next: () => Promise): Promise + 'agent/request'(this: Scoped, agent: Agent, turn: number, step: number, config: LlmCallConfig, signal: AbortSignal, next: () => Promise): Promise /** * Compose request-only messages placed before derived history. The frozen * result is computed once per loop instance, logged on its anchoring request @@ -251,7 +266,7 @@ declare module 'cordis' { * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. * @param agent - the agent whose session prefix is being composed. * @param prefix - the frozen seed; return an extended replacement. - * @param signal - aborts composition when the step is torn down. + * @param signal - the current turn's explicit abort signal. * @mode waterfall */ 'agent/session-prefix'(this: Scoped, agent: Agent, prefix: Message[], signal: AbortSignal, next: () => Promise): Promise @@ -262,10 +277,11 @@ declare module 'cordis' { * @param turn - the open turn number. * @param step - the step that produced the message. * @param message - the assistant message as assembled from the stream. + * @param signal - the current turn's explicit abort signal. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. * @mode waterfall */ - 'agent/step-result'(this: Scoped, agent: Agent, turn: number, step: number, message: Message, next: () => Promise): Promise + 'agent/step-result'(this: Scoped, agent: Agent, turn: number, step: number, message: Message, signal: AbortSignal, next: () => Promise): Promise /** * Awaited serial checkpoint after the response, real or synthetic tool * results, injected context, and steering are durable but before `step/end`. @@ -299,20 +315,22 @@ declare module 'cordis' { * @param agent - the agent deciding whether to run another step. * @param turn - the turn being continued or stopped. * @param defaultDecision - what the loop would do absent an override. + * @param signal - the current turn's explicit abort signal. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. * @mode waterfall */ - 'agent/turn-continuation'(this: Scoped, agent: Agent, turn: number, defaultDecision: ContinuationDecision, next: () => Promise): Promise + 'agent/turn-continuation'(this: Scoped, agent: Agent, turn: number, defaultDecision: ContinuationDecision, signal: AbortSignal, next: () => Promise): Promise /** * Monotonic terminal-stop checkpoint after continuation and steering are * folded; a stop remains authoritative through turn close and flush: * steering queued in that window is discarded, while ordinary sends survive. * @param agent - the agent whose composed continuation outcome may be stopped. * @param turn - the turn at its terminal-stop checkpoint. + * @param signal - the current turn's explicit abort signal. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. * @mode serial */ - 'agent/turn-stop'(this: Scoped, agent: Agent, turn: number): ContinuationStop | undefined + 'agent/turn-stop'(this: Scoped, agent: Agent, turn: number, signal: AbortSignal): Promise | ContinuationStop | undefined // ---- error notifications (emit) ---- /** diff --git a/packages/core/agent/tests/agent.spec.ts b/packages/core/agent/tests/agent.spec.ts index 5d79d1a91f..509ad14a22 100644 --- a/packages/core/agent/tests/agent.spec.ts +++ b/packages/core/agent/tests/agent.spec.ts @@ -2,9 +2,12 @@ import { describe, expect, expectTypeOf, it } from 'vitest' import { Context, Service, symbols } from 'cordis' import type { Events } from 'cordis' import { Session, SessionId } from '@deepseek-ai/dsh-session' -import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { + agentEvents, + agentInterruptReasonOf, +} 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) @@ -23,12 +26,12 @@ function stubAgent(rawId: string): Agent { } describe('AgentRegistry', () => { - it('keeps terminal stop decisions synchronous', () => { + it('allows terminal stop policy to cooperate asynchronously with turn cancellation', () => { type TurnStopListener = Events['agent/turn-stop'] type AsyncTurnStopListener = () => Promise - expectTypeOf().not.toExtend() - expectTypeOf>().toEqualTypeOf() + expectTypeOf().toExtend() + expectTypeOf>>().toEqualTypeOf() }) it('registers exact entries, emits lifecycle events, and unregisters on owner disposal', async () => { @@ -182,6 +185,40 @@ describe('agentEvents()', () => { }) }) +describe('explicit cancellation helpers', () => { + it('exposes the closed typed cancellation cause at the Agent seam', () => { + expectTypeOf[0]>().toEqualTypeOf() + expectTypeOf[1]>().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() + + 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' })) + const disposedReason = agentInterruptReasonOf(disposed.signal) + expect(disposedReason).toEqual({ kind: 'disposed' }) + expect(Object.isFrozen(disposedReason)).toBe(true) + + 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() + }) +}) + describe('AgentRegistry factory seam', () => { function stubFactory() { const calls: { diff --git a/packages/core/session/README.md b/packages/core/session/README.md index 28210e8f6c..f848909444 100644 --- a/packages/core/session/README.md +++ b/packages/core/session/README.md @@ -66,6 +66,8 @@ Merge-extensible via `SessionEventMap` — a plugin declaration-merges its own t Also defines `TurnTriggerMap` and `TurnEndReasonMap` (merge-extensible sum types for typed turn boundaries — `kind`-tagged instead of strings). A final model-request error retains one structured `LlmFailure`; other turn errors retain message/code, and both identify the failed step. +An interrupted live turn ends with the coarse `{ kind: 'aborted' }` outcome. Caller identity belongs to the Agent's runtime cancellation signal rather than the durable transcript; disposal remains the separate `{ kind: 'disposed' }` terminal state. + Every `SessionEvent` carries two optional top-level fields (structural metadata): - `sourceEventSeqs?: number[]` — seq numbers of provenance sources (e.g., the `assistant/chunk` seqs behind an `assistant/message`, or the shadowed entries behind a compaction replacement entry). On `assistant/message`, a present `[]` records a known empty provider stream, while omission means legacy or otherwise unrecorded provenance; other surface events require a non-empty list when this field is present. @@ -78,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/src/types.ts b/packages/core/session/src/types.ts index ea0ad55a51..6deed3a302 100644 --- a/packages/core/session/src/types.ts +++ b/packages/core/session/src/types.ts @@ -101,7 +101,8 @@ export type TurnTrigger = TurnTriggerMap[keyof TurnTriggerMap] */ export interface TurnEndReasonMap { completed: { kind: 'completed' } - aborted: { kind: 'aborted'; reason?: string } + /** A cancellation request interrupted the live turn. */ + aborted: { kind: 'aborted' } /** * The turn failed: a step threw or the model reported a failure. `step` is the * step number the failure occurred on (the operational error's location — the diff --git a/packages/core/session/tests/fork.spec.ts b/packages/core/session/tests/fork.spec.ts index 5344449078..921232d724 100644 --- a/packages/core/session/tests/fork.spec.ts +++ b/packages/core/session/tests/fork.spec.ts @@ -102,7 +102,7 @@ describe('SessionStore.fork', () => { const { ctx, sessions } = await setup() const reasons: TurnEndReason[] = [ { kind: 'completed' }, - { kind: 'aborted', reason: 'cancelled by user' }, + { kind: 'aborted' }, { kind: 'error', step: 1, message: 'model failed', code: 'MODEL' }, { kind: 'disposed' }, { kind: 'max-tokens' }, diff --git a/packages/core/session/tests/session.spec.ts b/packages/core/session/tests/session.spec.ts index a17981146d..0aef29b9a9 100644 --- a/packages/core/session/tests/session.spec.ts +++ b/packages/core/session/tests/session.spec.ts @@ -48,6 +48,32 @@ describe('Session', () => { expect(structuredClone(turnEnd.data.reason)).toEqual({ kind: 'max-tokens' }) }) + it('round-trips the coarse aborted turn outcome', () => { + const session = new Session(SessionId('aborted')) + session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } }) + session.append('turn/end', { turn: 1, reason: { kind: 'aborted' } }) + const replayed = new Session(SessionId('aborted-replay'), structuredClone(session.events)) + expect(replayed.events).toEqual(session.events) + const turnEnd = replayed.events.findLast(event => event.type === 'turn/end') + 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/core/system-prompt/README.md b/packages/core/system-prompt/README.md index 5c5c554351..65e8f3e590 100644 --- a/packages/core/system-prompt/README.md +++ b/packages/core/system-prompt/README.md @@ -16,7 +16,7 @@ System prompt assembly registry. Plugins contribute ordered sections, tool schem - `ctx.systemPrompt.section(section: PromptSection): () => void` Contribute a section. The layer is the calling context's scope: `agent.ctx` contributes to that agent alone, shadowing a same-named global section there. Duplicate names within one layer and non-finite orders throw. Disposed with the calling fiber. - `ctx.systemPrompt.tools(provider: (context: AssembleContext) => ToolProviderResult): () => void` Contribute tool schemas, evaluated at each assembly with that assembly's context. `ToolProviderResult` = `{ schemas, knownNames? }`: `schemas` is the post-restriction visible set; `knownNames` is the pre-restriction universe used by `toolOrder`. A provider must not return a schema named `TOOL_ORDER_REST`. Scoped providers are consulted only for their scope's assemblies. Disposed with the calling fiber. - `ctx.systemPrompt.variable(name: string, provider: (context) => string | undefined): () => void` Contribute a prompt variable, referenced from section text as `{{name}}`. Scoped variables shadow a same-named global for that agent. Duplicate-in-layer or unreferenceable names throw; `undefined` means "no value for this assembly". Disposed with the calling fiber. -- `ctx.systemPrompt.assemble(context?: AssembleContext): Promise` Assemble the prompt for one caller: the global layer merged with `context.scope`'s layer, with tool schemas detached before the transform seam. Runs through the scope-filtered `system-prompt/assemble` waterfall and returns its authoritative result. Rejects when a configured `toolOrder` names a tool outside the providers' `knownNames` universe, or when a provider returns the reserved rest-entry name. +- `ctx.systemPrompt.assemble(context?: AssembleContext): Promise` Assemble the prompt for one caller: the global layer merged with `context.scope`'s layer, with tool schemas detached before the transform seam. Runs through the scope-filtered `system-prompt/assemble` waterfall and returns its authoritative result. An optional `context.signal` explicitly controls this assembly request; providers and listeners may cooperate with it but must not retain it for another turn. Rejects when a configured `toolOrder` names a tool outside the providers' `knownNames` universe, or when a provider returns the reserved rest-entry name. ### Live events @@ -24,7 +24,7 @@ System prompt assembly registry. Plugins contribute ordered sections, tool schem ### Key types -- `AssembleContext` — what one `assemble()` call is FOR. Merge-extensible; declares `scope?: ScopeKey` (the layer selector) here, and `dsh-agent` declares `agent?: Agent` (the typed DX field — never set without `scope`; use `assembleContextFor(agent)`). Providers must tolerate absent fields (a bare `assemble()` carries an empty, scope-less context). +- `AssembleContext` — what one `assemble()` call is FOR. Merge-extensible; declares `scope?: ScopeKey` (the layer selector) and `signal?: AbortSignal` (the explicit request control capability) here, while `dsh-agent` declares `agent?: Agent` (the typed DX field — never set without `scope`; use `assembleContextFor(agent, signal)`). Providers must tolerate absent fields because a bare `assemble()` carries an empty, scope-less, signal-less context. `signal` is a request value, not part of the ambient Agent execution frame. - `PromptSection` — `{ name, order, text }`. Sections are concatenated in ascending `order`. Order bands: `-100` is the harness identity, `0` the deployment persona, tool guidance uses `100–199`. - `PromptAssembly` — `{ sections: AssembledSection[], tools: ToolSchema[], variables: Record }`. Section texts arrive resolved but not yet interpolated; `variables` holds every registered variable resolved against the context. Tool schemas are part of the assembly by design: "what the model is told it can do" is one coherent thing, even though adapters transmit schemas as a separate wire field. - `renderPrompt(assembly)` — interpolates `{{variable}}` references in each section, drops empty sections, joins with blank lines. STRICT: an unknown reference (`Object.hasOwn` lookup — prototype names like `{{constructor}}` are unknown), a registered-but-valueless reference, a malformed complete `{{…}}` group, or a `{{` that opens no complete group while a `}}` still follows (`{{{model}}}`) throws — fail loud beats shipping a malformed prompt. A lone `{{` with no `}}` anywhere after it passes through verbatim; substituted values are never re-scanned. diff --git a/packages/core/system-prompt/src/index.ts b/packages/core/system-prompt/src/index.ts index 5eb66d95f8..12171f1b2e 100644 --- a/packages/core/system-prompt/src/index.ts +++ b/packages/core/system-prompt/src/index.ts @@ -20,6 +20,8 @@ declare module 'cordis' { * Expert waterfall over the assembled sections, tools, and variables. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): scoped listeners * receive only that scope's assemblies. The returned value is authoritative. + * A supplied signal controls only this explicit assembly request and must not + * be retained to control later turns. * @param assembly - the mutable assembly built from registered providers. * @param context - the caller's per-assembly context. * @mode waterfall @@ -41,6 +43,8 @@ export interface AssembleContext { * only global providers and subject-less listeners participate. */ scope?: ScopeKey + /** Explicit control signal for the turn that requested this assembly, when any. */ + signal?: AbortSignal } /** One contributed section of the system prompt (registry input). */ diff --git a/packages/examples/cli-demo/src/cli.ts b/packages/examples/cli-demo/src/cli.ts index a2b61f85f6..7a6dfee8eb 100644 --- a/packages/examples/cli-demo/src/cli.ts +++ b/packages/examples/cli-demo/src/cli.ts @@ -181,12 +181,12 @@ async function waitForStartupIdle(agent: Agent, signal?: AbortSignal): Promise((resolve, reject) => { const onAbort = (): void => { - agent.cancel(interruptionReason(signal)) + agent.cancel({ kind: 'user' }) reject(new CliInterruptedError(interruptionReason(signal))) } signal.addEventListener('abort', onAbort, { once: true }) @@ -243,7 +243,7 @@ export async function runOneShot(ctx: Context, options: OneShotOptions): Promise options.onEvent(sessionId, event) } catch (error: unknown) { outputError = toError(error) - agent.cancel('stream output failed') + agent.cancel({ kind: 'user' }) } } @@ -273,7 +273,7 @@ export async function runOneShot(ctx: Context, options: OneShotOptions): Promise let onAbort: (() => void) | undefined if (signal !== undefined) { onAbort = (): void => { - agent.cancel(interruptionReason(signal)) + agent.cancel({ kind: 'user' }) if (targetTurn === undefined) settleRejected(new CliInterruptedError(interruptionReason(signal))) } signal.addEventListener('abort', onAbort, { once: true }) @@ -370,7 +370,7 @@ async function bootInterruptibly( export function formatTurnFailure(reason: TurnEndReason): string { switch (reason.kind) { case 'completed': return 'completed' - case 'aborted': return reason.reason === undefined ? 'was aborted' : `was aborted: ${reason.reason}` + case 'aborted': return 'was aborted' case 'error': return `failed at step ${reason.step}: ${'failure' in reason ? reason.failure.message : reason.message}` case 'disposed': return 'was disposed' case 'max-tokens': return 'reached the model output-token limit' diff --git a/packages/examples/cli-demo/tests/built-bin.e2e.ts b/packages/examples/cli-demo/tests/built-bin.e2e.ts index c57f09b006..3dadd32215 100644 --- a/packages/examples/cli-demo/tests/built-bin.e2e.ts +++ b/packages/examples/cli-demo/tests/built-bin.e2e.ts @@ -179,7 +179,7 @@ describe.skipIf(!existsSync(cliBin))('dsh-cli-demo BUILT bin', () => { ) expect(result, JSON.stringify(result)).toMatchObject({ code, signal: null }) expect(result.stdout).toContain('"kind":"aborted"') - expect(result.stderr).toContain(`received ${signal}`) + expect(result.stderr).toContain('turn 1 was aborted') }, 30_000) }) }) diff --git a/packages/examples/cli-demo/tests/cli.spec.ts b/packages/examples/cli-demo/tests/cli.spec.ts index f038efe67e..f20697b827 100644 --- a/packages/examples/cli-demo/tests/cli.spec.ts +++ b/packages/examples/cli-demo/tests/cli.spec.ts @@ -398,9 +398,9 @@ describe('runOneShot and executeCli', () => { await running abort.abort('received SIGINT') const output = await outcome - expect(JSON.parse(output.stdout)).toMatchObject({ success: false, reason: { kind: 'aborted', reason: 'received SIGINT' } }) + expect(JSON.parse(output.stdout)).toMatchObject({ success: false, reason: { kind: 'aborted' } }) expect(output.code).toBe(1) - expect(output.stderr).toContain('was aborted: received SIGINT') + expect(output.stderr).toContain('turn 1 was aborted') expect(agent.status).toBe('disposed') }) @@ -486,7 +486,7 @@ describe('formatTurnFailure', () => { const cases: [TurnEndReason, string][] = [ [{ kind: 'completed' }, 'completed'], [{ kind: 'aborted' }, 'was aborted'], - [{ kind: 'aborted', reason: 'stop' }, 'was aborted: stop'], + [{ kind: 'aborted' }, 'was aborted'], [{ kind: 'error', step: 2, message: 'bad' }, 'failed at step 2: bad'], [{ kind: 'error', step: 3, failure: { message: 'provider bad', code: 'SERVER' } }, 'failed at step 3: provider bad'], [{ kind: 'disposed' }, 'was disposed'], diff --git a/packages/goal/goal-session/README.md b/packages/goal/goal-session/README.md index 2ad4b161a3..ee86f72d8c 100644 --- a/packages/goal/goal-session/README.md +++ b/packages/goal/goal-session/README.md @@ -44,7 +44,7 @@ A goal mutation made during its round supersedes settlement of the older revisio Activation is never inherited when this plugin loads over an existing agent. `GoalService.disarm()` removes process-local authority without changing durable phase, revision, or history; explicit human-authorized resume records the later reactivation. The same rule applies after session resume and fork through the goal domain's `agent/session-start` handling. -Cancellation is observe-before-act: the concrete loop emits `agent/cancel-requested` before clearing queues or aborting a step. The plugin durably pauses an active goal only when the cancellation owns a reserved or admitted goal attempt; cancellation of unrelated human work merely disarms process-local continuation. If the pause mutation fails, the driver falls back to disarming. Plugin teardown closes admission, disarms every live goal, cancels an admitted round, and awaits the driver plus agent quiescence while its event fence remains installed. +Cancellation is observe-before-act: the concrete loop emits `agent/cancel-requested` with its typed cause before clearing queues or aborting the turn. The plugin durably pauses an active goal only when the cancellation owns a reserved or admitted goal attempt; cancellation of unrelated human work merely disarms process-local continuation. If the pause mutation fails, the driver falls back to disarming. Plugin teardown closes admission, disarms every live goal, cancels an admitted round with the `parent` cause, and awaits the driver plus agent quiescence while its event fence remains installed. ## Model Experience diff --git a/packages/goal/goal-session/src/index.ts b/packages/goal/goal-session/src/index.ts index 24364a4983..deb0a33f30 100644 --- a/packages/goal/goal-session/src/index.ts +++ b/packages/goal/goal-session/src/index.ts @@ -313,7 +313,7 @@ export function apply(ctx: Context): void { state.competingQueued = true if (attempt?.phase === 'queued') attempt.stale = true }) - ctx.on('agent/cancel-requested', (agent, reason) => { + ctx.on('agent/cancel-requested', (agent, cause) => { const state = stateFor(agent) const attempt = state.attempt state.attempt = undefined @@ -325,7 +325,7 @@ export function apply(ctx: Context): void { return } try { - applyOutcome(state, goal, { kind: 'pause', reason }) + applyOutcome(state, goal, { kind: 'pause', reason: cause.kind }) } catch (error: unknown) { ctx.logger.warn(`goal-session: could not pause cancelled goal for agent "${agent.id}": ${renderThrown(error)}`) disarm(state) @@ -393,7 +393,7 @@ export function apply(ctx: Context): void { && source.round === goal.roundsStarted + 1 } - ctx.on('agent/prompt-submit', async (agent, content, source, next): Promise => { + ctx.on('agent/prompt-submit', async (agent, content, source, _signal, next): Promise => { if (!isGoalRoundSource(source)) return next() const state = stateFor(agent) let valid = false @@ -443,7 +443,7 @@ export function apply(ctx: Context): void { if (attempt !== undefined) { attempt.stale = true if (attempt.phase === 'admitted' && state.agent.status === 'running') { - state.agent.cancel('goal-session driver disposed') + state.agent.cancel({ kind: 'parent' }) } waits.push(state.agent.whenIdle()) } diff --git a/packages/goal/goal-session/src/outcome.ts b/packages/goal/goal-session/src/outcome.ts index e69f53eeec..d3048cb6f4 100644 --- a/packages/goal/goal-session/src/outcome.ts +++ b/packages/goal/goal-session/src/outcome.ts @@ -26,7 +26,7 @@ export function classifyGoalRound(reason: TurnEndReason, durable: boolean): Goal case 'completed': return { kind: 'continue' } case 'aborted': - return { kind: 'pause', reason: reason.reason ?? 'cancelled' } + return { kind: 'pause', reason: 'cancelled' } case 'error': { const { code, message } = reason.failure ?? reason return code === 'RATE_LIMIT' || code === 'QUOTA' diff --git a/packages/goal/goal-session/tests/goal-session.spec.ts b/packages/goal/goal-session/tests/goal-session.spec.ts index 8495b73ecc..c6cb96df82 100644 --- a/packages/goal/goal-session/tests/goal-session.spec.ts +++ b/packages/goal/goal-session/tests/goal-session.spec.ts @@ -123,7 +123,6 @@ async function waitForRequests(adapter: ScriptedAdapter, count: number): Promise describe('goal-round outcome policy', () => { it.each([ [{ kind: 'completed' }, true, { kind: 'continue' }], - [{ kind: 'aborted', reason: 'operator stopped' }, true, { kind: 'pause', reason: 'operator stopped' }], [{ kind: 'aborted' }, true, { kind: 'pause', reason: 'cancelled' }], [{ kind: 'error', step: 1, message: 'slow down', code: 'RATE_LIMIT' }, true, { kind: 'blocked', code: 'usage-limited', message: 'slow down' }], @@ -248,7 +247,7 @@ describe('same-session goal driving', () => { it('maps a downstream prompt veto to blocked without admitting the round', async () => { const test = await harness([]) - test.ctx.on('agent/prompt-submit', (_agent, _content, source, next) => source.kind === 'goal' + test.ctx.on('agent/prompt-submit', (_agent, _content, source, _signal, next) => source.kind === 'goal' ? Promise.resolve({ kind: 'block', reason: 'deployment policy' }) : next()) test.ctx.goals.create(test.agent, { objective: 'respect policy' }) @@ -264,7 +263,7 @@ describe('same-session goal driving', () => { it('does not reserve again when a stopped-goal observer queues ordinary work', async () => { const test = await harness([textResponse('human follow-up')]) - test.ctx.on('agent/prompt-submit', (_agent, _content, source, next) => source.kind === 'goal' + test.ctx.on('agent/prompt-submit', (_agent, _content, source, _signal, next) => source.kind === 'goal' ? Promise.resolve({ kind: 'block', reason: 'stop this round' }) : next()) test.ctx.on('goal/changed', (agent, change) => { @@ -284,7 +283,7 @@ describe('same-session goal driving', () => { const cancel = test.ctx.on('agent/queued', (agent, _content, info) => { if (agent === test.agent && info.source.kind === 'goal') { cancel() - agent.cancel('operator cancelled pending goal') + agent.cancel({ kind: 'user' }) } }) test.ctx.goals.create(test.agent, { objective: 'do not start yet' }) @@ -302,7 +301,7 @@ describe('same-session goal driving', () => { test.ctx.goals.create(test.agent, { objective: 'stop in flight' }) await waitForRequests(test.adapter, 1) - test.agent.cancel('operator stopped active goal') + test.agent.cancel({ kind: 'user' }) await test.agent.whenIdle() const goal = await waitForGoal(test.ctx, test.agent, current => current?.phase === 'paused') @@ -369,7 +368,7 @@ describe('same-session goal driving', () => { it('rechecks revision after downstream prompt hooks before admitting', async () => { const test = await harness([textResponse('new revision')]) let edited = false - test.ctx.on('agent/prompt-submit', (agent, _content, source, next) => { + test.ctx.on('agent/prompt-submit', (agent, _content, source, _signal, next) => { if (source.kind === 'goal' && !edited) { edited = true const current = test.ctx.goals.get(agent) @@ -543,7 +542,7 @@ describe('same-session goal driving', () => { it('fails a post-hook read closed before the prompt can enter history', async () => { const test = await harness([]) let armed = true - test.ctx.on('agent/prompt-submit', (_agent, _content, source, next) => { + test.ctx.on('agent/prompt-submit', (_agent, _content, source, _signal, next) => { if (source.kind === 'goal' && armed) { armed = false vi.spyOn(test.ctx.goals, 'get').mockImplementationOnce(() => { @@ -575,7 +574,7 @@ describe('same-session goal driving', () => { it('does not invent goal state when ordinary queued work is cancelled', async () => { const test = await harness([]) test.agent.send([{ type: 'text', text: 'cancel ordinary work' }]) - test.agent.cancel('ordinary cancellation') + test.agent.cancel({ kind: 'user' }) await test.agent.whenIdle() expect(test.ctx.goals.get(test.agent)).toBeUndefined() @@ -588,7 +587,7 @@ describe('same-session goal driving', () => { await waitForRequests(test.adapter, 1) const created = test.ctx.goals.create(test.agent, { objective: 'continue after inspection' }) - test.agent.cancel('cancel the inspection') + test.agent.cancel({ kind: 'user' }) await test.agent.whenIdle() expect(test.ctx.goals.get(test.agent)).toMatchObject({ @@ -608,7 +607,7 @@ describe('same-session goal driving', () => { vi.spyOn(test.ctx.goals, 'pause').mockImplementationOnce(() => { throw new Error('pause failed') }) - agent.cancel('cancel the reserved goal round') + agent.cancel({ kind: 'user' }) }) test.ctx.goals.create(test.agent, { objective: 'fail closed after cancellation' }) @@ -621,10 +620,10 @@ describe('same-session goal driving', () => { it('blocks admission when downstream cancellation clears the reservation', async () => { const test = await harness([]) let cancelled = false - test.ctx.on('agent/prompt-submit', (agent, _content, source, next) => { + test.ctx.on('agent/prompt-submit', (agent, _content, source, _signal, next) => { if (source.kind === 'goal' && !cancelled) { cancelled = true - agent.cancel('cancel from downstream admission policy') + agent.cancel({ kind: 'user' }) } return next() }) diff --git a/packages/goal/tool-goal/tests/tool-goal.spec.ts b/packages/goal/tool-goal/tests/tool-goal.spec.ts index a81f1b4cd2..faaf9d1c76 100644 --- a/packages/goal/tool-goal/tests/tool-goal.spec.ts +++ b/packages/goal/tool-goal/tests/tool-goal.spec.ts @@ -330,7 +330,7 @@ describe('goal tool state transitions', () => { goal_id: goal['id'], revision: goal['revision'], action: 'resume', }, root.agent)) expect(goal).toMatchObject({ phase: 'active', revision: 4 }) - expect(await agentEvents(ctx, root.agent).serial('agent/turn-stop', 1)).toBeUndefined() + expect(await agentEvents(ctx, root.agent).serial('agent/turn-stop', 1, testToolSignal)).toBeUndefined() }) it('terminal-stops an autonomous completion but leaves a human pause interactive', async () => { @@ -341,7 +341,7 @@ describe('goal tool state transitions', () => { goal_id: created.id, revision: created.revision, action: 'pause', }, root.agent) expect(resultGoal(paused)).toMatchObject({ phase: 'paused' }) - expect(await agentEvents(ctx, root.agent).serial('agent/turn-stop', humanTurn)).toBeUndefined() + expect(await agentEvents(ctx, root.agent).serial('agent/turn-stop', humanTurn, testToolSignal)).toBeUndefined() const resumed = resultGoal(await execute(ctx, 'update_goal', { goal_id: created.id, revision: 2, action: 'resume', }, root.agent)) @@ -354,8 +354,8 @@ describe('goal tool state transitions', () => { goal_id: created.id, revision: resumed['revision'], action: 'complete', }, root.agent) expect(resultGoal(complete)).toMatchObject({ phase: 'complete' }) - expect(await agentEvents(ctx, root.agent).serial('agent/turn-stop', roundTurn)).toEqual({ action: 'stop' }) - expect(await agentEvents(ctx, root.agent).serial('agent/turn-stop', roundTurn)).toBeUndefined() + expect(await agentEvents(ctx, root.agent).serial('agent/turn-stop', roundTurn, testToolSignal)).toEqual({ action: 'stop' }) + expect(await agentEvents(ctx, root.agent).serial('agent/turn-stop', roundTurn, testToolSignal)).toBeUndefined() }) it('rearms a restored active goal only after a new direct human prompt', async () => { diff --git a/packages/guard/repeat-tool-guard/src/index.ts b/packages/guard/repeat-tool-guard/src/index.ts index 0c630686b4..2265c583d5 100644 --- a/packages/guard/repeat-tool-guard/src/index.ts +++ b/packages/guard/repeat-tool-guard/src/index.ts @@ -222,7 +222,7 @@ export function apply(ctx: Context, config: Config): void { // A user interjection changes the context; repetition across it is not a // loop. Pure reset hook: always delegates (attaching nothing, vetoing // nothing). - ctx.on('agent/prompt-submit', (agent, _content, _source, next): Promise => { + ctx.on('agent/prompt-submit', (agent, _content, _source, _signal, next): Promise => { chains.delete(agent) return next() }) 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 fefb6936c9..802022085e 100644 --- a/packages/hooks/hook-protocol/src/runner.ts +++ b/packages/hooks/hook-protocol/src/runner.ts @@ -27,8 +27,8 @@ export interface RunHookOptions { env?: Record /** Working directory for the hook (defaults to the executor's own default when omitted). */ cwd?: string - /** Abort signal — cancels the hook run when fired (the parent step aborts). */ - signal?: AbortSignal + /** Explicit owning-operation signal; firing it cancels the hook run. */ + 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-claude/src/index.ts b/packages/hooks/hooks-claude/src/index.ts index 2aee18580a..5a5d33427d 100644 --- a/packages/hooks/hooks-claude/src/index.ts +++ b/packages/hooks/hooks-claude/src/index.ts @@ -132,7 +132,7 @@ export function apply(ctx: Context, config: Config): void { point: string, matchQuery: string, payload: unknown, - opts: { agent?: Agent; turn?: number; signal?: AbortSignal }, + opts: { agent?: Agent; turn?: number; readonly signal: AbortSignal }, ): Promise { const groups: MatcherGroup[] = parsed[point] ?? [] const outputs: HookOutput[] = [] @@ -159,7 +159,7 @@ export function apply(ctx: Context, config: Config): void { defaultTimeoutMs, ...hookEnv ? { env: hookEnv } : {}, ...workdir !== undefined ? { cwd: workdir } : {}, - ...opts.signal ? { signal: opts.signal } : {}, + signal: opts.signal, trailingNewline: true, // Discard a `hookSpecificOutput` block whose `hookEventName` names a // different event than the one firing (the schemas key it by event). @@ -210,9 +210,9 @@ export function apply(ctx: Context, config: Config): void { // --- UserPromptSubmit → PromptDecision. The prompt text is the payload; no // matcher subject (CC ignores matchers for this event). --- - ctx.on('agent/prompt-submit', async (agent, content, _source, next): Promise => { + ctx.on('agent/prompt-submit', async (agent, content, _source, signal, next): Promise => { const turn = lastTurn(agent) - const merged = await runPoint('UserPromptSubmit', '', promptPayload(ctx, agent, content), { agent, turn }) + const merged = await runPoint('UserPromptSubmit', '', promptPayload(ctx, agent, content), { agent, turn, signal }) if (merged.decision === 'deny') { return { kind: 'block', reason: merged.reason ?? 'blocked by UserPromptSubmit hook' } } @@ -261,8 +261,8 @@ export function apply(ctx: Context, config: Config): void { // A blocking Stop hook forces continuation with its reason. // TODO(stop-loop-guard): cap consecutive forced continuations; hooks must self-limit meanwhile. - ctx.on('agent/turn-continuation', async (agent, turn, _default, next): Promise => { - const merged = await runPoint('Stop', '', stopPayload(ctx, agent), { agent, turn }) + ctx.on('agent/turn-continuation', async (agent, turn, _default, signal, next): Promise => { + const merged = await runPoint('Stop', '', stopPayload(ctx, agent), { agent, turn, signal }) if (merged.decision === 'deny') { // A blocking Stop hook forces continuation. const text = merged.reason ?? 'continue: blocked by Stop hook' diff --git a/packages/hooks/hooks-codex/src/index.ts b/packages/hooks/hooks-codex/src/index.ts index 82cace3d8e..7d05950957 100644 --- a/packages/hooks/hooks-codex/src/index.ts +++ b/packages/hooks/hooks-codex/src/index.ts @@ -106,7 +106,12 @@ export function apply(ctx: Context, config: Config): void { point: string, matchQuery: string, payload: unknown, - opts: { agent?: Agent; turn?: number; signal?: AbortSignal; plainStdoutAsContext?: boolean }, + opts: { + agent?: Agent + turn?: number + readonly signal: AbortSignal + plainStdoutAsContext?: boolean + }, ): Promise { const groups: MatcherGroup[] = parsed[point] ?? [] const outputs: HookOutput[] = [] @@ -129,7 +134,7 @@ export function apply(ctx: Context, config: Config): void { payload, defaultTimeoutMs, ...workdir !== undefined ? { cwd: workdir } : {}, - ...opts.signal ? { signal: opts.signal } : {}, + signal: opts.signal, trailingNewline: false, // Codex writes stdin without a trailing newline. // Discard a `hookSpecificOutput` block naming a different event. expectedEventName: point, @@ -183,9 +188,9 @@ export function apply(ctx: Context, config: Config): void { }) // UserPromptSubmit → PromptDecision. Codex supports block, not allow or ask. - ctx.on('agent/prompt-submit', async (agent, content, _source, next): Promise => { + ctx.on('agent/prompt-submit', async (agent, content, _source, signal, next): Promise => { const turn = lastTurn(agent) - const merged = await runPoint('UserPromptSubmit', '', { ...turnBase(ctx, agent, 'UserPromptSubmit', model), prompt: blocksToText(content) }, { agent, turn, plainStdoutAsContext: true }) + const merged = await runPoint('UserPromptSubmit', '', { ...turnBase(ctx, agent, 'UserPromptSubmit', model), prompt: blocksToText(content) }, { agent, turn, plainStdoutAsContext: true, signal }) /* jscpd:ignore-start */ if (merged.decision === 'deny') return { kind: 'block', reason: merged.reason ?? 'blocked by UserPromptSubmit hook' } // Context alone is not a veto: DELEGATE so a later prompt-submit listener can @@ -236,8 +241,8 @@ export function apply(ctx: Context, config: Config): void { // TODO(stop-loop-guard): Codex supplies `stop_hook_active` so a Stop hook can // avoid continuing the same turn indefinitely. It is always false here, so an // unconditionally blocking hook force-continues every step until it self-limits. - ctx.on('agent/turn-continuation', async (agent, turn, _default, next): Promise => { - const merged = await runPoint('Stop', '', { ...turnBase(ctx, agent, 'Stop', model), stop_hook_active: false, last_assistant_message: null }, { agent, turn }) + ctx.on('agent/turn-continuation', async (agent, turn, _default, signal, next): Promise => { + const merged = await runPoint('Stop', '', { ...turnBase(ctx, agent, 'Stop', model), stop_hook_active: false, last_assistant_message: null }, { agent, turn, signal }) /* jscpd:ignore-end */ if (merged.decision === 'deny') { // A blocking Stop hook forces continuation; a block with no reason (exit 2, 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') diff --git a/packages/llm/llm-retry/tests/persistence.spec.ts b/packages/llm/llm-retry/tests/persistence.spec.ts index 3e5a9c8dcd..1668c36d73 100644 --- a/packages/llm/llm-retry/tests/persistence.spec.ts +++ b/packages/llm/llm-retry/tests/persistence.spec.ts @@ -43,7 +43,7 @@ describe.each(['jsonl', 'sqlite'] as const)('%s retry-event persistence', (kind) delayMs: 750, failure: { message: 'provider busy', code: 'RATE_LIMIT', status: 429 }, }) - session.append('turn/end', { turn: 1, reason: { kind: 'aborted', reason: 'cancelled in backoff' } }) + session.append('turn/end', { turn: 1, reason: { kind: 'aborted' } }) expect(session.deriveMessages()).toEqual([]) await ctx.sessions.flush(session) diff --git a/packages/llm/llm-retry/tests/retry.spec.ts b/packages/llm/llm-retry/tests/retry.spec.ts index 8e2f086e97..443256ea2e 100644 --- a/packages/llm/llm-retry/tests/retry.spec.ts +++ b/packages/llm/llm-retry/tests/retry.spec.ts @@ -377,13 +377,13 @@ describe('bounded transient retry policy', () => { agent.send([{ type: 'text', text: 'go' }]) await scheduled const idle = waitForIdle(context, agent) - agent.cancel('user cancelled during retry') + agent.cancel({ kind: 'user' }) await idle expect(adapter.requests).toHaveLength(1) expect(agent.session.events.at(-1)).toMatchObject({ type: 'turn/end', - data: { reason: { kind: 'aborted', reason: 'user cancelled during retry' } }, + data: { reason: { kind: 'aborted' } }, }) expect(vi.getTimerCount()).toBe(0) }) @@ -396,7 +396,7 @@ describe('bounded transient retry policy', () => { ]) ;({ ctx: context } = await harness(adapter, {}, (ctx) => { ctx.on('agent/request-error', async (agent, _turn, _step, _error, _failure, _history, _signal, next) => { - agent.cancel('cancelled by earlier recovery policy') + agent.cancel({ kind: 'user' }) return next() }) })) @@ -410,7 +410,7 @@ describe('bounded transient retry policy', () => { expect(agent.session.events.some(event => event.type === 'llm/retry')).toBe(false) expect(agent.session.events.at(-1)).toMatchObject({ type: 'turn/end', - data: { reason: { kind: 'aborted', reason: 'cancelled by earlier recovery policy' } }, + data: { reason: { kind: 'aborted' } }, }) }) @@ -423,7 +423,7 @@ describe('bounded transient retry policy', () => { ;({ ctx: context } = await harness(adapter)) const agent = context.agentLoop.create(SessionId('retry-event-cancel'), { provider: 'mock', model: 'mock' }) context.on('session/event', (session, event) => { - if (session === agent.session && event.type === 'llm/retry') agent.cancel('cancelled by retry observer') + if (session === agent.session && event.type === 'llm/retry') agent.cancel({ kind: 'user' }) }) const idle = waitForIdle(context, agent) diff --git a/packages/subagent/subagent-inprocess/src/index.ts b/packages/subagent/subagent-inprocess/src/index.ts index f0e9731c9d..950ee09c4c 100644 --- a/packages/subagent/subagent-inprocess/src/index.ts +++ b/packages/subagent/subagent-inprocess/src/index.ts @@ -135,7 +135,7 @@ export async function startInProcessRun( const onAbort = (): void => { flags.cancelled = true - child.cancel('subagent request aborted') + child.cancel({ kind: 'parent' }) } request.signal.addEventListener('abort', onAbort, { once: true }) diff --git a/packages/subagent/subagent-inprocess/src/structured.ts b/packages/subagent/subagent-inprocess/src/structured.ts index 09aa2d24b7..811d754094 100644 --- a/packages/subagent/subagent-inprocess/src/structured.ts +++ b/packages/subagent/subagent-inprocess/src/structured.ts @@ -96,7 +96,7 @@ export function attachStructuredRuntime(childCtx: Context, schema: StructuredOut // Stop the child's turn once its output is captured. This monotonic serial // checkpoint runs after the ordinary continuation waterfall, its reason, // and late-steering folding, so no ordering trick can resume a finished run. - childCtx.on('agent/turn-stop', function (this: unknown): ContinuationStop | undefined { + childCtx.on('agent/turn-stop', function (this: unknown, _agent, _turn, _signal): ContinuationStop | undefined { return captured === undefined ? undefined : { action: 'stop' } }) diff --git a/packages/subagent/subagent-inprocess/tests/structured.spec.ts b/packages/subagent/subagent-inprocess/tests/structured.spec.ts index f8d584f4a1..2fa3398045 100644 --- a/packages/subagent/subagent-inprocess/tests/structured.spec.ts +++ b/packages/subagent/subagent-inprocess/tests/structured.spec.ts @@ -217,7 +217,7 @@ describe('in-process structured output', () => { ctx.on('agent/session-start', (child) => { if (child === parent) return wrapperInstalled = true - child.ctx.on('agent/turn-continuation', async (_subject, _turn, _decision, next): Promise => { + child.ctx.on('agent/turn-continuation', async (_subject, _turn, _decision, _signal, next): Promise => { const downstream = await next() expect(downstream).toEqual({ action: 'stop' }) return { action: 'continue' } @@ -243,7 +243,7 @@ describe('in-process structured output', () => { const run = await ctx.subagents.start('spawn', structuredRequest(parent)) ctx.on('agent/session-start', (child) => { if (child.id !== run.id) return - child.ctx.on('agent/turn-continuation', async (subject, _turn, _decision, next): Promise => { + child.ctx.on('agent/turn-continuation', async (subject, _turn, _decision, _signal, next): Promise => { const downstream = await next() expect(downstream).toEqual({ action: 'stop' }) subject.steer([{ type: 'text', text: 'late steering after downstream stop' }]) diff --git a/packages/subagent/subagent-inprocess/tests/subagent-inprocess.spec.ts b/packages/subagent/subagent-inprocess/tests/subagent-inprocess.spec.ts index e82c1ad028..57fc1e5178 100644 --- a/packages/subagent/subagent-inprocess/tests/subagent-inprocess.spec.ts +++ b/packages/subagent/subagent-inprocess/tests/subagent-inprocess.spec.ts @@ -17,9 +17,10 @@ async function setup(script: Script) { await ctx.plugin(Invariants) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(SubagentService) - ctx.llm.registerAdapter(['mock'], new MockAdapter(script)) + const adapter = new MockAdapter(script) + ctx.llm.registerAdapter(['mock'], adapter) const parent = ctx.agentLoop.create(SessionId('parent'), { provider: 'mock', model: 'mock' }) - return { ctx, parent } + return { ctx, parent, adapter } } function request(parent: Agent, signal = new AbortController().signal) { @@ -123,12 +124,16 @@ describe('startInProcessRun', () => { }) it('uses the request signal after publication and dispose as cancellation paths', async () => { - const { parent } = await setup(['hang', 'hang']) + const { parent, adapter } = await setup(['hang', 'hang']) const controller = new AbortController() const signalled = await startInProcessRun(request(parent, controller.signal), {}) await new Promise(resolve => setTimeout(resolve, 30)) controller.abort('stop child') await expect(signalled.result).resolves.toMatchObject({ stopReason: 'aborted' }) + expect(adapter.requests[0]?.signal?.reason).toEqual({ kind: 'parent' }) + const child = parent.ctx.agents.get(signalled.id) + const turnEnd = child?.session.events.findLast(event => event.type === 'turn/end') + expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'aborted' }) await signalled.dispose() const disposed = await startInProcessRun(request(parent), {}) diff --git a/packages/support/invariants/tests/invariants.spec.ts b/packages/support/invariants/tests/invariants.spec.ts index 4f066eff8c..7b4c9f6dac 100644 --- a/packages/support/invariants/tests/invariants.spec.ts +++ b/packages/support/invariants/tests/invariants.spec.ts @@ -1,5 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from 'cordis' +import type { Events } from 'cordis' import { createScope, scopeTarget } from '@deepseek-ai/dsh-scope' import { CallId } from '@deepseek-ai/dsh-llm' import type { Agent } from '@deepseek-ai/dsh-agent' @@ -900,6 +901,9 @@ describe('request cross-check ordering (prepend)', () => { }) describe('scoped-dispatch invariants', () => { + type AgentEventName = Extract + type EventArgs = Events[K] extends (...args: infer Args) => unknown ? Args : never + async function scopedCtx() { const ctx = new Context() await ctx.plugin(SessionStore) @@ -919,22 +923,31 @@ describe('scoped-dispatch invariants', () => { // Real Session objects keep the synthetic Agent handles structurally valid. const agent = { id: 'a1', session: new Session(SessionId('a1-s')) } as unknown as Agent const other = { id: 'a2', session: new Session(SessionId('a2-s')) } as unknown as Agent - // One dispatch per table row keeps every subject extractor covered: the - // matching carrier passes, the foreign-keyed one throws. + // Typed Agent rows keep their representative payloads aligned with the + // declarations while every subject extractor sees both carrier outcomes. + const signal = new AbortController().signal + const config = { provider: 'p', model: 'm' } + const message = { role: 'assistant' as const, content: [] } + const agentRows = { + 'agent/created': [agent], + 'agent/disposed': [agent], + 'agent/status': [agent, 'idle'], + 'agent/queued': [agent, [], { source: { kind: 'user' }, steering: false }], + 'agent/cancel-requested': [agent, { kind: 'user' }], + 'agent/session-start': [agent, 'startup'], + 'agent/pre-step': [agent, 1, 1, signal], + 'agent/post-step': [agent, 1, 1, signal], + 'agent/prompt-submit': [agent, [], { kind: 'user' }, signal, () => Promise.resolve({ kind: 'allow' })], + 'agent/request': [agent, 1, 1, config, signal, () => Promise.resolve(config)], + 'agent/request-error': [agent, 1, 1, new Error('request failed'), { message: 'request failed', code: 'UNKNOWN' }, [], signal, () => Promise.resolve({ action: 'fail' })], + 'agent/session-prefix': [agent, [], signal, () => Promise.resolve([])], + 'agent/step-result': [agent, 1, 1, message, signal, () => Promise.resolve(message)], + 'agent/turn-continuation': [agent, 1, { action: 'stop' }, signal, () => Promise.resolve({ action: 'stop' })], + 'agent/turn-stop': [agent, 1, signal], + 'agent/error': [agent, 1, 0, new Error('x')], + } satisfies { [K in AgentEventName]: EventArgs } const rows: [string, unknown[]][] = [ - ['agent/created', [agent]], - ['agent/disposed', [agent]], - ['agent/status', [agent, 'idle']], - ['agent/queued', [agent, [], { source: { kind: 'user' }, steering: false }]], - ['agent/session-start', [agent, 'startup']], - ['agent/pre-step', [agent, 1, 1, new AbortController().signal]], - ['agent/prompt-submit', [agent, [], { kind: 'user' }, () => Promise.resolve({ kind: 'allow' })]], - ['agent/request', [agent, 1, 1, { model: 'm' }, () => Promise.resolve({ model: 'm' })]], - ['agent/session-prefix', [agent, [], new AbortController().signal, () => Promise.resolve([])]], - ['agent/step-result', [agent, 1, 1, { role: 'assistant', content: [] }, () => Promise.resolve({ role: 'assistant', content: [] })]], - ['agent/turn-continuation', [agent, 1, { action: 'stop' }, () => Promise.resolve({ action: 'stop' })]], - ['agent/turn-stop', [agent, 1]], - ['agent/error', [agent, 1, 0, new Error('x')]], + ...Object.entries(agentRows), ['approval/request', [{ agent, toolName: 'echo' }, () => Promise.resolve('unavailable')]], ['goal/changed', [agent, { operation: 'create', ref: { id: 'goal-a', revision: 1 } }]], ['tools/pre-execute', [{ callId: 'c', name: 't', arguments: {}, agent }, () => Promise.resolve({ kind: 'allow' })]], diff --git a/packages/ui/acp/src/index.ts b/packages/ui/acp/src/index.ts index 62455223a4..1194ada9a1 100644 --- a/packages/ui/acp/src/index.ts +++ b/packages/ui/acp/src/index.ts @@ -355,7 +355,7 @@ export function apply(ctx: Context, config: AcpConfig): void { }, } }) - agentCtx.on('agent/request', async (_agent, _turn, _step, _callConfig, next): Promise => { + agentCtx.on('agent/request', async (_agent, _turn, _step, _callConfig, _signal, next): Promise => { const resolved = await next() const selected = target.assembled return selected === undefined ? resolved : { @@ -695,7 +695,7 @@ export function apply(ctx: Context, config: AcpConfig): void { // Prompt-submit is inside the new turn but before prompt assembly. Promptless // injection turns leave the switch pending because they execute no request. - ctx.on('agent/prompt-submit', (agent, _content, _source, next) => { + ctx.on('agent/prompt-submit', (agent, _content, _source, _signal, next) => { const rec = ownedRecord(agent) if (rec !== undefined) flushPendingSwitches(rec) return next() @@ -959,7 +959,7 @@ export function apply(ctx: Context, config: AcpConfig): void { cancel(params: CancelNotification): Promise { const rec = sessions.get(SessionId(params.sessionId)) if (rec === undefined) return Promise.resolve() - // session/cancel maps to the queue-aware agent.cancel(reason): it aborts + // session/cancel maps to the queue-aware agent.cancel({ kind: 'user' }): it aborts // a RUNNING step, clears the queued + steering FIFOs, and drops a // turn that is about to start (the pre-step window) — so a queued-but- // not-yet-started prompt never runs, while a prompt accepted afterward @@ -974,7 +974,7 @@ export function apply(ctx: Context, config: AcpConfig): void { if (rec.commandAbort !== undefined) { rec.commandAbort.abort(new Error('session/cancel')) } else { - rec.agent.cancel('session/cancel') + rec.agent.cancel({ kind: 'user' }) settlePrompt(rec, 'cancelled') } return Promise.resolve() diff --git a/packages/ui/acp/tests/codec.spec.ts b/packages/ui/acp/tests/codec.spec.ts index b4f0c10792..31ffb9ed48 100644 --- a/packages/ui/acp/tests/codec.spec.ts +++ b/packages/ui/acp/tests/codec.spec.ts @@ -15,7 +15,7 @@ describe('turnEndToStopReason', () => { it('maps every known TurnEndReason kind to a legal StopReason', () => { expect(turnEndToStopReason({ kind: 'completed' })).toBe('end_turn') expect(turnEndToStopReason({ kind: 'max-tokens' })).toBe('max_tokens') - expect(turnEndToStopReason({ kind: 'aborted', reason: 'x' })).toBe('cancelled') + expect(turnEndToStopReason({ kind: 'aborted' })).toBe('cancelled') expect(turnEndToStopReason({ kind: 'disposed' })).toBe('cancelled') expect(turnEndToStopReason({ kind: 'rejected', reason: 'blocked by hook' })).toBe('cancelled') expect(turnEndToStopReason({ kind: 'error', step: 1, message: 'boom' })).toBe('end_turn') diff --git a/packages/ui/acp/tests/config-options.spec.ts b/packages/ui/acp/tests/config-options.spec.ts index 29fb06b28c..fdb1c03d3f 100644 --- a/packages/ui/acp/tests/config-options.spec.ts +++ b/packages/ui/acp/tests/config-options.spec.ts @@ -176,7 +176,7 @@ describe('acp bridge — session config options', () => { const { sessionId } = await h.client.newSession({ cwd: process.cwd(), mcpServers: [] }) const agent = h.ctx.agents.list()[0] if (agent === undefined) throw new Error('expected an agent') - agent.ctx.on('agent/request', async (_agent, _turn, _step, callConfig, _next) => ({ + agent.ctx.on('agent/request', async (_agent, _turn, _step, callConfig, _signal, _next) => ({ ...callConfig, provider: 'mock', model: 'mock', diff --git a/packages/ui/acp/tests/turns.spec.ts b/packages/ui/acp/tests/turns.spec.ts index e3e8d679ea..4ca6775d06 100644 --- a/packages/ui/acp/tests/turns.spec.ts +++ b/packages/ui/acp/tests/turns.spec.ts @@ -325,6 +325,10 @@ describe('acp bridge — turn outcomes', () => { await harness.client.cancel({ sessionId }) const res = await promptDone expect(res.stopReason).toBe('cancelled') + const agent = harness.ctx.agents.get(SessionId(sessionId))! + await agent.whenIdle() + const turnEnd = agent.session.events.findLast(event => event.type === 'turn/end') + expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'aborted' }) }) it('cancel right after prompt settles cancelled and leaves the agent idle, no leaked turn', async () => { diff --git a/packages/ui/tui/src/index.ts b/packages/ui/tui/src/index.ts index cbb3593209..ded7d639a2 100644 --- a/packages/ui/tui/src/index.ts +++ b/packages/ui/tui/src/index.ts @@ -1008,7 +1008,7 @@ export function createTuiChat( : event.data.reason.message if (!liveErrors.delete(key)) appendNotice(message, 'error') } else if (event.data.reason.kind === 'aborted') { - appendNotice(event.data.reason.reason ?? 'Turn cancelled.', 'warning') + appendNotice('Turn cancelled.', 'warning') } else if (event.data.reason.kind === 'max-tokens') { appendNotice('The model reached its output-token limit.', 'warning') } else if (event.data.reason.kind === 'rejected') { @@ -1149,7 +1149,7 @@ export function createTuiChat( const requestExit = (): void => { if (agent.status === 'running') { - agent.cancel('terminal exit requested') + agent.cancel({ kind: 'user' }) appendNotice('Cancelling the active turn before exit…', 'warning') void agent.whenIdle().then(() => shutdown(true)) return @@ -1223,7 +1223,7 @@ export function createTuiChat( description: 'Cancel the active turn', handler: () => { if (agent.status !== 'running') return { kind: 'error', text: 'The agent is already idle.' } - agent.cancel('cancelled from terminal') + agent.cancel({ kind: 'user' }) return { kind: 'success', text: 'Cancellation requested.' } }, }) @@ -1303,12 +1303,12 @@ export function createTuiChat( return { consume: true } } if (matchesKey(data, Key.escape) && agent.status === 'running') { - agent.cancel('cancelled from terminal') + agent.cancel({ kind: 'user' }) return { consume: true } } if (matchesKey(data, Key.ctrl('c'))) { if (agent.status === 'running') { - agent.cancel('cancelled from terminal') + agent.cancel({ kind: 'user' }) } else if (editor.getText() !== '') { editor.setText('') } else { diff --git a/packages/ui/tui/tests/harness.ts b/packages/ui/tui/tests/harness.ts index c24577b7fd..afaef3b232 100644 --- a/packages/ui/tui/tests/harness.ts +++ b/packages/ui/tui/tests/harness.ts @@ -1,6 +1,6 @@ import { Context } from 'cordis' import type { Terminal } from '@earendil-works/pi-tui' -import AgentRegistry, { type Agent, type AgentStatus } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { type Agent, type AgentCancelCause, type AgentStatus } from '@deepseek-ai/dsh-agent' import CommandService from '@deepseek-ai/dsh-commands' import type { ContentBlock } from '@deepseek-ai/dsh-llm' import SessionStore, { SessionId, type Session } from '@deepseek-ai/dsh-session' @@ -12,7 +12,7 @@ interface FakeAgent extends Agent { status: AgentStatus sent: ContentBlock[][] steered: ContentBlock[][] - cancelled: string[] + cancelled: AgentCancelCause[] } export interface TuiHarnessOptions { @@ -68,7 +68,7 @@ export async function createTuiTestHarness -13| " cancelled during retry delay " - style 1-28 fg=yellow +13| " Turn cancelled. " + style 1-15 fg=yellow 14| "────────────────────────────────────────────────────────────────────────────────────────────────" style 0-95 dim 15| " " diff --git a/packages/ui/tui/tests/tui.snapshot.ts b/packages/ui/tui/tests/tui.snapshot.ts index b8afc452cb..295ceda116 100644 --- a/packages/ui/tui/tests/tui.snapshot.ts +++ b/packages/ui/tui/tests/tui.snapshot.ts @@ -274,7 +274,7 @@ describe('TUI terminal-state snapshots', () => { }) harness.session.append('turn/end', { turn: 1, - reason: { kind: 'aborted', reason: 'cancelled during retry delay' }, + reason: { kind: 'aborted' }, }) }) await checkpoint('retry-cancelled', harness.terminal, { includeScrollback: true }) diff --git a/packages/ui/tui/tests/tui.spec.ts b/packages/ui/tui/tests/tui.spec.ts index aa2ff5510e..c2c2d6b570 100644 --- a/packages/ui/tui/tests/tui.spec.ts +++ b/packages/ui/tui/tests/tui.spec.ts @@ -457,7 +457,7 @@ describe('pi-tui chat lifecycle and transcript', () => { result.terminal.send('\x0f') result.terminal.send('/cancel') result.terminal.send('\r') - expect(result.agent.cancelled).toContain('cancelled from terminal') + expect(result.agent.cancelled).toContainEqual({ kind: 'user' }) result.agent.status = 'idle' for (const command of ['/help', '/reasoning', '/tools', '/redraw']) { @@ -607,7 +607,7 @@ describe('pi-tui chat lifecycle and transcript', () => { result.terminal.send('/exit') result.terminal.send('\r') await tick() - expect(result.agent.cancelled).toContain('terminal exit requested') + expect(result.agent.cancelled).toContainEqual({ kind: 'user' }) expect(result.exit).toHaveBeenCalledWith(0) const events = await setup() @@ -620,7 +620,7 @@ describe('pi-tui chat lifecycle and transcript', () => { events.ctx.emit('agent/error', events.agent, 3, 2, new Error('live failure')) events.session.append('turn/end', { turn: 3, reason: { kind: 'error', step: 2, message: 'live failure' } }) events.session.append('turn/end', { turn: 4, reason: { kind: 'error', step: 1, message: 'durable failure' } }) - events.session.append('turn/end', { turn: 5, reason: { kind: 'aborted', reason: 'stopped' } }) + events.session.append('turn/end', { turn: 5, reason: { kind: 'aborted' } }) events.session.append('turn/end', { turn: 6, reason: { kind: 'max-tokens' } }) events.session.append('turn/end', { turn: 7, reason: { kind: 'rejected', reason: 'policy' } }) events.session.append('turn/end', { turn: 8, reason: { kind: 'interrupted' } }) @@ -632,8 +632,8 @@ describe('pi-tui chat lifecycle and transcript', () => { await tick() expect(events.terminal.output).toContain('live failure') expect(events.terminal.output).toContain('durable failure') + expect(events.terminal.output).toContain('Turn cancelled') expect(events.terminal.output).toContain('structured provider failure') - expect(events.terminal.output).toContain('stopped') expect(events.terminal.output).toContain('output-token limit') expect(events.terminal.output).toContain('Turn rejected') expect(events.terminal.output).toContain('previous process ended') diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 969462282c..a15e70cb46 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -28,6 +28,7 @@ const FENCE = 'ts cordis-catalog' */ export const LINK_MAP: Record = { Agent: 'core.md', + AgentCancelCause: 'core.md', AgentOptions: 'core.md', AgentStatus: 'core.md', ContentBlock: 'core.md', diff --git a/scripts/translation-pairing.manifest.json b/scripts/translation-pairing.manifest.json index 748f3fa13c..b34c66880f 100644 --- a/scripts/translation-pairing.manifest.json +++ b/scripts/translation-pairing.manifest.json @@ -24,6 +24,7 @@ "docs/user/guide/quickstart.md", "docs/user/index.md", ".agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md", + ".agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.md", ".agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.md", "python/README.md", "python/sdk-runtime/README.md", diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index a51e31ca65..582ce4bd50 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -13,6 +13,7 @@ { "doc": "docs/core-data-structures/core.md", "symbol": "ToolSchema", "source": "packages/llm/llm/src/types.ts" }, { "doc": "docs/core-data-structures/core.md", "symbol": "LlmCallConfig", "source": "packages/llm/llm/src/call-config.ts" }, { "doc": "docs/core-data-structures/core.md", "symbol": "SessionEvent", "source": "packages/core/session/src/types.ts" }, + { "doc": "docs/core-data-structures/core.md", "symbol": "AgentCancelCause", "source": "packages/core/agent/src/types.ts" }, { "doc": "docs/core-data-structures/core.md", "symbol": "InjectOptions", "source": "packages/core/agent/src/types.ts" }, { "doc": "docs/core-data-structures/core.md", "symbol": "Agent", "source": "packages/core/agent/src/types.ts" }, { "doc": "docs/core-data-structures/core.md", "symbol": "HookContext", "source": "packages/core/agent/src/types.ts" },