The Open Framework for Building Agents
fix(eve): steering - interrupt pending generation in the core runtime (#3416)
Andrew Barbafe6451c9bdb9
diff --git a/.changeset/gateway-object-prompt-caching.md b/.changeset/gateway-object-prompt-caching.mdnew file mode 100644index 000000000..cc62b11c9--- /dev/null+++ b/.changeset/gateway-object-prompt-caching.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Keep automatic prompt caching enabled when local model authentication resolves an AI Gateway model to a provider object. Anthropic models retain cache reuse after signing in through `eve dev`.diff --git a/.changeset/steer-before-turn-completion.md b/.changeset/steer-before-turn-completion.mdnew file mode 100644index 000000000..dd37b5bd7--- /dev/null+++ b/.changeset/steer-before-turn-completion.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Apply steering in the core runtime before a pending model request produces an answer, continuing the same turn with the correction across clients and channels. Preserve executing tools and their results, prevent duplicate in-process model execution on background wakeups, and keep boundary steering after assistant output begins.diff --git a/docs/agent-config.md b/docs/agent-config.mdindex af5579198..2277a83cb 100644--- a/docs/agent-config.md+++ b/docs/agent-config.md@@ -275,9 +275,10 @@ events, and side effects. Use stable idempotency keys for non-idempotent tools.eve ends a batch before it waits for input, authorization, or blockingcoordination, and before it acknowledges a background task. A batch can also-end below the configured ceiling when the turn completes. Steering waits for the-batch to commit, then applies accepted input within the same turn. Larger batches-increase the interval between steering boundaries. This option is experimental and may change or+end below the configured ceiling when the turn completes or steering arrives.+Before assistant output begins, steering can interrupt pending model generation.+Executing tools finish safely before the batch yields and applies the correction.+This option is experimental and may change ordisappear in any release. See [Execution model anddurability](./concepts/execution-model-and-durability#resuming-after-a-crash)for the retry behavior.diff --git a/docs/channels/chat-sdk.mdx b/docs/channels/chat-sdk.mdxindex 3ee86272e..a7190a3c7 100644--- a/docs/channels/chat-sdk.mdx+++ b/docs/channels/chat-sdk.mdx@@ -108,7 +108,9 @@ bot.onNewMention(async (thread, message) => {### Steering-Messages default to `turnPolicy: "steer"`: a message sent while an eve turn is active is buffered, then applied to the same turn at the next committed workflow boundary. Set `turnPolicy: "queue"` when the active turn should finish first:+Messages default to `turnPolicy: "steer"`. Before assistant answer output or local tool execution begins, steering interrupts pending model generation and applies the correction in the same turn. Executing tools finish and checkpoint their results first. After answer output starts, steering waits for the next committed workflow boundary. Reasoning and search progress do not count as answer output; interrupted provider-managed search may run again.++Set `turnPolicy: "queue"` when the active turn should finish first:```tsbot.onSubscribedMessage(async (thread, message) => {@@ -119,7 +121,7 @@ bot.onSubscribedMessage(async (thread, message) => {});```-Steering preserves the turn ID and lets the current model call and tools finish. If no turn is active, the message starts a turn normally. You can set the policy once on `chatSdkChannel({ turnPolicy })` or override it per `send(...)`.+Steering preserves the turn ID and completed tool work. If no turn is active, the message starts a turn normally. You can set the policy once on `chatSdkChannel({ turnPolicy })` or override it per `send(...)`.This policy controls overlapping eve turns. Chat SDK's separate `concurrency` option controls overlapping webhook handlers; use `concurrency: "concurrent"` when each inbound message should reach the steering path immediately.diff --git a/docs/channels/custom.mdx b/docs/channels/custom.mdxindex dd5022413..8971ca07e 100644--- a/docs/channels/custom.mdx+++ b/docs/channels/custom.mdx@@ -127,7 +127,11 @@ const inputResponses = parseInputResponses(decodedResponses);await source.respond(inputResponses, { auth });```-Message sends use the channel's `turnPolicy`, which defaults to `"steer"`. An accepted message arriving during an active turn is buffered and applied at the next committed workflow boundary. The active model call and tools finish safely; the message joins the same turn and keeps its turn ID. Configure `turnPolicy: "queue"` on `defineChannel(...)` when messages should wait for the active turn to finish, or override one send:+Message sends use the channel's `turnPolicy`, which defaults to `"steer"`. Before assistant answer output or local tool execution begins, steering interrupts pending model generation and applies the correction in the same turn. Executing tools finish and checkpoint their results first. After answer output starts, steering waits for the next committed workflow boundary. Reasoning and search progress do not count as answer output, and interrupted provider-managed search may run again. The turn ID stays the same.++A sent delivery can interrupt generation before your `deliver` hook runs. If the hook ignores the correction, eve resumes the original request with its original auth, delivery provenance, and channel state. Filter events before `send(...)` when they should never interrupt generation.++Configure `turnPolicy: "queue"` on `defineChannel(...)` when messages should wait for the active turn to finish, or override one send:```tsexport default defineChannel({diff --git a/docs/channels/eve.mdx b/docs/channels/eve.mdxindex 45a481cb0..42cdb2af0 100644--- a/docs/channels/eve.mdx+++ b/docs/channels/eve.mdx@@ -78,7 +78,9 @@ curl -X POST https://<deployment>/eve/v1/session/wrun_A \-d '{"inputResponses":[{"requestId":"req_A","optionId":"approve"}]}'```-Follow-up messages use `turnPolicy: "steer"` by default. If a turn is active, eve buffers the message and applies it at the next committed workflow boundary, preserving the turn ID. Set `turnPolicy: "queue"` on `eveChannel(...)` when follow-ups should wait for active turns to finish. `inputResponses` answer their addressed requests.+Follow-up messages use `turnPolicy: "steer"` by default. Before assistant answer output or local tool execution begins, steering interrupts pending model generation and applies the correction in the same turn. Executing tools finish and checkpoint their results first. After answer output starts, steering waits for the next committed workflow boundary. Reasoning and search progress do not count as answer output; interrupted provider-managed search may run again. The turn ID stays the same.++Set `turnPolicy: "queue"` on `eveChannel(...)` when follow-ups should wait for active turns to finish. `inputResponses` answer their addressed requests.Sending a message to an unknown, terminal, or not-yet-active session ID returns `409` with`{"code":"session_not_active","error":"The session is no longer active.","ok":false}`.diff --git a/docs/channels/linq.mdx b/docs/channels/linq.mdxindex 444c0c8a1..36b4a03cf 100644--- a/docs/channels/linq.mdx+++ b/docs/channels/linq.mdx@@ -16,7 +16,7 @@ export default linqChannel({});```-The default webhook route is `/eve/v1/linq`. The channel verifies forwarded webhooks with same-project Vercel OIDC by default, derives user auth from each message author, marks accepted messages as read, and continues the same eve session for every message in a Linq conversation. A new accepted message steers the active turn at the next committed workflow boundary.+The default webhook route is `/eve/v1/linq`. The channel verifies forwarded webhooks with same-project Vercel OIDC by default, derives user auth from each message author, marks accepted messages as read, and continues the same eve session for every message in a Linq conversation. A new accepted message steers the active turn. Before answer output or local tool execution begins, steering can interrupt pending model generation. Executing tools finish first; after answer output starts, steering waits for the next committed workflow boundary. See [Overlapping messages](./overview#overlapping-messages).Set `turnPolicy: "queue"` when every response should finish before Linq starts the next message.diff --git a/docs/channels/overview.mdx b/docs/channels/overview.mdxindex 931e6baf4..cacdd9343 100644--- a/docs/channels/overview.mdx+++ b/docs/channels/overview.mdx@@ -28,7 +28,9 @@ own.## Overlapping messages-Channels default to `turnPolicy: "steer"`. When an accepted message arrives while a turn is active, eve buffers it and applies it at the next committed workflow boundary. The current model call and tools complete safely; the message continues the same turn with the same turn ID.+Channels default to `turnPolicy: "steer"`. Before assistant answer output or local tool execution begins, a message can interrupt pending model generation and continue the same turn with the correction. Executing tools finish and checkpoint their results before steering reaches the next model call. After answer output starts, steering waits for the next committed workflow boundary. The turn ID stays the same.++Reasoning and search progress do not count as answer output. Interrupted provider-managed search may run again; completed local tools are preserved.Set `turnPolicy: "queue"` on any built-in or custom channel when each turn must finish before the next message starts:@@ -45,7 +47,7 @@ Adjacent queued messages can combine into one turn only when their full auth con`from(address).send(...)`, fixed `Session.send(...)`, cross-channel sends, and Chat SDK bridge sends also accept a per-send `turnPolicy` override. Pure `inputResponses` deliveries answer their pending request without steering. Explicit `cancel()` remains the stop-without-replacement operation.-Channel admission still runs first. Ignored mentions, rejected signatures, duplicates, and any other dropped platform events never affect the active turn.+Events rejected before `send(...)`, such as invalid signatures or filtered mentions, never reach the active turn. A delivery already sent to the session can interrupt pending generation before the channel's `deliver` hook processes it. If that hook ignores the correction, eve resumes the original request with its original auth, delivery provenance, and channel state.Each channel has its own provider terms, data flow, auth model, and user-consent expectations. Before sending non-public, sensitive, regulated, or production data through a channel, confirm that the channel provider and your configured scopes, signature checks, route auth, and delivery behavior are appropriate for your use case.diff --git a/docs/channels/photon.mdx b/docs/channels/photon.mdxindex 897d178fe..2a219ad0e 100644--- a/docs/channels/photon.mdx+++ b/docs/channels/photon.mdx@@ -25,7 +25,10 @@ The default webhook route is `/eve/v1/photon`. The channel verifies forwardedwebhooks with same-project Vercel OIDC by default, derives user auth from eachmessage author, marks accepted messages as read, and continues the same evesession for every message in an iMessage conversation. A new accepted message-steers the active turn at the next committed workflow boundary.+steers the active turn. Steering can interrupt pending model generation before+answer output or local tool execution begins. Executing tools finish first;+after answer output starts, steering waits for the next committed workflow+boundary. See [Overlapping messages](./overview#overlapping-messages).Set `turnPolicy: "queue"` when every response should finish before Photon starts the next message.diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdxindex 4d24d71df..e5f9a0b58 100644--- a/docs/channels/slack.mdx+++ b/docs/channels/slack.mdx@@ -294,7 +294,9 @@ export default slackChannel({#### Control overlapping turns-Accepted Slack messages steer by default: eve buffers the new message and applies it to the same turn at the next committed workflow boundary. Ignored mentions and messages rejected by your hooks never enter the turn. Set `turnPolicy: "queue"` when every active turn should finish:+Accepted Slack messages steer by default. Before assistant answer output or local tool execution begins, steering interrupts pending model generation and continues the same turn with the correction. Executing tools finish and checkpoint their results first; after answer output starts, steering waits for the next committed workflow boundary. Reasoning and search progress do not count as answer output, and interrupted provider-managed search may run again.++Mentions and messages filtered before sending never reach the active turn. See [Overlapping messages](./overview#overlapping-messages) for deliveries ignored later by a channel's `deliver` hook. Set `turnPolicy: "queue"` when every active turn should finish:```ts title="agent/channels/slack.ts"export default slackChannel({diff --git a/docs/concepts/execution-model-and-durability.mdx b/docs/concepts/execution-model-and-durability.mdxindex 3cb9db085..c0c12ba63 100644--- a/docs/concepts/execution-model-and-durability.mdx+++ b/docs/concepts/execution-model-and-durability.mdx@@ -101,9 +101,9 @@ executions from the same batch. Approval, input, blocking coordination, andbackground-task boundaries still force a checkpoint before eve waits oracknowledges the work.-Steering waits for the current batch to commit, then adds the accepted message-to the active turn before the next model step. Increasing the batch size also-increases the interval between steering boundaries.+Steering can interrupt pending model generation before assistant output begins.+An executing tool finishes safely, then the batch yields before another model+call so the owner can apply accepted steering within the same turn.Durability itself needs no configuration. eve owns the workflow lifecycle, andsessions are durable by default; checkpoint batching is an explicit@@ -153,7 +153,11 @@ delivery that lands in that interval retries until the successor claims theaddress instead of being reported as an inactive session. A channel thereforenever starts a replacement session for an address that is mid-handoff.-When a session is waiting, a delivery through its ID or any claimed channel address wakes it and starts the next turn. Message sends default to `turnPolicy: "steer"`: while a turn is active, the session owner buffers the message and applies it after the current workflow step commits. The model call and tool work complete safely, and steering continues the same turn with the same turn ID. Before emitting the turn's completion events, the owner checks for steering accepted at that boundary.+When a session is waiting, a delivery through its ID or any claimed channel address wakes it and starts the next turn. Message sends default to `turnPolicy: "steer"`. Before assistant output begins, the session owner signals pending model generation to stop, then applies the correction within the same turn and with the same turn ID. This includes model requests that perform provider-managed search before answering; interrupted search work may run again. Reasoning and search progress do not count as assistant output.++An executing eve tool finishes and commits its result before steering reaches the next model request. Steering does not cancel the turn or its background tasks. After assistant output starts, steering applies at the next committed workflow boundary and preserves streamed text. A message that reaches the boundary after the turn has settled starts another turn.++Once eve publishes an input request or begins publishing turn completion or failure, eve finishes committing that boundary before applying new messages.`turnPolicy: "queue"` preserves the message until the active turn settles. If several deliveries are ready when the owner checks, eve may fold adjacent messages into the next turn while preserving their arrival order. Pure `inputResponses` deliveries do not steer; they remain available to the pending request they address.diff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.mdindex a4fbe4bea..660d7def3 100644--- a/docs/concepts/sessions-runs-and-streaming.md+++ b/docs/concepts/sessions-runs-and-streaming.md@@ -191,7 +191,7 @@ curl -X POST http://127.0.0.1:2000/eve/v1/session/<sessionId> \-d '{"inputResponses":[{"requestId":"req_A","optionId":"approve"}]}'```-Message sends default to `"steer"`; if a turn is active, eve buffers the follow-up and applies it at the next committed workflow boundary under the same turn ID. Current model and tool work completes safely. Channels and TypeScript `Session.send(...)` calls can select `turnPolicy: "queue"` when the active turn should finish first. Structured `inputResponses` answer their addressed requests.+Message sends default to `"steer"`. Before assistant output begins, eve interrupts pending model generation and continues the same turn with the correction. Reasoning and provider search progress do not count as assistant output. An executing eve tool finishes safely, and its result is preserved before the correction reaches the next model call. After assistant output starts, steering applies at the next committed workflow boundary; text already streamed remains visible. Channels and TypeScript `Session.send(...)` calls can select `turnPolicy: "queue"` when the active turn should finish first. Structured `inputResponses` answer their addressed requests.If the session is waiting on a human-in-the-loop approval, respond with the channel’s Approve or Cancel controls. Text messages do not decide an approval; unrelated text starts an ordinary turn while the approval stays pending and answerable. A later structured `inputResponses` answer keyed by its `requestId` still resumes the original tool call, even after intervening turns.diff --git a/docs/guides/dev-tui.md b/docs/guides/dev-tui.mdindex 37f066ee0..d01050cdc 100644--- a/docs/guides/dev-tui.md+++ b/docs/guides/dev-tui.md@@ -82,7 +82,9 @@ Required authorization or deployment setup still runs for the selected item. PreType a message and press `Enter` to send it. When the agent asks a question or requests tool approval, respond in the prompt shown by the UI. Connection authorization can open a browser; keep local `eve dev` running until the browser returns to it.-While a turn is running, `Enter` sends your message to steer the agent at its next execution boundary. Slash commands wait until the turn ends, except `/cancel`, which cancels directly. If the session does not support steering, messages queue for the next turn. Press `Esc` or `Ctrl+C` to cancel the turn; when messages are queued, this uses the oldest queued message as the next turn instead. If a direct cancellation requested with `/cancel` or `Ctrl+C` does not settle, press `Ctrl+C` to stop waiting. The UI then returns to the prompt and asks you to press `Ctrl+C` again to exit. At an idle prompt, press `Ctrl+C` twice to exit.+While a turn is running, `Enter` sends your message immediately as steering. Before assistant output begins, the runtime interrupts pending model generation and continues the same turn with your correction. Executing tools finish safely. After output begins, steering applies at the next workflow boundary and preserves streamed text.++Slash commands wait until the turn ends, except `/cancel`, which cancels directly. If the session does not support steering, messages queue for the next turn. Press `Esc` or `Ctrl+C` to cancel a turn with no queued messages. With queued messages, these keys select the oldest message for steering, or for the next turn if steering is unavailable. If a direct cancellation requested with `/cancel` or `Ctrl+C` does not settle, press `Ctrl+C` to stop waiting. The UI then returns to the prompt and asks you to press `Ctrl+C` again to exit. At an idle prompt, press `Ctrl+C` twice to exit.| Key | Action || ------------- | ----------------------------------------------------------------------------------------------------------------------- |diff --git a/docs/guides/frontend/overview.mdx b/docs/guides/frontend/overview.mdxindex 229ced442..d74070d93 100644--- a/docs/guides/frontend/overview.mdx+++ b/docs/guides/frontend/overview.mdx@@ -107,7 +107,9 @@ await agent.send([]);```-Assistant text, reasoning, tool calls, and tool results stream into `data` as they arrive, and a new turn moves `status` from `ready` to `submitted` to `streaming` and back. Resuming an attached session uses `resuming` while eve performs bounded catch-up. Disable message and HITL submission in that state. A settled tail moves directly to `ready`; an in-flight tail moves to `streaming` before eve follows it. To steer an active turn with a follow-up, send the message with `turnPolicy: "steer"`. eve applies the message at the next committed workflow boundary and keeps the hook attached through completion:+Assistant text, reasoning, tool calls, and tool results stream into `data` as they arrive, and a new turn moves `status` from `ready` to `submitted` to `streaming` and back. Resuming an attached session uses `resuming` while eve performs bounded catch-up. Disable message and HITL submission in that state. A settled tail moves directly to `ready`; an in-flight tail moves to `streaming` before eve follows it.++To steer an active turn with a follow-up, send the message with `turnPolicy: "steer"`. Before answer output or local tool execution begins, eve interrupts pending model generation and continues the same turn with the correction. Executing tools finish and checkpoint their results first; after answer output starts, steering waits for the next committed workflow boundary. Reasoning and search progress do not count as answer output. The hook stays attached through completion:```tsxawait agent.send(message, { turnPolicy: "steer" });diff --git a/docs/subagents/index.mdx b/docs/subagents/index.mdxindex cd63a9a69..b8feb7453 100644--- a/docs/subagents/index.mdx+++ b/docs/subagents/index.mdx@@ -227,7 +227,7 @@ Subagent model calls automatically retry classified transient provider failures,A child parks after answering instead of terminating, keeping its session and conversation history alive. A failed child turn can also leave the child parked — its latest status shows the error and the parent may message it again. Pass a parked child's `agentId` to the same subagent tool with a new `message` to continue that session. Omitting `agentId` (or passing an empty string or `null`) always starts a new child, and an `agentId` that matches no known agent falls back to starting a new child rather than failing. Passing a known `agentId` through a different subagent tool fails with `AGENT_MISMATCH`.-To steer a running background child, call the same subagent tool with its `agentId` and the updated `message`. The child finishes its current Workflow step, then applies the update before its next model call in the same turn. The receipt retains the same `agentId` and `taskId`; steering does not cancel the task, replace its completion callback, or undo tool side effects that have already occurred.+To steer a running background child, call the same subagent tool with its `agentId` and the updated `message`. Before answer output or local tool execution begins, steering interrupts the child's pending model generation and applies the update in the same turn. Executing tools finish and checkpoint their results first; after answer output starts, steering waits for the next committed Workflow boundary. The receipt retains the same `agentId` and `taskId`; steering does not cancel the task, replace its completion callback, or undo tool side effects that have already occurred.A child that is still starting, or is owned by a blocking workflow invocation rather than an admitted background task, continues to return `AGENT_BUSY`. Delivery failures are reported to the caller; eve does not start a replacement child session to hide them.diff --git a/e2e/fixtures/agent-cancellation/agent/agent.ts b/e2e/fixtures/agent-cancellation/agent/agent.tsindex 162667a60..f8053ff09 100644--- a/e2e/fixtures/agent-cancellation/agent/agent.ts+++ b/e2e/fixtures/agent-cancellation/agent/agent.ts@@ -5,8 +5,15 @@ import type { MockModelRequest, MockModelResponse } from "eve/evals";const RECOVERY_REQUEST = "RESUME-CANCELLED-SLEEPER";const HITL_REQUEST = "GENERATED-PROGRAM-CHILD-HITL";-function respond(request: MockModelRequest): MockModelResponse | string {+async function respond(request: MockModelRequest): Promise<MockModelResponse | string> {const message = request.lastUserMessage ?? "";+ if (message.includes("Alice is preparing the 2026 report.")) {+ await new Promise((resolve) => setTimeout(resolve, 30_000));+ return "Original 2026 report";+ }+ if (message.includes("Alice corrected the report year to 2025.")) {+ return "Corrected 2025 report";+ }if (message.includes("Please complete work before answering.")) {return request.toolResults.some((result) => result.id === "complete-work")? "The work item is complete."diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/steer-pending-generation.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/steer-pending-generation.eval.tsnew file mode 100644index 000000000..38e3eb20b--- /dev/null+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/steer-pending-generation.eval.ts@@ -0,0 +1,39 @@+import { defineEval } from "eve/evals";+import { satisfies } from "eve/evals/expect";++export default defineEval({+ description:+ "A correction during pending generation produces one corrected answer in the same turn.",+ timeoutMs: 120_000,+ async test(t) {+ if (process.env.EVE_E2E_MODEL !== "mock") {+ t.skip("Requires the deterministic model's pending-generation gate.");+ }+ const live = await t.start("Alice is preparing the 2026 report.");+ await live.waitForEvent("step.started");+ const correction = await live.session.start("Alice corrected the report year to 2025.", {+ turnPolicy: "steer",+ });+ const result = await live.result();+ await correction.result();+ result.event("turn.started", { count: 1 });+ result.event("turn.completed", { count: 1 });+ result.event("message.received", { count: 2 });+ result.notEvent("turn.cancelled");+ result.notEvent("turn.failed");+ result.notEvent("step.failed");+ result.messageIncludes("Corrected 2025 report");+ await t.require(+ result.events,+ satisfies(+ (events: typeof result.events) =>+ !events.some(+ (event) =>+ event.type === "message.appended" && event.data.messageDelta.includes("Original"),+ ),+ "the superseded generation never publishes its answer",+ ),+ );+ t.succeeded();+ },+});diff --git a/e2e/fixtures/agent-subagents/agent/subagents/ticket-reproducer/instructions.md b/e2e/fixtures/agent-subagents/agent/subagents/ticket-reproducer/instructions.mdindex c7d3c2a29..7501bfb0b 100644--- a/e2e/fixtures/agent-subagents/agent/subagents/ticket-reproducer/instructions.md+++ b/e2e/fixtures/agent-subagents/agent/subagents/ticket-reproducer/instructions.md@@ -1 +1 @@-You are the reproduction stage in a software-factory pipeline. Read the supplied triage and review objects and return only an object matching the requested output schema. Set `combinedKey` to the triage `derivedKey`, a `|`, and the review `derivedKey`; set `sampleTicket` to the triage `priorityTicket`; derive the run token by removing `:triage` from the triage key; and set `testCase` to `test("RUN_TOKEN", () => expect(runSyntheticRegression()).not.toThrow());` with RUN_TOKEN replaced by that token. Do not invent values or redo triage or review.+You are the reproduction stage in a software-factory pipeline. Read the supplied triage and review objects and return only an object matching the requested output schema. Set `combinedLabel` to the triage `summaryLabel`, a `|`, and the review `summaryLabel`; set `sampleTicket` to the triage `priorityTicket`; derive the QA batch id by removing `TRIAGE-` from the triage label; and set `verificationNote` to `Check QA batch BATCH_ID using ticket T-000.` with BATCH_ID replaced by that id. Do not invent values or redo triage or review.diff --git a/e2e/fixtures/agent-subagents/agent/subagents/ticket-review/instructions.md b/e2e/fixtures/agent-subagents/agent/subagents/ticket-review/instructions.mdindex 418180a6e..d35172305 100644--- a/e2e/fixtures/agent-subagents/agent/subagents/ticket-review/instructions.md+++ b/e2e/fixtures/agent-subagents/agent/subagents/ticket-review/instructions.md@@ -1 +1 @@-You are the independent review stage in a software-factory pipeline. Read the complete supplied ticket array and return only an object matching the requested output schema. Set `ticketCount` from the array length, `accepted` to true only when all 200 ids are unique, and `derivedKey` to the unique `reviewKey` found in the tickets. Do not invent values or perform triage or reproduction work.+You are the independent review stage in a software-factory pipeline. Read the complete supplied ticket array and return only an object matching the requested output schema. Set `ticketCount` from the array length, `accepted` to true only when all 200 ids are unique, and `summaryLabel` to the unique `reviewLabel` found in the tickets. Do not invent values or perform triage or reproduction work.diff --git a/e2e/fixtures/agent-subagents/agent/subagents/ticket-triage/instructions.md b/e2e/fixtures/agent-subagents/agent/subagents/ticket-triage/instructions.mdindex d02edcacb..5d2388ff3 100644--- a/e2e/fixtures/agent-subagents/agent/subagents/ticket-triage/instructions.md+++ b/e2e/fixtures/agent-subagents/agent/subagents/ticket-triage/instructions.md@@ -1 +1 @@-You are the triage stage in a software-factory pipeline. Read the complete supplied ticket array and return only an object matching the requested output schema. Set `ticketCount` from the array length, `priorityTicket` to the first ticket id, and `derivedKey` to the unique `triageKey` found in the tickets. Do not invent values or perform review or reproduction work.+You are the triage stage in a software-factory pipeline. Read the complete supplied ticket array and return only an object matching the requested output schema. Set `ticketCount` from the array length, `priorityTicket` to the first ticket id, and `summaryLabel` to the unique `triageLabel` found in the tickets. Do not invent values or perform review or reproduction work.diff --git a/e2e/fixtures/agent-subagents/evals/agent-messaging-remote.eval.ts b/e2e/fixtures/agent-subagents/evals/agent-messaging-remote.eval.tsindex 3d8fd3d57..3cfcb880a 100644--- a/e2e/fixtures/agent-subagents/evals/agent-messaging-remote.eval.ts+++ b/e2e/fixtures/agent-subagents/evals/agent-messaging-remote.eval.ts@@ -1,6 +1,6 @@import { defineEval } from "eve/evals";-const MEMORABLE_FACT = "The tide station passphrase is HARBOR-LUMEN-4482";+const MEMORABLE_FACT = "Alice named the tide station notebook Harbor Lumen 4482.";/*** Cross-turn continuation of a remote child over a real HTTP hop: turn onediff --git a/e2e/fixtures/agent-subagents/evals/software-factory-workflow.eval.ts b/e2e/fixtures/agent-subagents/evals/software-factory-workflow.eval.tsindex 17626c29a..85db7281b 100644--- a/e2e/fixtures/agent-subagents/evals/software-factory-workflow.eval.ts+++ b/e2e/fixtures/agent-subagents/evals/software-factory-workflow.eval.ts@@ -17,11 +17,11 @@ export default defineEval({const expected = expectedFactoryOutput(token);const turn = await t.send([- `FACTORY_RUN_TOKEN=${token}.`,- "Alice is processing a manufactured software-factory backlog. Use the workflow tool exactly once, and do not call any of its subagents outside that program.",- "Create a minimal array of exactly 200 tickets with ids `T-000` through `T-199`. Each ticket must contain only `id`, except `T-000` also has `triageKey` set to FACTORY_RUN_TOKEN:triage and `T-199` also has `reviewKey` set to FACTORY_RUN_TOKEN:review, replacing FACTORY_RUN_TOKEN with the supplied token.",- "Use Promise.all to run ticket-triage and ticket-review concurrently, passing the complete tickets array to both calls. Use `outputSchema` to request exactly `{ ticketCount: integer, priorityTicket: string, derivedKey: string }` from ticket-triage and `{ ticketCount: integer, accepted: boolean, derivedKey: string }` from ticket-review.",- "After both complete, call ticket-reproducer with the returned `{ triage, review }` objects and use `outputSchema` to request exactly `{ combinedKey: string, sampleTicket: string, testCase: string }`. Make every listed output field required and allow no additional output fields.",+ `Alice's QA batch id is ${token}.`,+ "Alice is preparing a QA summary for a sample software backlog. Use the workflow tool exactly once, and call its subagents only from that program.",+ `Create a minimal array of exactly 200 tickets with ids \`T-000\` through \`T-199\`. Each ticket must contain only \`id\`, except \`T-000\` also has \`triageLabel\` set to \`TRIAGE-${token}\` and \`T-199\` also has \`reviewLabel\` set to \`REVIEW-${token}\`.`,+ "Use Promise.all to run ticket-triage and ticket-review concurrently, passing the complete tickets array to both calls. Use `outputSchema` to request exactly `{ ticketCount: integer, priorityTicket: string, summaryLabel: string }` from ticket-triage and `{ ticketCount: integer, accepted: boolean, summaryLabel: string }` from ticket-review.",+ "After both complete, call ticket-reproducer with the returned `{ triage, review }` objects and use `outputSchema` to request exactly `{ combinedLabel: string, sampleTicket: string, verificationNote: string }`. Make every listed output field required and allow no additional output fields.","Return `{ reproduction, review, triage }` and reply with only that returned JSON object.",].join(" "),);@@ -57,20 +57,20 @@ export default defineEval({function expectedFactoryOutput(token: string) {const triage = {- derivedKey: `${token}:triage`,priorityTicket: "T-000",+ summaryLabel: `TRIAGE-${token}`,ticketCount: 200,};const review = {accepted: true,- derivedKey: `${token}:review`,+ summaryLabel: `REVIEW-${token}`,ticketCount: 200,};return {reproduction: {- combinedKey: `${triage.derivedKey}|${review.derivedKey}`,+ combinedLabel: `${triage.summaryLabel}|${review.summaryLabel}`,sampleTicket: triage.priorityTicket,- testCase: `test("${token}", () => expect(runSyntheticRegression()).not.toThrow());`,+ verificationNote: `Check QA batch ${token} using ticket T-000.`,},review,triage,diff --git a/packages/eve/scripts/vendor-compiled/@workflow/core.mjs b/packages/eve/scripts/vendor-compiled/@workflow/core.mjsindex daa96fde2..cca35e2aa 100644--- a/packages/eve/scripts/vendor-compiled/@workflow/core.mjs+++ b/packages/eve/scripts/vendor-compiled/@workflow/core.mjs@@ -167,11 +167,36 @@ function stubCoreQuickJSEntrypoint() {};}+function guardInlineStepExecution() {+ return {+ name: "eve:guard-inline-step-execution",+ transform(source, id) {+ if (!id.replaceAll("\\", "/").endsWith("/@workflow/core/dist/runtime.js")) return null;++ // beta.51 only registers recovered inline steps with single-flight.+ // A queued wake can therefore run a newly claimed step again while its+ // original body is still active, especially when a local lease expires.+ const unguarded =+ /const executed = s\.lazyStepInput === undefined &&\s+s\.preclaimedStart === undefined\s+\? runStepSingleFlight\(runId, s\.correlationId, run\)\s+: run\(\);/;+ if (!unguarded.test(source)) {+ throw new Error("Recheck the @workflow/core inline step single-flight patch.");+ }+ return {+ code: source.replace(+ unguarded,+ "const executed = runStepSingleFlight(runId, s.correlationId, run);",+ ),+ map: null,+ };+ },+ };+}+export default {packageName: "@workflow/core",compiledPath: "@workflow/core",chunkGroup: "workflow",- plugins: [stubCoreWorldFactories(), stubCoreQuickJSEntrypoint()],+ plugins: [stubCoreWorldFactories(), stubCoreQuickJSEntrypoint(), guardInlineStepExecution()],entries: [{ entry: "dist/serialization.js", outputPath: "serialization" },{ entry: "dist/runtime/helpers.js", outputPath: "runtime/helpers" },diff --git a/packages/eve/src/cli/dev/tui/steering-stream.test.ts b/packages/eve/src/cli/dev/tui/steering-stream.test.tsindex 7823be9b0..e66f9f0c8 100644--- a/packages/eve/src/cli/dev/tui/steering-stream.test.ts+++ b/packages/eve/src/cli/dev/tui/steering-stream.test.ts@@ -4,6 +4,20 @@ import { stampTestEvents } from "#internal/testing/events.js";import { createMessageReceivedEvent, createSessionWaitingEvent } from "#protocol/message.js";describe("SteeringStream", () => {+ it("submits steering immediately without cancelling or waiting for the active stream", async () => {+ const admitted = Promise.withResolvers<AsyncIterable<never>>();+ const session = { cancel: vi.fn(), send: vi.fn(() => admitted.promise) };+ const stream = new SteeringStream(iterate([]), session);+ const sending = stream.send("Actually 2025");+ expect(session.send).toHaveBeenCalledWith("Actually 2025", {+ turnPolicy: "steer",+ signal: expect.any(AbortSignal),+ });+ expect(session.cancel).not.toHaveBeenCalled();+ admitted.resolve(iterate([]));+ await sending;+ stream.abort();+ });it("deduplicates a steering response on the same turn and emits its boundary once", async () => {const events = stampTestEvents([createMessageReceivedEvent({ message: "first", sequence: 0, turnId: "turn_0" }),diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.test.tsindex f29f58190..d1677f990 100644--- a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts@@ -2083,7 +2083,8 @@ describe("TerminalRenderer (inline scrollback)", () => {const { screen, input, renderer } = makeRenderer();let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;const cancel = vi.fn();- const steer = vi.fn(async () => {});+ const accepted = Promise.withResolvers<void>();+ const steer = vi.fn(() => accepted.promise);const rendering = renderer.renderStream({cancel,@@ -2109,6 +2110,7 @@ describe("TerminalRenderer (inline scrollback)", () => {expect(steer).toHaveBeenNthCalledWith(2, "go south");expect(screen.snapshot()).not.toContain("Queue");+ accepted.resolve();streamController?.enqueue({ type: "finish" });streamController?.close();await rendering;diff --git a/packages/eve/src/execution/legacy-session/import.integration.test.ts b/packages/eve/src/execution/legacy-session/import.integration.test.tsindex 0f3d54722..da2e011c5 100644--- a/packages/eve/src/execution/legacy-session/import.integration.test.ts+++ b/packages/eve/src/execution/legacy-session/import.integration.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest";import { createTestRuntime } from "#internal/testing/app-harness.js";import { legacySessionDriverWorkflow } from "#internal/testing/legacy-session-driver-workflow.js";import { waitForHook } from "#internal/testing/workflow-test-helpers.js";+import { waitForParkedTurnStep } from "#internal/testing/session-test-helpers.js";import { captureTurnEvents, filterEventsByType } from "#internal/testing/events.js";import { hydrateStepReturnValue } from "#compiled/@workflow/core/serialization.js";import type { DurableStepResult } from "#execution/session/turn-step-types.js";@@ -184,6 +185,7 @@ describe("imported session lifetime", () => {const importedOwner = await getHookByToken(sessionInboxHookToken(sessionCommandHookToken(driver.runId)),);+ await waitForParkedTurnStep(importedOwner.runId);await resumeSessionInbox({ sessionId: driver.runId },{@@ -202,6 +204,7 @@ describe("imported session lifetime", () => {sessionInboxHookToken(sessionCommandHookToken(driver.runId)),);expect(successor.runId).not.toBe(importedOwner.runId);+ await waitForParkedTurnStep(successor.runId);expect(await driver.status).toBe("running");await resumeSessionInbox({ sessionId: driver.runId }, { kind: "cancel" });await resumeSessionInbox(diff --git a/packages/eve/src/execution/model-call-batching.test.ts b/packages/eve/src/execution/model-call-batching.test.tsnew file mode 100644index 000000000..fa3f9470f--- /dev/null+++ b/packages/eve/src/execution/model-call-batching.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it, vi } from "vitest";+import { runModelCallBatch } from "#execution/model-call-batching.js";+import type { HarnessSession, StepResult } from "#harness/types.js";++describe("model call batching and steering", () => {+ it("checkpoints a completed tool result instead of starting another model call with pending steering", async () => {+ const steering = new AbortController();+ const session: HarnessSession = {+ sessionId: "session",+ continuationToken: "session",+ agent: { modelReference: { id: "mock" }, system: "Test", tools: [] },+ history: [],+ compaction: { threshold: 100000, recentWindowSize: 10 },+ };+ const completed: StepResult = {+ next: async () => {+ throw new Error("The owner must apply steering first");+ },+ session: {+ ...session,+ history: [+ {+ role: "tool",+ content: [+ {+ type: "tool-result",+ toolCallId: "saved",+ toolName: "save",+ output: { type: "text", value: "saved once" },+ },+ ],+ },+ ],+ },+ };+ const runStep = vi.fn(async () => {+ steering.abort();+ return completed;+ });+ expect(+ await runModelCallBatch({+ initialInput: undefined,+ initialSession: session,+ modelCallsPerStep: 4,+ steeringSignal: steering.signal,+ runStep,+ }),+ ).toBe(completed);+ expect(runStep).toHaveBeenCalledOnce();+ });+});diff --git a/packages/eve/src/execution/model-call-batching.ts b/packages/eve/src/execution/model-call-batching.tsindex 001b24c8d..8a0cd03ec 100644--- a/packages/eve/src/execution/model-call-batching.ts+++ b/packages/eve/src/execution/model-call-batching.ts@@ -2,6 +2,7 @@ import { derivePendingState } from "#execution/session/pending-turn-state.js";import type { HarnessSession, StepInput, StepResult } from "#harness/types.js";export async function runModelCallBatch(input: {+ readonly steeringSignal?: AbortSignal;readonly initialInput: StepInput | undefined;readonly initialSession: HarnessSession;readonly modelCallsPerStep: number;@@ -23,6 +24,8 @@ export async function runModelCallBatch(input: {});completedModelCalls++;if (+ input.steeringSignal?.aborted === true ||+ result.steered === true ||!shouldRunAnotherModelCall({completedModelCalls,modelCallsPerStep: input.modelCallsPerStep,diff --git a/packages/eve/src/execution/node-step.ts b/packages/eve/src/execution/node-step.tsindex 5aa40001e..c39089859 100644--- a/packages/eve/src/execution/node-step.ts+++ b/packages/eve/src/execution/node-step.ts@@ -53,6 +53,7 @@ export type CreateRuntime = (config: {* Input for building a harness step for one resolved runtime node.*/export interface CreateExecutionNodeStepInput {+ readonly steeringSignal?: AbortSignal;/** Cancellation signal forwarded to the tool-loop harness. */readonly abortSignal?: AbortSignal;/**@@ -97,6 +98,7 @@ export function createExecutionNodeStep(input: CreateExecutionNodeStepInput): Stconst instrumentation = input.instrumentation;const sessionInstrumentation = instrumentation?.prepareExecution();const step = createToolLoopHarness({+ steeringSignal: input.steeringSignal,abortSignal: input.abortSignal,capabilities: input.capabilities,clearOnly: input.clearOnly,diff --git a/packages/eve/src/execution/session-inbox/inbox.test.ts b/packages/eve/src/execution/session-inbox/inbox.test.tsindex 17bf5768a..567300577 100644--- a/packages/eve/src/execution/session-inbox/inbox.test.ts+++ b/packages/eve/src/execution/session-inbox/inbox.test.ts@@ -39,6 +39,23 @@ vi.mock("#compiled/@workflow/core/index.js", () => ({}));describe("createSessionInbox", () => {+ it("notifies delivery observers promptly and replays unread deliveries on subscription", async () => {+ const delivery = createDeferred<IteratorResult<SessionInboxPayload>>();+ installHooks(createMockHook({ token: "stable", reads: [delivery.promise] }));+ const inbox = createSessionInbox("session-1");+ const observed = vi.fn();+ const unsubscribe = inbox.onDelivery(observed);+ await inbox.claimSessionHook("stable");+ delivery.resolve(resolved(send("correction")));+ await delivery.promise;+ expect(observed).toHaveBeenCalledWith(send("correction"));+ unsubscribe();+ const lateObserver = vi.fn();+ inbox.onDelivery(lateObserver);+ expect(lateObserver).toHaveBeenCalledWith(send("correction"));+ expect(inbox.drain()).toEqual([send("correction")]);+ await inbox.dispose();+ });beforeEach(() => {createHookMock.mockReset();});diff --git a/packages/eve/src/execution/session-inbox/inbox.ts b/packages/eve/src/execution/session-inbox/inbox.tsindex 4d98c22e7..763557f2f 100644--- a/packages/eve/src/execution/session-inbox/inbox.ts+++ b/packages/eve/src/execution/session-inbox/inbox.ts@@ -44,6 +44,8 @@ export interface SessionInboxReader {* consumer still processes it in order.*/onInterrupt(handler: (payload: SessionInboxPayload) => void): () => void;+ /** Observes deliveries without consuming them; replays unread deliveries on subscription. */+ onDelivery(handler: (payload: SessionInboxPayload) => void): () => void;restore(payloads: readonly SessionInboxPayload[]): void;}@@ -77,6 +79,7 @@ export function createSessionInbox(sessionId: string): SessionInboxHandle {const queue: SessionInboxPayload[] = [];const waiters = new Set<() => void>();const interruptHandlers = new Set<(payload: SessionInboxPayload) => void>();+ const deliveryHandlers = new Set<(payload: SessionInboxPayload) => void>();let failure: { error: unknown } | undefined;const notify = (): void => {@@ -95,6 +98,8 @@ export function createSessionInbox(sessionId: string): SessionInboxHandle {const result = await iterator.next();if (result.done) break;queue.push(result.value);+ if (result.value.kind === "send" || result.value.kind === "deliver")+ for (const handler of deliveryHandlers) handler(result.value);if (isInterrupt(result.value))for (const handler of interruptHandlers) handler(result.value);notify();@@ -173,6 +178,12 @@ export function createSessionInbox(sessionId: string): SessionInboxHandle {interruptHandlers.add(handler);return () => interruptHandlers.delete(handler);},+ onDelivery(handler) {+ deliveryHandlers.add(handler);+ for (const payload of queue)+ if (payload.kind === "send" || payload.kind === "deliver") handler(payload);+ return () => deliveryHandlers.delete(handler);+ },restore(payloads) {if (sources.length === 0)throw new Error("Cannot restore session commands before reclaiming the session hooks.");diff --git a/packages/eve/src/execution/session/entry.integration.test.ts b/packages/eve/src/execution/session/entry.integration.test.tsindex 173bfc97a..816e5a4aa 100644--- a/packages/eve/src/execution/session/entry.integration.test.ts+++ b/packages/eve/src/execution/session/entry.integration.test.ts@@ -12,6 +12,7 @@ import { createChannelAddress } from "#channel/channel-address.js";import { captureTurnEvents, filterEventsByType } from "#internal/testing/events.js";import { createTestRuntime } from "#internal/testing/app-harness.js";import { waitForHook } from "#internal/testing/workflow-test-helpers.js";+import { waitForParkedTurnStep } from "#internal/testing/session-test-helpers.js";import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";import { workflowEntry } from "#execution/session/entry.js";import { sessionInboxHookToken } from "#execution/session-inbox/address.js";@@ -732,6 +733,8 @@ describe("workflowEntry integration", () => {(event) => event.type === "session.waiting",);+ await waitForParkedTurnStep(run.runId);+// A cancel with no active turn is consumed by the parked wait// without producing a parent turn. The callback must still surface// in the continued wait instead of stalling until unrelated@@ -1203,6 +1206,7 @@ describe("workflowEntry integration", () => {describe("deployment handoff", () => {const followUp = (acceptedDeploymentId: string, message: string, deliveryId: string) => ({+ turnPolicy: "queue" as const,auth: null,delivery: {acceptedDeploymentId,@@ -1241,6 +1245,7 @@ describe("workflowEntry integration", () => {let completed = false;try {expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");+ await waitForParkedTurnStep(anchor.runId);const originalTimer =sessionTimeoutMs === false ? undefined : await readSessionTimer(anchor.runId);@@ -1320,6 +1325,7 @@ describe("workflowEntry integration", () => {if (successorTimer !== undefined) {expect(await readSessionTimer(successor.runId)).toEqual(successorTimer);}+ await waitForParkedTurnStep(successor.runId, 2);await workflowRuntime.dispatchSession({command: followUp("dpl_c", "fourth message", "delivery-d"),sessionId: anchor.runId,@@ -1548,6 +1554,7 @@ describe("workflowEntry integration", () => {await resumeHook(sessionInboxHookToken(sessionCommandHookToken(anchor.runId)), {kind: "send",payload: { message: `Alice sends input ${index} during release.` },+ turnPolicy: "queue",});}}@@ -1555,6 +1562,7 @@ describe("workflowEntry integration", () => {});try {expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");+ await waitForParkedTurnStep(anchor.runId);await expect(workflowRuntime.dispatchSession({@@ -2231,8 +2239,8 @@ async function expectHookClaims(runId: string, tokens: string[]): Promise<void>const claims = events.data.flatMap((event) =>event.eventType === "hook_created" ? [event.eventData.token] : [],);- const cancellation = claims.filter((token) => token.startsWith("abrt_"));- expect(cancellation).toHaveLength(1);+ const signals = claims.filter((token) => token.startsWith("abrt_"));+ expect(signals).toHaveLength(2);expect(claims.filter((token) => !token.startsWith("abrt_")).sort()).toEqual(tokens.map(sessionInboxHookToken).sort(),);diff --git a/packages/eve/src/execution/session/handoff.test.ts b/packages/eve/src/execution/session/handoff.test.tsindex fb24a08cf..14b5d0912 100644--- a/packages/eve/src/execution/session/handoff.test.ts+++ b/packages/eve/src/execution/session/handoff.test.ts@@ -228,6 +228,7 @@ function createInbox(input: { released?: SessionInboxPayload[] } = {}): SessionIdrain: vi.fn(() => []),hasPending: vi.fn(() => false),next: vi.fn(),+ onDelivery: vi.fn(() => () => {}),onInterrupt: vi.fn(() => () => {}),release: vi.fn(async () => input.released ?? []),restore: vi.fn(),diff --git a/packages/eve/src/execution/session/input-queue.ts b/packages/eve/src/execution/session/input-queue.tsindex f3f3ecd77..7d07fe517 100644--- a/packages/eve/src/execution/session/input-queue.ts+++ b/packages/eve/src/execution/session/input-queue.ts@@ -151,9 +151,7 @@ export class SessionInputQueue {(entry): entry is QueuedDelivery =>entry.kind === "delivery" &&admitted.has(entry.sequence) &&- entry.delivery.taskDeliveryId === undefined &&- (entry.delivery.turnPolicy ?? "steer") === "steer" &&- (entry.delivery.caller === undefined || entry.delivery.caller.callId === callerCallId),+ isSteeringDelivery(entry.delivery, callerCallId),);if (steering.length === 0) return undefined;this.retain((entry) => entry.kind !== "delivery" || !steering.includes(entry));@@ -314,6 +312,17 @@ export class SessionInputQueue {}}+export function isSteeringDelivery(+ delivery: DeliverHookPayload,+ callerCallId: string | undefined,+): boolean {+ return (+ delivery.taskDeliveryId === undefined &&+ (delivery.turnPolicy ?? "steer") === "steer" &&+ (delivery.caller === undefined || delivery.caller.callId === callerCallId)+ );+}+function combine(entries: readonly DeliveryAdmission[]): DeliverHookPayload {return entries.length === 1? entries[0]!.deliverydiff --git a/packages/eve/src/execution/session/next-input.test.ts b/packages/eve/src/execution/session/next-input.test.tsindex 2a0f7cb98..0bea4abf3 100644--- a/packages/eve/src/execution/session/next-input.test.ts+++ b/packages/eve/src/execution/session/next-input.test.ts@@ -51,6 +51,9 @@ function createMockInbox(reads: readonly ScriptedRead[]): SessionInbox {if (read.result.done) return undefined;return read.result.value;},+ onDelivery() {+ return () => {};+ },onInterrupt() {return () => {};},@@ -410,6 +413,7 @@ describe("nextTurnDelivery routing", () => {drain: vi.fn(() => commands.splice(0)),hasPending: vi.fn(() => commands.length > 0),next: vi.fn(async () => commands.shift()),+ onDelivery: vi.fn(() => () => {}),onInterrupt: vi.fn(() => () => {}),restore: vi.fn(),};diff --git a/packages/eve/src/execution/session/state-cursor.ts b/packages/eve/src/execution/session/state-cursor.tsindex ada9d8dfd..aaa061a23 100644--- a/packages/eve/src/execution/session/state-cursor.ts+++ b/packages/eve/src/execution/session/state-cursor.ts@@ -51,9 +51,12 @@ export class SessionStateCursor {this.currentSessionState = sessionState;}- createStepInput(input: TurnStepPayload | undefined, abortSignal?: AbortSignal): TurnStepInput {+ createStepInput(+ input: TurnStepPayload | undefined,+ signals: Pick<TurnStepInput, "abortSignal" | "steeringSignal">,+ ): TurnStepInput {return {- abortSignal,+ ...signals,input,sessionWritable: this.sessionWritable,serializedContext: this.currentSerializedContext,diff --git a/packages/eve/src/execution/session/turn-step-result.ts b/packages/eve/src/execution/session/turn-step-result.tsindex dedcfbb84..8e728d4e3 100644--- a/packages/eve/src/execution/session/turn-step-result.ts+++ b/packages/eve/src/execution/session/turn-step-result.ts@@ -14,6 +14,12 @@ export function resolveSessionStepResult(beforeStepContext: Record<string, unknown>,): DurableStepResult {const nextState = createDurableSessionState({ session: stepResult.session });+ if (stepResult.steered)+ return {+ action: "steered",+ serializedContext: nextSerializedContext,+ sessionState: nextState,+ };const backgroundTransition =stepResult.backgroundTasks === undefined || stepResult.backgroundTaskSession === undefined? {}diff --git a/packages/eve/src/execution/session/turn-step-types.ts b/packages/eve/src/execution/session/turn-step-types.tsindex d8985fe39..8b43e8276 100644--- a/packages/eve/src/execution/session/turn-step-types.ts+++ b/packages/eve/src/execution/session/turn-step-types.ts@@ -24,6 +24,7 @@ export interface TurnStepPayload {/** Input for one atomic, session-owner-executed turn step. */export interface TurnStepInput {readonly abortSignal?: AbortSignal;+ readonly steeringSignal?: AbortSignal;readonly input: TurnStepPayload | undefined;readonly sessionWritable: WritableStream<Uint8Array>;readonly serializedContext: Record<string, unknown>;@@ -48,7 +49,7 @@ export type DurableStepResult = (readonly usage?: TokenUsage;readonly usageDelta?: TokenUsage;}- | { readonly action: "cancelled" }+ | { readonly action: "cancelled" | "steered" }| {readonly action: "park";readonly authorizationAttemptIds?: readonly string[];diff --git a/packages/eve/src/execution/session/turn-step.test.ts b/packages/eve/src/execution/session/turn-step.test.tsindex fad8f7c5e..7963d4df7 100644--- a/packages/eve/src/execution/session/turn-step.test.ts+++ b/packages/eve/src/execution/session/turn-step.test.ts@@ -34,6 +34,7 @@ import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.jsimport { serializeContext } from "#context/serialize.js";import { getPendingCoordinationBatch, setPendingCoordinationBatch } from "#harness/coordination.js";import { TurnCancelledError } from "#harness/turn-cancellation.js";+import { setHarnessEmissionState } from "#harness/emission-state.js";import { getPendingAuthorization, setPendingAuthorization } from "#harness/authorization.js";import { getProxyInputRequests, upsertProxyInputRequests } from "#harness/proxy-input-requests.js";import { appendPendingInputBatch } from "#harness/input-requests.js";@@ -1016,6 +1017,76 @@ describe("dispatchCoordinationStep", () => {});describe("turnStep", () => {+ it("resumes an interrupted turn when the channel ignores the correction", async () => {+ const originalAuth: SessionAuthContext = {+ attributes: {},+ authenticator: "test",+ issuer: "test",+ principalId: "alice",+ principalType: "user",+ subject: "alice",+ };+ const correctionAuth = { ...originalAuth, principalId: "bob", subject: "bob" };+ const adapter: ChannelAdapter = {+ kind: "ignore-correction",+ state: { reply: { recipient: "alice" } },+ deliver: (_payload, adapterCtx) => {+ expect(adapterCtx.ctx.get(AuthKey)).toEqual(correctionAuth);+ (adapterCtx.state.reply as { recipient: string }).recipient = "bob";+ return undefined;+ },+ };+ const bundle = Object.assign({}, createTurnStepTestBundle() as object, {+ adapterRegistry: { adaptersByKind: new Map([[adapter.kind, adapter]]) },+ }) as never;+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(bundle);+ const emissionState = { sequence: 0, sessionStarted: true, stepIndex: 1, turnId: "turn_0" };+ const session = setHarnessEmissionState(+ createStubSession({ history: [{ role: "user", kind: "user", content: "Original request" }] }),+ emissionState,+ );+ installSessionStoreMocks([session]);+ const execute = vi.fn(async (current: HarnessSession): Promise<StepResult> => {+ expect(loadContext().get(AuthKey)).toEqual(originalAuth);+ expect(loadContext().get(TurnDeliveryIdsKey)).toEqual(["original-delivery"]);+ expect(loadContext().get(ChannelKey)?.state).toEqual({ reply: { recipient: "alice" } });+ return { next: { done: true, output: "Original answer" }, session: current };+ });+ vi.mocked(createExecutionNodeStep).mockImplementation(() => execute);+ const ctx = new ContextContainer();+ ctx.set(AuthKey, originalAuth);+ ctx.set(TurnDeliveryIdsKey, ["original-delivery"]);+ ctx.set(BundleKey, bundle);+ ctx.set(ChannelKey, adapter);+ ctx.set(ContinuationTokenKey, "ignore-correction");+ ctx.set(ModeKey, "conversation");+ ctx.set(SessionIdKey, "sess-test");++ const result = await turnStep({+ input: {+ auth: correctionAuth,+ kind: "deliver",+ payloads: [{ message: "Ignored correction" }],+ deliveryMetadata: [+ {+ channelKind: adapter.kind,+ channelName: adapter.kind,+ deliveryId: "ignored-delivery",+ payloadIndex: 0,+ },+ ],+ },+ sessionWritable: createTestWritable(),+ serializedContext: serializeContext(ctx),+ sessionState: createStubSessionState({ emissionState }),+ });+ expect(result).toMatchObject({ action: "done", output: "Original answer" });+ expect(execute).toHaveBeenCalledOnce();+ expect(execute.mock.calls[0]?.[0].history).toEqual(session.history);+ expect(result.sessionState.emissionState.turnId).toBe("turn_0");+ expect(result.serializedContext[AuthKey.name]).toEqual(originalAuth);+ expect(result.serializedContext[TurnDeliveryIdsKey.name]).toEqual(["original-delivery"]);+ });it("keeps one task stream open while hiding a scheduled fallback from delivery hooks", async () => {const appended: string[] = [];const delivered: Array<string | null> = [];diff --git a/packages/eve/src/execution/session/turn-step.ts b/packages/eve/src/execution/session/turn-step.tsindex fbdd73a77..7f62bcab5 100644--- a/packages/eve/src/execution/session/turn-step.ts+++ b/packages/eve/src/execution/session/turn-step.ts@@ -105,9 +105,6 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>let durableSession = readDurableSession(input.sessionState);const ctx = await deserializeContext(input.serializedContext);- if (rawDelivery !== undefined) {- ctx.set(TurnTaskDeliveryKey, "none");- }const adapter = ctx.require(ChannelKey);const bundle = ctx.require(BundleKey);const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);@@ -149,6 +146,8 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>}}+ const previousAuth = ctx.get(AuthKey);+// Apply deliver-time auth ferried via `resumeHook` (initial-turn// input has no auth; it was seeded by buildRunContext).if (delivery?.auth !== undefined) {@@ -171,18 +170,6 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>});const initialEmissionState = getHarnessEmissionState(initialSession.state);- if (rawDelivery?.payloads.some((payload) => payload.message !== undefined)) {- const ids = rawDelivery.deliveryMetadata?.map((entry) => entry.deliveryId) ?? [];- ctx.set(- TurnDeliveryIdsKey,- initialEmissionState.turnId- ? [...new Set([...(ctx.get(TurnDeliveryIdsKey) ?? []), ...ids])]- : ids,- );- } else if (!initialEmissionState.sessionStarted && ctx.get(ChannelDeliveryKey) !== undefined) {- ctx.set(TurnDeliveryIdsKey, [ctx.require(ChannelDeliveryKey).deliveryId]);- }-if (rawDelivery !== undefined) {await contextStorage.run(ctx, () =>instrumentation?.instrumentChannelDelivery({@@ -222,6 +209,10 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>});const { adapterCtx, dynamicConnections, effectiveNode, handleEvent } = sink;try {+ const previousAdapterState =+ delivery !== undefined && !isHarnessBetweenTurns(initialSession)+ ? structuredClone(adapterCtx.state)+ : undefined;// Run the adapter's deliver hook for each queued payload and coalesce// the resulting StepInput values; runtime results ride the same input.let resolved: StepInput | undefined;@@ -245,6 +236,32 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>}resolved = results.length === 0 ? undefined : results.reduce(coalesceTurnInputs);}+ const ignoredActiveDelivery =+ delivery !== undefined && resolved === undefined && !isHarnessBetweenTurns(initialSession);+ if (ignoredActiveDelivery) {+ // The adapter sees the incoming caller, but an ignored correction must+ // not change the identity or reply destination of the interrupted work.+ if (previousAuth === undefined) ctx.delete(AuthKey);+ else ctx.set(AuthKey, previousAuth);+ adapterCtx.state = previousAdapterState!;+ } else {+ if (rawDelivery !== undefined) ctx.set(TurnTaskDeliveryKey, "none");+ if (rawDelivery?.payloads.some((payload) => payload.message !== undefined)) {+ const ids = rawDelivery.deliveryMetadata?.map((entry) => entry.deliveryId) ?? [];+ ctx.set(+ TurnDeliveryIdsKey,+ initialEmissionState.turnId+ ? [...new Set([...(ctx.get(TurnDeliveryIdsKey) ?? []), ...ids])]+ : ids,+ );+ } else if (+ !initialEmissionState.sessionStarted &&+ ctx.get(ChannelDeliveryKey) !== undefined+ ) {+ ctx.set(TurnDeliveryIdsKey, [ctx.require(ChannelDeliveryKey).deliveryId]);+ }+ }+if (runtimeResults !== undefined) {if (runtimeResults.acceptedAtMsByCallId !== undefined) {ctx.set(RuntimeActionSettlementTimesKey, runtimeResults.acceptedAtMsByCallId);@@ -271,7 +288,7 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>activityCohort.updateActivityRootForDelivery({activeTurnId: activeTurnId(initialEmissionState),ctx,- delivery: rawDelivery,+ delivery: ignoredActiveDelivery ? undefined : rawDelivery,sessionState: durableSession.state,taskRootTurnId,});@@ -292,7 +309,7 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>setChannelContext(ctx, updatedAdapter);}- if (delivery !== undefined && resolved === undefined) {+ if (delivery !== undefined && resolved === undefined && isHarnessBetweenTurns(initialSession)) {await contextStorage.run(ctx, () =>instrumentation?.instrumentChannelDelivery({ctx,@@ -382,6 +399,7 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>const modelSession = refreshedSession;const step = createExecutionNodeStep({+ steeringSignal: input.steeringSignal,abortSignal: input.abortSignal,capabilities,clearOnly: input.input?.control === "clear",@@ -409,6 +427,7 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>// or the pending batch would re-park and later re-dispatch.throwIfTurnAborted(input.abortSignal);stepResult = await runModelCallBatch({+ steeringSignal: input.steeringSignal,initialInput: resolved,initialSession,modelCallsPerStep,diff --git a/packages/eve/src/execution/session/turn.test.ts b/packages/eve/src/execution/session/turn.test.tsindex 426b078b4..133f0cd1d 100644--- a/packages/eve/src/execution/session/turn.test.ts+++ b/packages/eve/src/execution/session/turn.test.ts@@ -44,6 +44,247 @@ beforeEach(() => {afterEach(() => vi.restoreAllMocks());describe("SessionExecution background task checkpoints", () => {+ it("retains the durable steering signal across steps until a correction uses it", async () => {+ const inbox: SessionInbox = {+ claimedTokens: [],+ claimSessionHook: vi.fn(),+ claimSessionHooks: vi.fn(),+ drain: () => [],+ hasPending: () => false,+ next: vi.fn(),+ restore: vi.fn(),+ onDelivery: () => () => {},+ onInterrupt: () => () => {},+ };+ let signal: AbortSignal | undefined;+ vi.mocked(turnStep)+ .mockReset()+ .mockImplementationOnce(async (input) => {+ signal = input.steeringSignal;+ return {+ action: "continue",+ serializedContext: input.serializedContext,+ sessionState: input.sessionState,+ };+ })+ .mockImplementationOnce(async (input) => {+ expect(input.steeringSignal).toBe(signal);+ return {+ action: "done",+ serializedContext: input.serializedContext,+ sessionState: input.sessionState,+ };+ });+ await createExecution({ inbox, sessionState: state("") }).runTurn(undefined);+ expect(turnStep).toHaveBeenCalledTimes(2);+ });+ it.each(["cancel", "reset"] as const)(+ "gives %s precedence over generation steering",+ async (kind) => {+ let deliver: (payload: SessionInboxPayload) => void = () => {};+ let interrupt: (payload: SessionInboxPayload) => void = () => {};+ const pending: SessionInboxPayload[] = [];+ const inbox: SessionInbox = {+ claimedTokens: [],+ claimSessionHook: vi.fn(),+ claimSessionHooks: vi.fn(),+ drain: () => pending.splice(0),+ hasPending: () => pending.length > 0,+ next: vi.fn(),+ restore: vi.fn(),+ onDelivery: (handler) => {+ deliver = handler;+ return () => {};+ },+ onInterrupt: (handler) => {+ interrupt = handler;+ return () => {};+ },+ };+ vi.mocked(turnStep)+ .mockReset()+ .mockImplementationOnce(async (input) => {+ const correction = { kind: "deliver", payloads: [{ message: "Correction" }] } as const;+ pending.push(correction, { kind });+ deliver(correction);+ interrupt({ kind });+ expect(input.steeringSignal?.aborted).toBe(true);+ expect(input.abortSignal?.aborted).toBe(true);+ return {+ action: "steered",+ serializedContext: input.serializedContext,+ sessionState: input.sessionState,+ };+ });+ await expect(+ createExecution({ inbox, sessionState: state("") }).runTurn(undefined),+ ).resolves.toEqual({ cancelled: true, kind: "park" });+ expect(turnStep).toHaveBeenCalledTimes(1);+ },+ );+ it("keeps a correction pumped during boundary admission attached to the next step", async () => {+ let notify: (payload: SessionInboxPayload) => void = () => {};+ const pending: SessionInboxPayload[] = [];+ const first: DeliverHookPayload = {+ kind: "deliver",+ payloads: [{ message: "First correction" }],+ };+ const second: DeliverHookPayload = {+ kind: "deliver",+ payloads: [{ message: "Second correction" }],+ };+ let drainingFirst = true;+ const inbox: SessionInbox = {+ claimedTokens: [],+ claimSessionHook: vi.fn(),+ claimSessionHooks: vi.fn(),+ drain: () => {+ const snapshot = pending.splice(0);+ if (drainingFirst) {+ drainingFirst = false;+ queueMicrotask(() => {+ pending.push(second);+ notify(second);+ });+ }+ return snapshot;+ },+ hasPending: () => pending.length > 0,+ next: vi.fn(),+ restore: vi.fn(),+ onInterrupt: () => () => {},+ onDelivery: (handler) => {+ notify = handler;+ pending.forEach(handler);+ return () => {};+ },+ };+ vi.mocked(turnStep)+ .mockReset()+ .mockImplementationOnce(async (input) => {+ pending.push(first);+ notify(first);+ return {+ action: "steered",+ serializedContext: input.serializedContext,+ sessionState: input.sessionState,+ };+ })+ .mockImplementationOnce(async (input) => {+ expect(input.input?.delivery?.payloads).toEqual(first.payloads);+ expect(input.steeringSignal?.aborted).toBe(true);+ return {+ action: "steered",+ serializedContext: input.serializedContext,+ sessionState: input.sessionState,+ };+ })+ .mockImplementationOnce(async (input) => {+ expect(input.input?.delivery?.payloads).toEqual(second.payloads);+ expect(input.steeringSignal?.aborted).toBe(false);+ return {+ action: "done",+ serializedContext: input.serializedContext,+ sessionState: input.sessionState,+ };+ });+ await createExecution({ inbox, sessionState: state("") }).runTurn(undefined);+ expect(turnStep).toHaveBeenCalledTimes(3);+ });+ it("signals generation steering, coalesces corrections in order, and continues without cancellation", async () => {+ let notify: (payload: SessionInboxPayload) => void = () => {};+ const pending: SessionInboxPayload[] = [];+ const inbox: SessionInbox = {+ claimedTokens: [],+ claimSessionHook: vi.fn(),+ claimSessionHooks: vi.fn(),+ drain: () => pending.splice(0),+ hasPending: () => pending.length > 0,+ next: vi.fn(),+ restore: vi.fn(),+ onInterrupt: () => () => {},+ onDelivery: (handler) => {+ notify = handler;+ return () => {};+ },+ };+ vi.mocked(cancelDescendantTurnsStep).mockClear();+ vi.mocked(turnStep)+ .mockReset()+ .mockImplementationOnce(async (input) => {+ for (const message of ["Actually 2025", "Include the MVP"]) {+ const delivery = { kind: "deliver", payloads: [{ message }] } as const;+ pending.push(delivery);+ notify(delivery);+ }+ expect(input.steeringSignal?.aborted).toBe(true);+ expect(input.abortSignal?.aborted).toBe(false);+ return {+ action: "steered",+ serializedContext: input.serializedContext,+ sessionState: input.sessionState,+ };+ })+ .mockImplementationOnce(async (input) => {+ expect(input.steeringSignal?.aborted).toBe(false);+ expect(input.input?.delivery?.payloads.map((payload) => payload.message)).toEqual([+ "Actually 2025",+ "Include the MVP",+ ]);+ return {+ action: "done",+ output: "Corrected",+ serializedContext: input.serializedContext,+ sessionState: input.sessionState,+ };+ });+ const execution = createExecution({ inbox, sessionState: state("") });+ await expect(+ execution.runTurn({ delivery: { kind: "deliver", payloads: [{ message: "2026?" }] } }),+ ).resolves.toMatchObject({ kind: "done", output: "Corrected" });+ expect(cancelDescendantTurnsStep).not.toHaveBeenCalled();+ });++ it.each([+ { kind: "deliver", turnPolicy: "queue", payloads: [{ message: "Queued" }] },+ { kind: "deliver", taskDeliveryId: "task-1:done", payloads: [{ message: "Notification" }] },+ {+ kind: "deliver",+ payloads: [{ inputResponses: [{ requestId: "child-request", text: "Answer" }] }],+ },+ { kind: "deliver", caller: { callId: "other-child" }, payloads: [{ message: "Other caller" }] },+ ])(+ "does not interrupt generation for non-steering delivery $kind $turnPolicy $taskDeliveryId",+ async (payload) => {+ let notify: (payload: SessionInboxPayload) => void = () => {};+ const inbox: SessionInbox = {+ claimedTokens: [],+ claimSessionHook: vi.fn(),+ claimSessionHooks: vi.fn(),+ drain: () => [],+ hasPending: () => false,+ next: vi.fn(),+ restore: vi.fn(),+ onInterrupt: () => () => {},+ onDelivery: (handler) => {+ notify = handler;+ return () => {};+ },+ };+ vi.mocked(turnStep)+ .mockReset()+ .mockImplementationOnce(async (input) => {+ notify(payload as SessionInboxPayload);+ expect(input.steeringSignal?.aborted).toBe(false);+ return {+ action: "done",+ serializedContext: input.serializedContext,+ sessionState: input.sessionState,+ };+ });+ await createExecution({ inbox, sessionState: state("") }).runTurn(undefined);+ },+ );it("cancels an admitted workflow action when cancellation already arrived at the step boundary", async () => {const sessionState = state("");const inbox: SessionInbox = {@@ -56,6 +297,7 @@ describe("SessionExecution background task checkpoints", () => {.mockReturnValue([]),hasPending: vi.fn(() => false),next: vi.fn(() => new Promise<never>(() => {})),+ onDelivery: vi.fn(() => () => {}),onInterrupt: vi.fn(() => () => {}),restore: vi.fn(),};@@ -105,6 +347,7 @@ describe("SessionExecution background task checkpoints", () => {.mockReturnValue([]),hasPending: vi.fn(() => false),next: vi.fn(() => new Promise<never>(() => {})),+ onDelivery: vi.fn(() => () => {}),onInterrupt: vi.fn((handler) => {interrupt = handler;return () => {};@@ -150,6 +393,7 @@ describe("SessionExecution background task checkpoints", () => {drain: vi.fn().mockReturnValueOnce([background, steering]).mockReturnValue([]),hasPending: vi.fn(() => false),next: vi.fn(() => new Promise<never>(() => {})),+ onDelivery: vi.fn(() => () => {}),onInterrupt: vi.fn(() => () => {}),restore: vi.fn(),};@@ -197,6 +441,7 @@ describe("SessionExecution background task checkpoints", () => {drain: vi.fn().mockReturnValueOnce([steering]).mockReturnValue([]),hasPending: vi.fn(() => false),next: vi.fn(() => new Promise<never>(() => {})),+ onDelivery: vi.fn(() => () => {}),onInterrupt: vi.fn(() => () => {}),restore: vi.fn(),};@@ -253,6 +498,7 @@ describe("SessionExecution background task checkpoints", () => {drain: vi.fn().mockReturnValueOnce([followUp]).mockReturnValue([]),hasPending: vi.fn(() => false),next: vi.fn(() => new Promise<never>(() => {})),+ onDelivery: vi.fn(() => () => {}),onInterrupt: vi.fn(() => () => {}),restore: vi.fn(),};@@ -294,6 +540,7 @@ describe("SessionExecution background task checkpoints", () => {drain: vi.fn(() => []),hasPending: vi.fn(() => false),next: vi.fn(async () => runtimePayloads.shift()),+ onDelivery: vi.fn(() => () => {}),onInterrupt: vi.fn(() => () => {}),restore: vi.fn(),};@@ -359,6 +606,7 @@ describe("SessionExecution background task checkpoints", () => {.mockReturnValue([]),hasPending: vi.fn(() => false),next: vi.fn(() => new Promise<never>(() => {})),+ onDelivery: vi.fn(() => () => {}),onInterrupt: vi.fn((handler) => {interrupt = handler;return () => {};diff --git a/packages/eve/src/execution/session/turn.ts b/packages/eve/src/execution/session/turn.tsindex dc65eed4d..e7967bc1c 100644--- a/packages/eve/src/execution/session/turn.ts+++ b/packages/eve/src/execution/session/turn.ts@@ -5,7 +5,7 @@ import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-stimport { dispatchCoordinationStep } from "#execution/coordination-dispatch-step.js";import { routeDeliverToChildren } from "#execution/route-child-delivery.js";import { routeSelectedDelivery } from "#execution/session/route-selected-delivery.js";-import type { SessionInputQueue } from "#execution/session/input-queue.js";+import { isSteeringDelivery, type SessionInputQueue } from "#execution/session/input-queue.js";import {sessionCommandHookToken,sessionInboxHookToken,@@ -30,6 +30,7 @@ import { turnStep } from "#execution/session/turn-step.js";import { activeTurnId } from "#harness/active-turn-id.js";import { coalesceDeliveries } from "#harness/messages.js";import { TurnCancelledError } from "#harness/turn-cancellation.js";+import { decodeSessionInboxPayload } from "#execution/session-inbox/protocol.js";import {isInboxSubagentResultFromRecordedWorkflowToolRun,isInboxToolResultFromRecordedWorkflowToolRun,@@ -85,7 +86,10 @@ export class SessionExecution {const { cursor } = this.input;const beforeStepContext = cursor.serializedContext;const result: DurableStepResult = await turnStep(- cursor.createStepInput(nextStepInput, turn.signal),+ cursor.createStepInput(nextStepInput, {+ abortSignal: turn.signal,+ steeringSignal: turn.steeringSignal,+ }),);const pendingCallIds =result.action === "park" ? result.pendingCoordinationCallIds : undefined;@@ -110,6 +114,7 @@ export class SessionExecution {: result.sessionState,});await turn.admitBoundary();+ turn.resetSteering();if (result.action === "cancelled") return await this.finishCancelledTurn();if (turn.signal.aborted && (pendingCallIds === undefined || hasBackgroundTasks)) {@@ -261,9 +266,9 @@ type RuntimeEvent =* the turn reaches a committed boundary; a runtime-action wait routes them* eagerly so a proxied child can receive the answer it is blocked on.*- * Cancellation is pushed by the inbox pump the moment it is accepted so the- * running step aborts immediately; its durable side effects are applied when- * the queued command is admitted at the next boundary.+ * The pump signals cancellation and eligible steering immediately. Cancellation+ * aborts the turn; steering only interrupts generation before assistant output+ * or local tool execution. Both retain ordered admission at the next boundary.*/class ActiveTurn {private readonly admitted = new Set<number>();@@ -274,6 +279,8 @@ class ActiveTurn {private readonly input: SessionExecutionInput;private readonly callerCallId: string | undefined;private readonly unsubscribe: () => void;+ private unsubscribeDelivery: () => void;+ private steeringController = new AbortController();constructor(input: SessionExecutionInput, callerCallId: string | undefined) {this.input = input;@@ -282,14 +289,50 @@ class ActiveTurn {this.unsubscribe = input.inbox.onInterrupt((payload) => {if (this.cancelsThisTurn(payload)) this.abort();});+ this.unsubscribeDelivery = input.inbox.onDelivery(this.signalSteering);}+ private readonly signalSteering = (payload: SessionInboxPayload): void => {+ let delivery;+ try {+ delivery = decodeSessionInboxPayload(payload);+ } catch {+ return;+ }+ if (+ delivery.kind === "deliver" &&+ isSteeringDelivery(delivery, this.callerCallId) &&+ !this.input.cursor.sessionState.hasProxyInputRequests &&+ delivery.payloads.some(+ (value) =>+ value.message !== undefined &&+ value.inputResponses === undefined &&+ value.task === undefined,+ )+ )+ this.steeringController.abort();+ };+get signal(): AbortSignal {return this.controller.signal;}dispose(): void {this.unsubscribe();+ this.unsubscribeDelivery();+ }++ get steeringSignal(): AbortSignal {+ return this.steeringController.signal;+ }++ resetSteering(): void {+ if (!this.steeringController.signal.aborted) return;+ this.unsubscribeDelivery();+ this.steeringController = new AbortController();+ // Admission can yield while new deliveries are pumped. Replaying the+ // unread inbox keeps those arrivals attached to the next generation.+ this.unsubscribeDelivery = this.input.inbox.onDelivery(this.signalSteering);}/** Admits everything the pump accepted while the last step ran. */diff --git a/packages/eve/src/execution/skills/instructions.ts b/packages/eve/src/execution/skills/instructions.tsindex 693b833a5..65dedaced 100644--- a/packages/eve/src/execution/skills/instructions.ts+++ b/packages/eve/src/execution/skills/instructions.ts@@ -34,7 +34,7 @@ export function formatAvailableSkillsSection(const lines = ["Available skills","Listed skills are available in this run. Do not claim a listed skill is inaccessible unless activation or workspace inspection actually fails.",- "Dynamic skill announcements update this list. They replace earlier dynamic skills and override static skills with the same name.",+ "Dynamic skill announcements replace earlier dynamic skills and override static skills with the same name. Static skills omitted from a dynamic announcement remain available.","If the user names a skill or the request clearly matches one of the descriptions below, call load_skill before proceeding.","If multiple skills match, activate the minimal set that covers the task. After activation, follow the returned instructions instead of improvising around them.","If activation fails, say so briefly and continue with the best available alternative.",diff --git a/packages/eve/src/harness/emission-state.ts b/packages/eve/src/harness/emission-state.tsindex 9705d04c5..531d5004e 100644--- a/packages/eve/src/harness/emission-state.ts+++ b/packages/eve/src/harness/emission-state.ts@@ -8,6 +8,7 @@ import { clearTurnClientContextState } from "#harness/turn-client-context.js";* workflow runtime recreates the harness at each `"use step"` boundary.*/export interface HarnessEmissionState {+ readonly assistantOutputStarted?: boolean;readonly sessionStarted: boolean;readonly sequence: number;readonly stepIndex: number;diff --git a/packages/eve/src/harness/emission.ts b/packages/eve/src/harness/emission.tsindex 455e92f6e..d8028208f 100644--- a/packages/eve/src/harness/emission.ts+++ b/packages/eve/src/harness/emission.ts@@ -105,12 +105,15 @@ export async function emitTurnPreamble();}- return {+ const nextState: HarnessEmissionState = {sessionStarted: true,sequence: state.sequence,stepIndex: steering ? state.stepIndex : 0,turnId,};+ return steering && state.assistantOutputStarted+ ? { ...nextState, assistantOutputStarted: true }+ : nextState;}/**diff --git a/packages/eve/src/harness/generation-steering.test.ts b/packages/eve/src/harness/generation-steering.test.tsnew file mode 100644index 000000000..562b60c8d--- /dev/null+++ b/packages/eve/src/harness/generation-steering.test.ts@@ -0,0 +1,93 @@+import { describe, expect, it } from "vitest";+import { GenerationSteering } from "#harness/generation-steering.js";+import {+ createMessageAppendedEvent,+ createMessageCompletedEvent,+ createReasoningAppendedEvent,+ createInputRequestedEvent,+ createStepFailedEvent,+ createTurnCompletedEvent,+} from "#protocol/message.js";++describe("GenerationSteering", () => {+ it("observes a correction received before generation starts", () => {+ const steering = new AbortController();+ steering.abort();+ const generation = new GenerationSteering({ steeringSignal: steering.signal });+ expect(() => generation.begin()).toThrow("superseded");+ generation.dispose();+ });++ it("reasoning does not protect the request and late text cannot escape after steering", () => {+ const steering = new AbortController();+ const generation = new GenerationSteering({ steeringSignal: steering.signal });+ generation.begin();+ generation.beforeEvent(+ createReasoningAppendedEvent({+ reasoningDelta: "Thinking",+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_0",+ }),+ );+ generation.beforeEvent(+ createMessageCompletedEvent({+ message: null,+ finishReason: "tool-calls",+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_0",+ }),+ );+ steering.abort();+ expect(() =>+ generation.beforeEvent(+ createMessageAppendedEvent({+ messageDelta: "Stale",+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_0",+ }),+ ),+ ).toThrow("superseded");+ expect(() => generation.protectToolExecution()).toThrow("superseded");+ generation.dispose();+ });++ it.each(["text", "prior text", "tool", "request", "completion", "failure"])(+ "preserves work after %s but still permits explicit cancellation",+ (phase) => {+ const steering = new AbortController();+ const cancellation = new AbortController();+ const generation = new GenerationSteering({+ steeringSignal: steering.signal,+ abortSignal: cancellation.signal,+ outputStarted: phase === "prior text",+ });+ generation.begin();+ if (phase === "text")+ generation.beforeEvent(+ createMessageAppendedEvent({+ messageDelta: "Answer",+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_0",+ }),+ );+ if (phase === "tool") generation.protectToolExecution();+ const coordinates = { sequence: 0, stepIndex: 0, turnId: "turn_0" };+ if (phase === "request")+ generation.beforeEvent(createInputRequestedEvent({ ...coordinates, requests: [] }));+ if (phase === "completion") generation.beforeEvent(createTurnCompletedEvent(coordinates));+ if (phase === "failure")+ generation.beforeEvent(+ createStepFailedEvent({ ...coordinates, code: "MODEL_CALL_FAILED", message: "Failed" }),+ );+ steering.abort();+ expect(generation.signal.aborted).toBe(false);+ cancellation.abort();+ expect(generation.signal.aborted).toBe(true);+ generation.dispose();+ },+ );+});diff --git a/packages/eve/src/harness/generation-steering.ts b/packages/eve/src/harness/generation-steering.tsnew file mode 100644index 000000000..6a03681a2--- /dev/null+++ b/packages/eve/src/harness/generation-steering.ts@@ -0,0 +1,87 @@+import type { UnstampedMessageStreamEvent } from "#protocol/message.js";++class GenerationSteeredError extends Error {+ constructor() {+ super("Model generation superseded by steering.");+ this.name = "GenerationSteeredError";+ }+}++/** Interrupts generation without cancelling the turn or replaying local effects. */+export class GenerationSteering {+ private readonly controller = new AbortController();+ private active = false;+ private effectsStarted = false;+ private readonly steeringSignal: AbortSignal | undefined;+ readonly signal: AbortSignal;+ outputStarted: boolean;++ constructor(input: {+ abortSignal?: AbortSignal;+ steeringSignal?: AbortSignal;+ outputStarted?: boolean;+ }) {+ this.steeringSignal = input.steeringSignal;+ this.outputStarted = input.outputStarted === true;+ this.signal =+ input.steeringSignal === undefined && input.abortSignal !== undefined+ ? input.abortSignal+ : input.abortSignal === undefined+ ? this.controller.signal+ : AbortSignal.any([input.abortSignal, this.controller.signal]);+ this.steeringSignal?.addEventListener("abort", this.onSteering);+ }++ get interrupted(): boolean {+ return this.controller.signal.aborted;+ }++ begin(): void {+ this.active = true;+ this.onSteering();+ this.check();+ }++ protectToolExecution(): void {+ this.check();+ this.effectsStarted = true;+ }++ beforeEvent(event: UnstampedMessageStreamEvent): void {+ if (!this.active) return;+ this.check();+ // Published requests and terminal events must finish committing, even+ // when the model produced no assistant text.+ if (+ event.type === "input.requested" ||+ event.type === "step.failed" ||+ event.type === "turn.completed"+ )+ this.effectsStarted = true;+ if (+ (event.type === "message.appended" && event.data.messageDelta.length > 0) ||+ (event.type === "message.completed" && (event.data.message?.length ?? 0) > 0) ||+ event.type === "result.completed"+ )+ this.outputStarted = true;+ }++ check(): void {+ if (this.interrupted) throw this.controller.signal.reason;+ }++ dispose(): void {+ this.steeringSignal?.removeEventListener("abort", this.onSteering);+ }++ private readonly onSteering = (): void => {+ if (+ this.active &&+ !this.effectsStarted &&+ !this.outputStarted &&+ this.steeringSignal?.aborted+ ) {+ this.controller.abort(new GenerationSteeredError());+ }+ };+}diff --git a/packages/eve/src/harness/prompt-cache.test.ts b/packages/eve/src/harness/prompt-cache.test.tsindex 4242a24e0..773783c50 100644--- a/packages/eve/src/harness/prompt-cache.test.ts+++ b/packages/eve/src/harness/prompt-cache.test.ts@@ -1,4 +1,4 @@-import type { LanguageModel, ModelMessage, ToolSet } from "ai";+import { createGateway, type LanguageModel, type ModelMessage, type ToolSet } from "ai";import { describe, expect, it } from "vitest";import {@@ -18,6 +18,17 @@ function makeObjectModel(provider: string, modelId = "test-model"): LanguageMode}describe("detectPromptCachePath", () => {+ it("keeps automatic caching for Gateway provider objects used by local auth", () => {+ const model = createGateway({ apiKey: "test-key" })("anthropic/claude-opus-5");+ expect(detectPromptCachePath(model)).toEqual({ kind: "gateway-auto" });+ });++ it("recognizes namespaced Gateway providers", () => {+ expect(detectPromptCachePath(makeObjectModel("gateway.language-model"))).toEqual({+ kind: "gateway-auto",+ });+ });+it("returns gateway-auto for any string model id", () => {expect(detectPromptCachePath("anthropic/claude-sonnet-4-5")).toEqual({kind: "gateway-auto",diff --git a/packages/eve/src/harness/prompt-cache.ts b/packages/eve/src/harness/prompt-cache.tsindex b94d03898..4e0929949 100644--- a/packages/eve/src/harness/prompt-cache.ts+++ b/packages/eve/src/harness/prompt-cache.ts@@ -1,4 +1,5 @@import type { LanguageModel, ModelMessage, SystemModelMessage, ToolSet } from "ai";+import { isGatewayModel } from "#internal/gateway.js";/*** The caching strategy to apply for one harness step.@@ -51,7 +52,7 @@ const ANTHROPIC_CACHE_MARKER: AnthropicCacheMarker = Object.freeze({* Runs once per harness step right after `resolveModel()`.*/export function detectPromptCachePath(model: LanguageModel): PromptCachePath {- if (typeof model === "string") {+ if (typeof model === "string" || isGatewayModel(model)) {return { kind: "gateway-auto" };}diff --git a/packages/eve/src/harness/tool-loop-steering.integration.test.ts b/packages/eve/src/harness/tool-loop-steering.integration.test.tsnew file mode 100644index 000000000..d0276bf21--- /dev/null+++ b/packages/eve/src/harness/tool-loop-steering.integration.test.ts@@ -0,0 +1,335 @@+import { jsonSchema } from "ai";+import { MockLanguageModelV3 } from "ai/test";+import { describe, expect, it, vi } from "vitest";+import { createToolLoopHarness } from "#harness/tool-loop.js";+import { getHarnessEmissionState } from "#harness/emission-state.js";+import { TurnCancelledError } from "#harness/turn-cancellation.js";+import type { HarnessSession } from "#harness/types.js";+import type { UnstampedMessageStreamEvent } from "#protocol/message.js";++type StreamResult = Awaited<ReturnType<MockLanguageModelV3["doStream"]>>;+type Part = StreamResult["stream"] extends ReadableStream<infer T> ? T : never;+const usage = {+ inputTokens: { cacheRead: 0, cacheWrite: 0, noCache: 1, total: 1 },+ outputTokens: { reasoning: 0, text: 1, total: 1 },+};++function session(): HarnessSession {+ return {+ agent: { modelReference: { id: "steering-model" }, system: "Test assistant", tools: [] },+ compaction: { recentWindowSize: 10, threshold: 100_000 },+ continuationToken: "steering-session",+ history: [],+ sessionId: "steering-session",+ };+}++function finish(controller: ReadableStreamDefaultController<Part>, text: string): void {+ controller.enqueue({ type: "text-start", id: "answer" });+ controller.enqueue({ type: "text-delta", id: "answer", delta: text });+ controller.enqueue({ type: "text-end", id: "answer" });+ controller.enqueue({ type: "finish", finishReason: { unified: "stop", raw: undefined }, usage });+ controller.close();+}++describe("generation steering with the real AI SDK", () => {+ it.each(["steer", "cancel"] as const)("wakes retry backoff immediately on %s", async (kind) => {+ vi.useFakeTimers();+ const retrying = Promise.withResolvers<void>();+ const warning = vi.spyOn(console, "warn").mockImplementation((message) => {+ if (String(message).includes("retrying")) retrying.resolve();+ });+ const steering = new AbortController();+ const cancellation = new AbortController();+ const doStream = vi.fn<MockLanguageModelV3["doStream"]>(async () => ({+ stream: new ReadableStream<Part>({+ start(controller) {+ controller.enqueue({+ type: "error",+ error: Object.assign(new Error("Connection interrupted"), { isRetryable: true }),+ });+ controller.close();+ },+ }),+ }));+ try {+ const running = createToolLoopHarness({+ mode: "conversation",+ abortSignal: cancellation.signal,+ steeringSignal: steering.signal,+ tools: new Map(),+ resolveModel: async () => new MockLanguageModelV3({ doStream }),+ handleEvent: async () => {},+ })(session(), { message: "Prepare Alice's report" });+ await retrying.promise;+ if (kind === "cancel") cancellation.abort(new TurnCancelledError());+ steering.abort();+ if (kind === "cancel") await expect(running).rejects.toBeInstanceOf(TurnCancelledError);+ else expect((await running).steered).toBe(true);+ expect(doStream).toHaveBeenCalledOnce();+ } finally {+ warning.mockRestore();+ vi.useRealTimers();+ }+ });++ it.each(["input.requested", "turn.completed", "step.failed"] as const)(+ "finishes committing %s when a correction arrives during publication",+ async (boundary) => {+ const steering = new AbortController();+ const events: UnstampedMessageStreamEvent[] = [];+ const model = new MockLanguageModelV3({+ doStream: async () => {+ if (boundary === "step.failed") throw new Error("Model unavailable");+ return {+ stream: new ReadableStream<Part>({+ start(controller) {+ controller.enqueue({+ type: "tool-call",+ toolCallId: "question-1",+ toolName: "ask_question",+ input: JSON.stringify({ prompt: "Which year should Alice use?" }),+ });+ controller.enqueue({+ type: "finish",+ finishReason: { unified: "tool-calls", raw: undefined },+ usage,+ });+ controller.close();+ },+ }),+ };+ },+ });+ const result = await createToolLoopHarness({+ mode: "conversation",+ capabilities: { requestInput: true },+ steeringSignal: steering.signal,+ tools: new Map([+ [+ "ask_question",+ {+ name: "ask_question",+ description: "Ask the user a question",+ inputSchema: jsonSchema({ type: "object" }),+ behavior: {+ availability: ["requires-request-input"],+ handling: { kind: "request-input", request: "question" },+ },+ },+ ],+ ]),+ resolveModel: async () => model,+ handleEvent: async (event) => {+ events.push(event);+ if (event.type === boundary) steering.abort();+ },+ })(session(), { message: "Report only if there is a new update" });+ expect(result.steered).toBeUndefined();+ expect(result.next).toBeNull();+ expect(events.filter((event) => event.type === boundary)).toHaveLength(1);+ expect(events.filter((event) => event.type === "session.waiting")).toHaveLength(1);+ expect(events.filter((event) => event.type === "message.appended")).toHaveLength(0);+ },+ );++ it("commits the original input and turn preamble when steering precedes model startup", async () => {+ const steering = new AbortController();+ steering.abort();+ const doStream = vi.fn<MockLanguageModelV3["doStream"]>();+ const model = new MockLanguageModelV3({ doStream });+ const events: UnstampedMessageStreamEvent[] = [];+ const result = await createToolLoopHarness({+ mode: "conversation",+ steeringSignal: steering.signal,+ tools: new Map(),+ resolveModel: async () => model,+ handleEvent: async (event) => {+ events.push(event);+ },+ })(session(), { message: "Original request" });+ expect(result.steered).toBe(true);+ expect(doStream).not.toHaveBeenCalled();+ expect(JSON.stringify(result.session.history)).toContain("Original request");+ expect(events.filter((event) => event.type === "turn.started")).toHaveLength(1);+ expect(+ events.some((event) => event.type === "turn.completed" || event.type === "turn.cancelled"),+ ).toBe(false);+ });+ it("interrupts before provider search, drops late output, and resumes the same turn", async () => {+ const steering = new AbortController();+ const reasoning = Promise.withResolvers<void>();+ const events: UnstampedMessageStreamEvent[] = [];+ let firstStream: ReadableStreamDefaultController<Part>;+ let providerSignal: AbortSignal | undefined;+ const doStream = vi+ .fn<MockLanguageModelV3["doStream"]>()+ .mockImplementationOnce(async (options) => {+ providerSignal = options.abortSignal;+ return {+ stream: new ReadableStream<Part>({+ start(controller) {+ firstStream = controller;+ controller.enqueue({ type: "stream-start", warnings: [] });+ controller.enqueue({ type: "reasoning-start", id: "thinking" });+ controller.enqueue({+ type: "reasoning-delta",+ id: "thinking",+ delta: "Checking the year",+ });+ },+ }),+ };+ })+ .mockImplementationOnce(async () => ({+ stream: new ReadableStream<Part>({+ start(controller) {+ finish(controller, "Corrected 2025 answer");+ },+ }),+ }));+ const model = new MockLanguageModelV3({ doStream });+ const createStep = (signal?: AbortSignal) =>+ createToolLoopHarness({+ mode: "conversation",+ resolveModel: async () => model,+ tools: new Map(),+ steeringSignal: signal,+ handleEvent: async (event) => {+ events.push(event);+ if (event.type === "reasoning.appended") reasoning.resolve();+ },+ });+ const running = createStep(steering.signal)(session(), { message: "Who won in 2026?" });+ await reasoning.promise;+ steering.abort();+ const interrupted = await running;+ expect(providerSignal?.aborted).toBe(true);+ expect(interrupted.steered).toBe(true);+ expect(getHarnessEmissionState(interrupted.session.state).turnId).toBe("turn_0");+ // The provider ignores abort and finishes its obsolete request anyway.+ firstStream!.enqueue({+ type: "tool-call",+ toolCallId: "search",+ toolName: "web_search",+ input: "{}",+ providerExecuted: true,+ });+ finish(firstStream!, "Stale 2026 answer");+ const result = await createStep()(interrupted.session, { message: "Actually 2025" });+ expect(result.steered).toBeUndefined();+ expect(events.filter((event) => event.type === "turn.started")).toHaveLength(1);+ expect(events.filter((event) => event.type === "turn.completed")).toHaveLength(1);+ expect(events.filter((event) => event.type === "message.received")).toHaveLength(2);+ expect(+ events.some((event) => event.type === "turn.cancelled" || event.type === "turn.failed"),+ ).toBe(false);+ const answers = events+ .filter((event) => event.type === "message.appended")+ .map((event) => event.data.messageDelta)+ .join("");+ expect(answers).toBe("Corrected 2025 answer");+ expect(JSON.stringify(doStream.mock.calls[1]?.[0].prompt)).toContain("Who won in 2026?");+ expect(JSON.stringify(doStream.mock.calls[1]?.[0].prompt)).toContain("Actually 2025");+ expect(JSON.stringify(doStream.mock.calls[1]?.[0].prompt)).not.toContain("Stale");+ });++ it("finishes a local tool once and preserves its result for the corrected model call", async () => {+ const steering = new AbortController();+ const executing = Promise.withResolvers<void>();+ const release = Promise.withResolvers<void>();+ const execute = vi.fn(async () => {+ executing.resolve();+ await release.promise;+ return "saved";+ });+ const doStream = vi+ .fn<MockLanguageModelV3["doStream"]>()+ .mockImplementationOnce(async () => ({+ stream: new ReadableStream<Part>({+ start(controller) {+ controller.enqueue({+ type: "tool-call",+ toolCallId: "save-1",+ toolName: "save",+ input: "{}",+ });+ controller.enqueue({+ type: "finish",+ finishReason: { unified: "tool-calls", raw: undefined },+ usage,+ });+ controller.close();+ },+ }),+ }))+ .mockImplementationOnce(async () => ({+ stream: new ReadableStream<Part>({+ start(controller) {+ finish(controller, "Corrected");+ },+ }),+ }));+ const model = new MockLanguageModelV3({ doStream });+ const createStep = (signal?: AbortSignal) =>+ createToolLoopHarness({+ mode: "conversation",+ steeringSignal: signal,+ resolveModel: async () => model,+ handleEvent: async () => {},+ tools: new Map([+ [+ "save",+ {+ name: "save",+ description: "Save once",+ inputSchema: jsonSchema({ type: "object" }),+ execute,+ },+ ],+ ]),+ });+ const running = createStep(steering.signal)(session(), { message: "Save this" });+ await executing.promise;+ steering.abort();+ release.resolve();+ const completed = await running;+ expect(completed.steered).toBeUndefined();+ await createStep()(completed.session, { message: "Use the corrected year" });+ expect(execute).toHaveBeenCalledOnce();+ const prompt = JSON.stringify(doStream.mock.calls[1]?.[0].prompt);+ expect(prompt).toContain("saved");+ expect(prompt).toContain("Use the corrected year");+ });++ it("does not interrupt after assistant text has been published", async () => {+ const steering = new AbortController();+ const events: UnstampedMessageStreamEvent[] = [];+ let providerSignal: AbortSignal | undefined;+ const model = new MockLanguageModelV3({+ doStream: async (options) => {+ providerSignal = options.abortSignal;+ return {+ stream: new ReadableStream<Part>({+ start(controller) {+ finish(controller, "Already streaming");+ },+ }),+ };+ },+ });+ const result = await createToolLoopHarness({+ mode: "conversation",+ steeringSignal: steering.signal,+ tools: new Map(),+ resolveModel: async () => model,+ handleEvent: async (event) => {+ events.push(event);+ if (event.type === "message.appended") steering.abort();+ },+ })(session(), { message: "Start" });+ expect(result.steered).toBeUndefined();+ expect(providerSignal?.aborted).toBe(false);+ expect(events.filter((event) => event.type === "turn.completed")).toHaveLength(1);+ });+});diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.tsindex c52bf3d3e..2ab06927d 100644--- a/packages/eve/src/harness/tool-loop.ts+++ b/packages/eve/src/harness/tool-loop.ts@@ -1,4 +1,7 @@+import { setTimeout as delay } from "node:timers/promises";import { BoundaryHookError } from "#shared/boundary-hook-error.js";+import { GenerationSteering } from "#harness/generation-steering.js";+import { interruptStreamOnFailure } from "#harness/interruptible-stream.js";import {isStepCount,type LanguageModelCallEndEvent,@@ -441,8 +444,19 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {initialSession: Readonly<Parameters<StepFn>[0]>,input?: StepInput,): Promise<StepResult> {- const executeStep = (scope: InstrumentationStepScope<HarnessSession>) =>- executeStepBody(scope.session, input, scope);+ const executeStep = async (scope?: InstrumentationStepScope<HarnessSession>) => {+ const current = scope?.session ?? initialSession;+ const generation = new GenerationSteering({+ abortSignal: config.abortSignal,+ steeringSignal: config.steeringSignal,+ outputStarted: getHarnessEmissionState(current.state).assistantOutputStarted,+ });+ try {+ return await executeStepBody(current, generation, input, scope);+ } finally {+ generation.dispose();+ }+ };return (config.instrumentation?.runStep({@@ -452,12 +466,13 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {session: initialSession,},executeStep,- ) ?? executeStepBody(initialSession, input)+ ) ?? executeStep());}async function executeStepBody(initialSession: Readonly<Parameters<StepFn>[0]>,+ generation: GenerationSteering,input?: StepInput,stepInstrumentation?: InstrumentationStepScope<HarnessSession>,): Promise<StepResult> {@@ -484,12 +499,19 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {const callback = store?.get(SessionCallbackKey);const hasDelegatedCaller = parent !== undefined || callback !== undefined;let activeAttemptScope: InstrumentationAttempt | undefined;- const emit =+ const instrumentedEmit =stepInstrumentation?.createHandleEvent({getAttemptScope: () => activeAttemptScope,handleEvent: baseEmit,turnId: activeTurnId(emissionState),}) ?? baseEmit;+ const emit: typeof instrumentedEmit =+ instrumentedEmit === undefined+ ? undefined+ : async (event, messages) => {+ generation.beforeEvent(event);+ await instrumentedEmit(event, messages);+ };const failModelSelection = async (error: unknown,failureState: ReturnType<typeof getHarnessEmissionState>,@@ -1256,6 +1278,29 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {});}const promptMessages = currentMessages.history;+ let interruptedUsage: TokenUsageDelta | undefined;+ const finishSteeredStep = (): StepResult => {+ throwIfTurnAborted(config.abortSignal);+ ctx?.set(HistoryStateKey, currentMessages.historyState);+ if (interruptedUsage !== undefined) {+ session = setTurnUsageState(+ session,+ accumulateTurnUsage({+ previous: getTurnUsageState(session.state),+ turnId: emissionState.turnId,+ usage: interruptedUsage,+ }),+ );+ }+ return {+ steered: true,+ next: runStep,+ session: setHarnessEmissionState(+ { ...session, history: [...promptMessages] },+ advanceStep(emissionState),+ ),+ };+ };// Hydrate `eve-sandbox:` ref FileParts into inline bytes for the model call// only. Session history remains ref-only across future step boundaries.@@ -1319,6 +1364,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {const runSingleModelCall = async (opts: ModelCallOptions & { readonly attemptIndex: number },): Promise<HarnessStepResult> => {+ generation.begin();const { instructions, telemetryRuntimeContext = {} } =opts.preparedInput ?? prepareModelCallInput(opts.extraSystemNote);// Label the reissued call's telemetry; without this a retry is only@@ -1387,6 +1433,20 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {const modelTools = advertisedModelTools.modelTools;const effectiveTools = marker ? applyLastToolCacheBreakpoint(modelTools, marker) : modelTools;+ for (const tool of Object.values(effectiveTools)) {+ const execute = tool.execute;+ if (execute !== undefined)+ tool.execute = (...args) => {+ generation.protectToolExecution();+ return execute(...args);+ };+ const onInputAvailable = tool.onInputAvailable;+ if (onInputAvailable !== undefined)+ tool.onInputAvailable = (...args: Parameters<typeof onInputAvailable>) => {+ generation.protectToolExecution();+ return onInputAvailable(...args);+ };+ }const instrumentationTurnId = activeTurnId(emissionState);const attempt = stepInstrumentation?.prepareAttempt({@@ -1413,6 +1473,11 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {instructions,model,onLanguageModelCallEnd(event: LanguageModelCallEndEvent) {+ if (generation.interrupted) return;+ interruptedUsage = extractTokenUsageDelta({+ usage: event.usage,+ costUsd: extractGatewayCostUsd(event.providerMetadata),+ });for (const part of event.content) {if (part.type !== "tool-call" ||@@ -1432,6 +1497,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {// Replaces the AI SDK's default `console.error`; the harness still// emits stream events, this just keeps the raw error from being silent.onError(event: { error: unknown }) {+ if (generation.interrupted) return;// Recognized configuration failures (gateway auth, missing API key)// skip the raw inspector dump — its stack points at the harness, not// the fix, and the terminal-failure path logs the one-line summary@@ -1466,7 +1532,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {...hiddenRuntimeActionToolNames,]);const streamResult = await agent.stream({- abortSignal: config.abortSignal,+ abortSignal: generation.signal,messages: callMessages,});const {@@ -1475,11 +1541,17 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {invalidInputToolCallIds,inlineAuthorizationResults,trailingInlineToolResultParts,- } = await emitStreamContent(emit, emissionState, streamResult.fullStream, {- excludedActionToolNames,- tools: advertisedHarnessTools,- });+ } = await emitStreamContent(+ emit,+ emissionState,+ interruptStreamOnFailure(streamResult.fullStream, generation.signal),+ {+ excludedActionToolNames,+ tools: advertisedHarnessTools,+ },+ );throwIfTurnAborted(config.abortSignal);+ generation.check();const [stepResult, accumulatedResponseMessages] = await Promise.all([hooks.stepResult,streamResult.responseMessages,@@ -1522,10 +1594,11 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {});}const generateResult = await agent.generate({- abortSignal: config.abortSignal,+ abortSignal: generation.signal,messages: callMessages,});throwIfTurnAborted(config.abortSignal);+ generation.check();const stepResult = await hooks.stepResult;if (stepResult.finishReason === "content-filter") {throw new ContentFilteredModelResponseError(@@ -1549,7 +1622,9 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {await attempt?.complete();return result;} catch (error) {- await attempt?.fail(error);+ if (generation.interrupted) await attempt?.complete();+ else await attempt?.fail(error);+ generation.check();return rethrowNoOutputAsEmptyResponse(error);}};@@ -1568,7 +1643,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {sessionId: session.sessionId,turnId: emissionState.turnId,},- config.abortSignal,+ generation.signal,);// Resolve first-attempt instrumentation after step.started dynamic@@ -1595,6 +1670,10 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {} catch (error) {throwIfTurnAborted(config.abortSignal);+ if (generation.interrupted) {+ return finishSteeredStep();+ }+// Stage order: drop a gateway-rejected provider tool first, then// reissue an empty response; see runModelCallRecoveryPipeline for// the skip/act semantics.@@ -1621,6 +1700,8 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {});throwIfTurnAborted(config.abortSignal);+ if (generation.interrupted) return finishSteeredStep();+if (recoveryResult.outcome === "recovered") {result = recoveryResult.result;} else {@@ -1812,6 +1893,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {}),});session = setTurnUsageState(session, nextTurnUsage);+ interruptedUsage = undefined;// `formatLanguageModelGatewayId` requires `model.provider` to be a string;// mock models in tests omit it, so guard the lookup so a missing field// becomes `undefined` and is dropped by `setEveAttributes` instead of@@ -1834,20 +1916,30 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {// --- Handle result ------------------------------------------------------- const stepResult = await handleStepResult({- config,- emit,- emissionState,- durableModelPromptMessageCount:- turnClientContext === undefined || turnClientContext.messages.length === 0- ? modelMessages.length- : undefined,- promptMessages,- result,- runStep,- session,- coordinationTools: modelCallCoordinationTools,- });+ let stepResult: StepResult;+ try {+ generation.check();+ stepResult = await handleStepResult({+ config,+ emit,+ emissionState: generation.outputStarted+ ? { ...emissionState, assistantOutputStarted: true }+ : emissionState,+ durableModelPromptMessageCount:+ turnClientContext === undefined || turnClientContext.messages.length === 0+ ? modelMessages.length+ : undefined,+ promptMessages,+ result,+ runStep,+ session,+ coordinationTools: modelCallCoordinationTools,+ });+ } catch (error) {+ throwIfTurnAborted(config.abortSignal);+ if (generation.interrupted) return finishSteeredStep();+ throw error;+ }// The returned session now owns these messages; persist their baseline with it.ctx?.set(HistoryStateKey, currentMessages.historyState);return stepResult;@@ -3133,14 +3225,14 @@ function resolveApprovalKeyFromTools(async function runModelCallWithRetries<T>(fn: (attempt: number) => Promise<T>,diag: { readonly sessionId: string; readonly turnId: string },- abortSignal?: AbortSignal,+ signal: AbortSignal,): Promise<T> {for (let attempt = 1; ; attempt++) {- throwIfTurnAborted(abortSignal);+ signal.throwIfAborted();try {return await fn(attempt);} catch (error) {- throwIfTurnAborted(abortSignal);+ signal.throwIfAborted();if (attempt === MODEL_CALL_MAX_ATTEMPTS || classifyModelCallError(error) !== "retry") {throw error;}@@ -3153,7 +3245,7 @@ async function runModelCallWithRetries<T>(turnId: diag.turnId,error,});- await new Promise((resolve) => setTimeout(resolve, delayMs));+ await delay(delayMs, undefined, { signal });}}}diff --git a/packages/eve/src/harness/types.ts b/packages/eve/src/harness/types.tsindex bd42083be..6facf3842 100644--- a/packages/eve/src/harness/types.ts+++ b/packages/eve/src/harness/types.ts@@ -212,6 +212,7 @@ export interface SettledTurn {* Result returned by one harness step invocation.*/export interface StepResult {+ readonly steered?: true;/** Background-tool effects projected onto the session that entered this step. */readonly backgroundTaskSession?: HarnessSession;/** Durable tasks started by background tools and awaiting the parent commit barrier. */@@ -273,6 +274,7 @@ export type HandleEventFn = (* Dependencies injected into the tool-loop harness at construction time.*/export interface ToolLoopHarnessConfig {+ readonly steeringSignal?: AbortSignal;/** Cancellation signal for the active turn. */readonly abortSignal?: AbortSignal;/**diff --git a/packages/eve/src/instrumentation/channel-delivery.test.ts b/packages/eve/src/instrumentation/channel-delivery.test.tsindex 77f3b35b9..7b7f911d6 100644--- a/packages/eve/src/instrumentation/channel-delivery.test.ts+++ b/packages/eve/src/instrumentation/channel-delivery.test.ts@@ -209,4 +209,63 @@ describe("channel delivery instrumentation", () => {principalType: "anonymous",});});++ it("terminates every distinct delivery admitted before the turn completes", async () => {+ const started = vi.fn();+ const completed = vi.fn();+ const hooks = createInstrumentationHooks([+ {+ events: {+ "channel.delivery.completed": completed,+ "channel.delivery.started": started,+ },+ name: "delivery-lifecycle",+ tracePolicy: () => true,+ },+ ]);+ const ctx = new ContextContainer();+ setConversation(ctx, "private");+ const instrumentation = bindHooks(hooks, ctx);+ const delivery = (deliveryId: string, message: string) => ({+ deliveryMetadata: [+ {+ channelKind: "channel:slack" as const,+ channelName: "slack",+ deliveryId,+ payloadIndex: 0,+ },+ ],+ kind: "deliver" as const,+ payloads: [{ message }],+ });++ await contextStorage.run(ctx, async () => {+ for (const value of [+ delivery("delivery-original", "Read Alice's report."),+ delivery("delivery-steering", "Actually, use the 2025 report."),+ delivery("delivery-steering", "Actually, use the 2025 report."),+ ]) {+ await instrumentation?.instrumentChannelDelivery({+ ctx,+ delivery: value,+ rootSessionId: "session-1",+ sequence: 0,+ sessionId: "session-1",+ turnId: "turn_0",+ });+ }+ await instrumentation?.instrumentChannelDelivery({+ ctx,+ includeTurn: true,+ outcome: "completed",+ });+ });++ expect(started).toHaveBeenCalledTimes(2);+ expect(completed).toHaveBeenCalledTimes(2);+ expect(completed.mock.calls.map(([event]) => event.delivery.deliveryId).sort()).toEqual([+ "delivery-original",+ "delivery-steering",+ ]);+ });});diff --git a/packages/eve/src/instrumentation/channel-delivery.ts b/packages/eve/src/instrumentation/channel-delivery.tsindex a44eac4ca..5e35a09e4 100644--- a/packages/eve/src/instrumentation/channel-delivery.ts+++ b/packages/eve/src/instrumentation/channel-delivery.ts@@ -77,7 +77,7 @@ export async function instrumentChannelDelivery(if (input.hooks === undefined || input.delivery.deliveryMetadata === undefined) return;- const active: ActiveChannelDelivery[] = [];+ const active: ActiveChannelDelivery[] = [...(input.ctx.get(ActiveChannelDeliveriesKey) ?? [])];const conversation = input.ctx.get(ConversationContextKey) ?? UNKNOWN_CONVERSATION_CONTEXT;const channelAudience = conversation.audience;const hooks =@@ -108,6 +108,15 @@ export async function instrumentChannelDelivery(sessionId: input.sessionId,turnId: input.turnId,};+ if (+ active.some(+ (candidate) =>+ candidate.sessionId === item.sessionId &&+ candidate.delivery.deliveryId === item.delivery.deliveryId,+ )+ ) {+ continue;+ }active.push(item);await hooks?.publish({agentName: item.agentName,diff --git a/packages/eve/src/internal/gateway.ts b/packages/eve/src/internal/gateway.tsindex bfc8d92ae..63a6bbf57 100644--- a/packages/eve/src/internal/gateway.ts+++ b/packages/eve/src/internal/gateway.ts@@ -29,6 +29,6 @@ export function resolveProviderHeaders(model: LanguageModel): Record<string, strreturn Object.fromEntries(appendPackageUserAgent(new Headers()));}-function isGatewayModel(model: LanguageModel): boolean {+export function isGatewayModel(model: LanguageModel): boolean {return typeof model === "string" || model.provider?.split(".")[0] === "gateway";}diff --git a/packages/eve/src/internal/testing/session-test-helpers.ts b/packages/eve/src/internal/testing/session-test-helpers.tsnew file mode 100644index 000000000..594f6991c--- /dev/null+++ b/packages/eve/src/internal/testing/session-test-helpers.ts@@ -0,0 +1,26 @@+import { expect, vi } from "vitest";+import { hydrateStepReturnValue } from "#compiled/@workflow/core/serialization.js";+import type { DurableStepResult } from "#execution/session/turn-step-types.js";+import { getWorld } from "#internal/workflow/runtime.js";++export async function waitForParkedTurnStep(runId: string, count = 1): Promise<void> {+ // Stream publication precedes the durable commit. Tests that require an+ // idle owner must wait for the committed park before delivering input.+ await vi.waitFor(+ async () => {+ const steps = await (await getWorld()).steps.list({ runId, resolveData: "all" });+ let parked = 0;+ for (const step of steps.data) {+ if (!step.stepName.endsWith("//turnStep") || step.output === undefined) continue;+ const result: DurableStepResult = await hydrateStepReturnValue(+ step.output,+ runId,+ undefined,+ );+ if (result.action === "park") parked++;+ }+ expect(parked).toBeGreaterThanOrEqual(count);+ },+ { timeout: 10_000 },+ );+}diff --git a/packages/eve/test/scenarios/steering.scenario.test.ts b/packages/eve/test/scenarios/steering.scenario.test.tsnew file mode 100644index 000000000..7638b8384--- /dev/null+++ b/packages/eve/test/scenarios/steering.scenario.test.ts@@ -0,0 +1,122 @@+import { describe, expect, it } from "vitest";+import { Client } from "../../src/client/client.js";+import { type MessageStreamEvent, isCurrentTurnBoundaryEvent } from "../../src/protocol/message.js";+import { useScenarioApp } from "../../src/internal/testing/scenario-app.js";+import { startEveDev } from "./dev-server-harness.js";++const scenarioApp = useScenarioApp();++describe("durable generation steering", () => {+ it.each([undefined, "1"])(+ "does not repeat a model step when background children wake the owner (lease %s)",+ async (leaseSeconds) => {+ const app = await scenarioApp({+ name: "steering-background-wakes",+ installDependencies: true,+ files: {+ "agent/instructions.md": "Delegate the five work items.\n",+ "agent/agent.ts": `import { defineAgent } from "eve";+import { mockModel } from "eve/evals";+export default defineAgent({+ model: mockModel(async ({ toolResults }) => {+ if (toolResults.length === 0) return { toolCalls: Array.from({ length: 5 }, (_, i) => ({+ id: "work-" + i, name: "worker", input: { message: "Work item " + i },+ })) };+ await new Promise(resolve => setTimeout(resolve, 3000));+ return "Work delegated";+ }),+ modelContextWindowTokens: 32000,+});`,+ "agent/subagents/worker/instructions.md": "Complete the work item.\n",+ "agent/subagents/worker/agent.ts": `import { defineAgent } from "eve";+import { mockModel } from "eve/evals";+export default defineAgent({+ description: "Complete a work item in the background.",+ model: mockModel(async () => {+ await new Promise(resolve => setTimeout(resolve, 2000));+ return "Work complete";+ }),+ modelContextWindowTokens: 32000,+});`,+ },+ });+ const server = await startEveDev(app.appRoot, {+ env: {+ EVE_MOCK_AUTHORED_MODELS: "",+ NODE_ENV: "production",+ WORKFLOW_INLINE_OWNERSHIP_LEASE_SECONDS: leaseSeconds,+ },+ });+ try {+ const client = new Client({ host: server.url });+ const { response } = await client.sessions.create({ message: "Start five work items." });+ const result = await response.result();+ const events = result.events;+ const steps = events+ .filter((event) => event.type === "step.started")+ .map((event) => `${event.data.turnId}:${event.data.stepIndex}`);+ expect(steps).toHaveLength(2);+ expect(new Set(steps).size).toBe(steps.length);+ expect(events.filter((event) => event.type === "turn.completed")).toHaveLength(1);+ } finally {+ await server.stop();+ }+ },+ 360_000,+ );+ it("interrupts a pending request through the public session API and keeps one turn", async () => {+ const app = await scenarioApp({+ name: "generation-steering",+ installDependencies: true,+ files: {+ "agent/instructions.md": "Answer the latest request.\n",+ "agent/agent.ts": `import { defineAgent } from "eve";+import { mockModel } from "eve/evals";+export default defineAgent({+ model: mockModel(async ({ lastUserMessage }) => {+ if (lastUserMessage?.includes("Actually 2025")) return "Corrected 2025 answer";+ await new Promise(resolve => setTimeout(resolve, 10000));+ return "Stale 2026 answer";+ }),+ modelContextWindowTokens: 32000,+ experimental: { workflow: { modelCallsPerStep: 3 } },+});`,+ },+ });+ const server = await startEveDev(app.appRoot, {+ env: { EVE_MOCK_AUTHORED_MODELS: "", NODE_ENV: "production" },+ });+ try {+ const client = new Client({ host: server.url });+ const { session, response } = await client.sessions.create({ message: "Who won in 2026?" });+ const events: MessageStreamEvent[] = [];+ const started = Promise.withResolvers<void>();+ const collecting = (async () => {+ for await (const event of response) {+ events.push(event);+ if (event.type === "step.started") started.resolve();+ if (isCurrentTurnBoundaryEvent(event)) break;+ }+ })();+ await started.promise;+ const corrected = await session.send("Actually 2025", { turnPolicy: "steer" });+ const result = await corrected.result();+ await collecting;+ expect(result.status).toBe("waiting");+ expect(events.filter((event) => event.type === "turn.started")).toHaveLength(1);+ expect(events.filter((event) => event.type === "turn.completed")).toHaveLength(1);+ expect(events.filter((event) => event.type === "message.received")).toHaveLength(2);+ expect(+ events.some((event) => event.type === "turn.cancelled" || event.type === "turn.failed"),+ ).toBe(false);+ expect(+ events+ .filter((event) => event.type === "message.appended")+ .map((event) => event.data.messageDelta)+ .join(""),+ ).toBe("Corrected 2025 answer");+ } finally {+ await server.stop();+ }+ }, 360_000);+});diff --git a/packages/eve/test/tui-client/tui-steer.ts b/packages/eve/test/tui-client/tui-steer.tsindex 104a97898..517b80fb6 100644--- a/packages/eve/test/tui-client/tui-steer.ts+++ b/packages/eve/test/tui-client/tui-steer.ts@@ -45,7 +45,7 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {await screen.waitForIdlePrompt(5_000);- // A long first turn holds the stream open while messages queue behind it.+ // A long first turn holds the stream open while Enter submits steering.input.type("Write a short story of about 150 words about tides. Do not use any tools.");input.enter();await screen.waitForText("Working for", 30_000);