The Open Framework for Building Agents
feat(eve): add channel cancellation api (#870)
Andrew Barbab97f1d1e53dd
diff --git a/.changeset/channel-turn-cancellation-helpers.md b/.changeset/channel-turn-cancellation-helpers.mdnew file mode 100644index 000000000..245d9fd51--- /dev/null+++ b/.changeset/channel-turn-cancellation-helpers.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Custom channel routes can now cancel a session's in-flight turn: route handlers receive a `cancel({ continuationToken, turnId? })` helper addressed by the channel-local continuation token, and `Session` handles returned by `send()` and `getSession()` expose `cancel({ turnId? })` for session-id-addressed cancellation. `ClientSession.cancel()` accepts the same optional `turnId` stale-request guard.diff --git a/docs/channels/custom.mdx b/docs/channels/custom.mdxindex d31632140..c3e6bbfec 100644--- a/docs/channels/custom.mdx+++ b/docs/channels/custom.mdx@@ -47,7 +47,8 @@ export default defineChannel({Declare routes with the `POST()` and `GET()` helpers. Each route handler receives the raw `Request` and a helpers object:- `send(message, { auth, continuationToken, state?, title? })` starts or resumes a session. `title` overrides the new workflow session's display title without changing the model message. Returns a `Session`.-- `getSession(sessionId)` looks up an existing session. The returned `Session` exposes `getEventStream({ startIndex? })` for streaming.+- `cancel({ continuationToken, turnId? })` requests cancellation of the active turn on the session that owns the token. See [Cancel a turn](#cancel-a-turn).+- `getSession(sessionId)` looks up an existing session. The returned `Session` exposes `getEventStream({ startIndex? })` for streaming and `cancel({ turnId? })` for session-id-addressed cancellation.- `receive(channel, ...)` hands inbound work to a different channel for cross-channel hand-off.- `params` holds route parameters extracted from the path pattern.- `waitUntil(promise)` extends the request lifetime for background work.@@ -55,6 +56,35 @@ Declare routes with the `POST()` and `GET()` helpers. Each route handler receiveEvent handlers like `"message.completed"` are declared under the `events` key. They receive `(eventData, channel, ctx)`, where `eventData` is the event payload, `channel` carries platform handles and session continuation operations, and `ctx` is the eve `SessionContext`. Every channel kind shares this signature. The one exception is `session.failed`, which receives only `(eventData, channel)` with no `ctx`.+## Cancel a turn++A stop route cancels a session's in-flight turn with the `cancel` helper, addressed by the same channel-local continuation token used with `send()`:++```ts+import { defineChannel, POST } from "eve/channels";++export default defineChannel({+ routes: [+ POST("/threads/:threadId/stop", async (_req, { cancel, params }) => {+ const result = await cancel({ continuationToken: params.threadId });+ return Response.json(result);+ }),+ ],+});+```++Both result statuses are successful. `"accepted"` means the cancellation request was consumed, not that the observed turn will cancel; confirmation is `turn.cancelled` followed by `session.waiting` on the event stream. `"no_active_turn"` covers an unknown token and a session with nothing to cancel — idle, parked, or already completed.++Semantics:++- `cancel` never starts a session, sends input, or clears history. The session parks and accepts the next message normally.+- Pass `turnId` (stamped on every turn-scoped stream event) to guard against stale stop requests. A mismatched guard is consumed as a benign no-op and cannot cancel a newer turn.+- The helper addresses only this channel's sessions; it cannot cancel a session owned by another channel.+- Cancellation stops work without replacement input. Partial streamed output and completed side effects remain observable, and active local or remote subagents receive cancellation recursively.+- The route owns authentication of the inbound stop request, exactly as for `send()`.++When you already hold a `Session` — returned by `send()` or `getSession(sessionId)` — call `session.cancel({ turnId? })` to request the same cancellation addressed by session id.+## CORSCustom HTTP channels leave CORS untouched unless you opt in. Pass `cors: true`@@ -95,7 +125,7 @@ export default defineChannel({});```-`WS()` handlers receive the same helpers as HTTP route handlers: `send`, `getSession`, `receive`, `params`, `waitUntil`, and `requestIp`. The returned hooks are eve-owned structural types compatible with Nitro/H3 websocket routing, including `upgrade`, `open`, `message`, `close`, and `error`.+`WS()` handlers receive the same helpers as HTTP route handlers: `send`, `cancel`, `getSession`, `receive`, `params`, `waitUntil`, and `requestIp`. The returned hooks are eve-owned structural types compatible with Nitro/H3 websocket routing, including `upgrade`, `open`, `message`, `close`, and `error`.### Node upgrade server escape hatchdiff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.mdindex b2ba304f3..0f92b2472 100644--- a/docs/concepts/sessions-runs-and-streaming.md+++ b/docs/concepts/sessions-runs-and-streaming.md@@ -100,6 +100,8 @@ curl -X POST http://127.0.0.1:3000/eve/v1/session/<sessionId>/cancel`"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.+Custom channel routes request the same cancellation without knowing the session id: the `cancel` route helper is addressed by the channel-local continuation token, and `Session.cancel()` by session id. See [custom channels](../channels/custom#cancel-a-turn).+## Reconnect and rewindThe 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/e2e/fixtures/agent-cancellation/agent/channels/threads.ts b/e2e/fixtures/agent-cancellation/agent/channels/threads.tsnew file mode 100644index 000000000..1ca673924--- /dev/null+++ b/e2e/fixtures/agent-cancellation/agent/channels/threads.ts@@ -0,0 +1,32 @@+import { defineChannel, POST } from "eve/channels";++const AUTH = {+ attributes: { source: "cancellation-eval" },+ authenticator: "threads",+ principalId: "cancellation-eval",+ principalType: "service",+} as const;++/**+ * Chat-style channel for the continuation-addressed cancellation eval.+ *+ * Messages address a thread by channel-local continuation token. The stop+ * route cancels the thread's active turn through the public `cancel` route+ * helper without knowing the runtime session id.+ */+export default defineChannel({+ routes: [+ POST("/threads/:threadId/messages", async (request, { params, send }) => {+ const body = (await request.json().catch(() => ({}))) as { message?: string };+ const session = await send(body.message ?? "", {+ auth: AUTH,+ continuationToken: params.threadId ?? "",+ });+ return Response.json({ ok: true, sessionId: session.id });+ }),+ POST("/threads/:threadId/stop", async (_request, { params, cancel }) => {+ const result = await cancel({ continuationToken: params.threadId ?? "" });+ return Response.json(result);+ }),+ ],+});diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-channel-route.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-channel-route.eval.tsnew file mode 100644index 000000000..5844b629f--- /dev/null+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-channel-route.eval.ts@@ -0,0 +1,115 @@+import { defineEval, type EveEvalTargetHandle } from "eve/evals";+import { satisfies } from "eve/evals/expect";++const TOOL_NAME = "wait-for-cancellation";++interface MessageResponse {+ readonly ok: boolean;+ readonly sessionId?: string;+}++interface StopResponse {+ readonly status?: "accepted" | "no_active_turn";+}++async function postJson<T>(target: EveEvalTargetHandle, path: string, body: unknown): Promise<T> {+ const response = await target.fetch(path, {+ body: JSON.stringify(body),+ headers: { "content-type": "application/json" },+ method: "POST",+ });+ const text = await response.text();+ if (!response.ok) {+ throw new Error(`POST ${path} failed (${response.status}): ${text}`);+ }+ return JSON.parse(text) as T;+}++/**+ * Cancel an in-flight turn from a custom channel stop route.+ *+ * Flow: start a thread that hangs mid-tool, stop it through the channel's+ * continuation-addressed `cancel` helper, and assert the turn settles as+ * `turn.cancelled` followed by `session.waiting` with zero failure events.+ * Then prove the same thread resumes the same session normally and that an+ * unknown thread reports the benign `no_active_turn` outcome.+ */+export default defineEval({+ description: "Cancel an in-flight turn from a custom channel stop route.",+ timeoutMs: 240_000,++ async test(t) {+ const threadId = crypto.randomUUID();++ const unknownThread = await postJson<StopResponse>(+ t.target,+ `/threads/${crypto.randomUUID()}/stop`,+ {},+ );+ await t.require(+ unknownThread,+ satisfies(+ (value: StopResponse) => value.status === "no_active_turn",+ "stopping an unknown thread reports no_active_turn",+ ),+ );++ const started = await postJson<MessageResponse>(t.target, `/threads/${threadId}/messages`, {+ message: "Please wait for cancellation.",+ });+ await t.require(+ started,+ satisfies(+ (value: MessageResponse) => value.ok === true && typeof value.sessionId === "string",+ "the message route returns a session id",+ ),+ );+ const sessionId = started.sessionId!;++ const live = t.target.watchTurn(sessionId);+ await live.waitForEvent("actions.requested", {+ data: {+ actions: (actions) =>+ actions.some((action) => action.kind === "tool-call" && action.toolName === TOOL_NAME),+ },+ });+ t.log(`Tool call observed mid-turn; stopping thread ${threadId}.`);++ const stopped = await postJson<StopResponse>(t.target, `/threads/${threadId}/stop`, {});+ await t.require(+ stopped,+ satisfies(+ (value: StopResponse) => value.status === "accepted",+ "the stop request is accepted",+ ),+ );++ 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");++ const resumed = await postJson<MessageResponse>(t.target, `/threads/${threadId}/messages`, {+ message: "Reply with exactly CHANNEL-CANCEL-FOLLOW-UP-OK.",+ });+ await t.require(+ resumed,+ satisfies(+ (value: MessageResponse) => value.sessionId === sessionId,+ "the thread resumes the same session",+ ),+ );++ const followUp = await t.target+ .watchTurn(sessionId, { startIndex: cancelledTurn.events.length })+ .result();+ followUp.notEvent("turn.cancelled");+ followUp.notEvent("turn.failed");+ followUp.notEvent("session.failed");+ followUp.messageIncludes(/CHANNEL-CANCEL-FOLLOW-UP-OK/i);++ t.succeeded();+ },+});diff --git a/packages/eve/src/channel/cancel.test.ts b/packages/eve/src/channel/cancel.test.tsnew file mode 100644index 000000000..ece8ff54c--- /dev/null+++ b/packages/eve/src/channel/cancel.test.ts@@ -0,0 +1,70 @@+import { describe, expect, it, vi } from "vitest";++import { createCancelFn } from "#channel/cancel.js";+import type { Runtime } from "#channel/types.js";++function createRuntime(overrides?: Partial<Runtime>): Runtime {+ return {+ cancelTurn: vi.fn().mockResolvedValue({ status: "accepted" }),+ deliver: vi.fn(),+ getEventStream: vi.fn(),+ resolveSession: vi.fn().mockResolvedValue({ sessionId: "sess_1" }),+ run: vi.fn(),+ ...overrides,+ };+}++describe("createCancelFn", () => {+ it("namespaces the channel-local token before resolving the session", async () => {+ const runtime = createRuntime();++ const cancel = createCancelFn(runtime, "slack");+ await cancel({ continuationToken: "C1:T1" });++ expect(runtime.resolveSession).toHaveBeenCalledWith("slack:C1:T1");+ });++ it("cancels the resolved session and forwards the turn guard", async () => {+ const runtime = createRuntime();++ const cancel = createCancelFn(runtime, "slack");+ const result = await cancel({ continuationToken: "C1:T1", turnId: "turn_3" });++ expect(result).toEqual({ status: "accepted" });+ expect(runtime.cancelTurn).toHaveBeenCalledWith({ sessionId: "sess_1", turnId: "turn_3" });+ });++ it("returns 'no_active_turn' for a token no session owns", async () => {+ const runtime = createRuntime({ resolveSession: vi.fn().mockResolvedValue(undefined) });++ const cancel = createCancelFn(runtime, "slack");+ const result = await cancel({ continuationToken: "unknown" });++ expect(result).toEqual({ status: "no_active_turn" });+ expect(runtime.cancelTurn).not.toHaveBeenCalled();+ });++ it("passes through the runtime's cancellation status", async () => {+ const runtime = createRuntime({+ cancelTurn: vi.fn().mockResolvedValue({ status: "no_active_turn" }),+ });++ const cancel = createCancelFn(runtime, "slack");++ await expect(cancel({ continuationToken: "C1:T1" })).resolves.toEqual({+ status: "no_active_turn",+ });+ });++ it("propagates unexpected resolution failures and never starts a session", async () => {+ const failure = new Error("transient backing-store outage");+ const runtime = createRuntime({ resolveSession: vi.fn().mockRejectedValue(failure) });++ const cancel = createCancelFn(runtime, "slack");++ await expect(cancel({ continuationToken: "C1:T1" })).rejects.toBe(failure);+ expect(runtime.cancelTurn).not.toHaveBeenCalled();+ expect(runtime.run).not.toHaveBeenCalled();+ expect(runtime.deliver).not.toHaveBeenCalled();+ });+});diff --git a/packages/eve/src/channel/cancel.ts b/packages/eve/src/channel/cancel.tsnew file mode 100644index 000000000..70a381f13--- /dev/null+++ b/packages/eve/src/channel/cancel.ts@@ -0,0 +1,20 @@+import type { CancelFn, CancelOptions } from "#channel/routes.js";+import type { CancelTurnResult, Runtime } from "#channel/types.js";++/**+ * Builds the route-handler `cancel` helper for one channel. Resolves the+ * channel-local continuation token to its owning session without delivering+ * input, then delegates to the runtime's session-id-addressed cancellation.+ */+export function createCancelFn(runtime: Runtime, channelName: string): CancelFn {+ return async (options: CancelOptions): Promise<CancelTurnResult> => {+ const continuationToken = `${channelName}:${options.continuationToken}`;+ const owner = await runtime.resolveSession(continuationToken);++ if (owner === undefined) {+ return { status: "no_active_turn" };+ }++ return await runtime.cancelTurn({ sessionId: owner.sessionId, turnId: options.turnId });+ };+}diff --git a/packages/eve/src/channel/cross-channel-receive.test.ts b/packages/eve/src/channel/cross-channel-receive.test.tsindex 302ddc14a..fad69c062 100644--- a/packages/eve/src/channel/cross-channel-receive.test.ts+++ b/packages/eve/src/channel/cross-channel-receive.test.ts@@ -13,6 +13,7 @@ function makeRuntime(): Runtime {cancelTurn: vi.fn(),deliver: vi.fn(),getEventStream: vi.fn(),+ resolveSession: vi.fn(),run: vi.fn(),};}@@ -21,6 +22,9 @@ function makeSession(): Session {return {id: "sess_1",continuationToken: "tok",+ async cancel() {+ return { status: "no_active_turn" };+ },async getEventStream() {return new ReadableStream();},diff --git a/packages/eve/src/channel/routes.ts b/packages/eve/src/channel/routes.tsindex f6c685c08..82ac43772 100644--- a/packages/eve/src/channel/routes.ts+++ b/packages/eve/src/channel/routes.ts@@ -1,7 +1,7 @@import type { UserContent } from "ai";import type { CrossChannelReceiveFn } from "#channel/cross-channel-receive.js";-import type { SessionAuthContext, SessionCallback } from "#channel/types.js";+import type { CancelTurnResult, SessionAuthContext, SessionCallback } from "#channel/types.js";import type { InputResponse } from "#runtime/input/types.js";import type { Session } from "#channel/session.js";import type { RunMode } from "#shared/run-mode.js";@@ -12,13 +12,15 @@ type WebSocketHeaders = Headers | readonly (readonly [string, string])[] | Recor/*** Second argument passed to every route handler. `send` starts or continues a- * session on this channel; `getSession` looks one up by id; `receive` hands- * inbound work to a different channel; `params` contains the matched path- * parameters; `waitUntil` keeps background work alive past the response;+ * session on this channel; `cancel` stops the active turn on a session+ * addressed by continuation token; `getSession` looks one up by id; `receive`+ * hands inbound work to a different channel; `params` contains the matched+ * path parameters; `waitUntil` keeps background work alive past the response;* `requestIp` is the client IP, or `null` when the host cannot provide it.*/export interface RouteHandlerArgs<TState = undefined> {send: SendFn<TState>;+ cancel: CancelFn;getSession: GetSessionFn;/*** Starts a session on a different channel to hand off inbound work (e.g. an@@ -90,6 +92,27 @@ export type SendOptions<TState = undefined> = [TState] extends [undefined]*/export type GetSessionFn = (sessionId: string) => Session;+/**+ * Options for {@link CancelFn}. `continuationToken` is the channel-local raw+ * token, exactly as passed to {@link SendFn}. `turnId` limits the request to+ * the turn the caller observed; a stale guard is consumed as a benign no-op.+ */+export interface CancelOptions {+ readonly continuationToken: string;+ readonly turnId?: string;+}++/**+ * Requests cancellation of the active turn on the session that owns the+ * continuation token. Never starts a session, sends input, or clears history.+ *+ * Both statuses are successful: `"accepted"` means the request was consumed,+ * and `"no_active_turn"` covers an unknown token and a session with nothing+ * to cancel. Confirmation is `turn.cancelled` followed by `session.waiting`+ * on the event stream.+ */+export type CancelFn = (options: CancelOptions) => Promise<CancelTurnResult>;+export type RouteHandler<TState = undefined> = (req: Request,args: RouteHandlerArgs<TState>,diff --git a/packages/eve/src/channel/schedule.test.ts b/packages/eve/src/channel/schedule.test.tsindex b85260134..29021d212 100644--- a/packages/eve/src/channel/schedule.test.ts+++ b/packages/eve/src/channel/schedule.test.ts@@ -25,6 +25,7 @@ function createMockRuntime(): Runtime {return {cancelTurn: vi.fn(),deliver: vi.fn().mockRejectedValue(new Error("no parked session")),+ resolveSession: vi.fn(),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.tsindex 6fa0bb828..f93285e0f 100644--- a/packages/eve/src/channel/send.test.ts+++ b/packages/eve/src/channel/send.test.ts@@ -18,6 +18,7 @@ function createRuntime(deliverError: unknown): Runtime {return {cancelTurn: vi.fn(),deliver: vi.fn().mockRejectedValue(deliverError),+ resolveSession: vi.fn(),run: vi.fn().mockResolvedValue(createMockRunHandle()),getEventStream: vi.fn().mockResolvedValue(new ReadableStream<HandleMessageStreamEvent>()),};@@ -87,6 +88,7 @@ describe("createSendFn", () => {const deliverRuntime: Runtime = {cancelTurn: vi.fn(),deliver: vi.fn().mockResolvedValue({ sessionId: "existing-session-id" }),+ resolveSession: vi.fn(),run: vi.fn().mockResolvedValue(createMockRunHandle()),getEventStream: vi.fn().mockResolvedValue(new ReadableStream<HandleMessageStreamEvent>()),};@@ -119,6 +121,7 @@ describe("createSendFn", () => {const deliverRuntime: Runtime = {cancelTurn: vi.fn(),deliver: vi.fn().mockResolvedValue({ sessionId: "existing-session-id" }),+ resolveSession: vi.fn(),run: vi.fn().mockResolvedValue(createMockRunHandle()),getEventStream: vi.fn().mockResolvedValue(new ReadableStream<HandleMessageStreamEvent>()),};@@ -146,6 +149,7 @@ describe("createSendFn", () => {const deliverRuntime: Runtime = {cancelTurn: vi.fn(),deliver: vi.fn().mockResolvedValue({ sessionId: "existing-session-id" }),+ resolveSession: vi.fn(),run: vi.fn().mockResolvedValue(createMockRunHandle()),getEventStream: vi.fn().mockResolvedValue(new ReadableStream<HandleMessageStreamEvent>()),};diff --git a/packages/eve/src/channel/session.test.ts b/packages/eve/src/channel/session.test.tsindex 97d34bc2c..f41c30f72 100644--- a/packages/eve/src/channel/session.test.ts+++ b/packages/eve/src/channel/session.test.ts@@ -1,9 +1,47 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";-import { buildSessionHandle } from "#channel/session.js";+import { buildSessionHandle, createGetSessionFn, createSession } from "#channel/session.js";+import type { Runtime } from "#channel/types.js";import { ContextContainer } from "#context/container.js";import { AuthKey, ContinuationTokenKey, InitiatorAuthKey, SessionIdKey } from "#context/keys.js";+function createRuntime(): Runtime {+ return {+ cancelTurn: vi.fn().mockResolvedValue({ status: "accepted" }),+ deliver: vi.fn(),+ getEventStream: vi.fn(),+ resolveSession: vi.fn(),+ run: vi.fn(),+ };+}++describe("createSession#cancel", () => {+ it("cancels this session's turn by session id", async () => {+ const runtime = createRuntime();+ const session = createSession("sess_1", "C1:T1", runtime);++ await expect(session.cancel()).resolves.toEqual({ status: "accepted" });+ expect(runtime.cancelTurn).toHaveBeenCalledWith({ sessionId: "sess_1", turnId: undefined });+ });++ it("forwards the turn guard", async () => {+ const runtime = createRuntime();+ const session = createSession("sess_1", "C1:T1", runtime);++ await session.cancel({ turnId: "turn_2" });++ expect(runtime.cancelTurn).toHaveBeenCalledWith({ sessionId: "sess_1", turnId: "turn_2" });+ });++ it("is available on sessions returned by getSession", async () => {+ const runtime = createRuntime();+ const session = createGetSessionFn(runtime)("sess_2");++ await expect(session.cancel()).resolves.toEqual({ status: "accepted" });+ expect(runtime.cancelTurn).toHaveBeenCalledWith({ sessionId: "sess_2", turnId: undefined });+ });+});+describe("buildSessionHandle", () => {it("exposes sessionId / continuationToken / auth from the live accessor", () => {const ctx = new ContextContainer();diff --git a/packages/eve/src/channel/session.ts b/packages/eve/src/channel/session.tsindex 8d16c7ba9..89f946e6f 100644--- a/packages/eve/src/channel/session.ts+++ b/packages/eve/src/channel/session.ts@@ -1,6 +1,6 @@import type { ContextAccessor } from "#context/key.js";import type { HandleMessageStreamEvent } from "#protocol/message.js";-import type { Runtime } from "#channel/types.js";+import type { CancelTurnResult, Runtime } from "#channel/types.js";import type { SessionAuth } from "#context/keys.js";import { AuthKey, ContinuationTokenKey, InitiatorAuthKey, SessionIdKey } from "#context/keys.js";@@ -16,6 +16,13 @@ import { AuthKey, ContinuationTokenKey, InitiatorAuthKey, SessionIdKey } from "#export interface Session {readonly id: string;readonly continuationToken: string;+ /**+ * Requests cancellation of this session's in-flight turn. `turnId` limits+ * the request to the turn the caller observed. Both statuses are+ * successful; confirmation is `turn.cancelled` followed by+ * `session.waiting` on the event stream.+ */+ cancel(options?: { turnId?: string }): Promise<CancelTurnResult>;/*** Opens the durable event stream. Negative start indexes read relative to* the current tail (`-1` starts at the latest event).@@ -43,6 +50,9 @@ export function createSession(id: string, continuationToken: string, runtime: Rureturn {id,continuationToken,+ async cancel(options?: { turnId?: string }) {+ return runtime.cancelTurn({ sessionId: id, turnId: options?.turnId });+ },async getEventStream(options?: { startIndex?: number }) {return runtime.getEventStream(id, options);},diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.tsindex 744ebd5cd..970c9f6d5 100644--- a/packages/eve/src/channel/types.ts+++ b/packages/eve/src/channel/types.ts@@ -388,6 +388,13 @@ export interface Runtime {*/deliver(input: DeliverInput): Promise<{ sessionId: string }>;+ /**+ * Resolves the session that currently owns a continuation token without+ * delivering input or starting a run. Returns `undefined` when no session+ * owns the token.+ */+ resolveSession(continuationToken: string): Promise<{ sessionId: string } | undefined>;+/*** Returns a readable stream of lifecycle events for an existing session.*diff --git a/packages/eve/src/client/session.ts b/packages/eve/src/client/session.tsindex 36e43d4e6..04940a4b0 100644--- a/packages/eve/src/client/session.ts+++ b/packages/eve/src/client/session.ts@@ -94,12 +94,14 @@ export class ClientSession {** 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.+ * already parked. `turnId` limits the request to the turn the caller+ * observed; a stale guard is consumed as a benign no-op. 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> {+ async cancel(options?: { turnId?: string }): Promise<CancelSessionResult> {const sessionId = this.#state.sessionId;if (!sessionId) {throw new Error("Session has no session ID. Send a message first.");@@ -107,9 +109,18 @@ export class ClientSession {const url = createClientUrl(this.#context.host, createEveCancelTurnRoutePath(sessionId));const headers = await this.#context.resolveHeaders();+ headers.set("content-type", "application/json");+const response = await fetch(url,- withRedirectPolicy({ headers, method: "POST" }, this.#context.redirect),+ withRedirectPolicy(+ {+ headers,+ method: "POST",+ body: options ? JSON.stringify(options) : undefined,+ },+ this.#context.redirect,+ ),);const body = await response.text();diff --git a/packages/eve/src/execution/node-step.test.ts b/packages/eve/src/execution/node-step.test.tsindex 71e99a3e2..ef962133d 100644--- a/packages/eve/src/execution/node-step.test.ts+++ b/packages/eve/src/execution/node-step.test.ts@@ -217,6 +217,7 @@ function createNoopRuntime(): Runtime {return {cancelTurn: vi.fn(),deliver: vi.fn(),+ resolveSession: vi.fn(),run: vi.fn().mockRejectedValue(new Error("runtime.run should not be called in this test")),getEventStream: vi.fn()diff --git a/packages/eve/src/execution/turn-cancellation.integration.test.ts b/packages/eve/src/execution/turn-cancellation.integration.test.tsindex aede48f56..e87e73f8c 100644--- a/packages/eve/src/execution/turn-cancellation.integration.test.ts+++ b/packages/eve/src/execution/turn-cancellation.integration.test.ts@@ -15,7 +15,9 @@ 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 { createCancelFn } from "#channel/cancel.js";import type { RouteHandlerArgs } from "#channel/routes.js";+import { createSession } from "#channel/session.js";import { none } from "#public/channels/auth.js";import { eveChannel } from "#public/channels/eve.js";import type { Agent } from "#public/definitions/channel.js";@@ -26,8 +28,9 @@ import { attachRouteAgent } from "#internal/nitro/routes/channel-route-context.j/*** 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.+ * message normally. Coverage exercises direct hooks, the HTTP trigger, the+ * continuation-addressed channel helper, and layer-3 cancellation of adopted+ * local descendants.*/const FAILURE_EVENT_TYPES = ["step.failed", "turn.failed", "session.failed"] as const;@@ -244,6 +247,9 @@ function createCancelRouteCaller(): (send: () => {throw new Error("cancel route must not send");},+ cancel: () => {+ throw new Error("cancel route must not use the channel cancel helper");+ },getSession: () => {throw new Error("cancel route must not get a session");},@@ -424,6 +430,87 @@ describe("turn cancellation integration", () => {});}, 60_000);+ it("cancels a turn from a channel route helper addressed by continuation token", async () => {+ const fixture = createWaitToolRuntime("turn-cancel-helper");+ const rawToken = "turn-cancel-helper";+ const continuationToken = `http:${rawToken}`;+ const workflowRuntime = createWorkflowRuntime({+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),+ });+ const cancel = createCancelFn(workflowRuntime, "http");++ await fixture.runtime.run(async () => {+ // A token no session owns is the benign "nothing to cancel" success+ // and must never start a session.+ await expect(cancel({ continuationToken: "no-such-thread" })).resolves.toEqual({+ 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(continuationToken);+ await fixture.toolStarted;++ await expect(cancel({ continuationToken: rawToken })).resolves.toEqual({+ status: "accepted",+ });++ 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);++ // Session.cancel() addresses the same session by id. With the turn+ // settled and its cancel hook swept, it reports the benign status.+ await waitForHookSweep(sessionCancelHookToken(run.runId));+ const session = createSession(run.runId, rawToken, workflowRuntime);+ await expect(session.cancel()).resolves.toEqual({ status: "no_active_turn" });++ await waitForHook({ runId: run.runId }, { token: continuationToken });+ await resumeHook(continuationToken, {+ kind: "deliver",+ payloads: [{ message: "follow up after helper 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 helper cancel") === true,+ ),+ ).toBe(true);+ } finally {+ stream.dispose();+ await run.cancel();+ }+ });+ }, 60_000);+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";diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.tsindex b1a0735c5..c0f8d28c7 100644--- a/packages/eve/src/execution/workflow-runtime.test.ts+++ b/packages/eve/src/execution/workflow-runtime.test.ts@@ -13,11 +13,13 @@ import { isRuntimeNoActiveSessionError } from "#execution/runtime-errors.js";import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";+const getHookByTokenMock = vi.fn();const getRunMock = vi.fn();const resumeHookMock = vi.fn();const startMock = vi.fn();vi.mock("#compiled/@workflow/core/runtime.js", () => ({+ getHookByToken: (...args: unknown[]) => getHookByTokenMock(...args),getRun: (...args: unknown[]) => getRunMock(...args),resumeHook: (...args: unknown[]) => resumeHookMock(...args),start: (...args: unknown[]) => startMock(...args),@@ -28,6 +30,7 @@ vi.mock("#runtime/sessions/compiled-agent-cache.js", () => ({}));afterEach(() => {+ getHookByTokenMock.mockReset();getRunMock.mockReset();resumeHookMock.mockReset();startMock.mockReset();@@ -180,6 +183,35 @@ describe("createWorkflowRuntime#cancelTurn", () => {});});+describe("createWorkflowRuntime#resolveSession", () => {+ function buildRuntime() {+ return createWorkflowRuntime({ compiledArtifactsSource: {} as RuntimeCompiledArtifactsSource });+ }++ it("returns the owning session id from the hook lookup", async () => {+ getHookByTokenMock.mockResolvedValue({ runId: "owner-session" });++ await expect(buildRuntime().resolveSession("test:token")).resolves.toEqual({+ sessionId: "owner-session",+ });+ expect(getHookByTokenMock).toHaveBeenCalledWith("test:token");+ });++ it("returns undefined for an unknown token", async () => {+ const { HookNotFoundError } = await import("#compiled/@workflow/errors/index.js");+ getHookByTokenMock.mockRejectedValue(new HookNotFoundError("test:token"));++ await expect(buildRuntime().resolveSession("test:token")).resolves.toBeUndefined();+ });++ it("rethrows unexpected lookup failures", async () => {+ const failure = new Error("transient backing-store outage");+ getHookByTokenMock.mockRejectedValue(failure);++ await expect(buildRuntime().resolveSession("test:token")).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.tsindex 93ec8fb10..c3de291fa 100644--- a/packages/eve/src/execution/workflow-runtime.ts+++ b/packages/eve/src/execution/workflow-runtime.ts@@ -25,6 +25,7 @@ import { resolveInstalledPackageInfo } from "#internal/application/package.js";import { isEveDevEnvironment } from "#internal/application/dev-environment.js";import { createLogger, logError } from "#internal/logging.js";import {+ getHookByToken,getRun,resumeHook,start,@@ -204,6 +205,21 @@ export function createWorkflowRuntime(config: {getRun(sessionId).getReadable({ startIndex: options?.startIndex }),);},++ async resolveSession(continuationToken: string): Promise<{ sessionId: string } | undefined> {+ try {+ const hook = await getHookByToken(continuationToken);+ return { sessionId: hook.runId };+ } catch (error) {+ if (HookNotFoundError.is(error)) {+ return undefined;+ }+ logError(log, "failed to resolve session by continuation token", error, {+ continuationToken,+ });+ throw error;+ }+ },};}diff --git a/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.test.ts b/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.test.tsindex 4b4240bff..c8a6022ec 100644--- a/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.test.ts+++ b/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.test.ts@@ -108,7 +108,7 @@ const createRunner: DevelopmentRunnerFactory = () => {return {close: async () => {closed = true;- for (const listener of [...closedListeners]) {+ for (const listener of closedListeners) {listener();}closedListeners.clear();diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.tsindex 887b3b13e..3c18fc243 100644--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts@@ -234,6 +234,7 @@ describe("dispatchChannelRequest", () => {const runtimeForTest: Runtime = {cancelTurn: vi.fn(),deliver: vi.fn().mockResolvedValue({ sessionId: "sess_route" }),+ resolveSession: vi.fn(),getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),run: vi.fn(),};@@ -280,6 +281,7 @@ describe("dispatchChannelRequest", () => {const runtimeForTest: Runtime = {cancelTurn: vi.fn(),deliver: vi.fn().mockResolvedValue({ sessionId: "sess_route" }),+ resolveSession: vi.fn(),getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),run: vi.fn(),};@@ -321,6 +323,7 @@ describe("dispatchChannelRequest", () => {const runtimeForTest: Runtime = {cancelTurn: vi.fn().mockResolvedValue({ status: "accepted" }),deliver: vi.fn().mockResolvedValue({ sessionId: "sess_deliver" }),+ resolveSession: vi.fn(),getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),run: vi.fn().mockResolvedValue({continuationToken: "route-token",diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.tsindex 8336574b8..dc03c70ea 100644--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts@@ -6,6 +6,7 @@ import {} from "#channel/cross-channel-receive.js";import type { DeliverInput, RunInput, Runtime } from "#channel/types.js";import type { RouteHandlerArgs, WebSocketRouteHooks } from "#channel/routes.js";+import { createCancelFn } from "#channel/cancel.js";import { createSendFn } from "#channel/send.js";import { createGetSessionFn } from "#channel/session.js";import { createLogger, logError } from "#internal/logging.js";@@ -187,6 +188,7 @@ function buildRouteArgs(const adapter = channel?.adapter ?? { kind: "channel" };const agent = createRouteAgent(bundle.runtime, requestId);const send = createSendFn(bundle.runtime, adapter, channelName, { requestId });+ const cancel = createCancelFn(bundle.runtime, channelName);const getSession = createGetSessionFn(bundle.runtime);const receive = createCrossChannelReceiveFn(bundle.runtime,@@ -197,6 +199,7 @@ function buildRouteArgs(attachAgentInfoRouteResponse({send,+ cancel,getSession,receive,params,diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.tsindex 941679086..5be912ce1 100644--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts@@ -100,6 +100,9 @@ async function firePost(const send = vi.fn<SendFn<ChatSdkChannelState>>().mockResolvedValue({continuationToken: "chat-sdk:test",id: "session-1",+ async cancel() {+ return { status: "no_active_turn" as const };+ },async getEventStream() {return new ReadableStream();},@@ -114,6 +117,7 @@ async function firePost(}),{getSession: vi.fn() as any,+ cancel: vi.fn(),params: {},receive: vi.fn() as any,requestIp: null,@@ -168,6 +172,7 @@ describe("chatSdkChannel", () => {new Request("https://example.com/eve/v1/test?crc_token=abc123", { method: "GET" }),{getSession: vi.fn() as any,+ cancel: vi.fn(),params: {},receive: vi.fn() as any,requestIp: null,@@ -240,6 +245,9 @@ describe("chatSdkChannel", () => {const send = vi.fn<SendFn<ChatSdkChannelState>>().mockResolvedValue({continuationToken: "chat-sdk:test",id: "session-1",+ async cancel() {+ return { status: "no_active_turn" as const };+ },async getEventStream() {return new ReadableStream();},diff --git a/packages/eve/src/public/channels/eve.test.ts b/packages/eve/src/public/channels/eve.test.tsindex 648897498..4d7d5b38f 100644--- a/packages/eve/src/public/channels/eve.test.ts+++ b/packages/eve/src/public/channels/eve.test.ts@@ -61,6 +61,9 @@ function createEveCreateHandler(input: EveChannelInput) {const mockSend = vi.fn<SendFn>().mockResolvedValue({id: "test-session-id",continuationToken: "eve:test",+ async cancel() {+ return { status: "no_active_turn" };+ },async getEventStream() {return new ReadableStream();},@@ -71,6 +74,7 @@ function createEveCreateHandler(input: EveChannelInput) {async fetch(req: Request) {const args: RouteHandlerArgs = {send: mockSend,+ cancel: vi.fn(),getSession: vi.fn(),receive: vi.fn() as any,params: {},@@ -96,6 +100,9 @@ function createEveContinueHandler(input: EveChannelInput) {const mockSession: ChannelSession = {id: "test-session-id",continuationToken: "eve:test",+ async cancel() {+ return { status: "no_active_turn" };+ },async getEventStream() {return new ReadableStream();},@@ -109,6 +116,7 @@ function createEveContinueHandler(input: EveChannelInput) {async fetch(req: Request) {const args: RouteHandlerArgs = {send: mockSend,+ cancel: vi.fn(),getSession: mockGetSession,receive: vi.fn() as any,params: { sessionId: "test-session-id" },@@ -140,6 +148,7 @@ function createEveCancelHandler(input: EveChannelInput) {const args = attachRouteAgent({send: vi.fn(),+ cancel: vi.fn(),getSession: vi.fn(),receive: vi.fn() as any,params: { sessionId: "test-session-id" },@@ -175,6 +184,7 @@ function createEveStreamHandler(input: EveChannelInput) {const getEventStream = vi.fn().mockResolvedValue(new ReadableStream());const mockGetSession = vi.fn().mockReturnValue({+ cancel: vi.fn(),continuationToken: "eve:test",getEventStream,id: "test-session-id",@@ -185,6 +195,7 @@ function createEveStreamHandler(input: EveChannelInput) {async fetch(url: string) {const args: RouteHandlerArgs = {send: vi.fn(),+ cancel: vi.fn(),getSession: mockGetSession,receive: vi.fn() as any,params: { sessionId: "test-session-id" },diff --git a/packages/eve/src/public/channels/github/githubChannel.test.ts b/packages/eve/src/public/channels/github/githubChannel.test.tsindex f5a394c57..17a23e610 100644--- a/packages/eve/src/public/channels/github/githubChannel.test.ts+++ b/packages/eve/src/public/channels/github/githubChannel.test.ts@@ -171,6 +171,7 @@ async function firePost(const waitUntil = vi.fn();const response = await post.handler(request, {+ cancel: vi.fn(),getSession: vi.fn() as any,params: {},receive: vi.fn() as any,diff --git a/packages/eve/src/public/channels/index.ts b/packages/eve/src/public/channels/index.tsindex f78fb7f1c..ed9998326 100644--- a/packages/eve/src/public/channels/index.ts+++ b/packages/eve/src/public/channels/index.ts@@ -6,6 +6,9 @@ export {PATCH,DELETE,WS,+ type CancelFn,+ type CancelOptions,+ type CancelTurnResult,type Channel,type ChannelCors,type ChannelCorsOptions,diff --git a/packages/eve/src/public/channels/linear/linearChannel.test.ts b/packages/eve/src/public/channels/linear/linearChannel.test.tsindex 07ef7a91b..6f8aa6fa9 100644--- a/packages/eve/src/public/channels/linear/linearChannel.test.ts+++ b/packages/eve/src/public/channels/linear/linearChannel.test.ts@@ -127,6 +127,7 @@ async function firePost(const waitUntil = vi.fn();const response = await post.handler(request, {+ cancel: vi.fn(),getSession: vi.fn() as any,params: {},receive: vi.fn() as any,diff --git a/packages/eve/src/public/channels/teams/teamsChannel.test.ts b/packages/eve/src/public/channels/teams/teamsChannel.test.tsindex 778609571..9413748b2 100644--- a/packages/eve/src/public/channels/teams/teamsChannel.test.ts+++ b/packages/eve/src/public/channels/teams/teamsChannel.test.ts@@ -27,6 +27,7 @@ async function firePost(const send = vi.fn(async (_input: unknown, _options: unknown) => ({continuationToken: "TOKEN",+ cancel: async () => ({ status: "no_active_turn" as const }),getEventStream: async () => new ReadableStream(),id: "SESSION",}));@@ -39,6 +40,7 @@ async function firePost(}),{getSession: vi.fn(),+ cancel: vi.fn(),params: {},receive: vi.fn(),requestIp: null,@@ -248,6 +250,7 @@ describe("teamsChannel", () => {});const send = vi.fn(async (_input: unknown, _options: unknown) => ({continuationToken: "TOKEN",+ cancel: async () => ({ status: "no_active_turn" as const }),getEventStream: async () => new ReadableStream(),id: "SESSION",}));diff --git a/packages/eve/src/public/definitions/channel.test.ts b/packages/eve/src/public/definitions/channel.test.tsindex f7f42abdc..a9db21800 100644--- a/packages/eve/src/public/definitions/channel.test.ts+++ b/packages/eve/src/public/definitions/channel.test.ts@@ -558,6 +558,9 @@ describe("defineChannel", () => {return {id: channelId,continuationToken: channelId,+ async cancel() {+ return { status: "no_active_turn" as const };+ },async getEventStream() {return new ReadableStream();},diff --git a/packages/eve/src/public/definitions/channel.ts b/packages/eve/src/public/definitions/channel.tsindex 4e2858b59..354c1432f 100644--- a/packages/eve/src/public/definitions/channel.ts+++ b/packages/eve/src/public/definitions/channel.ts@@ -27,6 +27,8 @@ 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";export type {+ CancelFn,+ CancelOptions,HttpRouteDefinition,RouteDefinition,RouteHandlerArgs,diff --git a/packages/eve/test/eve-run-stream-channel.test.ts b/packages/eve/test/eve-run-stream-channel.test.tsindex e94b70b93..58f65ab46 100644--- a/packages/eve/test/eve-run-stream-channel.test.ts+++ b/packages/eve/test/eve-run-stream-channel.test.ts@@ -170,6 +170,9 @@ function createMockGetSession(events: ReadableStream<HandleMessageStreamEvent>)return vi.fn<GetSessionFn>().mockReturnValue({id: "session_xyz",continuationToken: "",+ async cancel() {+ return { status: "no_active_turn" };+ },async getEventStream() {return events;},@@ -182,6 +185,7 @@ function createArgs(input: {}): RouteHandlerArgs {return {send: vi.fn(),+ cancel: vi.fn(),getSession: input.getSession,receive: vi.fn() as any,params: input.params,diff --git a/packages/eve/test/scenarios/cross-channel-receive.scenario.test.ts b/packages/eve/test/scenarios/cross-channel-receive.scenario.test.tsindex 51f61737c..3af3cae1e 100644--- a/packages/eve/test/scenarios/cross-channel-receive.scenario.test.ts+++ b/packages/eve/test/scenarios/cross-channel-receive.scenario.test.ts@@ -82,6 +82,9 @@ function createCapturingRuntime(captured: CapturedRun[]): Runtime {async cancelTurn() {throw new Error("cancelTurn should not be called in this scenario");},+ async resolveSession() {+ throw new Error("resolveSession should not be called in this scenario");+ },async run(input) {captured.push({adapter: input.adapter,@@ -171,6 +174,9 @@ describe("cross-channel receive end-to-end", () => {send: async () => {throw new Error("webhook should delegate to args.receive()");},+ cancel: async () => {+ throw new Error("webhook should not cancel turns");+ },getSession: () => {throw new Error("webhook should not read sessions directly");},diff --git a/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts b/packages/eve/test/scenarios/schedule-trigger.scenario.test.tsindex 6fbebb217..f2f90ddd9 100644--- a/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts+++ b/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts@@ -60,6 +60,9 @@ function createCapturingRuntime(captured: CapturedRun[]): Runtime {async cancelTurn() {throw new Error("cancelTurn should not be called in this scenario");},+ async resolveSession() {+ throw new Error("resolveSession should not be called in this scenario");+ },async run(input) {captured.push({adapter: input.adapter,diff --git a/research/turn-cancellation-channel-ops.md b/research/turn-cancellation-channel-ops.mddeleted file mode 100644index 76e655489..000000000--- a/research/turn-cancellation-channel-ops.md+++ /dev/null@@ -1,117 +0,0 @@-----issue: https://github.com/vercel/eve/issues/483-status: proposed-last_updated: "2026-07-16"------# Turn cancellation for custom channel routes--## Summary--eve already supports cooperative turn cancellation through the runtime, the-authenticated eve HTTP route, `ClientSession.cancel()`, eval controls, and-recursive cancellation of active descendants. The remaining custom-channel-gap is addressing: a `defineChannel` route normally knows its channel-local-continuation token, not the runtime session id required by `Agent.cancelTurn`.--Add one `cancel` route helper that resolves the token without starting a-session and then delegates to the existing cancellation primitive. Steering-replacement input is separate and is specified in-[Channel turn steering](./channel-turn-steering.md).--## Authoring API--```ts-export interface RouteHandlerArgs<TState> {- // Existing helpers omitted.- cancel(options: { continuationToken: string; turnId?: string }): Promise<CancelTurnResult>;-}--export interface CancelTurnResult {- status: "accepted" | "no_active_turn";-}-```--The continuation token uses the same channel-local, unprefixed format as-`send()`. eve applies the channel namespace internally.--```ts-export default defineChannel({- routes: [- POST("/threads/:threadId/stop", async (_request, { cancel, params }) => {- const result = await cancel({ continuationToken: params.threadId });- return Response.json(result);- }),- ],-});-```--Authors who already have a session id can continue using the public-`RouteContext.agent.cancelTurn({ sessionId, turnId? })` primitive in authored-filesystem routes. The new `cancel` helper is the continuation-addressed-convenience surface for `defineChannel`. The lower-level agent method keeps the-precise `cancelTurn` name because it is addressed by runtime session id.--## Semantics--- `"accepted"` means the existing turn-cancellation hook accepted the request.- Settlement remains asynchronous and is confirmed by `turn.cancelled`- followed by `session.waiting` on the event stream.-- `"no_active_turn"` covers an unknown token, an idle or parked session, a- completed session, and a turn without a live cancellation target. Both- statuses are successful outcomes.-- `turnId` is an optional stale-request guard. A mismatch is consumed as a- benign no-op and cannot cancel a newer turn.-- The helper never starts a session, sends input, clears history, or falls back- to `runtime.run()`.-- Cancellation stops work without replacement input. It is not an alias for- `turnPolicy: "steer"`.-- Existing cancellation behavior is unchanged: partial streamed output and- completed side effects remain observable, durable settled history is kept,- and active local or remote descendants receive cancellation recursively.--## Runtime boundary--```text-channel-local continuation token- │- ▼-resolve current session owner without delivery- │- ▼-existing cancelTurn({ sessionId, turnId? })-```--Resolution and cancellation need not be one transaction because the optional-`turnId` guard protects the turn boundary. They do need these invariants:--1. Resolution returns the session that owned the token at its linearization- point; a concurrent rekey cannot retarget cancellation to another session.-2. A missing or retired token maps to `no_active_turn`, not an exception and- never a new run.-3. Runtime or Workflow failures other than an inactive target remain errors;- they must not be collapsed into `no_active_turn`.-4. The route author remains responsible for authenticating the inbound stop- request, exactly as for `send()`.--The internal implementation may use a non-delivery session command to resolve-the continuation hook's owning run id. That command must be consumed without-entering adapter delivery or changing the input queue.--## Verification and delivery--- Unit-test channel namespacing, result mapping, and route-helper injection for- HTTP and WebSocket routes.-- Cover unknown, parked, active, already-settled, guarded-match, and- guarded-mismatch cases.-- Race continuation rekeying and turn settlement against resolution; assert- that no newer session or turn is cancelled.-- Assert unexpected resolution errors propagate and never fall back to session- creation.-- Add a custom-channel e2e route that cancels a running tool using only the- public helper, observes the cancellation boundary, then resumes the same- session normally.--This is an additive public channel API and requires custom-channel docs, API-tests, and a patch changeset. It does not change the already-landed cancellation-protocol or events.