Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): cancellation layer 2 - HTTP cancel-turn trigger route (+ channel-ops research) (#817)

Andrew Barba20cd9a1f26ff
diff --git a/.changeset/eve-channel-cancel-turn-route.md b/.changeset/eve-channel-cancel-turn-route.md
new file mode 100644
index 000000000..dc70124b1
--- /dev/null
+++ b/.changeset/eve-channel-cancel-turn-route.md
@@ -0,0 +1,5 @@
+---
+"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.
diff --git a/docs/channels/eve.mdx b/docs/channels/eve.mdx
index 944e54a7f..667438666 100644
--- a/docs/channels/eve.mdx
+++ b/docs/channels/eve.mdx
@@ -18,12 +18,13 @@ export default eveChannel({
## Routes
-The application exposes a health route plus eve channel routes that inspect the agent, create sessions, send follow-ups, and stream events:
+The application exposes a health route plus eve channel routes that inspect the agent, create sessions, send follow-ups, cancel turns, and stream events:
- `GET /eve/v1/health`
- `GET /eve/v1/info`
- `POST /eve/v1/session` (start a session)
- `POST /eve/v1/session/:sessionId` (send a follow-up)
+- `POST /eve/v1/session/:sessionId/cancel` (cancel the in-flight turn)
- `GET /eve/v1/session/:sessionId/stream` (stream events, NDJSON)
Start a session with a minimal body. The response returns `sessionId` and the `continuationToken` you reuse for follow-ups:
@@ -44,6 +45,15 @@ curl -N https://<deployment>/eve/v1/session/ses_01h.../stream
# {"type":"message.completed",...}
```
+Cancel a session's in-flight turn with an empty body, or scope the cancel to the turn you observed by passing the `turnId` stamped on that turn's stream events:
+
+```bash
+curl -X POST https://<deployment>/eve/v1/session/ses_01h.../cancel
+# {"ok":true,"sessionId":"ses_01h...","status":"cancelling"}
+```
+
+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.
+
See [Sessions, runs & streaming](../concepts/sessions-runs-and-streaming) for the full request and stream flow, including the complete event set.
## CORS
diff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.md
index 8bfd2c8a5..f63679c49 100644
--- a/docs/concepts/sessions-runs-and-streaming.md
+++ b/docs/concepts/sessions-runs-and-streaming.md
@@ -89,6 +89,17 @@ If the session is waiting on a human-in-the-loop approval, a matching text reply
For deterministic ordering, send one follow-up at a time and wait for the next `session.waiting` event before sending another message to the same session. See [message delivery and queueing](./execution-model-and-durability#message-delivery-and-queueing) for the current runtime contract.
+## Cancel the in-flight turn
+
+POST to the session's cancel endpoint to stop the turn that is currently running. The body is optional; pass `turnId` (stamped on every turn-scoped stream event) to scope the cancel to the turn you observed:
+
+```bash
+curl -X POST http://127.0.0.1:3000/eve/v1/session/<sessionId>/cancel
+# {"ok":true,"sessionId":"<sessionId>","status":"cancelling"}
+```
+
+`"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.
+
## Reconnect and rewind
The stream is durable. Every event is recorded before a step completes, so the whole stream is replayable. A nonnegative `startIndex` is an absolute event count: use it to pick up where you dropped off or pass `0` to rewind to the start.
diff --git a/docs/evals/targets.mdx b/docs/evals/targets.mdx
index 63ece9d31..1b8b0549e 100644
--- a/docs/evals/targets.mdx
+++ b/docs/evals/targets.mdx
@@ -24,7 +24,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.
+- `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.
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/streaming.mdx b/docs/guides/client/streaming.mdx
index 522cdd81a..179941660 100644
--- a/docs/guides/client/streaming.mdx
+++ b/docs/guides/client/streaming.mdx
@@ -141,7 +141,9 @@ Tail-relative attachments do not automatically reconnect or advance the session'
## Abort a request
-Pass an `AbortSignal` to cancel the POST or stream. Arm the timeout before awaiting `send()` so it covers the POST as well as the stream:
+Pass an `AbortSignal` to cancel the POST or stream. Aborting is local transport cancellation: turns are resumable across disconnects, so detaching never stops the server-side turn — it keeps running and remains attachable by index. To stop the turn itself, POST the session's [cancel route](../../channels/eve#routes) and watch the stream settle with `turn.cancelled` followed by `session.waiting`.
+
+Arm the timeout before awaiting `send()` so it covers the POST as well as the stream:
```ts
const controller = new AbortController();
diff --git a/docs/guides/frontend/overview.mdx b/docs/guides/frontend/overview.mdx
index d15a51181..26cf0e5c9 100644
--- a/docs/guides/frontend/overview.mdx
+++ b/docs/guides/frontend/overview.mdx
@@ -69,7 +69,7 @@ export function Chat() {
| `events` | Raw eve stream events for this session. |
| `session` | Serializable session cursor (`sessionId`, `continuationToken`, `streamIndex`). |
| `send` | Send text or the full turn payload (multi-part messages, HITL responses). |
-| `stop` | Abort the active request. |
+| `stop` | Abort the client's in-flight stream. The server-side turn keeps running. |
| `reset` | Clear local events, data, errors, and the local session cursor. |
Most chat UIs only need `data.messages` and `status`. Drop down to `events` when you need the authoritative wire events directly, for example to persist an audit log or build a custom projection.
@@ -96,7 +96,9 @@ await agent.send({
});
```
-Assistant text, reasoning, tool calls, and tool results stream into `data` as they arrive, and `status` moves from `ready` to `submitted` to `streaming` and back. Call `stop()` to abort the active request, and `reset()` to clear local state so the next send starts a fresh durable session.
+Assistant text, reasoning, tool calls, and tool results stream into `data` as they arrive, and `status` moves from `ready` to `submitted` to `streaming` and back. Call `stop()` to abort the client's in-flight stream, and `reset()` to clear local state so the next send starts a fresh durable session.
+
+`stop()` is local: turns are resumable across disconnects, so detaching the stream never cancels the work — the turn keeps running and billing on the server. To stop the turn itself, POST the session's [cancel route](../../channels/eve#routes); the turn then settles on the stream as `turn.cancelled` followed by `session.waiting`.
After eve confirms an attachment turn with `message.received`, the default reducer projects each
received attachment as a `file` part on the user message. The part includes `mediaType`, optional
diff --git a/docs/guides/frontend/use-eve-agent-svelte.mdx b/docs/guides/frontend/use-eve-agent-svelte.mdx
index 83c4a9955..b4f7259bf 100644
--- a/docs/guides/frontend/use-eve-agent-svelte.mdx
+++ b/docs/guides/frontend/use-eve-agent-svelte.mdx
@@ -31,7 +31,7 @@ Import from `eve/svelte` and read the reactive getters directly. No `$` prefix:
| `events` | `readonly HandleMessageStreamEvent[]` | Raw server events for this session. |
| `session` | `SessionState` | Snapshot of session state. |
| `send` | `(input: SendTurnPayload) => Promise<void>` | Send text or a full turn (multi-part, attachments, HITL responses). |
-| `stop` | `() => void` | Abort the in-flight request. |
+| `stop` | `() => void` | Abort the client's in-flight stream. |
| `reset` | `() => void` | Clear state and start a new session. |
These state fields are reactive getters, so read them straight from templates, `$derived`, or `$effect`. They are not stores, so don't prefix them with `$`.
@@ -103,7 +103,7 @@ The find-and-answer flow is identical across frameworks. The [React hook referen
## Stop, reset, and resume
-`stop()` aborts the in-flight stream. `reset()` wipes state and starts a fresh session. To resume across reloads, hand `initialSession` the state you saved earlier and use `onSessionChange` to persist the cursor as it advances:
+`stop()` aborts the in-flight stream; the server-side turn keeps running and remains attachable — to stop the turn itself, POST the session's [cancel route](../../channels/eve#routes). `reset()` wipes state and starts a fresh session. To resume across reloads, hand `initialSession` the state you saved earlier and use `onSessionChange` to persist the cursor as it advances:
```ts
const agent = useEveAgent({
diff --git a/docs/guides/frontend/use-eve-agent-vue.mdx b/docs/guides/frontend/use-eve-agent-vue.mdx
index 105be0d2e..2684ffd33 100644
--- a/docs/guides/frontend/use-eve-agent-vue.mdx
+++ b/docs/guides/frontend/use-eve-agent-vue.mdx
@@ -33,7 +33,7 @@ const { data } = useEveAgent();
| `events` | `ComputedRef<readonly HandleMessageStreamEvent[]>` | Raw server events for this session. |
| `session` | `ComputedRef<SessionState>` | Snapshot of session state. |
| `send` | `(input: SendTurnPayload) => Promise<void>` | Send text or a full turn (multi-part, attachments, HITL responses). |
-| `stop` | `() => void` | Abort the in-flight request. |
+| `stop` | `() => void` | Abort the client's in-flight stream. |
| `reset` | `() => void` | Clear state and start a new session. |
The first five are `ComputedRef`s; the rest are methods. Destructure whatever you need, since refs keep their reactivity through destructuring. Read them with `.value` in `<script>`, and unwrapped in `<template>`.
@@ -116,7 +116,7 @@ The find-and-answer flow is the same across every framework. The [React hook ref
## Stop, reset, and resume
-`stop()` aborts the in-flight stream. `reset()` wipes state and starts a fresh session. To survive a reload, pass `initialSession` to restore a saved session and `onSessionChange` to persist the cursor as it moves:
+`stop()` aborts the in-flight stream; the server-side turn keeps running and remains attachable — to stop the turn itself, POST the session's [cancel route](../../channels/eve#routes). `reset()` wipes state and starts a fresh session. To survive a reload, pass `initialSession` to restore a saved session and `onSessionChange` to persist the cursor as it moves:
```ts
const agent = useEveAgent({
diff --git a/e2e/fixtures/agent-cancellation/.gitignore b/e2e/fixtures/agent-cancellation/.gitignore
new file mode 100644
index 000000000..eb095f0f8
--- /dev/null
+++ b/e2e/fixtures/agent-cancellation/.gitignore
@@ -0,0 +1,10 @@
+node_modules
+.env*
+.eve
+.vercel
+.next
+.output
+.nitro
+dist
+.DS_Store
+*.tsbuildinfo
diff --git a/e2e/fixtures/agent-cancellation/.vercelignore b/e2e/fixtures/agent-cancellation/.vercelignore
new file mode 100644
index 000000000..357664320
--- /dev/null
+++ b/e2e/fixtures/agent-cancellation/.vercelignore
@@ -0,0 +1,6 @@
+node_modules
+.eve
+.next
+.output
+.nitro
+dist
diff --git a/e2e/fixtures/agent-cancellation/agent/agent.ts b/e2e/fixtures/agent-cancellation/agent/agent.ts
new file mode 100644
index 000000000..cc302c34c
--- /dev/null
+++ b/e2e/fixtures/agent-cancellation/agent/agent.ts
@@ -0,0 +1,5 @@
+import { defineAgent } from "eve";
+
+export default defineAgent({
+ model: process.env.EVE_E2E_MODEL ?? "openai/gpt-5.6-sol",
+});
diff --git a/e2e/fixtures/agent-cancellation/agent/instructions.md b/e2e/fixtures/agent-cancellation/agent/instructions.md
new file mode 100644
index 000000000..ed44093bf
--- /dev/null
+++ b/e2e/fixtures/agent-cancellation/agent/instructions.md
@@ -0,0 +1,11 @@
+# Identity
+
+You are a test fixture agent for turn-cancellation coverage.
+
+# Rules
+
+- When the user asks you to wait for cancellation, 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
+ tools.
diff --git a/e2e/fixtures/agent-cancellation/agent/tools/wait-for-cancellation.ts b/e2e/fixtures/agent-cancellation/agent/tools/wait-for-cancellation.ts
new file mode 100644
index 000000000..a5df86034
--- /dev/null
+++ b/e2e/fixtures/agent-cancellation/agent/tools/wait-for-cancellation.ts
@@ -0,0 +1,29 @@
+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 current turn is cancelled. Only call when the user explicitly asks you to wait for cancellation.",
+ 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) {
+ abort();
+ return;
+ }
+ ctx.abortSignal.addEventListener("abort", abort, { once: true });
+ });
+ },
+});
diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-turn.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-turn.eval.ts
new file mode 100644
index 000000000..322f44beb
--- /dev/null
+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-turn.eval.ts
@@ -0,0 +1,174 @@
+import { defineEval, type EveEvalContext, type EveEvalTargetHandle } 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`.
+ */
+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.",
+ });
+ 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}.`);
+
+ const cancelled = await postJson<CancelTurnResponse>(t.target, cancelPath);
+ 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'",
+ ),
+ );
+
+ // 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");
+
+ // The session accepts the next message normally.
+ const followUp = await session.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"];
+ 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;
+ await t.sleep(500);
+ }
+ await t.require(
+ lateStatus,
+ satisfies(
+ (value: CancelTurnResponse["status"]) => value === "no_active_turn",
+ "a late cancel reports no_active_turn",
+ ),
+ );
+
+ t.event("turn.cancelled", { count: 1 });
+ },
+});
diff --git a/e2e/fixtures/agent-cancellation/evals/evals.config.ts b/e2e/fixtures/agent-cancellation/evals/evals.config.ts
new file mode 100644
index 000000000..e5a4265ca
--- /dev/null
+++ b/e2e/fixtures/agent-cancellation/evals/evals.config.ts
@@ -0,0 +1,6 @@
+import { defineEvalConfig } from "eve/evals";
+
+/** Default judge model for any `t.judge.*` assertion in this fixture. */
+export default defineEvalConfig({
+ judge: { model: process.env.EVE_E2E_MODEL ?? "openai/gpt-5.6-sol" },
+});
diff --git a/e2e/fixtures/agent-cancellation/package.json b/e2e/fixtures/agent-cancellation/package.json
new file mode 100644
index 000000000..7cde0d590
--- /dev/null
+++ b/e2e/fixtures/agent-cancellation/package.json
@@ -0,0 +1,24 @@
+{
+ "name": "agent-cancellation",
+ "version": "0.0.0",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "build": "eve build",
+ "dev": "eve dev",
+ "start": "eve start",
+ "typecheck": "eve build && tsc",
+ "test:e2e": "eve eval --strict"
+ },
+ "dependencies": {
+ "@opentelemetry/core": "2.6.1",
+ "@opentelemetry/sdk-trace-base": "2.6.1",
+ "@vercel/otel": "2.1.2",
+ "eve": "workspace:*",
+ "zod": "catalog:"
+ },
+ "devDependencies": {
+ "@types/node": "catalog:",
+ "typescript": "catalog:"
+ }
+}
diff --git a/e2e/fixtures/agent-cancellation/tsconfig.json b/e2e/fixtures/agent-cancellation/tsconfig.json
new file mode 100644
index 000000000..85e3eceb8
--- /dev/null
+++ b/e2e/fixtures/agent-cancellation/tsconfig.json
@@ -0,0 +1,17 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "esnext",
+ "moduleResolution": "bundler",
+ "outDir": "dist",
+ "rootDir": ".",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "declaration": true,
+ "noEmit": true,
+ "types": ["node"]
+ },
+ "include": ["agent/**/*.ts", "evals/**/*.ts"]
+}
diff --git a/packages/eve/src/channel/cross-channel-receive.test.ts b/packages/eve/src/channel/cross-channel-receive.test.ts
index 30c2e45f6..302ddc14a 100644
--- a/packages/eve/src/channel/cross-channel-receive.test.ts
+++ b/packages/eve/src/channel/cross-channel-receive.test.ts
@@ -10,6 +10,7 @@ import type { Runtime } from "#channel/types.js";
function makeRuntime(): Runtime {
return {
+ cancelTurn: vi.fn(),
deliver: vi.fn(),
getEventStream: vi.fn(),
run: vi.fn(),
diff --git a/packages/eve/src/channel/schedule.test.ts b/packages/eve/src/channel/schedule.test.ts
index 374dabb34..b85260134 100644
--- a/packages/eve/src/channel/schedule.test.ts
+++ b/packages/eve/src/channel/schedule.test.ts
@@ -23,6 +23,7 @@ function createMockRunHandle(): RunHandle {
function createMockRuntime(): Runtime {
return {
+ cancelTurn: vi.fn(),
deliver: vi.fn().mockRejectedValue(new Error("no parked session")),
run: vi.fn().mockResolvedValue(createMockRunHandle()),
getEventStream: vi.fn().mockResolvedValue(new ReadableStream<HandleMessageStreamEvent>()),
diff --git a/packages/eve/src/channel/send.test.ts b/packages/eve/src/channel/send.test.ts
index 74fe31d1f..6fa0bb828 100644
--- a/packages/eve/src/channel/send.test.ts
+++ b/packages/eve/src/channel/send.test.ts
@@ -16,6 +16,7 @@ function createMockRunHandle(): RunHandle {
function createRuntime(deliverError: unknown): Runtime {
return {
+ cancelTurn: vi.fn(),
deliver: vi.fn().mockRejectedValue(deliverError),
run: vi.fn().mockResolvedValue(createMockRunHandle()),
getEventStream: vi.fn().mockResolvedValue(new ReadableStream<HandleMessageStreamEvent>()),
@@ -84,6 +85,7 @@ describe("createSendFn", () => {
it("forwards context through deliver and run payloads", async () => {
const context = ["thread background"];
const deliverRuntime: Runtime = {
+ cancelTurn: vi.fn(),
deliver: vi.fn().mockResolvedValue({ sessionId: "existing-session-id" }),
run: vi.fn().mockResolvedValue(createMockRunHandle()),
getEventStream: vi.fn().mockResolvedValue(new ReadableStream<HandleMessageStreamEvent>()),
@@ -115,6 +117,7 @@ describe("createSendFn", () => {
it("adds channel request ids to deliver and run inputs when provided", async () => {
const deliverRuntime: Runtime = {
+ cancelTurn: vi.fn(),
deliver: vi.fn().mockResolvedValue({ sessionId: "existing-session-id" }),
run: vi.fn().mockResolvedValue(createMockRunHandle()),
getEventStream: vi.fn().mockResolvedValue(new ReadableStream<HandleMessageStreamEvent>()),
@@ -141,6 +144,7 @@ describe("createSendFn", () => {
type: "object",
} as const;
const deliverRuntime: Runtime = {
+ cancelTurn: vi.fn(),
deliver: vi.fn().mockResolvedValue({ sessionId: "existing-session-id" }),
run: vi.fn().mockResolvedValue(createMockRunHandle()),
getEventStream: vi.fn().mockResolvedValue(new ReadableStream<HandleMessageStreamEvent>()),
diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.ts
index b0fd6821f..608a3889a 100644
--- a/packages/eve/src/channel/types.ts
+++ b/packages/eve/src/channel/types.ts
@@ -18,6 +18,18 @@ export type RunSessionLimits = Pick<
"maxInputTokensPerSession" | "maxOutputTokensPerSession"
>;
+/** Identifies the session turn to cancel. */
+export interface CancelTurnInput {
+ readonly sessionId: string;
+ /** Limits the request to the turn the caller observed. */
+ readonly turnId?: string;
+}
+
+/** Result of requesting turn cancellation. Both statuses are successful. */
+export interface CancelTurnResult {
+ readonly status: "cancelling" | "no_active_turn";
+}
+
// ---------------------------------------------------------------------------
// Lineage
// ---------------------------------------------------------------------------
@@ -367,6 +379,9 @@ export interface Runtime {
*/
run(input: RunInput): Promise<RunHandle>;
+ /** Requests cancellation of a session's in-flight turn. */
+ cancelTurn(input: CancelTurnInput): Promise<CancelTurnResult>;
+
/**
* Delivers a follow-up message to a parked session.
*/
diff --git a/packages/eve/src/evals/runner/execute-task.test.ts b/packages/eve/src/evals/runner/execute-task.test.ts
index 2b79ef202..329ff6f7a 100644
--- a/packages/eve/src/evals/runner/execute-task.test.ts
+++ b/packages/eve/src/evals/runner/execute-task.test.ts
@@ -360,6 +360,59 @@ describe("executeTask", () => {
expect(outcome.assertions.every((assertion) => assertion.passed)).toBe(true);
});
+ it("sends a follow-up on an attached session via the stream-recovered continuation token", async () => {
+ // The attached stream parks with a token the eval never saw from a POST
+ // response: the only way the follow-up can carry it is recovery from the
+ // `session.waiting` boundary event.
+ const server = createScriptedServer(
+ [
+ {
+ sessionId: "channel-session",
+ events: [
+ turnStarted("turn_2"),
+ messageCompleted("follow-up done", "turn_2"),
+ turnCompleted("turn_2"),
+ sessionWaiting("eve:channel-rekeyed"),
+ ],
+ },
+ ],
+ {
+ streams: [
+ {
+ sessionId: "channel-session",
+ events: [
+ turnStarted("turn_1"),
+ messageCompleted("channel done", "turn_1"),
+ turnCompleted("turn_1"),
+ sessionWaiting("eve:channel-rekeyed"),
+ ],
+ },
+ ],
+ },
+ );
+ vi.spyOn(globalThis, "fetch").mockImplementation(server.fetch);
+
+ const outcome = await executeTask({
+ client: new Client({ host: target.url }),
+ target,
+ evaluation: createTestEval(async (t) => {
+ const session = await t.target.attachSession("channel-session");
+ const followUp = await session.send("continue please");
+ followUp.expectOk();
+ followUp.messageIncludes("follow-up done");
+ }, "attach-send"),
+ });
+
+ expect(outcome.error).toBeUndefined();
+ expect(server.posts).toHaveLength(1);
+ expect(new URL(server.posts[0]!.url).pathname).toBe("/eve/v1/session/channel-session");
+ expect(server.posts[0]?.body).toEqual({
+ continuationToken: "eve:channel-rekeyed",
+ message: "continue please",
+ });
+ expect(outcome.assertions.every((assertion) => assertion.passed)).toBe(true);
+ });
+
it("uses structured turn data as the scoped and aggregate output", async () => {
const server = createScriptedServer([
{
@@ -498,9 +551,9 @@ function turnCompleted(turnId: string): HandleMessageStreamEvent {
return { data: { sequence: 3, turnId }, type: "turn.completed" };
}
-function sessionWaiting(): HandleMessageStreamEvent {
+function sessionWaiting(continuationToken = "eve:session_1"): HandleMessageStreamEvent {
return {
- data: { continuationToken: "eve:session_1", wait: "next-user-message" },
+ data: { continuationToken, wait: "next-user-message" },
type: "session.waiting",
};
}
diff --git a/packages/eve/src/evals/types.ts b/packages/eve/src/evals/types.ts
index 1e8577ef6..2da11a945 100644
--- a/packages/eve/src/evals/types.ts
+++ b/packages/eve/src/evals/types.ts
@@ -369,7 +369,13 @@ export interface EveEvalTargetHandle extends EveEvalTarget {
dispatchSchedule(scheduleId: string): Promise<EveEvalScheduleDispatchResult>;
/** Authenticated fetch against the target base URL. */
fetch(path: string, init?: RequestInit): Promise<Response>;
- /** Attach to a pre-existing session and consume one turn boundary. */
+ /**
+ * Attach to a pre-existing session and consume one turn boundary.
+ *
+ * When that boundary is `session.waiting`, the attached session recovers
+ * the current continuation token from the stream, so `session.send(...)`
+ * and `session.respond(...)` continue the same durable session.
+ */
attachSession(
sessionId: string,
opts?: { readonly startIndex?: number },
diff --git a/packages/eve/src/execution/node-step.test.ts b/packages/eve/src/execution/node-step.test.ts
index a0622fd2b..69622b67e 100644
--- a/packages/eve/src/execution/node-step.test.ts
+++ b/packages/eve/src/execution/node-step.test.ts
@@ -210,6 +210,7 @@ function createTestNode(
function createNoopRuntime(): Runtime {
return {
+ cancelTurn: vi.fn(),
deliver: vi.fn(),
run: vi.fn().mockRejectedValue(new Error("runtime.run should not be called in this test")),
getEventStream: vi
diff --git a/packages/eve/src/execution/turn-cancellation-control.test.ts b/packages/eve/src/execution/turn-cancellation-control.test.ts
index 879ea1950..cda4eb17b 100644
--- a/packages/eve/src/execution/turn-cancellation-control.test.ts
+++ b/packages/eve/src/execution/turn-cancellation-control.test.ts
@@ -1,9 +1,7 @@
import { afterEach, describe, expect, it, vi } from "vitest";
-import {
- createTurnCancellationControl,
- sessionCancelHookToken,
-} from "#execution/turn-cancellation-control.js";
+import { createTurnCancellationControl } from "#execution/turn-cancellation-control.js";
+import { sessionCancelHookToken } from "#execution/turn-cancellation-token.js";
import { TurnCancelledError } from "#harness/turn-cancellation.js";
const createHookMock = vi.fn();
diff --git a/packages/eve/src/execution/turn-cancellation-control.ts b/packages/eve/src/execution/turn-cancellation-control.ts
index c7c438c57..1869ce4f7 100644
--- a/packages/eve/src/execution/turn-cancellation-control.ts
+++ b/packages/eve/src/execution/turn-cancellation-control.ts
@@ -1,25 +1,12 @@
import { createHook } from "#compiled/@workflow/core/index.js";
import { claimHookOwnership, disposeHook, isHookConflictError } from "#execution/hook-ownership.js";
+import {
+ sessionCancelHookToken,
+ type TurnCancelPayload,
+} from "#execution/turn-cancellation-token.js";
import { TurnCancelledError } from "#harness/turn-cancellation.js";
-/**
- * Derives the session-scoped cancel hook token. Stable for the session's
- * lifetime, so a cancel trigger can address it from the session id alone.
- */
-export function sessionCancelHookToken(sessionId: string): string {
- return `${sessionId}:cancel`;
-}
-
-/**
- * Payload accepted by the session cancel hook. The optional `turnId`
- * guard scopes the cancel to the turn the caller observed; a mismatch is
- * consumed as a benign no-op. Omitting it cancels the current turn.
- */
-export interface TurnCancelPayload {
- readonly turnId?: string;
-}
-
/**
* Owns one turn's cancellation surface inside the turn workflow: the
* session-scoped cancel hook and the durable `AbortController` whose
diff --git a/packages/eve/src/execution/turn-cancellation-token.ts b/packages/eve/src/execution/turn-cancellation-token.ts
new file mode 100644
index 000000000..c21fb4b08
--- /dev/null
+++ b/packages/eve/src/execution/turn-cancellation-token.ts
@@ -0,0 +1,12 @@
+/** Derives the stable session-scoped cancellation hook token. */
+export function sessionCancelHookToken(sessionId: string): string {
+ return `${sessionId}:cancel`;
+}
+
+/**
+ * Payload accepted by the session cancel hook. A mismatched `turnId` is a
+ * benign no-op; omitting it targets whichever turn owns the hook.
+ */
+export interface TurnCancelPayload {
+ readonly turnId?: string;
+}
diff --git a/packages/eve/src/execution/turn-cancellation.integration.test.ts b/packages/eve/src/execution/turn-cancellation.integration.test.ts
index 762756740..2ac1606ba 100644
--- a/packages/eve/src/execution/turn-cancellation.integration.test.ts
+++ b/packages/eve/src/execution/turn-cancellation.integration.test.ts
@@ -10,11 +10,18 @@ import {
import { waitForHook } from "#internal/testing/workflow-test-helpers.js";
import { ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";
import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
-import { sessionCancelHookToken } from "#execution/turn-cancellation-control.js";
+import { sessionCancelHookToken } from "#execution/turn-cancellation-token.js";
import { workflowEntry } from "#execution/workflow-entry.js";
+import { createWorkflowRuntime } from "#execution/workflow-runtime.js";
+import { createEveCancelTurnRoutePath } from "#protocol/routes.js";
import type { HandleMessageStreamEvent } from "#protocol/message.js";
+import type { RouteHandlerArgs } from "#channel/routes.js";
+import { none } from "#public/channels/auth.js";
+import { eveChannel } from "#public/channels/eve.js";
+import type { Agent } from "#public/definitions/channel.js";
import type { ToolContext } from "#public/definitions/tool.js";
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`
@@ -120,6 +127,18 @@ async function waitForRunCompletion(runId: string, timeout = 15_000): Promise<vo
throw new Error(`Timed out waiting for run "${runId}" to complete.`);
}
+/** Polls the world until a hook token is swept (terminal-run cleanup). */
+async function waitForHookSweep(token: string, timeout = 15_000): Promise<void> {
+ const world = await getWorld();
+ const deadline = Date.now() + timeout;
+ while (Date.now() < deadline) {
+ const hook = await world.hooks.getByToken(token).catch(() => null);
+ if (hook === null || hook === undefined) return;
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+ throw new Error(`Timed out waiting for hook token "${token}" to be swept.`);
+}
+
/** Polls the world for a hook row by token (hooks are per-run; the token is global). */
async function waitForHookByToken(token: string, timeout = 15_000): Promise<{ runId: string }> {
const world = await getWorld();
@@ -183,6 +202,78 @@ function expectNoFailureEvents(events: readonly HandleMessageStreamEvent[]): voi
}
}
+/** Builds a cancel-route caller backed by the workflow runtime. */
+function createCancelRouteCaller(): (
+ sessionId: string,
+ body?: { readonly turnId?: string },
+) => Promise<Response> {
+ const channel = eveChannel({ auth: none() });
+ const cancelRoute = (
+ channel.routes as readonly { method: string; path: string; handler?: unknown }[]
+ ).find((route) => route.method === "POST" && route.path === "/eve/v1/session/:sessionId/cancel");
+ if (cancelRoute?.handler === undefined) {
+ throw new Error("Expected eveChannel() to register the cancel-turn route.");
+ }
+ const handler = cancelRoute.handler as (
+ req: Request,
+ args: RouteHandlerArgs,
+ ) => Promise<Response>;
+ const runtime = createWorkflowRuntime({
+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
+ });
+ const agent: Agent = {
+ cancelTurn: (input) => runtime.cancelTurn(input),
+ async deliver() {
+ throw new Error("cancel route must not deliver");
+ },
+ async getEventStream() {
+ throw new Error("cancel route must not read events");
+ },
+ async run() {
+ throw new Error("cancel route must not start a session");
+ },
+ };
+
+ return async (sessionId, body) => {
+ const request = new Request(`https://example.com${createEveCancelTurnRoutePath(sessionId)}`, {
+ method: "POST",
+ ...(body === undefined
+ ? {}
+ : { body: JSON.stringify(body), headers: { "content-type": "application/json" } }),
+ });
+ const args = attachRouteAgent(
+ {
+ send: () => {
+ throw new Error("cancel route must not send");
+ },
+ getSession: () => {
+ throw new Error("cancel route must not get a session");
+ },
+ receive: () => {
+ throw new Error("cancel route must not receive");
+ },
+ params: { sessionId },
+ waitUntil: () => undefined,
+ requestIp: "127.0.0.1",
+ } satisfies RouteHandlerArgs,
+ agent,
+ );
+ return await handler(request, args);
+ };
+}
+
+async function expectCancelResponse(
+ response: Response,
+ expected: { readonly sessionId: string; readonly status: "cancelling" | "no_active_turn" },
+): Promise<void> {
+ expect(response.status).toBe(202);
+ await expect(response.json()).resolves.toEqual({
+ ok: true,
+ sessionId: expected.sessionId,
+ status: expected.status,
+ });
+}
+
describe("turn cancellation integration", () => {
it("cancels a turn mid-tool and accepts the next message normally", async () => {
const fixture = createWaitToolRuntime("turn-cancel-tool");
@@ -258,6 +349,83 @@ describe("turn cancellation integration", () => {
});
});
+ it("cancels a turn through the eve channel cancel route", async () => {
+ const fixture = createWaitToolRuntime("turn-cancel-route");
+ const continuationToken = "http:turn-cancel-route";
+ const cancelViaRoute = createCancelRouteCaller();
+
+ await fixture.runtime.run(async () => {
+ await expectCancelResponse(await cancelViaRoute("missing-session"), {
+ sessionId: "missing-session",
+ status: "no_active_turn",
+ });
+
+ const run = await start(workflowEntry, [
+ {
+ input: { message: `Use the ${WAIT_TOOL_NAME} tool.` },
+ serializedContext: buildSerializedContext({
+ channelKind: "http",
+ continuationToken,
+ mode: "conversation",
+ }),
+ },
+ ]);
+ const stream = captureTurnEvents(run);
+
+ try {
+ await waitForHookByToken(sessionCancelHookToken(run.runId));
+ await fixture.toolStarted;
+
+ const cancelled = await cancelViaRoute(run.runId);
+ await expectCancelResponse(cancelled, { sessionId: run.runId, status: "cancelling" });
+
+ const cancelledTurn = await stream.nextTurn();
+
+ expect(cancelledTurn.at(-1)?.type).toBe("session.waiting");
+ expect(
+ containsEventSequence(cancelledTurn, [
+ "turn.started",
+ "turn.cancelled",
+ "session.waiting",
+ ]),
+ ).toBe(true);
+ expect(filterEventsByType(cancelledTurn, "turn.cancelled")).toHaveLength(1);
+ expectNoFailureEvents(cancelledTurn);
+ expect(fixture.toolAborts()).toBe(1);
+
+ // 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.)
+ await waitForHookSweep(sessionCancelHookToken(run.runId));
+ const duplicate = await cancelViaRoute(run.runId);
+ await expectCancelResponse(duplicate, { sessionId: run.runId, status: "no_active_turn" });
+
+ await waitForHook({ runId: run.runId }, { token: continuationToken });
+ await resumeHook(continuationToken, {
+ kind: "deliver",
+ payloads: [{ message: "follow up after route cancel" }],
+ });
+
+ const followUpTurn = await stream.nextTurn();
+
+ expect(followUpTurn.at(-1)?.type).toBe("session.waiting");
+ expect(filterEventsByType(followUpTurn, "turn.cancelled")).toHaveLength(0);
+ expectNoFailureEvents(followUpTurn);
+ expect(
+ followUpTurn.some(
+ (event) =>
+ event.type === "message.completed" &&
+ event.data.message?.includes("follow up after route cancel") === true,
+ ),
+ ).toBe(true);
+ } finally {
+ stream.dispose();
+ await run.cancel();
+ }
+ });
+ }, 60_000);
+
it("cancels a turn waiting on an in-flight subagent and does not re-dispatch it", async () => {
const fixture = createWaitToolRuntime("turn-cancel-subagent");
const continuationToken = "http:turn-cancel-subagent";
diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.ts
index f15e4c185..14d27a072 100644
--- a/packages/eve/src/execution/workflow-runtime.test.ts
+++ b/packages/eve/src/execution/workflow-runtime.test.ts
@@ -131,6 +131,55 @@ describe("createWorkflowRuntime#deliver", () => {
});
});
+describe("createWorkflowRuntime#cancelTurn", () => {
+ function buildRuntime() {
+ return createWorkflowRuntime({ compiledArtifactsSource: {} as RuntimeCompiledArtifactsSource });
+ }
+
+ it("resumes the session cancel hook with an optional turn guard", async () => {
+ resumeHookMock.mockResolvedValue({ runId: "turn-run" });
+
+ await expect(
+ buildRuntime().cancelTurn({ sessionId: "session-1", turnId: "turn-2" }),
+ ).resolves.toEqual({ status: "cancelling" });
+ expect(resumeHookMock).toHaveBeenCalledWith("session-1:cancel", { turnId: "turn-2" });
+ });
+
+ it("uses an empty payload for an unguarded cancel", async () => {
+ resumeHookMock.mockResolvedValue({ runId: "turn-run" });
+
+ await expect(buildRuntime().cancelTurn({ sessionId: "session-1" })).resolves.toEqual({
+ status: "cancelling",
+ });
+ expect(resumeHookMock).toHaveBeenCalledWith("session-1:cancel", {});
+ });
+
+ it("maps missing and terminal targets to 'no_active_turn'", async () => {
+ const { EntityConflictError, HookNotFoundError, RunExpiredError, WorkflowRunNotFoundError } =
+ await import("#compiled/@workflow/errors/index.js");
+ const errors = [
+ new HookNotFoundError("session-1:cancel"),
+ new WorkflowRunNotFoundError("turn-run"),
+ new RunExpiredError("turn already completed"),
+ new EntityConflictError("turn completed during cancellation"),
+ ];
+
+ for (const error of errors) {
+ resumeHookMock.mockRejectedValueOnce(error);
+ await expect(buildRuntime().cancelTurn({ sessionId: "session-1" })).resolves.toEqual({
+ status: "no_active_turn",
+ });
+ }
+ });
+
+ it("rethrows unexpected runtime failures", async () => {
+ const failure = new Error("transient backing-store outage");
+ resumeHookMock.mockRejectedValue(failure);
+
+ await expect(buildRuntime().cancelTurn({ sessionId: "session-1" })).rejects.toBe(failure);
+ });
+});
+
describe("createWorkflowRuntime#run", () => {
const adapter: ChannelAdapter = { kind: "http" };
diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.ts
index 5872efed3..01de11caf 100644
--- a/packages/eve/src/execution/workflow-runtime.ts
+++ b/packages/eve/src/execution/workflow-runtime.ts
@@ -1,6 +1,13 @@
-import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";
+import {
+ EntityConflictError,
+ HookNotFoundError,
+ RunExpiredError,
+ WorkflowRunNotFoundError,
+} from "#compiled/@workflow/errors/index.js";
import type {
+ CancelTurnInput,
+ CancelTurnResult,
DeliverInput,
GetEventStreamOptions,
HookPayload,
@@ -34,6 +41,10 @@ import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-
import { buildRunContext } from "#execution/runtime-context.js";
import { parseNdjsonStream } from "#execution/ndjson-stream.js";
import { RuntimeNoActiveSessionError } from "#execution/runtime-errors.js";
+import {
+ sessionCancelHookToken,
+ type TurnCancelPayload,
+} from "#execution/turn-cancellation-token.js";
const WORKFLOW_ENTRY_NAME = "workflowEntry";
const TURN_WORKFLOW_NAME = "turnWorkflow";
@@ -158,6 +169,20 @@ 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;
+ }
+ },
+
async deliver(input: DeliverInput): Promise<{ sessionId: string }> {
const hookPayload: Extract<HookPayload, { kind: "deliver" }> = {
auth: input.auth,
@@ -192,6 +217,15 @@ export function createWorkflowRuntime(config: {
};
}
+function isInactiveCancelTarget(error: unknown): boolean {
+ return (
+ HookNotFoundError.is(error) ||
+ WorkflowRunNotFoundError.is(error) ||
+ RunExpiredError.is(error) ||
+ EntityConflictError.is(error)
+ );
+}
+
/**
* Starts a workflow on the latest deployment when latest routing applies,
* while preserving local/dev worlds that do not implement latest routing.
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 92782b9c2..5bfbad213 100644
--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts
+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it, vi } from "vitest";
import { CHANNEL_SENTINEL, type CompiledChannel } from "#channel/compiled-channel.js";
import type { RouteHandlerArgs } from "#channel/routes.js";
-import type { DeliverInput, RunInput, Runtime } from "#channel/types.js";
+import type { CancelTurnInput, DeliverInput, RunInput, Runtime } from "#channel/types.js";
import { readVercelProjectLink } from "#internal/vercel/project-link.js";
import type { RouteContext } from "#public/definitions/channel.js";
import { resolveVercelOidcCurrentProject } from "#runtime/governance/auth/vercel-oidc-project.js";
@@ -232,6 +232,7 @@ describe("dispatchChannelRequest", () => {
it("tags route sends with Vercel's request id", async () => {
const runtimeForTest: Runtime = {
+ cancelTurn: vi.fn(),
deliver: vi.fn().mockResolvedValue({ sessionId: "sess_route" }),
getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),
run: vi.fn(),
@@ -277,6 +278,7 @@ describe("dispatchChannelRequest", () => {
it("does not invent a channel request id when Vercel did not send one", async () => {
const runtimeForTest: Runtime = {
+ cancelTurn: vi.fn(),
deliver: vi.fn().mockResolvedValue({ sessionId: "sess_route" }),
getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),
run: vi.fn(),
@@ -317,6 +319,7 @@ describe("dispatchChannelRequest", () => {
it("does not mutate route-owned run and deliver inputs", async () => {
const runtimeForTest: Runtime = {
+ cancelTurn: vi.fn().mockResolvedValue({ status: "cancelling" }),
deliver: vi.fn().mockResolvedValue({ sessionId: "sess_deliver" }),
getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),
run: vi.fn().mockResolvedValue({
@@ -336,11 +339,16 @@ describe("dispatchChannelRequest", () => {
input: { message: "start" },
mode: "conversation",
} satisfies RunInput);
+ const cancelInput = Object.freeze({
+ sessionId: "sess_run",
+ turnId: "turn_1",
+ } satisfies CancelTurnInput);
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
channels: [
{
fetch: async (_request: Request, ctx: RouteContext) => {
+ await ctx.agent.cancelTurn(cancelInput);
await ctx.agent.deliver(deliverInput);
await ctx.agent.run(runInput);
return new Response("ok");
@@ -368,6 +376,7 @@ describe("dispatchChannelRequest", () => {
expect(response.status).toBe(200);
const deliveredInput = vi.mocked(runtimeForTest.deliver).mock.calls[0]?.[0];
const startedInput = vi.mocked(runtimeForTest.run).mock.calls[0]?.[0];
+ expect(runtimeForTest.cancelTurn).toHaveBeenCalledWith(cancelInput);
expect(deliveredInput).not.toBe(deliverInput);
expect(startedInput).not.toBe(runInput);
expect(deliveredInput?.requestId).toBe("iad1::abc123-1710000000000-deadbeef");
diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts
index 10c9b9e63..8336574b8 100644
--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts
+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts
@@ -11,7 +11,10 @@ import { createGetSessionFn } from "#channel/session.js";
import { createLogger, logError } from "#internal/logging.js";
import { readTrustedDevelopmentClientAddress } from "#internal/nitro/dev-client-address.js";
import { DEVELOPMENT_WORKFLOW_SECRET_ENV } from "#internal/workflow/development-world-protocol.js";
-import { attachAgentInfoRouteResponse } from "#internal/nitro/routes/channel-route-context.js";
+import {
+ attachAgentInfoRouteResponse,
+ attachRouteAgent,
+} from "#internal/nitro/routes/channel-route-context.js";
import type { NitroArtifactsConfig } from "#internal/nitro/routes/runtime-artifacts.js";
import { resolveNitroChannelRuntimeBundle } from "#internal/nitro/routes/runtime-stack.js";
import { readVercelProjectLink } from "#internal/vercel/project-link.js";
@@ -190,19 +193,22 @@ function buildRouteArgs(
toCrossChannelTargets(bundle.channels),
);
- const args = attachAgentInfoRouteResponse(
- {
- send,
- getSession,
- receive,
- params,
- waitUntil,
- requestIp,
- },
- async () => {
- const { handleAgentInfoRequest } = await import("#internal/nitro/routes/info.js");
- return await handleAgentInfoRequest(config);
- },
+ const args = attachRouteAgent(
+ attachAgentInfoRouteResponse(
+ {
+ send,
+ getSession,
+ receive,
+ params,
+ waitUntil,
+ requestIp,
+ },
+ async () => {
+ const { handleAgentInfoRequest } = await import("#internal/nitro/routes/info.js");
+ return await handleAgentInfoRequest(config);
+ },
+ ),
+ agent,
);
return {
@@ -214,6 +220,9 @@ function buildRouteArgs(
function createRouteAgent(runtime: Runtime, requestId: string | undefined): Agent {
return {
+ async cancelTurn(input) {
+ return await runtime.cancelTurn(input);
+ },
async deliver(input) {
const deliverInput: DeliverInput = { ...input, requestId }; // Avoid mutating a frozen caller input.
return await runtime.deliver(deliverInput);
diff --git a/packages/eve/src/internal/nitro/routes/channel-route-context.ts b/packages/eve/src/internal/nitro/routes/channel-route-context.ts
index e6b9fca67..7104d6107 100644
--- a/packages/eve/src/internal/nitro/routes/channel-route-context.ts
+++ b/packages/eve/src/internal/nitro/routes/channel-route-context.ts
@@ -1,18 +1,21 @@
import type { RouteHandlerArgs } from "#channel/routes.js";
+import type { Agent } from "#public/definitions/channel.js";
type AgentInfoRouteResponse = () => Promise<Response>;
const agentInfoRouteResponseKey = "__eveAgentInfoRouteResponse";
+const routeAgentKey = "__eveRouteAgent";
-type AgentInfoRouteArgs = RouteHandlerArgs & {
+type InternalRouteArgs = RouteHandlerArgs & {
[agentInfoRouteResponseKey]?: AgentInfoRouteResponse;
+ [routeAgentKey]?: Agent;
};
export function attachAgentInfoRouteResponse<TArgs extends RouteHandlerArgs>(
args: TArgs,
respond: AgentInfoRouteResponse,
): TArgs {
- const routeArgs: AgentInfoRouteArgs = args;
+ const routeArgs: InternalRouteArgs = args;
routeArgs[agentInfoRouteResponseKey] = respond;
return args;
}
@@ -20,6 +23,17 @@ export function attachAgentInfoRouteResponse<TArgs extends RouteHandlerArgs>(
export function readAgentInfoRouteResponse(
args: RouteHandlerArgs,
): AgentInfoRouteResponse | undefined {
- const routeArgs: AgentInfoRouteArgs = args;
+ const routeArgs: InternalRouteArgs = args;
return routeArgs[agentInfoRouteResponseKey];
}
+
+export function attachRouteAgent<TArgs extends RouteHandlerArgs>(args: TArgs, agent: Agent): TArgs {
+ const routeArgs: InternalRouteArgs = args;
+ routeArgs[routeAgentKey] = agent;
+ return args;
+}
+
+export function readRouteAgent(args: RouteHandlerArgs): Agent | undefined {
+ const routeArgs: InternalRouteArgs = args;
+ return routeArgs[routeAgentKey];
+}
diff --git a/packages/eve/src/internal/testing/route-harness.ts b/packages/eve/src/internal/testing/route-harness.ts
index 5d76f874c..08c080562 100644
--- a/packages/eve/src/internal/testing/route-harness.ts
+++ b/packages/eve/src/internal/testing/route-harness.ts
@@ -12,11 +12,12 @@ import type { Agent, RouteContext } from "#public/definitions/channel.js";
*/
/**
- * Observable mock {@link Agent}. The `run` / `deliver` / `getEventStream`
+ * Observable mock {@link Agent}. The `run` / `deliver` / `cancelTurn` / `getEventStream`
* methods are `vi.fn()` instances, so tests can assert on call counts,
* arguments, and reorder return values mid-test with `mockResolvedValueOnce`.
*/
export interface MockAgent extends Agent {
+ readonly cancelTurn: Mock;
readonly run: Mock;
readonly deliver: Mock;
readonly getEventStream: Mock;
@@ -34,6 +35,7 @@ export interface MockAgent extends Agent {
*/
export function createMockAgent(): MockAgent {
return {
+ cancelTurn: vi.fn().mockResolvedValue({ status: "no_active_turn" }),
deliver: vi.fn().mockResolvedValue(undefined),
getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),
run: vi.fn().mockResolvedValue({
diff --git a/packages/eve/src/protocol/routes.ts b/packages/eve/src/protocol/routes.ts
index 71c700acd..e2ea33a77 100644
--- a/packages/eve/src/protocol/routes.ts
+++ b/packages/eve/src/protocol/routes.ts
@@ -32,6 +32,13 @@ export const EVE_CONTINUE_SESSION_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/session/:
*/
export const EVE_MESSAGE_STREAM_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/session/:sessionId/stream`;
+/**
+ * Stable framework-owned route pattern for cancelling a session's
+ * in-flight turn. Accepts an optional `{ turnId }` body guard scoping
+ * the cancel to the turn the caller observed.
+ */
+export const EVE_CANCEL_TURN_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/session/:sessionId/cancel`;
+
/**
* Framework-owned route pattern for dispatching one authored schedule
* exactly once from the dev server.
@@ -110,6 +117,13 @@ export function createEveContinueSessionRoutePath(sessionId: string): string {
return `${EVE_ROUTE_PREFIX}/session/${encodeURIComponent(sessionId)}`;
}
+/**
+ * Creates the stable framework-owned cancel-turn route path for one session.
+ */
+export function createEveCancelTurnRoutePath(sessionId: string): string {
+ return `${EVE_ROUTE_PREFIX}/session/${encodeURIComponent(sessionId)}/cancel`;
+}
+
/**
* Creates the stable framework-owned connection callback route path for
* one (`name`, `token`) pair.
diff --git a/packages/eve/src/public/channels/eve.test.ts b/packages/eve/src/public/channels/eve.test.ts
index b1fc745fd..bf0e701ec 100644
--- a/packages/eve/src/public/channels/eve.test.ts
+++ b/packages/eve/src/public/channels/eve.test.ts
@@ -4,7 +4,8 @@ import { describe, expect, it, vi } from "vitest";
import { buildAdapterContext } from "#channel/adapter-context.js";
import { callAdapterEventHandler, type ChannelAdapter } from "#channel/adapter.js";
import { isCompiledChannel } from "#channel/compiled-channel.js";
-import { createJsonMessageRequest } from "#internal/testing/route-harness.js";
+import { createJsonMessageRequest, createMockAgent } from "#internal/testing/route-harness.js";
+import { attachRouteAgent } from "#internal/nitro/routes/channel-route-context.js";
import { type AuthFn, none } from "#public/channels/auth.js";
import { eveChannel, defaultEveAuth, type EveChannelInput } from "#public/channels/eve.js";
import type { SessionAuthContext } from "#channel/types.js";
@@ -119,6 +120,51 @@ function createEveContinueHandler(input: EveChannelInput) {
};
}
+/**
+ * Creates a POST handler test harness for the cancel-turn route
+ * (POST /eve/v1/session/:sessionId/cancel).
+ */
+function createEveCancelHandler(input: EveChannelInput) {
+ const channel = eveChannel(input);
+ const cancelRoute = channel.routes.find(
+ (r) => r.method === "POST" && r.path === "/eve/v1/session/:sessionId/cancel",
+ );
+ if (!cancelRoute) throw new Error("No cancel POST route found");
+
+ const agent = createMockAgent();
+ agent.cancelTurn.mockResolvedValue({ status: "cancelling" });
+
+ return {
+ cancelTurn: agent.cancelTurn,
+ async fetch(req: Request) {
+ const args = attachRouteAgent(
+ {
+ send: vi.fn(),
+ getSession: vi.fn(),
+ receive: vi.fn() as any,
+ params: { sessionId: "test-session-id" },
+ waitUntil: () => undefined,
+ requestIp: "127.0.0.1",
+ } satisfies RouteHandlerArgs,
+ agent,
+ );
+ return (cancelRoute as any).handler(req, args);
+ },
+ };
+}
+
+function cancelRequest(body?: unknown): Request {
+ return new Request("https://example.com/eve/v1/session/test-session-id/cancel", {
+ ...(body === undefined
+ ? {}
+ : {
+ body: typeof body === "string" ? body : JSON.stringify(body),
+ headers: { "content-type": "application/json" },
+ }),
+ method: "POST",
+ });
+}
+
/** Creates a GET handler test harness for the durable session stream route. */
function createEveStreamHandler(input: EveChannelInput) {
const channel = eveChannel(input);
@@ -1205,3 +1251,98 @@ describe("eveChannel — auth array shape", () => {
expect(options.auth).toEqual(ACCEPTED);
});
});
+
+describe("eveChannel — cancel turn", () => {
+ it("cancels the current turn with no body and reports 'cancelling'", async () => {
+ const handler = createEveCancelHandler({ auth: none() });
+
+ const response = await handler.fetch(cancelRequest());
+
+ expect(response.status).toBe(202);
+ expect(response.headers.get("cache-control")).toBe("no-store");
+ expect(response.headers.get("x-eve-session-id")).toBe("test-session-id");
+ await expect(response.json()).resolves.toEqual({
+ ok: true,
+ sessionId: "test-session-id",
+ status: "cancelling",
+ });
+ expect(handler.cancelTurn).toHaveBeenCalledTimes(1);
+ expect(handler.cancelTurn).toHaveBeenCalledWith({
+ sessionId: "test-session-id",
+ turnId: undefined,
+ });
+ });
+
+ it("accepts an empty JSON object body", async () => {
+ const handler = createEveCancelHandler({ auth: none() });
+
+ const response = await handler.fetch(cancelRequest({}));
+
+ expect(response.status).toBe(202);
+ expect(handler.cancelTurn).toHaveBeenCalledWith({
+ sessionId: "test-session-id",
+ turnId: undefined,
+ });
+ });
+
+ it("forwards the optional turnId guard", async () => {
+ const handler = createEveCancelHandler({ auth: none() });
+
+ const response = await handler.fetch(cancelRequest({ turnId: "turn_2" }));
+
+ expect(response.status).toBe(202);
+ expect(handler.cancelTurn).toHaveBeenCalledWith({
+ sessionId: "test-session-id",
+ turnId: "turn_2",
+ });
+ });
+
+ it("reports 'no_active_turn' as success when nothing is cancellable", async () => {
+ const handler = createEveCancelHandler({ auth: none() });
+ handler.cancelTurn.mockResolvedValue({ status: "no_active_turn" });
+
+ const response = await handler.fetch(cancelRequest());
+
+ expect(response.status).toBe(202);
+ await expect(response.json()).resolves.toEqual({
+ ok: true,
+ sessionId: "test-session-id",
+ status: "no_active_turn",
+ });
+ });
+
+ it("rejects unauthenticated requests before requesting cancellation", async () => {
+ const handler = createEveCancelHandler({ auth: [] });
+
+ const response = await handler.fetch(cancelRequest());
+
+ expect(response.status).toBe(401);
+ expect(handler.cancelTurn).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ["malformed JSON", "not-json"],
+ ["a non-object body", [1, 2]],
+ ["a non-string turnId", { turnId: 7 }],
+ ["an empty turnId", { turnId: "" }],
+ ])("rejects %s with 400", async (_description, body) => {
+ const handler = createEveCancelHandler({ auth: none() });
+ const response = await handler.fetch(cancelRequest(body));
+
+ expect(response.status).toBe(400);
+ expect(handler.cancelTurn).not.toHaveBeenCalled();
+ });
+
+ it("returns 500 when the cancellation request fails unexpectedly", async () => {
+ const handler = createEveCancelHandler({ auth: none() });
+ handler.cancelTurn.mockRejectedValue(new Error("backing store outage"));
+
+ const response = await handler.fetch(cancelRequest());
+
+ expect(response.status).toBe(500);
+ await expect(response.json()).resolves.toMatchObject({
+ error: "Failed to cancel the turn.",
+ ok: false,
+ });
+ });
+});
diff --git a/packages/eve/src/public/channels/eve.ts b/packages/eve/src/public/channels/eve.ts
index eda36829a..1b10125e9 100644
--- a/packages/eve/src/public/channels/eve.ts
+++ b/packages/eve/src/public/channels/eve.ts
@@ -1,10 +1,13 @@
import { type FilePart, type TextPart, type UserContent } from "ai";
-import type { SessionAuthContext, SessionCallback } from "#channel/types.js";
+import type { CancelTurnResult, SessionAuthContext, SessionCallback } from "#channel/types.js";
import { parseSessionCallback } from "#channel/session-callback.js";
import { hasInternalRefScheme } from "#internal/attachments/url-refs.js";
import { createLogger, logError } from "#internal/logging.js";
-import { readAgentInfoRouteResponse } from "#internal/nitro/routes/channel-route-context.js";
+import {
+ readAgentInfoRouteResponse,
+ readRouteAgent,
+} from "#internal/nitro/routes/channel-route-context.js";
import {
EVE_MESSAGE_STREAM_CONTENT_TYPE,
EVE_MESSAGE_STREAM_FORMAT,
@@ -13,7 +16,7 @@ import {
EVE_STREAM_FORMAT_HEADER,
EVE_STREAM_VERSION_HEADER,
} from "#protocol/message.js";
-import { EVE_INFO_ROUTE_PATH } from "#protocol/routes.js";
+import { EVE_CANCEL_TURN_ROUTE_PATTERN, EVE_INFO_ROUTE_PATH } from "#protocol/routes.js";
import { type InputResponse, isInputResponse } from "#runtime/input/types.js";
import { type AuthFn, routeAuth } from "#public/channels/auth.js";
import {
@@ -154,7 +157,8 @@ export interface EveChannel extends Channel {}
/**
* Builds the default eve HTTP channel: a {@link defineChannel} instance serving the
* built-in `/eve/v1` routes (GET inspects the agent, POST creates a session, POST
- * delivers a follow-up, GET streams a session's NDJSON event feed). Every route
+ * delivers a follow-up, POST cancels the in-flight turn, GET streams a session's
+ * NDJSON event feed). Every route
* runs {@link EveChannelInput.auth} via {@link routeAuth} before dispatching.
* Default-export the result as your `agent/channels/eve.ts` channel; reach for
* {@link defineChannel} directly only for a custom transport.
@@ -314,6 +318,45 @@ export function eveChannel(input: EveChannelInput): EveChannel {
);
}),
+ POST(EVE_CANCEL_TURN_ROUTE_PATTERN, async (req, args) => {
+ const authResult = await routeAuth(req, input.auth);
+ if (authResult instanceof Response) return authResult;
+
+ const sessionId = args.params.sessionId;
+ if (!sessionId) {
+ return Response.json({ error: "Missing session id.", ok: false }, { status: 400 });
+ }
+
+ const body = await parseCancelTurnBody(req);
+ if (body instanceof Response) return body;
+
+ let result: CancelTurnResult;
+ try {
+ const agent = readRouteAgent(args);
+ if (agent === undefined) {
+ throw new Error("Missing route agent.");
+ }
+ result = await agent.cancelTurn({ sessionId, turnId: body.turnId });
+ } catch (error) {
+ const errorId = logError(log, "cancel-turn request failed", error, { sessionId });
+ return Response.json(
+ { error: "Failed to cancel the turn.", errorId, ok: false },
+ { status: 500 },
+ );
+ }
+
+ return Response.json(
+ { ok: true, sessionId, status: result.status },
+ {
+ headers: {
+ "cache-control": "no-store",
+ [EVE_SESSION_ID_HEADER]: sessionId,
+ },
+ status: 202,
+ },
+ );
+ }),
+
GET("/eve/v1/session/:sessionId/stream", async (req, { getSession, params }) => {
const authResult = await routeAuth(req, input.auth);
if (authResult instanceof Response) return authResult;
@@ -547,6 +590,44 @@ function parseContinueBody(payload: Record<string, unknown>): ParsedContinueBody
return { message, continuationToken, inputResponses, context, outputSchema };
}
+interface ParsedCancelTurnBody {
+ turnId?: string;
+}
+
+async function parseCancelTurnBody(req: Request): Promise<ParsedCancelTurnBody | Response> {
+ let text: string;
+ try {
+ text = await req.text();
+ } catch {
+ return Response.json({ error: "Unreadable request body.", ok: false }, { status: 400 });
+ }
+ if (text.trim().length === 0) {
+ return {};
+ }
+
+ let payload: unknown;
+ try {
+ payload = JSON.parse(text);
+ } catch {
+ return Response.json({ error: "Invalid JSON body.", ok: false }, { status: 400 });
+ }
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
+ return Response.json({ error: "Expected a JSON object.", ok: false }, { status: 400 });
+ }
+
+ const turnId = (payload as { turnId?: unknown }).turnId;
+ if (turnId === undefined) {
+ return {};
+ }
+ if (typeof turnId !== "string" || turnId.length === 0) {
+ return Response.json(
+ { error: "Expected 'turnId' to be a non-empty string.", ok: false },
+ { status: 400 },
+ );
+ }
+ return { turnId };
+}
+
function createSendPayload(
body: ParsedCreateBody,
context = body.context,
diff --git a/packages/eve/src/public/definitions/channel.ts b/packages/eve/src/public/definitions/channel.ts
index 6013ccf8e..a25d530c1 100644
--- a/packages/eve/src/public/definitions/channel.ts
+++ b/packages/eve/src/public/definitions/channel.ts
@@ -7,6 +7,8 @@ import type { TypedReceiveTarget } from "#channel/receive-target.js";
import type { RouteDefinition, SendFn } from "#channel/routes.js";
import type { Session, SessionHandle } from "#channel/session.js";
import type {
+ CancelTurnInput,
+ CancelTurnResult,
DeliverInput,
DeliverPayload,
GetEventStreamOptions,
@@ -20,7 +22,7 @@ import type { GenericChannelDefinition, GenericReceiveInput } from "#shared/chan
declare const CHANNEL_METADATA_TYPE: unique symbol;
-export type { GetEventStreamOptions } from "#channel/types.js";
+export type { CancelTurnInput, CancelTurnResult, GetEventStreamOptions } from "#channel/types.js";
export type { Session, SessionHandle } from "#channel/session.js";
export type { ChannelCors, ChannelCorsOptions } from "#channel/cors.js";
export { GET, POST, PUT, PATCH, DELETE, WS } from "#channel/routes.js";
@@ -61,17 +63,16 @@ export type ChannelRouteMethod = ChannelMethod | "WEBSOCKET";
* framework constructs this per request and passes it as the second
* argument.
*
- * Routes call into the agent to start new sessions (`agent.run`),
- * deliver follow-up messages to existing sessions (`agent.deliver`), or
- * read events from a previously-started session (`agent.getEventStream`).
+ * Routes call into the agent to start sessions, deliver follow-ups,
+ * cancel turns, and read events.
*/
export interface RouteContext {
/**
* Handle to the agent that this route sends inbound requests to.
* Conceptually the runtime + harness combined: routes call `run`,
- * `deliver`, and `getEventStream` to drive sessions of this agent
- * without knowing about the workflow runtime, the harness, or any
- * other execution-layer detail.
+ * `deliver`, `cancelTurn`, and `getEventStream` to drive sessions of
+ * this agent without knowing about the workflow runtime, the harness,
+ * or any other execution-layer detail.
*
* Every route speaks the same `RunInput` shape regardless of which
* webhook it serves — `agent` is platform-agnostic.
@@ -109,8 +110,9 @@ export interface RouteContext {
*
* `Agent` is conceptually the workflow runtime plus the tool-loop harness:
* routes call `run` to start a new session of the agent, `deliver` to
- * send a follow-up to a parked session, and `getEventStream` to read events
- * from a previously-started session. The framework's internal `Runtime`
+ * send a follow-up to a parked session, `cancelTurn` to stop in-flight work,
+ * and `getEventStream` to read events from a previously-started session.
+ * The framework's internal `Runtime`
* interface (in `channel/types.ts`) is the underlying primitive — `Agent`
* is the *public* shape exposed on `RouteContext` so route authors
* speak in terms of the agent rather than the runtime.
@@ -122,6 +124,16 @@ export interface Agent {
* with the same token resume the same session.
*/
run(input: RunInput): Promise<RunHandle>;
+ /**
+ * 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
+ * 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.
+ */
+ cancelTurn(input: CancelTurnInput): Promise<CancelTurnResult>;
/**
* Sends a follow-up message to a session that is currently parked waiting
* for input. Throws if no parked session exists for the supplied
diff --git a/packages/eve/src/runtime/session-callback-route.test.ts b/packages/eve/src/runtime/session-callback-route.test.ts
index c3a61b270..8c4ac568e 100644
--- a/packages/eve/src/runtime/session-callback-route.test.ts
+++ b/packages/eve/src/runtime/session-callback-route.test.ts
@@ -177,6 +177,9 @@ describe("session callback route", () => {
function createRouteContext(params: Record<string, string>): RouteContext {
return {
agent: {
+ async cancelTurn() {
+ throw new Error("unexpected cancelTurn");
+ },
async deliver() {
throw new Error("unexpected deliver");
},
diff --git a/packages/eve/test/scenarios/cross-channel-receive.scenario.test.ts b/packages/eve/test/scenarios/cross-channel-receive.scenario.test.ts
index 71c049cb3..51f61737c 100644
--- a/packages/eve/test/scenarios/cross-channel-receive.scenario.test.ts
+++ b/packages/eve/test/scenarios/cross-channel-receive.scenario.test.ts
@@ -79,6 +79,9 @@ interface CapturedRun {
function createCapturingRuntime(captured: CapturedRun[]): Runtime {
return {
+ async cancelTurn() {
+ throw new Error("cancelTurn should not be called in this scenario");
+ },
async run(input) {
captured.push({
adapter: input.adapter,
diff --git a/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts b/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts
index b6e3d3d97..6fbebb217 100644
--- a/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts
+++ b/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts
@@ -57,6 +57,9 @@ interface CapturedRun {
function createCapturingRuntime(captured: CapturedRun[]): Runtime {
return {
+ async cancelTurn() {
+ throw new Error("cancelTurn should not be called in this scenario");
+ },
async run(input) {
captured.push({
adapter: input.adapter,
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index bd91bec2b..7aa8313f4 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -593,6 +593,31 @@ importers:
specifier: 'catalog:'
version: 7.0.2
+ e2e/fixtures/agent-cancellation:
+ dependencies:
+ '@opentelemetry/core':
+ specifier: 2.6.1
+ version: 2.6.1(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace-base':
+ specifier: 2.6.1
+ version: 2.6.1(@opentelemetry/[email protected])
+ '@vercel/otel':
+ specifier: 2.1.2
+ version: 2.1.2(@opentelemetry/[email protected])(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))
+ eve:
+ specifier: workspace:*
+ version: link:../../../packages/eve
+ zod:
+ specifier: 'catalog:'
+ version: 4.4.3
+ devDependencies:
+ '@types/node':
+ specifier: 'catalog:'
+ version: 25.9.1
+ typescript:
+ specifier: 'catalog:'
+ version: 7.0.2
+
e2e/fixtures/agent-channels:
dependencies:
'@opentelemetry/core':
@@ -705,15 +730,6 @@ importers:
specifier: 'catalog:'
version: 7.0.2
- e2e/fixtures/compaction-regression-shared:
- dependencies:
- eve:
- specifier: workspace:*
- version: link:../../../packages/eve
- zod:
- specifier: 'catalog:'
- version: 4.4.3
-
e2e/fixtures/agent-model:
dependencies:
eve:
@@ -1012,6 +1028,15 @@ importers:
specifier: 'catalog:'
version: 7.0.2
+ e2e/fixtures/compaction-regression-shared:
+ dependencies:
+ eve:
+ specifier: workspace:*
+ version: link:../../../packages/eve
+ zod:
+ specifier: 'catalog:'
+ version: 4.4.3
+
e2e/fixtures/extensions:
dependencies:
eve:
diff --git a/research/turn-cancellation-channel-ops.md b/research/turn-cancellation-channel-ops.md
new file mode 100644
index 000000000..4b5fc7d1b
--- /dev/null
+++ b/research/turn-cancellation-channel-ops.md
@@ -0,0 +1,175 @@
+---
+issue: https://github.com/vercel/eve/issues/483
+status: proposed
+last_updated: "2026-07-15"
+---
+
+# Turn cancellation for custom channels
+
+## Summary
+
+Chat-style webhooks often receive several short messages while an agent is
+still responding. Plain `send()` queues those messages, so the agent can emit
+an obsolete answer before it processes the newer context. Custom channels need
+two operations:
+
+- `send(payload, { supersede: "turn" })` queues the payload and cancels only
+ the turn that was already active;
+- `cancelTurn({ continuationToken, turnId? })` supports explicit stop commands.
+
+The layer-2 runtime operation cancels by session id. Channel operations also
+need a race-safe continuation-token lookup and delivery primitive. They cannot
+be composed safely from today's independent hook resumes.
+
+## Authoring API
+
+```ts
+export interface SendOptions<TState> {
+ // Existing fields omitted.
+ supersede?: "turn";
+}
+
+export interface RouteHandlerArgs<TState> {
+ // Existing fields omitted.
+ cancelTurn(options: { continuationToken: string; turnId?: string }): Promise<CancelTurnResult>;
+}
+
+export interface CancelTurnResult {
+ status: "cancelling" | "no_active_turn";
+}
+```
+
+`"cancelling"` 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.
+
+The one-member `supersede` union leaves room for a future
+`supersede: "session"` reset operation without defining its semantics here.
+
+## Example
+
+```ts
+export default defineChannel({
+ routes: [
+ POST("/webhooks/imessage", async (req, { send, waitUntil }) => {
+ const inbound = await verifyAndParse(req);
+ if (inbound instanceof Response) return inbound;
+
+ waitUntil(
+ send(
+ { message: inbound.text },
+ {
+ auth: null,
+ continuationToken: inbound.conversationId,
+ supersede: "turn",
+ },
+ ),
+ );
+ return new Response(null, { status: 200 });
+ }),
+ ],
+ events: {
+ "message.completed": async (data, channel) => {
+ if (data.finishReason !== "tool-calls" && data.message) {
+ await channel.imessage.sendText(data.message);
+ }
+ },
+ },
+});
+```
+
+Filtering `finishReason: "tool-calls"` avoids sending pre-tool narration as a
+final reply. Cancellation does not retract outbound side effects: if a handler
+has already sent content, eve cannot take it back. A channel that requires a
+strict no-superseded-output guarantee must buffer output until it observes the
+turn's terminal event.
+
+## Required semantics
+
+### A superseding send must not cancel itself
+
+The payload must be durably attached to the existing session before the
+operation reports success. Cancellation must target the turn observed before
+that delivery, using its `turnId`. If the session advances before cancellation
+commits, the guard turns the cancellation into a no-op instead of cancelling
+the turn that contains the new payload.
+
+### Rekeying must not create a second session
+
+`ctx.session.setContinuationToken()` can replace the delivery hook while a
+webhook is in flight. Once the supersede operation resolves a continuation
+token to an existing session, a concurrent rekey must not make delivery fall
+through to `runtime.run()` and start a new history. The operation must either
+deliver to the resolved session or return an explicit retryable conflict.
+
+### Concurrent superseding sends must compose
+
+Every accepted payload is delivered exactly once. Several sends may cancel the
+same observed turn, and their payloads may be coalesced into the next turn in
+the order defined by the existing delivery queue. No request may silently
+retarget a newer turn.
+
+### Existing cancellation limits remain
+
+Task-mode and hook-conflict-degraded turns may have no current cancellation
+hook. Superseding delivery still succeeds in that case and behaves like plain
+queueing. Partial model output remains on the event stream, while durable model
+history keeps only content that had already settled. Already-executed tool or
+channel side effects remain; cancellation is not rollback.
+
+## Runtime boundary
+
+Neither simple ordering is sufficient:
+
+- cancel then deliver leaves a gap where the channel token can rekey; the old
+ delivery can miss and incorrectly start a fresh session;
+- deliver then unguarded cancel can stop the new turn that already includes the
+ payload.
+
+The implementation therefore needs one runtime-owned composite operation:
+
+```text
+channel send
+ │
+ ▼
+resolve token ──► existing session + observed active turn
+ │
+ ├─ durably deliver payload to that session
+ └─ cancel only the observed turn id
+ │
+ └─ session advanced? guard mismatch, benign no-op
+```
+
+The exact World implementation may be transactional or use a stable
+session-addressed inbox, but the observable invariants above are required.
+`Runtime.cancelTurn({ sessionId, turnId? })` remains the primitive for explicit
+session-id cancellation; channel token resolution belongs above it.
+
+## Testing
+
+- Unit-test result mapping and continuation-token namespacing.
+- Prove delivery commits before the guarded cancellation is issued.
+- Race `setContinuationToken()` against superseding delivery and assert the
+ payload stays on the original session with no fallback run.
+- Race turn settlement against superseding delivery and assert a newer turn is
+ never cancelled.
+- Exercise concurrent superseding sends and verify exactly-once delivery and
+ deterministic coalescing.
+- Cover idle, parked HITL, task-mode, stale `turnId`, and degraded turns.
+- Add an e2e custom-channel fixture that supersedes a hanging turn and answers
+ the complete coalesced input once.
+
+## Out of scope
+
+- Session reset, `/new`, and `supersede: "session"`.
+- Descendant cancellation cascade.
+- Cancellation from in-band event handlers.
+- Built-in channel debounce policy.
+- Retraction of already-sent channel messages or completed tool side effects.
+
+## Delivery
+
+Land the runtime composite and its race tests before exposing either public
+channel API. The public additions require a patch changeset and channel
+authoring documentation.
diff --git a/research/turn-cancellation-trigger-surface.md b/research/turn-cancellation-trigger-surface.md
new file mode 100644
index 000000000..424a5ca75
--- /dev/null
+++ b/research/turn-cancellation-trigger-surface.md
@@ -0,0 +1,94 @@
+---
+issue: https://github.com/vercel/eve/issues/483
+status: in-review
+last_updated: "2026-07-15"
+---
+
+# Turn cancellation, layer 2: HTTP trigger
+
+## Summary
+
+Layer 1 (#573) made each parkable turn claim a stable
+`{sessionId}:cancel` hook and settle cancellation as `turn.cancelled` followed
+by `session.waiting`. Layer 2 exposes that behavior through
+`POST /eve/v1/session/:sessionId/cancel` on `eveChannel()` and adds hosted e2e
+coverage.
+
+The route delegates to `Agent.cancelTurn({ sessionId, turnId? })`; hook
+addressing and workflow error normalization stay behind `Runtime`. No new
+durable state, events, or workflow behavior is introduced.
+
+## HTTP contract
+
+- Auth uses the channel's existing `routeAuth` policy.
+- The optional body is `{ "turnId"?: string }`. An empty body targets whichever
+ turn owns the hook. A `turnId` limits the request to the observed turn; a
+ mismatch is consumed as a no-op.
+- Responses include `cache-control: no-store` and `EVE_SESSION_ID_HEADER`.
+
+| 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: "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. |
+| 500 | `{ ok: false, error, errorId }` | An unexpected runtime failure occurred. |
+
+Both 202 outcomes are successful so clients can safely retry or issue a late
+stop request. Task-mode sessions have no turn cancellation hook and therefore
+return `no_active_turn`.
+
+## Semantics
+
+- `"cancelling"` 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
+ 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
+ turn.
+- Missing hooks, missing owner runs, terminal-run expiry, and terminal-state
+ conflicts map to `"no_active_turn"`; other errors become 500s.
+- Cancellation leaves partial content on the event stream and retains completed
+ side effects; durable model history keeps only content that had already
+ settled. It emits no failure event and leaves the session ready for a
+ follow-up.
+
+## Data flow
+
+```text
+POST /eve/v1/session/:sessionId/cancel { turnId? }
+ │
+ ├─ routeAuth
+ ├─ parse body
+ └─ agent.cancelTurn
+ │
+ └─ runtime.cancelTurn
+ └─ resumeHook(`${sessionId}:cancel`, { turnId? })
+ ├─ missing / terminal target → no_active_turn
+ └─ accepted payload → cancelling
+```
+
+The token helper lives in `execution/turn-cancellation-token.ts`; the HTTP
+route does not import workflow hook APIs.
+
+## Coverage
+
+- Unit tests cover parsing, auth, Agent delegation, result mapping, headers,
+ terminal races, and unexpected errors.
+- World-local integration cancels a hanging tool through the real route,
+ verifies stale guards are no-ops, treats unknown and late requests as
+ `no_active_turn`, and proves the next turn succeeds.
+- The `agent-cancellation` e2e fixture waits for `actions.requested`, cancels
+ over HTTP, checks `turn.cancelled` → `session.waiting`, then sends a follow-up.
+ Its stream open retries the same short propagation window as the client.
+
+## Out of scope
+
+Task-mode terminal cancellation, caller-supplied reasons, descendant cascade,
+session reset, and client/channel convenience APIs remain separate work.
+
+## Delivery
+
+Ship the route, Runtime/Agent operation, docs, tests, e2e fixture, and patch
+changeset together.