feat(core): make turn cancellation explicit

This commit is contained in:
Yichen Jiang
2026-07-16 18:12:34 +08:00
parent b1e19d8b69
commit c238992fbb
55 changed files with 884 additions and 383 deletions

View File

@@ -33,6 +33,8 @@ The loop plugin registers `AgentFactory`, keeping consumers independent of its c
Most interception points are cooperative waterfalls returning seam-specific decisions. `agent/pre-step` is a serial surface-mutation checkpoint, while `agent/turn-stop` is the terminal serial fold: it runs after ordinary continuation and steering folding, and a returned stop remains in force through turn close and flush so later steering cannot create an extra step or turn. Ordinary queued prompts remain intact. The full rationale is in the [agent-scope runtime-design RFC](../../../docs/rfc/implemented/architecture/2026-07-12-agent-scope-runtime-design.md#three-execution-boundaries-are-deliberately-one-way).
Every asynchronous turn seam receives the same explicit `AbortSignal` for that turn. Listeners may cooperate with cancellation but must not retain the signal to control another turn; ambient `ctx.agentExecution` identity carries no liveness or cancellation authority. The signal and typed cancellation contract are defined by the [explicit turn cancellation RFC](../../../docs/rfc/implemented/architecture/2026-07-16-explicit-turn-cancellation.md).
Turn and step boundaries and the model token stream are durable `session/event` facts rather than mirrored `agent/*` notifications. Consumers read `turn/*`, `step/*`, and `assistant/chunk` from the session feed; tool policy and outcome observation belong to the complete pipeline documented by [`dsh-tools`](../tools/README.md).
### Agent interface (`types.ts`)
@@ -42,7 +44,7 @@ The handle every plugin programs against:
- `agent.send(content, options?)` — queue a message; starts a turn when idle. 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).
- `agent.steer(content, options?)` — steer a running turn (inject between steps); uses the same owned acceptance boundary and behaves like `send` when idle
- `agent.inject(content, options?)` — inject in-session context (context/message event); the next request sees it. Does not run the model. While a turn is open it joins that turn; while idle it is wrapped in a one-shot `injection` turn so every event stays turn-enclosed ([the turn-enclosure invariant](../../../docs/rfc/implemented/architecture/2026-06-15-turn-enclosure-invariant.md))
- `agent.cancel(reason?)` — cancel ALL pending work: clears the queued + steering FIFOs, aborts the in-flight step, and drops a turn about to start (the pre-step window) so a queued-but-not-started prompt never runs. A UI/ACP `session/cancel` maps to this. The single public stop primitive. Idle with nothing pending → a safe no-op.
- `agent.cancel(cause?)` — cancel ALL pending work: clears the queued + steering FIFOs, aborts the active turn, and drops queued work not yet claimed by the driver. `AgentCancelCause` is the runtime-only `{ kind: 'user' } | { kind: 'parent' }`; omission means `user`, the first cause wins for an active turn, and ACP `session/cancel` maps to `user`. `normalizeAgentCancelCause()` provides the same strict detached-value boundary used by the concrete loop: validation is synchronous even while idle, accepts only an exact plain object, and returns a safe no-op when no work exists.
- `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`

View File

@@ -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 } }
}

View File

@@ -10,6 +10,7 @@ import type { Context } from 'cordis'
import type { Scoped } from '@deepseek-ai/dsh-scope'
import type { ContentBlock, LlmCallConfig, Message, MessageSource } from '@deepseek-ai/dsh-llm'
import type {} from '@deepseek-ai/dsh-system-prompt'
import type { Session } from '@deepseek-ai/dsh-session'
/** Identifies one live agent in the registry. */
export type AgentId = Branded<'AgentId'>
@@ -22,8 +23,6 @@ export type AgentId = Branded<'AgentId'>
export function AgentId(id: string): AgentId {
return id as AgentId
}
import type { Session } from '@deepseek-ai/dsh-session'
declare module '@deepseek-ai/dsh-system-prompt' {
interface AssembleContext {
/** Agent for this assembly; absent on diagnostics. When present, `scope` must identify the same agent. */
@@ -80,6 +79,72 @@ export type ContinuationStop = Extract<ContinuationDecision, { action: 'stop' }>
/** 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' }
/**
* Validate and detach a caller-supplied Agent cancellation cause.
* @param value - the candidate cancellation cause.
* @returns a fresh frozen cause suitable for the current turn signal.
* @throws {TypeError} when the value is not an exact supported cause.
*/
export function normalizeAgentCancelCause(value: unknown): AgentCancelCause {
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
throw new TypeError('agent cancel cause must be an exact plain object with kind "user" or "parent"')
}
const prototype = Object.getPrototypeOf(value) as unknown
if (prototype !== Object.prototype && prototype !== null) {
throw new TypeError('agent cancel cause must be an exact plain object with kind "user" or "parent"')
}
const keys = Reflect.ownKeys(value)
if (keys.length !== 1 || keys[0] !== 'kind') {
throw new TypeError('agent cancel cause must contain exactly one field: kind')
}
const kind = (value as { readonly kind?: unknown }).kind
switch (kind) {
case 'user':
return Object.freeze({ kind: 'user' })
case 'parent':
return Object.freeze({ kind: 'parent' })
default:
throw new TypeError(`unsupported agent cancel cause kind: ${String(kind)}`)
}
}
/** Runtime reason carried by the signal that controls one live turn. */
export type AgentInterruptReason = AgentCancelCause | { readonly kind: 'disposed' }
/**
* Read a supported agent interruption from an explicitly supplied signal.
* Unknown reasons return `undefined`; this helper never consults ambient agent
* execution identity, which does not grant cancellation authority.
*
* @param signal - the current turn's explicit control signal.
* @returns its canonical supported reason, or `undefined` while live or when an
* unrelated controller supplied an unsupported reason.
*/
export function agentInterruptReasonOf(signal: AbortSignal): AgentInterruptReason | undefined {
if (!signal.aborted) return undefined
const reason: unknown = signal.reason
if (typeof reason === 'object' && reason !== null && !Array.isArray(reason)) {
const prototype = Object.getPrototypeOf(reason) as unknown
const keys = Reflect.ownKeys(reason)
if ((prototype === Object.prototype || prototype === null)
&& keys.length === 1 && keys[0] === 'kind'
&& (reason as { readonly kind?: unknown }).kind === 'disposed') {
return Object.freeze({ kind: 'disposed' })
}
}
try {
return normalizeAgentCancelCause(reason)
} catch (error: unknown) {
if (error instanceof TypeError) return undefined
throw error
}
}
/** Public agent handle; the concrete driver belongs to `@deepseek-ai/dsh-agent-loop`. */
export interface Agent {
readonly id: AgentId
@@ -112,11 +177,13 @@ export interface Agent {
/**
* Clear queued and steering work, including work waiting to start, and abort
* the active step. The supplied 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.
* the active turn. The first cause wins for that turn, and `whenIdle()` resolves
* after cancellation reaches quiescence. Omission means `{ kind: 'user' }`;
* invalid causes throw synchronously even while idle. Idle cancellation is a
* no-op after validation and does not arm a later cancel.
* @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<void>
@@ -202,14 +269,17 @@ declare module 'cordis' {
'agent/pre-step'(this: Scoped<Agent>, agent: Agent, turn: number, step: number, fullSystemPrompt: string, sessionPrefix: readonly Message[], signal: AbortSignal): Promise<void> | void
/**
* Allow, rewrite, or block one drained 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 draining its inbox.
* @param content - the drained 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: Agent, content: ContentBlock[], source: MessageSource, next: () => Promise<PromptDecision>): Promise<PromptDecision>
'agent/prompt-submit'(this: Scoped<Agent>, agent: Agent, content: ContentBlock[], source: MessageSource, signal: AbortSignal, next: () => Promise<PromptDecision>): Promise<PromptDecision>
/**
* Replace the frozen call configuration. Model-visible content must use
* logged channels; this seam cannot mutate messages. Injection here joins
@@ -218,10 +288,11 @@ 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 agent 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: Agent, turn: number, step: number, config: LlmCallConfig, next: () => Promise<LlmCallConfig>): Promise<LlmCallConfig>
'agent/request'(this: Scoped<Agent>, agent: Agent, turn: number, step: number, config: LlmCallConfig, signal: AbortSignal, next: () => Promise<LlmCallConfig>): Promise<LlmCallConfig>
/**
* Compose request-only messages placed before derived history. The frozen
* result is computed once per loop instance, logged on its anchoring request
@@ -233,7 +304,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: Agent, prefix: Message[], signal: AbortSignal, next: () => Promise<Message[]>): Promise<Message[]>
@@ -244,30 +315,33 @@ 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: Agent, turn: number, step: number, message: Message, next: () => Promise<Message>): Promise<Message>
'agent/step-result'(this: Scoped<Agent>, agent: Agent, turn: number, step: number, message: Message, signal: AbortSignal, next: () => Promise<Message>): Promise<Message>
/**
* Override whether the turn continues. The default continues after tool
* calls or steering and stops otherwise; a continue reason becomes steering.
* @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: Agent, turn: number, defaultDecision: ContinuationDecision, next: () => Promise<ContinuationDecision>): Promise<ContinuationDecision>
'agent/turn-continuation'(this: Scoped<Agent>, agent: Agent, turn: number, defaultDecision: ContinuationDecision, signal: AbortSignal, next: () => Promise<ContinuationDecision>): Promise<ContinuationDecision>
/**
* 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: Agent, turn: number): ContinuationStop | undefined
'agent/turn-stop'(this: Scoped<Agent>, agent: Agent, turn: number, signal: AbortSignal): Promise<ContinuationStop | undefined> | ContinuationStop | undefined
// ---- error notifications (emit) ----
/**

View File

@@ -22,12 +22,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<ContinuationStop | undefined>
expectTypeOf<AsyncTurnStopListener>().not.toExtend<TurnStopListener>()
expectTypeOf<ReturnType<TurnStopListener>>().toEqualTypeOf<ContinuationStop | undefined>()
expectTypeOf<AsyncTurnStopListener>().toExtend<TurnStopListener>()
expectTypeOf<Awaited<ReturnType<TurnStopListener>>>().toEqualTypeOf<ContinuationStop | undefined>()
})
it('registers exact entries, emits lifecycle events, and unregisters on owner disposal', async () => {