Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): cancellation - cascade to descendant turns (#832)

Andrew Barba25683870ff7b
diff --git a/.changeset/cancel-descendant-turns.md b/.changeset/cancel-descendant-turns.md
new file mode 100644
index 000000000..3caed957e
--- /dev/null
+++ b/.changeset/cancel-descendant-turns.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Cancel active local, nested, and remote subagent turns when their parent turn is cancelled. Client and eval sessions can now cancel active turns directly, and eval live-turn handles can wait for typed mid-turn events before cancellation or settlement.
diff --git a/.changeset/eve-channel-cancel-turn-route.md b/.changeset/eve-channel-cancel-turn-route.md
index dc70124b1..f2e1e1b1a 100644
--- a/.changeset/eve-channel-cancel-turn-route.md
+++ b/.changeset/eve-channel-cancel-turn-route.md
@@ -2,4 +2,4 @@
"eve": patch
---
-Added `POST /eve/v1/session/:sessionId/cancel` to the eve HTTP channel for requesting cancellation of an in-flight turn. The optional `{ turnId }` body limits the request to the turn the caller observed; the response reports `"cancelling"` when a cancellation hook accepts it or the benign `"no_active_turn"` when no resumable target exists.
+Added `POST /eve/v1/session/:sessionId/cancel` to the eve HTTP channel for requesting cancellation of an in-flight turn. The optional `{ turnId }` body limits the request to the turn the caller observed; the response reports `"accepted"` when a cancellation hook accepts it or the benign `"no_active_turn"` when no resumable target exists.
diff --git a/docs/channels/eve.mdx b/docs/channels/eve.mdx
index 667438666..0c8f7e6e3 100644
--- a/docs/channels/eve.mdx
+++ b/docs/channels/eve.mdx
@@ -49,10 +49,10 @@ Cancel a session's in-flight turn with an empty body, or scope the cancel to the
```bash
curl -X POST https://<deployment>/eve/v1/session/ses_01h.../cancel
-# {"ok":true,"sessionId":"ses_01h...","status":"cancelling"}
+# {"ok":true,"sessionId":"ses_01h...","status":"accepted"}
```
-Cancellation is asynchronous: `"cancelling"` means a cancellation hook accepted the request. Confirm the effective outcome on the stream as `turn.cancelled` followed by `session.waiting` — never as a failure. Content emitted before the cancel stays on the event stream, while durable model history keeps only content that had already settled. The session accepts the next message normally. When there is no resumable cancellation target (including an unknown session, a settled turn, or a duplicate cancel), the route responds with `"no_active_turn"` — also a success, so a stop button can fire and forget. A `turnId` naming any other turn is accepted and consumed as a no-op, so a guarded cancel racing a turn boundary cannot stop a turn the caller never saw.
+Cancellation is asynchronous: `"accepted"` means a cancellation hook accepted the request. Confirm the effective outcome on the stream as `turn.cancelled` followed by `session.waiting` — never as a failure. Active local and remote subagents are cancelled recursively before the parent settles; their own streams carry their cancellation boundaries, and cancelled work does not emit `subagent.completed` on the parent. Content emitted before the cancel stays on the event stream, while durable model history keeps only content that had already settled. The session accepts the next message normally. When there is no resumable cancellation target (including an unknown session, a settled turn, or a duplicate cancel), the route responds with `"no_active_turn"` — also a success, so a stop button can fire and forget. A `turnId` naming any other turn is accepted and consumed as a no-op, so a guarded cancel racing a turn boundary cannot stop a turn the caller never saw.
See [Sessions, runs & streaming](../concepts/sessions-runs-and-streaming) for the full request and stream flow, including the complete event set.
diff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.md
index f63679c49..b2ba304f3 100644
--- a/docs/concepts/sessions-runs-and-streaming.md
+++ b/docs/concepts/sessions-runs-and-streaming.md
@@ -95,10 +95,10 @@ POST to the session's cancel endpoint to stop the turn that is currently running
```bash
curl -X POST http://127.0.0.1:3000/eve/v1/session/<sessionId>/cancel
-# {"ok":true,"sessionId":"<sessionId>","status":"cancelling"}
+# {"ok":true,"sessionId":"<sessionId>","status":"accepted"}
```
-`"cancelling"` means a cancellation hook accepted the request. Confirm cancellation on the stream as `turn.cancelled` followed by `session.waiting`; the session then accepts the next message normally. `"no_active_turn"` means no resumable cancellation target exists, including an unknown session or an already-settled turn. Both statuses are success, so clients can fire and forget. See the [eve channel](../channels/eve) for the full route contract.
+`"accepted"` means a cancellation hook accepted the request. Confirm cancellation on the stream as `turn.cancelled` followed by `session.waiting`; the session then accepts the next message normally. If the turn is waiting on active local or remote subagents, eve also requests cancellation of every adopted child, recursively, before settling the parent. Each child reports its own cancellation boundary on its child-session stream; the parent does not emit `subagent.completed` for cancelled work. `"no_active_turn"` means no resumable cancellation target exists, including an unknown session or an already-settled turn. Both statuses are success, so clients can fire and forget. See the [eve channel](../channels/eve) for the full route contract.
## Reconnect and rewind
diff --git a/docs/evals/assertions.mdx b/docs/evals/assertions.mdx
index 924770c9d..0a834a1f1 100644
--- a/docs/evals/assertions.mdx
+++ b/docs/evals/assertions.mdx
@@ -22,7 +22,7 @@ Scoped assertions take no explicit value and gate by default. Assertions on `t`
| `t.usedNoTools()` | No tool calls at all |
| `t.maxToolCalls(n)` | At most `n` tool calls |
| `t.noFailedActions()` | No tool, subagent, or skill action reported a failure |
-| `t.calledSubagent(name, opts?)` | A subagent delegation happened (`remoteUrl`, `output` constraints) |
+| `t.calledSubagent(name, opts?)` | A subagent delegation happened (identity, remote, output, status, count) |
| `t.event(type, opts?)` / `t.notEvent(type, opts?)` | Typed event presence, data, and count matching |
| `t.eventOrder([...matchers])` | Matching event groups occur in order |
| `t.eventsSatisfy(label, predicate)` | Escape hatch: any predicate over the typed event stream |
@@ -77,7 +77,7 @@ Pick the cheapest builder that captures what "correct" means. When exact match i
## The matcher mini-language
-`t.calledTool` and `t.calledSubagent` take matcher objects. Tools accept `{ input, output, status, count }`; subagents accept `{ remoteUrl, output, status, count }`. Calls match `status: "completed"` by default; use `"pending"`, `"failed"`, or `"rejected"` explicitly for lifecycle checks. A numeric `count` requires an exact number of calls matching every supplied constraint. Use a predicate for ranges or other custom count requirements; it receives the observed number of matching calls.
+`t.calledTool` and `t.calledSubagent` take matcher objects. Tools accept `{ input, output, status, count }`; subagents accept `{ callId, childSessionId, remoteUrl, output, status, count }`. Calls match `status: "completed"` by default; use `"pending"`, `"failed"`, or `"rejected"` explicitly for lifecycle checks. A numeric `count` requires an exact number of calls matching every supplied constraint. Use a predicate for ranges or other custom count requirements; it receives the observed number of matching calls.
Matcher values accept a literal (objects partial-deep-match), a RegExp, or a predicate function that returns a boolean:
diff --git a/docs/evals/cases.mdx b/docs/evals/cases.mdx
index 762b38dc6..22821be54 100644
--- a/docs/evals/cases.mdx
+++ b/docs/evals/cases.mdx
@@ -102,6 +102,8 @@ export default defineEval({
`t` drives the primary session; `t.newSession()` returns an independent `EveEvalSession` against the same target, whose events feed the same run-level assertions.
- `t.send(input)` sends a turn and waits for it to settle. It accepts the same input as `ClientSession.send()` (a string or a structured message) and resolves to a turn carrying `.message` and `.expectOk()`.
+- `t.start(input)` starts a turn but returns as soon as the server accepts it. The returned live turn exposes `.sessionId`, `.waitForEvent(...)`, `.cancel()`, and `.result()` for coordinating with work that is still running.
+- `t.cancel()` requests cooperative cancellation of the primary session's active turn. Both `accepted` and `no_active_turn` are successful outcomes.
- `t.sendFile(text, path, mediaType?)` attaches a local file as a data URL.
- `t.requireInputRequest(filter?)` records a gate, requires exactly one pending request, and returns it. Filters match tool name, action input, prompt, display, and option ids.
- `t.respond(...responses)` answers specific pending input requests and sends them as the next turn.
@@ -110,6 +112,35 @@ export default defineEval({
Each `send` (and `respond`/`respondAll`) resolves to an immutable turn with `.message`, `.data`, `.events`, `.inputRequests`, `.toolCalls`, `.sessionId`, `.status`, and `.expectOk()`. Use `.sessionId` to relate turns or attach follow-up work to the session that produced a specific turn. `expectOk()` throws only when the turn ended failed; a session left open for a next message is the normal end state of a successful turn.
+## In-flight turns
+
+Use `start()` when the eval must observe or affect a turn before it settles. A live turn owns one stream consumer: `waitForEvent()` reads typed events from its buffer, and `result()` waits for the boundary and records the same buffered stream as an immutable turn. Event data matchers use the same partial-deep matcher language as `t.event(...)`.
+
+```ts title="evals/cancel-running-tool.eval.ts"
+import { defineEval } from "eve/evals";
+
+export default defineEval({
+ async test(t) {
+ const live = await t.start("Run the long operation.");
+
+ await live.waitForEvent("actions.requested", {
+ data: {
+ actions: (actions) =>
+ actions.some(
+ (action) => action.kind === "tool-call" && action.toolName === "long_operation",
+ ),
+ },
+ });
+
+ await live.cancel();
+ const turn = await live.result();
+ turn.eventOrder([{ type: "turn.cancelled" }, { type: "session.waiting" }]);
+ },
+});
+```
+
+`waitForEvent()` rejects if the stream fails or reaches its turn boundary before the requested event. Call `result()` after any coordination to settle the stream and make its events available to run-level assertions.
+
Use `expectOk()` only when the next operation depends on that intermediate turn succeeding. A final `t.succeeded()` already records a complete-run gate.
To intentionally omit an eval for the current target, call `t.skip(reason)` before sending messages or recording assertions. Skipped evals are reported separately and do not affect the exit code.
diff --git a/docs/evals/overview.mdx b/docs/evals/overview.mdx
index 6fe6691a9..2e3f6687a 100644
--- a/docs/evals/overview.mdx
+++ b/docs/evals/overview.mdx
@@ -100,7 +100,7 @@ model: mockModel({
`t` is both the driver and the assertion surface. There are no separate `input`, `run`, `checks`, or `scores` fields. You write ordinary control flow, sending turns and asserting inline.
-- **Drive** the agent: `t.send(...)`, `t.respond(...)`, `t.respondAll(...)`, `t.sendFile(...)`, `t.requireInputRequest(...)`, `t.newSession()`. Read what came back with `t.reply` (the last assistant message), `t.sessionId`, and `t.events`. See [Cases](./cases).
+- **Drive** the agent: `t.send(...)`, `t.start(...)`, `t.cancel()`, `t.respond(...)`, `t.respondAll(...)`, `t.sendFile(...)`, `t.requireInputRequest(...)`, `t.newSession()`. Live turns returned by `start()` can wait for typed mid-turn events before cancellation or settlement. Read what came back with `t.reply` (the last assistant message), `t.sessionId`, and `t.events`. See [Cases](./cases).
- **Assert** with three surfaces, covered next.
## Three assertion surfaces
diff --git a/docs/evals/targets.mdx b/docs/evals/targets.mdx
index 1b8b0549e..e740b3d97 100644
--- a/docs/evals/targets.mdx
+++ b/docs/evals/targets.mdx
@@ -25,6 +25,7 @@ export default defineEval({
- `t.target.fetch(path, init)` performs an authenticated fetch against the target, useful for channel and webhook ingress. See [Authentication](#authentication) for how the runner authenticates.
- `t.target.dispatchSchedule(id)` triggers a [schedule](../schedules) through the dev-only schedule route and returns the session ids it created. It works only against a target with dev routes enabled (the local `eve eval` dev server, or a deployment running in development mode), and throws otherwise.
- `t.target.attachSession(sessionId, { startIndex? })` consumes one turn from a session created outside the eval, by a channel or a schedule, so its events feed the run-level assertions. `startIndex` skips events before that position, so a session already partway through its stream resumes from where you left off rather than replaying from the start. When the consumed turn parks (`session.waiting`), the attached session recovers the current continuation token from the stream, so `session.send(...)` and `session.respond(...)` continue the same durable session.
+- `t.target.watchTurn(sessionId, { startIndex? })` starts consuming an externally-created turn immediately and returns a live-turn handle. Use `waitForEvent(...)` to coordinate with mid-turn work, `cancel()` to request cancellation, and `result()` to consume through the boundary. The live turn's `.session` is the attached `EveEvalSession` for follow-up sends after settlement.
Sessions attached this way are full `EveEvalSession`s: you can keep driving them and assert directly on that session (`session.succeeded()`, `session.calledTool(...)`). Aggregate assertions on `t` continue to read the whole run, including every attached session.
diff --git a/docs/guides/client/continuations.mdx b/docs/guides/client/continuations.mdx
index a86b49625..18f26eece 100644
--- a/docs/guides/client/continuations.mdx
+++ b/docs/guides/client/continuations.mdx
@@ -23,6 +23,8 @@ await response.result();
await saveSessionState(session.state);
```
+As soon as `send()` returns, `session.state.sessionId` identifies the accepted in-flight turn for cancellation or stream reconnection. Consume the response before saving a fully advanced cursor: the continuation token and `streamIndex` update as events reach the turn boundary.
+
Store the full state object:
```ts
diff --git a/docs/guides/client/streaming.mdx b/docs/guides/client/streaming.mdx
index 179941660..10feeb6ae 100644
--- a/docs/guides/client/streaming.mdx
+++ b/docs/guides/client/streaming.mdx
@@ -5,6 +5,20 @@ description: "Consume eve client stream events live, reconnect by event index, a
Every `ClientSession.send()` call posts the turn, then reads the session's NDJSON (newline-delimited JSON) event stream. `MessageResponse` gives you two ways to consume that stream, aggregating it with `result()` or iterating it live.
+Once `send()` is accepted, the session exposes its assigned `sessionId` and can request cooperative cancellation with `session.cancel()`, even while the response stream is still running. The result status is `accepted` when the active turn accepted the signal or `no_active_turn` when it already settled:
+
+```ts
+const session = client.session();
+const response = await session.send("Run the long operation.");
+
+const cancellation = await session.cancel();
+console.log(cancellation.status);
+
+const result = await response.result();
+```
+
+Cancellation does not replace stream consumption. Continue reading the response to observe its terminal `turn.cancelled` and `session.waiting` boundary and to advance the client session cursor normally.
+
## Aggregate a turn
Use `result()` when you only need the final turn summary:
diff --git a/docs/guides/remote-agents.md b/docs/guides/remote-agents.md
index dd3c95c9b..2d8e103c5 100644
--- a/docs/guides/remote-agents.md
+++ b/docs/guides/remote-agents.md
@@ -70,6 +70,8 @@ A local subagent runs inline. A remote one runs in its own deployment, so dispat
The parent stream carries the same `subagent.called`, `action.result`, and `subagent.completed` events as local delegation. For a remote call, `subagent.called.data.remote.url` records the target.
+Cancelling the parent while a remote call is active sends an authenticated `POST /eve/v1/session/:childSessionId/cancel` to the remote and waits for that request to be accepted before the parent settles. eve resolves the remote's `headers` and `auth` again for every cancellation attempt, so rotating credentials work the same way as they do for session creation. Cancellation always uses the standard eve cancel path on `url`, even when `path` customizes only the create-session endpoint. The remote child reports `turn.cancelled` → `session.waiting` on its own stream; an older or unreachable remote is logged but cannot turn the parent's cancellation into a failure.
+
Both failure paths surface to the parent as a failed tool result, so the caller can explain or recover within the same session. A failed _start_ returns the error inline. A remote that starts and then fails posts a terminal failure callback, which the parent receives as an errored subagent result carrying the remote's error (or `REMOTE_AGENT_FAILED` when none is supplied). Terminal callback delivery runs as a durable step on the underlying workflow engine (see [Execution model & durability](../concepts/execution-model-and-durability)). A failed callback POST is rethrown rather than marking the task complete, so the engine retries it.
## What to read next
diff --git a/docs/subagents.mdx b/docs/subagents.mdx
index 74481fc4e..883998953 100644
--- a/docs/subagents.mdx
+++ b/docs/subagents.mdx
@@ -106,6 +106,8 @@ Do not rely on subagent delegation by itself as an approval boundary. Put sensit
Each delegated subagent spins up its own child session and stream. The parent stream carries the control-plane events `subagent.called` and `subagent.completed`, plus interactive `input.requested`, `authorization.required`, and `authorization.completed` events proxied from descendants so the root channel can prompt the user. To follow the child's other progress, read `subagent.called.data.childSessionId` and subscribe at `GET /eve/v1/session/:childSessionId/stream`.
+Cancelling a parent turn also requests cancellation of every active child it started, recursively through nested and remote subagents. Each affected session emits its own `turn.cancelled` → `session.waiting` boundary; the cancelled parent does not synthesize tool results or emit `subagent.completed`. A child that already completed or parked has no active turn and is a benign no-op.
+
Subagent model calls automatically retry classified transient provider failures, including overload errors delivered after a stream starts. eve makes at most three fresh model-call attempts, repeating only the current uncommitted call so completed earlier steps, tool results, and sandbox work remain available to the child. Other recoverable task errors fall back to Workflow's durable step retry from the last committed session snapshot. Exhausting the transient model-call attempts or the dedicated empty-response reissue returns one failed task result instead of stacking both retry budgets; terminal errors fail immediately.
## When to split
diff --git a/e2e/fixtures/agent-cancellation/agent/instructions.md b/e2e/fixtures/agent-cancellation/agent/instructions.md
index ed44093bf..db2c23427 100644
--- a/e2e/fixtures/agent-cancellation/agent/instructions.md
+++ b/e2e/fixtures/agent-cancellation/agent/instructions.md
@@ -4,7 +4,9 @@ You are a test fixture agent for turn-cancellation coverage.
# Rules
-- When the user asks you to wait for cancellation, call the
+- When the user asks you to delegate a cancellation wait, call the `sleeper`
+ subagent exactly once and tell it to wait for cancellation.
+- When the user asks you to wait for cancellation yourself, call the
`wait-for-cancellation` tool exactly once, immediately, with no preamble
text before the call.
- For any other request, answer directly and concisely without calling
diff --git a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.ts b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.ts
new file mode 100644
index 000000000..d711cad62
--- /dev/null
+++ b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.ts
@@ -0,0 +1,6 @@
+import { defineAgent } from "eve";
+
+export default defineAgent({
+ description: "Waits until its delegated turn is cancelled.",
+ model: process.env.EVE_E2E_MODEL ?? "openai/gpt-5.6-sol",
+});
diff --git a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.md b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.md
new file mode 100644
index 000000000..fc296da3c
--- /dev/null
+++ b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.md
@@ -0,0 +1,8 @@
+# Identity
+
+You are a cancellation test sleeper.
+
+# Rules
+
+- Call `wait-for-cancellation` exactly once, immediately, with no preamble.
+- Do not call any other tool.
diff --git a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/tools/wait-for-cancellation.ts b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/tools/wait-for-cancellation.ts
new file mode 100644
index 000000000..cd11ab185
--- /dev/null
+++ b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/tools/wait-for-cancellation.ts
@@ -0,0 +1,24 @@
+import { defineTool } from "eve/tools";
+import { never } from "eve/tools/approval";
+import { z } from "zod";
+
+const FALLBACK_TIMEOUT_MS = 90_000;
+
+export default defineTool({
+ description: "Waits until the delegated turn is cancelled.",
+ inputSchema: z.object({}),
+ approval: never(),
+ execute(_input, ctx) {
+ return new Promise<string>((resolve, reject) => {
+ const timer = setTimeout(() => {
+ resolve("wait-for-cancellation: fallback timeout reached without cancellation");
+ }, FALLBACK_TIMEOUT_MS);
+ const abort = (): void => {
+ clearTimeout(timer);
+ reject(ctx.abortSignal.reason);
+ };
+ if (ctx.abortSignal.aborted) return abort();
+ ctx.abortSignal.addEventListener("abort", abort, { once: true });
+ });
+ },
+});
diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-subagent.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-subagent.eval.ts
new file mode 100644
index 000000000..f7d46e79e
--- /dev/null
+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-subagent.eval.ts
@@ -0,0 +1,52 @@
+import { defineEval } from "eve/evals";
+import { satisfies } from "eve/evals/expect";
+
+export default defineEval({
+ description: "Cancel a parent turn and cascade cancellation to its local sleeper subagent.",
+ timeoutMs: 240_000,
+
+ async test(t) {
+ const parent = await t.start("Delegate a cancellation wait to the sleeper subagent.");
+ const called = await parent.waitForEvent("subagent.called", {
+ data: { name: "sleeper" },
+ });
+
+ const child = t.target.watchTurn(called.data.childSessionId);
+ await child.waitForEvent("actions.requested", {
+ data: {
+ actions: (actions) =>
+ actions.some(
+ (action) => action.kind === "tool-call" && action.toolName === "wait-for-cancellation",
+ ),
+ },
+ });
+
+ const cancelled = await parent.cancel();
+ await t.require(
+ cancelled,
+ satisfies(
+ (value: typeof cancelled) => value.status === "accepted",
+ "parent cancel request is accepted",
+ ),
+ );
+
+ const [parentTurn, childTurn] = await Promise.all([parent.result(), child.result()]);
+ childTurn.event("turn.cancelled", { count: 1 });
+ childTurn.eventOrder([{ type: "turn.cancelled" }, { type: "session.waiting" }]);
+ childTurn.notEvent("turn.failed");
+ childTurn.notEvent("session.failed");
+
+ parentTurn.event("turn.cancelled", { count: 1 });
+ parentTurn.eventOrder([{ type: "turn.cancelled" }, { type: "session.waiting" }]);
+ parentTurn.notEvent("subagent.completed");
+ parentTurn.notEvent("turn.failed");
+ parentTurn.notEvent("session.failed");
+
+ const followUp = await t.send("Reply with exactly CANCELLATION-SUBAGENT-FOLLOW-UP-OK.");
+ followUp.expectOk();
+ followUp.notEvent("turn.cancelled");
+ followUp.messageIncludes(/CANCELLATION-SUBAGENT-FOLLOW-UP-OK/i);
+
+ t.event("turn.cancelled", { count: 2 });
+ },
+});
diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-turn.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-turn.eval.ts
index 322f44beb..ec9f523ef 100644
--- a/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-turn.eval.ts
+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-turn.eval.ts
@@ -1,170 +1,65 @@
-import { defineEval, type EveEvalContext, type EveEvalTargetHandle } from "eve/evals";
+import { defineEval } from "eve/evals";
import { satisfies } from "eve/evals/expect";
const TOOL_NAME = "wait-for-cancellation";
-interface CreateSessionResponse {
- readonly ok: boolean;
- readonly sessionId?: string;
-}
-
-interface CancelTurnResponse {
- readonly ok: boolean;
- readonly sessionId?: string;
- readonly status?: "cancelling" | "no_active_turn";
-}
-
-async function postJson<T>(
- target: EveEvalTargetHandle,
- path: string,
- body?: unknown,
-): Promise<{ readonly payload: T; readonly status: number }> {
- const response = await target.fetch(path, {
- ...(body === undefined
- ? {}
- : { body: JSON.stringify(body), headers: { "content-type": "application/json" } }),
- method: "POST",
- });
- const text = await response.text();
- let payload: T;
- try {
- payload = JSON.parse(text) as T;
- } catch {
- throw new Error(`POST ${path} returned non-JSON (${response.status}): ${text}`);
- }
- return { payload, status: response.status };
-}
-
-async function waitForToolCall(t: EveEvalContext, sessionId: string): Promise<void> {
- const controller = new AbortController();
- const signal = AbortSignal.any([controller.signal, t.signal]);
-
- try {
- const response = await t.target.fetch(
- `/eve/v1/session/${encodeURIComponent(sessionId)}/stream`,
- { method: "GET", signal },
- );
- if (!response.ok || response.body === null) {
- throw new Error(`Stream request failed (${response.status}).`);
- }
-
- const reader = response.body.getReader();
- const decoder = new TextDecoder();
- let buffered = "";
-
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
- buffered += decoder.decode(value, { stream: true });
-
- const lines = buffered.split("\n");
- buffered = lines.pop() ?? "";
- for (const line of lines) {
- if (line.trim().length === 0) continue;
- const event = JSON.parse(line) as {
- type: string;
- data?: { actions?: readonly { kind?: string; toolName?: string }[] };
- };
- if (
- event.type === "actions.requested" &&
- event.data?.actions?.some(
- (action) => action.kind === "tool-call" && action.toolName === TOOL_NAME,
- ) === true
- ) {
- return;
- }
- if (event.type === "turn.failed" || event.type === "session.failed") {
- throw new Error(`Turn failed before the ${TOOL_NAME} tool was called.`);
- }
- if (event.type === "session.waiting") {
- throw new Error(`Turn settled before the ${TOOL_NAME} tool was called.`);
- }
- }
- }
- throw new Error(`Stream closed before the ${TOOL_NAME} tool was called.`);
- } finally {
- controller.abort();
- }
-}
-
/**
* Cancel an in-flight turn over the eve HTTP channel.
*
- * Flow: start a turn that hangs mid-tool, POST
- * `/eve/v1/session/:id/cancel`, and assert the turn settles as
- * `turn.cancelled` followed by `session.waiting` with zero failure
- * events — then prove the session accepts a follow-up message normally
- * and a late duplicate cancel reports the benign `no_active_turn`.
+ * Flow: start a turn that hangs mid-tool, request cooperative cancellation,
+ * and assert the turn settles as `turn.cancelled` followed by
+ * `session.waiting` with zero failure events. Then prove the session accepts a
+ * follow-up normally and a late duplicate cancel reports the benign
+ * `no_active_turn` outcome.
*/
export default defineEval({
description: "Cancel an in-flight turn over the eve HTTP cancel route.",
timeoutMs: 240_000,
async test(t) {
- const created = await postJson<CreateSessionResponse>(t.target, "/eve/v1/session", {
- message: "Please wait for cancellation.",
+ const live = await t.start("Please wait for cancellation.");
+ await live.waitForEvent("actions.requested", {
+ data: {
+ actions: (actions) =>
+ actions.some((action) => action.kind === "tool-call" && action.toolName === TOOL_NAME),
+ },
});
- await t.require(
- created,
- satisfies(
- (value: typeof created) =>
- value.status === 202 &&
- value.payload.ok === true &&
- typeof value.payload.sessionId === "string",
- "create session returns a session id",
- ),
- );
- const sessionId = created.payload.sessionId!;
- const cancelPath = `/eve/v1/session/${encodeURIComponent(sessionId)}/cancel`;
-
- await waitForToolCall(t, sessionId);
- t.log(`Tool call observed mid-turn; cancelling session ${sessionId}.`);
+ t.log(`Tool call observed mid-turn; cancelling session ${live.sessionId}.`);
- const cancelled = await postJson<CancelTurnResponse>(t.target, cancelPath);
+ const cancelled = await live.cancel();
await t.require(
cancelled,
satisfies(
(value: typeof cancelled) =>
- value.status === 202 &&
- value.payload.ok === true &&
- value.payload.sessionId === sessionId &&
- value.payload.status === "cancelling",
- "cancel route accepts the cancel with status 'cancelling'",
+ value.sessionId === live.sessionId && value.status === "accepted",
+ "cancel request is accepted with status 'accepted'",
),
);
- // The cancelled turn: turn.cancelled → session.waiting, never a failure.
- // The attach recovers the continuation token from the cancelled turn's
- // `session.waiting` boundary, so the same handle can send follow-ups.
- const session = await t.target.attachSession(sessionId, { startIndex: 0 });
- session.event("turn.cancelled", { count: 1 });
- session.eventOrder([{ type: "turn.cancelled" }, { type: "session.waiting" }]);
- session.notEvent("turn.failed");
- session.notEvent("step.failed");
- session.notEvent("session.failed");
+ const cancelledTurn = await live.result();
+ cancelledTurn.event("turn.cancelled", { count: 1 });
+ cancelledTurn.eventOrder([{ type: "turn.cancelled" }, { type: "session.waiting" }]);
+ cancelledTurn.notEvent("turn.failed");
+ cancelledTurn.notEvent("step.failed");
+ cancelledTurn.notEvent("session.failed");
- // The session accepts the next message normally.
- const followUp = await session.send("Reply with exactly CANCELLATION-FOLLOW-UP-OK.");
+ const followUp = await t.send("Reply with exactly CANCELLATION-FOLLOW-UP-OK.");
followUp.expectOk();
followUp.notEvent("turn.cancelled");
followUp.notEvent("turn.failed");
followUp.notEvent("session.failed");
followUp.messageIncludes(/CANCELLATION-FOLLOW-UP-OK/i);
- // With the session parked and the settled turn's hook swept, a
- // duplicate cancel is the benign "nothing to cancel" success. The
- // sweep is asynchronous, so poll briefly.
- let lateStatus: CancelTurnResponse["status"];
+ let lateStatus: "accepted" | "no_active_turn" | undefined;
for (let attempt = 0; attempt < 30; attempt += 1) {
- const late = await postJson<CancelTurnResponse>(t.target, cancelPath);
- lateStatus = late.payload.status;
- if (late.status === 202 && lateStatus === "no_active_turn") break;
+ lateStatus = (await t.cancel()).status;
+ if (lateStatus === "no_active_turn") break;
await t.sleep(500);
}
await t.require(
lateStatus,
satisfies(
- (value: CancelTurnResponse["status"]) => value === "no_active_turn",
+ (value: typeof lateStatus) => value === "no_active_turn",
"a late cancel reports no_active_turn",
),
);
diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.ts
index 608a3889a..744ebd5cd 100644
--- a/packages/eve/src/channel/types.ts
+++ b/packages/eve/src/channel/types.ts
@@ -1,6 +1,7 @@
import type { UserContent } from "ai";
import type { HandleMessageStreamEvent } from "#protocol/message.js";
+import type { CancelTurnStatus } from "#protocol/cancel-turn.js";
import type { RunMode } from "#shared/run-mode.js";
import type { RuntimeActionResult } from "#runtime/actions/types.js";
import type { InputRequest, InputResponse } from "#runtime/input/types.js";
@@ -27,7 +28,7 @@ export interface CancelTurnInput {
/** Result of requesting turn cancellation. Both statuses are successful. */
export interface CancelTurnResult {
- readonly status: "cancelling" | "no_active_turn";
+ readonly status: CancelTurnStatus;
}
// ---------------------------------------------------------------------------
diff --git a/packages/eve/src/client/index.ts b/packages/eve/src/client/index.ts
index 57bdad743..0ab0f5cfe 100644
--- a/packages/eve/src/client/index.ts
+++ b/packages/eve/src/client/index.ts
@@ -42,6 +42,7 @@ export type {
AgentInfoSubagentEntry,
AgentInfoToolEntry,
AgentInfoTools,
+ CancelSessionResult,
ClientAuth,
ClientOptions,
ClientRedirectPolicy,
diff --git a/packages/eve/src/client/session.test.ts b/packages/eve/src/client/session.test.ts
index ec882f88d..8aad984dd 100644
--- a/packages/eve/src/client/session.test.ts
+++ b/packages/eve/src/client/session.test.ts
@@ -12,15 +12,16 @@ function createSession(
options: {
readonly maxReconnectAttempts?: number;
readonly preserveCompletedSessions?: boolean;
+ readonly redirect?: "error" | "follow" | "manual";
+ readonly resolveHeaders?: () => Promise<Headers>;
} = {},
) {
const context: ConstructorParameters<typeof ClientSession>[0] = {
host: "https://eve.test",
maxReconnectAttempts: options.maxReconnectAttempts ?? 0,
preserveCompletedSessions: options.preserveCompletedSessions ?? false,
- async resolveHeaders() {
- return new Headers();
- },
+ redirect: options.redirect,
+ resolveHeaders: options.resolveHeaders ?? (async () => new Headers()),
};
return new ClientSession(context, state);
@@ -52,6 +53,64 @@ function createStreamResponse(events: readonly unknown[]) {
}
describe("ClientSession", () => {
+ it("cancels an accepted turn before its stream settles with freshly resolved auth", async () => {
+ let headerResolution = 0;
+ const requests: Array<{ headers: Headers; method: string; url: string }> = [];
+ vi.spyOn(globalThis, "fetch").mockImplementation(async (request, init) => {
+ const url =
+ typeof request === "string" ? request : request instanceof URL ? request.href : request.url;
+ requests.push({
+ headers: new Headers(init?.headers),
+ method: init?.method ?? "GET",
+ url,
+ });
+ if (new URL(url).pathname.endsWith("/cancel")) {
+ return Response.json(
+ { ok: true, sessionId: "session_1", status: "accepted" },
+ { status: 202 },
+ );
+ }
+ return createAcceptedResponse();
+ });
+ const session = createSession(
+ { streamIndex: 0 },
+ {
+ redirect: "error",
+ resolveHeaders: async () => {
+ headerResolution += 1;
+ return new Headers({ authorization: `Bearer token-${headerResolution}` });
+ },
+ },
+ );
+
+ const turn = await session.send("wait");
+ const cancelled = await session.cancel();
+
+ expect(turn.sessionId).toBe("session_1");
+ expect(session.state.sessionId).toBe("session_1");
+ expect(cancelled).toEqual({ sessionId: "session_1", status: "accepted" });
+ expect(requests).toHaveLength(2);
+ expect(new URL(requests[1]!.url).pathname).toBe("/eve/v1/session/session_1/cancel");
+ expect(requests[1]!.method).toBe("POST");
+ expect(requests[1]!.headers.get("authorization")).toBe("Bearer token-2");
+ });
+
+ it("rejects cancellation before a session has started", async () => {
+ await expect(createSession().cancel()).rejects.toThrow("Session has no session ID");
+ });
+
+ it("rejects a cancel response for a different session", async () => {
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ Response.json(
+ { ok: true, sessionId: "another-session", status: "accepted" },
+ { status: 202 },
+ ),
+ );
+ const session = createSession({ sessionId: "session_1", streamIndex: 0 });
+
+ await expect(session.cancel()).rejects.toThrow("Cancel route returned an invalid response");
+ });
+
it("serializes clientContext when sending a create-session message", async () => {
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(createAcceptedResponse());
const session = createSession();
diff --git a/packages/eve/src/client/session.ts b/packages/eve/src/client/session.ts
index 39eaa9b58..36e43d4e6 100644
--- a/packages/eve/src/client/session.ts
+++ b/packages/eve/src/client/session.ts
@@ -1,7 +1,9 @@
import type { HandleMessageStreamEvent } from "#protocol/message.js";
import { EVE_SESSION_ID_HEADER, isCurrentTurnBoundaryEvent } from "#protocol/message.js";
+import { CancelTurnResponseSchema } from "#protocol/cancel-turn.js";
import {
EVE_CREATE_SESSION_ROUTE_PATH,
+ createEveCancelTurnRoutePath,
createEveContinueSessionRoutePath,
} from "#protocol/routes.js";
import { ClientError } from "#client/client-error.js";
@@ -12,6 +14,7 @@ import { normalizeOutputSchemaForRequest } from "#client/output-schema.js";
import { advanceSession } from "#client/session-utils.js";
import { createClientUrl } from "#client/url.js";
import type {
+ CancelSessionResult,
ClientRedirectPolicy,
SendTurnInput,
SendTurnPayload,
@@ -52,8 +55,9 @@ export class ClientSession {
}
/**
- * Current session cursor. Always reflects the latest state after each
- * completed turn. Serialize this to persist and resume later.
+ * Current session cursor. The assigned session ID appears as soon as a send
+ * is accepted; the continuation token and stream index advance as its event
+ * stream is consumed. Serialize this to persist and resume later.
*/
get state(): SessionState {
return this.#state;
@@ -72,6 +76,12 @@ export class ClientSession {
const postResult = await this.#postTurn(payload, state);
const { continuationToken, sessionId } = postResult;
+ // Cancellation and observation can begin as soon as the POST is accepted,
+ // before the response stream reaches a turn boundary.
+ if (this.#state === state) {
+ this.#state = { ...state, sessionId };
+ }
+
return new MessageResponse<TOutput>({
continuationToken,
createStream: () => this.#createEventStream(sessionId, continuationToken, state, payload),
@@ -79,6 +89,49 @@ export class ClientSession {
});
}
+ /**
+ * Requests cooperative cancellation of this session's active turn.
+ *
+ * Both `accepted` and `no_active_turn` are successful outcomes. The latter
+ * means the active turn settled before the request arrived or the session is
+ * already parked. Credentials are resolved immediately before the request.
+ *
+ * @throws {Error} If this handle has not started or attached to a session.
+ * @throws {ClientError} If the cancel route returns a non-successful status.
+ */
+ async cancel(): Promise<CancelSessionResult> {
+ const sessionId = this.#state.sessionId;
+ if (!sessionId) {
+ throw new Error("Session has no session ID. Send a message first.");
+ }
+
+ const url = createClientUrl(this.#context.host, createEveCancelTurnRoutePath(sessionId));
+ const headers = await this.#context.resolveHeaders();
+ const response = await fetch(
+ url,
+ withRedirectPolicy({ headers, method: "POST" }, this.#context.redirect),
+ );
+ const body = await response.text();
+
+ if (!response.ok) {
+ throw new ClientError(response.status, body, response.headers);
+ }
+
+ let payload: unknown;
+ try {
+ payload = JSON.parse(body);
+ } catch {
+ throw new Error(`Cancel route returned invalid JSON (${response.status}).`);
+ }
+
+ const result = CancelTurnResponseSchema.safeParse(payload);
+ if (!result.success || result.data.sessionId !== sessionId) {
+ throw new Error(`Cancel route returned an invalid response (${response.status}).`);
+ }
+
+ return { sessionId: result.data.sessionId, status: result.data.status };
+ }
+
/**
* Opens this session's event stream for the current session ID.
*
@@ -374,3 +427,7 @@ function createHandleMessageBody(input: {
return body;
}
+
+function withRedirectPolicy(init: RequestInit, redirect?: ClientRedirectPolicy): RequestInit {
+ return redirect === undefined ? init : { ...init, redirect };
+}
diff --git a/packages/eve/src/client/types.ts b/packages/eve/src/client/types.ts
index f3d15590c..0711f164b 100644
--- a/packages/eve/src/client/types.ts
+++ b/packages/eve/src/client/types.ts
@@ -2,6 +2,7 @@ import type { UserContent } from "ai";
import type { StandardJSONSchemaV1 } from "#compiled/@standard-schema/spec/index.js";
import type { HandleMessageStreamEvent } from "#protocol/message.js";
+import type { CancelTurnStatus } from "#protocol/cancel-turn.js";
import type { InputRequest, InputResponse } from "#runtime/input/types.js";
import type { JsonObject } from "#shared/json.js";
@@ -186,6 +187,14 @@ export interface StreamOptions {
readonly signal?: AbortSignal;
}
+/** Result of requesting cancellation for a client session's active turn. */
+export interface CancelSessionResult {
+ /** Session whose active turn was targeted. */
+ readonly sessionId: string;
+ /** Both outcomes are successful; `no_active_turn` means there was nothing left to cancel. */
+ readonly status: CancelTurnStatus;
+}
+
/**
* Aggregated result of one message turn, returned by
* {@link MessageResponse.result}.
diff --git a/packages/eve/src/evals/assertions/run.test.ts b/packages/eve/src/evals/assertions/run.test.ts
index 2032b66c9..87950f584 100644
--- a/packages/eve/src/evals/assertions/run.test.ts
+++ b/packages/eve/src/evals/assertions/run.test.ts
@@ -35,6 +35,8 @@ function completedToolCall(name: string): EveEvalToolCall {
function subagentCall(name: string, status: EveEvalSubagentCall["status"]): EveEvalSubagentCall {
return {
+ callId: `call-${status}`,
+ childSessionId: `session-${status}`,
name,
output: status === "completed" ? "ok" : undefined,
status,
@@ -244,6 +246,16 @@ describe("run assertions", () => {
expect(
(await Run.calledSubagent("child", { count: (count) => count === 1 }).evaluate(result)).score,
).toBe(1);
+ expect(
+ (
+ await Run.calledSubagent("child", {
+ callId: "call-completed",
+ childSessionId: "session-completed",
+ count: 1,
+ status: "completed",
+ }).evaluate(result)
+ ).score,
+ ).toBe(1);
});
it("toolOrder checks request order", async () => {
diff --git a/packages/eve/src/evals/assertions/run.ts b/packages/eve/src/evals/assertions/run.ts
index caeef0faa..b51eae7cd 100644
--- a/packages/eve/src/evals/assertions/run.ts
+++ b/packages/eve/src/evals/assertions/run.ts
@@ -224,9 +224,9 @@ export function noFailedActions(): RunAssertion {
}
/**
- * Asserts a subagent delegation to `name` occurred. `remoteUrl` matches the
- * `subagent.called` remote metadata, `output` matches the `subagent.completed`
- * output.
+ * Asserts a subagent delegation to `name` occurred. Identity and remote
+ * metadata come from `subagent.called`; `output` comes from
+ * `subagent.completed`.
*/
export function calledSubagent(
name: string,
diff --git a/packages/eve/src/evals/context.ts b/packages/eve/src/evals/context.ts
index 62985a443..7c8e184f0 100644
--- a/packages/eve/src/evals/context.ts
+++ b/packages/eve/src/evals/context.ts
@@ -53,6 +53,7 @@ export function createEvalContext(deps: {
get sessionId() {
return primary().sessionId;
},
+ cancel: () => primary().cancel(),
requireInputRequest: (filter) => primary().requireInputRequest(filter),
respond: (...responses) => primary().respond(...responses),
respondAll: (optionId) => primary().respondAll(optionId),
@@ -60,6 +61,10 @@ export function createEvalContext(deps: {
lastPrompt = promptText(input);
return primary().send(input);
},
+ start: (input) => {
+ lastPrompt = promptText(input);
+ return primary().start(input);
+ },
sendFile: (text, filePath, mediaType) => {
lastPrompt = text;
return primary().sendFile(text, filePath, mediaType);
diff --git a/packages/eve/src/evals/index.ts b/packages/eve/src/evals/index.ts
index 29070843e..1633684ca 100644
--- a/packages/eve/src/evals/index.ts
+++ b/packages/eve/src/evals/index.ts
@@ -13,6 +13,7 @@ export { mockModel } from "#evals/mock-model.js";
export type { RuntimeIdentity } from "#protocol/message.js";
export type { InputRequest } from "#runtime/input/types.js";
+export type { CancelSessionResult } from "#client/types.js";
export type {
EveEvalCountMatcher,
@@ -45,6 +46,7 @@ export type {
EveEvalConfigInput,
EveEvalDefinition,
EveEvalInput,
+ EveEvalLiveTurn,
EveEvalResult,
EveEvalTarget,
EveEvalTargetCapabilities,
@@ -52,6 +54,8 @@ export type {
EveEvalTaskResult,
EveEvalToolCall,
EveEvalTurn,
+ EveEvalStreamEvent,
+ EveEvalWaitForEventOptions,
EveEvalVerdict,
JudgeContext,
JudgeOpts,
diff --git a/packages/eve/src/evals/match.ts b/packages/eve/src/evals/match.ts
index 0fe7778a8..a2a24c4cc 100644
--- a/packages/eve/src/evals/match.ts
+++ b/packages/eve/src/evals/match.ts
@@ -58,6 +58,10 @@ export type EveEvalSkillLoadMatchOptions = Omit<EveEvalToolCallMatchOptions, "in
* Constraints applied to subagent calls by `t.calledSubagent`.
*/
export interface EveEvalSubagentCallMatchOptions {
+ /** Matcher over the runtime-action call id. */
+ readonly callId?: EveEvalValueMatcher<string | undefined>;
+ /** Matcher over the durable child session id, when delegation started. */
+ readonly childSessionId?: EveEvalValueMatcher<string | undefined>;
/** Matcher over the `subagent.called` remote URL. */
readonly remoteUrl?: EveEvalValueMatcher<string | undefined>;
/** Matcher over the `subagent.completed` output. */
@@ -150,6 +154,15 @@ export function subagentCallMatches(
call: EveEvalSubagentCall,
options: EveEvalSubagentCallMatchOptions,
): boolean {
+ if (options.callId !== undefined && !matchesValue(options.callId, call.callId)) {
+ return false;
+ }
+ if (
+ options.childSessionId !== undefined &&
+ !matchesValue(options.childSessionId, call.childSessionId)
+ ) {
+ return false;
+ }
if (options.remoteUrl !== undefined && !matchesValue(options.remoteUrl, call.remoteUrl)) {
return false;
}
diff --git a/packages/eve/src/evals/runner/derive-run-facts.test.ts b/packages/eve/src/evals/runner/derive-run-facts.test.ts
index f22787c2f..c3d2c7d6d 100644
--- a/packages/eve/src/evals/runner/derive-run-facts.test.ts
+++ b/packages/eve/src/evals/runner/derive-run-facts.test.ts
@@ -319,6 +319,8 @@ describe("deriveRunFacts", () => {
const facts = deriveRunFacts(events, { sessionId: "s0" });
expect(facts.subagentCalls).toEqual([
{
+ callId: "c1",
+ childSessionId: "s1",
name: "weather",
remoteUrl: "http://127.0.0.1:4001",
output: "Sunny, 72F",
@@ -343,6 +345,7 @@ describe("deriveRunFacts", () => {
expect(facts.subagentCalls).toEqual([
{
+ callId: "c1",
name: "weather",
output: { code: "REMOTE_AGENT_START_FAILED" },
status: "failed",
diff --git a/packages/eve/src/evals/runner/derive-run-facts.ts b/packages/eve/src/evals/runner/derive-run-facts.ts
index b6660314f..a5d85b8c6 100644
--- a/packages/eve/src/evals/runner/derive-run-facts.ts
+++ b/packages/eve/src/evals/runner/derive-run-facts.ts
@@ -13,6 +13,8 @@ interface MutableToolCall {
}
interface MutableSubagentCall {
+ callId: string;
+ childSessionId?: string;
name: string;
remoteUrl?: string;
output?: JsonValue;
@@ -85,6 +87,7 @@ export function deriveRunFacts(
if (existing !== undefined) return existing;
const call: MutableSubagentCall = {
+ callId,
name,
status: "pending",
turnIndex: Math.max(turnIndex, 0),
@@ -126,6 +129,7 @@ export function deriveRunFacts(
case "subagent.called": {
const call = ensureSubagentCall(event.data.callId, event.data.name);
+ call.childSessionId = event.data.childSessionId;
if (event.data.remote !== undefined) {
call.remoteUrl = event.data.remote.url;
}
diff --git a/packages/eve/src/evals/runner/execute-task.test.ts b/packages/eve/src/evals/runner/execute-task.test.ts
index 329ff6f7a..11a7f281c 100644
--- a/packages/eve/src/evals/runner/execute-task.test.ts
+++ b/packages/eve/src/evals/runner/execute-task.test.ts
@@ -327,6 +327,130 @@ describe("executeTask", () => {
expect(outcome.error).toContain("skip() must be called before");
});
+ it("coordinates started and externally watched live turns through one stream owner", async () => {
+ const server = createScriptedServer(
+ [
+ {
+ sessionId: "parent-session",
+ events: [
+ turnStarted("parent-turn"),
+ subagentCalled("parent-turn", "child-session", "sleeper"),
+ turnCompleted("parent-turn"),
+ sessionWaiting("eve:parent-session"),
+ ],
+ },
+ {
+ sessionId: "child-session",
+ events: [
+ turnStarted("child-follow-up"),
+ messageCompleted("child continued", "child-follow-up"),
+ turnCompleted("child-follow-up"),
+ sessionWaiting("eve:child-session-next"),
+ ],
+ },
+ ],
+ {
+ cancelStatus: "accepted",
+ streams: [
+ {
+ sessionId: "child-session",
+ events: [
+ turnStarted("child-turn"),
+ actionsRequested("child-turn", "wait-for-cancellation"),
+ turnCompleted("child-turn"),
+ sessionWaiting("eve:child-session"),
+ ],
+ },
+ ],
+ },
+ );
+ vi.spyOn(globalThis, "fetch").mockImplementation(server.fetch);
+
+ const outcome = await executeTask({
+ client: new Client({ host: target.url }),
+ target,
+ evaluation: createTestEval(async (t) => {
+ const parent = await t.start("delegate");
+ expect(parent.sessionId).toBe("parent-session");
+
+ const called = await parent.waitForEvent("subagent.called", {
+ data: { name: "sleeper" },
+ });
+ expect(called.data.childSessionId).toBe("child-session");
+
+ const child = t.target.watchTurn(called.data.childSessionId);
+ const requested = await child.waitForEvent("actions.requested", {
+ data: {
+ actions: (actions) =>
+ actions.some(
+ (action) =>
+ action.kind === "tool-call" && action.toolName === "wait-for-cancellation",
+ ),
+ },
+ });
+ expect(requested.data.actions).toHaveLength(1);
+ await expect(parent.cancel()).resolves.toEqual({
+ sessionId: "parent-session",
+ status: "accepted",
+ });
+
+ const [parentTurn, childTurn] = await Promise.all([parent.result(), child.result()]);
+ expect(await parent.result()).toBe(parentTurn);
+ parentTurn.event("subagent.called", { count: 1 });
+ childTurn.calledTool("wait-for-cancellation", { status: "pending", count: 1 });
+ await expect(parent.waitForEvent("subagent.completed")).rejects.toThrow(/session\.waiting/);
+
+ const childFollowUp = await child.session.send("continue child");
+ childFollowUp.messageIncludes("child continued");
+ }, "live-turns"),
+ });
+
+ expect(outcome.error).toBeUndefined();
+ expect(server.cancels).toEqual(["parent-session"]);
+ expect(server.posts[1]?.body).toEqual({
+ continuationToken: "eve:child-session",
+ message: "continue child",
+ });
+ expect(outcome.result.sessions?.map((session) => session.sessionId)).toEqual([
+ "parent-session",
+ "child-session",
+ ]);
+ expect(outcome.assertions.every((assertion) => assertion.passed)).toBe(true);
+ });
+
+ it("fails unmatched live event waiters without rejecting the failed turn result", async () => {
+ const server = createScriptedServer([
+ {
+ sessionId: "failed-session",
+ events: [
+ turnStarted("failed-turn"),
+ {
+ data: {
+ code: "MODEL_FAILED",
+ message: "model failed",
+ sessionId: "failed-session",
+ },
+ type: "session.failed",
+ },
+ ],
+ },
+ ]);
+ vi.spyOn(globalThis, "fetch").mockImplementation(server.fetch);
+
+ const outcome = await executeTask({
+ client: new Client({ host: target.url }),
+ target,
+ evaluation: createTestEval(async (t) => {
+ const live = await t.start("fail");
+ await expect(live.waitForEvent("actions.requested")).rejects.toThrow(/session\.failed/);
+ await expect(live.result()).resolves.toMatchObject({ status: "failed" });
+ }, "live-turn-failure"),
+ });
+
+ expect(outcome.error).toBeUndefined();
+ expect(outcome.result.status).toBe("failed");
+ });
+
it("attaches to a target-created session and captures its stream", async () => {
const server = createScriptedServer([], {
streams: [
@@ -474,6 +598,7 @@ describe("executeTask", () => {
function createScriptedServer(
turns: readonly { events: readonly HandleMessageStreamEvent[]; sessionId: string }[],
options: {
+ readonly cancelStatus?: "accepted" | "no_active_turn";
readonly streams?: readonly {
readonly events: readonly HandleMessageStreamEvent[];
readonly sessionId: string;
@@ -483,6 +608,7 @@ function createScriptedServer(
const pendingTurns = [...turns];
const streamQueues = new Map<string, HandleMessageStreamEvent[][]>();
const posts: Array<{ body: unknown; method: string; url: string }> = [];
+ const cancels: string[] = [];
for (const stream of options.streams ?? []) {
const queue = streamQueues.get(stream.sessionId) ?? [];
@@ -491,11 +617,22 @@ function createScriptedServer(
}
return {
+ cancels,
posts,
async fetch(request: string | URL | Request, init?: RequestInit): Promise<Response> {
const url =
typeof request === "string" ? request : request instanceof URL ? request.href : request.url;
const method = init?.method ?? "GET";
+ const pathname = new URL(url).pathname;
+
+ if (method === "POST" && pathname.endsWith("/cancel")) {
+ const sessionId = decodeURIComponent(pathname.split("/").at(-2) ?? "");
+ cancels.push(sessionId);
+ return Response.json(
+ { ok: true, sessionId, status: options.cancelStatus ?? "no_active_turn" },
+ { status: 202 },
+ );
+ }
if (method === "POST") {
const next = pendingTurns.shift();
@@ -625,3 +762,23 @@ function actionsRequested(
type: "actions.requested",
};
}
+
+function subagentCalled(
+ turnId: string,
+ childSessionId: string,
+ name: string,
+): HandleMessageStreamEvent {
+ return {
+ data: {
+ callId: "call_subagent",
+ childSessionId,
+ sessionId: "parent-session",
+ sequence: 1,
+ name,
+ toolName: name,
+ turnId,
+ workflowId: "workflow_child",
+ },
+ type: "subagent.called",
+ };
+}
diff --git a/packages/eve/src/evals/session.ts b/packages/eve/src/evals/session.ts
index 6e78178b2..766a52915 100644
--- a/packages/eve/src/evals/session.ts
+++ b/packages/eve/src/evals/session.ts
@@ -4,7 +4,12 @@ import { basename, extname } from "node:path";
import { createTextWithFileContent } from "#client/file-parts.js";
import type { Client } from "#client/client.js";
import type { ClientSession } from "#client/session.js";
-import type { SendTurnInput, SendTurnPayload, SessionState } from "#client/types.js";
+import type {
+ CancelSessionResult,
+ SendTurnInput,
+ SendTurnPayload,
+ SessionState,
+} from "#client/types.js";
import type { HandleMessageStreamEvent, TurnFailureStreamEvent } from "#protocol/message.js";
import { isCurrentTurnBoundaryEvent, isTurnFailureEvent } from "#protocol/message.js";
import {
@@ -18,15 +23,18 @@ import { deriveRunFacts } from "#evals/runner/derive-run-facts.js";
import { AssertionCollector } from "#evals/assertions/collector.js";
import { createOutputAssertions, createScopedAssertions } from "#evals/assertions/scoped.js";
import { EvalRequirementFailed } from "#evals/control-flow.js";
-import { inputRequestMatches, toolCallMatches } from "#evals/match.js";
+import { inputRequestMatches, matchesValue, toolCallMatches } from "#evals/match.js";
import type {
EveEvalAssertions,
EveEvalDerivedFacts,
+ EveEvalLiveTurn,
EveEvalOutputAssertions,
EveEvalSession,
EveEvalSessionResult,
+ EveEvalStreamEvent,
EveEvalToolCall,
EveEvalTurn,
+ EveEvalWaitForEventOptions,
} from "#evals/types.js";
import type { EveEvalInputRequestMatchOptions, EveEvalToolCallMatchOptions } from "#evals/match.js";
@@ -103,6 +111,10 @@ export class EvalSessionDriver implements EveEvalSession {
return this.#session.state;
}
+ async cancel(): Promise<CancelSessionResult> {
+ return await this.#session.cancel();
+ }
+
requireInputRequest(filter: EveEvalInputRequestMatchOptions = {}): InputRequest {
if (this.#pendingInputRequests.length === 0) {
this.#failRequirement(
@@ -151,15 +163,16 @@ export class EvalSessionDriver implements EveEvalSession {
}
async send(input: SendTurnInput): Promise<EveEvalTurn> {
+ return await (await this.start(input)).result();
+ }
+
+ async start(input: SendTurnInput): Promise<EveEvalLiveTurn> {
const response = await this.#session.send(attachSignal(input, this.#signal));
- const result = await response.result();
- return this.#recordTurn({
- data: result.data,
- events: result.events,
- inputRequests: result.inputRequests,
- message: result.message,
- sessionId: result.sessionId,
- status: result.status,
+ return new EvalLiveTurn({
+ events: response,
+ record: (events) => this.#recordObservedTurn(response.sessionId, events),
+ session: this,
+ sessionId: response.sessionId,
});
}
@@ -176,34 +189,21 @@ export class EvalSessionDriver implements EveEvalSession {
async readTurn(options?: { readonly startIndex?: number }): Promise<EveEvalTurn> {
const sessionId = this.sessionId;
- const events: HandleMessageStreamEvent[] = [];
- let sawBoundary = false;
-
- for await (const event of this.#session.stream({
- signal: this.#signal,
- startIndex: options?.startIndex,
- })) {
- events.push(event);
-
- if (isCurrentTurnBoundaryEvent(event)) {
- sawBoundary = true;
- break;
- }
- }
-
- if (!sawBoundary) {
- throw new Error(
- `Stream for session "${this.sessionId ?? "(unknown)"}" closed before a turn boundary.`,
- );
- }
+ return await this.watchTurn(options, requireSessionId(sessionId)).result();
+ }
- return this.#recordTurn({
- data: extractCompletedResult(events),
- events,
- inputRequests: extractInputRequests(events),
- message: extractCompletedMessage(events),
- sessionId: requireSessionId(sessionId),
- status: deriveResultStatus(events),
+ watchTurn(
+ options?: { readonly startIndex?: number },
+ sessionId = requireSessionId(this.sessionId),
+ ): EveEvalLiveTurn {
+ return new EvalLiveTurn({
+ events: this.#session.stream({
+ signal: this.#signal,
+ startIndex: options?.startIndex,
+ }),
+ record: (events) => this.#recordObservedTurn(sessionId, events),
+ session: this,
+ sessionId,
});
}
@@ -245,6 +245,17 @@ export class EvalSessionDriver implements EveEvalSession {
return turn;
}
+ #recordObservedTurn(sessionId: string, events: readonly HandleMessageStreamEvent[]): EveEvalTurn {
+ return this.#recordTurn({
+ data: extractCompletedResult(events),
+ events,
+ inputRequests: extractInputRequests(events),
+ message: extractCompletedMessage(events),
+ sessionId,
+ status: deriveResultStatus(events),
+ });
+ }
+
#assertionSubject() {
const sessionId = this.sessionId;
const derived = deriveRunFacts(this.#events, { sessionId });
@@ -262,6 +273,123 @@ export class EvalSessionDriver implements EveEvalSession {
}
}
+interface LiveEventWaiter {
+ readonly matches: (event: HandleMessageStreamEvent) => boolean;
+ readonly reject: (error: Error) => void;
+ readonly resolve: (event: HandleMessageStreamEvent) => void;
+}
+
+class EvalLiveTurn implements EveEvalLiveTurn {
+ readonly session: EveEvalSession;
+ readonly sessionId: string;
+ readonly #completion: Promise<EveEvalTurn>;
+ readonly #events: HandleMessageStreamEvent[] = [];
+ readonly #waiters = new Set<LiveEventWaiter>();
+ #waitError: Error | undefined;
+
+ constructor(input: {
+ readonly events: AsyncIterable<HandleMessageStreamEvent>;
+ readonly record: (events: readonly HandleMessageStreamEvent[]) => EveEvalTurn;
+ readonly session: EveEvalSession;
+ readonly sessionId: string;
+ }) {
+ this.session = input.session;
+ this.sessionId = input.sessionId;
+ this.#completion = this.#consume(input.events, input.record);
+ void this.#completion.catch(() => {});
+ }
+
+ get events(): readonly HandleMessageStreamEvent[] {
+ return this.#events;
+ }
+
+ async cancel(): Promise<CancelSessionResult> {
+ return await this.session.cancel();
+ }
+
+ async result(): Promise<EveEvalTurn> {
+ return await this.#completion;
+ }
+
+ async waitForEvent<TType extends HandleMessageStreamEvent["type"]>(
+ type: TType,
+ options?: EveEvalWaitForEventOptions<TType>,
+ ): Promise<EveEvalStreamEvent<TType>> {
+ const matches = (event: HandleMessageStreamEvent): boolean =>
+ event.type === type &&
+ (options?.data === undefined ||
+ matchesValue(options.data, "data" in event ? event.data : undefined));
+ const observed = this.#events.find(matches);
+ if (observed !== undefined) return observed as EveEvalStreamEvent<TType>;
+ if (this.#waitError !== undefined) throw this.#waitError;
+
+ return await new Promise<EveEvalStreamEvent<TType>>((resolve, reject) => {
+ const waiter: LiveEventWaiter = {
+ matches,
+ reject,
+ resolve: (event) => resolve(event as EveEvalStreamEvent<TType>),
+ };
+ this.#waiters.add(waiter);
+ });
+ }
+
+ async #consume(
+ source: AsyncIterable<HandleMessageStreamEvent>,
+ record: (events: readonly HandleMessageStreamEvent[]) => EveEvalTurn,
+ ): Promise<EveEvalTurn> {
+ try {
+ let sawBoundary = false;
+ for await (const event of source) {
+ this.#events.push(event);
+ this.#resolveWaiters(event);
+
+ if (isTurnFailureEvent(event)) {
+ this.#closeWaiters(
+ new Error(
+ `Session ${this.sessionId} failed before the expected event (${event.type}).`,
+ ),
+ );
+ }
+
+ if (isCurrentTurnBoundaryEvent(event)) {
+ sawBoundary = true;
+ this.#closeWaiters(
+ new Error(`Session ${this.sessionId} reached ${event.type} before the expected event.`),
+ );
+ break;
+ }
+ }
+
+ if (!sawBoundary) {
+ throw new Error(`Stream for session "${this.sessionId}" closed before a turn boundary.`);
+ }
+
+ return record(this.#events);
+ } catch (error) {
+ const normalized = error instanceof Error ? error : new Error(String(error));
+ this.#closeWaiters(normalized);
+ throw error;
+ }
+ }
+
+ #resolveWaiters(event: HandleMessageStreamEvent): void {
+ for (const waiter of this.#waiters) {
+ if (!waiter.matches(event)) continue;
+ this.#waiters.delete(waiter);
+ waiter.resolve(event);
+ }
+ }
+
+ #closeWaiters(error: Error): void {
+ if (this.#waitError !== undefined) return;
+ this.#waitError = error;
+ for (const waiter of this.#waiters) {
+ waiter.reject(error);
+ }
+ this.#waiters.clear();
+ }
+}
+
interface EvalTurn extends EveEvalAssertions, EveEvalOutputAssertions {}
class EvalTurn implements EveEvalTurn {
@@ -371,16 +499,15 @@ export class EvalSessionManager {
sessionId: string,
options?: { readonly startIndex?: number },
): Promise<EvalSessionDriver> {
- const session = new EvalSessionDriver({
- collector: this.#collector,
- session: this.#client.session({ sessionId, streamIndex: options?.startIndex ?? 0 }),
- signal: this.#signal,
- });
- this.#sessions.push(session);
+ const session = this.#createAttachedSession(sessionId, options);
await session.readTurn(options);
return session;
}
+ watchTurn(sessionId: string, options?: { readonly startIndex?: number }): EveEvalLiveTurn {
+ return this.#createAttachedSession(sessionId, options).watchTurn(options, sessionId);
+ }
+
snapshots(): readonly EveEvalSessionResult[] {
return this.#sessions.map((session) => session.snapshot(session === this.#primary));
}
@@ -406,6 +533,19 @@ export class EvalSessionManager {
this.#sessions.push(session);
return session;
}
+
+ #createAttachedSession(
+ sessionId: string,
+ options?: { readonly startIndex?: number },
+ ): EvalSessionDriver {
+ const session = new EvalSessionDriver({
+ collector: this.#collector,
+ session: this.#client.session({ sessionId, streamIndex: options?.startIndex ?? 0 }),
+ signal: this.#signal,
+ });
+ this.#sessions.push(session);
+ return session;
+ }
}
function attachSignal(input: SendTurnInput, signal: AbortSignal | undefined): SendTurnInput {
diff --git a/packages/eve/src/evals/target.ts b/packages/eve/src/evals/target.ts
index 774c7e953..492b2ffee 100644
--- a/packages/eve/src/evals/target.ts
+++ b/packages/eve/src/evals/target.ts
@@ -116,6 +116,23 @@ function createHandle(input: {
return await sessions.attachSession(sessionId, opts);
},
+ watchTurn(sessionId: string, opts?: { readonly startIndex?: number }) {
+ if (input.sessions !== undefined) {
+ return input.sessions.watchTurn(sessionId, opts);
+ }
+
+ if (base !== undefined) {
+ return base.watchTurn(sessionId, opts);
+ }
+
+ if (client === undefined) {
+ throw new Error("Eval target cannot watch sessions without a client.");
+ }
+
+ const sessions = new EvalSessionManager({ client });
+ return sessions.watchTurn(sessionId, opts);
+ },
+
async dispatchSchedule(scheduleId: string): Promise<EveEvalScheduleDispatchResult> {
if (!input.capabilities.devRoutes) {
throw new Error("target.dispatchSchedule() requires a target with dev routes enabled.");
diff --git a/packages/eve/src/evals/types.ts b/packages/eve/src/evals/types.ts
index 2da11a945..9464fcce8 100644
--- a/packages/eve/src/evals/types.ts
+++ b/packages/eve/src/evals/types.ts
@@ -2,7 +2,7 @@ import type { LanguageModel } from "ai";
import type { StandardSchemaV1 } from "#compiled/@standard-schema/spec/index.js";
import type { HandleMessageStreamEvent, RuntimeIdentity } from "#protocol/message.js";
-import type { SendTurnInput, SessionState } from "#client/types.js";
+import type { CancelSessionResult, SendTurnInput, SessionState } from "#client/types.js";
import type { InputRequest, InputResponse } from "#runtime/input/types.js";
import type { JsonObject, JsonValue } from "#shared/json.js";
import type { AgentModelOptionsDefinition } from "#shared/agent-definition.js";
@@ -42,6 +42,10 @@ export interface EveEvalToolCall {
* (`subagent.called` / `subagent.started`, joined with `subagent.completed`).
*/
export interface EveEvalSubagentCall {
+ /** Runtime-action call id joining this delegation's lifecycle events, when observed. */
+ readonly callId?: string;
+ /** Durable child session id for local and remote workflow delegations. */
+ readonly childSessionId?: string;
/** Subagent name. */
readonly name: string;
/** Remote agent URL for remote delegations (`subagent.called` remote metadata). */
@@ -212,6 +216,41 @@ export interface EveEvalOutputAssertions {
outputMatches(schema: StandardSchemaV1): AssertionHandle;
}
+/** Typed stream event returned by {@link EveEvalLiveTurn.waitForEvent}. */
+export type EveEvalStreamEvent<
+ TType extends HandleMessageStreamEvent["type"] = HandleMessageStreamEvent["type"],
+> = Extract<HandleMessageStreamEvent, { type: TType }>;
+
+/** Matcher options for waiting until one live turn emits a specific event. */
+export type EveEvalWaitForEventOptions<TType extends HandleMessageStreamEvent["type"]> = Omit<
+ Extract<EveEvalEventMatch, { type: TType }>,
+ "count" | "type"
+>;
+
+/**
+ * One accepted turn whose event stream is still in progress.
+ *
+ * The handle owns the stream consumer: event waiters observe its buffer and
+ * {@link result} settles and records that same stream exactly once.
+ */
+export interface EveEvalLiveTurn {
+ /** Events observed on this turn so far. */
+ readonly events: readonly HandleMessageStreamEvent[];
+ /** Session driver that started or owns this turn. */
+ readonly session: EveEvalSession;
+ /** Durable session id available as soon as the turn is accepted or attached. */
+ readonly sessionId: string;
+ /** Request cooperative cancellation of this turn's session. */
+ cancel(): Promise<CancelSessionResult>;
+ /** Wait for the turn boundary and return the recorded immutable result. */
+ result(): Promise<EveEvalTurn>;
+ /** Wait until the live stream emits one typed event matching `options`. */
+ waitForEvent<TType extends HandleMessageStreamEvent["type"]>(
+ type: TType,
+ options?: EveEvalWaitForEventOptions<TType>,
+ ): Promise<EveEvalStreamEvent<TType>>;
+}
+
/** Operations and state shared by the primary eval context and independent sessions. */
export interface EveEvalSessionDriver {
/** All events observed on this session so far. */
@@ -222,6 +261,8 @@ export interface EveEvalSessionDriver {
readonly state: SessionState;
/** eve session id after the first successful send. */
readonly sessionId: string | undefined;
+ /** Request cooperative cancellation of this session's active turn. */
+ cancel(): Promise<CancelSessionResult>;
/** Require exactly one pending input request matching `filter`, or abort dependent control flow. */
requireInputRequest(filter?: EveEvalInputRequestMatchOptions): InputRequest;
/** Resolve specific pending requests and run the resumed turn. */
@@ -230,6 +271,8 @@ export interface EveEvalSessionDriver {
respondAll(optionId: string): Promise<EveEvalTurn>;
/** Send one turn through this session. */
send(input: SendTurnInput): Promise<EveEvalTurn>;
+ /** Start one turn and return as soon as its session is accepted. */
+ start(input: SendTurnInput): Promise<EveEvalLiveTurn>;
/** Send one text turn with a local file attached as a data URL. */
sendFile(text: string, filePath: string, mediaType?: string): Promise<EveEvalTurn>;
}
@@ -380,6 +423,12 @@ export interface EveEvalTargetHandle extends EveEvalTarget {
sessionId: string,
opts?: { readonly startIndex?: number },
): Promise<EveEvalSession>;
+ /**
+ * Observe one in-progress turn from a session created outside the eval.
+ * The returned live-turn handle starts consuming immediately and owns the
+ * stream through its next turn boundary.
+ */
+ watchTurn(sessionId: string, opts?: { readonly startIndex?: number }): EveEvalLiveTurn;
}
// ---------------------------------------------------------------------------
diff --git a/packages/eve/src/execution/cancel-descendant-turns-step.test.ts b/packages/eve/src/execution/cancel-descendant-turns-step.test.ts
new file mode 100644
index 000000000..b4a740ec9
--- /dev/null
+++ b/packages/eve/src/execution/cancel-descendant-turns-step.test.ts
@@ -0,0 +1,220 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { deserializeContext } from "#context/serialize.js";
+import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-step.js";
+import { createDurableSessionState } from "#execution/durable-session-store.js";
+import {
+ cancelRemoteAgentTurn,
+ isRetryableRemoteAgentCancelError,
+ resolveRemoteAgentForAction,
+} from "#execution/remote-agent-dispatch.js";
+import { requestWorkflowTurnCancellation } from "#execution/workflow-runtime.js";
+import {
+ recordPendingSubagentChild,
+ setPendingRuntimeActionBatch,
+} from "#harness/runtime-actions.js";
+import type { HarnessSession } from "#harness/types.js";
+import type { RuntimeActionRequest } from "#runtime/actions/types.js";
+
+vi.mock("#context/serialize.js", () => ({
+ deserializeContext: vi.fn(),
+}));
+
+vi.mock("./workflow-runtime.js", () => ({
+ requestWorkflowTurnCancellation: vi.fn(),
+}));
+
+vi.mock("./remote-agent-dispatch.js", () => ({
+ cancelRemoteAgentTurn: vi.fn(),
+ isRetryableRemoteAgentCancelError: vi.fn(),
+ resolveRemoteAgentForAction: vi.fn(),
+}));
+
+const localAction = {
+ callId: "call-local",
+ description: "Delegate locally.",
+ input: { message: "work locally" },
+ kind: "subagent-call",
+ name: "local",
+ nodeId: "subagents/local",
+ subagentName: "local",
+} satisfies RuntimeActionRequest;
+
+const remoteAction = {
+ callId: "call-remote",
+ description: "Delegate remotely.",
+ input: { message: "work remotely" },
+ kind: "remote-agent-call",
+ name: "remote",
+ nodeId: "subagents/remote.ts",
+ remoteAgentName: "remote",
+} satisfies RuntimeActionRequest;
+
+const remote = {
+ kind: "remote",
+ name: "remote",
+ nodeId: "subagents/remote.ts",
+ path: "/custom-create-path",
+ url: "https://remote.example.com",
+} as never;
+
+afterEach(() => {
+ vi.clearAllMocks();
+ vi.useRealTimers();
+});
+
+describe("cancelDescendantTurnsStep", () => {
+ it("cancels every adopted local and remote child in parallel", async () => {
+ installRemoteRegistry();
+ vi.mocked(resolveRemoteAgentForAction).mockReturnValue(remote);
+ vi.mocked(requestWorkflowTurnCancellation).mockResolvedValue({ status: "accepted" });
+ vi.mocked(cancelRemoteAgentTurn).mockResolvedValue({ status: "accepted" });
+
+ await cancelDescendantTurnsStep({
+ serializedContext: { context: "parent" },
+ sessionState: createPendingState(),
+ });
+
+ expect(requestWorkflowTurnCancellation).toHaveBeenCalledWith({
+ sessionId: "local-child",
+ });
+ expect(resolveRemoteAgentForAction).toHaveBeenCalledWith({
+ nodeId: remoteAction.nodeId,
+ registry: expect.any(Map),
+ remoteAgentName: remoteAction.remoteAgentName,
+ });
+ expect(cancelRemoteAgentTurn).toHaveBeenCalledWith({
+ remote,
+ sessionId: "remote-child",
+ });
+ });
+
+ it("does not deserialize remote context for local-only descendants", async () => {
+ vi.mocked(requestWorkflowTurnCancellation).mockResolvedValue({ status: "accepted" });
+
+ await cancelDescendantTurnsStep({
+ serializedContext: {},
+ sessionState: createPendingState({ includeRemote: false }),
+ });
+
+ expect(requestWorkflowTurnCancellation).toHaveBeenCalledWith({
+ sessionId: "local-child",
+ });
+ expect(deserializeContext).not.toHaveBeenCalled();
+ });
+
+ it("retries no-active-turn responses during the child adoption window", async () => {
+ vi.useFakeTimers();
+ installRemoteRegistry();
+ vi.mocked(resolveRemoteAgentForAction).mockReturnValue(remote);
+ vi.mocked(requestWorkflowTurnCancellation)
+ .mockResolvedValueOnce({ status: "no_active_turn" })
+ .mockResolvedValueOnce({ status: "accepted" });
+ vi.mocked(cancelRemoteAgentTurn)
+ .mockResolvedValueOnce({ status: "no_active_turn" })
+ .mockResolvedValueOnce({ status: "accepted" });
+
+ const cancellation = cancelDescendantTurnsStep({
+ serializedContext: {},
+ sessionState: createPendingState(),
+ });
+ await vi.advanceTimersByTimeAsync(3_000);
+ await cancellation;
+
+ expect(requestWorkflowTurnCancellation).toHaveBeenCalledTimes(2);
+ expect(cancelRemoteAgentTurn).toHaveBeenCalledTimes(2);
+ });
+
+ it("contains unexpected local failures and exhausted remote failures", async () => {
+ vi.useFakeTimers();
+ installRemoteRegistry();
+ vi.mocked(resolveRemoteAgentForAction).mockReturnValue(remote);
+ vi.mocked(requestWorkflowTurnCancellation).mockRejectedValue(
+ new Error("local hook storage unavailable"),
+ );
+ vi.mocked(cancelRemoteAgentTurn).mockRejectedValue(new TypeError("remote unavailable"));
+ vi.mocked(isRetryableRemoteAgentCancelError).mockReturnValue(true);
+ const error = vi.spyOn(console, "error").mockImplementation(() => {});
+
+ const cancellation = cancelDescendantTurnsStep({
+ serializedContext: {},
+ sessionState: createPendingState(),
+ });
+ await vi.advanceTimersByTimeAsync(3_000);
+ await expect(cancellation).resolves.toBeUndefined();
+
+ expect(requestWorkflowTurnCancellation).toHaveBeenCalledOnce();
+ expect(cancelRemoteAgentTurn).toHaveBeenCalledTimes(12);
+ expect(error).toHaveBeenCalledWith(
+ "[eve:execution.cancel-descendant-turns] failed to cancel local descendant turn",
+ expect.objectContaining({ callId: "call-local", childSessionId: "local-child" }),
+ );
+ expect(error).toHaveBeenCalledWith(
+ "[eve:execution.cancel-descendant-turns] failed to cancel remote descendant turn",
+ expect.objectContaining({ callId: "call-remote", childSessionId: "remote-child" }),
+ );
+ });
+
+ it("treats pending batches from older deployments as having no descendants", async () => {
+ const session = setPendingRuntimeActionBatch({
+ actions: [localAction],
+ event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
+ responseMessages: [],
+ session: createSession(),
+ });
+
+ await cancelDescendantTurnsStep({
+ serializedContext: {},
+ sessionState: createDurableSessionState({ session }),
+ });
+
+ expect(requestWorkflowTurnCancellation).not.toHaveBeenCalled();
+ expect(cancelRemoteAgentTurn).not.toHaveBeenCalled();
+ expect(deserializeContext).not.toHaveBeenCalled();
+ });
+});
+
+function installRemoteRegistry(): void {
+ vi.mocked(deserializeContext).mockResolvedValue({
+ require: vi.fn(() => ({
+ subagentRegistry: { subagentsByNodeId: new Map([[remoteAction.nodeId, remote]]) },
+ })),
+ } as never);
+}
+
+function createPendingState(input: { readonly includeRemote?: boolean } = {}) {
+ const includeRemote = input.includeRemote ?? true;
+ let session = setPendingRuntimeActionBatch({
+ actions: includeRemote ? [localAction, remoteAction] : [localAction],
+ event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
+ responseMessages: [],
+ session: createSession(),
+ });
+ session = recordPendingSubagentChild({
+ callId: localAction.callId,
+ child: {
+ continuationToken: "subagent:parent:call-local",
+ kind: "local",
+ sessionId: "local-child",
+ },
+ session,
+ });
+ if (includeRemote) {
+ session = recordPendingSubagentChild({
+ callId: remoteAction.callId,
+ child: { kind: "remote", sessionId: "remote-child" },
+ session,
+ });
+ }
+ return createDurableSessionState({ session });
+}
+
+function createSession(): HarnessSession {
+ return {
+ agent: { modelReference: { id: "test-model" }, system: "", tools: [] },
+ compaction: { recentWindowSize: 10, threshold: 100_000 },
+ continuationToken: "http:parent",
+ history: [],
+ sessionId: "parent",
+ };
+}
diff --git a/packages/eve/src/execution/cancel-descendant-turns-step.ts b/packages/eve/src/execution/cancel-descendant-turns-step.ts
new file mode 100644
index 000000000..854e0cb89
--- /dev/null
+++ b/packages/eve/src/execution/cancel-descendant-turns-step.ts
@@ -0,0 +1,131 @@
+import type { CancelTurnResult } from "#channel/types.js";
+import { deserializeContext } from "#context/serialize.js";
+import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
+import { readDurableSession, type DurableSessionState } from "#execution/durable-session-store.js";
+import {
+ cancelRemoteAgentTurn,
+ isRetryableRemoteAgentCancelError,
+ resolveRemoteAgentForAction,
+} from "#execution/remote-agent-dispatch.js";
+import { requestWorkflowTurnCancellation } from "#execution/workflow-runtime.js";
+import { getPendingRuntimeActionBatch } from "#harness/runtime-actions.js";
+import { createLogger, logError } from "#internal/logging.js";
+import type {
+ RuntimeRemoteAgentCallActionRequest,
+ RuntimeSubagentCallActionRequest,
+} from "#runtime/actions/types.js";
+import type { RuntimeSubagentRegistry } from "#runtime/subagents/registry.js";
+
+const CANCEL_ATTEMPTS = 12;
+const CANCEL_RETRY_DELAY_MS = 250;
+const log = createLogger("execution.cancel-descendant-turns");
+
+/** Cancels every successfully adopted child in the current pending batch. */
+export async function cancelDescendantTurnsStep(input: {
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+}): Promise<void> {
+ "use step";
+
+ let batch;
+ try {
+ const session = await readDurableSession(input.sessionState);
+ batch = getPendingRuntimeActionBatch(session.state);
+ } catch (error) {
+ logError(log, "failed to read pending descendants during cancellation", error, {
+ sessionId: input.sessionState.sessionId,
+ });
+ return;
+ }
+
+ if (batch === undefined) return;
+ const childSessionIds = batch.childSessionIds;
+ if (childSessionIds === undefined) return;
+
+ let remoteRegistry: Promise<RuntimeSubagentRegistry["subagentsByNodeId"]> | undefined;
+ const getRemoteRegistry = () =>
+ (remoteRegistry ??= deserializeContext(input.serializedContext).then(
+ (ctx) => ctx.require(BundleKey).subagentRegistry.subagentsByNodeId,
+ ));
+
+ const cancellations = batch.actions.flatMap((action): Promise<void>[] => {
+ const childSessionId = childSessionIds[action.callId];
+ if (childSessionId === undefined) return [];
+
+ if (action.kind === "subagent-call") {
+ return [cancelLocalDescendant({ action, childSessionId })];
+ }
+ if (action.kind === "remote-agent-call") {
+ return [
+ cancelRemoteDescendant({
+ action,
+ childSessionId,
+ remoteRegistry: getRemoteRegistry(),
+ }),
+ ];
+ }
+ return [];
+ });
+
+ await Promise.all(cancellations);
+}
+
+async function cancelLocalDescendant(input: {
+ readonly action: RuntimeSubagentCallActionRequest;
+ readonly childSessionId: string;
+}): Promise<void> {
+ try {
+ await requestCancellationWithRetry({
+ request: () => requestWorkflowTurnCancellation({ sessionId: input.childSessionId }),
+ shouldRetryError: () => false,
+ });
+ } catch (error) {
+ logError(log, "failed to cancel local descendant turn", error, {
+ callId: input.action.callId,
+ childSessionId: input.childSessionId,
+ subagentName: input.action.subagentName,
+ });
+ }
+}
+
+async function cancelRemoteDescendant(input: {
+ readonly action: RuntimeRemoteAgentCallActionRequest;
+ readonly childSessionId: string;
+ readonly remoteRegistry: Promise<RuntimeSubagentRegistry["subagentsByNodeId"]>;
+}): Promise<void> {
+ try {
+ const registry = await input.remoteRegistry;
+ const remote = resolveRemoteAgentForAction({
+ nodeId: input.action.nodeId,
+ remoteAgentName: input.action.remoteAgentName,
+ registry,
+ });
+
+ await requestCancellationWithRetry({
+ request: () => cancelRemoteAgentTurn({ remote, sessionId: input.childSessionId }),
+ shouldRetryError: isRetryableRemoteAgentCancelError,
+ });
+ } catch (error) {
+ logError(log, "failed to cancel remote descendant turn", error, {
+ callId: input.action.callId,
+ childSessionId: input.childSessionId,
+ remoteAgentName: input.action.remoteAgentName,
+ });
+ }
+}
+
+async function requestCancellationWithRetry(input: {
+ readonly request: () => Promise<CancelTurnResult>;
+ readonly shouldRetryError: (error: unknown) => boolean;
+}): Promise<void> {
+ for (let attempt = 1; attempt <= CANCEL_ATTEMPTS; attempt += 1) {
+ try {
+ const result = await input.request();
+ if (result.status === "accepted" || attempt === CANCEL_ATTEMPTS) return;
+ } catch (error) {
+ if (!input.shouldRetryError(error) || attempt === CANCEL_ATTEMPTS) throw error;
+ }
+
+ await new Promise((resolve) => setTimeout(resolve, CANCEL_RETRY_DELAY_MS));
+ }
+}
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.ts
index a416bd4e3..d1d9fb4b6 100644
--- a/packages/eve/src/execution/dispatch-runtime-actions-step.ts
+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.ts
@@ -19,7 +19,7 @@ import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js
import { deserializeContext } from "#context/serialize.js";
import {
getPendingRuntimeActionBatch,
- recordPendingSubagentChildToken,
+ recordPendingSubagentChild,
} from "#harness/runtime-actions.js";
import {
createSubagentCalledEvent,
@@ -141,14 +141,37 @@ export async function dispatchRuntimeActionsStep(input: {
session,
source,
});
- const handle = await childRuntime.run(runInput);
+ try {
+ const handle = await childRuntime.run(runInput);
+ childSessionId = handle.sessionId;
+ } catch (error) {
+ logError(log, "local subagent start failed", error, {
+ callId: action.callId,
+ nodeId: action.nodeId,
+ subagentName: action.subagentName,
+ });
+ results.push({
+ callId: action.callId,
+ isError: true,
+ kind: "subagent-result",
+ output: {
+ code: "SUBAGENT_START_FAILED",
+ message: toErrorMessage(error),
+ },
+ subagentName: action.subagentName,
+ });
+ continue;
+ }
- nextSession = recordPendingSubagentChildToken({
+ nextSession = recordPendingSubagentChild({
callId: action.callId,
- childContinuationToken,
+ child: {
+ continuationToken: childContinuationToken,
+ kind: "local",
+ sessionId: childSessionId,
+ },
session: nextSession,
});
- childSessionId = handle.sessionId;
name = action.name;
toolName = action.subagentName;
break;
@@ -180,6 +203,11 @@ export async function dispatchRuntimeActionsStep(input: {
name = action.name;
remote = { url: resolvedRemote.url };
toolName = action.remoteAgentName;
+ nextSession = recordPendingSubagentChild({
+ callId: action.callId,
+ child: { kind: "remote", sessionId: childSessionId },
+ session: nextSession,
+ });
break;
}
default:
diff --git a/packages/eve/src/execution/remote-agent-dispatch.test.ts b/packages/eve/src/execution/remote-agent-dispatch.test.ts
index 8bee9f871..5c0a268ca 100644
--- a/packages/eve/src/execution/remote-agent-dispatch.test.ts
+++ b/packages/eve/src/execution/remote-agent-dispatch.test.ts
@@ -1,6 +1,10 @@
import { afterEach, describe, expect, it, vi } from "vitest";
-import { startRemoteAgentSession } from "#execution/remote-agent-dispatch.js";
+import {
+ cancelRemoteAgentTurn,
+ isRetryableRemoteAgentCancelError,
+ startRemoteAgentSession,
+} from "#execution/remote-agent-dispatch.js";
import type { RuntimeRemoteAgentCallActionRequest } from "#runtime/actions/types.js";
import type { ResolvedRuntimeRemoteAgentNode } from "#runtime/types.js";
@@ -174,6 +178,102 @@ describe("startRemoteAgentSession", () => {
});
});
+describe("cancelRemoteAgentTurn", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it("posts to the standard cancel endpoint with freshly resolved remote auth", async () => {
+ const auth = vi
+ .fn()
+ .mockResolvedValueOnce({ headers: { authorization: "Bearer first" } })
+ .mockResolvedValueOnce({ headers: { authorization: "Bearer second" } });
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(
+ Response.json(
+ { ok: true, sessionId: "remote/session id", status: "no_active_turn" },
+ { status: 202 },
+ ),
+ )
+ .mockResolvedValueOnce(
+ Response.json(
+ { ok: true, sessionId: "remote/session id", status: "accepted" },
+ { status: 202 },
+ ),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const remote = { ...createRemoteAgent(), auth };
+
+ await expect(
+ cancelRemoteAgentTurn({ remote, sessionId: "remote/session id" }),
+ ).resolves.toEqual({ status: "no_active_turn" });
+ await expect(
+ cancelRemoteAgentTurn({ remote, sessionId: "remote/session id" }),
+ ).resolves.toEqual({ status: "accepted" });
+
+ expect(auth).toHaveBeenCalledTimes(2);
+ expect(fetchMock).toHaveBeenNthCalledWith(
+ 1,
+ "https://remote.example.com/eve/v1/session/remote%2Fsession%20id/cancel",
+ {
+ headers: {
+ authorization: "Bearer first",
+ "x-static": "yes",
+ },
+ method: "POST",
+ },
+ );
+ expect(fetchMock.mock.calls[1]?.[1]?.headers).toEqual({
+ authorization: "Bearer second",
+ "x-static": "yes",
+ });
+ });
+
+ it("rejects responses for a different session", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi
+ .fn()
+ .mockResolvedValue(
+ Response.json(
+ { ok: true, sessionId: "another-session", status: "accepted" },
+ { status: 202 },
+ ),
+ ),
+ );
+
+ const error = await cancelRemoteAgentTurn({
+ remote: createRemoteAgent(),
+ sessionId: "remote-session",
+ }).catch((caught: unknown) => caught);
+
+ expect(error).toBeInstanceOf(Error);
+ expect(isRetryableRemoteAgentCancelError(error)).toBe(false);
+ });
+
+ it("classifies only propagation and transient HTTP failures as retryable", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(new Response(null, { status: 503 }))
+ .mockResolvedValueOnce(new Response(null, { status: 404 }));
+ vi.stubGlobal("fetch", fetchMock);
+
+ const transient = await cancelRemoteAgentTurn({
+ remote: createRemoteAgent(),
+ sessionId: "remote-session",
+ }).catch((error: unknown) => error);
+ const permanent = await cancelRemoteAgentTurn({
+ remote: createRemoteAgent(),
+ sessionId: "remote-session",
+ }).catch((error: unknown) => error);
+
+ expect(isRetryableRemoteAgentCancelError(transient)).toBe(true);
+ expect(isRetryableRemoteAgentCancelError(permanent)).toBe(false);
+ expect(isRetryableRemoteAgentCancelError(new TypeError("network unavailable"))).toBe(true);
+ });
+});
+
function createAction(): RuntimeRemoteAgentCallActionRequest {
return {
callId: "call-remote",
diff --git a/packages/eve/src/execution/remote-agent-dispatch.ts b/packages/eve/src/execution/remote-agent-dispatch.ts
index a74182013..160aa36c2 100644
--- a/packages/eve/src/execution/remote-agent-dispatch.ts
+++ b/packages/eve/src/execution/remote-agent-dispatch.ts
@@ -1,5 +1,7 @@
import { EVE_SESSION_ID_HEADER } from "#protocol/message.js";
-import { createEveCallbackRoutePath } from "#protocol/routes.js";
+import { CancelTurnResponseSchema } from "#protocol/cancel-turn.js";
+import { createEveCallbackRoutePath, createEveCancelTurnRoutePath } from "#protocol/routes.js";
+import type { CancelTurnResult } from "#channel/types.js";
import { createWorkflowCallbackUrl } from "#execution/workflow-callback-url.js";
import { formatSubagentInput } from "#execution/subagent-invocation.js";
import type { HarnessSession } from "#harness/types.js";
@@ -7,6 +9,16 @@ import type { RuntimeRemoteAgentCallActionRequest } from "#runtime/actions/types
import type { RuntimeSubagentRegistry } from "#runtime/subagents/registry.js";
import type { ResolvedRuntimeRemoteAgentNode } from "#runtime/types.js";
+class RemoteAgentCancelRequestError extends Error {
+ readonly retryable: boolean;
+
+ constructor(message: string, options: { readonly retryable: boolean }) {
+ super(message);
+ this.name = "RemoteAgentCancelRequestError";
+ this.retryable = options.retryable;
+ }
+}
+
export async function startRemoteAgentSession(input: {
readonly action: RuntimeRemoteAgentCallActionRequest;
readonly callbackBaseUrl: string | undefined;
@@ -71,6 +83,48 @@ export async function startRemoteAgentSession(input: {
);
}
+export async function cancelRemoteAgentTurn(input: {
+ readonly remote: ResolvedRuntimeRemoteAgentNode;
+ readonly sessionId: string;
+}): Promise<CancelTurnResult> {
+ const headers = await resolveRemoteAgentRequestHeaders(input.remote);
+ const response = await fetch(createRemoteAgentCancelTurnUrl(input.remote, input.sessionId), {
+ headers,
+ method: "POST",
+ });
+
+ if (!response.ok) {
+ throw new RemoteAgentCancelRequestError(
+ `Remote agent "${input.remote.name}" cancel-turn request failed with HTTP ${response.status}.`,
+ { retryable: isRetryableRemoteCancelStatus(response.status) },
+ );
+ }
+
+ let body: unknown;
+ try {
+ body = await response.json();
+ } catch {
+ throw new RemoteAgentCancelRequestError(
+ `Remote agent "${input.remote.name}" cancel-turn response was not valid JSON.`,
+ { retryable: false },
+ );
+ }
+
+ const result = CancelTurnResponseSchema.safeParse(body);
+ if (!result.success || result.data.sessionId !== input.sessionId) {
+ throw new RemoteAgentCancelRequestError(
+ `Remote agent "${input.remote.name}" cancel-turn response was invalid.`,
+ { retryable: false },
+ );
+ }
+
+ return { status: result.data.status };
+}
+
+export function isRetryableRemoteAgentCancelError(error: unknown): boolean {
+ return !(error instanceof RemoteAgentCancelRequestError) || error.retryable;
+}
+
export function resolveRemoteAgentForAction(input: {
readonly nodeId: string;
readonly registry: RuntimeSubagentRegistry["subagentsByNodeId"];
@@ -88,6 +142,20 @@ function createRemoteAgentSessionUrl(remote: ResolvedRuntimeRemoteAgentNode): st
return new URL(remote.path, `${trimTrailingSlash(remote.url)}/`).toString();
}
+function createRemoteAgentCancelTurnUrl(
+ remote: ResolvedRuntimeRemoteAgentNode,
+ sessionId: string,
+): string {
+ return new URL(
+ createEveCancelTurnRoutePath(sessionId),
+ `${trimTrailingSlash(remote.url)}/`,
+ ).toString();
+}
+
+function isRetryableRemoteCancelStatus(status: number): boolean {
+ return status === 408 || status === 425 || status === 429 || status >= 500;
+}
+
async function resolveRemoteAgentRequestHeaders(
remote: ResolvedRuntimeRemoteAgentNode,
): Promise<Record<string, string>> {
diff --git a/packages/eve/src/execution/turn-cancellation.integration.test.ts b/packages/eve/src/execution/turn-cancellation.integration.test.ts
index 2ac1606ba..aede48f56 100644
--- a/packages/eve/src/execution/turn-cancellation.integration.test.ts
+++ b/packages/eve/src/execution/turn-cancellation.integration.test.ts
@@ -24,12 +24,10 @@ import type { ResolvedToolDefinition } from "#runtime/types.js";
import { attachRouteAgent } from "#internal/nitro/routes/channel-route-context.js";
/**
- * Layer-1 turn cancellation: resuming a session's `{sessionId}:cancel`
- * hook mid-turn settles the turn as `turn.cancelled` → `session.waiting`
- * with zero failure events, no step retries, and a session that accepts
- * the next message normally. The payload may carry a `turnId` guard
- * scoping the cancel to one observed turn. (The HTTP trigger arrives in
- * layer 2; these tests resume the hook directly.)
+ * Turn cancellation settles as `turn.cancelled` → `session.waiting` with
+ * zero failure events, no step retries, and a session that accepts the next
+ * message normally. Coverage exercises direct hooks, the HTTP trigger, and
+ * layer-3 cancellation of adopted local descendants.
*/
const FAILURE_EVENT_TYPES = ["step.failed", "turn.failed", "session.failed"] as const;
@@ -264,7 +262,7 @@ function createCancelRouteCaller(): (
async function expectCancelResponse(
response: Response,
- expected: { readonly sessionId: string; readonly status: "cancelling" | "no_active_turn" },
+ expected: { readonly sessionId: string; readonly status: "accepted" | "no_active_turn" },
): Promise<void> {
expect(response.status).toBe(202);
await expect(response.json()).resolves.toEqual({
@@ -377,7 +375,7 @@ describe("turn cancellation integration", () => {
await fixture.toolStarted;
const cancelled = await cancelViaRoute(run.runId);
- await expectCancelResponse(cancelled, { sessionId: run.runId, status: "cancelling" });
+ await expectCancelResponse(cancelled, { sessionId: run.runId, status: "accepted" });
const cancelledTurn = await stream.nextTurn();
@@ -396,7 +394,7 @@ describe("turn cancellation integration", () => {
// With the turn settled and its cancel hook swept from the
// world, a duplicate cancel is the benign "nothing to cancel"
// success. (Between settle and sweep a duplicate may still be
- // accepted as "cancelling" and land unconsumed — also benign.)
+ // accepted as "accepted" and land unconsumed — also benign.)
await waitForHookSweep(sessionCancelHookToken(run.runId));
const duplicate = await cancelViaRoute(run.runId);
await expectCancelResponse(duplicate, { sessionId: run.runId, status: "no_active_turn" });
@@ -426,7 +424,7 @@ describe("turn cancellation integration", () => {
});
}, 60_000);
- it("cancels a turn waiting on an in-flight subagent and does not re-dispatch it", async () => {
+ it("cascades cancellation to an in-flight subagent and does not re-dispatch it", async () => {
const fixture = createWaitToolRuntime("turn-cancel-subagent");
const continuationToken = "http:turn-cancel-subagent";
@@ -459,14 +457,11 @@ describe("turn cancellation integration", () => {
expect(filterEventsByType(cancelledTurn, "subagent.called")).toHaveLength(1);
expectNoFailureEvents(cancelledTurn);
- // Unblock the orphaned child (no cascade in layer 1 — its late
- // result lands on the parent's disposed inbox and is dropped).
const childSessionId = filterEventsByType(cancelledTurn, "subagent.called")[0]?.data
.childSessionId;
expect(childSessionId).toBeDefined();
- const childCancelToken = sessionCancelHookToken(childSessionId ?? "");
- await waitForHookByToken(childCancelToken);
- await resumeHook(childCancelToken, {}).catch(() => undefined);
+ await waitForHookSweep(sessionCancelHookToken(childSessionId ?? ""));
+ expect(fixture.toolAborts()).toBe(1);
// The cleared pending batch must not re-dispatch on the next turn.
await waitForHook({ runId: run.runId }, { token: continuationToken });
diff --git a/packages/eve/src/execution/turn-workflow.test.ts b/packages/eve/src/execution/turn-workflow.test.ts
index 388c7f63a..92ff9d7bc 100644
--- a/packages/eve/src/execution/turn-workflow.test.ts
+++ b/packages/eve/src/execution/turn-workflow.test.ts
@@ -1,6 +1,7 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import type { HookPayload } from "#channel/types.js";
+import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-step.js";
import { dispatchRuntimeActionsStep } from "#execution/dispatch-runtime-actions-step.js";
import { dispatchWorkflowRuntimeActionsStep } from "#execution/dispatch-workflow-runtime-actions-step.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
@@ -45,6 +46,10 @@ vi.mock("./dispatch-workflow-runtime-actions-step.js", () => ({
dispatchWorkflowRuntimeActionsStep: vi.fn(),
}));
+vi.mock("./cancel-descendant-turns-step.js", () => ({
+ cancelDescendantTurnsStep: vi.fn(),
+}));
+
vi.mock("./workflow-callback-url.js", () => ({
resolveWorkflowCallbackBaseUrl: vi.fn((metadataUrl: string) => metadataUrl),
}));
@@ -270,6 +275,10 @@ describe("turnWorkflow", () => {
await turnWorkflow(input);
expect(vi.mocked(turnStep).mock.calls[0]?.[0].abortSignal).toBeInstanceOf(AbortSignal);
+ expect(cancelDescendantTurnsStep).toHaveBeenCalledWith({
+ serializedContext: { state: "start" },
+ sessionState,
+ });
// The cancel token is session-scoped so a trigger can derive it from
// the session id alone.
expect(cancelHookTokens()).toEqual(["wrun_test_123:cancel"]);
@@ -524,6 +533,58 @@ describe("turnWorkflow", () => {
);
});
+ it("waits for dispatch adoption before cascading a cancellation", async () => {
+ const initialState = createSessionState({ continuationToken: "http:parent" });
+ const pendingState = createSessionState({ continuationToken: "http:parent:turn" });
+ const adoptedState = createSessionState({ continuationToken: "http:parent:turn:adopted" });
+ let finishDispatch:
+ | ((value: { results: readonly []; sessionState: DurableSessionState }) => void)
+ | undefined;
+ const dispatchResult = new Promise<{
+ results: readonly [];
+ sessionState: DurableSessionState;
+ }>((resolve) => {
+ finishDispatch = resolve;
+ });
+ installInbox([], { cancelPayloads: [{}], stayOpen: true });
+ vi.mocked(dispatchRuntimeActionsStep).mockReturnValue(dispatchResult);
+ vi.mocked(turnStep)
+ .mockResolvedValueOnce({
+ action: "park",
+ hasPendingAuthorization: false,
+ hasPendingInputBatch: false,
+ pendingRuntimeActionKeys: ["subagent-call:delegate:call-1"],
+ serializedContext: { state: "pending" },
+ sessionState: pendingState,
+ })
+ .mockResolvedValueOnce({
+ action: "cancelled",
+ serializedContext: { state: "cancelled" },
+ sessionState: adoptedState,
+ });
+
+ const { input } = createInput({
+ driverCapabilities: { cancelledTurnSettle: true, turnInbox: true },
+ mode: "task",
+ sessionState: initialState,
+ });
+ const workflow = turnWorkflow(input);
+ await vi.waitFor(() => expect(dispatchRuntimeActionsStep).toHaveBeenCalledOnce());
+ expect(cancelDescendantTurnsStep).not.toHaveBeenCalled();
+
+ finishDispatch?.({ results: [], sessionState: adoptedState });
+ await workflow;
+
+ expect(vi.mocked(turnStep).mock.calls[1]?.[0].abortSignal?.aborted).toBe(true);
+ expect(cancelDescendantTurnsStep).toHaveBeenCalledWith({
+ serializedContext: { state: "pending" },
+ sessionState: adoptedState,
+ });
+ expect(vi.mocked(dispatchRuntimeActionsStep).mock.invocationCallOrder[0]).toBeLessThan(
+ vi.mocked(cancelDescendantTurnsStep).mock.invocationCallOrder[0]!,
+ );
+ });
+
it("keeps dynamic-workflow child dispatch and immediate remote failures in the same turn", async () => {
const pendingState = createSessionState();
const completedState = createSessionState();
@@ -886,6 +947,7 @@ function installInbox(
readonly cancelPayloads?: readonly unknown[];
readonly claimError?: unknown;
readonly conflict?: { readonly runId: string } | null;
+ readonly stayOpen?: boolean;
} = {},
): InboxMock {
const inbox = createInboxMock(values, options);
@@ -954,6 +1016,7 @@ function createInboxMock(
options: {
readonly claimError?: unknown;
readonly conflict?: { readonly runId: string } | null;
+ readonly stayOpen?: boolean;
} = {},
): InboxMock {
const queue = [...values];
@@ -961,7 +1024,9 @@ function createInboxMock(
const createIterator = vi.fn(() => ({
next: vi.fn(async () => {
const value = queue.shift();
- return value === undefined ? { done: true, value: undefined } : { done: false, value };
+ if (value !== undefined) return { done: false, value };
+ if (options.stayOpen === true) return await new Promise<never>(() => {});
+ return { done: true, value: undefined };
}),
return: vi.fn(async () => ({ done: true, value: undefined })),
}));
diff --git a/packages/eve/src/execution/turn-workflow.ts b/packages/eve/src/execution/turn-workflow.ts
index d754272e0..4c892ad81 100644
--- a/packages/eve/src/execution/turn-workflow.ts
+++ b/packages/eve/src/execution/turn-workflow.ts
@@ -1,6 +1,7 @@
import { createHook, getWorkflowMetadata } from "#compiled/@workflow/core/index.js";
import type { DeliverHookPayload } from "#channel/types.js";
+import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-step.js";
import { sendTurnControlStep, type TurnInboxPayload } from "#execution/turn-control-protocol.js";
import { dispatchRuntimeActionsStep } from "#execution/dispatch-runtime-actions-step.js";
import { dispatchWorkflowRuntimeActionsStep } from "#execution/dispatch-workflow-runtime-actions-step.js";
@@ -114,6 +115,10 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {
// epilogue runs in the driver (`settleCancelledTurnStep`), not as
// a step in this run, where queued cancel wakes could re-dispatch
// it.
+ await cancelDescendantTurnsStep({
+ serializedContext: cursor.serializedContext,
+ sessionState: cursor.sessionState,
+ });
await cancellation?.dispose();
await cursor.finish(
{ sessionState: cursor.sessionState },
diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.ts
index 14d27a072..b1a0735c5 100644
--- a/packages/eve/src/execution/workflow-runtime.test.ts
+++ b/packages/eve/src/execution/workflow-runtime.test.ts
@@ -141,7 +141,7 @@ describe("createWorkflowRuntime#cancelTurn", () => {
await expect(
buildRuntime().cancelTurn({ sessionId: "session-1", turnId: "turn-2" }),
- ).resolves.toEqual({ status: "cancelling" });
+ ).resolves.toEqual({ status: "accepted" });
expect(resumeHookMock).toHaveBeenCalledWith("session-1:cancel", { turnId: "turn-2" });
});
@@ -149,7 +149,7 @@ describe("createWorkflowRuntime#cancelTurn", () => {
resumeHookMock.mockResolvedValue({ runId: "turn-run" });
await expect(buildRuntime().cancelTurn({ sessionId: "session-1" })).resolves.toEqual({
- status: "cancelling",
+ status: "accepted",
});
expect(resumeHookMock).toHaveBeenCalledWith("session-1:cancel", {});
});
diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.ts
index 01de11caf..93ec8fb10 100644
--- a/packages/eve/src/execution/workflow-runtime.ts
+++ b/packages/eve/src/execution/workflow-runtime.ts
@@ -170,17 +170,7 @@ export function createWorkflowRuntime(config: {
},
async cancelTurn(input: CancelTurnInput): Promise<CancelTurnResult> {
- const payload: TurnCancelPayload = input.turnId === undefined ? {} : { turnId: input.turnId };
-
- try {
- await resumeHook(sessionCancelHookToken(input.sessionId), payload);
- return { status: "cancelling" };
- } catch (error) {
- if (isInactiveCancelTarget(error)) {
- return { status: "no_active_turn" };
- }
- throw error;
- }
+ return await requestWorkflowTurnCancellation(input);
},
async deliver(input: DeliverInput): Promise<{ sessionId: string }> {
@@ -217,6 +207,23 @@ export function createWorkflowRuntime(config: {
};
}
+/** Requests cancellation through a session's stable workflow hook. */
+export async function requestWorkflowTurnCancellation(
+ input: CancelTurnInput,
+): Promise<CancelTurnResult> {
+ const payload: TurnCancelPayload = input.turnId === undefined ? {} : { turnId: input.turnId };
+
+ try {
+ await resumeHook(sessionCancelHookToken(input.sessionId), payload);
+ return { status: "accepted" };
+ } catch (error) {
+ if (isInactiveCancelTarget(error)) {
+ return { status: "no_active_turn" };
+ }
+ throw error;
+ }
+}
+
function isInactiveCancelTarget(error: unknown): boolean {
return (
HookNotFoundError.is(error) ||
diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.ts
index 988299680..248a86205 100644
--- a/packages/eve/src/execution/workflow-steps.test.ts
+++ b/packages/eve/src/execution/workflow-steps.test.ts
@@ -7,7 +7,10 @@ import { ContextKey } from "#context/key.js";
import { AuthKey, ContinuationTokenKey, ModeKey, SessionIdKey } from "#context/keys.js";
import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
import { serializeContext } from "#context/serialize.js";
-import { setPendingRuntimeActionBatch } from "#harness/runtime-actions.js";
+import {
+ getPendingRuntimeActionBatch,
+ setPendingRuntimeActionBatch,
+} from "#harness/runtime-actions.js";
import { getPendingAuthorization, setPendingAuthorization } from "#harness/authorization.js";
import type { HarnessSession, StepResult } from "#harness/types.js";
import { createEmptyHookRegistry } from "#runtime/hooks/registry.js";
@@ -296,7 +299,7 @@ describe("dispatchTurnStep", () => {
});
describe("dispatchRuntimeActionsStep", () => {
- it("starts a declared subagent named agent in a deeply nested session", async () => {
+ it("preserves a started local child when a later start fails", async () => {
vi.stubEnv("VERCEL_ENV", "production");
const compiledArtifactsSource = {} as never;
const compiledBundle = {
@@ -330,7 +333,9 @@ describe("dispatchRuntimeActionsStep", () => {
turnAgent: TestTurnAgent,
} as never;
vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(compiledBundle);
- startMock.mockResolvedValue({ runId: "child-run" });
+ startMock
+ .mockResolvedValueOnce({ runId: "child-run" })
+ .mockRejectedValueOnce(new Error("child start failed"));
getRunMock.mockReturnValue({
getReadable: () =>
new ReadableStream<Uint8Array>({
@@ -351,6 +356,15 @@ describe("dispatchRuntimeActionsStep", () => {
nodeId: "subagents/agent",
subagentName: "agent",
},
+ {
+ callId: "call-2",
+ description: "Second runtime action event description.",
+ input: { message: "investigate fallback routing" },
+ kind: "subagent-call",
+ name: "agent",
+ nodeId: "subagents/agent",
+ subagentName: "agent",
+ },
],
event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
responseMessages: [],
@@ -375,7 +389,31 @@ describe("dispatchRuntimeActionsStep", () => {
sessionState,
});
- expect(result).toEqual({ results: [], sessionState: expect.any(Object) });
+ expect(result).toEqual({
+ results: [
+ {
+ callId: "call-2",
+ isError: true,
+ kind: "subagent-result",
+ output: {
+ code: "SUBAGENT_START_FAILED",
+ message: "child start failed",
+ },
+ subagentName: "agent",
+ },
+ ],
+ sessionState: expect.any(Object),
+ });
+ expect(getPendingRuntimeActionBatch(result.sessionState.snapshot?.session.state)).toMatchObject(
+ {
+ childContinuationTokens: {
+ "call-1": "subagent:parent-session:call-1",
+ },
+ childSessionIds: {
+ "call-1": "child-run",
+ },
+ },
+ );
expect(startMock).toHaveBeenCalledWith(
workflowEntryReference,
[
@@ -522,6 +560,90 @@ describe("dispatchRuntimeActionsStep", () => {
expect(workflowWritesByNamespace.get(DEFAULT_WORKFLOW_STREAM_NAMESPACE)).toBeUndefined();
});
+ it("records a successfully started remote child session for cancellation", async () => {
+ const remote = {
+ definition: {
+ description: "Research remote",
+ kind: "remote",
+ name: "research",
+ nodeId: "remote/research",
+ path: "/eve/v1/session",
+ url: "https://remote.example.com",
+ },
+ };
+ const compiledBundle = {
+ adapterRegistry: {
+ adaptersByKind: new Map([[threadContextAdapter.kind, threadContextAdapter]]),
+ },
+ compiledArtifactsSource: {},
+ graph: {
+ nodesByNodeId: new Map(),
+ root: {
+ sandboxRegistry: { sandbox: null },
+ turnAgent: TestTurnAgent,
+ },
+ },
+ hookRegistry: createEmptyHookRegistry(),
+ resolvedAgent: { config: {} },
+ subagentRegistry: {
+ subagentsByNodeId: new Map([["remote/research", remote]]),
+ },
+ toolRegistry: {},
+ turnAgent: TestTurnAgent,
+ } as never;
+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(compiledBundle);
+ vi.stubGlobal(
+ "fetch",
+ vi
+ .fn()
+ .mockResolvedValue(
+ Response.json(
+ { ok: true, sessionId: "remote-child" },
+ { headers: { "x-eve-session-id": "remote-child" }, status: 202 },
+ ),
+ ),
+ );
+
+ const session = setPendingRuntimeActionBatch({
+ actions: [
+ {
+ callId: "call-remote",
+ description: "Delegate the work.",
+ input: { message: "investigate latest routing" },
+ kind: "remote-agent-call",
+ name: "research",
+ nodeId: "remote/research",
+ remoteAgentName: "research",
+ },
+ ],
+ event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
+ responseMessages: [],
+ session: createStubSession({
+ continuationToken: "http:parent",
+ sessionId: "parent-session",
+ }),
+ });
+ installSessionStoreMocks([session]);
+
+ const result = await dispatchRuntimeActionsStep({
+ callbackBaseUrl: "https://caller.example.com",
+ parentContinuationToken: "turn-inbox",
+ parentWritable: createTestWritable(),
+ serializedContext: createSerializedContext(),
+ sessionState: createStubSessionState({
+ continuationToken: "http:parent",
+ sessionId: "parent-session",
+ }),
+ });
+
+ expect(result.results).toEqual([]);
+ expect(getPendingRuntimeActionBatch(result.sessionState.snapshot?.session.state)).toMatchObject(
+ {
+ childSessionIds: { "call-remote": "remote-child" },
+ },
+ );
+ });
+
it("blocks a stale recursive agent call from a delegated session", async () => {
const compiledBundle = {
adapterRegistry: {
diff --git a/packages/eve/src/harness/runtime-actions.test.ts b/packages/eve/src/harness/runtime-actions.test.ts
index ae8229a53..593a0baa5 100644
--- a/packages/eve/src/harness/runtime-actions.test.ts
+++ b/packages/eve/src/harness/runtime-actions.test.ts
@@ -1,6 +1,8 @@
import { describe, expect, it } from "vitest";
import {
+ getPendingRuntimeActionBatch,
+ recordPendingSubagentChild,
resolvePendingRuntimeActions,
setPendingRuntimeActionBatch,
} from "#harness/runtime-actions.js";
@@ -103,3 +105,33 @@ describe("resolvePendingRuntimeActions", () => {
});
});
});
+
+describe("pending subagent child adoption", () => {
+ it("records child session ids without disturbing local continuation-token cleanup", () => {
+ let session = createParkedSession();
+ session = recordPendingSubagentChild({
+ callId: "call-1",
+ child: {
+ continuationToken: "subagent:test-session:call-1",
+ kind: "local",
+ sessionId: "local-child",
+ },
+ session,
+ });
+ session = recordPendingSubagentChild({
+ callId: "call-remote",
+ child: { kind: "remote", sessionId: "remote-child" },
+ session,
+ });
+
+ expect(getPendingRuntimeActionBatch(session.state)).toMatchObject({
+ childContinuationTokens: {
+ "call-1": "subagent:test-session:call-1",
+ },
+ childSessionIds: {
+ "call-1": "local-child",
+ "call-remote": "remote-child",
+ },
+ });
+ });
+});
diff --git a/packages/eve/src/harness/runtime-actions.ts b/packages/eve/src/harness/runtime-actions.ts
index 90cefd100..902f32424 100644
--- a/packages/eve/src/harness/runtime-actions.ts
+++ b/packages/eve/src/harness/runtime-actions.ts
@@ -37,14 +37,14 @@ interface PendingRuntimeActionEventMetadata {
/**
* Serializable pending runtime-action batch stored on `session.state`.
*
- * `childContinuationTokens` maps each `subagent-call` action's
- * `callId` to the deterministic child token minted by dispatch, so
- * the harness can clear proxy-input entries on result resolution
- * without re-deriving the token (keeps `harness/` runtime-agnostic).
+ * `childContinuationTokens` lets the harness clear local proxy-input entries
+ * on result resolution. `childSessionIds` lets the turn workflow cancel every
+ * successfully adopted local or remote child before dropping the batch.
*/
-interface PendingRuntimeActionBatch {
+export interface PendingRuntimeActionBatch {
readonly actions: readonly RuntimeActionRequest[];
readonly childContinuationTokens?: Readonly<Record<string, string>>;
+ readonly childSessionIds?: Readonly<Record<string, string>>;
readonly event: PendingRuntimeActionEventMetadata;
readonly responseMessages: readonly ModelMessage[];
}
@@ -117,14 +117,21 @@ export function setPendingRuntimeActionBatch(input: {
return { ...input.session, state };
}
-/**
- * Records the child continuation token for a dispatched subagent-call
- * so {@link resolvePendingRuntimeActions} can clear proxy-input
- * entries when the child finishes.
- */
-export function recordPendingSubagentChildToken(input: {
+type PendingSubagentChildIdentity =
+ | {
+ readonly continuationToken: string;
+ readonly kind: "local";
+ readonly sessionId: string;
+ }
+ | {
+ readonly kind: "remote";
+ readonly sessionId: string;
+ };
+
+/** Records one successfully dispatched child's durable identities. */
+export function recordPendingSubagentChild(input: {
readonly callId: string;
- readonly childContinuationToken: string;
+ readonly child: PendingSubagentChildIdentity;
readonly session: HarnessSession;
}): HarnessSession {
const batch = getPendingRuntimeActionBatch(input.session.state);
@@ -136,9 +143,17 @@ export function recordPendingSubagentChildToken(input: {
const state = { ...input.session.state };
state[PENDING_RUNTIME_ACTION_BATCH_KEY] = {
...batch,
- childContinuationTokens: {
- ...batch.childContinuationTokens,
- [input.callId]: input.childContinuationToken,
+ ...(input.child.kind === "local"
+ ? {
+ childContinuationTokens: {
+ ...batch.childContinuationTokens,
+ [input.callId]: input.child.continuationToken,
+ },
+ }
+ : {}),
+ childSessionIds: {
+ ...batch.childSessionIds,
+ [input.callId]: input.child.sessionId,
},
} satisfies PendingRuntimeActionBatch;
diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts
index 5bfbad213..887b3b13e 100644
--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts
+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts
@@ -319,7 +319,7 @@ describe("dispatchChannelRequest", () => {
it("does not mutate route-owned run and deliver inputs", async () => {
const runtimeForTest: Runtime = {
- cancelTurn: vi.fn().mockResolvedValue({ status: "cancelling" }),
+ cancelTurn: vi.fn().mockResolvedValue({ status: "accepted" }),
deliver: vi.fn().mockResolvedValue({ sessionId: "sess_deliver" }),
getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),
run: vi.fn().mockResolvedValue({
diff --git a/packages/eve/src/protocol/cancel-turn.test.ts b/packages/eve/src/protocol/cancel-turn.test.ts
new file mode 100644
index 000000000..d26d5fcb5
--- /dev/null
+++ b/packages/eve/src/protocol/cancel-turn.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from "vitest";
+
+import { CancelTurnResponseSchema } from "#protocol/cancel-turn.js";
+
+describe("CancelTurnResponseSchema", () => {
+ it.each(["accepted", "no_active_turn"] as const)("accepts the %s outcome", (status) => {
+ expect(
+ CancelTurnResponseSchema.safeParse({ ok: true, sessionId: "session-1", status }).success,
+ ).toBe(true);
+ });
+
+ it("rejects the former in-progress wording", () => {
+ expect(
+ CancelTurnResponseSchema.safeParse({
+ ok: true,
+ sessionId: "session-1",
+ status: "cancelling",
+ }).success,
+ ).toBe(false);
+ });
+});
diff --git a/packages/eve/src/protocol/cancel-turn.ts b/packages/eve/src/protocol/cancel-turn.ts
new file mode 100644
index 000000000..1ea500896
--- /dev/null
+++ b/packages/eve/src/protocol/cancel-turn.ts
@@ -0,0 +1,18 @@
+import { z } from "#compiled/zod/index.js";
+
+/** Outcome of requesting cooperative turn cancellation. */
+export type CancelTurnStatus = "accepted" | "no_active_turn";
+
+/** Successful standard turn-cancellation response. */
+export interface CancelTurnResponse {
+ readonly ok: true;
+ readonly sessionId: string;
+ readonly status: CancelTurnStatus;
+}
+
+/** Successful response returned by the standard turn-cancellation route. */
+export const CancelTurnResponseSchema: z.ZodType<CancelTurnResponse> = z.object({
+ ok: z.literal(true),
+ sessionId: z.string().min(1),
+ status: z.enum(["accepted", "no_active_turn"]),
+});
diff --git a/packages/eve/src/public/channels/eve.test.ts b/packages/eve/src/public/channels/eve.test.ts
index bf0e701ec..648897498 100644
--- a/packages/eve/src/public/channels/eve.test.ts
+++ b/packages/eve/src/public/channels/eve.test.ts
@@ -132,7 +132,7 @@ function createEveCancelHandler(input: EveChannelInput) {
if (!cancelRoute) throw new Error("No cancel POST route found");
const agent = createMockAgent();
- agent.cancelTurn.mockResolvedValue({ status: "cancelling" });
+ agent.cancelTurn.mockResolvedValue({ status: "accepted" });
return {
cancelTurn: agent.cancelTurn,
@@ -1253,7 +1253,7 @@ describe("eveChannel — auth array shape", () => {
});
describe("eveChannel — cancel turn", () => {
- it("cancels the current turn with no body and reports 'cancelling'", async () => {
+ it("cancels the current turn with no body and reports 'accepted'", async () => {
const handler = createEveCancelHandler({ auth: none() });
const response = await handler.fetch(cancelRequest());
@@ -1264,7 +1264,7 @@ describe("eveChannel — cancel turn", () => {
await expect(response.json()).resolves.toEqual({
ok: true,
sessionId: "test-session-id",
- status: "cancelling",
+ status: "accepted",
});
expect(handler.cancelTurn).toHaveBeenCalledTimes(1);
expect(handler.cancelTurn).toHaveBeenCalledWith({
diff --git a/packages/eve/src/public/channels/eve.ts b/packages/eve/src/public/channels/eve.ts
index 1b10125e9..6af9feae2 100644
--- a/packages/eve/src/public/channels/eve.ts
+++ b/packages/eve/src/public/channels/eve.ts
@@ -1,6 +1,7 @@
import { type FilePart, type TextPart, type UserContent } from "ai";
import type { CancelTurnResult, SessionAuthContext, SessionCallback } from "#channel/types.js";
+import type { CancelTurnResponse } from "#protocol/cancel-turn.js";
import { parseSessionCallback } from "#channel/session-callback.js";
import { hasInternalRefScheme } from "#internal/attachments/url-refs.js";
import { createLogger, logError } from "#internal/logging.js";
@@ -346,7 +347,7 @@ export function eveChannel(input: EveChannelInput): EveChannel {
}
return Response.json(
- { ok: true, sessionId, status: result.status },
+ { ok: true, sessionId, status: result.status } satisfies CancelTurnResponse,
{
headers: {
"cache-control": "no-store",
diff --git a/packages/eve/src/public/definitions/channel.ts b/packages/eve/src/public/definitions/channel.ts
index a25d530c1..4e2858b59 100644
--- a/packages/eve/src/public/definitions/channel.ts
+++ b/packages/eve/src/public/definitions/channel.ts
@@ -128,7 +128,7 @@ export interface Agent {
* Requests cancellation of a session's in-flight turn. A `turnId` limits
* the request to the turn the caller observed.
*
- * `"cancelling"` means a cancellation hook accepted the request; observe
+ * `"accepted"` means a cancellation hook accepted the request; observe
* the event stream for `turn.cancelled` to confirm that it affected the
* current turn. `"no_active_turn"` means no cancellable hook was active.
* Both outcomes are successful.
diff --git a/packages/eve/src/runtime/agent/mock-model-adapter.test.ts b/packages/eve/src/runtime/agent/mock-model-adapter.test.ts
index 2ff2eac28..d922a6592 100644
--- a/packages/eve/src/runtime/agent/mock-model-adapter.test.ts
+++ b/packages/eve/src/runtime/agent/mock-model-adapter.test.ts
@@ -660,6 +660,39 @@ describe("createMockAuthoredRuntimeModel", () => {
]);
});
+ it("calls an explicit list of authored tools in parallel", async () => {
+ const result = await generateWithPrompt(
+ [
+ {
+ content: [
+ "Call tools in parallel: local-sleeper, remote-sleeper",
+ 'message: "Use wait-for-cancel."',
+ ].join("\n"),
+ role: "user",
+ },
+ ],
+ ["local-sleeper", "remote-sleeper"].map((name) => ({
+ inputSchema: {
+ properties: { message: { type: "string" } },
+ required: ["message"],
+ type: "object",
+ },
+ name,
+ type: "function",
+ })),
+ );
+
+ expect(result.finishReason).toEqual({ raw: undefined, unified: "tool-calls" });
+ expect(result.content).toEqual(
+ ["local-sleeper", "remote-sleeper"].map((name) => ({
+ input: JSON.stringify({ message: "Use wait-for-cancel." }),
+ toolCallId: `call_${name.replaceAll("-", "_")}`,
+ toolName: name,
+ type: "tool-call",
+ })),
+ );
+ });
+
it("calls final_output with a schema-shaped sample when the tool is offered", async () => {
const result = await generateWithPrompt(
[{ content: "Summarize this", role: "user" }],
diff --git a/packages/eve/src/runtime/agent/mock-model-adapter.ts b/packages/eve/src/runtime/agent/mock-model-adapter.ts
index 46201b538..4971dac74 100644
--- a/packages/eve/src/runtime/agent/mock-model-adapter.ts
+++ b/packages/eve/src/runtime/agent/mock-model-adapter.ts
@@ -106,6 +106,7 @@ function createMockModelResult(
}
} else {
const toolCallResult =
+ createParallelAuthoredToolCallsResult(options, modelId) ??
createSubagentDelegationResult(options, modelId) ??
createSkillLoadResult(options.prompt, modelId) ??
createAuthoredToolCallResult(options, modelId);
@@ -206,6 +207,52 @@ function createSkillLoadResult(
const SUBAGENT_TOOL_NAME = "agent";
const SUBAGENT_DELEGATION_DIRECTIVE = /\bdelegate\s+to\s+a\s+subagent\s*:\s*(.+)$/iu;
+const PARALLEL_AUTHORED_TOOLS_DIRECTIVE = /^call tools in parallel:\s*(.+)$/imu;
+
+function createParallelAuthoredToolCallsResult(
+ options: BootstrapGenerateOptions,
+ modelId: string,
+): BootstrapGenerateResult | null {
+ const lastUserMessage = getLastUserPromptText(options.prompt);
+ if (lastUserMessage === null) {
+ return null;
+ }
+
+ const directive = PARALLEL_AUTHORED_TOOLS_DIRECTIVE.exec(lastUserMessage);
+ const requestedNames = directive?.[1]
+ ?.split(",")
+ .map((name) => name.trim())
+ .filter(Boolean);
+
+ if (requestedNames === undefined || requestedNames.length < 2) {
+ return null;
+ }
+ if (new Set(requestedNames).size !== requestedNames.length) {
+ return null;
+ }
+
+ const availableTools = new Map(getAvailableTools(options).map((tool) => [tool.name, tool]));
+ const requestedTools: AvailableBootstrapTool[] = [];
+ for (const name of requestedNames) {
+ const tool = availableTools.get(name);
+ if (tool === undefined) {
+ return null;
+ }
+ requestedTools.push(tool);
+ }
+
+ const city = resolveWeatherCity(lastUserMessage);
+ return createToolCallsGenerateResult({
+ calls: requestedTools.map((tool) => ({
+ input: createMockAuthoredToolInput(tool, lastUserMessage, city),
+ toolCallId: createToolCallId(tool.name),
+ toolName: tool.name,
+ })),
+ inputTokens: estimateTokenCount(getPromptText(options.prompt)),
+ modelId,
+ outputTokens: estimateTokenCount(lastUserMessage),
+ });
+}
/**
* Emits one built-in `agent` tool call when the current user message uses
@@ -362,15 +409,37 @@ function createToolCallGenerateResult(input: {
readonly toolCallId: string;
readonly toolName: string;
}): BootstrapGenerateResult {
- return {
- content: [
+ return createToolCallsGenerateResult({
+ calls: [
{
- input: JSON.stringify(input.input),
+ input: input.input,
toolCallId: input.toolCallId,
toolName: input.toolName,
- type: "tool-call",
},
],
+ inputTokens: input.inputTokens,
+ modelId: input.modelId,
+ outputTokens: input.outputTokens,
+ });
+}
+
+function createToolCallsGenerateResult(input: {
+ readonly calls: readonly {
+ readonly input: unknown;
+ readonly toolCallId: string;
+ readonly toolName: string;
+ }[];
+ readonly inputTokens: number;
+ readonly modelId: string;
+ readonly outputTokens: number;
+}): BootstrapGenerateResult {
+ return {
+ content: input.calls.map((call) => ({
+ input: JSON.stringify(call.input),
+ toolCallId: call.toolCallId,
+ toolName: call.toolName,
+ type: "tool-call",
+ })),
finishReason: { raw: undefined, unified: "tool-calls" },
response: {
id: "bootstrap-response",
diff --git a/packages/eve/test/scenarios/turn-cancellation.scenario.test.ts b/packages/eve/test/scenarios/turn-cancellation.scenario.test.ts
new file mode 100644
index 000000000..b04f694b1
--- /dev/null
+++ b/packages/eve/test/scenarios/turn-cancellation.scenario.test.ts
@@ -0,0 +1,324 @@
+import { describe, expect, it } from "vitest";
+
+import { Client } from "../../src/client/client.js";
+import {
+ type HandleMessageStreamEvent,
+ isCurrentTurnBoundaryEvent,
+} from "../../src/protocol/message.js";
+import { createEveCancelTurnRoutePath } from "../../src/protocol/routes.js";
+import {
+ type ScenarioAppDescriptor,
+ useScenarioApp,
+} from "../../src/internal/testing/scenario-app.js";
+import { startEveDev } from "./dev-server-harness.js";
+
+const scenarioApp = useScenarioApp();
+const SCENARIO_TIMEOUT_MS = 360_000;
+const EVENT_TIMEOUT_MS = 30_000;
+const REMOTE_TOKEN = "layer-3-scenario-token";
+
+const REMOTE_DESCRIPTOR: ScenarioAppDescriptor = {
+ dependencies: { zod: "^4.3.6" },
+ files: {
+ "agent/agent.ts": `import { defineAgent } from "eve";
+
+export default defineAgent({ model: "openai/gpt-5.4-mini" });
+`,
+ "agent/channels/eve.ts": `import { eveChannel } from "eve/channels/eve";
+
+export default eveChannel({
+ auth(request) {
+ if (request.headers.get("authorization") !== "Bearer ${REMOTE_TOKEN}") return null;
+ return {
+ attributes: {},
+ authenticator: "scenario-bearer",
+ principalId: "cancellation-parent",
+ principalType: "service",
+ };
+ },
+});
+`,
+ "agent/instructions.md": "Call explicitly requested tools.\n",
+ "agent/tools/wait-for-cancel.ts": `import { defineTool } from "eve/tools";
+import { z } from "zod";
+
+export default defineTool({
+ description: "Wait until the current turn is cancelled.",
+ inputSchema: z.object({}),
+ execute(_input, ctx) {
+ return new Promise((_resolve, reject) => {
+ const abort = () => reject(ctx.abortSignal.reason);
+ if (ctx.abortSignal.aborted) return abort();
+ ctx.abortSignal.addEventListener("abort", abort, { once: true });
+ });
+ },
+});
+`,
+ },
+ installDependencies: true,
+ name: "remote-cancellation-child",
+};
+
+function createParentDescriptor(remoteUrl: string): ScenarioAppDescriptor {
+ return {
+ dependencies: { zod: "^4.3.6" },
+ files: {
+ "agent/agent.ts": `import { defineAgent } from "eve";
+
+export default defineAgent({ model: "openai/gpt-5.4-mini" });
+`,
+ "agent/instructions.md": "Delegate cancellation waits as requested.\n",
+ "agent/subagents/local-sleeper/agent.ts": `import { defineAgent } from "eve";
+
+export default defineAgent({
+ description: "Runs the wait-for-cancel tool and waits for cancellation.",
+ model: "openai/gpt-5.4-mini",
+});
+`,
+ "agent/subagents/local-sleeper/instructions.md":
+ "Call wait-for-cancel immediately and do nothing else.\n",
+ "agent/subagents/local-sleeper/tools/wait-for-cancel.ts": `import { defineTool } from "eve/tools";
+import { z } from "zod";
+
+export default defineTool({
+ description: "Wait until the current turn is cancelled.",
+ inputSchema: z.object({}),
+ execute(_input, ctx) {
+ return new Promise((_resolve, reject) => {
+ const abort = () => reject(ctx.abortSignal.reason);
+ if (ctx.abortSignal.aborted) return abort();
+ ctx.abortSignal.addEventListener("abort", abort, { once: true });
+ });
+ },
+});
+`,
+ "agent/subagents/remote-sleeper.ts": `import { defineRemoteAgent } from "eve";
+import { bearer } from "eve/agents/auth";
+
+export default defineRemoteAgent({
+ auth: bearer("${REMOTE_TOKEN}"),
+ description: "Runs the wait-for-cancel tool and waits for cancellation.",
+ url: ${JSON.stringify(remoteUrl)},
+});
+`,
+ },
+ installDependencies: true,
+ name: "mixed-cancellation-parent",
+ };
+}
+
+describe("turn cancellation descendant cascade", () => {
+ it(
+ "cancels racing local and authenticated remote children then continues the parent",
+ async () => {
+ const remoteApp = await scenarioApp(REMOTE_DESCRIPTOR);
+ const remoteServer = await startEveDev(remoteApp.appRoot);
+
+ try {
+ const parentApp = await scenarioApp(createParentDescriptor(remoteServer.url));
+ const parentServer = await startEveDev(parentApp.appRoot);
+
+ try {
+ const parentClient = new Client({ host: parentServer.url });
+ const parentSession = parentClient.session();
+ const response = await parentSession.send(
+ [
+ "Call tools in parallel: local-sleeper, remote-sleeper",
+ 'message: "Use wait-for-cancel."',
+ ].join("\n"),
+ );
+ const parentIterator = response[Symbol.asyncIterator]();
+ const called = await readSubagentCalls({
+ count: 2,
+ iterator: parentIterator,
+ label: "local and remote subagent dispatch",
+ });
+ const localCalled = called.find((event) => event.data.remote === undefined);
+ const remoteCalled = called.find((event) => event.data.remote !== undefined);
+ if (localCalled === undefined || remoteCalled === undefined) {
+ throw new Error("Expected one local and one remote subagent.called event.");
+ }
+ expect(remoteCalled.data.remote?.url).toBe(remoteServer.url);
+
+ const localIterator = parentClient
+ .session({ sessionId: localCalled.data.childSessionId, streamIndex: 0 })
+ .stream()
+ [Symbol.asyncIterator]();
+
+ const remoteClient = new Client({
+ auth: { bearer: REMOTE_TOKEN },
+ host: remoteServer.url,
+ });
+ const remoteIterator = remoteClient
+ .session({ sessionId: remoteCalled.data.childSessionId, streamIndex: 0 })
+ .stream()
+ [Symbol.asyncIterator]();
+ await Promise.all([
+ readUntil({
+ iterator: localIterator,
+ label: "local wait-for-cancel tool call",
+ matches: isWaitForCancelToolCall,
+ }),
+ readUntil({
+ iterator: remoteIterator,
+ label: "remote wait-for-cancel tool call",
+ matches: isWaitForCancelToolCall,
+ }),
+ ]);
+
+ const cancelResponse = await parentClient.fetch(
+ createEveCancelTurnRoutePath(response.sessionId),
+ { method: "POST" },
+ );
+ expect(cancelResponse.status).toBe(202);
+ await expect(cancelResponse.json()).resolves.toMatchObject({
+ ok: true,
+ sessionId: response.sessionId,
+ status: "accepted",
+ });
+
+ const [localEvents, remoteEvents] = await Promise.all([
+ readThroughBoundary({
+ iterator: localIterator,
+ label: "local cancellation boundary",
+ }),
+ readThroughBoundary({
+ iterator: remoteIterator,
+ label: "remote cancellation boundary",
+ }),
+ ]);
+ const parentEvents = await readThroughBoundary({
+ iterator: parentIterator,
+ label: "parent cancellation boundary",
+ });
+
+ expectCancellationBoundary(localEvents);
+ expectCancellationBoundary(remoteEvents);
+ expectCancellationBoundary(parentEvents);
+ expect(parentEvents.some((event) => event.type === "subagent.completed")).toBe(false);
+
+ const followUp = await (
+ await parentSession.send("Reply with the exact string `still-alive` and nothing else.")
+ ).result();
+ expect(followUp.sessionId).toBe(response.sessionId);
+ expect(followUp.status).toBe("waiting");
+ expect(followUp.message).toBe("still-alive");
+ expect(followUp.events.some((event) => event.type === "turn.cancelled")).toBe(false);
+ } catch (error) {
+ throw new Error(
+ [
+ `parent stdout:\n${parentServer.stdout()}`,
+ `parent stderr:\n${parentServer.stderr()}`,
+ `remote stdout:\n${remoteServer.stdout()}`,
+ `remote stderr:\n${remoteServer.stderr()}`,
+ ].join("\n\n"),
+ { cause: error },
+ );
+ } finally {
+ await parentServer.stop();
+ }
+ } finally {
+ await remoteServer.stop();
+ }
+ },
+ SCENARIO_TIMEOUT_MS,
+ );
+});
+
+type SubagentCalledEvent = Extract<HandleMessageStreamEvent, { type: "subagent.called" }>;
+
+async function readSubagentCalls(input: {
+ readonly count: number;
+ readonly iterator: AsyncIterator<HandleMessageStreamEvent>;
+ readonly label: string;
+}): Promise<readonly SubagentCalledEvent[]> {
+ return await withinEventDeadline(
+ (async () => {
+ const events: SubagentCalledEvent[] = [];
+ while (events.length < input.count) {
+ const next = await input.iterator.next();
+ if (next.done) throw new Error(`Stream ended before ${input.label}.`);
+ if (next.value.type === "subagent.called") events.push(next.value);
+ }
+ return events;
+ })(),
+ input.label,
+ );
+}
+
+function isWaitForCancelToolCall(event: HandleMessageStreamEvent): boolean {
+ return (
+ event.type === "actions.requested" &&
+ event.data.actions.some(
+ (action) => action.kind === "tool-call" && action.toolName === "wait-for-cancel",
+ )
+ );
+}
+
+async function readUntil(input: {
+ readonly iterator: AsyncIterator<HandleMessageStreamEvent>;
+ readonly label: string;
+ readonly matches: (event: HandleMessageStreamEvent) => boolean;
+}): Promise<{ readonly event: HandleMessageStreamEvent }> {
+ return await withinEventDeadline(
+ (async () => {
+ while (true) {
+ const next = await input.iterator.next();
+ if (next.done) throw new Error(`Stream ended before ${input.label}.`);
+ if (input.matches(next.value)) return { event: next.value };
+ }
+ })(),
+ input.label,
+ );
+}
+
+async function readThroughBoundary(input: {
+ readonly iterator: AsyncIterator<HandleMessageStreamEvent>;
+ readonly label: string;
+}): Promise<readonly HandleMessageStreamEvent[]> {
+ const events: HandleMessageStreamEvent[] = [];
+ await withinEventDeadline(
+ (async () => {
+ while (true) {
+ const next = await input.iterator.next();
+ if (next.done) throw new Error(`Stream ended before ${input.label}.`);
+ events.push(next.value);
+ if (isCurrentTurnBoundaryEvent(next.value)) return;
+ }
+ })(),
+ input.label,
+ );
+ if (input.iterator.return !== undefined) {
+ await withinEventDeadline(
+ input.iterator.return(undefined),
+ `${input.label} stream cancellation`,
+ );
+ }
+ return events;
+}
+
+function expectCancellationBoundary(events: readonly HandleMessageStreamEvent[]): void {
+ const types = events.map((event) => event.type);
+ expect(types).toContain("turn.cancelled");
+ expect(types.at(-1)).toBe("session.waiting");
+ expect(types).not.toContain("step.failed");
+ expect(types).not.toContain("turn.failed");
+ expect(types).not.toContain("session.failed");
+}
+
+async function withinEventDeadline<T>(operation: Promise<T>, label: string): Promise<T> {
+ let timeout: ReturnType<typeof setTimeout> | undefined;
+ try {
+ return await Promise.race([
+ operation,
+ new Promise<never>((_resolve, reject) => {
+ timeout = setTimeout(
+ () => reject(new Error(`Timed out waiting for ${label}.`)),
+ EVENT_TIMEOUT_MS,
+ );
+ }),
+ ]);
+ } finally {
+ if (timeout !== undefined) clearTimeout(timeout);
+ }
+}
diff --git a/research/turn-cancellation-channel-ops.md b/research/turn-cancellation-channel-ops.md
index 4b5fc7d1b..9495e82ae 100644
--- a/research/turn-cancellation-channel-ops.md
+++ b/research/turn-cancellation-channel-ops.md
@@ -35,11 +35,11 @@ export interface RouteHandlerArgs<TState> {
}
export interface CancelTurnResult {
- status: "cancelling" | "no_active_turn";
+ status: "accepted" | "no_active_turn";
}
```
-`"cancelling"` means a registered cancellation hook accepted the request, not
+`"accepted"` means a registered cancellation hook accepted the request, not
that cancellation has settled or necessarily matched the caller's guarded
turn. `"no_active_turn"` covers unknown, idle, parked, swept, and otherwise
uncancellable sessions. Both are successful outcomes.
diff --git a/research/turn-cancellation-descendant-cascade.md b/research/turn-cancellation-descendant-cascade.md
new file mode 100644
index 000000000..b5829469d
--- /dev/null
+++ b/research/turn-cancellation-descendant-cascade.md
@@ -0,0 +1,53 @@
+---
+issue: https://github.com/vercel/eve/issues/483
+status: in-review
+last_updated: "2026-07-15"
+---
+
+# Turn cancellation, layer 3: descendant cascade
+
+## Summary
+
+Cancelling a parent turn now cancels every successfully started child in its
+pending runtime-action batch before the parent settles. Local children receive
+a resume on their stable `{childSessionId}:cancel` hook. Remote children receive
+an authenticated `POST /eve/v1/session/:childSessionId/cancel`. Each child runs
+the same cascade, so cancellation follows nested local and remote delegation.
+
+```text
+parent cancel
+ │
+ ├─ wait for dispatch adoption
+ │
+ ├─ local child ── resume {sessionId}:cancel
+ └─ remote child ── POST /eve/v1/session/:id/cancel
+ │
+ └─ child repeats the cascade
+```
+
+## Semantics
+
+- Dispatch remains non-abortable until every start attempt has returned. The
+ parent durably records each successful child session id before it observes
+ cancellation, closing the start-versus-cancel adoption race.
+- Child cancellation requests run in parallel. The parent waits for requests
+ to be accepted, not for descendant turns to finish settling.
+- A newly started child may return before its cancel hook is registered. Local
+ and remote `no_active_turn` responses retry up to 12 attempts at 250 ms.
+ Remote network errors and HTTP 408, 425, 429, and 5xx responses use the same
+ window, resolving outbound auth again for every attempt.
+- Descendant cancellation cannot turn a parent cancellation into a failure.
+ Permanent and exhausted request errors are logged; the parent still emits
+ `turn.cancelled` followed by `session.waiting` and drops the pending batch.
+- Completed, parked, swept, or cancellation-degraded children are benign
+ no-ops. This layer cancels active turns only; terminal task cancellation and
+ parked-session reset remain separate work.
+
+## Rejected mechanisms
+
+Workflow `Run.cancel()` is not the primary mechanism because it only stops a
+workflow at a suspension point and does not abort the in-flight `turnStep`.
+Minting a Workflow webhook would duplicate eve's authenticated cancellation
+route and expose an unnecessary public capability URL. Reusing the turn hook
+and HTTP route keeps local and remote cancellation on the same cooperative
+settlement path.
diff --git a/research/turn-cancellation-trigger-surface.md b/research/turn-cancellation-trigger-surface.md
index 424a5ca75..159dab43c 100644
--- a/research/turn-cancellation-trigger-surface.md
+++ b/research/turn-cancellation-trigger-surface.md
@@ -28,7 +28,7 @@ durable state, events, or workflow behavior is introduced.
| Status | Body | Meaning |
| ------- | --------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
-| 202 | `{ ok: true, sessionId, status: "cancelling" }` | A registered cancellation hook accepted the request. Observe the stream for the effective outcome. |
+| 202 | `{ ok: true, sessionId, status: "accepted" }` | A registered cancellation hook accepted the request. Observe the stream for the effective outcome. |
| 202 | `{ ok: true, sessionId, status: "no_active_turn" }` | No resumable cancellation target exists, including unknown and already-settled sessions. |
| 400 | `{ ok: false, error }` | Malformed body or missing session id. |
| 401/403 | — | Authentication rejected the request. |
@@ -40,9 +40,9 @@ return `no_active_turn`.
## Semantics
-- `"cancelling"` is acceptance, not settlement. Confirm an effective cancel by
+- `"accepted"` is acceptance, not settlement. Confirm an effective cancel by
observing `turn.cancelled` and `session.waiting`.
-- A guarded mismatch returns `"cancelling"` because the hook accepted and
+- A guarded mismatch returns `"accepted"` because the hook accepted and
discarded the payload.
- A hook-conflict-degraded current turn is uncancellable. A stale prior owner
may accept the request, so HTTP status alone cannot identify the affected
@@ -66,7 +66,7 @@ POST /eve/v1/session/:sessionId/cancel { turnId? }
└─ runtime.cancelTurn
└─ resumeHook(`${sessionId}:cancel`, { turnId? })
├─ missing / terminal target → no_active_turn
- └─ accepted payload → cancelling
+ └─ accepted payload → accepted
```
The token helper lives in `execution/turn-cancellation-token.ts`; the HTTP
diff --git a/research/turn-cancellation-turn-workflow.md b/research/turn-cancellation-turn-workflow.md
index ed79d9fd7..dfe4e62ad 100644
--- a/research/turn-cancellation-turn-workflow.md
+++ b/research/turn-cancellation-turn-workflow.md
@@ -69,9 +69,8 @@ resuming the cancel hook, which tests do directly.
workflow results): the wait stops and the turn settles cancelled the same
way. The pending runtime-action batch and workflow interrupt are dropped
at settle time (their tool-call exchange lives inside the batch and never
- reached history; replaying them would re-dispatch the actions).
- Descendants are _not_ cascaded to (layer 3); their late results land on
- the dead turn inbox and are dropped.
+ reached history; replaying them would re-dispatch the actions). Layer 3 now
+ cancels successfully adopted descendants before this settle.
- **Cancel after the turn settled (or before it starts)**: benign no-op —
the settle disposed the session cancel hook, so a late resume rejects
with `HookNotFoundError`. Duplicate and same-instant cancels are also