Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): cancel session-owned background tasks (#2985)

Rui90917771ad17
diff --git a/.changeset/cancel-owned-background-tasks.md b/.changeset/cancel-owned-background-tasks.md
new file mode 100644
index 000000000..db845f495
--- /dev/null
+++ b/.changeset/cancel-owned-background-tasks.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Allow clients to cancel every background task owned by a session with `session.cancel({ tasks: true })`. Timed-out eval cases now reset their owned sessions before the next case starts so background work cannot leak across cases.
diff --git a/docs/channels/eve.mdx b/docs/channels/eve.mdx
index c6867589e..36725222f 100644
--- a/docs/channels/eve.mdx
+++ b/docs/channels/eve.mdx
@@ -91,7 +91,7 @@ Stream a session as newline-delimited JSON from `GET /eve/v1/session/:sessionId/
### Cancel a turn
-Post to `/eve/v1/session/:sessionId/cancel` to request cancellation of the active turn. You can include the observed `turnId` to keep a late request from cancelling a newer turn. Cancellation is asynchronous; confirm it on the stream as `turn.cancelled` followed by `session.waiting`.
+Post to `/eve/v1/session/:sessionId/cancel` to request cancellation of the active turn. You can include the observed `turnId` to keep a late request from cancelling a newer turn. Include `tasks: true` to also cancel every background task owned by the session, including while the session is parked. Cancellation is asynchronous; confirm the turn boundary on the stream as `turn.cancelled` followed by `session.waiting`, and inspect task state in a later turn to confirm task cancellation.
See [Cancel the in-flight turn](../concepts/sessions-runs-and-streaming#cancel-the-in-flight-turn) for response statuses, HTTP status codes, subagent cancellation, and race behavior.
diff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.md
index 92de64737..18783693f 100644
--- a/docs/concepts/sessions-runs-and-streaming.md
+++ b/docs/concepts/sessions-runs-and-streaming.md
@@ -191,7 +191,15 @@ curl -X POST http://127.0.0.1:2000/eve/v1/session/<sessionId>/cancel
# {"ok":true,"sessionId":"<sessionId>","status":"accepted"}
```
-`"accepted"` means the live session durably queued the request. Confirm an actual cancellation on the stream as `turn.cancelled` followed by `session.waiting`; the session then accepts the next message normally. Background tasks that were already admitted survive initiating-turn cancellation and are stopped with `task_cancel`; background work that has not yet been admitted is rejected with the cancelled step. Each cancelled child reports its own boundary on its child-session stream. A live but already-parked session also returns `"accepted"` and consumes the command as a no-op. `"no_active_turn"` means the session or channel address is unknown or terminal. Both statuses are success, so clients can fire and forget. See the [eve channel](../channels/eve) for the full route contract.
+By default, background tasks that were already admitted survive initiating-turn cancellation. Pass `tasks: true` to cancel every background task owned by the session as well. This works while the session is parked, so you can stop background work without resetting the session:
+
+```bash
+curl -X POST http://127.0.0.1:2000/eve/v1/session/<sessionId>/cancel \
+ -H 'content-type: application/json' \
+ -d '{"tasks":true}'
+```
+
+`"accepted"` means the live session durably queued the request; cancellation completes asynchronously. Confirm turn cancellation on the stream as `turn.cancelled` followed by `session.waiting`. Inspect task state in a later turn to confirm task cancellation. The session then accepts the next message normally. Background work that has not yet been admitted is rejected with the cancelled step. Each cancelled child reports its own boundary on its child-session stream. A live but already-parked session returns `"accepted"`; plain cancellation is a no-op there, while `tasks: true` still cancels indexed tasks. `"no_active_turn"` means the session or channel address is unknown or terminal. Both statuses are success, so clients can fire and forget. See the [eve channel](../channels/eve) for the full route contract.
The HTTP route returns `202` for `"accepted"` and `200` for
`"no_active_turn"`. Only the accepted result includes `sessionId`.
diff --git a/docs/guides/client/streaming.mdx b/docs/guides/client/streaming.mdx
index 93fb13bc1..73923257a 100644
--- a/docs/guides/client/streaming.mdx
+++ b/docs/guides/client/streaming.mdx
@@ -237,7 +237,7 @@ stream index after the captured prefix.
## Abort a request
-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`.
+Pass an `AbortSignal` to cancel the POST or stream. Aborting is local transport cancellation: turns are resumable across disconnects, so detaching never stops server-side work. Use `session.cancel()` to stop the active turn, or `session.cancel({ tasks: true })` to also stop background tasks owned by the session. Cancellation is asynchronous; watch the stream for `turn.cancelled` followed by `session.waiting`, and inspect task state in a later turn to confirm task cancellation.
Arm the timeout before awaiting `send()` so it covers the POST as well as the stream:
diff --git a/e2e/fixtures/agent-cancellation/agent/agent.ts b/e2e/fixtures/agent-cancellation/agent/agent.ts
index 5e758ce1f..774cfeea3 100644
--- a/e2e/fixtures/agent-cancellation/agent/agent.ts
+++ b/e2e/fixtures/agent-cancellation/agent/agent.ts
@@ -2,7 +2,7 @@ import { e2eAgentConfig } from "@eve-e2e/config";
import { defineAgent } from "eve";
import type { MockModelRequest, MockModelResponse } from "eve/evals";
-const RECOVERY_TOKEN = "CANCELLED-SUBAGENT-RECOVERED";
+const RECOVERY_REQUEST = "RESUME-CANCELLED-SLEEPER";
function respond(request: MockModelRequest): MockModelResponse | string {
const message = request.lastUserMessage ?? "";
@@ -30,7 +30,7 @@ function respond(request: MockModelRequest): MockModelResponse | string {
"No agents listed."
);
}
- if (message.includes(RECOVERY_TOKEN)) {
+ if (message.includes(RECOVERY_REQUEST)) {
const result = request.toolResults.find((entry) => entry.id === "resume-sleeper");
if (result !== undefined) {
return typeof result.output === "string" ? result.output : JSON.stringify(result.output);
@@ -42,7 +42,7 @@ function respond(request: MockModelRequest): MockModelResponse | string {
{
id: "resume-sleeper",
input: {
- js: `return await tools["sleeper"]({ agentId: ${agentId}, message: ${JSON.stringify(RECOVERY_TOKEN)} });`,
+ js: `return await tools["sleeper"]({ agentId: ${agentId}, message: ${JSON.stringify(RECOVERY_REQUEST)} });`,
},
name: "Workflow",
},
diff --git a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.ts b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.ts
index a5d86664b..e39e49104 100644
--- a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.ts
+++ b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.ts
@@ -1,14 +1,15 @@
import { e2eSubagentConfig } from "@eve-e2e/config";
import { defineAgent } from "eve";
-const RECOVERY_TOKEN = "CANCELLED-SUBAGENT-RECOVERED";
+const RECOVERY_REQUEST = "RESUME-CANCELLED-SLEEPER";
+const RECOVERY_RESULT = "CANCELLED-SUBAGENT-RECOVERED";
export default defineAgent({
description: "Waits until its delegated turn is cancelled, then supports a recovery probe.",
...e2eSubagentConfig({
mock: ({ lastUserMessage }) =>
- lastUserMessage?.includes(RECOVERY_TOKEN) === true
- ? RECOVERY_TOKEN
+ lastUserMessage?.includes(RECOVERY_REQUEST) === true
+ ? RECOVERY_RESULT
: {
toolCalls: [
{
diff --git a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.md b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.md
index 36b10de78..28a1b05ef 100644
--- a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.md
+++ b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.md
@@ -4,6 +4,6 @@ You are a cancellation test sleeper.
# Rules
-- If the message contains `CANCELLED-SUBAGENT-RECOVERED`, do not call any tool. Reply with exactly `CANCELLED-SUBAGENT-RECOVERED`.
+- If the message contains `RESUME-CANCELLED-SLEEPER`, do not call any tool. Reply with exactly `CANCELLED-SUBAGENT-RECOVERED`.
- Otherwise, call `wait-for-cancellation` exactly once, immediately, with no preamble.
- Do not call any other tool.
diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-subagent.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-subagent.eval.ts
index b45615d94..af927a81e 100644
--- a/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-subagent.eval.ts
+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-subagent.eval.ts
@@ -1,7 +1,8 @@
import { defineEval } from "eve/evals";
import { satisfies } from "eve/evals/expect";
-const RECOVERY_TOKEN = "CANCELLED-SUBAGENT-RECOVERED";
+const RECOVERY_REQUEST = "RESUME-CANCELLED-SLEEPER";
+const RECOVERY_RESULT = "CANCELLED-SUBAGENT-RECOVERED";
export default defineEval({
description:
@@ -71,12 +72,12 @@ export default defineEval({
const resumed = await t.send(
[
"Use the Workflow tool exactly once.",
- `In its JavaScript, call sleeper with agentId ${JSON.stringify(agentId)} and message ${JSON.stringify(RECOVERY_TOKEN)}.`,
+ `In its JavaScript, call sleeper with agentId ${JSON.stringify(agentId)} and message ${JSON.stringify(RECOVERY_REQUEST)}.`,
"Return the inline result and reply with it verbatim. Do not call sleeper outside Workflow.",
].join(" "),
);
resumed.expectOk();
- resumed.messageIncludes(RECOVERY_TOKEN);
+ resumed.messageIncludes(RECOVERY_RESULT);
resumed.event("subagent.called", {
count: 1,
data: {
diff --git a/e2e/fixtures/agent-subagents-hitl/evals/mixed-runtime-action-approval.eval.ts b/e2e/fixtures/agent-subagents-hitl/evals/mixed-runtime-action-approval.eval.ts
index 878a8eb5a..18cf7279e 100644
--- a/e2e/fixtures/agent-subagents-hitl/evals/mixed-runtime-action-approval.eval.ts
+++ b/e2e/fixtures/agent-subagents-hitl/evals/mixed-runtime-action-approval.eval.ts
@@ -1,4 +1,4 @@
-import { defineEval } from "eve/evals";
+import { defineEval, type EveEvalContext, type EveEvalSession, type EveEvalTurn } from "eve/evals";
const COLLISION_MARKER = "MIXED-PARK-COMPLETE-7K2M";
@@ -33,7 +33,10 @@ export default defineEval({
const resumed = await t.respondAll("approve");
resumed.expectOk();
- resumed.messageIncludes(COLLISION_MARKER);
+ const completed = resumed.message?.includes(COLLISION_MARKER)
+ ? resumed
+ : await waitForMessage(t, t, COLLISION_MARKER);
+ completed.messageIncludes(COLLISION_MARKER);
t.succeeded();
t.noFailedActions();
@@ -41,3 +44,24 @@ export default defineEval({
t.calledSubagent("collision-child", { count: 1, status: "completed" });
},
});
+
+type SessionCursor = Pick<EveEvalSession, "sessionId" | "state">;
+
+async function waitForMessage(
+ t: EveEvalContext,
+ initialSession: SessionCursor,
+ marker: string,
+): Promise<EveEvalTurn> {
+ let session = initialSession;
+ for (let attempt = 0; attempt < 5; attempt += 1) {
+ if (session.sessionId === undefined || session.state === undefined) {
+ throw new Error("Mixed approval completion wait has no parent session cursor.");
+ }
+ const live = t.target.watchTurn(session.sessionId, { startIndex: session.state.streamIndex });
+ const turn = await live.result();
+ turn.noFailedActions();
+ if (turn.message?.includes(marker) === true) return turn;
+ session = live.session;
+ }
+ throw new Error("Mixed approval result did not reach the parent after five turns.");
+}
diff --git a/e2e/fixtures/fixture-tasks/evals/shared.ts b/e2e/fixtures/fixture-tasks/evals/shared.ts
index 1f54fd38a..769312255 100644
--- a/e2e/fixtures/fixture-tasks/evals/shared.ts
+++ b/e2e/fixtures/fixture-tasks/evals/shared.ts
@@ -3,7 +3,7 @@ import { satisfies } from "eve/evals/expect";
export type TaskEvalSessionDriver = Pick<
EveEvalSession,
- "pendingInputRequests" | "respond" | "send" | "sessionId" | "state"
+ "events" | "pendingInputRequests" | "respond" | "send" | "sessionId" | "state"
>;
export interface PendingTaskInput {
@@ -147,6 +147,53 @@ export async function sendAndFollowQueuedTurn(
throw new Error(`Queued message "${message}" was not received after 20 turns.`);
}
+/** Waits for one runtime-authored terminal task delivery on the parent stream. */
+export async function waitForTaskNotification(
+ t: EveEvalContext,
+ initialSession: TaskEvalSessionDriver,
+ taskId: string,
+ status: "cancelled" | "completed" | "failed",
+ observedTurns: readonly EveEvalTurn[] = [],
+): Promise<{ readonly session: TaskEvalSessionDriver; readonly turn: EveEvalTurn }> {
+ let session = initialSession;
+ const expected = `Background task ${taskId} (`;
+ const matches = (turn: EveEvalTurn) =>
+ turn.events.some(
+ (event) =>
+ event.type === "message.received" &&
+ messageText(event.data.message).includes(expected) &&
+ messageText(event.data.message).includes(` is ${status}.`),
+ );
+ const observed = observedTurns.find(matches);
+ if (observed !== undefined) return { session, turn: observed };
+ const recorded = session.events.some(
+ (event) =>
+ event.type === "message.received" &&
+ messageText(event.data.message).includes(expected) &&
+ messageText(event.data.message).includes(` is ${status}.`),
+ );
+ if (recorded) {
+ const turn = observedTurns.at(-1);
+ if (turn === undefined) {
+ throw new Error(`Task ${taskId} notification was recorded without an observed turn.`);
+ }
+ return { session, turn };
+ }
+ for (let attempt = 0; attempt < 20; attempt += 1) {
+ const sessionId = session.sessionId;
+ if (sessionId === undefined)
+ throw new Error("Task notification wait has no parent session id.");
+ const live = t.target.watchTurn(sessionId, {
+ startIndex: requireSessionStreamIndex(session, "Task notification wait"),
+ });
+ const turn = await live.result();
+ turn.noFailedActions().label(`task notification wait ${attempt + 1} has no failed actions`);
+ session = live.session;
+ if (matches(turn)) return { session, turn };
+ }
+ throw new Error(`Task ${taskId} did not deliver terminal status "${status}" after 20 turns.`);
+}
+
/** Waits for completion, then reads the immutable terminal view through no-op cancellation. */
export async function waitForCompletedTask(
t: EveEvalContext,
diff --git a/e2e/fixtures/fixture-tasks/evals/task-transition.ts b/e2e/fixtures/fixture-tasks/evals/task-transition.ts
index 96ded2dff..b30ae1cbb 100644
--- a/e2e/fixtures/fixture-tasks/evals/task-transition.ts
+++ b/e2e/fixtures/fixture-tasks/evals/task-transition.ts
@@ -112,6 +112,28 @@ export const TASK_TRANSITIONS = {
sideEffects: { executed: ["task-view-append", "parent-wake", "child-abort"] },
},
}),
+ "task.lifecycle.cancel.owned-session-accepted-nonterminal": transition({
+ preState: { lifecycle: ["working", "input_required"] },
+ input: "cancel",
+ guards: ["task-is-nonterminal", "parent-session-owns-task"],
+ expected: {
+ outcome: "accepted",
+ postState: { lifecycle: "cancelled", outstandingInput: "none" },
+ events: { emitted: ["task-ready-notification"] },
+ sideEffects: { executed: ["task-view-append", "parent-wake", "child-abort"] },
+ },
+ }),
+ "task.lifecycle.cancel.default-preserves-nonterminal": transition({
+ preState: { lifecycle: "input_required" },
+ input: "cancel",
+ guards: ["session-cancel-omits-task-scope"],
+ expected: {
+ outcome: "noop",
+ postState: { lifecycle: "input_required" },
+ events: { suppressed: ["task-ready-notification"] },
+ sideEffects: { suppressed: ["task-view-append", "child-abort"] },
+ },
+ }),
"task.lifecycle.cancel.noop-already-cancelled": transition({
preState: { lifecycle: "cancelled" },
input: "cancel",
diff --git a/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.default-preserves-nonterminal.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.default-preserves-nonterminal.eval.ts
new file mode 100644
index 000000000..134cf8c86
--- /dev/null
+++ b/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.default-preserves-nonterminal.eval.ts
@@ -0,0 +1,38 @@
+import { requireBackgroundTaskId, waitForTaskInput, waitForTaskNotification } from "./shared.js";
+import { defineTaskEval } from "./task-transition.js";
+
+/** Plain session cancellation remains turn-only while the parent is parked. */
+export default defineTaskEval({
+ description: "session.cancel() preserves an admitted background task by default.",
+ transition: {
+ primary: "task.lifecycle.cancel.default-preserves-nonterminal",
+ setup: ["task.dispatch.start.accepted-acknowledged", "task.input.require.accepted-valid-batch"],
+ dimensions: { transport: "local", parentPhase: "parked" },
+ },
+ async test(t) {
+ const started = await t.send("TASK-CANCEL-SETUP");
+ started.expectOk();
+ const taskId = requireBackgroundTaskId(started);
+ const blocked = await waitForTaskInput(t, t, "release");
+ const sessionId = blocked.session.sessionId;
+ if (sessionId === undefined) throw new Error("Task parent has no session id.");
+
+ const response = await t.target.fetch(`/eve/v1/session/${sessionId}/cancel`, {
+ method: "POST",
+ });
+ if (response.status !== 202) {
+ throw new Error(`Plain parked cancellation returned HTTP ${response.status}.`);
+ }
+
+ const answered = await blocked.session.respond([
+ { optionId: "approve", requestId: blocked.request.requestId },
+ ]);
+ answered.expectOk();
+
+ const completed = await waitForTaskNotification(t, blocked.session, taskId, "completed", [
+ answered,
+ ]);
+ const followUp = await completed.session.send("TASK-CANCEL-VERIFY-NOOP");
+ followUp.expectOk();
+ },
+});
diff --git a/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.owned-session-accepted-nonterminal.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.owned-session-accepted-nonterminal.eval.ts
new file mode 100644
index 000000000..a64585528
--- /dev/null
+++ b/e2e/fixtures/fixture-tasks/evals/task.lifecycle.cancel.owned-session-accepted-nonterminal.eval.ts
@@ -0,0 +1,62 @@
+import { satisfies } from "eve/evals/expect";
+
+import {
+ requireBackgroundTaskId,
+ requireTaskView,
+ waitForTaskInput,
+ waitForTaskStatus,
+} from "./shared.js";
+import { defineTaskEval } from "./task-transition.js";
+
+/** Session cancellation can retire indexed tasks while the parent is parked. */
+export default defineTaskEval({
+ description: "session.cancel({ tasks: true }) cancels an owned task without ending the session.",
+ transition: {
+ primary: "task.lifecycle.cancel.owned-session-accepted-nonterminal",
+ setup: ["task.dispatch.start.accepted-acknowledged", "task.input.require.accepted-valid-batch"],
+ dimensions: { transport: "local", parentPhase: "parked" },
+ },
+ async test(t) {
+ const started = await t.send("TASK-CANCEL-SETUP");
+ started.expectOk();
+ const taskId = requireBackgroundTaskId(started);
+ const blocked = await waitForTaskInput(t, t, "release");
+ const sessionId = blocked.session.sessionId;
+ if (sessionId === undefined) throw new Error("Task parent has no session id.");
+
+ const response = await t.target.fetch(`/eve/v1/session/${sessionId}/cancel`, {
+ body: JSON.stringify({ tasks: true }),
+ headers: { "content-type": "application/json" },
+ method: "POST",
+ });
+ const responseBody: unknown = await response.json();
+ await t.require(
+ { body: responseBody, status: response.status },
+ satisfies(
+ (result: { readonly body: unknown; readonly status: number }) =>
+ result.status === 202 &&
+ result.body !== null &&
+ typeof result.body === "object" &&
+ Reflect.get(result.body, "status") === "accepted",
+ "the parked session accepts owned-task cancellation",
+ ),
+ );
+
+ const verified = await waitForTaskStatus(
+ t,
+ blocked.session,
+ "TASK-CANCEL-VERIFY",
+ taskId,
+ "cancelled",
+ );
+ verified.expectOk();
+ verified.messageIncludes("TASK-CANCEL-STATUS");
+ await t.require(
+ requireTaskView(verified.requireToolCall("task_cancel").output, taskId),
+ satisfies(
+ (view: Record<string, unknown>) => Reflect.get(view, "status") === "cancelled",
+ "the session remains usable and exposes the cancelled task",
+ ),
+ );
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/channel/v15.ts b/packages/eve/extension-contracts/compatibility/channel/v15.ts
new file mode 100644
index 000000000..67e58f0bb
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/channel/v15.ts
@@ -0,0 +1,3 @@
+import { disableRoute } from "#public/channels/index.js";
+
+export default disableRoute();
diff --git a/packages/eve/extension-contracts/compatibility/schedule/v8.ts b/packages/eve/extension-contracts/compatibility/schedule/v8.ts
new file mode 100644
index 000000000..58d9be225
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/schedule/v8.ts
@@ -0,0 +1,8 @@
+import { defineSchedule } from "#public/schedules/index.js";
+
+export default defineSchedule({
+ cron: "0 0 * * *",
+ run({ waitUntil }) {
+ waitUntil(Promise.resolve());
+ },
+});
diff --git a/packages/eve/extension-contracts/reports/channel/v16.json b/packages/eve/extension-contracts/reports/channel/v16.json
new file mode 100644
index 000000000..f1ea40bdf
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/channel/v16.json
@@ -0,0 +1,21 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "channel",
+ "epoch": 16,
+ "sha256": "f943a1fe862c90e064c520797586934bf09f4f7189f02f43e72b5c3a07e6394e",
+ "exports": [
+ "DELETE",
+ "GET",
+ "HEAD",
+ "OPTIONS",
+ "PATCH",
+ "POST",
+ "PUT",
+ "WS",
+ "createWebSocketUpgradeServer",
+ "defineChannel",
+ "disableRoute",
+ "isChannel",
+ "isDisabledRouteSentinel"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/schedule/v9.json b/packages/eve/extension-contracts/reports/schedule/v9.json
new file mode 100644
index 000000000..9a0c3e4e7
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/schedule/v9.json
@@ -0,0 +1,14 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "schedule",
+ "epoch": 9,
+ "sha256": "116a1298129f8a4dae5bc82e56298e156963edc19ff70ded57df02fcd2ea12f3",
+ "exports": [
+ "ScheduleDefinition",
+ "ScheduleHandlerArgs",
+ "ScheduleRunHandler",
+ "ScheduleToFn",
+ "TypedReceiveTarget",
+ "defineSchedule"
+ ]
+}
diff --git a/packages/eve/src/channel/session.test.ts b/packages/eve/src/channel/session.test.ts
index 703bc7ae9..c98dae2e6 100644
--- a/packages/eve/src/channel/session.test.ts
+++ b/packages/eve/src/channel/session.test.ts
@@ -55,19 +55,19 @@ describe("createSession#cancel", () => {
await expect(session.cancel()).resolves.toEqual({ sessionId: "sess_1", status: "accepted" });
expect(runtime.dispatchSession).toHaveBeenCalledWith({
- command: { kind: "cancel", turnId: undefined },
+ command: { kind: "cancel" },
sessionId: "sess_1",
});
});
- it("forwards the turn guard", async () => {
+ it("forwards the turn guard and owned-task scope", async () => {
const runtime = createRuntime();
const session = createSession("sess_1", runtime);
- await session.cancel({ turnId: "turn_2" });
+ await session.cancel({ tasks: true, turnId: "turn_2" });
expect(runtime.dispatchSession).toHaveBeenCalledWith({
- command: { kind: "cancel", turnId: "turn_2" },
+ command: { kind: "cancel", tasks: true, turnId: "turn_2" },
sessionId: "sess_1",
});
});
@@ -78,7 +78,7 @@ describe("createSession#cancel", () => {
await expect(session.cancel()).resolves.toEqual({ sessionId: "sess_2", status: "accepted" });
expect(runtime.dispatchSession).toHaveBeenCalledWith({
- command: { kind: "cancel", turnId: undefined },
+ command: { kind: "cancel" },
sessionId: "sess_2",
});
});
diff --git a/packages/eve/src/channel/session.ts b/packages/eve/src/channel/session.ts
index 9e28e4924..ba955d39b 100644
--- a/packages/eve/src/channel/session.ts
+++ b/packages/eve/src/channel/session.ts
@@ -44,8 +44,12 @@ export interface Session {
inputResponses: StrictInputResponses<TResponses>,
options: SessionRespondOptions,
): Promise<SessionSendCommandResult>;
- /** Requests cancellation of this exact session's active turn or one owned task. */
- cancel(options?: { taskId?: string; turnId?: string }): Promise<CancelTurnResult>;
+ /** Requests cancellation of this exact session's active turn and optionally its owned tasks. */
+ cancel(options?: {
+ taskId?: string;
+ tasks?: boolean;
+ turnId?: string;
+ }): Promise<CancelTurnResult>;
/** Queues compaction on this exact session ID. */
compact(): Promise<CompactSessionResult>;
/** Queues a context clear on this exact session ID. */
@@ -143,11 +147,14 @@ export function createSession(
sessionId: id,
});
},
- async cancel(options?: { taskId?: string; turnId?: string }) {
- return await runtime.dispatchSession({
- command: { kind: "cancel", taskId: options?.taskId, turnId: options?.turnId },
- sessionId: id,
- });
+ async cancel(options?: { taskId?: string; tasks?: boolean; turnId?: string }) {
+ const command: { kind: "cancel"; taskId?: string; tasks?: boolean; turnId?: string } = {
+ kind: "cancel",
+ };
+ if (options?.taskId !== undefined) command.taskId = options.taskId;
+ if (options?.tasks !== undefined) command.tasks = options.tasks;
+ if (options?.turnId !== undefined) command.turnId = options.turnId;
+ return await runtime.dispatchSession({ command, sessionId: id });
},
async compact() {
return await runtime.dispatchSession({ command: { kind: "compact" }, sessionId: id });
diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.ts
index 86d5e08bf..9f2b60180 100644
--- a/packages/eve/src/channel/types.ts
+++ b/packages/eve/src/channel/types.ts
@@ -36,6 +36,8 @@ export interface CancelTurnInput {
readonly sessionId: string;
/** Framework task whose queued child deliveries should be discarded. */
readonly taskId?: string;
+ /** Cancels every nonterminal task owned by the session. */
+ readonly tasks?: boolean;
/** Limits the request to the turn the caller observed. */
readonly turnId?: string;
}
@@ -214,7 +216,12 @@ export type SessionCommand =
readonly taskDeliveryId?: string;
readonly turnPolicy?: TurnPolicy;
}
- | { readonly kind: "cancel"; readonly taskId?: string; readonly turnId?: string }
+ | {
+ readonly kind: "cancel";
+ readonly taskId?: string;
+ readonly tasks?: boolean;
+ readonly turnId?: string;
+ }
| { readonly kind: "compact" }
| { readonly kind: "clear" }
| { readonly kind: "reset"; readonly reason?: string };
diff --git a/packages/eve/src/client/session-controls.ts b/packages/eve/src/client/session-controls.ts
index 4fe4f6b2d..33ef31a7d 100644
--- a/packages/eve/src/client/session-controls.ts
+++ b/packages/eve/src/client/session-controls.ts
@@ -26,14 +26,20 @@ interface SessionControlContext {
export async function cancelClientSession(input: {
readonly context: SessionControlContext;
- readonly options?: { readonly turnId?: string };
+ readonly options?: {
+ readonly signal?: AbortSignal;
+ readonly tasks?: boolean;
+ readonly turnId?: string;
+ };
readonly sessionId: string;
}): Promise<CancelSessionResult> {
+ const { signal, ...body } = input.options ?? {};
const { payload, response } = await postJson({
- body: input.options,
+ body,
context: input.context,
operation: "Cancel",
path: createEveSessionCancelRoutePath(input.sessionId),
+ signal,
});
const result = CancelTurnResponseSchema.safeParse(payload);
if (
@@ -91,14 +97,16 @@ export async function compactClientSession(input: {
export async function resetClientSession(input: {
readonly context: SessionControlContext;
- readonly options?: { readonly reason?: string };
+ readonly options?: { readonly reason?: string; readonly signal?: AbortSignal };
readonly sessionId: string;
}): Promise<ResetResult> {
+ const { signal, ...body } = input.options ?? {};
const { payload } = await postJson({
- body: input.options,
+ body,
context: input.context,
operation: "Reset",
path: createEveSessionResetRoutePath(input.sessionId),
+ signal,
});
const result = ResetResponseSchema.safeParse(payload);
if (
@@ -117,6 +125,7 @@ async function postJson(input: {
readonly context: SessionControlContext;
readonly operation: string;
readonly path: string;
+ readonly signal?: AbortSignal;
}): Promise<{ readonly payload: unknown; readonly response: Response }> {
const headers = await input.context.resolveHeaders();
headers.set("content-type", "application/json");
@@ -127,6 +136,7 @@ async function postJson(input: {
body: input.body === undefined ? undefined : JSON.stringify(input.body),
headers,
method: "POST",
+ signal: input.signal,
},
input.context.redirect,
),
diff --git a/packages/eve/src/client/session.test.ts b/packages/eve/src/client/session.test.ts
index 14eab08fb..5fefa5db9 100644
--- a/packages/eve/src/client/session.test.ts
+++ b/packages/eve/src/client/session.test.ts
@@ -134,6 +134,25 @@ describe("ClientSession", () => {
expect(requests[1]!.headers.get("authorization")).toBe("Bearer token-2");
});
+ it("sends tasks in the cancel body and uses signal only for fetch", async () => {
+ const controller = new AbortController();
+ const fetchMock = vi
+ .spyOn(globalThis, "fetch")
+ .mockResolvedValue(
+ Response.json({ ok: true, sessionId: "session_1", status: "accepted" }, { status: 202 }),
+ );
+ const session = createSession();
+
+ await expect(
+ session.cancel({ signal: controller.signal, tasks: true, turnId: "turn_1" }),
+ ).resolves.toEqual({ sessionId: "session_1", status: "accepted" });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const init = fetchMock.mock.calls[0]?.[1];
+ expect(init?.signal).toBe(controller.signal);
+ expect(JSON.parse(String(init?.body))).toEqual({ tasks: true, turnId: "turn_1" });
+ });
+
it("snapshots the session from the start through one pinned durable tail", async () => {
const requests: string[] = [];
vi.spyOn(globalThis, "fetch").mockImplementation(async (request, init) => {
@@ -452,7 +471,13 @@ describe("ClientSession", () => {
it("resets the exact session while keeping the handle pinned to its ID", async () => {
let headerResolution = 0;
- const requests: Array<{ headers: Headers; method: string; url: string; body?: string }> = [];
+ const requests: Array<{
+ body?: string;
+ headers: Headers;
+ method: string;
+ signal?: AbortSignal | null;
+ url: string;
+ }> = [];
vi.spyOn(globalThis, "fetch").mockImplementation(async (request, init) => {
const url =
typeof request === "string" ? request : request instanceof URL ? request.href : request.url;
@@ -460,6 +485,7 @@ describe("ClientSession", () => {
body: typeof init?.body === "string" ? init.body : undefined,
headers: new Headers(init?.headers),
method: init?.method ?? "GET",
+ signal: init?.signal,
url,
});
return Response.json({
@@ -479,7 +505,8 @@ describe("ClientSession", () => {
},
);
- await expect(session.reset()).resolves.toEqual({
+ const signal = AbortSignal.timeout(1_000);
+ await expect(session.reset({ signal })).resolves.toEqual({
previousSessionId: "session_1",
status: "reset",
});
@@ -489,6 +516,7 @@ describe("ClientSession", () => {
expect(new URL(requests[0]!.url).pathname).toBe("/eve/v1/session/session_1/reset");
expect(requests[0]!.method).toBe("POST");
expect(requests[0]!.headers.get("authorization")).toBe("Bearer token-1");
+ expect(requests[0]!.signal).toBe(signal);
expect(JSON.parse(requests[0]!.body ?? "{}")).toEqual({});
});
diff --git a/packages/eve/src/client/session.ts b/packages/eve/src/client/session.ts
index bd3e02b0f..b67960ce6 100644
--- a/packages/eve/src/client/session.ts
+++ b/packages/eve/src/client/session.ts
@@ -127,8 +127,12 @@ export class ClientSession {
return this.#messageResponse<TOutput>(response, input, initialStreamIndex);
}
- /** Requests cooperative cancellation of this session's active turn. */
- async cancel(options?: { readonly turnId?: string }): Promise<CancelSessionResult> {
+ /** Requests cooperative cancellation of this session's active turn and optionally its tasks. */
+ async cancel(options?: {
+ readonly signal?: AbortSignal;
+ readonly tasks?: boolean;
+ readonly turnId?: string;
+ }): Promise<CancelSessionResult> {
return await cancelClientSession({
context: this.#context,
options,
@@ -147,7 +151,10 @@ export class ClientSession {
}
/** Terminally retires this exact session ID. The handle remains pinned to it. */
- async reset(options?: { readonly reason?: string }): Promise<ResetResult> {
+ async reset(options?: {
+ readonly reason?: string;
+ readonly signal?: AbortSignal;
+ }): Promise<ResetResult> {
return await resetClientSession({
context: this.#context,
options,
diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.ts
index 2f66db611..c82c125a8 100644
--- a/packages/eve/src/compiler/extension-compatibility.ts
+++ b/packages/eve/src/compiler/extension-compatibility.ts
@@ -38,15 +38,15 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
channel: {
- current: 15,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15],
+ current: 16,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16],
dropped: {
12: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
},
},
schedule: {
- current: 8,
- supported: [1, 2, 3, 4, 6, 7, 8],
+ current: 9,
+ supported: [1, 2, 3, 4, 6, 7, 8, 9],
dropped: {
5: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
},
diff --git a/packages/eve/src/evals/runner/execute-task.test.ts b/packages/eve/src/evals/runner/execute-task.test.ts
index 5e7d8b771..be0c66855 100644
--- a/packages/eve/src/evals/runner/execute-task.test.ts
+++ b/packages/eve/src/evals/runner/execute-task.test.ts
@@ -1,6 +1,7 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { Client } from "#client/client.js";
+import { ClientSession } from "#client/session.js";
import {
EVE_MESSAGE_STREAM_VERSION,
EVE_STREAM_VERSION_HEADER,
@@ -58,6 +59,75 @@ describe("executeTask", () => {
expect(outcome.error).toMatch(/timed out|timeout/i);
});
+ it("resets each distinct known session after a configured timeout", async () => {
+ const reset = vi.spyOn(ClientSession.prototype, "reset").mockResolvedValue({
+ previousSessionId: "ignored-by-runner",
+ status: "reset",
+ });
+ let evalSignal: AbortSignal | undefined;
+
+ const outcome = await executeTask({
+ client: new Client({ host: target.url }),
+ target,
+ evaluation: createTestEval(async (t) => {
+ evalSignal = t.signal;
+ t.target.watchTurn("shared-root");
+ t.target.watchTurn("shared-root");
+ t.target.watchTurn("other-root");
+ await new Promise<void>(() => {});
+ }, "timeout-cleanup"),
+ timeoutMs: 1,
+ });
+
+ expect(outcome.error).toMatch(/timed out|timeout/i);
+ expect(reset).toHaveBeenCalledTimes(2);
+ expect(
+ reset.mock.contexts.map((session) => (session as ClientSession).state.sessionId),
+ ).toEqual(["shared-root", "other-root"]);
+ for (const [options] of reset.mock.calls) {
+ expect(options).toMatchObject({ reason: "Eval timed out", signal: expect.any(AbortSignal) });
+ expect(options?.signal).not.toBe(evalSignal);
+ expect(options?.signal?.aborted).toBe(false);
+ }
+ });
+
+ it("does not run timeout cleanup for an ordinary eval failure", async () => {
+ const reset = vi.spyOn(ClientSession.prototype, "reset").mockResolvedValue({
+ previousSessionId: "known-root",
+ status: "reset",
+ });
+
+ const outcome = await executeTask({
+ client: new Client({ host: target.url }),
+ target,
+ evaluation: createTestEval((t) => {
+ t.target.watchTurn("known-root");
+ throw new Error("eval failed");
+ }, "failure-with-timeout-configured"),
+ timeoutMs: 1_000,
+ });
+
+ expect(outcome.error).toBe("eval failed");
+ expect(reset).not.toHaveBeenCalled();
+ });
+
+ it("preserves the timeout verdict and appends cleanup failures", async () => {
+ vi.spyOn(ClientSession.prototype, "reset").mockRejectedValue(new Error("cleanup exploded"));
+
+ const outcome = await executeTask({
+ client: new Client({ host: target.url }),
+ target,
+ evaluation: createTestEval(async (t) => {
+ t.target.watchTurn("known-root");
+ await new Promise<void>(() => {});
+ }, "timeout-cleanup-failure"),
+ timeoutMs: 1,
+ });
+
+ expect(outcome.error).toMatch(/timed out|timeout/i);
+ expect(outcome.error).toContain("Eval timeout cleanup failed: cleanup exploded");
+ });
+
it("exposes a sleep helper with a one-second default", async () => {
vi.useFakeTimers();
let settled = false;
diff --git a/packages/eve/src/evals/runner/execute-task.ts b/packages/eve/src/evals/runner/execute-task.ts
index 9f52bc2f8..c6823a6d0 100644
--- a/packages/eve/src/evals/runner/execute-task.ts
+++ b/packages/eve/src/evals/runner/execute-task.ts
@@ -18,6 +18,8 @@ import { scopeEvalTargetHandle } from "#evals/target.js";
import { AssertionCollector } from "#evals/assertions/collector.js";
import { EvalRequirementFailed, EvalSkipped } from "#evals/control-flow.js";
+const EVAL_TIMEOUT_CLEANUP_TIMEOUT_MS = 5_000;
+
/**
* Options for executing one eval's task.
*/
@@ -88,6 +90,19 @@ export async function executeTask(options: ExecuteTaskOptions): Promise<ExecuteT
}
}
+ if (timeoutMs !== undefined && signal.aborted) {
+ const cleanupResults = await manager.cleanup(
+ AbortSignal.timeout(EVAL_TIMEOUT_CLEANUP_TIMEOUT_MS),
+ );
+ const cleanupErrors = cleanupResults.flatMap((result) =>
+ result.status === "rejected" ? [toErrorMessage(result.reason)] : [],
+ );
+ if (cleanupErrors.length > 0) {
+ const cleanupDetail = `Eval timeout cleanup failed: ${cleanupErrors.join("; ")}`;
+ error = error === undefined ? cleanupDetail : `${error}\n${cleanupDetail}`;
+ }
+ }
+
const result = buildTaskResult({
logs,
sessions: manager.snapshots(),
diff --git a/packages/eve/src/evals/session-cleanup.ts b/packages/eve/src/evals/session-cleanup.ts
new file mode 100644
index 000000000..d55e5bbbc
--- /dev/null
+++ b/packages/eve/src/evals/session-cleanup.ts
@@ -0,0 +1,19 @@
+interface CleanupSession {
+ readonly sessionId: string | undefined;
+ cleanup(signal: AbortSignal): Promise<void>;
+}
+
+/** Settles each distinct eval-owned root once. */
+export async function cleanupEvalSessions(
+ sessions: readonly CleanupSession[],
+ signal: AbortSignal,
+): Promise<readonly PromiseSettledResult<void>[]> {
+ const known = new Map<string, CleanupSession>();
+ for (const session of sessions) {
+ const sessionId = session.sessionId;
+ if (sessionId !== undefined && !known.has(sessionId)) known.set(sessionId, session);
+ }
+ return await Promise.allSettled(
+ [...known.values()].map(async (session) => await session.cleanup(signal)),
+ );
+}
diff --git a/packages/eve/src/evals/session.ts b/packages/eve/src/evals/session.ts
index cff1e05e4..3928529e7 100644
--- a/packages/eve/src/evals/session.ts
+++ b/packages/eve/src/evals/session.ts
@@ -21,6 +21,7 @@ import { summarizeTurnEvents } from "#client/session-utils.js";
import { extractCompletedResult } from "#client/output-schema.js";
import type { InputRequest, InputResponse } from "#shared/input.js";
import { deriveRunFacts } from "#evals/runner/derive-run-facts.js";
+import { cleanupEvalSessions } from "#evals/session-cleanup.js";
import { formatEvalTranscript, inferMediaType } from "#evals/session-content.js";
import { AssertionCollector } from "#evals/assertions/collector.js";
import { createOutputAssertions, createScopedAssertions } from "#evals/assertions/scoped.js";
@@ -141,6 +142,12 @@ export class EvalSessionDriver implements EveEvalSession {
return await this.#session.cancel();
}
+ /** @internal */
+ async cleanup(signal: AbortSignal): Promise<void> {
+ if (this.#session === undefined) return;
+ await this.#session.reset({ reason: "Eval timed out", signal });
+ }
+
requireInputRequest(filter: EveEvalInputRequestMatchOptions = {}): InputRequest {
if (this.#pendingInputRequests.length === 0) {
this.#failRequirement(
@@ -616,6 +623,10 @@ export class EvalSessionManager {
hasActivity(): boolean {
return this.#sessions.length > 0;
}
+ /** @internal */
+ async cleanup(signal: AbortSignal): Promise<readonly PromiseSettledResult<void>[]> {
+ return await cleanupEvalSessions(this.#sessions, signal);
+ }
#createSession(primary: boolean): EvalSessionDriver {
const session = new EvalSessionDriver({
diff --git a/packages/eve/src/eve-channel/index.ts b/packages/eve/src/eve-channel/index.ts
index 6ca9497bd..e5b41ab91 100644
--- a/packages/eve/src/eve-channel/index.ts
+++ b/packages/eve/src/eve-channel/index.ts
@@ -380,6 +380,7 @@ export function eveChannel(input: EveChannelInput): EveChannel {
try {
result = await attachSession(sessionId).cancel({
taskId: body.taskId,
+ tasks: body.tasks,
turnId: body.turnId,
});
} catch (error) {
diff --git a/packages/eve/src/eve-channel/request.cancel.test.ts b/packages/eve/src/eve-channel/request.cancel.test.ts
new file mode 100644
index 000000000..a6cb499cc
--- /dev/null
+++ b/packages/eve/src/eve-channel/request.cancel.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from "vitest";
+
+import { parseCancelTurnBody } from "#eve-channel/request.js";
+
+describe("parseCancelTurnBody", () => {
+ it("parses session-owned task cancellation", async () => {
+ const result = await parseCancelTurnBody(
+ new Request("https://eve.test/eve/v1/session/session_1/cancel", {
+ body: JSON.stringify({ tasks: true, turnId: "turn_1" }),
+ method: "POST",
+ }),
+ );
+
+ expect(result).toEqual({ tasks: true, turnId: "turn_1" });
+ });
+
+ it.each([null, 1, "true", []])("rejects a non-boolean tasks value %o", async (tasks) => {
+ const result = await parseCancelTurnBody(
+ new Request("https://eve.test/eve/v1/session/session_1/cancel", {
+ body: JSON.stringify({ tasks }),
+ method: "POST",
+ }),
+ );
+
+ expect(result).toBeInstanceOf(Response);
+ if (!(result instanceof Response)) return;
+ expect(result.status).toBe(400);
+ await expect(result.json()).resolves.toEqual({
+ error: "Expected 'tasks' to be a boolean.",
+ ok: false,
+ });
+ });
+});
diff --git a/packages/eve/src/eve-channel/request.ts b/packages/eve/src/eve-channel/request.ts
index 2499e2873..6a525949a 100644
--- a/packages/eve/src/eve-channel/request.ts
+++ b/packages/eve/src/eve-channel/request.ts
@@ -188,6 +188,7 @@ export function parseSessionMessageBody(
interface ParsedCancelTurnBody {
taskId?: string;
+ tasks?: boolean;
turnId?: string;
}
@@ -199,12 +200,19 @@ export async function parseCancelTurnBody(req: Request): Promise<ParsedCancelTur
const turnId = payload.turnId;
const taskId = payload.taskId;
+ const tasks = payload.tasks;
if (turnId !== undefined && (typeof turnId !== "string" || turnId.length === 0)) {
return Response.json(
{ error: "Expected 'turnId' to be a non-empty string.", ok: false },
{ status: 400 },
);
}
+ if (tasks !== undefined && typeof tasks !== "boolean") {
+ return Response.json(
+ { error: "Expected 'tasks' to be a boolean.", ok: false },
+ { status: 400 },
+ );
+ }
if (taskId !== undefined && (typeof taskId !== "string" || taskId.length === 0)) {
return Response.json(
{ error: "Expected 'taskId' to be a non-empty string.", ok: false },
@@ -213,6 +221,7 @@ export async function parseCancelTurnBody(req: Request): Promise<ParsedCancelTur
}
const result: ParsedCancelTurnBody = {};
if (typeof taskId === "string") result.taskId = taskId;
+ if (typeof tasks === "boolean") result.tasks = tasks;
if (typeof turnId === "string") result.turnId = turnId;
return result;
}
diff --git a/packages/eve/src/execution/cancel-indexed-session-tasks-step.test.ts b/packages/eve/src/execution/cancel-indexed-session-tasks-step.test.ts
new file mode 100644
index 000000000..72440edfd
--- /dev/null
+++ b/packages/eve/src/execution/cancel-indexed-session-tasks-step.test.ts
@@ -0,0 +1,93 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { DurableSessionState } from "#execution/durable-session-store.js";
+import { cancelAllIndexedSessionTasksStep } from "#execution/cancel-indexed-session-tasks-step.js";
+import { SESSION_TASKS_STATE_KEY, type SessionTaskIndexEntry } from "#tasks/session-index.js";
+
+const { cancelOwnedTaskMock, deserializeContextMock, hydrateDurableSessionMock } = vi.hoisted(
+ () => ({
+ cancelOwnedTaskMock: vi.fn(),
+ deserializeContextMock: vi.fn(),
+ hydrateDurableSessionMock: vi.fn(),
+ }),
+);
+
+vi.mock("#context/serialize.js", () => ({ deserializeContext: deserializeContextMock }));
+vi.mock("#execution/effective-agent-config.js", () => ({
+ resolveEffectiveAgentRuntime: vi.fn(() => ({ turnAgent: "turn-agent" })),
+}));
+vi.mock("#execution/session.js", () => ({ hydrateDurableSession: hydrateDurableSessionMock }));
+vi.mock("#execution/tasks/parent/dispatch.js", () => ({ cancelOwnedTask: cancelOwnedTaskMock }));
+
+describe("cancelAllIndexedSessionTasksStep", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ cancelOwnedTaskMock.mockResolvedValue(undefined);
+ deserializeContextMock.mockResolvedValue({ require: vi.fn(() => "bundle") });
+ hydrateDurableSessionMock.mockReturnValue("runtime-session");
+ });
+
+ it("cancels every indexed task sequentially with the hydrated parent session", async () => {
+ const task1 = indexedTask("task-1");
+ const task2 = indexedTask("task-2");
+
+ await cancelAllIndexedSessionTasksStep({
+ serializedContext: { context: "latest" },
+ sessionState: makeSessionState([task1, task2]),
+ });
+
+ expect(cancelOwnedTaskMock).toHaveBeenCalledTimes(2);
+ expect(cancelOwnedTaskMock).toHaveBeenNthCalledWith(1, {
+ cancelOwnedWork: expect.any(Function),
+ entry: task1,
+ serializedContext: { context: "latest" },
+ session: "runtime-session",
+ });
+ expect(cancelOwnedTaskMock).toHaveBeenNthCalledWith(2, {
+ cancelOwnedWork: expect.any(Function),
+ entry: task2,
+ serializedContext: { context: "latest" },
+ session: "runtime-session",
+ });
+ });
+
+ it("does not require runtime context when no tasks are indexed", async () => {
+ await expect(
+ cancelAllIndexedSessionTasksStep({ sessionState: makeSessionState([]) }),
+ ).resolves.toBeUndefined();
+
+ expect(deserializeContextMock).not.toHaveBeenCalled();
+ expect(cancelOwnedTaskMock).not.toHaveBeenCalled();
+ });
+});
+
+function indexedTask(taskId: string): SessionTaskIndexEntry {
+ return {
+ createdByTurnId: "turn_0",
+ executor: { data: {}, kind: "workflow" },
+ metadata: { kind: "tool", name: "research" },
+ taskId,
+ taskInboxToken: `${taskId}-inbox`,
+ taskRunId: `${taskId}-run`,
+ };
+}
+
+function makeSessionState(tasks: readonly SessionTaskIndexEntry[]): DurableSessionState {
+ return {
+ continuationToken: "http:test",
+ emissionState: { sequence: 0, sessionStarted: false, stepIndex: 0, turnId: "" },
+ hasProxyInputRequests: false,
+ sessionId: "parent-session",
+ snapshot: {
+ session: {
+ agent: { system: "" },
+ continuationToken: "http:test",
+ history: [],
+ sessionId: "parent-session",
+ state: { [SESSION_TASKS_STATE_KEY]: { tasks, version: 2 } },
+ },
+ version: 1,
+ },
+ version: 1,
+ };
+}
diff --git a/packages/eve/src/execution/cancel-indexed-session-tasks-step.ts b/packages/eve/src/execution/cancel-indexed-session-tasks-step.ts
new file mode 100644
index 000000000..eba709863
--- /dev/null
+++ b/packages/eve/src/execution/cancel-indexed-session-tasks-step.ts
@@ -0,0 +1,67 @@
+import { deserializeContext } from "#context/serialize.js";
+import { readDurableSession, type DurableSessionState } from "#execution/durable-session-store.js";
+import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
+import { hydrateDurableSession } from "#execution/session.js";
+import { cancelOwnedTask } from "#execution/tasks/parent/dispatch.js";
+import { cancelBackgroundAgentTask } from "#execution/tools/subagent/task-cancel.js";
+import { createLogger, logError } from "#internal/logging.js";
+import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
+import { getSessionTaskIndex } from "#tasks/session-index.js";
+
+const log = createLogger("execution.cancel-indexed-session-tasks");
+
+/** Cooperatively cancels every task currently indexed by a durable session. */
+export async function cancelAllIndexedSessionTasksStep(input: {
+ readonly serializedContext?: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+}): Promise<void> {
+ "use step";
+
+ let durable;
+ try {
+ durable = await readDurableSession(input.sessionState);
+ } catch (error) {
+ logError(log, "failed to read the session for indexed task cancellation", error, {
+ parentSessionId: input.sessionState.sessionId,
+ });
+ return;
+ }
+
+ let entries;
+ try {
+ entries = getSessionTaskIndex(durable.state);
+ } catch (error) {
+ logError(log, "failed to read the task index", error, {
+ parentSessionId: durable.sessionId,
+ });
+ return;
+ }
+ if (entries.length === 0) return;
+ if (input.serializedContext === undefined) {
+ throw new Error("Indexed task cancellation requires serialized runtime context.");
+ }
+
+ const ctx = await deserializeContext(input.serializedContext);
+ const bundle = ctx.require(BundleKey);
+ const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);
+ const session = hydrateDurableSession({
+ durable,
+ turnAgent: effectiveAgent.turnAgent,
+ });
+
+ for (const entry of entries) {
+ try {
+ await cancelOwnedTask({
+ cancelOwnedWork: cancelBackgroundAgentTask,
+ entry,
+ serializedContext: input.serializedContext,
+ session,
+ });
+ } catch (error) {
+ logError(log, "failed to cancel indexed task", error, {
+ parentSessionId: durable.sessionId,
+ taskId: entry.taskId,
+ });
+ }
+ }
+}
diff --git a/packages/eve/src/execution/inline-turn.ts b/packages/eve/src/execution/inline-turn.ts
index ed89d2ea1..ddb7e4621 100644
--- a/packages/eve/src/execution/inline-turn.ts
+++ b/packages/eve/src/execution/inline-turn.ts
@@ -1,5 +1,6 @@
import type { DeliverHookPayload, HookPayload, SessionCapabilities } from "#channel/types.js";
import { readAcceptedDeploymentId } from "#execution/accepted-delivery-deployment.js";
+import { cancelAllIndexedSessionTasksStep } from "#execution/cancel-indexed-session-tasks-step.js";
import type {
InitialTurnStep,
TurnStepPayload,
@@ -41,10 +42,17 @@ export async function runInlineTurn(input: {
readonly seenTaskDeliveries?: Set<string>;
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
+ readonly stateCursor?: SessionStateCursor;
}): Promise<InlineTurnOutcome> {
const acceptedDeploymentId = readAcceptedDeploymentId(input.delivery);
if (acceptedDeploymentId === undefined) return { kind: "child" };
+ const cursor =
+ input.stateCursor ??
+ new SessionStateCursor({
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
+ });
const control = new InlineTurnControl({
bufferedDeliveries: input.bufferedDeliveries,
bufferedSessionControls: input.bufferedSessionControls,
@@ -52,10 +60,7 @@ export async function runInlineTurn(input: {
commandInbox: input.commandInbox,
expectedTurnId: activeTurnId(input.sessionState.emissionState),
seenTaskDeliveries: input.seenTaskDeliveries,
- });
- const cursor = new SessionStateCursor({
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
+ stateCursor: cursor,
});
let nextStepInput: TurnStepPayload | undefined = input.delivery;
@@ -160,6 +165,7 @@ class InlineTurnControl {
private readonly controller = new AbortController();
private readonly expectedTurnId: string;
private readonly seenTaskDeliveries: Set<string>;
+ private readonly stateCursor: SessionStateCursor;
private cancellation: TurnCancelPayload | undefined;
constructor(input: {
@@ -169,6 +175,7 @@ class InlineTurnControl {
readonly commandInbox: SessionCommandInbox;
readonly expectedTurnId: string;
readonly seenTaskDeliveries?: Set<string>;
+ readonly stateCursor: SessionStateCursor;
}) {
this.bufferedDeliveries = input.bufferedDeliveries;
this.bufferedSessionControls = input.bufferedSessionControls;
@@ -176,6 +183,7 @@ class InlineTurnControl {
this.commandInbox = input.commandInbox;
this.expectedTurnId = input.expectedTurnId;
this.seenTaskDeliveries = input.seenTaskDeliveries ?? new Set();
+ this.stateCursor = input.stateCursor;
}
get initialCancellation(): TurnCancelPayload | undefined {
@@ -248,6 +256,12 @@ class InlineTurnControl {
return;
}
if (command.kind === "cancel") {
+ if ("tasks" in command && command.tasks === true) {
+ await cancelAllIndexedSessionTasksStep({
+ serializedContext: this.stateCursor.serializedContext,
+ sessionState: this.stateCursor.sessionState,
+ });
+ }
if (command.taskId !== undefined) this.discardTaskDeliveries(command.taskId);
const turnId =
command.taskId !== undefined &&
@@ -256,7 +270,9 @@ class InlineTurnControl {
? undefined
: command.turnId;
if (turnId === undefined || turnId === this.expectedTurnId) {
- this.abort(turnId === undefined ? {} : { turnId });
+ const payload =
+ turnId === undefined ? { tasks: command.tasks } : { tasks: command.tasks, turnId };
+ this.abort(payload);
}
}
}
diff --git a/packages/eve/src/execution/parked-delivery-wait.test.ts b/packages/eve/src/execution/parked-delivery-wait.test.ts
index e768021f2..4200a647e 100644
--- a/packages/eve/src/execution/parked-delivery-wait.test.ts
+++ b/packages/eve/src/execution/parked-delivery-wait.test.ts
@@ -14,6 +14,11 @@ import { SessionStateCursor } from "#execution/session-state-cursor.js";
vi.mock("./route-child-delivery.js", () => ({
routeDeliverToChildren: vi.fn(),
}));
+vi.mock("./cancel-indexed-session-tasks-step.js", () => ({
+ cancelAllIndexedSessionTasksStep: vi.fn(),
+}));
+
+import { cancelAllIndexedSessionTasksStep } from "#execution/cancel-indexed-session-tasks-step.js";
interface ScriptedRead {
readonly result: IteratorResult<SessionInboxPayload>;
@@ -77,9 +82,9 @@ function authorizationRead(): ScriptedRead {
};
}
-function cancelRead(): ScriptedRead {
+function cancelRead(command: Record<string, unknown> = {}): ScriptedRead {
return {
- result: { done: false, value: { kind: "cancel" } },
+ result: { done: false, value: { kind: "cancel", ...command } },
source: "session",
};
}
@@ -123,6 +128,19 @@ describe("nextTurnDelivery", () => {
expect(inbox.windowTransitions).toEqual([true, false]);
});
+ it("cancels indexed tasks and keeps waiting for ordinary parked activity", async () => {
+ const inbox = createMockInbox([cancelRead({ tasks: true }), authorizationRead()]);
+ const input = waitInput(inbox);
+
+ const next = await nextTurnDelivery(input);
+
+ expect(next.kind).toBe("authorization");
+ expect(cancelAllIndexedSessionTasksStep).toHaveBeenCalledWith({
+ serializedContext: input.stateCursor.serializedContext,
+ sessionState: input.stateCursor.sessionState,
+ });
+ });
+
it("keeps the authorization window open across a consumed no-op cancel", async () => {
// A cancel with no active turn is consumed without producing a parent
// turn; the wait continues and the callback must still surface within
diff --git a/packages/eve/src/execution/parked-delivery-wait.ts b/packages/eve/src/execution/parked-delivery-wait.ts
index 070388f4a..6389215fb 100644
--- a/packages/eve/src/execution/parked-delivery-wait.ts
+++ b/packages/eve/src/execution/parked-delivery-wait.ts
@@ -1,4 +1,5 @@
import type { DeliverHookPayload, DeliverPayload } from "#channel/types.js";
+import { cancelAllIndexedSessionTasksStep } from "#execution/cancel-indexed-session-tasks-step.js";
import { routeDeliverToChildren } from "#execution/route-child-delivery.js";
import type { SessionCommandInbox } from "#execution/session-command-inbox.js";
import type { SessionStateCursor } from "#execution/session-state-cursor.js";
@@ -102,6 +103,7 @@ async function awaitNextTurnDelivery(input: {
commandInbox: input.commandInbox,
deferDeliveries: input.deferDeliveries,
seenTaskDeliveries,
+ stateCursor: input.stateCursor,
});
if (nextAction.kind === "authorization") {
@@ -145,6 +147,7 @@ async function waitForNextSessionAction(input: {
readonly commandInbox: SessionCommandInbox;
readonly deferDeliveries?: boolean;
readonly seenTaskDeliveries: Set<string>;
+ readonly stateCursor: SessionStateCursor;
}): Promise<NextSessionAction> {
const pendingSessionControl = input.bufferedSessionControls.shift();
if (pendingSessionControl !== undefined) {
@@ -214,6 +217,12 @@ async function waitForNextSessionAction(input: {
}
if (decoded.kind === "cancel") {
+ if ("tasks" in decoded && decoded.tasks === true) {
+ await cancelAllIndexedSessionTasksStep({
+ serializedContext: input.stateCursor.serializedContext,
+ sessionState: input.stateCursor.sessionState,
+ });
+ }
if (decoded.taskId !== undefined) {
input.cancelledTaskIds.add(decoded.taskId);
const kept = input.bufferedDeliveries.filter(
diff --git a/packages/eve/src/execution/session-command-inbox.test.ts b/packages/eve/src/execution/session-command-inbox.test.ts
index 021deb5af..d105dafae 100644
--- a/packages/eve/src/execution/session-command-inbox.test.ts
+++ b/packages/eve/src/execution/session-command-inbox.test.ts
@@ -123,7 +123,7 @@ describe("createSessionCommandInbox", () => {
);
expect(createHookMock).toHaveBeenCalledOnce();
expect(createHookMock).toHaveBeenCalledWith({
- metadata: { sessionInboxWireVersion: 5 },
+ metadata: { sessionInboxWireVersion: 6 },
token: "stable",
});
await inbox.dispose();
diff --git a/packages/eve/src/execution/terminate-child-sessions-step.test.ts b/packages/eve/src/execution/terminate-child-sessions-step.test.ts
index 4b7399a59..67d9090a5 100644
--- a/packages/eve/src/execution/terminate-child-sessions-step.test.ts
+++ b/packages/eve/src/execution/terminate-child-sessions-step.test.ts
@@ -313,7 +313,7 @@ describe("terminateChildSessionsStep", () => {
cancelReason: "Parent session ended",
});
expect(errorSpy).toHaveBeenCalledWith(
- "[eve:execution.terminate-child-sessions] failed to cancel task during parent finalization",
+ "[eve:execution.cancel-indexed-session-tasks] failed to cancel indexed task",
expect.objectContaining({
parentSessionId: "parent-session",
taskId: "task-1",
diff --git a/packages/eve/src/execution/terminate-child-sessions-step.ts b/packages/eve/src/execution/terminate-child-sessions-step.ts
index 1c920cb80..32dc7093c 100644
--- a/packages/eve/src/execution/terminate-child-sessions-step.ts
+++ b/packages/eve/src/execution/terminate-child-sessions-step.ts
@@ -1,20 +1,16 @@
import { deserializeContext } from "#context/serialize.js";
import type { ContextContainer } from "#context/container.js";
import { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";
+import { cancelAllIndexedSessionTasksStep } from "#execution/cancel-indexed-session-tasks-step.js";
import { readDurableSession, type DurableSessionState } from "#execution/durable-session-store.js";
-import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
-import { hydrateDurableSession } from "#execution/session.js";
import {
resetRemoteAgentSession,
resolveRemoteAgentForAction,
resolveRemoteAgentStreamHeaders,
} from "#subagents/remote-dispatch.js";
-import { cancelOwnedTask } from "#execution/tasks/parent/dispatch.js";
-import { cancelBackgroundAgentTask } from "#execution/tools/subagent/task-cancel.js";
import { getAgentHandleStore } from "#subagents/handles/store.js";
import { createLogger, logError } from "#internal/logging.js";
import { cancelRun, getWorld } from "#internal/workflow/runtime.js";
-import { getSessionTaskIndex } from "#tasks/session-index.js";
import { BundleKey, type CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
const log = createLogger("execution.terminate-child-sessions");
@@ -45,12 +41,6 @@ export async function terminateChildSessionsStep(input: {
return;
}
- // Cooperatively cancel live tasks first: their runs are the single
- // writers for task state, and committing `cancelled` before the child
- // terminations below means no child termination can race a completion
- // into an ended parent. Already-terminal tasks report `unreachable`,
- // which is the expected no-op.
- const taskEntries = readSessionTaskIndex(session.state, session.sessionId);
const handles = getAgentHandleStore(session.state)?.handles ?? [];
const hasRemoteHandle = handles.some(
(handle) => "address" in handle && handle.address.kind === "agent/remote",
@@ -61,36 +51,19 @@ export async function terminateChildSessionsStep(input: {
readonly ctx: ContextContainer;
}
| undefined;
- if (taskEntries.length > 0 || hasRemoteHandle) {
+ // Cooperatively cancel live tasks first: their runs are the single writers
+ // for task state, so child termination cannot race completion into an ended parent.
+ await cancelAllIndexedSessionTasksStep({
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
+ });
+ if (hasRemoteHandle) {
if (input.serializedContext === undefined) {
throw new Error("Child finalization requires serialized runtime context.");
}
const ctx = await deserializeContext(input.serializedContext);
runtimeContext = { bundle: ctx.require(BundleKey), ctx };
}
- if (taskEntries.length > 0) {
- const { bundle, ctx } = runtimeContext!;
- const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);
- const runtimeSession = hydrateDurableSession({
- durable: session,
- turnAgent: effectiveAgent.turnAgent,
- });
- for (const entry of taskEntries) {
- try {
- await cancelOwnedTask({
- cancelOwnedWork: cancelBackgroundAgentTask,
- entry,
- serializedContext: input.serializedContext,
- session: runtimeSession,
- });
- } catch (error) {
- logError(log, "failed to cancel task during parent finalization", error, {
- parentSessionId: session.sessionId,
- taskId: entry.taskId,
- });
- }
- }
- }
if (handles.length === 0) {
return;
@@ -159,17 +132,3 @@ export async function terminateChildSessionsStep(input: {
}
}
}
-
-function readSessionTaskIndex(
- state: Parameters<typeof getSessionTaskIndex>[0],
- parentSessionId: string,
-): ReturnType<typeof getSessionTaskIndex> {
- try {
- return getSessionTaskIndex(state);
- } catch (error) {
- logError(log, "failed to read the task index during parent finalization", error, {
- parentSessionId,
- });
- return [];
- }
-}
diff --git a/packages/eve/src/execution/turn-cancellation-control.ts b/packages/eve/src/execution/turn-cancellation-control.ts
index 7b55768db..3c792d6a5 100644
--- a/packages/eve/src/execution/turn-cancellation-control.ts
+++ b/packages/eve/src/execution/turn-cancellation-control.ts
@@ -21,6 +21,7 @@ export interface TurnCancellationControl {
* the signal aborted. Race it against turn-owned awaits — never
* `await` it alone.
*/
+ readonly payload: Promise<TurnCancelPayload>;
readonly requested: Promise<"cancel">;
/** Disposes the hook, abandoning any outstanding read. Idempotent. */
dispose(): Promise<void>;
@@ -61,14 +62,15 @@ export async function createTurnCancellationControl(input: {
input.initialPayload !== undefined &&
matchesActiveTurn(input.initialPayload, input.expectedTurnId);
if (initiallyCancelled) abort();
- const requested = initiallyCancelled
- ? Promise.resolve("cancel" as const)
- : consumeMatchingCancel(iterator, input.expectedTurnId, abort).then(() => "cancel" as const);
+ const payload = initiallyCancelled
+ ? Promise.resolve(input.initialPayload!)
+ : consumeMatchingCancel(iterator, input.expectedTurnId, abort);
let disposed = false;
return {
+ payload,
signal: controller.signal,
- requested,
+ requested: payload.then(() => "cancel" as const),
async dispose(): Promise<void> {
if (disposed) return;
disposed = true;
@@ -86,13 +88,13 @@ async function consumeMatchingCancel(
iterator: AsyncIterator<TurnCancelPayload>,
expectedTurnId: string,
onCancel: () => void,
-): Promise<void> {
+): Promise<TurnCancelPayload> {
while (true) {
const next = await iterator.next();
if (next.done) return await new Promise<never>(() => {});
if (matchesActiveTurn(next.value, expectedTurnId)) {
onCancel();
- return;
+ return next.value;
}
}
}
diff --git a/packages/eve/src/execution/turn-cancellation-token.ts b/packages/eve/src/execution/turn-cancellation-token.ts
index 0ebc9b2bf..33cddf0f4 100644
--- a/packages/eve/src/execution/turn-cancellation-token.ts
+++ b/packages/eve/src/execution/turn-cancellation-token.ts
@@ -8,5 +8,6 @@ export function turnCancellationHookToken(controlToken: string): string {
* benign no-op; omitting it targets whichever turn owns the hook.
*/
export interface TurnCancelPayload {
+ readonly tasks?: boolean;
readonly turnId?: string;
}
diff --git a/packages/eve/src/execution/turn-control-receiver.test.ts b/packages/eve/src/execution/turn-control-receiver.test.ts
index efa044880..1fa278881 100644
--- a/packages/eve/src/execution/turn-control-receiver.test.ts
+++ b/packages/eve/src/execution/turn-control-receiver.test.ts
@@ -2,6 +2,8 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import type { DeliverHookPayload } from "#channel/types.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
+import { cancelAllIndexedSessionTasksStep } from "#execution/cancel-indexed-session-tasks-step.js";
+import { SessionStateCursor } from "#execution/session-state-cursor.js";
import { forwardTurnCancellationStep } from "#execution/forward-turn-cancellation-step.js";
import { forwardTurnDeliveryStep } from "#execution/forward-turn-delivery-step.js";
import { reportDroppedWirePayloadStep } from "#execution/report-dropped-wire-payload-step.js";
@@ -15,6 +17,10 @@ vi.mock("#compiled/@workflow/core/index.js", () => ({
createHook: (...args: unknown[]) => createHookMock(...args),
}));
+vi.mock("./cancel-indexed-session-tasks-step.js", () => ({
+ cancelAllIndexedSessionTasksStep: vi.fn(),
+}));
+
vi.mock("./forward-turn-delivery-step.js", () => ({
forwardTurnDeliveryStep: vi.fn(),
}));
@@ -250,6 +256,23 @@ describe("TurnControlReceiver", () => {
]);
});
+ it("cancels indexed tasks and preserves active turn cancellation", async () => {
+ installControlHook([parkResult()], true);
+
+ await runReceiver([], {
+ commandInbox: createCommandInbox([{ kind: "cancel", tasks: true } as never]),
+ });
+
+ expect(cancelAllIndexedSessionTasksStep).toHaveBeenCalledWith({
+ serializedContext: {},
+ sessionState: expect.objectContaining({ sessionId: "session" }),
+ });
+ expect(forwardTurnCancellationStep).toHaveBeenCalledWith({
+ payload: { tasks: true },
+ token: "turn-control:cancel",
+ });
+ });
+
it("forwards cancel and reset through the active turn's private hook", async () => {
installControlHook([parkResult()], true);
const bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset"> = [];
@@ -289,6 +312,7 @@ function runReceiver(
commandInbox: options.commandInbox ?? createCommandInbox(),
expectedTurnId: "turn_0",
seenTaskDeliveries: options.seenTaskDeliveries,
+ stateCursor: new SessionStateCursor({ serializedContext: {}, sessionState: createState() }),
token: "turn-control",
});
return receiver.waitForAction().finally(() => receiver.dispose());
diff --git a/packages/eve/src/execution/turn-control-receiver.ts b/packages/eve/src/execution/turn-control-receiver.ts
index 0b6c3c12a..653158781 100644
--- a/packages/eve/src/execution/turn-control-receiver.ts
+++ b/packages/eve/src/execution/turn-control-receiver.ts
@@ -1,12 +1,14 @@
import { createHook, type Hook } from "#compiled/@workflow/core/index.js";
import type { DeliverHookPayload } from "#channel/types.js";
+import { cancelAllIndexedSessionTasksStep } from "#execution/cancel-indexed-session-tasks-step.js";
import { forwardTurnCancellationStep } from "#execution/forward-turn-cancellation-step.js";
import type { TurnControlPayload } from "#execution/turn-control-protocol.js";
import { forwardTurnDeliveryStep } from "#execution/forward-turn-delivery-step.js";
import { closeHookIterator, disposeHook } from "#execution/hook-ownership.js";
import type { NextDriverAction } from "#execution/next-driver-action.js";
import type { SessionCommandInbox } from "#execution/session-command-inbox.js";
+import type { SessionStateCursor } from "#execution/session-state-cursor.js";
import { turnCancellationHookToken } from "#execution/turn-cancellation-token.js";
import { reportDroppedWirePayloadStep } from "#execution/report-dropped-wire-payload-step.js";
import {
@@ -30,6 +32,7 @@ export class TurnControlReceiver {
private readonly expectedTurnId: string;
private readonly cancelledTaskIds: Set<string>;
private readonly seenTaskDeliveries: Set<string>;
+ private readonly stateCursor: SessionStateCursor;
private pendingControl: Promise<IteratorResult<TurnControlPayload>> | null = null;
constructor(input: {
@@ -39,6 +42,7 @@ export class TurnControlReceiver {
readonly commandInbox: SessionCommandInbox;
readonly expectedTurnId: string;
readonly seenTaskDeliveries?: Set<string>;
+ readonly stateCursor: SessionStateCursor;
readonly token: string;
}) {
this.bufferedDeliveries = input.bufferedDeliveries;
@@ -46,6 +50,7 @@ export class TurnControlReceiver {
this.cancelledTaskIds = input.cancelledTaskIds ?? new Set();
this.commandInbox = input.commandInbox;
this.seenTaskDeliveries = input.seenTaskDeliveries ?? new Set();
+ this.stateCursor = input.stateCursor;
this.control = createHook<TurnControlPayload>({ token: input.token });
this.controlIterator = this.control[Symbol.asyncIterator]();
this.expectedTurnId = input.expectedTurnId;
@@ -100,6 +105,12 @@ export class TurnControlReceiver {
return undefined;
}
if (command.kind === "cancel") {
+ if ("tasks" in command && command.tasks === true) {
+ await cancelAllIndexedSessionTasksStep({
+ serializedContext: this.stateCursor.serializedContext,
+ sessionState: this.stateCursor.sessionState,
+ });
+ }
if (command.taskId !== undefined) this.discardTaskDeliveries(command.taskId);
const turnId =
command.taskId !== undefined &&
@@ -107,8 +118,10 @@ export class TurnControlReceiver {
command.turnId !== this.expectedTurnId
? undefined
: command.turnId;
+ const payload: { tasks?: boolean; turnId?: string } = { tasks: command.tasks };
+ if (turnId !== undefined) payload.turnId = turnId;
await forwardTurnCancellationStep({
- payload: turnId === undefined ? {} : { turnId },
+ payload,
token: turnCancellationHookToken(this.control.token),
});
return undefined;
diff --git a/packages/eve/src/execution/turn-dispatch.test.ts b/packages/eve/src/execution/turn-dispatch.test.ts
index d0ed8926d..b4ded7fde 100644
--- a/packages/eve/src/execution/turn-dispatch.test.ts
+++ b/packages/eve/src/execution/turn-dispatch.test.ts
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import type { DeliverHookPayload } from "#channel/types.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
+import { cancelAllIndexedSessionTasksStep } from "#execution/cancel-indexed-session-tasks-step.js";
import { dispatchTurnStep } from "#execution/dispatch-turn-step.js";
import { forwardTurnDeliveryStep } from "#execution/forward-turn-delivery-step.js";
import { dispatchAndAwaitTurn } from "#execution/turn-dispatch.js";
@@ -15,6 +16,10 @@ vi.mock("#compiled/@workflow/core/index.js", () => ({
createHook: (...args: unknown[]) => createHookMock(...args),
}));
+vi.mock("./cancel-indexed-session-tasks-step.js", () => ({
+ cancelAllIndexedSessionTasksStep: vi.fn(),
+}));
+
vi.mock("./dispatch-turn-step.js", () => ({
dispatchTurnStep: vi.fn(async () => ({ runId: "turn-run" })),
}));
@@ -264,6 +269,54 @@ describe("dispatchAndAwaitTurn", () => {
expect(createHookMock).not.toHaveBeenCalled();
});
+ it("cancels indexed tasks from an inline turn and preserves turn cancellation", async () => {
+ const state = createState("http:test");
+ vi.mocked(turnStep).mockImplementation(async ({ abortSignal }) => {
+ await new Promise<void>((resolve) => abortSignal?.addEventListener("abort", () => resolve()));
+ return {
+ action: "cancelled",
+ serializedContext: { state: "cancelled" },
+ sessionState: state,
+ };
+ });
+ let delivered = false;
+ const commandInbox = createCommandInbox({
+ next: vi.fn(async () => {
+ if (!delivered) {
+ delivered = true;
+ return { done: false as const, value: { kind: "cancel", tasks: true } as never };
+ }
+ return await new Promise<IteratorResult<SessionInboxPayload>>(() => {});
+ }),
+ });
+ installControlHook([
+ {
+ action: { cancelled: true, kind: "park", serializedContext: {}, sessionState: state },
+ kind: "turn-result",
+ },
+ ]);
+
+ await dispatchAndAwaitTurn({
+ bufferedDeliveries: [],
+ bufferedSessionControls: [],
+ commandInbox,
+ controlToken: "turn-control",
+ delivery: createAcceptedDelivery(),
+ mode: "conversation",
+ parentWritable: new WritableStream<Uint8Array>(),
+ serializedContext: { state: "start" },
+ sessionState: state,
+ });
+
+ expect(cancelAllIndexedSessionTasksStep).toHaveBeenCalledWith({
+ serializedContext: { state: "start" },
+ sessionState: state,
+ });
+ expect(dispatchTurnStep).toHaveBeenCalledWith(
+ expect.objectContaining({ initialCancellation: { tasks: true } }),
+ );
+ });
+
it("keeps ordinary tool-loop continuations inline", async () => {
const firstState = createState("http:test:rekeyed");
const finalState = createState("http:test:rekeyed");
diff --git a/packages/eve/src/execution/turn-dispatch.ts b/packages/eve/src/execution/turn-dispatch.ts
index efba94ad8..2c93f436d 100644
--- a/packages/eve/src/execution/turn-dispatch.ts
+++ b/packages/eve/src/execution/turn-dispatch.ts
@@ -8,6 +8,7 @@ import type {
} from "#execution/durable-session-migrations/turn-workflow.js";
import { runInlineTurn } from "#execution/inline-turn.js";
import type { SessionCommandInbox } from "#execution/session-command-inbox.js";
+import { SessionStateCursor } from "#execution/session-state-cursor.js";
import type { TurnCancelPayload } from "#execution/turn-cancellation-token.js";
import type { TurnDriverAction } from "#execution/turn-control-receiver.js";
import type { RunMode } from "#shared/run-mode.js";
@@ -41,16 +42,24 @@ interface TurnDispatchInput {
readonly serializedContext: Record<string, unknown>;
readonly seenTaskDeliveries?: Set<string>;
readonly sessionState: DurableSessionState;
+ readonly stateCursor?: SessionStateCursor;
}
export async function dispatchAndAwaitTurn(input: TurnDispatchInput): Promise<DispatchedTurn> {
- const inline = await runInlineTurn(input);
+ const stateCursor =
+ input.stateCursor ??
+ new SessionStateCursor({
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
+ });
+ const inline = await runInlineTurn({ ...input, stateCursor });
if (inline.kind === "result") {
return { action: inline.action, async dispose() {} };
}
return await dispatchAndAwaitChildTurn({
...input,
initialCancellation: inline.initialCancellation,
+ stateCursor,
initialStep: inline.initialStep,
});
}
@@ -68,6 +77,7 @@ async function dispatchAndAwaitChildTurn(
commandInbox: input.commandInbox,
expectedTurnId: activeTurnId(input.sessionState.emissionState),
seenTaskDeliveries: input.seenTaskDeliveries ?? new Set(),
+ stateCursor: input.stateCursor!,
token: input.controlToken,
});
diff --git a/packages/eve/src/execution/turn-workflow.ts b/packages/eve/src/execution/turn-workflow.ts
index 4842d386e..bb420f5dc 100644
--- a/packages/eve/src/execution/turn-workflow.ts
+++ b/packages/eve/src/execution/turn-workflow.ts
@@ -11,6 +11,7 @@ import { createHook, getWorkflowMetadata } from "#compiled/@workflow/core/index.
import type { DeliverHookPayload } from "#channel/types.js";
import { preserveSerializedSessionDynamicModelSelection } from "#context/serialized-dynamic-model-selection.js";
import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-step.js";
+import { cancelAllIndexedSessionTasksStep } from "#execution/cancel-indexed-session-tasks-step.js";
import { sendTurnControlStep, type TurnInboxPayload } from "#execution/turn-control-protocol.js";
import { dispatchCoordinationStep } from "#execution/coordination-dispatch-step.js";
import { acknowledgeDelegatedTasksStep } from "#execution/tasks/parent/delegate.js";
@@ -302,6 +303,14 @@ async function finishCancelledTurn(input: {
readonly cancellation: TurnCancellationControl | undefined;
readonly cursor: TurnExecutionCursor;
}): Promise<void> {
+ const cancellation =
+ input.cancellation?.signal.aborted === true ? await input.cancellation.payload : undefined;
+ if (cancellation?.tasks === true) {
+ await cancelAllIndexedSessionTasksStep({
+ serializedContext: input.cursor.serializedContext,
+ sessionState: input.cursor.sessionState,
+ });
+ }
await cancelDescendantTurnsStep({
serializedContext: input.cursor.serializedContext,
sessionState: input.cursor.sessionState,
diff --git a/packages/eve/src/execution/wire/session-inbox-contract.ts b/packages/eve/src/execution/wire/session-inbox-contract.ts
index fef334457..3398fc04a 100644
--- a/packages/eve/src/execution/wire/session-inbox-contract.ts
+++ b/packages/eve/src/execution/wire/session-inbox-contract.ts
@@ -1,5 +1,5 @@
/** Every explicit session-inbox wire version still supported by producers. */
-export const SESSION_INBOX_WIRE_VERSIONS = [1, 2, 3, 4, 5] as const;
+export const SESSION_INBOX_WIRE_VERSIONS = [1, 2, 3, 4, 5, 6] as const;
export type SessionInboxWireVersion = (typeof SESSION_INBOX_WIRE_VERSIONS)[number];
diff --git a/packages/eve/src/execution/wire/session-inbox-encoder.ts b/packages/eve/src/execution/wire/session-inbox-encoder.ts
index 5afa9c9e4..b3fa727c8 100644
--- a/packages/eve/src/execution/wire/session-inbox-encoder.ts
+++ b/packages/eve/src/execution/wire/session-inbox-encoder.ts
@@ -30,21 +30,31 @@ import {
encodeSessionCommandV5,
type SessionInboxWireV5,
} from "#execution/wire/session-inbox-wire.v5.js";
+import {
+ encodeSessionCommandV6,
+ type SessionInboxWireV6,
+} from "#execution/wire/session-inbox-wire.v6.js";
type SessionInboxCommand = DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload;
/** Current wire type consumed after migration. */
-export type SessionInboxWire = SessionInboxWireV5;
+export type SessionInboxWire = SessionInboxWireV6;
type LegacySessionInboxWireTarget = Extract<SessionInboxWireTarget, { readonly version: 0 }>;
type VersionedSessionInboxEncoder = (command: SessionInboxCommand) => unknown;
const versionedEncoders = {
- 1: (command: SessionInboxCommand) => encodeSessionCommandV1(withoutAcceptedDeployment(command)),
- 2: (command: SessionInboxCommand) => encodeSessionCommandV2(withoutAcceptedDeployment(command)),
- 3: encodeSessionCommandV3,
- 4: encodeSessionCommandV4,
- 5: encodeSessionCommandV5,
+ 1: (command: SessionInboxCommand) =>
+ encodeSessionCommandV1(withoutAcceptedDeployment(withoutOwnedTaskCancellation(command))),
+ 2: (command: SessionInboxCommand) =>
+ encodeSessionCommandV2(withoutAcceptedDeployment(withoutOwnedTaskCancellation(command))),
+ 3: (command: SessionInboxCommand) =>
+ encodeSessionCommandV3(withoutOwnedTaskCancellation(command)),
+ 4: (command: SessionInboxCommand) =>
+ encodeSessionCommandV4(withoutOwnedTaskCancellation(command)),
+ 5: (command: SessionInboxCommand) =>
+ encodeSessionCommandV5(withoutOwnedTaskCancellation(command)),
+ 6: encodeSessionCommandV6,
} satisfies Record<SessionInboxWireVersion, VersionedSessionInboxEncoder>;
/** Encodes a command for the selected session-inbox consumer. */
@@ -53,6 +63,7 @@ function encode(command: SessionInboxCommand, target: { readonly version: 2 }):
function encode(command: SessionInboxCommand, target: { readonly version: 3 }): SessionInboxWireV3;
function encode(command: SessionInboxCommand, target: { readonly version: 4 }): SessionInboxWireV4;
function encode(command: SessionInboxCommand, target: { readonly version: 5 }): SessionInboxWireV5;
+function encode(command: SessionInboxCommand, target: { readonly version: 6 }): SessionInboxWireV6;
function encode(
command: SessionInboxCommand,
target: { readonly version: SessionInboxWireVersion },
@@ -70,6 +81,7 @@ function encode(
| SessionInboxWireV3
| SessionInboxWireV4
| SessionInboxWireV5
+ | SessionInboxWireV6
| Record<string, unknown>;
function encode(
command: SessionInboxCommand,
@@ -80,14 +92,24 @@ function encode(
| SessionInboxWireV3
| SessionInboxWireV4
| SessionInboxWireV5
+ | SessionInboxWireV6
| Record<string, unknown> {
+ if (command.kind === "cancel" && command.tasks === true && target.version < 6) {
+ throw new SessionInboxWireError(
+ `Cannot encode session-owned task cancellation for wire version ${target.version}.`,
+ );
+ }
if (target.version === 0) {
const currentTaskWire =
target.variant === "send" && command.kind === "send" && command.payload.task !== undefined
? encodeSessionCommandV5(command)
: undefined;
let legacy = encodeSessionCommandV0(
- encodeSessionCommandV1(withoutCurrentTaskMessages(withoutAcceptedDeployment(command))),
+ encodeSessionCommandV1(
+ withoutCurrentTaskMessages(
+ withoutAcceptedDeployment(withoutOwnedTaskCancellation(command)),
+ ),
+ ),
target.variant,
);
if (currentTaskWire?.kind === "deliver") {
@@ -116,13 +138,20 @@ function encode(
| SessionInboxWireV2
| SessionInboxWireV3
| SessionInboxWireV4
- | SessionInboxWireV5;
+ | SessionInboxWireV5
+ | SessionInboxWireV6;
}
throw new SessionInboxWireError(
`Cannot encode session inbox payload for unknown wire version ${JSON.stringify((target as { version?: unknown }).version)}.`,
);
}
+function withoutOwnedTaskCancellation(command: SessionInboxCommand): SessionInboxCommand {
+ if (command.kind !== "cancel" || command.tasks === undefined) return command;
+ const { tasks: _tasks, ...legacy } = command;
+ return legacy;
+}
+
function withoutCurrentTaskMessages(command: SessionInboxCommand): SessionInboxCommand {
if (command.kind !== "send" || command.payload.task === undefined) return command;
const {
diff --git a/packages/eve/src/execution/wire/session-inbox-resume.test.ts b/packages/eve/src/execution/wire/session-inbox-resume.test.ts
index 144cc71a0..254c804f6 100644
--- a/packages/eve/src/execution/wire/session-inbox-resume.test.ts
+++ b/packages/eve/src/execution/wire/session-inbox-resume.test.ts
@@ -131,6 +131,41 @@ describe("resumeSessionInbox", () => {
});
});
+ it("negotiates v6 for stable session-owned task cancellation", async () => {
+ const token = sessionCommandHookToken("session-1");
+ const hook = sessionHook("session-1", token, { sessionInboxWireVersion: 6 });
+ getHookByTokenMock.mockResolvedValue(hook);
+ resumeHookMock.mockResolvedValue(hook);
+
+ await resumeSessionInbox(token, { kind: "cancel", tasks: true, turnId: "turn-1" });
+
+ expect(getHookByTokenMock).toHaveBeenCalledWith(token);
+ expect(resumeHookMock).toHaveBeenCalledWith(hook, {
+ kind: "cancel",
+ tasks: true,
+ turnId: "turn-1",
+ version: 6,
+ });
+ });
+
+ it.each([
+ ["markerless", undefined],
+ ["v5", { sessionInboxWireVersion: 5 }],
+ ])(
+ "rejects stable session-owned task cancellation for a %s consumer before persistence",
+ async (_name, metadata) => {
+ const token = sessionCommandHookToken("session-1");
+ getHookByTokenMock.mockResolvedValue(sessionHook("session-1", token, metadata));
+
+ await expect(resumeSessionInbox(token, { kind: "cancel", tasks: true })).rejects.toThrow(
+ /Cannot encode session-owned task cancellation for wire version/,
+ );
+
+ expect(getHookByTokenMock).toHaveBeenCalledWith(token);
+ expect(resumeHookMock).not.toHaveBeenCalled();
+ },
+ );
+
it("encodes continuation delivery for the resolved consumer and resumes that hook", async () => {
const hook = sessionHook("session-1", "continuation-1", { sessionInboxWireVersion: 1 });
getHookByTokenMock.mockResolvedValue(hook);
diff --git a/packages/eve/src/execution/wire/session-inbox-resume.ts b/packages/eve/src/execution/wire/session-inbox-resume.ts
index 8589a5e7d..d49702e62 100644
--- a/packages/eve/src/execution/wire/session-inbox-resume.ts
+++ b/packages/eve/src/execution/wire/session-inbox-resume.ts
@@ -43,6 +43,7 @@ function isStableInboxFastPathCompatible(
command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload,
): boolean {
if (!isSessionCommandHookToken(token)) return false;
+ if (command.kind === "cancel" && command.tasks === true) return false;
return !("caller" in command && command.caller?.activityObserver !== undefined);
}
diff --git a/packages/eve/src/execution/wire/session-inbox-wire.test.ts b/packages/eve/src/execution/wire/session-inbox-wire.test.ts
index ce25006ad..9acb0353d 100644
--- a/packages/eve/src/execution/wire/session-inbox-wire.test.ts
+++ b/packages/eve/src/execution/wire/session-inbox-wire.test.ts
@@ -11,6 +11,15 @@ describe("session inbox wire policy", () => {
).toThrowError(SessionInboxWireError);
});
+ it("migrates version 5 cancel commands without enabling owned-task cancellation", () => {
+ expect(sessionInboxWire.decode({ kind: "cancel", version: 5 })).toEqual({
+ kind: "cancel",
+ taskId: undefined,
+ tasks: undefined,
+ turnId: undefined,
+ });
+ });
+
it("normalizes cross-realm records before running pure migrations", () => {
const wire = runInNewContext(`({
caller: undefined,
diff --git a/packages/eve/src/execution/wire/session-inbox-wire.ts b/packages/eve/src/execution/wire/session-inbox-wire.ts
index f5819a93f..902a3d80e 100644
--- a/packages/eve/src/execution/wire/session-inbox-wire.ts
+++ b/packages/eve/src/execution/wire/session-inbox-wire.ts
@@ -44,12 +44,22 @@ export { SessionInboxWireError } from "#execution/wire/session-inbox-contract.js
/** Prefixes migration and contract failures alike, so messages read as one voice. */
const WIRE_LABEL = "session inbox payload";
+const sessionInboxWireV5Migration: VersionMigration = {
+ from: 5,
+ migrate(prior) {
+ if (!isObject(prior)) throw new Error("session inbox wire v5 value is not an object.");
+ return { ...prior, version: 6 };
+ },
+ to: 6,
+};
+
const sessionInboxMigrations: readonly VersionMigration[] = [
sessionInboxWireV0Migration,
sessionInboxWireV1Migration,
sessionInboxWireV2Migration,
sessionInboxWireV3Migration,
sessionInboxWireV4Migration,
+ sessionInboxWireV5Migration,
];
/**
@@ -151,7 +161,7 @@ function normalizeWire(wire: SessionInboxWire): DecodedSessionInbox {
case "reset":
return { kind: "reset", reason: wire.reason };
case "cancel":
- return { kind: "cancel", taskId: wire.taskId, turnId: wire.turnId };
+ return { kind: "cancel", taskId: wire.taskId, tasks: wire.tasks, turnId: wire.turnId };
default:
throw new SessionInboxWireError(
`${WIRE_LABEL} has an unrecognized kind ${JSON.stringify((wire as { kind?: unknown }).kind)}.`,
diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v6.test.ts b/packages/eve/src/execution/wire/session-inbox-wire.v6.test.ts
new file mode 100644
index 000000000..e120cedfc
--- /dev/null
+++ b/packages/eve/src/execution/wire/session-inbox-wire.v6.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it } from "vitest";
+
+import { sessionInboxWire } from "#execution/wire/session-inbox-encoder.js";
+import { SessionInboxWireError } from "#execution/wire/session-inbox-contract.js";
+import { sessionInboxWire as sessionInboxWireDecoder } from "#execution/wire/session-inbox-wire.js";
+import { sessionInboxWireV6Schema } from "#execution/wire/session-inbox-wire.v6.js";
+
+describe("session inbox wire v6", () => {
+ it("round-trips session-owned task cancellation", () => {
+ const wire = sessionInboxWire.encode(
+ { kind: "cancel", tasks: true, turnId: "turn_1" },
+ { version: 6 },
+ );
+
+ expect(wire).toEqual({ kind: "cancel", tasks: true, turnId: "turn_1", version: 6 });
+ expect(sessionInboxWireDecoder.decode(wire)).toEqual({
+ kind: "cancel",
+ taskId: undefined,
+ tasks: true,
+ turnId: "turn_1",
+ });
+ });
+
+ it("keeps the v6 cancel schema strict", () => {
+ expect(
+ sessionInboxWireV6Schema.safeParse({ kind: "cancel", tasks: "true", version: 6 }).success,
+ ).toBe(false);
+ expect(
+ sessionInboxWireV6Schema.safeParse({ extra: true, kind: "cancel", version: 6 }).success,
+ ).toBe(false);
+ });
+
+ it.each([
+ { variant: "deliver", version: 0 } as const,
+ { variant: "send", version: 0 } as const,
+ { version: 1 } as const,
+ { version: 2 } as const,
+ { version: 3 } as const,
+ { version: 4 } as const,
+ { version: 5 } as const,
+ ])("fails closed when encoding tasks:true for old target %o", (target) => {
+ expect(() => sessionInboxWire.encode({ kind: "cancel", tasks: true }, target)).toThrowError(
+ SessionInboxWireError,
+ );
+ });
+
+ it.each([1, 2, 3, 4, 5] as const)(
+ "preserves ordinary cancellation for v%i consumers",
+ (version) => {
+ expect(sessionInboxWire.encode({ kind: "cancel", turnId: "turn_1" }, { version })).toEqual({
+ kind: "cancel",
+ turnId: "turn_1",
+ version,
+ });
+ },
+ );
+});
diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v6.ts b/packages/eve/src/execution/wire/session-inbox-wire.v6.ts
new file mode 100644
index 000000000..c1f0fee32
--- /dev/null
+++ b/packages/eve/src/execution/wire/session-inbox-wire.v6.ts
@@ -0,0 +1,57 @@
+import { z } from "#compiled/zod/index.js";
+
+import type {
+ DeliverHookPayload,
+ SessionCommand,
+ SessionTimeoutHookPayload,
+} from "#channel/types.js";
+import { SessionInboxWireError } from "#execution/wire/session-inbox-contract.js";
+import {
+ encodeSessionCommandV5,
+ sessionInboxWireV5Schema,
+} from "#execution/wire/session-inbox-wire.v5.js";
+import { formatValidationError } from "#runtime/validation.js";
+
+const v5 = sessionInboxWireV5Schema.options;
+const v5Cancel = v5[5];
+const VERSION = 6;
+const version = z.literal(VERSION);
+
+/** Version 6 adds session-owned task cancellation to the cancel command. */
+export const sessionInboxWireV6Schema = z.discriminatedUnion("kind", [
+ v5[0].extend({ version }),
+ v5[1].extend({ version }),
+ v5[2].extend({ version }),
+ v5[3].extend({ version }),
+ v5[4].extend({ version }),
+ v5Cancel.extend({ tasks: z.boolean().optional(), version }),
+]);
+
+export type SessionInboxWireV6 = z.infer<typeof sessionInboxWireV6Schema>;
+
+/** Builds and validates one complete version-6 wire value. */
+export function encodeSessionCommandV6(
+ command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload,
+): SessionInboxWireV6 {
+ const v5Command = withoutOwnedTaskCancellation(command);
+ const value: Record<string, unknown> = {
+ ...encodeSessionCommandV5(v5Command),
+ version: VERSION,
+ };
+ if (command.kind === "cancel") value.tasks = command.tasks;
+ const parsed = sessionInboxWireV6Schema.safeParse(value);
+ if (!parsed.success) {
+ throw new SessionInboxWireError(
+ `Produced a session inbox payload that does not match wire version ${VERSION}: ${formatValidationError(parsed.error)}`,
+ );
+ }
+ return parsed.data;
+}
+
+function withoutOwnedTaskCancellation(
+ command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload,
+): DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload {
+ if (command.kind !== "cancel" || command.tasks === undefined) return command;
+ const { tasks: _tasks, ...v5 } = command;
+ return v5;
+}
diff --git a/packages/eve/src/execution/workflow-entry.ts b/packages/eve/src/execution/workflow-entry.ts
index ebd543b27..1fc490bac 100644
--- a/packages/eve/src/execution/workflow-entry.ts
+++ b/packages/eve/src/execution/workflow-entry.ts
@@ -508,6 +508,7 @@ async function runDriverLoop(input: {
serializedContext,
seenTaskDeliveries,
sessionState: stateCursor.sessionState,
+ stateCursor,
});
await disposeSettledTurnControl?.();
disposeSettledTurnControl = turn.dispose;
diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.ts
index aad3fa3d5..2a8625265 100644
--- a/packages/eve/src/execution/workflow-runtime.ts
+++ b/packages/eve/src/execution/workflow-runtime.ts
@@ -391,10 +391,11 @@ function inactiveCommandResult<TCommand extends SessionCommand>(
export async function requestWorkflowTurnCancellation(
input: CancelTurnInput,
): Promise<CancelTurnResult> {
- const command: { kind: "cancel"; taskId?: string; turnId?: string } = {
+ const command: { kind: "cancel"; taskId?: string; tasks?: boolean; turnId?: string } = {
kind: "cancel",
};
if (input.taskId !== undefined) command.taskId = input.taskId;
+ if (input.tasks !== undefined) command.tasks = input.tasks;
if (input.turnId !== undefined) command.turnId = input.turnId;
return await dispatchWorkflowCommand(sessionCommandHookToken(input.sessionId), command);
}
diff --git a/packages/eve/src/public/channels/eve-session-routes.test.ts b/packages/eve/src/public/channels/eve-session-routes.test.ts
index cdf24dc42..f9b07da5c 100644
--- a/packages/eve/src/public/channels/eve-session-routes.test.ts
+++ b/packages/eve/src/public/channels/eve-session-routes.test.ts
@@ -220,6 +220,29 @@ describe("eve ID-addressed session routes", () => {
expect(session[operation]).toHaveBeenCalledTimes(1);
});
+ it("forwards owned-task cancellation without changing the response", async () => {
+ const session = createFixedSession();
+ const response = await route("POST", "/eve/v1/session/:sessionId/cancel")(
+ new Request("https://eve.test/eve/v1/session/wrun_A/cancel", {
+ body: JSON.stringify({ tasks: true, turnId: "turn_1" }),
+ method: "POST",
+ }),
+ createArgs(session),
+ );
+
+ expect(session.cancel).toHaveBeenCalledWith({
+ taskId: undefined,
+ tasks: true,
+ turnId: "turn_1",
+ });
+ expect(response.status).toBe(202);
+ await expect(response.json()).resolves.toEqual({
+ ok: true,
+ sessionId: "wrun_A",
+ status: "accepted",
+ });
+ });
+
it("returns a synchronous inactive cancellation result without a session id", async () => {
const session = createFixedSession({
cancel: vi.fn().mockResolvedValue({ status: "no_active_turn" }),
diff --git a/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts b/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts
index 1ba272ae5..4c318b7d7 100644
--- a/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts
+++ b/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts
@@ -249,7 +249,7 @@ describe("mounted extension installed under node_modules", () => {
);
expect(
JSON.parse(extensionFiles[`node_modules/${PACKAGE_NAME}/dist/extension/_manifest.json`]!),
- ).toMatchObject({ requires: { channel: 15, schedule: 8, subagent: 8 } });
+ ).toMatchObject({ requires: { channel: 16, schedule: 9, subagent: 8 } });
const app = await scenarioApp({
name: "mounted-extension-installed",
installDependencies: true,