The Open Framework for Building Agents
feat(eve): run sessions in one owner workflow with deployment handoff (#3263)
Andrew Barba61d409744341
diff --git a/.changeset/short-stream-bursts.md b/.changeset/short-stream-bursts.mdnew file mode 100644index 000000000..d90f79adb--- /dev/null+++ b/.changeset/short-stream-bursts.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Batch closely spaced stream events on Vercel within a 10 ms window to reduce network writes. Explicit Workflow stream-flush overrides remain supported.diff --git a/.changeset/single-owner-sessions.md b/.changeset/single-owner-sessions.mdnew file mode 100644index 000000000..04ef750a9--- /dev/null+++ b/.changeset/single-owner-sessions.md@@ -0,0 +1,9 @@+---+"eve": minor+---++Run every conversational turn directly inside the session's owning workflow instead of dispatching a child turn run per message. An idle session hands its settled state to the exact deployment that accepted a new delivery, whether the delivery arrives through the session ID or any channel continuation address, keeping the original session ID and event stream and renewing the session's configured timeout. Deliveries that land while a handoff is in progress wait for the successor instead of starting a replacement session.++Steering a running turn applies at the next committed step boundary without cancelling in-flight model or tool work and preserves the turn's identity and usage; input that arrives after the model has answered starts the next turn. `continuation.rekey()` is replaced by `continuation.alias()`: every claimed address stays active, and the most recently selected alias is exposed as `continuation.token`.++Sessions from the former driver/turn execution model are imported on their next turn, preserving identity, history, and the original stream while interrupting pending work; drivers started before eve 0.45 are reported inactive and their channel starts a fresh session. Retain the original deployment until imported sessions end, and retire sessions before rolling back across this boundary.diff --git a/.github/scripts/capture-workflow-events.mjs b/.github/scripts/capture-workflow-events.mjsnew file mode 100644index 000000000..3c626f687--- /dev/null+++ b/.github/scripts/capture-workflow-events.mjs@@ -0,0 +1,30 @@+import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";+import { join } from "node:path";++const [fixtureDirectory, outputDirectory] = process.argv.slice(2);+if (!fixtureDirectory || !outputDirectory) {+ throw new Error("Usage: capture-workflow-events.mjs <fixture-directory> <output-directory>");+}++const directory = join(fixtureDirectory, ".eve", ".workflow-data", "events");+const files = await readdir(directory).catch((error) => {+ if (error.code === "ENOENT") return [];+ throw error;+});+const events = [];+for (const file of files.filter((file) => file.endsWith(".json"))) {+ const event = JSON.parse(await readFile(join(directory, file), "utf8"));+ // Never retain serialized inputs, hook payloads, credentials, or model content.+ events.push({+ runId: event.runId,+ eventId: event.eventId,+ eventType: event.eventType,+ correlationId: event.correlationId,+ createdAt: event.createdAt,+ stepName: event.eventData?.stepName,+ ownerMessageId: event.eventData?.ownerMessageId,+ });+}+events.sort((a, b) => String(a.eventId).localeCompare(String(b.eventId)));+await mkdir(outputDirectory, { recursive: true });+await writeFile(join(outputDirectory, "workflow-events.json"), JSON.stringify(events, null, 2));diff --git a/.github/workflows/e2e-local.yml b/.github/workflows/e2e-local.ymlindex f14a21d7a..d45e61020 100644--- a/.github/workflows/e2e-local.yml+++ b/.github/workflows/e2e-local.yml@@ -137,6 +137,10 @@ jobs:pnpm exec eve eval --strict --verbose \--junit "$EVE_EVAL_JUNIT_DIR/${{ matrix.name }}-${{ matrix.model_name }}.xml"+ - name: Capture failed workflow event ordering+ if: failure() && needs.changes.outputs.relevant == 'true'+ run: node .github/scripts/capture-workflow-events.mjs "${{ matrix.dir }}" .artifacts+- name: Upload eval artifactsif: (failure()) && needs.changes.outputs.relevant == 'true'uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1@@ -144,6 +148,7 @@ jobs:name: eval-artifacts-${{ matrix.name }}-${{ matrix.model_name }}path: |.junit+ .artifacts/workflow-events.jsone2e/fixtures/*/.eve/evalsapps/fixtures/*/.eve/evals${{ matrix.dir }}/.eve/tracesdiff --git a/apps/fixtures/agent-tui-client/agent/channels/anchored.ts b/apps/fixtures/agent-tui-client/agent/channels/anchored.tsindex 85a156eeb..8f57ec4d0 100644--- a/apps/fixtures/agent-tui-client/agent/channels/anchored.ts+++ b/apps/fixtures/agent-tui-client/agent/channels/anchored.ts@@ -93,7 +93,7 @@ export default defineChannel({continuation !== undefined &&!continuation.token.endsWith(`:${anchorToken}`)) {- continuation.rekey(anchorToken);+ continuation.alias(anchorToken);}},},diff --git a/docs/agent-config.md b/docs/agent-config.mdindex 5bc086a1d..7e73a91cb 100644--- a/docs/agent-config.md+++ b/docs/agent-config.md@@ -163,10 +163,12 @@ export default defineAgent({});```-`sessionTimeoutMs` sets an absolute lifetime for every session, including-delegated sessions. It defaults to 30 days, starts at creation, and survives-restarts and redeployments. At the deadline, eve lets an active turn settle,-then emits `session.completed` and releases the continuation; the next+`sessionTimeoutMs` sets the lifetime for every session, including delegated+sessions. It defaults to 30 days and starts at creation. Each successful+deployment handoff or legacy-session import restarts the original configured+duration. Process restarts, ordinary messages, and failed or skipped handoffs+keep the existing deadline. At the deadline, eve lets an active turn settle,+then emits `session.completed` and releases every continuation address; the nextqualifying channel message starts fresh. Set it to `false` to disable thetimeout. Expiration does not delete stored session data.@@ -275,10 +277,9 @@ 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 cancels the-active model-and-tool cycle, commits earlier completed cycles in the batch, and-starts the replacement turn from that state. It does not roll the session back-to the beginning of the batch. This option is experimental and may change or+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 ordisappear in any release. See [Execution model anddurability](./concepts/execution-model-and-durability#resuming-after-a-crash)for the retry behavior.@@ -304,10 +305,10 @@ export default defineAgent({});```-This will be applied to the session run and every turn run the session-dispatches, as well as the run that collects session activity. Runs eve-starts for other purposes keep the world's default: session timeouts,-background tasks, and [workflow tools](./tools/workflows).+This applies to every run that owns the session, including successor owners+started after a deployment handoff, and to the run that collects session+activity. Runs eve starts for other purposes keep the world's default: session+timeouts, background tasks, and [workflow tools](./tools/workflows).The value applies per agent. A [subagent](./subagents) that runs its own sessionuses its own value, unlike `experimental.workflow.world`, which is root-only.diff --git a/docs/channels/chat-sdk.mdx b/docs/channels/chat-sdk.mdxindex e5c88098e..3ee86272e 100644--- a/docs/channels/chat-sdk.mdx+++ b/docs/channels/chat-sdk.mdx@@ -108,7 +108,7 @@ bot.onNewMention(async (thread, message) => {### Steering-Messages default to `turnPolicy: "steer"`: a message sent while an eve turn is active is durably buffered, then cancels that turn and starts as its replacement. Set `turnPolicy: "queue"` when the active turn should finish first:+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:```tsbot.onSubscribedMessage(async (thread, message) => {@@ -119,7 +119,7 @@ bot.onSubscribedMessage(async (thread, message) => {});```-Cancellation-backed steering emits `turn.cancelled`, and the replacement message starts a new turn with a new turn ID. Partial output and completed side effects from the interrupted turn are not rolled back. If no turn is active, the message is sent normally. You can set the policy once on `chatSdkChannel({ turnPolicy })` or override it per `send(...)`.+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(...)`.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 6d8bf7f8f..dd5022413 100644--- a/docs/channels/custom.mdx+++ b/docs/channels/custom.mdx@@ -70,12 +70,12 @@ Each route receives these operation surfaces:Event handlers receive `(eventData, channel, ctx)`. `ctx.session.id` identifiesthe exact session, while `channel.continuation` exposes the current address and-`rekey()` when this channel needs to move it. `session.failed` receives only-`(eventData, channel)` because it runs outside session context; its event data-contains `sessionId` directly.+`alias()` when this channel needs to add another address. `session.failed`+receives only `(eventData, channel)` because it runs outside session context;+its event data contains `sessionId` directly.`channel.continuation.token` is always the channel-local address accepted by-`from()`, `resolveSession()`, and `rekey()`. Framework namespace prefixes are not+`from()`, `resolveSession()`, and `alias()`. Framework namespace prefixes are notpart of the authored channel API.## Channel operations and session handles@@ -127,7 +127,7 @@ 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 durably buffered before eve cancels that turn and starts the message as a replacement turn. Configure `turnPolicy: "queue"` on `defineChannel(...)` when active turns should finish in order, or override one send:+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:```tsexport default defineChannel({@@ -358,11 +358,11 @@ twilioContinuationToken("+15551234567", "+15557654321"); // "+15551234567:+15557Custom channels write their own function that joins the identity fields. The framework derives nothing for you; the channel owns its token format.-When the identity that should address a session is not known until later, re-key the live address with `channel.continuation?.rekey(rawToken)`. The runtime preserves the current channel namespace.+When another identity should address a session, add it with `channel.continuation?.alias(rawToken)`. The runtime preserves the current channel namespace and exposes the new token as `channel.continuation.token` for later handlers.-Re-keying changes the address of the current session. `reset` is different: it terminally retires the current session and makes its existing address available to a later `send()`. `cancel` is narrower still: it stops only the active turn and leaves the session, history, and continuation-token ownership intact.+Aliasing adds an address to the current session. Earlier addresses continue to resolve to the same session and accept the same payloads. `reset` terminally retires the current session and makes all its addresses available to later `send()` calls. `cancel` stops only the active turn and leaves the session, history, and continuation-token ownership intact.-The `context(state, session)` config option builds the per-step `channel` argument handed to every event handler. It receives the channel's live adapter `state` and a `SessionHandle`, and returns the channel-owned context (thread handles, API clients, late-bound callbacks). The framework injects [`ChannelContinuationOps`](#define-a-channel) and passes the result as the second positional argument to each handler. Closing over `session` lets the factory register callbacks that re-key the address later. State mutations made through the returned context are written back to adapter state.+The `context(state, session)` config option builds the per-step `channel` argument handed to every event handler. It receives the channel's live adapter `state` and a `SessionHandle`, and returns the channel-owned context (thread handles, API clients, late-bound callbacks). The framework injects [`ChannelContinuationOps`](#define-a-channel) and passes the result as the second positional argument to each handler. Closing over `session` lets the factory register callbacks that add an alias later. State mutations made through the returned context are written back to adapter state.```tsimport { defineChannel } from "eve/channels";@@ -376,7 +376,7 @@ defineChannel<{ ref: string | null }>({state,registerAnchor(ref: string) {state.ref = ref;- session.continuation?.rekey(ref);+ session.continuation?.alias(ref);},};},@@ -389,7 +389,9 @@ defineChannel<{ ref: string | null }>({});```-At the next workflow boundary, the runtime claims the new park hook before releasing the old token. If another active session already owns the new token, the re-keying session fails instead of taking it over. After a successful re-key, inbound deliveries still addressed to the old token are dropped, so coordinate with your senders to use the new token.+At the next workflow boundary, the runtime adds the new address to the session's merged inbox. If another active session already owns the new token, the aliasing session fails instead of taking it over. Every address claimed by the session remains active until the session ends or resets. Sessions with continuation addresses remain on their current deployment until Workflow supports atomic ownership transfer.++Tokens must be nonempty. A session supports up to 256 addresses, including its stable inbox; repeating an existing alias does not consume another address.## File uploadsdiff --git a/docs/channels/eve.mdx b/docs/channels/eve.mdxindex 2580e55a9..45a481cb0 100644--- a/docs/channels/eve.mdx+++ b/docs/channels/eve.mdx@@ -78,7 +78,7 @@ 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 before cooperatively cancelling that turn, then starts the follow-up as a replacement turn with a new turn ID. Set `turnPolicy: "queue"` on `eveChannel(...)` when follow-ups should wait for active turns to finish. `inputResponses` never steer.+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.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 d47f98632..444c0c8a1 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 cooperatively cancels an active turn and steers its replacement turn.+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.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 3f4981590..931e6baf4 100644--- a/docs/channels/overview.mdx+++ b/docs/channels/overview.mdx@@ -28,7 +28,7 @@ own.## Overlapping messages-Channels default to `turnPolicy: "steer"`. When an accepted message arrives while a turn is active, eve first durably buffers the message, then cooperatively cancels the active turn and starts a replacement turn. The cancelled turn emits `turn.cancelled` followed by `session.waiting`; the replacement starts with a new turn ID. Output already streamed and completed side effects are not rolled back.+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.Set `turnPolicy: "queue"` on any built-in or custom channel when each turn must finish before the next message starts:diff --git a/docs/channels/photon.mdx b/docs/channels/photon.mdxindex bd491aef6..897d178fe 100644--- a/docs/channels/photon.mdx+++ b/docs/channels/photon.mdx@@ -25,7 +25,7 @@ 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-cooperatively cancels an active turn and steers its replacement turn.+steers the active turn at the next committed workflow boundary.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 d73ecf74c..4d24d71df 100644--- a/docs/channels/slack.mdx+++ b/docs/channels/slack.mdx@@ -294,7 +294,7 @@ export default slackChannel({#### Control overlapping turns-Accepted Slack messages use cancellation-backed steering by default: eve buffers the new message, cancels the active turn, and starts a replacement turn. Admission happens first, so ignored mentions and messages rejected by your hooks never cancel work. Set `turnPolicy: "queue"` when every active turn should finish:+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:```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 8d5521fd5..3cb9db085 100644--- a/docs/concepts/execution-model-and-durability.mdx+++ b/docs/concepts/execution-model-and-durability.mdx@@ -13,7 +13,7 @@ Work nests in three levels:- **turn**: one user message and all the work it triggers (model calls, tool calls, reasoning) until the agent produces its response.- **step**: a durable checkpoint inside a turn. By default, it contains one model call and the inline tool calls that follow it.-Every turn runs as a durable workflow, built on the open-source [Workflow SDK](https://workflow-sdk.dev/) (Vercel Workflow when you deploy on Vercel). eve checkpoints progress and serializes durable state at each step boundary. Your code runs inside a managed step, so tools, the sandbox, and subagents feel synchronous even though the session underneath them is durable.+Every session runs as one durable workflow, built on the open-source [Workflow SDK](https://workflow-sdk.dev/) (Vercel Workflow when you deploy on Vercel). The session workflow executes each turn and checkpoints progress at step boundaries. Your code runs inside a managed step, so tools, the sandbox, and subagents feel synchronous even though the session underneath them is durable.The experimental[`workflow.modelCallsPerStep`](../agent-config#workflow-checkpoint-batching)@@ -21,9 +21,40 @@ agent setting can group several sequential model-and-tool cycles into oneWorkflow step. This reduces checkpoint overhead but makes the entire group onereplay unit.-The Workflow SDK is not inherently tied to Vercel. In local development and in a self-deployed `eve start` process, eve uses the SDK's local world by default; that world persists workflow runs on disk under `.eve/.workflow-data` and dispatches through the same Nitro-hosted workflow routes. On Vercel, the same workflow code runs against Vercel Workflow instead, which adds platform features such as latest production deployment routing and dashboard run metadata.+The Workflow SDK is not inherently tied to Vercel. In local development and in a self-deployed `eve start` process, eve uses the SDK's local world by default; that world persists workflow runs on disk under `.eve/.workflow-data` and dispatches through the same Nitro-hosted workflow routes. On Vercel, the same workflow code runs against Vercel Workflow instead, which adds deployment-aware routing and dashboard run metadata.-When a Vercel production deployment changes, the next model turn in an existing session uses that deployment's current system-role instructions, model, and tools. Static user-role instructions stay pinned in the durable conversation history and are not seeded again. Identity-based channels such as Telegram private chats and Twilio phone-number conversations therefore adopt agent behavior updates without duplicating or rewriting their existing context.+When a Vercel production deployment changes, a new delivery to an idle session hands the session's settled state to the exact deployment that accepted the request. This applies whether the delivery arrives through the session ID or through any channel continuation address the session has claimed. The session keeps its original ID and event stream, while the next model turn uses that deployment's current system-role instructions, model, and tools. Static user-role instructions stay pinned in the durable conversation history and are not seeded again. A successful handoff restarts the session's original configured [`sessionTimeoutMs`](../agent-config#runtime-limits) duration; disabled timeouts stay disabled. Failed or skipped handoffs keep the existing deadline.++Before taking ownership, the target deployment validates the checkpoint's stored tasks and subagent handles and checks that no pending work remains. This includes settled tasks. If that validation fails, the previous owner recovers the session and processes the triggering delivery. Task and handle state preserve unknown metadata fields, while known fields and lifecycle rules must still be valid. Authored session state remains opaque to this validation.++eve does not move live work between deployments. A session with a running turn, pending human input or authorization, queued messages, or active tasks and subagents stays on its current deployment. After that work settles, a later delivery can move the idle session; the earlier deployment signal is not remembered.++### Upgrading sessions from the former execution model++You can upgrade directly from a release that used a session driver and separate+turn workflows. When an existing driver next dispatches a turn to this deployment,+eve imports its committed conversation into the current runtime. The session+keeps its ID, history, authored state, usage, limits, and original event stream.+Subsequent turns use the new deployment's instructions, model, and tools.++This is a one-time interruption of pending work. Old tool calls, subagents,+input requests, and authorization attempts are abandoned; start that work again+if it is still needed. Messages already buffered exclusively inside the old+driver are not imported. The triggering message is preserved without repeating+committed tool effects.++Import supports drivers started on eve 0.45 or later. A session from an older+release reports itself inactive on its next message, and its channel starts a+fresh session.++Keep the original deployment available until these sessions end. Their old+drivers remain waiting to keep the original streams open; the current runtime+owns subsequent turns. Import restarts the original configured session timeout;+disabled timeouts stay disabled. A driver+that has not reached its next turn dispatch has not migrated yet.++Transparent rollback to the former execution model is unsupported. Retire and+restart affected sessions before rolling back.Nitro hosts the HTTP routes and workflow entrypoints. It does not supply the workflow state store or the sandbox runtime. Those are separate adapters: Workflow uses the active world implementation, and Sandbox uses the backend from `agent/sandbox` or `defaultBackend()`.@@ -70,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 does not replay or discard the whole batch. eve aborts the active-model-and-tool cycle, commits earlier completed cycles in the batch, and starts-the replacement turn from that state in the next Workflow step.+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.Durability itself needs no configuration. eve owns the workflow lifecycle, andsessions are durable by default; checkpoint batching is an explicit@@ -102,15 +133,29 @@ ID-addressed HTTP delivery and a channel-address delivery both target thesession's current command inbox; neither is a general message queue.Only one active session can own a channel continuation token. A channel-created-session commits both its stable session-ID alias and its channel alias before-processing the first turn, and fails creation if another run already owns the-channel alias. Rekeying replaces only that channel alias. An HTTP-created-session has the stable ID alias and no channel continuation token. Competing-channel input is not forwarded to the owner.--When a session is waiting, a delivery through its ID or current channel address wakes it and starts the next turn. Message sends default to `turnPolicy: "steer"`: while a turn is active, the session driver durably buffers the replacement before requesting cooperative cancellation. The interrupted turn emits `turn.cancelled` followed by `session.waiting`, then the replacement starts with a new turn ID. Partial output and completed side effects are not rolled back.--`turnPolicy: "queue"` preserves the message until the active turn settles. If several deliveries are ready when the driver 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.+session claims both its stable session-ID inbox and its initial channel address+before processing the first turn, and fails creation if another run already+owns the channel address. Aliasing adds another continuation address to the+same session; every previously claimed address remains active until the session+ends or resets. An ID-only HTTP session has the stable inbox and no channel+continuation address. When cold starts race for the same address, the losing+candidate forwards its accepted message to the owner and exits.++Channel delivery attempts to resume the address before creating a session.+After Workflow accepts the delivery, eve resolves the stable session ID for+the returned handle. That identity lookup does not block workflow resumption.+ID-addressed delivery already knows the session ID and needs no hook metadata+lookup. An ambiguous delivery failure does not trigger session creation.++While a handoff is in progress, the session's addresses are briefly unowned.+The releasing owner leaves a short-lived marker for each address, so a+delivery that lands in that interval retries until the successor claims the+address instead of being reported as an inactive session. A channel therefore+never 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.++`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.Every built-in and custom channel accepts a default `turnPolicy`, and imperative message sends can override it. The policy is part of the same durable delivery command as the message, so concurrent senders cannot separate replacement ownership from cancellation intent. Separate sessions still run independently.diff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.mdindex 632f17194..6ad0d3af2 100644--- a/docs/concepts/sessions-runs-and-streaming.md+++ b/docs/concepts/sessions-runs-and-streaming.md@@ -11,15 +11,22 @@ The HTTP API and TypeScript client use one durable `sessionId` for messages,controls, and streams. Every operation targets that exact session; none followsor creates a replacement implicitly.+The session ID currently identifies the original Workflow run that owns the+event stream. A deployment handoff changes the executing run, not the session+ID or stream. Stream namespaces belong to a run; eve does not support+caller-assigned session IDs or globally addressed streams.+Authored channels also have channel-local continuation tokens. A token addresseswhichever session currently owns a platform conversation, such as a Slack thread.That identity stays behind the channel boundary and is never accepted or returnedby the eve HTTP session API. See [Custom channels](../channels/custom#channel-operations-and-session-handles).Sessions last 30 days by default; configure `limits.sessionTimeoutMs` in-`agent.ts`, or set it to `false` to disable the deadline. At expiration, eve+`agent.ts`, or set it to `false` to disable the deadline. A successful deployment+handoff or legacy-session import restarts the original configured duration.+Ordinary messages and process restarts keep the existing deadline. At expiration, evelets an active turn settle, emits `session.completed`, and releases the-continuation so the next qualifying channel message starts fresh. Stored+session's continuation addresses so the next qualifying channel message starts fresh. Storedsession data is not deleted. See [Agent config](../agent-config#runtime-limits).React, Vue, and Svelte apps reach for [`useEveAgent()`](../guides/frontend/overview) instead of calling these routes by hand. Next.js and Nuxt apps can proxy them to the eve runtime from the same origin.@@ -164,7 +171,7 @@ Three more things to know:- **Ids identify events, not intent.** Two events with identical payloads — the `step.failed` → `turn.failed` → `session.failed` cascade, or two identical text deltas in one step — are distinct events with distinct ids. Deduplicate on `meta.id` only; matching on content would drop real data.- **A subagent's event is re-emitted, not shared.** When a parent forwards a child's event onto its own stream, the parent's copy is a separate event with its own id. Correlate the two streams through `subagent.called.data.childSessionId`.-Authored [hooks](../guides/hooks) receive the same envelope, but observe each event as it is emitted rather than as it is read — so a hook sees a retry as new events, and `meta.id` is a key for a stored row rather than a retry guard. Two things a hook does not have to defend against: a turn that parks for human input resumes without re-emitting anything it already sent, and a retried turn dispatch cannot double-stream a turn, because only one turn run can claim a session's turn inbox.+Authored [hooks](../guides/hooks) receive the same envelope, but observe each event as it is emitted rather than as it is read — so a hook sees a retry as new events, and `meta.id` is a key for a stored row rather than a retry guard. Two things a hook does not have to defend against: a turn that parks for human input resumes without re-emitting anything it already sent, and a retried turn dispatch cannot double-stream a turn, because one session owner executes it.## Send a follow-up message@@ -184,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 cancellation-backed `"steer"`; if a turn is active, eve buffers the follow-up, cancels that turn, and starts the message under a new turn ID. Channels and TypeScript `Session.send(...)` calls can select `turnPolicy: "queue"` when active work should finish first. Structured `inputResponses` never steer.+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.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.@@ -194,7 +201,7 @@ A structured response matches any currently pending request by ID, not only theOne delivery can answer requests from several batches. eve resumes approval-bearing batches in durable order and carries later answers forward until each batch can resume.-Multiple replacement messages retain their durable arrival order and may be folded into the same replacement turn when they arrive before cancellation settles. See [message delivery and steering](./execution-model-and-durability#message-delivery-and-steering) for the current runtime contract.+Multiple steering messages retain their durable arrival order and may be folded into one input at the next boundary. A message accepted after turn settlement starts the next turn. See [message delivery and steering](./execution-model-and-durability#message-delivery-and-steering).## Cancel the in-flight turndiff --git a/docs/guides/frontend/overview.mdx b/docs/guides/frontend/overview.mdxindex ec4850908..229ced442 100644--- a/docs/guides/frontend/overview.mdx+++ b/docs/guides/frontend/overview.mdx@@ -107,7 +107,7 @@ 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 replace an active turn with a follow-up, send the message with `turnPolicy: "steer"`. eve accepts the message through the durable session, cancels the active turn, and keeps the hook attached through the replacement turn:+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:```tsxawait agent.send(message, { turnPolicy: "steer" });diff --git a/docs/memory/custom-provider.md b/docs/memory/custom-provider.mdindex 11ae6b904..4196e8a22 100644--- a/docs/memory/custom-provider.md+++ b/docs/memory/custom-provider.md@@ -175,7 +175,7 @@ turn recalls the same data again.- A throwing or invalid `recall["turn.started"]` fails the turn before themodel call. No slot's recall results are committed. If the turn's`abortSignal` is already aborted, eve treats the error as cancellation and- continues with any queued steering replacement. An `AbortError` with an active+ continues with any queued follow-up. An `AbortError` with an activesignal still fails the turn.- A throwing `capture["compaction.requested"]` leaves history unchanged.- A throwing `recall["compaction.completed"]` fails an automatic turn. Fordiff --git a/docs/subagents/index.mdx b/docs/subagents/index.mdxindex f3d76d78e..cd63a9a69 100644--- a/docs/subagents/index.mdx+++ b/docs/subagents/index.mdx@@ -227,9 +227,9 @@ 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`. eve cancels the previous task before starting a new task in the same child session. The child retains its conversation history, and the receipt contains the same `agentId` with a new `taskId`. The cancelled task cannot publish a later successful result. Steering does not 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`. 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.-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`. Cancellation or delivery failures are reported to the caller; eve does not start a replacement child session to hide them.+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.Whenever the set of parked (resumable) children changes, eve appends a framework-injected note to the conversation — labeled `[Agents]` and carrying an `<agents>` block — listing each child's `agentId`, name, and latest status. The static system prompt tells the model the note is injected by eve, not written by the user. The note is appended only when the listing changes (an append-only design that preserves the provider prompt cache), the most recent note is authoritative, and children that are starting or running do not appear until they park again.diff --git a/docs/tools/workflows.mdx b/docs/tools/workflows.mdxindex 0fd4ed196..82a4cf068 100644--- a/docs/tools/workflows.mdx+++ b/docs/tools/workflows.mdx@@ -370,7 +370,7 @@ final-output rules of ordinary `defineTool` generators.## Cancel and clean up: `ctx.abortSignal`-`ctx.abortSignal` aborts when the run is cancelled: a steered turn for a waiting tool, `task_cancel`+`ctx.abortSignal` aborts when the run is cancelled: explicit turn cancellation for a waiting tool, `task_cancel`or the session ending for a background one. It is durable — it survives replay, and a step thatreceives it observes the abort. Pass it into the steps that should stop, and clean up in`try/finally`:diff --git a/docs/tutorial/how-it-runs.mdx b/docs/tutorial/how-it-runs.mdxindex befde46fe..3888a8bc6 100644--- a/docs/tutorial/how-it-runs.mdx+++ b/docs/tutorial/how-it-runs.mdx@@ -11,7 +11,7 @@ The analytics assistant sent one message and got one answer. Three terms describ| **turn** | One message you send and the work it triggers. || **step** | A durable checkpoint within the turn. |-Each turn runs as a durable workflow, and eve saves progress at every step. Completed steps never re-run; eve replays the recorded result. A step interrupted mid-execution re-runs, so make non-idempotent side effects like charges or emails idempotent, or gate them with approval. A turn that's waiting on you (an approval, a question) resumes whenever you answer, even if that's much later.+The session runs as one durable workflow, and eve saves each turn's progress at every step. Completed steps never re-run; eve replays the recorded result. A step interrupted mid-execution re-runs, so make non-idempotent side effects like charges or emails idempotent, or gate them with approval. A turn that's waiting on you (an approval, a question) resumes whenever you answer, even if that's much later.That's why the features in the rest of this tutorial work the way they do:diff --git a/e2e/README.md b/e2e/README.mdindex c2843dd42..5f773e7d5 100644--- a/e2e/README.md+++ b/e2e/README.md@@ -113,23 +113,11 @@ identically at build and runtime, and Vercel has no team variable at runtime.### Redeploy suite`agent-tools-sandbox/evals/sandbox/redeploy.eval.ts` proves sandbox semantics-across deployment updates as they behave on preview targets: a parked session-keeps working (with its `/workspace` state intact) when messages route through-a new deployment, its turns stay pinned to the deployment that created it-(branch-less CLI preview deploys cannot resolve a "latest" deployment; see-`shouldRouteToLatestDeployment` in `execution/workflow-runtime.ts`), and new-sessions adopt the new deployment — a skill added by the redeploy loads there.-The pinned-turn assertion is a deliberate tripwire: it must be flipped when-turn dispatch gains preview latest-routing-(https://github.com/vercel/eve/issues/582).--`agent-channels/evals/custom-channels/cross-version-session-inbox.eval.ts`-deploys the fixture with the published `[email protected]`, holds a turn active in-that old consumer, then redeploys the current checkout and sends a replacement-message through the same durable session. It verifies both sides of the codec:-the current producer must choose the old consumer's wire version, and the real-old consumer must decode and buffer it. The eval then cancels the deliberately-blocked turn and verifies that the old session runs the buffered follow-up.+across deployment updates as they behave on preview targets. A delivery to an+idle parked session hands ownership to the exact deployment that accepted the+request while preserving the public session stream. The eval verifies that an+instruction-only redeploy preserves the sandbox workspace, a resource-changing+redeploy rotates it, and a new session loads the new deployment's skill.The eval redeploys from inside its test body: it mutates the agent source,runs `eve build` + `vc deploy`, and repoints a run-scoped Vercel alias atdiff --git a/e2e/fixtures/agent-basic-runtime/agent/agent.ts b/e2e/fixtures/agent-basic-runtime/agent/agent.tsindex ddbf9f6d7..a49881ccd 100644--- a/e2e/fixtures/agent-basic-runtime/agent/agent.ts+++ b/e2e/fixtures/agent-basic-runtime/agent/agent.ts@@ -11,7 +11,13 @@ const childModel = mockModel({});const config = e2eAgentConfig({- mock: ({ lastUserMessage, toolResults }) => {+ mock: ({ lastUserMessage, toolResults, userMessages }) => {+ if (lastUserMessage?.includes("favorite word") && lastUserMessage.includes("?")) {+ const remembered = userMessages+ .map((message) => /My favorite word is (\w+)/u.exec(message)?.[1])+ .find((word) => word !== undefined);+ return remembered ?? "No favorite word was provided.";+ }if (lastUserMessage?.startsWith("Call call_child ")) {const result = toolResults.find((entry) => entry.name === "call_child");return result === undefineddiff --git a/e2e/fixtures/agent-basic-runtime/evals/runtime/multi-turn-session.eval.ts b/e2e/fixtures/agent-basic-runtime/evals/runtime/multi-turn-session.eval.tsindex 99f61fe9b..d4339ae63 100644--- a/e2e/fixtures/agent-basic-runtime/evals/runtime/multi-turn-session.eval.ts+++ b/e2e/fixtures/agent-basic-runtime/evals/runtime/multi-turn-session.eval.ts@@ -1,5 +1,5 @@import { defineEval } from "eve/evals";-import { equals, includes } from "eve/evals/expect";+import { equals, includes, satisfies } from "eve/evals/expect";/*** Core session-route runtime behavior: multi-turn session continuity.@@ -16,6 +16,26 @@ export default defineEval({const second = await t.send("What is my favorite word? Reply with just the word.");await t.require(second.sessionId, equals(first.sessionId));+ second.messageIncludes(/marigold/i);++ const cancel = await t.cancel();+ await t.require(+ cancel,+ satisfies(+ (value: typeof cancel) =>+ value.status === "accepted" && value.sessionId === first.sessionId,+ "the parked session accepts cancellation through its stable address",+ ),+ );++ const third = await t.send(+ "Alice is checking the saved conversation. What favorite word did I ask you to remember? Reply with just that word.",+ );+ await t.require(third.sessionId, equals(first.sessionId));+ third.notEvent("session.started");+ third.notEvent("turn.cancelled");+ third.notEvent("session.failed");+ third.messageIncludes(/marigold/i);t.succeeded();t.messageIncludes(/marigold/i);diff --git a/e2e/fixtures/agent-cancellation/agent/agent.ts b/e2e/fixtures/agent-cancellation/agent/agent.tsindex e9c2b5d3b..162667a60 100644--- a/e2e/fixtures/agent-cancellation/agent/agent.ts+++ b/e2e/fixtures/agent-cancellation/agent/agent.ts@@ -7,6 +7,11 @@ const HITL_REQUEST = "GENERATED-PROGRAM-CHILD-HITL";function respond(request: MockModelRequest): MockModelResponse | string {const message = request.lastUserMessage ?? "";+ if (message.includes("Please complete work before answering.")) {+ return request.toolResults.some((result) => result.id === "complete-work")+ ? "The work item is complete."+ : { toolCalls: [{ id: "complete-work", input: {}, name: "complete-work" }] };+ }if (message.includes("Please wait for cancellation.")) {return {toolCalls: [{ id: "wait-for-cancellation", input: {}, name: "wait-for-cancellation" }],diff --git a/e2e/fixtures/agent-cancellation/agent/instructions.md b/e2e/fixtures/agent-cancellation/agent/instructions.mdindex 0d5281cb7..71485cb1a 100644--- a/e2e/fixtures/agent-cancellation/agent/instructions.md+++ b/e2e/fixtures/agent-cancellation/agent/instructions.md@@ -4,6 +4,7 @@ You are a test fixture agent for turn-cancellation coverage.# Rules+- When asked to complete work before answering, call `complete-work` once.- When the user asks for `steering-worker`, delegate the supplied messageverbatim to that subagent in the background. Acknowledge the receipt withoutreporting a result.diff --git a/e2e/fixtures/agent-cancellation/agent/tools/complete-work.ts b/e2e/fixtures/agent-cancellation/agent/tools/complete-work.tsnew file mode 100644index 000000000..3a82d880f--- /dev/null+++ b/e2e/fixtures/agent-cancellation/agent/tools/complete-work.ts@@ -0,0 +1,13 @@+import { defineTool } from "eve/tools";+import { never } from "eve/tools/approval";+import { z } from "zod";++export default defineTool({+ description: "Completes a short work item. Call when asked to complete work before answering.",+ inputSchema: z.object({}),+ approval: never(),+ async execute() {+ await new Promise<void>((resolve) => setTimeout(resolve, 10_000));+ return "The work item is complete.";+ },+});diff --git a/e2e/fixtures/agent-cancellation/agent/tools/wait-for-boundary.ts b/e2e/fixtures/agent-cancellation/agent/tools/wait-for-boundary.tsnew file mode 100644index 000000000..1ef473d7d--- /dev/null+++ b/e2e/fixtures/agent-cancellation/agent/tools/wait-for-boundary.ts@@ -0,0 +1,15 @@+import { setTimeout } from "node:timers/promises";+import { defineTool } from "eve/tools";+import { never } from "eve/tools/approval";+import { z } from "zod";++export default defineTool({+ description:+ "Complete a brief operation before processing Alice's next update. Call only when explicitly requested.",+ inputSchema: z.object({}),+ approval: never(),+ async execute(_input, ctx) {+ await setTimeout(2_000, undefined, { signal: ctx.abortSignal });+ return "The operation completed; process any new update now.";+ },+});diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/background-steering.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/background-steering.eval.tsindex 7d053ed31..667967e5b 100644--- a/e2e/fixtures/agent-cancellation/evals/cancellation/background-steering.eval.ts+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/background-steering.eval.ts@@ -69,13 +69,15 @@ export default cases.map(({ parentActive, steering, description }) =>if (parentActive) {// Establish a running child before holding another parent turn;// holding the launch turn can delay dispatch until its wait ends.- parent = await parent.session.start("Please wait for cancellation.");+ parent = await parent.session.start(+ "Alice is preparing an update. Call wait-for-boundary once before responding.",+ );await parent.waitForEvent("actions.requested", {data: {actions: (actions) =>actions.some((action) =>- action.kind === "tool-call" && action.toolName === "wait-for-cancellation",+ action.kind === "tool-call" && action.toolName === "wait-for-boundary",),},});@@ -94,7 +96,7 @@ export default cases.map(({ parentActive, steering, description }) =>),);- const interruptedParent = parentActive ? parent : undefined;+ const activeParent = parentActive ? parent : undefined;parent = await parent.session.start(steering? "Actually, use STEERED instead of ORIGINAL."@@ -103,13 +105,20 @@ export default cases.map(({ parentActive, steering, description }) =>);await t.require(parent.sessionId, equals(sessionId));- if (interruptedParent !== undefined) {- // A send is correlated to its new delivery; the previous handle- // observes the turn that steering interrupts.- const cancelled = await interruptedParent.result();- cancelled.notEvent("turn.failed");- cancelled.event("turn.cancelled", { count: 1 });- parentTurns.push(cancelled);+ if (activeParent !== undefined) {+ const continued = await activeParent.result();+ continued.expectOk();+ continued.notEvent("turn.cancelled");+ continued.event("turn.started", { count: 1 });+ continued.event("turn.completed", { count: 1 });+ continued.event("message.received", {+ data: {+ message: steering+ ? "Actually, use STEERED instead of ORIGINAL."+ : "What is 2 + 2? Reply with just the number.",+ },+ count: 1,+ });}// Observe through the result-bearing task wake, not just the parent's// acknowledgment of the steering message or an AGENT_BUSY failure wake.@@ -154,22 +163,21 @@ export default cases.map(({ parentActive, steering, description }) =>);const firstChildTurn = await child.result();- const childWasCancelled = firstChildTurn.events.some(- (event) => event.type === "turn.cancelled",+ const receipts = parentTurns.flatMap((turn) =>+ turn.events.flatMap((event) =>+ event.type === "subagent.completed" && event.data.backgroundTask !== undefined+ ? [event.data.backgroundTask.taskId]+ : [],+ ),);- if (steering && childWasCancelled) {- // Also permits cancel-and-resume of the same child; no specific- // control API or task-id lifetime is required by these assertions.- const resumed = await t.target- .watchTurn(called.data.childSessionId, { startIndex: child.session.state!.streamIndex })- .result();- resumed.expectOk();- resumed.messageIncludes(expected);- } else {- firstChildTurn.expectOk();- firstChildTurn.notEvent("turn.cancelled");- firstChildTurn.messageIncludes(expected);+ await t.require(new Set(receipts).size, equals(1));+ if (steering) {+ await t.require(receipts.length >= 2, equals(true));}+ firstChildTurn.expectOk();+ firstChildTurn.notEvent("turn.cancelled");+ firstChildTurn.event("turn.started", { count: 1 });+ firstChildTurn.messageIncludes(expected);if (steering) {firstChildTurn.eventsSatisfy("the original child never emits the superseded result",diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/steer-channel-message.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/steer-channel-message.eval.tsindex b9bd89f2e..08add1aa0 100644--- a/e2e/fixtures/agent-cancellation/evals/cancellation/steer-channel-message.eval.ts+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/steer-channel-message.eval.ts@@ -2,7 +2,7 @@ import type { TurnPolicy } from "eve/channels";import { defineEval, type EveEvalTargetHandle } from "eve/evals";import { satisfies } from "eve/evals/expect";-const TOOL_NAME = "wait-for-cancellation";+const TOOL_NAME = "complete-work";interface MessageResponse {readonly ok: boolean;@@ -28,14 +28,14 @@ async function postMessage(return JSON.parse(text) as MessageResponse;}-/** Replaces an active turn through the custom channel's default steering policy. */+/** Applies an accepted message at a safe boundary within the active turn. */export default defineEval({- description: "An accepted channel message replaces the active turn by default.",+ description: "An accepted channel message steers the active turn without cancelling its work.",timeoutMs: 240_000,async test(t) {const threadId = crypto.randomUUID();- const started = await postMessage(t.target, threadId, "Please wait for cancellation.");+ const started = await postMessage(t.target, threadId, "Please complete work before answering.");await t.require(started,satisfies(@@ -67,15 +67,9 @@ export default defineEval({),);- const cancelled = await activeTurn.result();- cancelled.event("turn.cancelled", { count: 1 });- cancelled.eventOrder([{ type: "turn.cancelled" }, { type: "session.waiting" }]);- cancelled.notEvent("turn.failed");- cancelled.notEvent("session.failed");-- const replacementTurn = await t.target- .watchTurn(sessionId, { startIndex: cancelled.events.length })- .result();+ const replacementTurn = await activeTurn.result();+ replacementTurn.event("turn.started", { count: 1 });+ replacementTurn.event("message.received", { count: 2 });replacementTurn.notEvent("turn.cancelled");replacementTurn.notEvent("turn.failed");replacementTurn.notEvent("session.failed");diff --git a/e2e/fixtures/agent-channels/agent/agent.ts b/e2e/fixtures/agent-channels/agent/agent.tsindex d746d5e38..6ee424a36 100644--- a/e2e/fixtures/agent-channels/agent/agent.ts+++ b/e2e/fixtures/agent-channels/agent/agent.ts@@ -3,18 +3,7 @@ import { defineAgent } from "eve";export default defineAgent({...e2eAgentConfig({- mock: ({ lastUserMessage }) =>- lastUserMessage?.includes("Please wait for cross-version follow-up.") === true- ? {- toolCalls: [- {- id: "wait-for-cancellation",- input: {},- name: "wait-for-cancellation",- },- ],- }- : `Mock reply: ${lastUserMessage ?? ""}`,+ mock: ({ lastUserMessage }) => `Mock reply: ${lastUserMessage ?? ""}`,}),reasoning: "high",});diff --git a/e2e/fixtures/agent-channels/agent/channels/cross-version.ts b/e2e/fixtures/agent-channels/agent/channels/cross-version.tsdeleted file mode 100644index 58f71799b..000000000--- a/e2e/fixtures/agent-channels/agent/channels/cross-version.ts+++ /dev/null@@ -1,64 +0,0 @@-import { defineChannel, POST, type Session } from "eve/channels";-import evePackage from "eve/package.json" with { type: "json" };--import { checkDeploymentRevision } from "../lib/deployment-revision";--const smokeTestAuth = {- attributes: { source: "smoke-test" },- authenticator: "cross-version-webhook",- principalId: "smoke-test",- principalType: "service",-} as const;--type CrossVersionRouteContext = {- readonly from?: (address: string) => {- send(- message: string,- options: {- readonly auth: typeof smokeTestAuth;- readonly turnPolicy?: "queue" | "steer";- },- ): Promise<Session>;- };- readonly send?: (- message: string,- options: {- readonly auth: typeof smokeTestAuth;- readonly continuationToken: string;- },- ) => Promise<Session>;-};--export default defineChannel({- routes: [- POST("/cross-version-webhook", async (req, ctx) => {- const pendingDeployment = checkDeploymentRevision(req);- if (pendingDeployment !== undefined) return pendingDeployment;- const body = (await req.json().catch(() => ({}))) as {- message?: string;- sessionRef?: string;- turnPolicy?: "queue" | "steer";- };- const message = body.message ?? "Reply with the single word: hello.";- const address = body.sessionRef ?? crypto.randomUUID();- const crossVersionContext = ctx as CrossVersionRouteContext;-- let session: Session;- if (crossVersionContext.from !== undefined) {- session = await crossVersionContext.from(address).send(message, {- auth: smokeTestAuth,- turnPolicy: body.turnPolicy,- });- } else if (crossVersionContext.send !== undefined) {- session = await crossVersionContext.send(message, {- auth: smokeTestAuth,- continuationToken: address,- });- } else {- throw new Error("Expected the route context to expose from() or send().");- }-- return Response.json({ ok: true, sessionId: session.id, eveVersion: evePackage.version });- }),- ],-});diff --git a/e2e/fixtures/agent-channels/agent/lib/deployment-revision.ts b/e2e/fixtures/agent-channels/agent/lib/deployment-revision.tsdeleted file mode 100644index 723ba6ba3..000000000--- a/e2e/fixtures/agent-channels/agent/lib/deployment-revision.ts+++ /dev/null@@ -1,17 +0,0 @@-export const DEPLOYMENT_REVISION_HEADER = "x-eve-e2e-deployment-revision";-export const DEPLOYMENT_PENDING_CODE = "e2e_deployment_pending";--export function checkDeploymentRevision(- request: Request,- revision = process.env.EVE_E2E_DEPLOYMENT_REVISION,-): Response | undefined {- const expected = request.headers.get(DEPLOYMENT_REVISION_HEADER);- if (expected === null || expected === revision) return undefined;- return Response.json(- {- code: DEPLOYMENT_PENDING_CODE,- error: "The requested deployment is not serving this request yet.",- },- { status: 409 },- );-}diff --git a/e2e/fixtures/agent-channels/agent/tools/wait-for-cancellation.ts b/e2e/fixtures/agent-channels/agent/tools/wait-for-cancellation.tsdeleted file mode 100644index 3d03d4b0b..000000000--- a/e2e/fixtures/agent-channels/agent/tools/wait-for-cancellation.ts+++ /dev/null@@ -1,29 +0,0 @@-import { defineTool } from "eve/tools";-import { never } from "eve/tools/approval";-import { z } from "zod";--const FALLBACK_TIMEOUT_MS = 10 * 60_000;--export default defineTool({- description:- "Waits until the current turn is cancelled. Only call when the user explicitly asks you to wait for a cross-version follow-up.",- inputSchema: z.object({}),- approval: never(),- execute(_input, ctx) {- return new Promise<string>((resolve, reject) => {- const timer = setTimeout(() => {- resolve("wait-for-cancellation: fallback timeout reached without cancellation");- }, FALLBACK_TIMEOUT_MS);-- const abort = (): void => {- clearTimeout(timer);- reject(ctx.abortSignal.reason);- };- if (ctx.abortSignal.aborted) {- abort();- return;- }- ctx.abortSignal.addEventListener("abort", abort, { once: true });- });- },-});diff --git a/e2e/fixtures/agent-channels/evals/custom-channels/cross-version-session-inbox.eval.ts b/e2e/fixtures/agent-channels/evals/custom-channels/cross-version-session-inbox.eval.tsdeleted file mode 100644index 58de02246..000000000--- a/e2e/fixtures/agent-channels/evals/custom-channels/cross-version-session-inbox.eval.ts+++ /dev/null@@ -1,305 +0,0 @@-import { execFile } from "node:child_process";-import { readFile, readlink, realpath, rm, symlink, writeFile } from "node:fs/promises";-import { resolve } from "node:path";-import { promisify } from "node:util";--import { defineEval } from "eve/evals";-import type { EveEvalContext } from "eve/evals";-import { satisfies } from "eve/evals/expect";--import {- DEPLOYMENT_PENDING_CODE,- DEPLOYMENT_REVISION_HEADER,-} from "../../agent/lib/deployment-revision";--const ALIAS_ENV = "EVE_E2E_REDEPLOY_ALIAS";-const OLD_EVE_VERSION = "0.30.8";-const ACTIVE_TURN_MESSAGE = "Please wait for cross-version follow-up.";-const FOLLOW_UP_TOKEN = "CROSS-VERSION-WIRE-OK";--const INSTRUCTIONS_PATH = resolve("agent", "instructions.md");-const FIXTURE_EVE_LINK = resolve("node_modules", "eve");-const CONFIG_EVE_LINK = resolve("..", "e2e-config", "node_modules", "eve");-const OLD_EVE_PACKAGE = resolve("node_modules", "historical-eve-0-30-8");--const OLD_DEPLOYMENT_MARKER = "cross-version-eve-0-30-8";-const CURRENT_DEPLOYMENT_MARKER = "cross-version-eve-current";-const TOOL_NAME = "wait-for-cancellation";--const execFileAsync = promisify(execFile);-const EXEC_OPTIONS = { maxBuffer: 64 * 1024 * 1024 } as const;--type MessageResponse = { ok: boolean; sessionId?: string; eveVersion: string };--/**- * Proves the complete mixed-version codec boundary through the real Workflow- * hook: the current producer resumes an active turn built and deployed with- * the published [email protected] consumer, then the old session accepts the- * replacement message and completes its next turn.- */-export default defineEval({- description:- "Session inbox: the current producer resumes an active [email protected] consumer through the durable hook.",- tags: ["redeploy"],- timeoutMs: 20 * 60_000,-- async test(t) {- const alias = process.env[ALIAS_ENV];- if (alias === undefined || alias.length === 0) {- t.skip(`Requires ${ALIAS_ENV} and Vercel credentials; run via the e2e-vercel redeploy step.`);- }- if (new URL(t.target.url).host !== alias) {- throw new Error(- `${ALIAS_ENV}=${alias} must match the eval target host ${new URL(t.target.url).host}; ` +- "redeploys repoint the alias, so the eval must run against it.",- );- }-- const originalInstructions = await readFile(INSTRUCTIONS_PATH, "utf8");- const oldRevision = crypto.randomUUID();- const currentRevision = crypto.randomUUID();- const links = await Promise.all([- snapshotLink(FIXTURE_EVE_LINK),- snapshotLink(CONFIG_EVE_LINK),- ]);- const currentEvePackage = await realpath(FIXTURE_EVE_LINK);- const currentEveVersion = await readPackageVersion(currentEvePackage);- const oldEvePackage = await realpath(OLD_EVE_PACKAGE);- const oldEveVersion = await readPackageVersion(oldEvePackage);- if (oldEveVersion !== OLD_EVE_VERSION) {- throw new Error(- `Expected ${OLD_EVE_PACKAGE} to resolve eve@${OLD_EVE_VERSION}; got eve@${oldEveVersion}.`,- );- }-- try {- await replaceLink(FIXTURE_EVE_LINK, oldEvePackage);- await replaceLink(CONFIG_EVE_LINK, oldEvePackage);- await writeFile(- INSTRUCTIONS_PATH,- `${originalInstructions}\nDeployment marker: ${OLD_DEPLOYMENT_MARKER}.\n`,- );- await deployToAlias(t, alias, "[email protected]", oldRevision, oldEvePackage);- await waitForAliasToServe(t, OLD_DEPLOYMENT_MARKER);-- const sessionRef = crypto.randomUUID();- const started = await postToDeployment(t, oldRevision, {- message: ACTIVE_TURN_MESSAGE,- sessionRef,- });- await t.require(- started,- satisfies(- (value: MessageResponse) =>- value.ok === true &&- typeof value.sessionId === "string" &&- value.eveVersion === OLD_EVE_VERSION,- "[email protected] starts the durable session",- ),- );- const sessionId = started.sessionId!;- const activeTurn = t.target.watchTurn(sessionId);-- await activeTurn.waitForEvent("actions.requested", {- data: {- actions: (actions) =>- actions.some((action) => action.kind === "tool-call" && action.toolName === TOOL_NAME),- },- });-- await restoreLinks(links);- await writeFile(- INSTRUCTIONS_PATH,- `${originalInstructions}\nDeployment marker: ${CURRENT_DEPLOYMENT_MARKER}.\n`,- );- await deployToAlias(t, alias, `eve@${currentEveVersion}`, currentRevision, currentEvePackage);- await waitForAliasToServe(t, CURRENT_DEPLOYMENT_MARKER);-- const replacement = await postToDeployment(t, currentRevision, {- message: `Reply with exactly ${FOLLOW_UP_TOKEN}.`,- sessionRef,- turnPolicy: "queue",- });- await t.require(- replacement,- satisfies(- (value: MessageResponse) =>- value.ok === true &&- value.sessionId === sessionId &&- value.eveVersion === currentEveVersion,- "the current producer targets the existing [email protected] session",- ),- );-- // [email protected] buffers a raw `send` during an active turn but predates- // `turnPolicy: "steer"`. Settle the deliberately blocked turn through a- // separate cancellation; the queued message must then become the next- // turn if the old receiver decoded and retained it.- await t.sleep(1_000);- const cancellation = await activeTurn.cancel();- await t.require(- cancellation,- satisfies(- (value: { readonly sessionId?: string; readonly status: string }) =>- value.status === "accepted" && value.sessionId === sessionId,- "the current deployment cancels the active [email protected] turn",- ),- );-- const cancelled = await activeTurn.result();- cancelled.event("turn.cancelled", { count: 1 });- cancelled.eventOrder([{ type: "turn.cancelled" }, { type: "session.waiting" }]);- cancelled.notEvent("turn.failed");- cancelled.notEvent("session.failed");-- const followUp = await t.target- .watchTurn(sessionId, { startIndex: cancelled.events.length })- .result();- followUp.notEvent("turn.cancelled");- followUp.notEvent("turn.failed");- followUp.notEvent("session.failed");- followUp.messageIncludes(FOLLOW_UP_TOKEN);-- t.succeeded();- } finally {- await restoreLinks(links);- await writeFile(INSTRUCTIONS_PATH, originalInstructions);- }- },-});--interface LinkSnapshot {- readonly path: string;- readonly target: string;-}--async function snapshotLink(path: string): Promise<LinkSnapshot> {- return { path, target: await readlink(path) };-}--async function replaceLink(path: string, target: string): Promise<void> {- await rm(path, { force: true });- await symlink(target, path);-}--async function restoreLinks(links: readonly LinkSnapshot[]): Promise<void> {- for (const link of links) {- await replaceLink(link.path, link.target);- }-}--async function readPackageVersion(packagePath: string): Promise<string> {- const manifest = JSON.parse(await readFile(resolve(packagePath, "package.json"), "utf8")) as {- version?: string;- };- if (manifest.version === undefined) {- throw new Error(`Package at ${packagePath} has no version.`);- }- return manifest.version;-}--/** Builds the fixture and repoints the run-scoped alias at the fresh deployment. */-async function deployToAlias(- t: EveEvalContext,- alias: string,- phase: string,- revision: string,- evePackagePath: string,-): Promise<void> {- // pnpm's dependency synchronization can repair the intentionally replaced links.- await execFileAsync(process.execPath, [resolve(evePackagePath, "bin", "eve.js"), "build"], {- ...EXEC_OPTIONS,- env: {- ...process.env,- VERCEL: "1",- VERCEL_ENV: "preview",- VERCEL_TARGET_ENV: "preview",- },- });- const tokenArgs =- process.env.VERCEL_TOKEN === undefined ? [] : ["--token", process.env.VERCEL_TOKEN];- const modelArgs =- process.env.EVE_E2E_MODEL === undefined- ? []- : ["--env", `EVE_E2E_MODEL=${process.env.EVE_E2E_MODEL}`];- const revisionArgs = ["--env", `EVE_E2E_DEPLOYMENT_REVISION=${revision}`];- const scopeArgs =- process.env.VERCEL_ORG_ID === undefined ? [] : ["--scope", process.env.VERCEL_ORG_ID];- const deploy = await execFileAsync(- "pnpm",- [- "exec",- "vc",- "deploy",- "--prebuilt",- "--yes",- "--target=preview",- ...modelArgs,- ...revisionArgs,- ...tokenArgs,- ],- EXEC_OPTIONS,- );- const deploymentUrl = deploy.stdout.trim().split("\n").at(-1)?.trim();- if (deploymentUrl === undefined || !deploymentUrl.startsWith("https://")) {- throw new Error(`vc deploy did not print a deployment URL; got: ${deploy.stdout}`);- }- t.log(`deployed ${deploymentUrl} (${phase}); aliasing ${alias}`);-- await execFileAsync(- "pnpm",- ["exec", "vc", "alias", "set", deploymentUrl, alias, ...tokenArgs, ...scopeArgs],- EXEC_OPTIONS,- );-}--async function postToDeployment(- t: EveEvalContext,- revision: string,- body: unknown,-): Promise<MessageResponse> {- const deadline = Date.now() + 120_000;- while (Date.now() < deadline) {- const response = await t.target.fetch("/cross-version-webhook", {- method: "POST",- headers: {- "content-type": "application/json",- [DEPLOYMENT_REVISION_HEADER]: revision,- },- body: JSON.stringify(body),- signal: t.signal,- });- const result = (await response.json()) as MessageResponse & { code?: string };- if (response.status === 409 && result.code === DEPLOYMENT_PENDING_CODE) {- await t.sleep(1_000);- continue;- }- if (!response.ok) {- throw new Error(`Cross-version message failed (${response.status}).`);- }- return result;- }- throw new Error("Timed out waiting for the cross-version message's deployment.");-}--/** Waits until the alias exposes the marker from the expected deployment. */-async function waitForAliasToServe(t: EveEvalContext, marker: string): Promise<void> {- const deadline = Date.now() + 120_000;- let lastStatus = "transport error";- let lastMarkerMatch = false;- while (Date.now() < deadline) {- try {- const response = await t.target.fetch("/eve/v1/info", { cache: "no-store" });- lastStatus = String(response.status);- lastMarkerMatch = response.ok && JSON.stringify(await response.json()).includes(marker);- if (lastMarkerMatch) return;- } catch {- // The alias may briefly be unavailable while its deployment propagates.- }- await t.sleep(1_000);- }- throw new Error(- `Timed out waiting for alias ${new URL(t.target.url).host} to serve marker ${marker}; ` +- `last status=${lastStatus}, marker matched=${lastMarkerMatch}.`,- );-}diff --git a/e2e/fixtures/agent-channels/test/deployment-revision.test.mjs b/e2e/fixtures/agent-channels/test/deployment-revision.test.mjsdeleted file mode 100644index 6b350e79f..000000000--- a/e2e/fixtures/agent-channels/test/deployment-revision.test.mjs+++ /dev/null@@ -1,35 +0,0 @@-import assert from "node:assert/strict";-import { test } from "node:test";--import {- checkDeploymentRevision,- DEPLOYMENT_PENDING_CODE,- DEPLOYMENT_REVISION_HEADER,-} from "../agent/lib/deployment-revision.ts";--function pinnedRequest() {- return new Request("https://fixture.example/cross-version-webhook", {- headers: { [DEPLOYMENT_REVISION_HEADER]: "requested-revision" },- });-}--test("rejects a stale deployment before dispatch", async () => {- const response = checkDeploymentRevision(pinnedRequest(), "previous-revision");-- assert.equal(response.status, 409);- assert.equal((await response.json()).code, DEPLOYMENT_PENDING_CODE);-});--test("allows a request on its pinned deployment", () => {- assert.equal(checkDeploymentRevision(pinnedRequest(), "requested-revision"), undefined);-});--test("preserves requests without a deployment pin", () => {- assert.equal(- checkDeploymentRevision(- new Request("https://fixture.example/cross-version-webhook"),- "previous-revision",- ),- undefined,- );-});diff --git a/e2e/fixtures/agent-task-reporting/evals/event-matching.test.mjs b/e2e/fixtures/agent-task-reporting/evals/event-matching.test.mjsindex 83877d315..cb16745b3 100644--- a/e2e/fixtures/agent-task-reporting/evals/event-matching.test.mjs+++ b/e2e/fixtures/agent-task-reporting/evals/event-matching.test.mjs@@ -4,7 +4,9 @@ import { test } from "node:test";import {childActivations,checkForTask,+ completedTaskIds,eventsForSession,+ modelStepCount,requireOriginalTasksHealthy,toolEvidence,} from "./event-matching.ts";@@ -142,6 +144,48 @@ test("rejects a logical-call retry that changes its result", () => {assert.throws(() => toolEvidence(turns, "child", "probe"), /tool result probe-call changed/);});+test("counts retried model preambles once by logical coordinates", () => {+ const started = (id, stepIndex = 0) =>+ event(id, "step.started", {+ modelId: "openai/test",+ sequence: 4,+ stepIndex,+ turnId: "turn_4",+ });+ const turns = [+ { sessionId: "parent", events: [started("step-1"), started("step-retry")] },+ { sessionId: "parent", events: [started("step-2", 1)] },+ { sessionId: "child", events: [started("child-step")] },+ ];++ assert.equal(modelStepCount(turns), 3);+});++test("deduplicates retried completion notifications but not duplicate text in one message", () => {+ const message =+ "Background task task_first (agent) is completed.\nBackground task task_second (agent) is completed.";+ const notification = (id, value = message) =>+ event(id, "message.received", { message: value, sequence: 4, turnId: "turn_4" });+ const snapshot = {+ sessionId: "parent",+ events: [notification("message-1"), notification("message-retry")],+ };++ assert.deepEqual(completedTaskIds(snapshot), ["task_first", "task_second"]);+ assert.deepEqual(+ completedTaskIds({+ ...snapshot,+ events: [+ notification(+ "duplicated-in-message",+ "Background task task_first (agent) is completed.\nBackground task task_first (agent) is completed.",+ ),+ ],+ }),+ ["task_first", "task_first"],+ );+});+test("does not join a same-call-ID request and result from different sessions", () => {const turns = snapshots();turns[2].sessionId = "sibling";diff --git a/e2e/fixtures/agent-task-reporting/evals/event-matching.ts b/e2e/fixtures/agent-task-reporting/evals/event-matching.tsindex c7cc7352d..6205b837e 100644--- a/e2e/fixtures/agent-task-reporting/evals/event-matching.ts+++ b/e2e/fixtures/agent-task-reporting/evals/event-matching.ts@@ -6,6 +6,45 @@ type Event = EveEvalTurn["events"][number];export type SessionEvents = Pick<EveEvalTurn, "sessionId" | "events">;export const CHECKS = ["first", "second", "third"] as const;export type Check = (typeof CHECKS)[number];+const COMPLETION = /Background task (task_[a-z0-9]+) \([^)]+\) is completed\./giu;++/** Counts logical model steps while tolerating durable step retries with new event IDs. */+export function modelStepCount(snapshots: readonly SessionEvents[]): number {+ const steps = new Set<string>();+ for (const snapshot of snapshots) {+ for (const event of snapshot.events) {+ if (event.type !== "step.started") continue;+ steps.add(+ JSON.stringify([+ snapshot.sessionId,+ event.data.turnId,+ event.data.sequence,+ event.data.stepIndex,+ event.data.modelId,+ ]),+ );+ }+ }+ return steps.size;+}++/** Extracts each logical notification once without hiding duplicates inside one message. */+export function completedTaskIds(snapshot: SessionEvents): string[] {+ const messages = new Set<string>();+ const taskIds: string[] = [];+ for (const event of snapshot.events) {+ if (event.type !== "message.received") continue;+ const logicalMessage = JSON.stringify([+ event.data.turnId,+ event.data.sequence,+ event.data.message,+ ]);+ if (messages.has(logicalMessage)) continue;+ messages.add(logicalMessage);+ taskIds.push(...[...event.data.message.matchAll(COMPLETION)].map((match) => match[1]));+ }+ return taskIds;+}export function requireOriginalTasksHealthy(snapshots: readonly SessionEvents[],diff --git a/e2e/fixtures/agent-task-reporting/evals/reporting.ts b/e2e/fixtures/agent-task-reporting/evals/reporting.tsindex 4a316d0fc..41bb6e073 100644--- a/e2e/fixtures/agent-task-reporting/evals/reporting.ts+++ b/e2e/fixtures/agent-task-reporting/evals/reporting.ts@@ -6,7 +6,9 @@ import {CHECKS,childActivations,checkForTask,+ completedTaskIds,eventsForSession,+ modelStepCount,requireOriginalTasksHealthy,toolEvidence,type Check,@@ -17,7 +19,6 @@ export const QUESTION ="Alice is packing seven boxes with eight jars in each. How many jars is that? Reply with just the number.";const RESULTS = { first: "oranges", second: "pears", third: "apples" } as const;-const COMPLETION = /Background task (task_[a-z0-9]+) \([^)]+\) is completed\./giu;interface Child {readonly check: Check;@@ -297,8 +298,7 @@ export function completeReport() {}export function modelSteps(turns: readonly EveEvalTurn[]): number {- return turns.flatMap((turn) => turn.events).filter((event) => event.type === "step.started")- .length;+ return modelStepCount(turns);}export function completedAt(turn: EveEvalTurn): number {@@ -413,14 +413,6 @@ function assertModel(turn: EveEvalTurn, modelId: string) {);}-function completedTaskIds(turn: EveEvalTurn): string[] {- return turn.events.flatMap((event) =>- event.type === "message.received"- ? [...event.data.message.matchAll(COMPLETION)].map((match) => match[1]!)- : [],- );-}-async function post(t: EveEvalContext, run: ReportingRun, suffix: "" | "/compact", body: unknown) {const response = await t.target.fetch(`/eve/v1/session/${encodeURIComponent(run.sessionId)}${suffix}`,diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/redeploy.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/redeploy.eval.tsindex 7ce8a935c..d18440aed 100644--- a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/redeploy.eval.ts+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/redeploy.eval.ts@@ -13,9 +13,9 @@ import type { EveEvalContext } from "eve/evals";// each redeploy repoints the alias, so the runner's client — and the durable// session it drives — lands on the new deployment without any URL swap.//-// Each inbound request stamps the exact deployment that accepted it. The-// parked driver dispatches that request's turn to the stamped deployment, so-// repointing the alias adopts new code without resolving a "latest" sentinel.+// Each inbound request stamps the exact deployment that accepted it. An idle+// parked session hands ownership to that deployment before executing the turn,+// so repointing the alias adopts new code without a "latest" lookup.//// Timeline under test:// t0 session A writes a file into its sandbox workspacediff --git a/e2e/fixtures/agent-tools/agent/channels/anchored.ts b/e2e/fixtures/agent-tools/agent/channels/anchored.tsindex 85a156eeb..8f57ec4d0 100644--- a/e2e/fixtures/agent-tools/agent/channels/anchored.ts+++ b/e2e/fixtures/agent-tools/agent/channels/anchored.ts@@ -93,7 +93,7 @@ export default defineChannel({continuation !== undefined &&!continuation.token.endsWith(`:${anchorToken}`)) {- continuation.rekey(anchorToken);+ continuation.alias(anchorToken);}},},diff --git a/e2e/fixtures/agent-tools/evals/channel-metadata/anchored-no-topic.eval.ts b/e2e/fixtures/agent-tools/evals/channel-metadata/anchored-no-topic.eval.tsindex 7c2148a54..bec5fa013 100644--- a/e2e/fixtures/agent-tools/evals/channel-metadata/anchored-no-topic.eval.ts+++ b/e2e/fixtures/agent-tools/evals/channel-metadata/anchored-no-topic.eval.ts@@ -5,11 +5,13 @@ import { defineEval } from "eve/evals";import { METADATA_TOOL, PROMPT, startChannelSession } from "./shared";// The anchored channel's metadata has no `topic`, so the resolver-// returns null and no tool registers: the turn completes without a-// dynamic-channel-metadata result and without failures.+// returns null and no tool registers. The channel also adds its permanent+// address after the first reply; sending again through the initial address+// verifies that additive continuation hooks keep both addresses active.export default defineEval({tags: ["real-model"],- description: "Channel metadata smoke: missing topic metadata takes the null-resolve path.",+ description:+ "Channel metadata smoke: missing topic takes the null path and alias preserves the initial address.",async test(t) {const threadId = `thread-${randomBytes(4).toString("hex")}`;const sessionId = await startChannelSession(t.target, "/anchor/start", {@@ -22,6 +24,16 @@ export default defineEval({session.notCalledTool(METADATA_TOOL);session.noFailedActions();+ const resumedSessionId = await startChannelSession(t.target, "/anchor/start", {+ message: "Reply exactly: resumed through the initial address.",+ threadId,+ });+ if (resumedSessionId !== sessionId) {+ throw new Error(+ `Initial continuation address created ${resumedSessionId} instead of resuming ${sessionId}.`,+ );+ }+t.succeeded();t.notCalledTool(METADATA_TOOL);},diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/hold_deploy.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/hold_deploy.tsindex 627e1a891..9fe4bf474 100644--- a/e2e/fixtures/agent-workflow-tools/agent/tools/hold_deploy.ts+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/hold_deploy.ts@@ -3,7 +3,7 @@ import { sleep } from "workflow";import { z } from "zod";/**- * Parks the turn on a long durable sleep so a steer can cancel it. Exercises+ * Parks the turn on a long durable sleep until explicitly cancelled. Exercises* cancellation cascading into a workflow tool run.*/export default defineWorkflowTool({diff --git a/e2e/fixtures/agent-workflow-tools/evals/hold-deploy.cancel.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/hold-deploy.cancel.eval.tsindex 8c66ddee3..e8f271b11 100644--- a/e2e/fixtures/agent-workflow-tools/evals/hold-deploy.cancel.eval.ts+++ b/e2e/fixtures/agent-workflow-tools/evals/hold-deploy.cancel.eval.ts@@ -8,7 +8,7 @@ import { satisfies } from "eve/evals/expect";*/export default defineEval({timeoutMs: 60_000,- description: "Steering a turn cancels the workflow tool run it is parked on.",+ description: "Cancelling a turn cancels the workflow tool run it is parked on.",async test(t) {const live = await t.start("WORKFLOW-HOLD-START");await live.waitForEvent("actions.requested", {diff --git a/e2e/fixtures/agent-workflow-tools/evals/mixed-agent-resolution.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/mixed-agent-resolution.eval.tsindex 8d0ca3cb0..82b5d61b2 100644--- a/e2e/fixtures/agent-workflow-tools/evals/mixed-agent-resolution.eval.ts+++ b/e2e/fixtures/agent-workflow-tools/evals/mixed-agent-resolution.eval.ts@@ -8,7 +8,7 @@ export default defineEval({initial.expectOk();initial.calledTool("blocking_agent", { count: 1, status: "completed" });initial.calledTool("background_agent", { count: 1, status: "completed" });- initial.event("subagent.called", { data: { name: "workflow-marker" }, count: 1 });+ initial.event("subagent.called", { data: { name: "workflow-marker" } });initial.messageIncludes("WORKFLOW-MIXED-AGENTS-INITIAL-RESULT");initial.notEvent("message.received", {data: { message: /WORKFLOW-CHILD:api:background/u },diff --git a/e2e/fixtures/fixture-tasks/evals/batching.ts b/e2e/fixtures/fixture-tasks/evals/batching.tsindex de228d876..135f94965 100644--- a/e2e/fixtures/fixture-tasks/evals/batching.ts+++ b/e2e/fixtures/fixture-tasks/evals/batching.ts@@ -29,7 +29,7 @@ export async function startBlockedFanout(t: EveEvalContext, count: number) {const setupEvents: EveEvalTurn["events"][number][] = [];const requests = new Map<string, InputRequest>();collectRequests(started);- for (let attempt = 0; requests.size < count && attempt < count; attempt += 1) {+ while (requests.size < count) {collectRequests(await nextTurn());}diff --git a/e2e/fixtures/fixture-tasks/evals/task.agent.steer.accepted-busy.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.agent.steer.accepted-busy.eval.tsindex 59cd6bf4f..55d3df4c1 100644--- a/e2e/fixtures/fixture-tasks/evals/task.agent.steer.accepted-busy.eval.ts+++ b/e2e/fixtures/fixture-tasks/evals/task.agent.steer.accepted-busy.eval.ts@@ -1,4 +1,4 @@-import { satisfies } from "eve/evals/expect";+import { equals, satisfies } from "eve/evals/expect";import { defineTaskEval } from "./task-transition.js";import {@@ -8,13 +8,12 @@ import {sendAndFollowQueuedTurn,waitForCompletedTask,waitForTaskInput,- waitForTaskNotification,} from "./shared.js";/** Same-batch calls compete for one claim; a later message steers the admitted task. */export default defineTaskEval({description:- "One same-batch continuation is admitted; later steering cancels its task and reuses the child.",+ "One same-batch continuation is admitted; later steering preserves its task and pending approval.",transition: {primary: "task.agent.steer.accepted-busy",setup: [@@ -72,21 +71,15 @@ export default defineTaskEval({later.turn.expectOk();later.turn.calledSubagent("busy-worker", { count: 1, status: "completed" });const steeredTaskId = requireBackgroundTaskId(later.turn);- await t.require(- steeredTaskId,- satisfies((taskId) => taskId !== admittedTaskId, "steering creates a new task identity"),- );-- const cancelled = await waitForTaskNotification(- t,- later.session,- admittedTaskId,- "cancelled",- later.observedTurns,- );+ await t.require(steeredTaskId, equals(admittedTaskId));+ // Steering retains the existing request; it does not publish a replacement approval.+ const approved = await later.session.respond([+ { requestId: held.request.requestId, optionId: "approve" },+ ]);+ approved.expectOk();const completed = await waitForCompletedTask(t,- cancelled.session,+ later.session,"CHILD-TASK-EXCLUSIVITY-VERIFY",steeredTaskId,);@@ -103,7 +96,7 @@ export default defineTaskEval({value !== null &&typeof value === "object" &&Reflect.get(value, "data") === "BUSY-WORKER:Return BUSY-WORKER-LATER.",- "the replacement task completes with the steering message's result",+ "the original task completes with the steering message's result",),);},diff --git a/e2e/fixtures/fixture-tasks/evals/task.parent-interaction.send.accepted-live-children.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.parent-interaction.send.accepted-live-children.eval.tsindex 1f92c1a95..d3f3d511c 100644--- a/e2e/fixtures/fixture-tasks/evals/task.parent-interaction.send.accepted-live-children.eval.ts+++ b/e2e/fixtures/fixture-tasks/evals/task.parent-interaction.send.accepted-live-children.eval.ts@@ -54,7 +54,9 @@ async function waitForReleaseRequests(const requests = new Map<string, InputRequest>();let session = initialSession;collectReleaseRequests(initialTurn, requests);- for (let attempt = 0; attempt < FANOUT_SIZE && requests.size < FANOUT_SIZE; attempt += 1) {+ // The parent completion may be the first watched boundary before child HITL+ // callbacks arrive, so allow one boundary in addition to the ten requests.+ for (let attempt = 0; attempt <= FANOUT_SIZE && requests.size < FANOUT_SIZE; attempt += 1) {const sessionId = session.sessionId;if (sessionId === undefined) throw new Error("Task fanout has no parent session id.");const live = t.target.watchTurn(sessionId, {diff --git a/packages/eve/extension-contracts/reports/channel/v23.json b/packages/eve/extension-contracts/reports/channel/v23.jsonnew file mode 100644index 000000000..4af5cff63--- /dev/null+++ b/packages/eve/extension-contracts/reports/channel/v23.json@@ -0,0 +1,21 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "channel",+ "epoch": 23,+ "sha256": "4b5f98a56d3a462551de62856fa36b0f17fc73e7528ad0fdafb01c767f6f0727",+ "exports": [+ "DELETE",+ "GET",+ "HEAD",+ "OPTIONS",+ "PATCH",+ "POST",+ "PUT",+ "WS",+ "createWebSocketUpgradeServer",+ "defineChannel",+ "disableRoute",+ "isChannel",+ "isDisabledRouteSentinel"+ ]+}diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v41.json b/packages/eve/extension-contracts/reports/dynamicTool/v41.jsonnew file mode 100644index 000000000..fe99d8fcd--- /dev/null+++ b/packages/eve/extension-contracts/reports/dynamicTool/v41.json@@ -0,0 +1,14 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "dynamicTool",+ "epoch": 41,+ "sha256": "415a74bc1d72a76ac201cb1aedc34c3722df2c3cf526583306a906c9a1433b69",+ "exports": [+ "DynamicToolEntry",+ "DynamicToolEvents",+ "DynamicToolResult",+ "DynamicToolSet",+ "defineDurableCallback",+ "defineDynamic"+ ]+}diff --git a/packages/eve/extension-contracts/reports/tool/v44.json b/packages/eve/extension-contracts/reports/tool/v44.jsonnew file mode 100644index 000000000..dfabc6013--- /dev/null+++ b/packages/eve/extension-contracts/reports/tool/v44.json@@ -0,0 +1,22 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "tool",+ "epoch": 44,+ "sha256": "9768c0cc59251793f94e5000683382e9bf494bc4d12caec0785801faedfdc4a0",+ "exports": [+ "WorkflowTool",+ "WorkflowToolInput",+ "WorkflowToolOptions",+ "defaultWebSearch",+ "defineTool",+ "defineWorkflowTool",+ "disableTool",+ "isDisabledToolSentinel",+ "isWebSearchToolDefinition",+ "toolOutput",+ "toolOutputPart",+ "toolResultFrom",+ "webSearch",+ "workflow"+ ]+}diff --git a/packages/eve/scripts/vendor-compiled/@workflow/core.mjs b/packages/eve/scripts/vendor-compiled/@workflow/core.mjsindex 83f803bca..daa96fde2 100644--- a/packages/eve/scripts/vendor-compiled/@workflow/core.mjs+++ b/packages/eve/scripts/vendor-compiled/@workflow/core.mjs@@ -173,6 +173,8 @@ export default {chunkGroup: "workflow",plugins: [stubCoreWorldFactories(), stubCoreQuickJSEntrypoint()],entries: [+ { entry: "dist/serialization.js", outputPath: "serialization" },+ { entry: "dist/runtime/helpers.js", outputPath: "runtime/helpers" },{outputPath: "index",},diff --git a/packages/eve/src/channel/adapter-context.ts b/packages/eve/src/channel/adapter-context.tsindex a4221422e..3229f031a 100644--- a/packages/eve/src/channel/adapter-context.ts+++ b/packages/eve/src/channel/adapter-context.ts@@ -8,7 +8,7 @@ import { buildSessionHandle } from "#channel/session.js";** Populates `session` with a live {@link SessionHandle} backed by the* supplied accessor so handlers can read identity / auth and call- * `session.continuation.rekey(...)` to re-key the parked session.+ * `session.continuation.alias(...)` to add an address for the parked session.*/export function buildAdapterContext<TCtx extends ChannelAdapterContext<any> = ChannelAdapterContext,diff --git a/packages/eve/src/channel/adapter.test.ts b/packages/eve/src/channel/adapter.test.tsindex 2d67b5410..9189251c2 100644--- a/packages/eve/src/channel/adapter.test.ts+++ b/packages/eve/src/channel/adapter.test.ts@@ -114,7 +114,7 @@ describe("ChannelAdapter helpers", () => {expect(defaultDeliverResult({})).toBeUndefined();});- it("publishes a waiting handler's re-keyed channel address", async () => {+ it("publishes a waiting handler's aliased channel address", async () => {let continuationToken = "slack:temporary";let observedToken: string | undefined;const context: ChannelAdapterContext = {@@ -126,7 +126,7 @@ describe("ChannelAdapter helpers", () => {get token() {return continuationToken.slice("slack:".length);},- rekey(token: string) {+ alias(token: string) {continuationToken = `slack:${token}`;},},@@ -137,7 +137,7 @@ describe("ChannelAdapter helpers", () => {kind: "slack","session.waiting"(data, ctx) {observedToken = data.continuationToken;- ctx.session.continuation?.rekey("C1:T1");+ ctx.session.continuation?.alias("C1:T1");},};diff --git a/packages/eve/src/channel/adapter.ts b/packages/eve/src/channel/adapter.tsindex 461788bc9..6a7cc2316 100644--- a/packages/eve/src/channel/adapter.ts+++ b/packages/eve/src/channel/adapter.ts@@ -28,8 +28,8 @@ const log = createLogger("channel.adapter");* {@link ContextAccessor} that tools and providers use).** `session` is a live handle to the current session — id, auth,- * optional channel continuation address, including an imperative `rekey()`- * for channels that need to re-key the session mid-turn (e.g. Slack's+ * optional channel continuation address, including an imperative `alias()`+ * for channels that need to add an alias for the session mid-turn (e.g. Slack's* auto-anchor on first post).*/export interface ChannelAdapterContext<TState = Record<string, unknown>> {diff --git a/packages/eve/src/channel/channel-address.ts b/packages/eve/src/channel/channel-address.tsindex 4e9df5d57..6f3a0eb54 100644--- a/packages/eve/src/channel/channel-address.ts+++ b/packages/eve/src/channel/channel-address.ts@@ -22,7 +22,7 @@ import type {TurnPolicy,} from "#channel/types.js";import { DEFAULT_TURN_POLICY } from "#channel/types.js";-import { isReservedSessionCommandToken } from "#execution/session-command-token.js";+import { isReservedSessionCommandToken } from "#execution/session-inbox/address.js";import type { RunMode } from "#shared/run-mode.js";interface BaseChannelAddressDeliveryOptions {diff --git a/packages/eve/src/channel/session.test.ts b/packages/eve/src/channel/session.test.tsindex c98dae2e6..004cf2cf8 100644--- a/packages/eve/src/channel/session.test.ts+++ b/packages/eve/src/channel/session.test.ts@@ -8,7 +8,13 @@ import {} from "#channel/session.js";import type { Runtime } from "#channel/types.js";import { ContextContainer } from "#context/container.js";-import { AuthKey, ContinuationTokenKey, InitiatorAuthKey, SessionIdKey } from "#context/keys.js";+import {+ AuthKey,+ ContinuationHookTokensKey,+ ContinuationTokenKey,+ InitiatorAuthKey,+ SessionIdKey,+} from "#context/keys.js";import { attachClientContext, readClientContext } from "#internal/client-context.js";import { type InputResponse, parseInputResponses } from "#shared/input.js";@@ -249,28 +255,28 @@ describe("buildSessionHandle", () => {expect(session.continuation?.token).toBe("C1:T1");});- it("namespaces the channel-local token on continuation.rekey", () => {+ it("namespaces the channel-local token on continuation.alias", () => {const ctx = new ContextContainer();ctx.set(ContinuationTokenKey, "slack:C1:");const session = buildSessionHandle(ctx);- session.continuation?.rekey("C1:T1");+ session.continuation?.alias("C1:T1");expect(ctx.get(ContinuationTokenKey)).toBe("slack:C1:T1");});- it("round-trips the exposed channel-local token through continuation.rekey", () => {+ it("round-trips the exposed channel-local token through continuation.alias", () => {const ctx = new ContextContainer();ctx.set(ContinuationTokenKey, "slack:C1:T1");const session = buildSessionHandle(ctx);- session.continuation?.rekey(session.continuation.token);+ session.continuation?.alias(session.continuation.token);expect(ctx.get(ContinuationTokenKey)).toBe("slack:C1:T1");});- it("is idempotent: a redundant continuation.rekey does not write", () => {- // Authors call continuation.rekey from hot-path event handlers+ it("records every distinct continuation address without duplicating redundant aliases", () => {+ // Authors call continuation.alias from hot-path event handlers// (e.g. Slack's `message.completed`). The handler can't always// know whether the token has actually changed, so the SessionHandle// itself short-circuits redundant writes — the workflow body@@ -294,13 +300,21 @@ describe("buildSessionHandle", () => {const session = buildSessionHandle(observed);- session.continuation?.rekey("C1:T1");+ session.continuation?.alias("C1:T1");expect(writeCount).toBe(0);expect(ctx.get(ContinuationTokenKey)).toBe("slack:C1:T1");- session.continuation?.rekey("C1:T2");- expect(writeCount).toBe(1);+ session.continuation?.alias("C1:T2");+ session.continuation?.alias("C1:T3");+ session.continuation?.alias("C1:T2");++ expect(writeCount).toBe(6);expect(ctx.get(ContinuationTokenKey)).toBe("slack:C1:T2");+ expect(ctx.get(ContinuationHookTokensKey)).toEqual([+ "slack:C1:T1",+ "slack:C1:T2",+ "slack:C1:T3",+ ]);});it("throws clearly when no namespaced placeholder token exists", () => {diff --git a/packages/eve/src/channel/session.ts b/packages/eve/src/channel/session.tsindex ba955d39b..c7532ff6c 100644--- a/packages/eve/src/channel/session.ts+++ b/packages/eve/src/channel/session.ts@@ -21,7 +21,13 @@ import type {import { DEFAULT_TURN_POLICY } from "#channel/types.js";import { serializeUrlFilePartsInMessage } from "#channel/send-input.js";import type { SessionAuth } from "#context/keys.js";-import { AuthKey, ContinuationTokenKey, InitiatorAuthKey, SessionIdKey } from "#context/keys.js";+import {+ AuthKey,+ ContinuationHookTokensKey,+ ContinuationTokenKey,+ InitiatorAuthKey,+ SessionIdKey,+} from "#context/keys.js";import {type InputResponse,parseInputResponses,@@ -79,15 +85,16 @@ export type SessionRespondOptions = SessionDeliveryOptions;* Live handle to the current session, exposed on `ctx.session` to* `deliver` and event handlers. The framework hydrates the read-only* fields from the active context at step start. A write through- * `continuation.rekey()` updates the context so the- * runtime can re-key the parked workflow hook at the next step boundary.+ * `continuation.alias()` selects a new current address and records it so the+ * runtime can add its hook to the session inbox at the next step boundary.+ * Previously claimed addresses remain active.*/export interface SessionHandle {readonly id: string;readonly auth: SessionAuth;readonly continuation?: {readonly token: string;- rekey(rawToken: string): void;+ alias(rawToken: string): void;};}@@ -219,9 +226,14 @@ export function buildSessionHandle(accessor: ContextAccessor): SessionHandle {if (currentToken === undefined || currentToken.length === 0) return undefined;return {token: toChannelLocalContinuationToken(currentToken),- rekey(rawToken: string): void {+ alias(rawToken: string): void {+ if (rawToken.length === 0) throw new Error("A session alias requires a nonempty token.");const token = namespaceContinuationToken(currentToken, rawToken);if (currentToken === token) return;+ accessor.set(ContinuationHookTokensKey, (claimed) => {+ const tokens = claimed ?? [currentToken];+ return tokens.includes(token) ? tokens : [...tokens, token];+ });accessor.set(ContinuationTokenKey, token);},};diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.tsindex 481d2bc69..763b40241 100644--- a/packages/eve/src/channel/types.ts+++ b/packages/eve/src/channel/types.ts@@ -1,6 +1,6 @@import type { UserContent } from "ai";-import type { SessionInboxAddress } from "#execution/wire/session-inbox-contract.js";+import type { SessionInboxAddress } from "#execution/session-inbox/address.js";import type { MessageStreamEvent, UnstampedMessageStreamEvent } from "#protocol/message.js";import type { CancelTurnResult as ProtocolCancelTurnResult } from "#protocol/cancel-turn.js";import type { RunMode } from "#shared/run-mode.js";@@ -291,6 +291,8 @@ export interface DeliverHookPayload {/** Internal deadline signal sent through the stable session command inbox. */export interface SessionTimeoutHookPayload {readonly kind: "session-timeout";+ /** The owner run that armed this timer; a later owner ignores a predecessor's deadline. */+ readonly ownerRunId: string;}/** Requests a context compaction without delivering model input. */@@ -503,10 +505,11 @@ export interface RunInput {readonly activityObserver?: ActivityObserverConfig;/*** Session continuation token for delivery and hook creation. Channels can- * re-key the session during the first turn via- * `ctx.session.continuation.rekey(...)` (e.g. Slack adopts its first+ * add a continuation address during the first turn via+ * `ctx.session.continuation.alias(...)` (e.g. Slack adopts its first* post's `ts` as the thread root), so an initial placeholder token is- * acceptable when full identity isn't known until the first message. ID-only+ * acceptable when full identity isn't known until the first message. Earlier+ * addresses remain valid after an alias. ID-only* transports omit this field.*/readonly continuationToken?: string;diff --git a/packages/eve/src/cli/commands/logs-events.integration.test.ts b/packages/eve/src/cli/commands/logs-events.integration.test.tsindex 2e654ac64..edf7ab565 100644--- a/packages/eve/src/cli/commands/logs-events.integration.test.ts+++ b/packages/eve/src/cli/commands/logs-events.integration.test.ts@@ -48,7 +48,7 @@ describe("readDevSessionEvents", () => {eventType: "run_created",eventData: {deploymentId: "dpl_test",- workflowName: "turnWorkflow",+ workflowName: "sessionWorkflow",input: [],},});diff --git a/packages/eve/src/cli/dev/tui/message-queue.test.ts b/packages/eve/src/cli/dev/tui/message-queue.test.tsindex 21b4aa91c..c8e397799 100644--- a/packages/eve/src/cli/dev/tui/message-queue.test.ts+++ b/packages/eve/src/cli/dev/tui/message-queue.test.ts@@ -131,14 +131,14 @@ describe("renderMessageQueueRows", () => {expect(render(queue, false)[0]).not.toContain("esc");});- it("shows the steering header while cancellation is in flight", () => {+ it("shows the steering header while awaiting an execution boundary", () => {const queue = new MessageQueue();queue.enqueue("go north");queue.enqueue("go south");queue.handleEscape();const rows = render(queue);- expect(rows[0]).toContain("Steering — cancelling the running turn…");+ expect(rows[0]).toContain("Steering — waiting for the next boundary…");expect(rows[0]).toContain("1/5 still queued");expect(rows[1]).toContain("└ go south");});diff --git a/packages/eve/src/cli/dev/tui/message-queue.ts b/packages/eve/src/cli/dev/tui/message-queue.tsindex 1cb576f86..95709f9e4 100644--- a/packages/eve/src/cli/dev/tui/message-queue.ts+++ b/packages/eve/src/cli/dev/tui/message-queue.ts@@ -5,8 +5,8 @@* Enter queues the draft (up to {@link MESSAGE_QUEUE_LIMIT}); each queued* message waits for the turn to end, where the whole queue coalesces into* the next turn's message. Esc or Ctrl+C pops the oldest message to steer the- * conversation instead of waiting: the renderer requests cooperative turn- * cancellation and the runner submits the popped message as the next turn.+ * conversation instead of waiting: the renderer sends the popped message to+ * the active session for admission at its next execution boundary.* `/cancel` requests cancellation directly. Either key on an empty queue* cancels the turn immediately without a replacement message.*@@ -24,9 +24,8 @@ export const MESSAGE_QUEUE_LIMIT = 5;/** What one Esc press did to the queue state. */export type MessageQueueEscapeOutcome =/**- * A message is (now) staged for steering — the caller should request- * cooperative turn cancellation. Repeated presses pop further messages- * into the same staged steer payload and re-request cancellation.+ * A message is staged for steering. The caller sends it to the active+ * session; repeated presses may select more queued messages.*/| "steer"/** Empty queue — the caller should cancel the turn. */@@ -36,7 +35,7 @@ export type MessageQueueEscapeOutcome =export interface MessageQueueView {readonly messages: readonly string[];readonly full: boolean;- /** A popped message is staged and turn cancellation was requested. */+ /** A popped message is awaiting steering admission. */readonly steering: boolean;/** A cancel key on an empty queue landed; cancellation was requested. */readonly cancelling: boolean;@@ -81,7 +80,7 @@ export class MessageQueue {return "steer";}if (this.#steerMessage !== undefined) {- // Already steering: re-request cancellation (idempotent server-side).+ // Retry an unaccepted steering message before requesting cancellation.return "steer";}this.#cancelRequested = true;@@ -113,6 +112,18 @@ export class MessageQueue {return this.#takeAllMessages();}+ /** Takes only a key-selected message for immediate boundary steering. */+ takeSteering(): string | undefined {+ const message = this.#steerMessage;+ this.#steerMessage = undefined;+ return message;+ }++ /** Preserves an unaccepted steering message for a later retry. */+ restoreSteering(message: string): void {+ this.#steerMessage = joinOptionalMessages(message, this.#steerMessage);+ }+/*** Everything still held — staged steer payload plus queued messages —* coalesced for restoring into the prompt editor when a turn ends without@@ -207,7 +218,7 @@ function headerBody(view: MessageQueueView, working: boolean, theme: Theme): strconst count = `${String(view.messages.length)}/${String(MESSAGE_QUEUE_LIMIT)}`;if (view.steering) {const remaining = view.messages.length > 0 ? `${dot}${count} still queued` : "";- return c.dim(`Steering — cancelling the running turn…${remaining}`);+ return c.dim(`Steering — waiting for the next boundary…${remaining}`);}const fullness = view.full ? `${dot}queue full` : "";const hint = working ? `${dot}esc or ctrl+c steers with the next message` : "";diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.tsindex 00208b2ed..2725863e9 100644--- a/packages/eve/src/cli/dev/tui/runner.test.ts+++ b/packages/eve/src/cli/dev/tui/runner.test.ts@@ -2418,6 +2418,56 @@ describe("EveTUIRunner failure rendering", () => {});describe("EveTUIRunner reused step indexes", () => {+ it("renders a follow-up turn carried by the same steering stream", async () => {+ const prompts: Array<string | undefined> = ["start", undefined];+ const emitted: AgentTUIStreamEvent[] = [];+ const session = sessionYielding([+ { type: "turn.started", data: { sequence: 0, turnId: "turn_0" } },+ { type: "step.started", data: { sequence: 0, stepIndex: 0, turnId: "turn_0" } },+ {+ type: "message.completed",+ data: {+ finishReason: "stop",+ message: "First answer.",+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_0",+ },+ },+ { type: "turn.completed", data: { sequence: 0, turnId: "turn_0" } },+ { type: "turn.started", data: { sequence: 1, turnId: "turn_1" } },+ { type: "step.started", data: { sequence: 1, stepIndex: 0, turnId: "turn_1" } },+ {+ type: "message.completed",+ data: {+ finishReason: "stop",+ message: "Follow-up answer.",+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_1",+ },+ },+ { type: "turn.completed", data: { sequence: 1, turnId: "turn_1" } },+ { type: "session.waiting", data: { wait: "next-user-message" } },+ ]);+ const renderer: AgentTUIRenderer = {+ readPrompt: vi.fn(async () => prompts.shift()),+ renderStream: vi.fn(async (result) => {+ for await (const event of result.events as AsyncIterable<AgentTUIStreamEvent>) {+ emitted.push(event);+ }+ }),+ };++ await new EveTUIRunner({ session, renderer, name: "Weather Agent" }).run();++ expect(+ emitted.flatMap((event) =>+ event.type === "assistant-complete" && event.text !== undefined ? [event.text] : [],+ ),+ ).toEqual(["First answer.", "Follow-up answer."]);+ });+it("renders the post-subagent message that the harness emits under a reused stepIndex", async () => {// Mirrors the real parent stream around a subagent dispatch: the second// model call arrives under a fresh `step.started` but the SAME@@ -4357,8 +4407,7 @@ describe("EveTUIRunner mid-turn message queue", () => {gate.resolve();return { sessionId: "session_test", status: "accepted" as const };}- // The first request raced the dispatch window: the turn workflow has- // not claimed its cancel hook yet, so the server reports no turn.+ // The first request arrived before the owner began the turn.return { status: "no_active_turn" as const };});const prompts: Array<string | undefined> = ["hello", undefined];@@ -4487,7 +4536,7 @@ describe("EveTUIRunner session id reporting", () => {});describe("EveTUIRunner cancelled-turn subagent settling", () => {- it("settles subagent sections when the turn is cancelled by a steer", async () => {+ it("settles subagent sections when the turn is explicitly cancelled", async () => {// A child stream that never ends on its own — it only stops when the// pump aborts it (the scoped cancellation path under test).const client = stubClient();diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.tsindex 29770e95b..02987f834 100644--- a/packages/eve/src/cli/dev/tui/runner.ts+++ b/packages/eve/src/cli/dev/tui/runner.ts@@ -1,3 +1,4 @@+import { SteeringStream } from "#cli/dev/tui/steering-stream.js";import {type ActionResultStreamEvent,type ActionsRequestedStreamEvent,@@ -150,6 +151,7 @@ async function abortableDelay(ms: number, signal: AbortSignal): Promise<void> {}export type AgentTUIStreamResult = {+ steer?: (message: string) => Promise<void>;events: AsyncIterable<AgentTUIStreamEvent> | ReadableStream<AgentTUIStreamEvent>;abort?: () => void;/**@@ -1529,9 +1531,8 @@ export class EveTUIRunner {/*** Requests cooperative cancellation of the streaming turn and retries- * while the turn stays live. A key-driven cancel that lands in the dispatch- * window — after the turn was sent but before the turn workflow claims its- * cancel hook (i.e. before `turn.started` reaches the client) — resolves as a+ * while the turn stays live. A key-driven cancel that lands before the owner+ * begins the turn (i.e. before `turn.started` reaches the client) resolves as a* benign `no_active_turn` and would otherwise be silently lost, leaving* the TUI showing "Cancelling…" while the turn runs to completion.* Retrying until the stream reaches its boundary closes that window.@@ -1593,17 +1594,21 @@ export class EveTUIRunner {sourceSession: ClientSession | undefined,): AgentTUIStreamResult {const turnState = createTurnState();+ const steering =+ sourceSession === undefined ? undefined : new SteeringStream(events, sourceSession);return {+ steer: steering === undefined ? undefined : (message) => steering.send(message),abort: () => {turnState.aborted = true;this.#failedSession = sourceSession;+ steering?.abort();abort();},cancel: () => {void this.#requestTurnCancellation(turnState, sourceSession);},events: eveEventsToTUIStream({- events,+ events: steering ?? events,pendingInputRequests: this.#pendingInputRequests,turnState,onSubagentCalled: (called) => this.#subagentPump.begin(called),@@ -2261,6 +2266,7 @@ async function* eveEventsToTUIStream(// Recorded so key-driven cancellation can scope its request to the// turn the user is watching; a cancel that arrives after the// boundary then no-ops instead of hitting the next turn.+ if (event.data.turnId !== turnState.turnId) visibleTurnCompleted = false;turnState.turnId = event.data.turnId;break;@@ -2557,7 +2563,7 @@ async function* eveEventsToTUIStream(break;case "turn.cancelled":- // A cooperative cancel (`/cancel`, Esc, Ctrl+C, or a steer) — not a failure.+ // Explicit cooperative cancellation preserves the session.// `session.waiting` follows and finishes the stream normally.onTurnCancelled?.(event.data.turnId);yield* closeOpenParts(textParts, "assistant-complete", stepEpoch);diff --git a/packages/eve/src/cli/dev/tui/steering-stream.test.ts b/packages/eve/src/cli/dev/tui/steering-stream.test.tsnew file mode 100644index 000000000..7823be9b0--- /dev/null+++ b/packages/eve/src/cli/dev/tui/steering-stream.test.ts@@ -0,0 +1,87 @@+import { describe, expect, it, vi } from "vitest";+import { SteeringStream } from "#cli/dev/tui/steering-stream.js";+import { stampTestEvents } from "#internal/testing/events.js";+import { createMessageReceivedEvent, createSessionWaitingEvent } from "#protocol/message.js";++describe("SteeringStream", () => {+ 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" }),+ createMessageReceivedEvent({ message: "steer", sequence: 0, turnId: "turn_0" }),+ createSessionWaitingEvent(),+ ]);+ const session = { send: vi.fn(async () => iterate(events.slice(1))) };+ const stream = new SteeringStream(iterate(events), session);+ await stream.send("steer");+ expect(await collect(stream)).toEqual(events);+ expect(session.send).toHaveBeenCalledWith("steer", {+ turnPolicy: "steer",+ signal: expect.any(AbortSignal),+ });+ });++ it("follows a message accepted after the original turn settled", async () => {+ const events = stampTestEvents([+ createMessageReceivedEvent({ message: "first", sequence: 0, turnId: "turn_0" }),+ createSessionWaitingEvent(),+ createMessageReceivedEvent({ message: "later", sequence: 1, turnId: "turn_1" }),+ createSessionWaitingEvent(),+ ]);+ const stream = new SteeringStream(iterate(events.slice(0, 2)), {+ send: async () => iterate(events.slice(2)),+ });+ await stream.send("later");+ expect(await collect(stream)).toEqual([events[0], events[2], events[3]]);+ });++ it("skips an overlapping settled boundary before following the accepted turn", async () => {+ const events = stampTestEvents([+ createMessageReceivedEvent({ message: "first", sequence: 0, turnId: "turn_0" }),+ createSessionWaitingEvent(),+ createMessageReceivedEvent({ message: "later", sequence: 1, turnId: "turn_1" }),+ createSessionWaitingEvent(),+ ]);+ const stream = new SteeringStream(iterate(events.slice(0, 2)), {+ send: async () => iterate(events.slice(1)),+ });+ await stream.send("later");+ expect(await collect(stream)).toEqual([events[0], events[2], events[3]]);+ });++ it("aborts all accepted follow-up responses when the consumer detaches", async () => {+ const signals: AbortSignal[] = [];+ const stream = new SteeringStream(iterate([]), {+ send: async (_message, options) => {+ signals.push(options.signal);+ return iterate([]);+ },+ });+ await stream.send("first");+ await stream.send("second");+ stream.abort();+ expect(signals.every((signal) => signal.aborted)).toBe(true);+ await expect(stream.send("late")).rejects.toThrow("active stream ended");+ });++ it("reports failed admission without losing the original stream boundary", async () => {+ const events = stampTestEvents([createSessionWaitingEvent()]);+ const stream = new SteeringStream(iterate(events), {+ send: async () => {+ throw new Error("send failed");+ },+ });+ await expect(stream.send("steer")).rejects.toThrow("send failed");+ expect(await collect(stream)).toEqual(events);+ await expect(stream.send("late")).rejects.toThrow("active stream ended");+ });+});++async function* iterate<T>(values: readonly T[]): AsyncGenerator<T> {+ yield* values;+}++async function collect<T>(values: AsyncIterable<T>): Promise<T[]> {+ const result: T[] = [];+ for await (const value of values) result.push(value);+ return result;+}diff --git a/packages/eve/src/cli/dev/tui/steering-stream.ts b/packages/eve/src/cli/dev/tui/steering-stream.tsnew file mode 100644index 000000000..acfa81ea5--- /dev/null+++ b/packages/eve/src/cli/dev/tui/steering-stream.ts@@ -0,0 +1,66 @@+import { createEventDeduper } from "#protocol/event-dedupe.js";+import { isCurrentTurnBoundaryEvent, type MessageStreamEvent } from "#protocol/message.js";++/**+ * Follows accepted messages through their boundary, including a send racing+ * settlement. Delivery responses may overlap; stream event IDs deduplicate them.+ */+export class SteeringStream implements AsyncIterable<MessageStreamEvent> {+ private readonly session: {+ send(+ message: string,+ options: { turnPolicy: "steer"; signal: AbortSignal },+ ): Promise<AsyncIterable<MessageStreamEvent>>;+ };+ private readonly streams: Promise<AsyncIterable<MessageStreamEvent> | undefined>[];+ private closed = false;+ private readonly controller = new AbortController();++ constructor(initial: AsyncIterable<MessageStreamEvent>, session: SteeringStream["session"]) {+ this.session = session;+ this.streams = [Promise.resolve(initial)];+ }++ async send(message: string): Promise<void> {+ if (this.closed) throw new Error("The active stream ended before steering was sent.");+ const response = this.session.send(message, {+ turnPolicy: "steer",+ signal: this.controller.signal,+ });+ // Handle failure immediately even if the initial stream has not finished.+ this.streams.push(+ response.then(+ (value) => value,+ () => undefined,+ ),+ );+ await response;+ }++ abort(): void {+ this.closed = true;+ this.controller.abort();+ }++ async *[Symbol.asyncIterator](): AsyncGenerator<MessageStreamEvent> {+ const seen = createEventDeduper();+ let boundary: MessageStreamEvent | undefined;+ try {+ while (this.streams.length > 0) {+ const stream = await this.streams.shift()!;+ if (stream === undefined) continue;+ for await (const event of stream) {+ if (!seen.admit(event)) continue;+ if (isCurrentTurnBoundaryEvent(event)) {+ boundary = event;+ break;+ }+ yield event;+ }+ }+ if (boundary !== undefined) yield boundary;+ } finally {+ this.abort();+ }+ }+}diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.test.tsindex 4df1e1682..4e4bc6211 100644--- a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts@@ -2079,7 +2079,7 @@ describe("TerminalRenderer (inline scrollback)", () => {renderer.shutdown();});- it("pops the oldest queued message on Esc, cancels the turn, and stages the steer prompt", async () => {+ it("sends the oldest queued message on Esc without cancelling the turn", async () => {const { screen, input, renderer } = makeRenderer();const escape = async () => {input.send("\x1b");@@ -2087,9 +2087,11 @@ describe("TerminalRenderer (inline scrollback)", () => {};let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;const cancel = vi.fn();+ const steer = vi.fn(async () => {});const rendering = renderer.renderStream({cancel,+ steer,events: new ReadableStream<AgentTUIStreamEvent>({start(controller) {streamController = controller;@@ -2111,18 +2113,16 @@ describe("TerminalRenderer (inline scrollback)", () => {});await escape();- expect(cancel).toHaveBeenCalledTimes(1);- expect(screen.snapshot()).toContain("Steering — cancelling the running turn…");- expect(screen.snapshot()).toContain("1/5 still queued");+ expect(cancel).not.toHaveBeenCalled();+ expect(steer).toHaveBeenCalledWith("go north");+ expect(screen.snapshot()).toContain("Queue 1/5");// The server settles the cancelled turn and the stream reaches its boundary.- streamController?.enqueue({ type: "turn-cancelled" });+ streamController?.enqueue({ type: "finish" });streamController?.close();await rendering;- expect(screen.snapshot()).toContain("Cancelled");// The popped message steers; the remaining one stays queued behind it.- expect(renderer.takeQueuedPrompt()).toBe("go north");expect(renderer.takeQueuedPrompt()).toBe("go south");renderer.shutdown();});@@ -2226,7 +2226,7 @@ describe("TerminalRenderer (inline scrollback)", () => {renderer.shutdown();});- it("marks drained prompts with the provenance arrow — above for steer, below for queue", async () => {+ it("marks steered and queued prompts with their provenance arrow", async () => {const { screen, input, renderer } = makeRenderer();const escape = async () => {input.send("\x1b");@@ -2243,7 +2243,7 @@ describe("TerminalRenderer (inline scrollback)", () => {let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;const first = renderer.renderStream({- cancel: vi.fn(),+ steer: vi.fn(async () => {}),events: new ReadableStream<AgentTUIStreamEvent>({start(controller) {streamController = controller;@@ -2258,16 +2258,11 @@ describe("TerminalRenderer (inline scrollback)", () => {input.type("go north");input.enter();await escape();- streamController?.enqueue({ type: "turn-cancelled" });+ streamController?.enqueue({ type: "finish" });streamController?.close();await first;- const steered = renderer.takeQueuedPrompt();- expect(steered).toBe("go north");- await renderer.renderStream(- { events: closedStream() },- { submittedPrompt: steered, continueSession: true },- );+ expect(renderer.takeQueuedPrompt()).toBeUndefined();let lines = screen.snapshot().split("\n");const steerIndex = lines.findIndex((line) => line.includes("│ go north"));expect(lines[steerIndex - 1]?.trim()).toBe("↑");diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.tsindex 8e819d7dd..5e32ce954 100644--- a/packages/eve/src/cli/dev/tui/terminal-renderer.ts+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.ts@@ -568,6 +568,7 @@ export class TerminalRenderer implements AgentTUIRenderer {readonly #messageQueue = new MessageQueue();/** The streaming result's cooperative cancel, available to Esc and Ctrl+C. */#requestTurnCancel?: () => void;+ #sendSteering?: (message: string) => Promise<void>;/** Set by the `turn-cancelled` stream event: settle in-flight tool blocks. */#turnCancelled = false;/** Server session id backing the conversation; named in the parting line. */@@ -578,7 +579,7 @@ export class TerminalRenderer implements AgentTUIRenderer {* the user block can carry its steer/queue gutter arrow.*/#nextSubmittedPromptOrigin?: "steer" | "queue";- /** True once this stream's prompt requested cancellation or steering. */+ /** True once this stream's prompt requested cancellation. */#cancelRequestedByUser = false;/** The prompt submitted for the streaming turn, for external-cancel recovery. */#currentSubmittedPrompt?: string;@@ -955,6 +956,7 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#currentSubmittedPrompt = options?.submittedPrompt;this.#messageQueue.beginTurn();this.#requestTurnCancel = result.cancel;+ this.#sendSteering = result.steer;this.#totalTokens = undefined;this.#promptTokens = undefined;this.#assistantOutputTokens = undefined;@@ -1004,6 +1006,7 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#resolveStreamInterrupt = undefined;if (this.#interrupted) result.abort?.();this.#requestTurnCancel = undefined;+ this.#sendSteering = undefined;this.#detachInput();this.#stopTicker();this.#streamDraftActive = false;@@ -3240,14 +3243,27 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#paint();break;}- // Esc and Ctrl+C drive steering and cancellation: pop the oldest- // queued message and cancel the running turn so the runner submits it- // as the replacement turn; with nothing queued, cancel immediately.+ // Send queued input through the active session. With nothing queued,+ // the same keys request explicit cancellation.// Without a cancel capability an empty queue leaves either key inert.if (this.#messageQueue.idle && this.#requestTurnCancel === undefined) break;- this.#messageQueue.handleEscape();- this.#cancelRequestedByUser = true;- this.#requestTurnCancel?.();+ const outcome = this.#messageQueue.handleEscape();+ if (outcome === "steer") {+ const send = this.#sendSteering;+ if (send !== undefined) {+ const message = this.#messageQueue.takeSteering()!;+ this.#nextSubmittedPromptOrigin = "steer";+ this.#addSubmittedPrompt(message);+ void send(message).catch((error) => {+ this.#messageQueue.restoreSteering(message);+ this.#addErrorBlock("Steering failed", toErrorMessage(error));+ this.#paint();+ });+ }+ } else {+ this.#cancelRequestedByUser = true;+ this.#requestTurnCancel?.();+ }this.#paint();break;}diff --git a/packages/eve/src/client/eve-agent-store-state.ts b/packages/eve/src/client/eve-agent-store-state.tsnew file mode 100644index 000000000..02cd29cc2--- /dev/null+++ b/packages/eve/src/client/eve-agent-store-state.ts@@ -0,0 +1,21 @@+import type { MessageResponse } from "#client/message-response.js";+import type { CancelSessionResult } from "#client/types.js";++export interface PendingMessageSubmission {+ readonly createdAt: number;+ readonly id: string;+ readonly message: string;+}++export interface ActiveTurn {+ readonly abortController: AbortController;+ acceptedFollowUps: number;+ readonly cancel: () => Promise<CancelSessionResult>;+ readonly completion: Promise<void>;+ readonly followUpDispatches: Set<Promise<void>>;+ receivedFollowUps: number;+ readonly followUpSubmissionIds: Set<string>;+ readonly resolveCompletion: () => void;+ readonly response: Promise<MessageResponse | undefined>;+ readonly resolveResponse: (response: MessageResponse | undefined) => void;+}diff --git a/packages/eve/src/client/eve-agent-store.test.ts b/packages/eve/src/client/eve-agent-store.test.tsindex cc24ccdfd..f45a2e809 100644--- a/packages/eve/src/client/eve-agent-store.test.ts+++ b/packages/eve/src/client/eve-agent-store.test.ts@@ -821,13 +821,54 @@ describe("EveAgentStore session resume", () => {});describe("EveAgentStore steering", () => {- it("accepts an in-flight steer and follows its replacement turn", async () => {+ it.each([true, false])(+ "completes steering received in the active turn (optimistic=%s)",+ async (optimistic) => {+ const active = controlledStreamResponse();+ const events = stampTestEvents([+ createTurnStartedEvent({ sequence: 0, turnId: "turn_1" }),+ createMessageReceivedEvent({ message: "First", sequence: 0, turnId: "turn_1" }),+ createMessageReceivedEvent({ message: "Instead", sequence: 0, turnId: "turn_1" }),+ createMessageCompletedEvent({+ finishReason: "stop",+ message: "Updated reply.",+ sequence: 0,+ stepIndex: 1,+ turnId: "turn_1",+ }),+ createSessionWaitingEvent(),+ ] as UnstampedMessageStreamEvent[]).map((event) => ({+ ...event,+ meta: { ...event.meta, deliveryIds: ["delivery_1"] },+ }));+ const fetchMock = vi+ .spyOn(globalThis, "fetch")+ .mockResolvedValueOnce(startedResponse())+ .mockResolvedValueOnce(active.response)+ .mockResolvedValueOnce(startedResponse());+ const store = new EveAgentStore({ optimistic, reducer: defaultMessageReducer() });+ const initial = store.send({ message: "First" });+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));+ active.emit(events[0]!);+ active.emit(events[1]!);+ const steering = store.send({ message: "Instead", turnPolicy: "steer" });+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(3));+ for (const event of events.slice(2)) active.emit(event);+ active.close();+ await Promise.all([initial, steering]);+ expect(store.snapshot.status).toBe("ready");+ expect(store.snapshot.events).toEqual(events);+ expect(fetchMock).toHaveBeenCalledTimes(3);+ },+ );++ it("follows a late steering delivery after the active turn settles", async () => {const activeStream = controlledStreamResponse();- const replacementStream = controlledStreamResponse();+ const followUpStream = controlledStreamResponse();const [firstReceived,firstStarted,- firstCancelled,+ firstCompleted,firstWaiting,secondReceived,secondStarted,@@ -836,13 +877,19 @@ describe("EveAgentStore steering", () => {] = stampTestEvents([createMessageReceivedEvent({ message: "First", sequence: 0, turnId: "turn_1" }),createTurnStartedEvent({ sequence: 1, turnId: "turn_1" }),- createTurnCancelledEvent({ sequence: 2, turnId: "turn_1" }),+ createMessageCompletedEvent({+ finishReason: "stop",+ message: "First reply.",+ sequence: 2,+ stepIndex: 0,+ turnId: "turn_1",+ }),createSessionWaitingEvent(),createMessageReceivedEvent({ message: "Instead", sequence: 0, turnId: "turn_2" }),createTurnStartedEvent({ sequence: 1, turnId: "turn_2" }),createMessageCompletedEvent({finishReason: "stop",- message: "Replacement reply.",+ message: "Follow-up reply.",sequence: 2,stepIndex: 0,turnId: "turn_2",@@ -857,7 +904,7 @@ describe("EveAgentStore steering", () => {.mockResolvedValueOnce(startedResponse()).mockResolvedValueOnce(activeStream.response).mockResolvedValueOnce(startedResponse())- .mockResolvedValueOnce(replacementStream.response);+ .mockResolvedValueOnce(followUpStream.response);const store = new EveAgentStore({ reducer: defaultMessageReducer() });const firstSend = store.send({ message: "First" });@@ -872,22 +919,22 @@ describe("EveAgentStore steering", () => {turnPolicy: "steer",});- activeStream.emit(firstCancelled!);+ activeStream.emit(firstCompleted!);activeStream.emit(firstWaiting!);activeStream.close();await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(4));- replacementStream.emit(secondReceived!);- replacementStream.emit(secondStarted!);- replacementStream.emit(secondCompleted!);- replacementStream.emit(secondWaiting!);- replacementStream.close();+ followUpStream.emit(secondReceived!);+ followUpStream.emit(secondStarted!);+ followUpStream.emit(secondCompleted!);+ followUpStream.emit(secondWaiting!);+ followUpStream.close();await Promise.all([firstSend, steering]);expect(store.snapshot.status).toBe("ready");expect(store.snapshot.events).toEqual([firstReceived,firstStarted,- firstCancelled,+ firstCompleted,firstWaiting,secondReceived,secondStarted,@@ -897,7 +944,7 @@ describe("EveAgentStore steering", () => {expect(store.snapshot.data.messages.at(-1)?.parts).toContainEqual({state: "done",stepIndex: 0,- text: "Replacement reply.",+ text: "Follow-up reply.",type: "text",});});diff --git a/packages/eve/src/client/eve-agent-store.ts b/packages/eve/src/client/eve-agent-store.tsindex 7ffd4ffbf..3634024c1 100644--- a/packages/eve/src/client/eve-agent-store.ts+++ b/packages/eve/src/client/eve-agent-store.ts@@ -1,4 +1,5 @@import { Client } from "#client/client.js";+import type { ActiveTurn, PendingMessageSubmission } from "#client/eve-agent-store-state.js";import type { MessageResponse } from "#client/message-response.js";import type { EveAgentReducer, EveAgentReducerEvent } from "#client/reducer.js";import type { ClientSession } from "#client/session.js";@@ -95,26 +96,8 @@ export interface EveAgentStoreInit<TData> {readonly session?: ClientSession;}-interface PendingMessageSubmission {- readonly createdAt: number;- readonly id: string;- readonly message: string;-}-const detachStore = Symbol("detachEveAgentStore");-interface ActiveTurn {- readonly abortController: AbortController;- acceptedFollowUps: number;- readonly cancel: () => Promise<CancelSessionResult>;- readonly completion: Promise<void>;- readonly followUpDispatches: Set<Promise<void>>;- receivedFollowUps: number;- readonly resolveCompletion: () => void;- readonly response: Promise<MessageResponse | undefined>;- readonly resolveResponse: (response: MessageResponse | undefined) => void;-}-/*** Framework-agnostic state machine for an eve agent session.*@@ -220,6 +203,7 @@ export class EveAgentStore<TData> {completion: completion.promise,followUpDispatches: new Set(),receivedFollowUps: 0,+ followUpSubmissionIds: new Set(),resolveCompletion: completion.resolve,response: response.promise,resolveResponse: response.resolve,@@ -323,6 +307,7 @@ export class EveAgentStore<TData> {completion: completion.promise,followUpDispatches: new Set(),receivedFollowUps: 0,+ followUpSubmissionIds: new Set(),resolveCompletion: completion.resolve,response: response.promise,resolveResponse: response.resolve,@@ -442,7 +427,7 @@ export class EveAgentStore<TData> {async #sendFollowUp<TOutput>(turn: ActiveTurn, input: SendTurnPayload<TOutput>): Promise<void> {if (input.message === undefined || input.turnPolicy !== "steer") {throw new Error(- 'eve session is already processing a turn. Send a message with turnPolicy: "steer" to replace it.',+ 'eve session is already processing a turn. Send a message with turnPolicy: "steer" to guide it at the next boundary.',);}@@ -454,6 +439,7 @@ export class EveAgentStore<TData> {if (!this.#isActiveTurn(turn)) return await this.send(preparedInput);const submissionId = this.#projectOptimisticMessage(preparedInput);+ if (submissionId !== undefined) turn.followUpSubmissionIds.add(submissionId);this.#publish();let dispatch!: Promise<void>;@@ -488,7 +474,6 @@ export class EveAgentStore<TData> {for await (const event of this.#session.stream({ signal: turn.abortController.signal })) {if (!this.#isActiveTurn(turn)) return;- if (event.type === "message.received") turn.receivedFollowUps += 1;this.#acceptServerEvent(event);if (isCurrentTurnBoundaryEvent(event)) {@@ -533,7 +518,7 @@ export class EveAgentStore<TData> {}#projectOptimisticMessage(input: SendTurnPayload): string | undefined {- if (!this.#optimistic || input.message === undefined) {+ if (input.message === undefined) {return undefined;}@@ -544,14 +529,15 @@ export class EveAgentStore<TData> {message: summarizeUserContent(input.message),};this.#pendingMessageSubmissions = [...this.#pendingMessageSubmissions, pending];- this.#appendProjectionEvent({- data: {- createdAt: pending.createdAt,- message: pending.message,- submissionId: pending.id,- },- type: "client.message.submitted",- });+ if (this.#optimistic)+ this.#appendProjectionEvent({+ data: {+ createdAt: pending.createdAt,+ message: pending.message,+ submissionId: pending.id,+ },+ type: "client.message.submitted",+ });return id;}@@ -586,6 +572,8 @@ export class EveAgentStore<TData> {const pendingSubmission = this.#pendingMessageSubmissions[0];if (event.type === "message.received" && pendingSubmission !== undefined) {const submissionId = pendingSubmission.id;+ if (this.#activeTurn?.followUpSubmissionIds.delete(submissionId))+ this.#activeTurn.receivedFollowUps += 1;this.#pendingMessageSubmissions = this.#pendingMessageSubmissions.slice(1);this.#replaceProjectionEvent((candidate) =>diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.tsindex 98f2a989a..dfc20ab02 100644--- a/packages/eve/src/compiler/extension-compatibility.ts+++ b/packages/eve/src/compiler/extension-compatibility.ts@@ -22,8 +22,8 @@ interface ExtensionCapabilityContract {const EXTENSION_CAPABILITY_CONTRACTS = {extension: { current: 1, supported: [1], dropped: {} },tool: {- current: 43,- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 28, 29, 30, 31, 32, 34, 35, 42, 43],+ current: 44,+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 28, 29, 30, 31, 32, 34, 35, 44],dropped: {14: "TaskExec.delegated was removed; migrate to workflow-backed background tools",15: "TaskExec replaces stageEffect with send",@@ -46,13 +46,15 @@ const EXTENSION_CAPABILITY_CONTRACTS = {39: "experimental_workflow and eve/tools/workflow were removed; migrate to the workflow factory from eve/tools/workflow",40: "runWorkflowProgram was made internal; use the workflow factory from eve/tools/workflow",41: "workflow no longer accepts agents and its options argument is optional; use workflow() or workflow({ maxSubagents })",+ 42: "Legacy session history migration was removed; user-role messages require current provenance kinds.",+ 43: "Legacy session history migration was removed; user-role messages require current provenance kinds.",},},dynamicTool: {- current: 40,+ current: 41,supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 28, 29, 30, 31, 32,- 33, 34, 39, 40,+ 33, 41,],dropped: {21: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",@@ -61,17 +63,24 @@ const EXTENSION_CAPABILITY_CONTRACTS = {25: "TaskExec.delegated was removed; migrate to workflow-backed background tools",26: "Background tools now use task yield descriptors",27: "TaskExec.delegated was removed; migrate to workflow-backed background tools",+ 34: "Legacy session history migration was removed; user-role messages require current provenance kinds.",35: "workflowMaxSubagents was removed with experimental_workflow; configure generated-program limits with the workflow factory",36: "workflowMaxSubagents was removed with experimental_workflow; configure generated-program limits with the workflow factory",37: "workflowMaxSubagents was removed with experimental_workflow; configure generated-program limits with the workflow factory",38: "workflowMaxSubagents was removed with experimental_workflow; configure generated-program limits with the workflow factory",+ 39: "Legacy session history migration was removed; user-role messages require current provenance kinds.",+ 40: "Legacy session history migration was removed; user-role messages require current provenance kinds.",},},channel: {- current: 22,- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22],+ current: 23,+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 23],dropped: {12: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",+ 19: "Continuation rekey was removed; channel extensions must use additive continuation.alias instead.",+ 20: "Continuation rekey was removed; channel extensions must use additive continuation.alias instead.",+ 21: "Continuation rekey was removed; channel extensions must use additive continuation.alias instead.",+ 22: "Continuation rekey was removed; channel extensions must use additive continuation.alias instead.",},},schedule: {diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.tsindex efd21b56e..32689b854 100644--- a/packages/eve/src/context/keys.ts+++ b/packages/eve/src/context/keys.ts@@ -21,7 +21,7 @@ import { ContextKey } from "#context/key.js";import {SESSION_INBOX_CONTEXT_KEY,type SessionInboxAddress,-} from "#execution/wire/session-inbox-contract.js";+} from "#execution/session-inbox/address.js";import { SESSION_CALLBACK_CONTEXT_KEY_NAME } from "#context/key-names.js";import type { InstrumentationChannelDeliveryRef } from "#instrumentation/lifecycle.js";import type { UserModelMessage } from "#harness/messages.js";@@ -78,6 +78,10 @@ export const SessionIdKey = new ContextKey<string>("eve.sessionId");export const ConversationIdKey = new ContextKey<string>("eve.conversationId");export const SessionInboxKey = new ContextKey<SessionInboxAddress>(SESSION_INBOX_CONTEXT_KEY);export const ContinuationTokenKey = new ContextKey<string>("eve.continuationToken");+/** Every channel continuation address requested for this session, in claim order. */+export const ContinuationHookTokensKey = new ContextKey<readonly string[]>(+ "eve.continuationHookTokens",+);export const ChannelRequestIdKey = new ContextKey<string>("eve.channelRequestId");/** Parent-verified local client provenance, valid only for the current dev host secret. */export interface LocalDevRequestProvenance {diff --git a/packages/eve/src/eve-channel/index.ts b/packages/eve/src/eve-channel/index.tsindex 1f84eea76..dd0baa308 100644--- a/packages/eve/src/eve-channel/index.ts+++ b/packages/eve/src/eve-channel/index.ts@@ -1,10 +1,9 @@+import { handleExpiredLegacyAuthorization } from "#execution/legacy-session/authorization.js";+import { EVE_ROUTE_PREFIX } from "#protocol/routes.js";import type { SessionAuthContext, SessionParent, SessionTraceContext } from "#channel/types.js";import type { Session } from "#channel/session.js";import { resolveForwardedPrincipal } from "#channel/forwarded-principal.js";-import {- handleConnectionCallbackRequest,- handleLegacyConnectionCallbackRequest,-} from "#execution/connections/callback-route.js";+import { handleConnectionCallbackRequest } from "#execution/connections/callback-route.js";import { handleActivityRequest } from "#execution/activity-route.js";import { handleSessionCallbackRequest } from "#subagents/callback-route.js";import { handleTaskInputResponseRequest } from "#execution/task-input-response-route.js";@@ -31,7 +30,6 @@ import {EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,EVE_HEALTH_ROUTE_PATH,EVE_INFO_ROUTE_PATH,- EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN,EVE_SESSION_ROUTE_PATH,EVE_SESSION_CANCEL_ROUTE_PATTERN,EVE_SESSION_CLEAR_ROUTE_PATTERN,@@ -128,10 +126,16 @@ export function eveChannel(input: EveChannelInput): EveChannel {return await respond();}),+ GET(+ `${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`,+ handleExpiredLegacyAuthorization,+ ),+ POST(+ `${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`,+ handleExpiredLegacyAuthorization,+ ),GET(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN, handleConnectionCallbackRequest),POST(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN, handleConnectionCallbackRequest),- GET(EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN, handleLegacyConnectionCallbackRequest),- POST(EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN, handleLegacyConnectionCallbackRequest),POST(EVE_ACTIVITY_ROUTE_PATTERN, handleActivityRequest),POST(EVE_CALLBACK_ROUTE_PATTERN, handleSessionCallbackRequest),POST(EVE_TASK_INPUT_ROUTE_PATTERN, handleTaskInputResponseRequest),diff --git a/packages/eve/src/execution/accepted-delivery-deployment.ts b/packages/eve/src/execution/accepted-delivery-deployment.tsdeleted file mode 100644index a21085ac3..000000000--- a/packages/eve/src/execution/accepted-delivery-deployment.ts+++ /dev/null@@ -1,31 +0,0 @@-import type { HookPayload } from "#channel/types.js";-import type { TurnStepInput } from "#execution/durable-session-migrations/turn-workflow.js";-import type { DurableStepResult } from "#execution/next-driver-action.js";--/** Returns one trusted accepting deployment only when every delivery agrees. */-export function readAcceptedDeploymentId(input: HookPayload): string | undefined {- if (input.kind !== "deliver" || input.deliveryMetadata?.length === 0) return undefined;- const acceptedDeploymentId = input.deliveryMetadata?.[0]?.acceptedDeploymentId;- if (acceptedDeploymentId === undefined || acceptedDeploymentId.length === 0) return undefined;- return input.deliveryMetadata?.every(- (metadata) => metadata.acceptedDeploymentId === acceptedDeploymentId,- )- ? acceptedDeploymentId- : undefined;-}--/** Defers a speculative inline step before mutation when it reached another deployment. */-export function deferMismatchedInlineTurnStep(input: TurnStepInput): DurableStepResult | undefined {- if (- input.acceptedDeploymentId === undefined ||- process.env.VERCEL_DEPLOYMENT_ID?.trim() === input.acceptedDeploymentId- ) {- return undefined;- }- return {- action: "continue",- requiresChildDispatch: true,- serializedContext: input.serializedContext,- sessionState: input.sessionState,- };-}diff --git a/packages/eve/src/execution/activity-cohort.test.ts b/packages/eve/src/execution/activity-cohort.test.tsindex 08d81ed23..f6d01f5d4 100644--- a/packages/eve/src/execution/activity-cohort.test.ts+++ b/packages/eve/src/execution/activity-cohort.test.ts@@ -6,12 +6,13 @@ import { restoreAuthorizationActivity } from "#execution/activity-cohort.js";import { matchAuthorizationCallbacks } from "#execution/authorization-callback-match.js";describe("restoreAuthorizationActivity", () => {- it("restores candidate authorization activity by candidate ID", () => {+ it("restores authorization activity by attempt ID", () => {const ctx = new ContextContainer();const pending = {- activityRootTurnIds: { "candidate-1": "turn-origin" },+ activityRootTurnIds: { "attempt-1": "turn-origin" },challenges: [{+ attemptId: "attempt-1",candidateId: "candidate-1",challenge: { url: "https://auth.example.com" },hookUrl: "https://app.example.com/callback",@@ -23,6 +24,7 @@ describe("restoreAuthorizationActivity", () => {const { matches } = matchAuthorizationCallbacks(pending, [{authorizationCallback: {+ attemptId: "attempt-1",callback: { params: { code: "callback-code" } },connectionName: "github",},@@ -31,7 +33,7 @@ describe("restoreAuthorizationActivity", () => {const ids = restoreAuthorizationActivity({ ctx, matches, pending });- expect(ids).toEqual(["candidate-1"]);+ expect(ids).toEqual(["attempt-1"]);expect(ctx.get(ActivityRootTurnIdKey)).toBe("turn-origin");expect(ctx.get(ActivityPendingBlockersKey)).toBeUndefined();});diff --git a/packages/eve/src/execution/activity-cohort.ts b/packages/eve/src/execution/activity-cohort.tsindex 0dd82aad8..814f4e1fd 100644--- a/packages/eve/src/execution/activity-cohort.ts+++ b/packages/eve/src/execution/activity-cohort.ts@@ -56,9 +56,7 @@ export function restoreAuthorizationActivity(input: {readonly matches: readonly MatchedAuthorizationCallback[];readonly pending: PendingAuthorizationState;}): readonly string[] {- const ids = input.matches.map(- (match) => match.result.attemptId ?? match.candidateId ?? match.result.name,- );+ const ids = input.matches.map((match) => match.result.attemptId);const rootTurnId = ids.map((id) => input.pending.activityRootTurnIds?.[id]).find(Boolean);if (rootTurnId !== undefined) {input.ctx.set(ActivityRootTurnIdKey, rootTurnId);diff --git a/packages/eve/src/execution/authorization-callback-match.test.ts b/packages/eve/src/execution/authorization-callback-match.test.tsindex 3f809ec60..20766cb3e 100644--- a/packages/eve/src/execution/authorization-callback-match.test.ts+++ b/packages/eve/src/execution/authorization-callback-match.test.ts@@ -3,6 +3,59 @@ import { matchAuthorizationCallbacks } from "#execution/authorization-callback-mimport type { PendingAuthorizationState } from "#harness/authorization.js";describe("matchAuthorizationCallbacks", () => {+ it.each([undefined, "another-attempt"])("ignores an unmatched attempt %s", (attemptId) => {+ const result = matchAuthorizationCallbacks(+ {+ challenges: [+ {+ attemptId: "attempt-1",+ name: "crm",+ hookUrl: "https://app.example/callback",+ challenge: {},+ principal: { type: "app" },+ },+ ],+ },+ [+ {+ authorizationCallback: {+ attemptId,+ connectionName: "crm",+ callback: { params: {} },+ },+ },+ ],+ );+ expect(result.matches).toEqual([]);+ });++ it("consumes one callback per attempt and preserves unrelated delivery", () => {+ const callback = {+ authorizationCallback: {+ attemptId: "attempt-1",+ connectionName: "crm",+ callback: { params: {} },+ },+ };+ const message = { message: "Continue after signing in" };+ const result = matchAuthorizationCallbacks(+ {+ challenges: [+ {+ attemptId: "attempt-1",+ name: "crm",+ hookUrl: "https://app.example/callback",+ challenge: {},+ principal: { type: "app" },+ },+ ],+ },+ [callback, message, callback],+ );+ expect(result.matches).toHaveLength(1);+ expect(result.remainingPayloads).toEqual([message]);+ });+it("carries the resolved connection instance into the callback result", () => {const pending: PendingAuthorizationState = {challenges: [diff --git a/packages/eve/src/execution/authorization-callback-match.ts b/packages/eve/src/execution/authorization-callback-match.tsindex 6f7a37469..a9c51a0ae 100644--- a/packages/eve/src/execution/authorization-callback-match.ts+++ b/packages/eve/src/execution/authorization-callback-match.ts@@ -6,10 +6,10 @@ import type { AuthorizationCallback } from "#shared/connection-types.js";export interface MatchedAuthorizationCallback {readonly authorization: ConnectionAuthorizationChallenge;readonly candidateId?: string;- readonly result: { readonly name: string } & AuthorizationResult;+ readonly result: { readonly name: string; readonly attemptId: string } & AuthorizationResult;}-/** Matches current callbacks by attempt ID and legacy callbacks only to legacy state. */+/** Matches each callback to exactly one pending authorization attempt. */export function matchAuthorizationCallbacks(pending: PendingAuthorizationState,payloads: readonly DeliverPayload[],@@ -27,7 +27,6 @@ export function matchAuthorizationCallbacks(attemptId?: string;callback: AuthorizationCallback;connectionName: string;- legacy?: true;}| undefined;if (callback === undefined) {@@ -37,15 +36,13 @@ export function matchAuthorizationCallbacks(const challenge = pending.challenges.find((candidate) => {if (candidate.name !== callback.connectionName) return false;- return callback.legacy === true- ? candidate.attemptId === undefined- : candidate.attemptId === callback.attemptId;+ return typeof callback.attemptId === "string" && candidate.attemptId === callback.attemptId;});- const attemptKey = challenge?.attemptId ?? challenge?.candidateId ?? challenge?.name;+ const attemptKey = challenge?.attemptId;if (challenge === undefined ||attemptKey === undefined ||- (challenge.principal === undefined && callback.legacy !== true) ||+ challenge.principal === undefined ||matchedAttemptKeys.has(attemptKey)) {continue;@@ -56,7 +53,7 @@ export function matchAuthorizationCallbacks(authorization: challenge.challenge,candidateId: challenge.candidateId,result: {- attemptId: challenge.attemptId,+ attemptId: attemptKey,callback: callback.callback,hookUrl: challenge.hookUrl,instanceId: challenge.instanceId,diff --git a/packages/eve/src/execution/cancel-descendant-turns-step.ts b/packages/eve/src/execution/cancel-descendant-turns-step.tsindex 95586027b..351907143 100644--- a/packages/eve/src/execution/cancel-descendant-turns-step.ts+++ b/packages/eve/src/execution/cancel-descendant-turns-step.ts@@ -39,7 +39,7 @@ export async function cancelDescendantTurnsStep(input: {let running: readonly RunningAgentHandle[];let workflowToolRuns: readonly WorkflowToolRunRecord[];try {- const session = await readDurableSession(input.sessionState);+ const session = readDurableSession(input.sessionState);workflowToolRuns = getWorkflowToolRuns(session.state);const workflowOwnerIds = new Set(workflowToolRuns.map((run) => run.runId));running = (getAgentHandleStore(session.state)?.handles ?? []).filter(diff --git a/packages/eve/src/execution/cancel-indexed-session-tasks-step.test.ts b/packages/eve/src/execution/cancel-indexed-session-tasks-step.test.tsindex 55ec1a691..e7f4fb418 100644--- a/packages/eve/src/execution/cancel-indexed-session-tasks-step.test.ts+++ b/packages/eve/src/execution/cancel-indexed-session-tasks-step.test.ts@@ -87,7 +87,6 @@ function makeSessionState(tasks: readonly SessionTaskIndexEntry[]): DurableSessisessionId: "parent-session",state: { [SESSION_TASKS_STATE_KEY]: { tasks, version: 2 } },},- version: 1,},version: 1,};diff --git a/packages/eve/src/execution/cancel-indexed-session-tasks-step.ts b/packages/eve/src/execution/cancel-indexed-session-tasks-step.tsindex eba709863..fa5b492e7 100644--- a/packages/eve/src/execution/cancel-indexed-session-tasks-step.ts+++ b/packages/eve/src/execution/cancel-indexed-session-tasks-step.ts@@ -19,7 +19,7 @@ export async function cancelAllIndexedSessionTasksStep(input: {let durable;try {- durable = await readDurableSession(input.sessionState);+ durable = readDurableSession(input.sessionState);} catch (error) {logError(log, "failed to read the session for indexed task cancellation", error, {parentSessionId: input.sessionState.sessionId,diff --git a/packages/eve/src/execution/cancelled-model-call-batch.ts b/packages/eve/src/execution/cancelled-model-call-batch.tsindex 07c612207..dfed51418 100644--- a/packages/eve/src/execution/cancelled-model-call-batch.ts+++ b/packages/eve/src/execution/cancelled-model-call-batch.ts@@ -4,7 +4,7 @@ import { preserveSerializedSessionDynamicModelSelection } from "#context/serialiimport { serializeContext } from "#context/serialize.js";import { preserveCancelledTurnMessage } from "#execution/cancelled-turn-message.js";import { createDurableSessionState } from "#execution/durable-session-store.js";-import type { DurableStepResult } from "#execution/next-driver-action.js";+import type { DurableStepResult } from "#execution/session/turn-step-types.js";import { readRetainedBackgroundToolResult } from "#execution/tasks/parent/tool-execution.js";import type { HarnessSession, StepInput, StepResult } from "#harness/types.js";import { preserveSerializedInstrumentationState } from "#instrumentation/state.js";diff --git a/packages/eve/src/execution/connections/callback-route.ts b/packages/eve/src/execution/connections/callback-route.tsindex c688ded5e..8aa912b70 100644--- a/packages/eve/src/execution/connections/callback-route.ts+++ b/packages/eve/src/execution/connections/callback-route.ts@@ -1,3 +1,4 @@+import { resumeAuthorizationCallback } from "#execution/legacy-session/authorization.js";/*** Framework-shipped callback route used by in-turn interactive* connection authorization.@@ -22,40 +23,14 @@* internet.*/-import { resumeHook } from "#internal/workflow/runtime.js";import type { RouteContext } from "#public/definitions/channel.js";import { buildAuthorizationCompletePage } from "#runtime/connections/authorization-complete-page.js";import type { AuthorizationCallback } from "#shared/connection-types.js";-/**- * Logical name prefix of the framework-shipped connection callback- * channel. The trailing method segment (`get` or `post`) keeps each- * `(method, urlPath)` pair distinct in the channel registry.- */--/**- * Inbound handler for the connection callback route. Exported for test- * coverage; the framework channel resolver wires it into Nitro via- * {@link getConnectionCallbackChannelDefinitions}.- */+/** Resumes the exact authorization attempt through the session inbox. */export async function handleConnectionCallbackRequest(request: Request,ctx: RouteContext,-): Promise<Response> {- return handleCallbackRequest(request, ctx, false);-}--export async function handleLegacyConnectionCallbackRequest(- request: Request,- ctx: RouteContext,-): Promise<Response> {- return handleCallbackRequest(request, ctx, true);-}--async function handleCallbackRequest(- request: Request,- ctx: RouteContext,- legacy: boolean,): Promise<Response> {const name = ctx.params.name;const attemptId = ctx.params.attemptId;@@ -66,7 +41,7 @@ async function handleCallbackRequest(if (typeof token !== "string" || token.length === 0) {return Response.json({ error: "Missing callback token.", ok: false }, { status: 400 });}- if (!legacy && (typeof attemptId !== "string" || attemptId.length === 0)) {+ if (typeof attemptId !== "string" || attemptId.length === 0) {return Response.json({ error: "Missing authorization attempt ID.", ok: false },{ status: 400 },@@ -75,16 +50,10 @@ async function handleCallbackRequest(const callback = await projectAuthorizationCallback(request);- // Deliver the callback through the per-session auth hook token- // embedded in the URL by getHookUrl(). The workflow body creates- // this hook upfront (before any turns run) so it always exists- // when the callback arrives.try {- const authorizationCallback = legacy- ? { callback, connectionName: name, legacy: true as const }- : { attemptId: attemptId!, callback, connectionName: name };- await resumeHook(token, {- kind: "deliver" as const,+ const authorizationCallback = { attemptId, callback, connectionName: name };+ await resumeAuthorizationCallback(token, {+ kind: "authorization-callback" as const,payloads: [{ authorizationCallback }],});} catch {diff --git a/packages/eve/src/execution/continuation-conflict-step.test.ts b/packages/eve/src/execution/continuation-conflict-step.test.tsindex 1b64fc119..ef6c6a23b 100644--- a/packages/eve/src/execution/continuation-conflict-step.test.ts+++ b/packages/eve/src/execution/continuation-conflict-step.test.ts@@ -2,21 +2,18 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";import { settleContinuationConflictStep } from "#execution/continuation-conflict-step.js";-import { sessionCommandHookToken } from "#execution/session-command-token.js";const cancelRunMock = vi.fn();-const getRawHookByTokenMock = vi.fn();const getWorldMock = vi.fn();-const world = { hooks: { getByToken: getRawHookByTokenMock } };+const world = {};const resumeSessionInboxMock = vi.fn();-vi.mock("#execution/wire/session-inbox-resume.js", () => ({+vi.mock("#execution/session-inbox/resume.js", () => ({resumeSessionInbox: (...args: unknown[]) => resumeSessionInboxMock(...args),}));vi.mock("#internal/workflow/runtime.js", () => ({cancelRun: (...args: unknown[]) => cancelRunMock(...args),- getRawHookByToken: (...args: unknown[]) => getRawHookByTokenMock(...args),getWorld: (...args: unknown[]) => getWorldMock(...args),}));@@ -40,7 +37,6 @@ describe("settleContinuationConflictStep", () => {activityCollectorRunId: "wrun_collector",command,continuationToken: "slack:C1:T1",- ownerSessionId: "wrun_owner",});expect(resumeSessionInboxMock).toHaveBeenCalledWith("slack:C1:T1", command);@@ -49,56 +45,17 @@ describe("settleContinuationConflictStep", () => {});});- it("falls back to the winner's stable inbox after the alias is re-keyed", async () => {- resumeSessionInboxMock- .mockRejectedValueOnce(new HookNotFoundError("slack:C1:T1"))- .mockResolvedValueOnce({ runId: "wrun_owner" });-- await settleContinuationConflictStep({- command,- continuationToken: "slack:C1:T1",- ownerSessionId: "wrun_owner",- });-- expect(resumeSessionInboxMock).toHaveBeenNthCalledWith(1, "slack:C1:T1", command);- expect(resumeSessionInboxMock).toHaveBeenNthCalledWith(- 2,- sessionCommandHookToken("wrun_owner"),- command,- );- });-- it("resolves a legacy conflict's owner once before using its stable inbox", async () => {- resumeSessionInboxMock- .mockRejectedValueOnce(new HookNotFoundError("slack:C1:T1"))- .mockResolvedValueOnce({ runId: "wrun_owner" });- getRawHookByTokenMock.mockResolvedValue({ runId: "wrun_owner" });-- await settleContinuationConflictStep({- command,- continuationToken: "slack:C1:T1",- });-- expect(getRawHookByTokenMock).toHaveBeenCalledOnce();- expect(getRawHookByTokenMock).toHaveBeenCalledWith("slack:C1:T1");- expect(resumeSessionInboxMock).toHaveBeenNthCalledWith(- 2,- sessionCommandHookToken("wrun_owner"),- command,- );- });-- it("identifies a legacy delivery whose owner can no longer be resolved", async () => {- resumeSessionInboxMock.mockRejectedValue(new HookNotFoundError("slack:C1:T1"));- getRawHookByTokenMock.mockRejectedValue(new HookNotFoundError("slack:C1:T1"));-+ it("surfaces a vanished alias and still retires the losing collector", async () => {+ const error = new HookNotFoundError("slack:C1:T1");+ resumeSessionInboxMock.mockRejectedValue(error);await expect(settleContinuationConflictStep({+ activityCollectorRunId: "wrun_collector",command,continuationToken: "slack:C1:T1",}),- ).rejects.toThrow(- 'Unable to forward losing candidate delivery "request-1": continuation owner could not be resolved.',- );+ ).rejects.toBe(error);+ expect(resumeSessionInboxMock).toHaveBeenCalledExactlyOnceWith("slack:C1:T1", command);+ expect(cancelRunMock).toHaveBeenCalledOnce();});});diff --git a/packages/eve/src/execution/continuation-conflict-step.ts b/packages/eve/src/execution/continuation-conflict-step.tsindex 408fe3a00..05f6062a3 100644--- a/packages/eve/src/execution/continuation-conflict-step.ts+++ b/packages/eve/src/execution/continuation-conflict-step.ts@@ -1,14 +1,12 @@import {EntityConflictError,- HookNotFoundError,RunExpiredError,WorkflowRunNotFoundError,} from "#compiled/@workflow/errors/index.js";import type { SessionCommand } from "#channel/types.js";-import { sessionCommandHookToken } from "#execution/session-command-token.js";-import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";-import { cancelRun, getRawHookByToken, getWorld } from "#internal/workflow/runtime.js";+import { resumeSessionInbox } from "#execution/session-inbox/resume.js";+import { cancelRun, getWorld } from "#internal/workflow/runtime.js";import { walkCauseChain } from "#shared/errors.js";/** Settles side effects owned by a session candidate that lost its continuation claim. */@@ -16,17 +14,12 @@ export async function settleContinuationConflictStep(input: {readonly activityCollectorRunId?: string;readonly command?: Extract<SessionCommand, { readonly kind: "send" }>;readonly continuationToken: string;- readonly ownerSessionId?: string;}): Promise<void> {"use step";try {if (input.command !== undefined) {- await forwardCommand({- command: input.command,- continuationToken: input.continuationToken,- ownerSessionId: input.ownerSessionId,- });+ await resumeSessionInbox(input.continuationToken, input.command);}} finally {if (input.activityCollectorRunId !== undefined) {@@ -35,41 +28,6 @@ export async function settleContinuationConflictStep(input: {}}-async function forwardCommand(input: {- readonly command: Extract<SessionCommand, { readonly kind: "send" }>;- readonly continuationToken: string;- readonly ownerSessionId?: string;-}): Promise<void> {- try {- await resumeSessionInbox(input.continuationToken, input.command);- } catch (error) {- if (!HookNotFoundError.is(error)) throw error;- const ownerSessionId = await resolveOwnerSessionId(input);- await resumeSessionInbox(sessionCommandHookToken(ownerSessionId), input.command);- }-}--async function resolveOwnerSessionId(input: {- readonly command: Extract<SessionCommand, { readonly kind: "send" }>;- readonly continuationToken: string;- readonly ownerSessionId?: string;-}): Promise<string> {- if (input.ownerSessionId !== undefined) return input.ownerSessionId;-- try {- const hook = await getRawHookByToken(input.continuationToken);- if (typeof hook.runId === "string" && hook.runId.length > 0) return hook.runId;- } catch (error) {- if (!HookNotFoundError.is(error)) throw error;- }-- const delivery =- input.command.requestId === undefined ? "" : ` ${JSON.stringify(input.command.requestId)}`;- throw new Error(- `Unable to forward losing candidate delivery${delivery}: continuation owner could not be resolved.`,- );-}-async function cancelCollector(runId: string): Promise<void> {try {await cancelRun(await getWorld(), runId, {diff --git a/packages/eve/src/execution/coordination-dispatch-shared.ts b/packages/eve/src/execution/coordination-dispatch-shared.tsindex d1e43e8fa..4f86e707d 100644--- a/packages/eve/src/execution/coordination-dispatch-shared.ts+++ b/packages/eve/src/execution/coordination-dispatch-shared.ts@@ -58,7 +58,7 @@ export type DispatchPlanEntry =export interface CoordinationDispatchInput {readonly callbackBaseUrl?: string;readonly workflowToolRunOwner: WorkflowToolRunOwner;- readonly parentWritable: WritableStream<Uint8Array>;+ readonly sessionWritable: WritableStream<Uint8Array>;readonly serializedContext: Record<string, unknown>;readonly sessionState: DurableSessionState;}@@ -113,7 +113,7 @@ export async function prepareCoordinationDispatch(input: {readonly serializedContext: Record<string, unknown>;readonly sessionState: DurableSessionState;}): Promise<PreparedCoordinationDispatch | undefined> {- const durableSession = await readDurableSession(input.sessionState);+ const durableSession = readDurableSession(input.sessionState);const pending = getPendingCoordinationBatch(durableSession.state);if (pending === undefined) return undefined;diff --git a/packages/eve/src/execution/create-session-step.test.ts b/packages/eve/src/execution/create-session-step.test.tsindex 766d33a96..8e895a78f 100644--- a/packages/eve/src/execution/create-session-step.test.ts+++ b/packages/eve/src/execution/create-session-step.test.ts@@ -33,10 +33,10 @@ describe("createSessionStep", () => {taskId: "task-1",});- expect(state.snapshot?.session.agent.system).not.toContain("Background task updates");- expect(state.snapshot?.session.agent.system).not.toContain("task_update");- expect(state.snapshot?.session.taskId).toBe("task-1");- expect(state.snapshot?.session.state).toBeUndefined();+ expect(state.snapshot.session.agent.system).not.toContain("Background task updates");+ expect(state.snapshot.session.agent.system).not.toContain("task_update");+ expect(state.snapshot.session.taskId).toBe("task-1");+ expect(state.snapshot.session.state).toBeUndefined();});it("defaults root sessions to the root input token budget", async () => {@@ -53,7 +53,7 @@ describe("createSessionStep", () => {sessionId: "sess-root",});- expect(state.snapshot?.session.limits?.maxInputTokensPerSession).toBe(+ expect(state.snapshot.session.limits?.maxInputTokensPerSession).toBe(DEFAULT_ROOT_MAX_INPUT_TOKENS_PER_SESSION,);});@@ -74,7 +74,7 @@ describe("createSessionStep", () => {sessionId: "sess-child",});- expect(state.snapshot?.session.limits).toEqual({+ expect(state.snapshot.session.limits).toEqual({maxInputTokensPerSession: 3_000_000,});});@@ -95,7 +95,7 @@ describe("createSessionStep", () => {sessionId: "sess-child",});- expect(state.snapshot?.session.limits).toEqual({});+ expect(state.snapshot.session.limits).toEqual({});});it("caps configured child token limits at the inherited token budget", async () => {@@ -116,7 +116,7 @@ describe("createSessionStep", () => {sessionId: "sess-child",});- expect(state.snapshot?.session.limits?.maxInputTokensPerSession).toBe(2_000_000);+ expect(state.snapshot.session.limits?.maxInputTokensPerSession).toBe(2_000_000);});it("caps a configured child token-cost limit at the inherited budget", async () => {@@ -135,7 +135,7 @@ describe("createSessionStep", () => {sessionId: "sess-child",});- expect(state.snapshot?.session.limits?.maxTokenCostUsdPerSession).toBe(0.75);+ expect(state.snapshot.session.limits?.maxTokenCostUsdPerSession).toBe(0.75);});it("keeps tighter configured child token limits under inherited token budget", async () => {@@ -156,7 +156,7 @@ describe("createSessionStep", () => {sessionId: "sess-child",});- expect(state.snapshot?.session.limits?.maxInputTokensPerSession).toBe(1_000_000);+ expect(state.snapshot.session.limits?.maxInputTokensPerSession).toBe(1_000_000);});it("still applies inherited token budget when configured child limit is false", async () => {@@ -177,7 +177,7 @@ describe("createSessionStep", () => {sessionId: "sess-child",});- expect(state.snapshot?.session.limits?.maxInputTokensPerSession).toBe(500_000);+ expect(state.snapshot.session.limits?.maxInputTokensPerSession).toBe(500_000);});it("seeds session token limits from resolved agent config", async () => {@@ -200,7 +200,7 @@ describe("createSessionStep", () => {sessionId: "sess-root",});- expect(state.snapshot?.session.limits).toMatchObject({+ expect(state.snapshot.session.limits).toMatchObject({maxInputTokensPerSession: 200_000,maxOutputTokensPerSession: 20_000,maxTokenCostUsdPerSession: 1.5,diff --git a/packages/eve/src/execution/create-session-step.ts b/packages/eve/src/execution/create-session-step.tsindex e4d7c187e..2a7472c7b 100644--- a/packages/eve/src/execution/create-session-step.ts+++ b/packages/eve/src/execution/create-session-step.ts@@ -17,7 +17,7 @@ import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agen/*** Result returned by {@link createSessionStep}.*- * Exposes the projected {@link DurableSessionState} the driver needs to+ * Exposes the projected {@link DurableSessionState} the owner needs to* drive the turn loop.*/export interface CreateSessionStepResult {diff --git a/packages/eve/src/execution/dispatch-turn-step.ts b/packages/eve/src/execution/dispatch-turn-step.tsdeleted file mode 100644index d970a5207..000000000--- a/packages/eve/src/execution/dispatch-turn-step.ts+++ /dev/null@@ -1,38 +0,0 @@-import {- createTurnWorkflowInput,- type TurnWorkflowDispatchInput,-} from "#execution/durable-session-migrations/turn-workflow.js";-import { readAcceptedDeploymentId } from "#execution/accepted-delivery-deployment.js";-import { buildTurnAttributes, readRootSessionId } from "#execution/eve-workflow-attributes.js";-import {- startWorkflowOnAcceptedDeployment,- turnWorkflowReference,-} from "#execution/workflow-runtime.js";-import { normalizeEveAttributes } from "#runtime/attributes/normalize.js";--/** Starts a per-turn child workflow for the current driver session. */-export async function dispatchTurnStep(- input: TurnWorkflowDispatchInput,-): Promise<{ readonly runId: string }> {- "use step";-- const run = await startWorkflowOnAcceptedDeployment(- turnWorkflowReference,- [createTurnWorkflowInput(input)],- readAcceptedDeploymentId(input.delivery),- {- allowReservedAttributes: true,- experimental_retention: input.retention,- attributes: normalizeEveAttributes(- buildTurnAttributes({- parentSessionId: input.sessionState.sessionId,- requestId: input.delivery.kind === "deliver" ? input.delivery.requestId : undefined,- rootSessionId: readRootSessionId(input.serializedContext) ?? input.sessionState.sessionId,- serializedContext: input.serializedContext,- }),- ),- },- );-- return { runId: run.runId };-}diff --git a/packages/eve/src/execution/durable-session-migrations/chain.test.ts b/packages/eve/src/execution/durable-session-migrations/chain.test.tsdeleted file mode 100644index 38adabbf7..000000000--- a/packages/eve/src/execution/durable-session-migrations/chain.test.ts+++ /dev/null@@ -1,234 +0,0 @@-import { describe, expect, it } from "vitest";--import { runMigrationChain, type VersionMigration } from "./chain.js";--/**- * Exercises the chain runner with synthetic versioned shapes. The- * snapshot-specific wiring is covered in `snapshot.test.ts`.- */-describe("runMigrationChain", () => {- it("returns value unchanged when already at the target version", () => {- const value = { id: "abc", version: 1 as const };-- const result = runMigrationChain<{ readonly version: 1; readonly id: string }>({- label: "test shape",- migrations: [],- targetVersion: 1,- value,- });-- expect(result).toBe(value);- });-- it("walks a value through every registered migration in order", () => {- interface V1 {- readonly version: 1;- readonly name: string;- }- interface V2 {- readonly version: 2;- readonly name: string;- readonly count: number;- }- interface V3 {- readonly version: 3;- readonly id: string;- readonly count: number;- }-- const migrations: VersionMigration[] = [- {- from: 1,- migrate: (prior) => {- const v1 = prior as V1;- return { count: 0, name: v1.name, version: 2 } satisfies V2;- },- to: 2,- },- {- from: 2,- migrate: (prior) => {- const v2 = prior as V2;- return { count: v2.count, id: v2.name, version: 3 } satisfies V3;- },- to: 3,- },- ];-- const result = runMigrationChain<V3>({- label: "test shape",- migrations,- targetVersion: 3,- value: { name: "alpha", version: 1 } satisfies V1,- });-- expect(result).toEqual({ count: 0, id: "alpha", version: 3 });- });-- it("applies only the migrations between the current and target versions", () => {- const applied: number[] = [];- const migrations: VersionMigration[] = [- {- from: 1,- migrate: (v) => {- applied.push(1);- return { ...(v as object), version: 2 };- },- to: 2,- },- {- from: 2,- migrate: (v) => {- applied.push(2);- return { ...(v as object), version: 3 };- },- to: 3,- },- {- from: 3,- migrate: (v) => {- applied.push(3);- return { ...(v as object), version: 4 };- },- to: 4,- },- ];-- runMigrationChain<{ readonly version: 3 }>({- label: "test shape",- migrations,- targetVersion: 3,- value: { version: 2 },- });-- expect(applied).toEqual([2]);- });-- it("throws when no migration is registered for an intermediate version", () => {- expect(() =>- runMigrationChain({- label: "test shape",- migrations: [- {- from: 2,- migrate: (v) => ({ ...(v as object), version: 3 }),- to: 3,- },- ],- targetVersion: 3,- value: { version: 1 },- }),- ).toThrow(/no migration registered for version 1 → 2/);- });-- it("throws when a migration produces the wrong target version", () => {- expect(() =>- runMigrationChain({- label: "test shape",- migrations: [- {- from: 1,- // Misbehaving migration: declares v2 but produces v3.- migrate: (v) => ({ ...(v as object), version: 3 }),- to: 2,- },- ],- targetVersion: 2,- value: { version: 1 },- }),- ).toThrow(/migration 1 → 2 produced a value with version 3/);- });-- it("throws when a migration declares more than one version step", () => {- expect(() =>- runMigrationChain({- label: "test shape",- migrations: [- {- from: 1,- migrate: (v) => ({ ...(v as object), version: 3 }),- to: 3,- },- ],- targetVersion: 3,- value: { version: 1 },- }),- ).toThrow(/migration 1 → 3 must step exactly one version at a time/);- });-- it("throws when the value version is newer than the target", () => {- expect(() =>- runMigrationChain({- label: "test shape",- migrations: [],- targetVersion: 1,- value: { version: 2 },- }),- ).toThrow(/version 2, which is newer than the supported version 1/);- });-- it("throws when the value has no numeric version field", () => {- expect(() =>- runMigrationChain({- label: "test shape",- migrations: [],- targetVersion: 1,- value: { name: "no version" },- }),- ).toThrow(/no numeric "version" field/);- });-- it("throws when the value version is not a positive integer", () => {- expect(() =>- runMigrationChain({- label: "test shape",- migrations: [],- targetVersion: 1,- value: { version: 0 },- }),- ).toThrow(/version 0 is not a positive integer/);- });-- it("throws when value is null", () => {- expect(() =>- runMigrationChain({- label: "test shape",- migrations: [],- targetVersion: 1,- value: null,- }),- ).toThrow(/no numeric "version" field/);- });-- it("reads a versionless value as initialVersion when provided", () => {- const migrations: VersionMigration[] = [- {- from: 0,- migrate: (v) => ({ ...(v as object), version: 1 }),- to: 1,- },- ];-- const result = runMigrationChain<{ readonly version: 1; readonly id: string }>({- initialVersion: 0,- label: "test shape",- migrations,- targetVersion: 1,- value: { id: "abc" },- });-- expect(result).toEqual({ id: "abc", version: 1 });- });-- it("rejects a present but non-numeric version even when initialVersion is set", () => {- expect(() =>- runMigrationChain({- initialVersion: 0,- label: "test shape",- migrations: [],- targetVersion: 1,- value: { version: "1" },- }),- ).toThrow(/no numeric "version" field/);- });-});diff --git a/packages/eve/src/execution/durable-session-migrations/chain.ts b/packages/eve/src/execution/durable-session-migrations/chain.tsdeleted file mode 100644index 9203be1ae..000000000--- a/packages/eve/src/execution/durable-session-migrations/chain.ts+++ /dev/null@@ -1,80 +0,0 @@-/**- * Generic version-walking migration framework for versioned durable- * wire shapes. Each migration steps a value one version forward; the- * runner chains them so a value written at any historic version can- * be read at the current one.- */--/**- * One migration step in a version chain. `to` MUST equal `from + 1`- * and `migrate` MUST stamp the returned value's `version` field with- * `to`; the runner verifies both.- */-export interface VersionMigration {- readonly from: number;- readonly to: number;- migrate: (prior: unknown) => { readonly version: number };-}--/**- * Walks `value` through `migrations` until its `version` matches- * `targetVersion`. Throws on missing migrations, malformed steps, or- * a value newer than the runner supports.- */-export function runMigrationChain<TOut extends { readonly version: number }>(input: {- readonly value: unknown;- readonly migrations: readonly VersionMigration[];- readonly targetVersion: number;- readonly label: string;- /**- * Version to read a wire value as when it carries no `version` field —- * for shapes that predate versioning ("version 0"). Omit to require an- * explicit numeric `version` (the default). A present but non-numeric- * `version` is always malformed, opt-in or not.- */- readonly initialVersion?: number;-}): TOut {- if (typeof input.value !== "object" || input.value === null) {- throw new Error(`${input.label}: value has no numeric "version" field.`);- }- const declaredVersion = (input.value as { readonly version?: unknown }).version;- let current: { readonly version: number };- if (typeof declaredVersion === "number") {- current = input.value as { readonly version: number };- } else if (!("version" in input.value) && input.initialVersion !== undefined) {- current = { ...input.value, version: input.initialVersion };- } else {- throw new Error(`${input.label}: value has no numeric "version" field.`);- }- const minVersion = input.initialVersion ?? 1;- if (!Number.isInteger(current.version) || current.version < minVersion) {- throw new Error(`${input.label}: version ${current.version} is not a positive integer.`);- }- if (current.version > input.targetVersion) {- throw new Error(- `${input.label}: encountered version ${current.version}, which is newer than the supported version ${input.targetVersion}. ` +- `This usually indicates the wire was written by a newer eve deployment than the one reading it.`,- );- }- while (current.version < input.targetVersion) {- const migration = input.migrations.find((m) => m.from === current.version);- if (!migration) {- throw new Error(- `${input.label}: no migration registered for version ${current.version} → ${current.version + 1}.`,- );- }- if (migration.to !== migration.from + 1) {- throw new Error(- `${input.label}: migration ${migration.from} → ${migration.to} must step exactly one version at a time.`,- );- }- const next = migration.migrate(current);- if (next.version !== migration.to) {- throw new Error(- `${input.label}: migration ${migration.from} → ${migration.to} produced a value with version ${next.version}.`,- );- }- current = next;- }- return current as TOut;-}diff --git a/packages/eve/src/execution/durable-session-migrations/snapshot.test.ts b/packages/eve/src/execution/durable-session-migrations/snapshot.test.tsdeleted file mode 100644index 51907be44..000000000--- a/packages/eve/src/execution/durable-session-migrations/snapshot.test.ts+++ /dev/null@@ -1,92 +0,0 @@-import { describe, expect, it } from "vitest";--import {- DURABLE_SESSION_VERSION,- type DurableSessionSnapshot,-} from "#execution/durable-session-store.js";-import { projectToDurableSession } from "#execution/session.js";-import type { HarnessSession } from "#harness/types.js";--import { migrateDurableSessionSnapshot } from "./snapshot.js";--/**- * Pins the no-op path and failure modes for the snapshot migrator.- * Generic chain behavior is covered in `chain.test.ts`.- */-describe("migrateDurableSessionSnapshot", () => {- it("returns a v1 snapshot unchanged", () => {- const snapshot: DurableSessionSnapshot = {- session: projectToDurableSession(buildSession()),- version: DURABLE_SESSION_VERSION,- };-- const migrated = migrateDurableSessionSnapshot(snapshot);-- expect(migrated).toEqual(snapshot);- expect(migrated.version).toBe(DURABLE_SESSION_VERSION);- });-- it("preserves unrecognized fields on the snapshot through the migrator", () => {- // Forward-compat: a newer deployment may append optional fields- // without bumping the version; the migrator passes them through.- const snapshotWithFutureField = {- futureField: { hint: "experimental" },- session: projectToDurableSession(buildSession()),- version: DURABLE_SESSION_VERSION,- };-- const migrated = migrateDurableSessionSnapshot(snapshotWithFutureField);-- expect((migrated as { futureField?: unknown }).futureField).toEqual({- hint: "experimental",- });- });-- it("throws clearly on a version newer than the supported one", () => {- expect(() =>- migrateDurableSessionSnapshot({- session: {},- version: 999,- }),- ).toThrow(/durable session snapshot: encountered version 999/);- });-- it("throws when the snapshot has no numeric version field", () => {- expect(() => migrateDurableSessionSnapshot({ session: {} })).toThrow(- /durable session snapshot: value has no numeric "version" field/,- );- });-- it("throws when no migration is registered for an older version", () => {- // Unreachable until `DURABLE_SESSION_VERSION` moves past 1.- // Guards the "bumped version but forgot a migration" failure mode.- if (DURABLE_SESSION_VERSION === 1) {- return;- }- expect(() =>- migrateDurableSessionSnapshot({- session: {},- version: 1,- }),- ).toThrow(/no migration registered for version 1 → 2/);- });-});--function buildSession(): HarnessSession {- return {- agent: {- modelReference: { id: "test-model", contextWindowTokens: 200_000 },- system: "test system",- tools: [],- },- compaction: {- lastKnownInputTokens: 0,- lastKnownPromptMessageCount: 0,- recentWindowSize: 10,- threshold: 180_000,- },- continuationToken: "http:test",- history: [],- sessionId: "wrun_test",- };-}diff --git a/packages/eve/src/execution/durable-session-migrations/snapshot.ts b/packages/eve/src/execution/durable-session-migrations/snapshot.tsdeleted file mode 100644index 7e7513779..000000000--- a/packages/eve/src/execution/durable-session-migrations/snapshot.ts+++ /dev/null@@ -1,54 +0,0 @@-/**- * Durable session snapshot migrations.- *- * ## Adding a new snapshot version- *- * When a shape change cannot be expressed as a purely additive field:- *- * 1. Bump `DURABLE_SESSION_VERSION` in `durable-session-store.ts`.- * 2. Update {@link DurableSessionSnapshot}, {@link DurableSession},- * `projectToDurableSession`, and `hydrateDurableSession`.- * 3. Add `snapshot-v{N}-to-v{N+1}.ts` exporting one- * {@link VersionMigration} (`from: N`, `to: N + 1`, pure- * function, stamps the new `version`).- * 4. Append the migration to {@link snapshotMigrations}.- * 5. Cover it in `snapshot.test.ts`.- */-import type { ModelMessage } from "ai";--import type { DurableSessionSnapshot } from "#execution/durable-session-store.js";-import { DURABLE_SESSION_VERSION } from "#execution/durable-session-store.js";-import { validateHarnessModelMessages } from "#harness/messages.js";--import { runMigrationChain, type VersionMigration } from "./chain.js";--/**- * Ordered list of registered snapshot migrations. Empty today since- * only v1 exists; new migrations append to the tail.- */-const snapshotMigrations: readonly VersionMigration[] = [];--/**- * Migrates a {@link DurableSessionSnapshot} up to- * {@link DURABLE_SESSION_VERSION}. Pure; safe to call inline.- */-export function migrateDurableSessionSnapshot(value: unknown): DurableSessionSnapshot {- const snapshot = runMigrationChain<DurableSessionSnapshot>({- label: "durable session snapshot",- migrations: snapshotMigrations,- targetVersion: DURABLE_SESSION_VERSION,- value,- });-- // Pre-0.54 history used user-role messages for both human and framework input.- // Keep v1 so a pinned older driver can still forward the updated snapshot.- const history = snapshot.session.history.map((message: ModelMessage) =>- message.role === "user" && !("kind" in message)- ? { ...message, kind: "legacy.unknown" as const }- : message,- );- return {- ...snapshot,- session: { ...snapshot.session, history: validateHarnessModelMessages(history) },- };-}diff --git a/packages/eve/src/execution/durable-session-migrations/turn-workflow-v0-to-v1.ts b/packages/eve/src/execution/durable-session-migrations/turn-workflow-v0-to-v1.tsdeleted file mode 100644index df6377631..000000000--- a/packages/eve/src/execution/durable-session-migrations/turn-workflow-v0-to-v1.ts+++ /dev/null@@ -1,40 +0,0 @@-/**- * Turn workflow input v0 → v1 migration.- *- * Before versioning, the driver wrote a flat, unversioned run input;- * `runMigrationChain` reads that as version 0 (via its `initialVersion`- * option) and this lifts the flat shape into the nested v1 input. The- * reshape is inlined rather than delegating to `createTurnWorkflowInput`,- * so the historical transform stays frozen as the live dispatch- * constructor evolves.- */-import type { VersionMigration } from "./chain.js";-import type { TurnWorkflowDispatchInput, TurnWorkflowInput } from "./turn-workflow.js";--export const turnWorkflowInputV0ToV1: VersionMigration = {- from: 0,- migrate(prior: unknown): TurnWorkflowInput {- if (!isPreVersionTurnWorkflowInput(prior)) {- throw new Error(- "turn workflow input: version 0 value is not a recognized pre-version shape.",- );- }- return {- capabilities: prior.capabilities,- completionToken: prior.completionToken,- mode: prior.mode,- stepInput: {- input: prior.delivery,- parentWritable: prior.parentWritable,- serializedContext: prior.serializedContext,- sessionState: prior.sessionState,- },- version: 1,- };- },- to: 1,-};--function isPreVersionTurnWorkflowInput(value: unknown): value is TurnWorkflowDispatchInput {- return typeof value === "object" && value !== null && "delivery" in value;-}diff --git a/packages/eve/src/execution/durable-session-migrations/turn-workflow-v1-to-v2.ts b/packages/eve/src/execution/durable-session-migrations/turn-workflow-v1-to-v2.tsdeleted file mode 100644index e7a89c3b4..000000000--- a/packages/eve/src/execution/durable-session-migrations/turn-workflow-v1-to-v2.ts+++ /dev/null@@ -1,9 +0,0 @@-import type { VersionMigration } from "./chain.js";--export const turnWorkflowInputV1ToV2: VersionMigration = {- from: 1,- migrate(prior) {- return { ...(prior as Record<string, unknown>), version: 2 };- },- to: 2,-};diff --git a/packages/eve/src/execution/durable-session-migrations/turn-workflow.test.ts b/packages/eve/src/execution/durable-session-migrations/turn-workflow.test.tsdeleted file mode 100644index 7968a0ba7..000000000--- a/packages/eve/src/execution/durable-session-migrations/turn-workflow.test.ts+++ /dev/null@@ -1,192 +0,0 @@-import { describe, expect, it } from "vitest";--import type { HookPayload } from "#channel/types.js";-import {- DURABLE_SESSION_VERSION,- type DurableSessionState,-} from "#execution/durable-session-store.js";--import {- createTurnWorkflowInput,- migrateTurnWorkflowInput,- TURN_WORKFLOW_INPUT_VERSION,- type TurnWorkflowInput,-} from "./turn-workflow.js";--describe("turn workflow wire migrations", () => {- it("returns a current workflow input unchanged", () => {- const input = {- capabilities: undefined,- completionToken: "turn-token",- driverCapabilities: { turnInbox: true },- mode: "conversation",- stepInput: {- input: createDelivery(),- parentWritable: new WritableStream<Uint8Array>(),- serializedContext: { state: "current" },- sessionState: createSessionState(),- },- version: TURN_WORKFLOW_INPUT_VERSION,- } satisfies TurnWorkflowInput;-- expect(migrateTurnWorkflowInput(input)).toBe(input);- });-- it("creates versioned workflow input for new turn workflow starts", () => {- const delivery = createDelivery();- const parentWritable = new WritableStream<Uint8Array>();- const sessionState = createSessionState();-- expect(- createTurnWorkflowInput({- capabilities: undefined,- completionToken: "turn-token",- delivery,- mode: "conversation",- parentWritable,- serializedContext: { state: "driver" },- sessionState,- }),- ).toEqual({- capabilities: undefined,- completionToken: "turn-token",- driverCapabilities: { cancelledTurnSettle: true, turnInbox: true },- mode: "conversation",- stepInput: {- input: delivery,- parentWritable,- serializedContext: { state: "driver" },- sessionState,- },- version: TURN_WORKFLOW_INPUT_VERSION,- });- });-- it("migrates frozen v1 child inputs into the current continuation shape", () => {- const input = {- capabilities: undefined,- completionToken: "turn-token",- driverCapabilities: { cancelledTurnSettle: true as const, turnInbox: true as const },- mode: "conversation" as const,- stepInput: {- input: createDelivery(),- parentWritable: new WritableStream<Uint8Array>(),- serializedContext: { state: "v1" },- sessionState: createSessionState(),- },- version: 1 as const,- };-- expect(migrateTurnWorkflowInput(input)).toEqual({- ...input,- version: TURN_WORKFLOW_INPUT_VERSION,- });- });-- it("migrates pre-version (unversioned) workflow input into the current shape", () => {- const delivery = createDelivery();- const parentWritable = new WritableStream<Uint8Array>();- const sessionState = createSessionState({- continuationToken: "http:pre-version",- sessionId: "wrun_pre_version",- });-- expect(- migrateTurnWorkflowInput({- capabilities: undefined,- completionToken: "turn-token",- delivery,- mode: "conversation",- parentWritable,- serializedContext: { state: "pre-version" },- sessionState,- }),- ).toEqual({- capabilities: undefined,- completionToken: "turn-token",- mode: "conversation",- stepInput: {- input: delivery,- parentWritable,- serializedContext: { state: "pre-version" },- sessionState,- },- version: TURN_WORKFLOW_INPUT_VERSION,- });- });-- it("ignores legacy fields dropped from older flat shapes (e.g. sessionWritable)", () => {- const delivery = createDelivery();- const sessionState = createSessionState();-- const migrated = migrateTurnWorkflowInput({- capabilities: undefined,- completionToken: "turn-token",- delivery,- mode: "conversation",- parentWritable: new WritableStream<Uint8Array>(),- serializedContext: { state: "legacy" },- sessionState,- sessionWritable: new WritableStream(),- });-- expect(migrated.version).toBe(TURN_WORKFLOW_INPUT_VERSION);- expect("sessionWritable" in migrated).toBe(false);- expect("sessionWritable" in migrated.stepInput).toBe(false);- expect(migrated.stepInput.input).toBe(delivery);- });-- it("throws clearly on workflow input from a newer version", () => {- expect(() => migrateTurnWorkflowInput({ version: 999 })).toThrow(- /turn workflow input: encountered version 999/,- );- });-- it("rejects a versionless value that is not the pre-version shape", () => {- expect(() =>- migrateTurnWorkflowInput({- capabilities: undefined,- completionToken: "turn-token",- mode: "conversation",- stepInput: {- input: createDelivery(),- parentWritable: new WritableStream<Uint8Array>(),- serializedContext: { state: "missing-version" },- sessionState: createSessionState(),- },- }),- ).toThrow(/turn workflow input: version 0 value is not a recognized pre-version shape/);- });-- it("throws clearly on workflow input from malformed version", () => {- expect(() =>- migrateTurnWorkflowInput({- capabilities: undefined,- completionToken: "turn-token",- mode: "conversation",- stepInput: {- input: createDelivery(),- parentWritable: new WritableStream<Uint8Array>(),- serializedContext: { state: "malformed-version" },- sessionState: createSessionState(),- },- version: "1",- }),- ).toThrow(/turn workflow input: value has no numeric "version" field/);- });-});--function createDelivery(): HookPayload {- return { kind: "deliver", payloads: [{ message: "hello" }] };-}--function createSessionState(overrides: Partial<DurableSessionState> = {}): DurableSessionState {- return {- continuationToken: "http:test",- emissionState: { sequence: 0, sessionStarted: false, stepIndex: 0, turnId: "" },- hasProxyInputRequests: false,- sessionId: "wrun_test",- version: DURABLE_SESSION_VERSION,- ...overrides,- };-}diff --git a/packages/eve/src/execution/durable-session-migrations/turn-workflow.ts b/packages/eve/src/execution/durable-session-migrations/turn-workflow.tsdeleted file mode 100644index d9b41bce8..000000000--- a/packages/eve/src/execution/durable-session-migrations/turn-workflow.ts+++ /dev/null@@ -1,142 +0,0 @@-/**- * Turn workflow input migrations.- *- * The driver workflow can stay pinned while per-turn child workflows- * route to latest, so the child workflow run input is a durable wire- * shape newer code must read. Inputs written before- * {@link TURN_WORKFLOW_INPUT_VERSION} carry no `version`; the chain reads- * them as version 0 and the registered v0 → v1 migration lifts the flat- * shape into the current input, so a turn dispatched by an older- * deployment still runs after a rollout. Future shape changes bump- * {@link TURN_WORKFLOW_INPUT_VERSION} and append a v{N} → v{N+1} migration.- */-import type {- HookPayload,- RuntimeActionResultHookPayload,- SessionCapabilities,-} from "#channel/types.js";-import type { DurableSessionState } from "#execution/durable-session-store.js";-import type { RuntimeActionResult } from "#shared/action-types.js";-import type { AgentWorkflowRetentionDefinition } from "#shared/agent-definition.js";-import type { RunMode } from "#shared/run-mode.js";-import type { DurableStepResult } from "#execution/next-driver-action.js";-import type { TurnCancelPayload } from "#execution/turn-cancellation-token.js";--import { runMigrationChain, type VersionMigration } from "./chain.js";-import { turnWorkflowInputV0ToV1 } from "./turn-workflow-v0-to-v1.js";-import { turnWorkflowInputV1ToV2 } from "./turn-workflow-v1-to-v2.js";--export const TURN_WORKFLOW_INPUT_VERSION = 2;--/** Trusted runtime-action results collected by the parent turn driver. */-interface RuntimeActionResultStepInput {- readonly acceptedAtMsByCallId?: Readonly<Record<string, number>>;- readonly kind: "runtime-action-result";- readonly results: readonly RuntimeActionResult[];-}--export type TurnStepPayload =- | Exclude<HookPayload, RuntimeActionResultHookPayload>- | RuntimeActionResultStepInput;--export interface TurnStepInput {- /** Cancellation signal forwarded into the turn step. */- readonly abortSignal?: AbortSignal;- /** Executes only on this Vercel deployment; mismatches defer before mutation. */- readonly acceptedDeploymentId?: string;- readonly input: TurnStepPayload | undefined;- readonly parentWritable: WritableStream<Uint8Array>;- readonly serializedContext: Record<string, unknown>;- readonly sessionState: DurableSessionState;-}--interface TurnWorkflowInputBase {- readonly capabilities: SessionCapabilities | undefined;- readonly completionToken: string;- /**- * Additive driver feature negotiation. Older pinned drivers omit this,- * which keeps runtime-action orchestration on the legacy entry-owned path.- */- readonly driverCapabilities?: {- readonly turnInbox?: true;- readonly cancelledTurnSettle?: true;- };- readonly mode: RunMode;- readonly stepInput: TurnStepInput;-}--/** A step completed inline before the turn needed the shared turn runner. */-export interface InitialTurnStep {- readonly beforeStep: {- readonly serializedContext: Record<string, unknown>;- readonly sessionState: DurableSessionState;- };- readonly result: DurableStepResult;-}--export type TurnWorkflowInput = TurnWorkflowInputBase &- (- | {- readonly initialCancellation?: undefined;- readonly initialStep?: undefined;- readonly version: 1;- }- | {- readonly initialCancellation?: TurnCancelPayload;- readonly initialStep?: InitialTurnStep;- readonly version: typeof TURN_WORKFLOW_INPUT_VERSION;- }- );--export interface TurnWorkflowDispatchInput {- readonly capabilities: SessionCapabilities | undefined;- readonly completionToken: string;- readonly delivery: HookPayload;- readonly mode: RunMode;- readonly initialStep?: InitialTurnStep;- readonly initialCancellation?: TurnCancelPayload;- readonly parentWritable: WritableStream<Uint8Array>;- /**- * Dispatch-only. `dispatchTurnStep` passes it to `start()`; the turn body- * never reads it, so it is deliberately absent from {@link TurnWorkflowInput}- * and does not participate in the versioned wire shape.- */- readonly retention?: AgentWorkflowRetentionDefinition;- readonly serializedContext: Record<string, unknown>;- readonly sessionState: DurableSessionState;-}--const turnWorkflowInputMigrations: readonly VersionMigration[] = [- turnWorkflowInputV0ToV1,- turnWorkflowInputV1ToV2,-];--export function createTurnWorkflowInput(input: TurnWorkflowDispatchInput): TurnWorkflowInput {- return {- capabilities: input.capabilities,- completionToken: input.completionToken,- driverCapabilities: { cancelledTurnSettle: true, turnInbox: true },- initialCancellation: input.initialCancellation,- initialStep: input.initialStep,- mode: input.mode,- stepInput: {- input: input.delivery,- parentWritable: input.parentWritable,- serializedContext: input.serializedContext,- sessionState: input.sessionState,- },- version: TURN_WORKFLOW_INPUT_VERSION,- };-}--export function migrateTurnWorkflowInput(value: unknown): TurnWorkflowInput {- // Inputs predating versioning carry no `version`; the chain reads them as- // version 0 and walks the registered v0 → v1 migration.- return runMigrationChain<TurnWorkflowInput>({- initialVersion: 0,- label: "turn workflow input",- migrations: turnWorkflowInputMigrations,- targetVersion: TURN_WORKFLOW_INPUT_VERSION,- value,- });-}diff --git a/packages/eve/src/execution/durable-session-store.test.ts b/packages/eve/src/execution/durable-session-store.test.tsindex 844096c8e..2fe8dd8ba 100644--- a/packages/eve/src/execution/durable-session-store.test.ts+++ b/packages/eve/src/execution/durable-session-store.test.ts@@ -1,295 +1,53 @@-import { afterEach, describe, expect, it, vi } from "vitest";-+import { describe, expect, it } from "vitest";import type { HarnessSession } from "#harness/types.js";import {createDurableSessionState,DURABLE_SESSION_VERSION,- type DurableSessionSnapshot,type DurableSessionState,- projectSessionState,readDurableSession,replaceDurableSessionSnapshot,} from "#execution/durable-session-store.js";-import type { NextDriverAction } from "#execution/next-driver-action.js";import { projectToDurableSession } from "#execution/session.js";-const getRunMock = vi.hoisted(() => vi.fn());--vi.mock("#compiled/@workflow/core/runtime.js", () => ({- getRun: (...args: unknown[]) => getRunMock(...args),-}));--afterEach(() => {- getRunMock.mockReset();- vi.useRealTimers();-});--/**- * Pins the cross-version wire contract: `version` discriminators,- * spread-only forwarding (preserving unknown fields), and the closed- * `NextDriverAction` dispatch surface. Breakage here means in-flight- * sessions on a pinned older driver lose data on upgrade.- */-describe("durable-session-store cross-version contract", () => {- it("stamps `DurableSessionState.version` and never carries session-shape flags", () => {- const session = buildSession({- sessionId: "wrun_state_version",- continuationToken: "http:test",- });-- const state = projectSessionState({ session });-- expect(state.version).toBe(DURABLE_SESSION_VERSION);- expect(state.sessionId).toBe("wrun_state_version");- expect(state.continuationToken).toBe("http:test");- expect(state.hasProxyInputRequests).toBe(false);- // Emission state is projected onto the handle so framework steps- // can stamp protocol events without taking an extra step boundary.- expect(state.emissionState).toEqual({- sequence: 0,- sessionStarted: false,- stepIndex: 0,- turnId: "",- });- // Closed contract: pending-batch flags live on `NextDriverAction`- // arms, not on the driver-visible state.- expect(state).not.toHaveProperty("hasPendingInputBatch");- expect(state).not.toHaveProperty("hasPendingCoordinationBatch");- expect(state).not.toHaveProperty("pendingCoordinationCallIds");- expect(state).not.toHaveProperty("snapshot");- });-- it("projects only the durable subset into DurableSession", () => {+describe("durable session checkpoints", () => {+ it("embeds the durable session and its workflow projections together", () => {const session = buildSession({- sessionId: "wrun_persist",- continuationToken: "http:test",+ sessionId: "session",+ continuationToken: "alias",withRefreshableAgent: true,});-- const durable = projectToDurableSession(session);-- expect(durable.sessionId).toBe(session.sessionId);- expect(durable.continuationToken).toBe(session.continuationToken);- expect(durable.history).toBe(session.history);- expect(durable.agent).toEqual({ system: session.agent.system });- // turnAgent-derived fields are rebuilt every turn — not persisted.- expect(durable.agent).not.toHaveProperty("modelReference");- expect(durable.agent).not.toHaveProperty("tools");- expect(durable.agent).not.toHaveProperty("compactionModelReference");- });-- it("preserves unrecognized DurableSessionState fields via spread (forward compat)", () => {- // Hypothetical state shape introduced by a newer eve version.- const futureState: DurableSessionState & { futureFlag: { hint: string } } = {- continuationToken: "http:test",- emissionState: { sequence: 0, sessionStarted: false, stepIndex: 0, turnId: "" },- futureFlag: { hint: "experimental" },- hasProxyInputRequests: false,- sessionId: "wrun_future",- version: 1,- };-- // Mirror the driver's spread-only forwarding pattern.- const passedThrough: DurableSessionState = { ...futureState };- expect((passedThrough as { futureFlag?: unknown }).futureFlag).toEqual({- hint: "experimental",- });- });-- it("preserves unrecognized fields on a DurableSessionSnapshot", () => {- const durable = projectToDurableSession(- buildSession({ sessionId: "wrun_snapshot", continuationToken: "http:test" }),- );- const snapshotWithFutureField = {- session: { ...durable, futureField: { kind: "experimental" } },- version: DURABLE_SESSION_VERSION,- } as DurableSessionSnapshot;-- // Unknown fields inside the durable session shape must round-trip.- const passedThrough = { ...snapshotWithFutureField };- expect(passedThrough.version).toBe(DURABLE_SESSION_VERSION);- expect((passedThrough.session as { futureField?: unknown }).futureField).toEqual({- kind: "experimental",- });- });-- it("NextDriverAction `kind` is the closed driver dispatch surface", () => {- const baseState: DurableSessionState = {- continuationToken: "http:test",- emissionState: { sequence: 0, sessionStarted: false, stepIndex: 0, turnId: "" },- hasProxyInputRequests: false,- sessionId: "wrun_action",- version: 1,- };- const ctx: Record<string, unknown> = { "eve.sessionId": "wrun_action" };-- const arms: NextDriverAction[] = [- { kind: "done", output: "ok", serializedContext: ctx, sessionState: baseState },- { kind: "park", serializedContext: ctx, sessionState: baseState },- {- kind: "dispatch-coordination",- pendingCallIds: ["call-1"],- serializedContext: ctx,- sessionState: baseState,- },- ];-- // Lock the closed-contract kind set. Adding a new arm is breaking.- expect(new Set(arms.map((a) => a.kind))).toEqual(- new Set(["done", "park", "dispatch-coordination"]),- );- });-- it("creates state with the latest durable snapshot", () => {- const session = buildSession({- continuationToken: "http:test",- sessionId: "wrun_embedded_write",- });-const state = createDurableSessionState({ session });-expect(state).toEqual({- ...projectSessionState({ session }),- snapshot: {- session: projectToDurableSession(session),- version: DURABLE_SESSION_VERSION,- },+ sessionId: "session",+ continuationToken: "alias",+ version: DURABLE_SESSION_VERSION,+ hasProxyInputRequests: false,+ emissionState: { sequence: 0, sessionStarted: false, stepIndex: 0, turnId: "" },+ snapshot: { session: projectToDurableSession(session) },});+ expect(readDurableSession(state)).toBe(state.snapshot.session);+ expect(state.snapshot.session.agent).toEqual({ system: "test system" });});- it("replaces the session without dropping unknown snapshot fields", () => {- const original = createDurableSessionState({- session: buildSession({ continuationToken: "http:old", sessionId: "wrun_replace" }),+ it("refreshes projections when replacing session program memory", () => {+ const state = createDurableSessionState({+ session: buildSession({ sessionId: "session", continuationToken: "old" }),});- const state = {- ...original,- snapshot: {- ...original.snapshot,- futureSnapshotField: { owner: "newer deployment" },- },- } as DurableSessionState;- const session = {- ...state.snapshot!.session,- continuationToken: "http:new",- };-+ const session = { ...readDurableSession(state), continuationToken: "new" };const replaced = replaceDurableSessionSnapshot({ session, state });-- expect(replaced.continuationToken).toBe("http:new");- expect(replaced.snapshot?.session).toBe(session);- expect(- (replaced.snapshot as DurableSessionSnapshot & { futureSnapshotField?: unknown })- .futureSnapshotField,- ).toEqual({ owner: "newer deployment" });- });-- it("reads an embedded snapshot without opening the legacy stream", async () => {- const session = buildSession({- continuationToken: "http:test",- sessionId: "wrun_embedded_read",- });- const state = createDurableSessionState({ session });-- const durableSession = await readDurableSession(state);-- expect(durableSession).toEqual(projectToDurableSession(session));- expect(getRunMock).not.toHaveBeenCalled();+ expect(replaced.continuationToken).toBe("new");+ expect(readDurableSession(replaced)).toBe(session);+ expect(state.continuationToken).toBe("old");});- it("classifies unmarked legacy history in an embedded snapshot", async () => {- const session = buildSession({- continuationToken: "http:test",- sessionId: "wrun_embedded_legacy",- });- const state = createDurableSessionState({ session });- const legacySnapshot = {- ...state.snapshot,- session: {- ...state.snapshot!.session,- history: [{ content: "Retained before eve 0.54.", role: "user" }],- },- } as DurableSessionSnapshot;-- const durableSession = await readDurableSession({ ...state, snapshot: legacySnapshot });-- expect(durableSession.history).toEqual([- { content: "Retained before eve 0.54.", kind: "legacy.unknown", role: "user" },- ]);- expect(getRunMock).not.toHaveBeenCalled();- });-- it("cancels the legacy tail read after loading one durable session snapshot", async () => {- const session = buildSession({- continuationToken: "http:test",- sessionId: "wrun_tail_cancel",- });- const snapshot = {- session: {- ...projectToDurableSession(session),- history: [{ content: "Retained before eve 0.54.", role: "user" }],- },- version: DURABLE_SESSION_VERSION,- } as DurableSessionSnapshot;- const cancel = vi.fn();- const stream = new ReadableStream<DurableSessionSnapshot>({- cancel,- start(controller) {- controller.enqueue(snapshot);- },- });- const getReadable = vi.fn(() => stream);- getRunMock.mockReturnValue({ getReadable });-- const durableSession = await readDurableSession(projectSessionState({ session }));-- expect(durableSession).toEqual({- ...snapshot.session,- history: [{ content: "Retained before eve 0.54.", kind: "legacy.unknown", role: "user" }],- });- expect(getRunMock).toHaveBeenCalledWith("wrun_tail_cancel");- expect(getReadable).toHaveBeenCalledWith({- namespace: "eve.session",- startIndex: -1,- });- expect(cancel).toHaveBeenCalledWith("eve durable session tail read complete");- expect(stream.locked).toBe(false);- });-- it("throws a named timeout and cancels the legacy tail read when the stream hangs", async () => {- vi.useFakeTimers();-- const session = buildSession({- continuationToken: "http:test",- sessionId: "wrun_tail_timeout",- });- const cancel = vi.fn();- const stream = new ReadableStream<DurableSessionSnapshot>({- cancel,- });- const getReadable = vi.fn(() => stream);- getRunMock.mockReturnValue({ getReadable });-- const promise = readDurableSession(projectSessionState({ session }));- const assertion = expect(promise).rejects.toMatchObject({- message: expect.stringContaining(- 'Timed out reading durable session snapshot from stream "eve.session" for run wrun_tail_timeout after 10000ms.',- ),- name: "DurableSessionReadTimeoutError",- });-- await vi.advanceTimersByTimeAsync(10_000);-- await assertion;-- expect(getRunMock).toHaveBeenCalledTimes(1);- expect(getReadable).toHaveBeenCalledTimes(1);- expect(getReadable).toHaveBeenCalledWith({- namespace: "eve.session",- startIndex: -1,- });- expect(cancel).toHaveBeenCalledWith("eve durable session tail read timed out after 10000ms");- expect(stream.locked).toBe(false);- });+ it.each([{ version: 2, snapshot: { session: {} } }, { version: 1 }])(+ "rejects unsupported checkpoints without a storage fallback",+ (state) => {+ expect(() => readDurableSession(state as DurableSessionState)).toThrow(+ "Unsupported session checkpoint",+ );+ },+ );});function buildSession(input: {diff --git a/packages/eve/src/execution/durable-session-store.ts b/packages/eve/src/execution/durable-session-store.tsindex 17c799540..e2ac1c277 100644--- a/packages/eve/src/execution/durable-session-store.ts+++ b/packages/eve/src/execution/durable-session-store.ts@@ -1,37 +1,14 @@-/**- * Durable session storage.- *- * Session-mutating steps return the current snapshot inside- * {@link DurableSessionState}; Workflow step results are the atomic- * persistence boundary for session program memory. The legacy- * `"eve.session"` stream remains as a fallback for old in-flight- * sessions that only carry a small state handle.- *- * The driver workflow run is pinned to the deployment that called- * `start()`; child turn workflows run on latest. Both- * {@link DurableSessionState} and {@link DurableSessionSnapshot} carry- * a `version` so a pinned driver can ferry shapes written by newer- * steps. Adding optional fields is forward-compatible (devalue- * preserves unknown POJO fields); shape-breaking changes bump- * `version` and add a migrator.- */import { getHarnessEmissionState, type HarnessEmissionState } from "#harness/emission.js";import type { HarnessModelMessage } from "#harness/messages.js";import { hasProxyInputRequests } from "#harness/proxy-input-requests.js";import type { HarnessSession, SessionStateMap } from "#harness/types.js";-import { migrateDurableSessionSnapshot } from "#execution/durable-session-migrations/snapshot.js";import { projectToDurableSession } from "#execution/session.js";import type { SandboxState } from "#sandbox/state.js";import type { JsonObject } from "#shared/json.js";-import { getRun } from "#internal/workflow/runtime.js";--const EVE_SESSION_STREAM_NAMESPACE = "eve.session";-/** Current wire version for {@link DurableSessionState} and {@link DurableSessionSnapshot}. */+/** Explicit checkpoint contract shared by deployment handoffs. */export const DURABLE_SESSION_VERSION = 1;-const DURABLE_SESSION_READ_TIMEOUT_MS = 10_000;-/*** Serializable handle to a durable session.*@@ -39,14 +16,12 @@ const DURABLE_SESSION_READ_TIMEOUT_MS = 10_000;* workflow body needs without taking a step boundary: identity, the* hook continuation token,* `hasProxyInputRequests` (a closed-contract short-circuit that lets- * the driver skip a per-delivery proxy-routing step when no+ * the owner skip a per-delivery proxy-routing step when no* descendant subagent is active), and `emissionState` (so workflow-body* framework steps can stamp protocol events* with `{ turnId, sequence, stepIndex }` without reading the full- * durable session). All other control-plane state travels via- * {@link import("#execution/next-driver-action.js").NextDriverAction}.- * `snapshot` is optional so old stream-backed states can still read- * from the legacy `eve.session` fallback.+ * durable session). Turn steps return state transitions to the owning+ * `SessionStateCursor`; policy-only turn outcomes never carry snapshots.*/export interface DurableSessionState {readonly version: typeof DURABLE_SESSION_VERSION;@@ -54,12 +29,12 @@ export interface DurableSessionState {readonly continuationToken: string;readonly hasProxyInputRequests: boolean;readonly emissionState: HarnessEmissionState;- readonly snapshot?: DurableSessionSnapshot;+ readonly snapshot: DurableSessionSnapshot;}/*** Durable projection of {@link HarnessSession} embedded in state- * snapshots or legacy `eve.session` stream chunks.+ * snapshots.** Omits `agent.modelReference`, `agent.tools`,* `agent.compactionModelReference`, and the `compaction` thresholds —@@ -94,91 +69,17 @@ export interface DurableSession {};}-/** Versioned wrapper around a {@link DurableSession} on the wire. */+/** Session program memory persisted atomically with Workflow step results. */export interface DurableSessionSnapshot {- readonly version: typeof DURABLE_SESSION_VERSION;readonly session: DurableSession;}-/** Projects a {@link HarnessSession} into the boundary-safe state value. */-export function projectSessionState(input: {- readonly session: HarnessSession;-}): DurableSessionState {- return {- continuationToken: input.session.continuationToken,- emissionState: getHarnessEmissionState(input.session.state),- hasProxyInputRequests: hasProxyInputRequests(input.session.state),- sessionId: input.session.sessionId,- version: DURABLE_SESSION_VERSION,- };-}--/**- * Reads the latest durable session snapshot and returns the- * {@link DurableSession} inside.- *- * New states carry the snapshot directly through Workflow step- * results. States without `snapshot` fall back to the legacy- * `eve.session` stream tail (`startIndex: -1`). The snapshot is- * migrated to {@link DURABLE_SESSION_VERSION} before return; unknown- * versions throw.- *- * Devalue handles encode/decode so rich types in the session (URL- * `FilePart.data`, Buffer, Date, Map, Set) round-trip structurally.- *- * MUST be called from inside a `"use step"` body.- */-export async function readDurableSession(state: DurableSessionState): Promise<DurableSession> {- if (state.snapshot !== undefined) {- return migrateDurableSessionSnapshot(state.snapshot).session;- }-- const stream = getRun<unknown>(state.sessionId).getReadable<unknown>({- namespace: EVE_SESSION_STREAM_NAMESPACE,- startIndex: -1,- });- const reader = stream.getReader();- let cancelReason = "eve durable session tail read failed";- let timeout: ReturnType<typeof setTimeout> | undefined;- try {- const result = await Promise.race([- reader.read().then((read) => ({ kind: "read" as const, read })),- new Promise<{ readonly kind: "timeout" }>((resolve) => {- timeout = setTimeout(() => resolve({ kind: "timeout" }), DURABLE_SESSION_READ_TIMEOUT_MS);- }),- ]);-- if (result.kind === "timeout") {- cancelReason = `eve durable session tail read timed out after ${DURABLE_SESSION_READ_TIMEOUT_MS}ms`;- throw new DurableSessionReadTimeoutError(state);- }-- if (result.read.done || result.read.value === undefined) {- cancelReason = "eve durable session tail read returned no snapshot";- throw new Error(- `No durable session snapshot found in stream "${EVE_SESSION_STREAM_NAMESPACE}" for run ${state.sessionId}.`,- );- }-- cancelReason = "eve durable session tail read complete";- const snapshot = migrateDurableSessionSnapshot(result.read.value);- return snapshot.session;- } finally {- if (timeout !== undefined) {- clearTimeout(timeout);- }- await reader.cancel(cancelReason).catch(() => {});- reader.releaseLock();- }-}--class DurableSessionReadTimeoutError extends Error {- constructor(state: DurableSessionState) {- super(- `Timed out reading durable session snapshot from stream "${EVE_SESSION_STREAM_NAMESPACE}" for run ${state.sessionId} after ${DURABLE_SESSION_READ_TIMEOUT_MS}ms.`,- );- this.name = "DurableSessionReadTimeoutError";+/** Reads only the embedded checkpoint; no stream or migration fallback exists. */+export function readDurableSession(state: DurableSessionState): DurableSession {+ if (state.version !== DURABLE_SESSION_VERSION || state.snapshot?.session === undefined) {+ throw new Error("Unsupported session checkpoint. Start a new session on this deployment.");}+ return state.snapshot.session;}/**@@ -188,33 +89,24 @@ class DurableSessionReadTimeoutError extends Error {export function createDurableSessionState(input: {readonly session: HarnessSession;}): DurableSessionState {- const snapshot: DurableSessionSnapshot = {- session: projectToDurableSession(input.session),- version: DURABLE_SESSION_VERSION,- };-- return {- ...projectSessionState({ session: input.session }),- snapshot,- };+ return projectDurableSessionState(projectToDurableSession(input.session));}-/** Replaces the embedded session while preserving additive snapshot fields. */+/** Replaces session program memory and refreshes its workflow projections. */export function replaceDurableSessionSnapshot(input: {readonly session: DurableSession;readonly state: DurableSessionState;}): DurableSessionState {+ return { ...input.state, ...projectDurableSessionState(input.session) };+}++function projectDurableSessionState(session: DurableSession): DurableSessionState {return {- ...input.state,- continuationToken: input.session.continuationToken,- emissionState: getHarnessEmissionState(input.session.state),- hasProxyInputRequests: hasProxyInputRequests(input.session.state),- sessionId: input.session.sessionId,+ continuationToken: session.continuationToken,+ emissionState: getHarnessEmissionState(session.state),+ hasProxyInputRequests: hasProxyInputRequests(session.state),+ sessionId: session.sessionId,version: DURABLE_SESSION_VERSION,- snapshot: {- ...input.state.snapshot,- session: input.session,- version: DURABLE_SESSION_VERSION,- },+ snapshot: { session },};}diff --git a/packages/eve/src/execution/eve-workflow-attributes.test.ts b/packages/eve/src/execution/eve-workflow-attributes.test.tsindex 7c5c54282..0185b45bf 100644--- a/packages/eve/src/execution/eve-workflow-attributes.test.ts+++ b/packages/eve/src/execution/eve-workflow-attributes.test.ts@@ -3,7 +3,6 @@ import { afterEach, describe, expect, it, vi } from "vitest";import {buildSessionAttributes,buildSubagentRootAttributes,- buildTurnAttributes,deriveSessionTitle,EVE_SESSION_TITLE_MAX_CHARS,isWorkflowTraceContentVisible,@@ -464,50 +463,6 @@ describe("buildSubagentRootAttributes", () => {});});-describe("buildTurnAttributes", () => {- it("emits type=turn with parent and root session", () => {- const attrs = buildTurnAttributes({- parentSessionId: "wrun_session_123",- rootSessionId: "wrun_session_123",- serializedContext: slackChannelCtx,- });-- expect(attrs).toEqual({- "$eve.channel_request_id": undefined,- "$eve.is_otel_trace_enabled": false,- "$eve.is_trace_content_visible": true,- "$eve.trace_id": undefined,- "$eve.type": "turn",- "$eve.parent": "wrun_session_123",- "$eve.root": "wrun_session_123",- });- });-- it("emits the channel request id when present", () => {- const attrs = buildTurnAttributes({- parentSessionId: "wrun_session_123",- requestId: "req_turn",- rootSessionId: "wrun_session_123",- serializedContext: slackChannelCtx,- });-- expect(attrs["$eve.channel_request_id"]).toBe("req_turn");- });-- it("emits $eve.trace_id from a sampled trace seed", () => {- const attrs = buildTurnAttributes({- parentSessionId: "wrun_session_123",- rootSessionId: "wrun_session_123",- serializedContext: {- ...slackChannelCtx,- "eve.sessionTraceSeed": { spanId: "c".repeat(16), traceFlags: 1, traceId: "d".repeat(32) },- },- });-- expect(attrs["$eve.trace_id"]).toBe("d".repeat(32));- });-});-describe("readSessionTraceId", () => {it("returns the trace id from a sampled seed", () => {expect(diff --git a/packages/eve/src/execution/eve-workflow-attributes.ts b/packages/eve/src/execution/eve-workflow-attributes.tsindex fc9dde560..cc313ec2c 100644--- a/packages/eve/src/execution/eve-workflow-attributes.ts+++ b/packages/eve/src/execution/eve-workflow-attributes.ts@@ -319,30 +319,3 @@ export function buildSubagentRootAttributes(input: {"$eve.trigger": readChannelKind(input.serializedContext),};}--/**- * Builds the `$eve.*` attribute payload for one turn workflow run.- *- * Turns live one level below their session: `$eve.parent` always points- * to the parent's sessionId (which is the session-row's- * `workflowRunId`), and `$eve.root` denormalizes the chain root (equal- * to `$eve.parent` for turns of top-level sessions). Turn ordering is- * recovered from each run's `createdAt`, so no explicit sequence tag is- * emitted.- */-export function buildTurnAttributes(input: {- readonly parentSessionId: string;- readonly requestId?: string;- readonly rootSessionId: string;- readonly serializedContext: Record<string, unknown>;-}): Record<string, EveAttributeValue> {- return {- "$eve.channel_request_id": input.requestId,- "$eve.is_otel_trace_enabled": isWorkflowOtelTraceEnabled(input.serializedContext),- "$eve.is_trace_content_visible": isWorkflowTraceContentVisible(input.serializedContext),- "$eve.trace_id": readSessionTraceId(input.serializedContext),- "$eve.type": "turn",- "$eve.parent": input.parentSessionId,- "$eve.root": input.rootSessionId,- };-}diff --git a/packages/eve/src/execution/file-memory.integration.test.ts b/packages/eve/src/execution/file-memory.integration.test.tsindex 0cb5ece29..bf16397b0 100644--- a/packages/eve/src/execution/file-memory.integration.test.ts+++ b/packages/eve/src/execution/file-memory.integration.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { workflowEntry } from "#execution/workflow-entry.js";+import { workflowEntry } from "#execution/session/entry.js";import { createTestRuntime } from "#internal/testing/app-harness.js";import { captureTurnEvents, filterEventsByType } from "#internal/testing/events.js";import { start } from "#internal/workflow/runtime.js";@@ -80,6 +80,8 @@ describe("file memory integration", () => {async function runTurn(input: { readonly message: string; readonly principalId: string }) {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: input.message },serializedContext: {"eve.auth": {diff --git a/packages/eve/src/execution/forward-turn-cancellation-step.ts b/packages/eve/src/execution/forward-turn-cancellation-step.tsdeleted file mode 100644index 70255be9f..000000000--- a/packages/eve/src/execution/forward-turn-cancellation-step.ts+++ /dev/null@@ -1,25 +0,0 @@-import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";--import type { TurnCancelPayload } from "#execution/turn-cancellation-token.js";-import { resumeHook } from "#internal/workflow/runtime.js";--/** Forwards an inbox cancellation command to one private active-turn hook. */-export async function forwardTurnCancellationStep(input: {- readonly payload: TurnCancelPayload;- readonly token: string;-}): Promise<boolean> {- "use step";-- for (let attempt = 0; attempt < 50; attempt += 1) {- try {- await resumeHook(input.token, input.payload);- return true;- } catch (error) {- if (!HookNotFoundError.is(error)) throw error;- if (attempt === 49) return false;- await new Promise<void>((resolve) => setTimeout(resolve, 20));- }- }-- return false;-}diff --git a/packages/eve/src/execution/forward-turn-delivery-step.ts b/packages/eve/src/execution/forward-turn-delivery-step.tsdeleted file mode 100644index fa668f69c..000000000--- a/packages/eve/src/execution/forward-turn-delivery-step.ts+++ /dev/null@@ -1,12 +0,0 @@-import type { TurnInboxPayload } from "#execution/turn-control-protocol.js";-import { resumeHook } from "#internal/workflow/runtime.js";--/** Forwards one accepted public delivery to the private inbox of its requesting turn. */-export async function forwardTurnDeliveryStep(input: {- readonly inboxToken: string;- readonly payload: TurnInboxPayload;-}): Promise<void> {- "use step";-- await resumeHook(input.inboxToken, input.payload);-}diff --git a/packages/eve/src/execution/hook-ownership.ts b/packages/eve/src/execution/hook-ownership.tsindex 890aa852c..f48efec8c 100644--- a/packages/eve/src/execution/hook-ownership.ts+++ b/packages/eve/src/execution/hook-ownership.ts@@ -5,7 +5,7 @@ export async function claimHookOwnership<T>(hook: Hook<T>): Promise<void> {try {conflict = await hook.getConflict();} catch (error) {- return await disposeAndThrow(hook, normalizeHookClaimError(error, hook.token));+ return await disposeAndThrow(hook, error);}if (conflict !== null) {@@ -13,26 +13,8 @@ export async function claimHookOwnership<T>(hook: Hook<T>): Promise<void> {}}-export async function closeHookIterator<T>(iterator: AsyncIterator<T>): Promise<void> {- if (typeof iterator.return === "function") {- await iterator.return(undefined);- }-}--export async function disposeHook(hook: {- dispose?: () => unknown;- [Symbol.dispose]?: () => unknown;-}): Promise<void> {- const explicitDispose = hook.dispose;- if (typeof explicitDispose === "function") {- await explicitDispose.call(hook);- return;- }-- const symbolDispose = hook[Symbol.dispose];- if (typeof symbolDispose === "function") {- await symbolDispose.call(hook);- }+export async function disposeHook(hook: { dispose: () => unknown }): Promise<void> {+ await hook.dispose();}async function disposeAndThrow(hook: Hook<unknown>, error: unknown): Promise<never> {@@ -44,19 +26,7 @@ async function disposeAndThrow(hook: Hook<unknown>, error: unknown): Promise<nevthrow error;}-function normalizeHookClaimError(error: unknown, token: string): unknown {- if (!isHookConflictError(error)) {- return error;- }-- // Legacy worlds reject here when they cannot identify the owning run.- return createHookConflictError(- typeof error.token === "string" ? error.token : token,- typeof error.conflictingRunId === "string" ? error.conflictingRunId : undefined,- );-}--/** Recognizes hook conflicts across current and legacy Workflow World implementations. */+/** Error names survive Workflow serialization across runtime boundaries. */export function isHookConflictError(error: unknown): error is {readonly conflictingRunId?: unknown;readonly name: "HookConflictError";@@ -72,12 +42,12 @@ export function isHookConflictError(error: unknown): error is {function createHookConflictError(token: string,- conflictingRunId?: string,+ conflictingRunId: string,): Error & {- readonly conflictingRunId?: string;+ readonly conflictingRunId: string;readonly token: string;} {- const owner = conflictingRunId === undefined ? "" : ` (run "${conflictingRunId}")`;+ const owner = ` (run "${conflictingRunId}")`;return Object.assign(new Error(`Hook token "${token}" is already in use${owner}`), {conflictingRunId,name: "HookConflictError",diff --git a/packages/eve/src/execution/inline-turn.ts b/packages/eve/src/execution/inline-turn.tsdeleted file mode 100644index f6aad7df4..000000000--- a/packages/eve/src/execution/inline-turn.ts+++ /dev/null@@ -1,297 +0,0 @@-import type { DeliverHookPayload, HookPayload, SessionCapabilities } from "#channel/types.js";-import { readAcceptedDeploymentId } from "#execution/accepted-delivery-deployment.js";-import { cancelAllIndexedSessionTasksStep } from "#execution/cancel-indexed-session-tasks-step.js";-import type {- InitialTurnStep,- TurnStepPayload,-} from "#execution/durable-session-migrations/turn-workflow.js";-import type { DurableSessionState } from "#execution/durable-session-store.js";-import type { DurableStepResult, NextDriverAction } from "#execution/next-driver-action.js";-import { reportDroppedWirePayloadStep } from "#execution/report-dropped-wire-payload-step.js";-import type { SessionCommandInbox, SessionInboxPayload } from "#execution/session-command-inbox.js";-import { SessionStateCursor } from "#execution/session-state-cursor.js";-import type { TurnCancelPayload } from "#execution/turn-cancellation-token.js";-import {- sessionInboxWire,- SessionInboxWireError,- type DecodedSessionInbox,-} from "#execution/wire/session-inbox-wire.js";-import { turnStep } from "#execution/workflow-steps.js";-import { activeTurnId } from "#harness/active-turn-id.js";-import { TurnCancelledError } from "#harness/turn-cancellation.js";-import type { RunMode } from "#shared/run-mode.js";--export type InlineTurnOutcome =- | {- readonly initialCancellation?: TurnCancelPayload;- readonly initialStep?: InitialTurnStep;- readonly kind: "child" | "continue";- }- | { readonly action: NextDriverAction; readonly kind: "result" };--/** Runs same-deployment steps directly until they need the shared turn runner. */-export async function runInlineTurn(input: {- readonly bufferedDeliveries: DeliverHookPayload[];- readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;- readonly cancelledTaskIds?: Set<string>;- readonly capabilities?: SessionCapabilities;- readonly commandInbox: SessionCommandInbox;- readonly delivery: HookPayload;- readonly mode: RunMode;- readonly parentWritable: WritableStream<Uint8Array>;- readonly seenTaskDeliveries?: Set<string>;- readonly serializedContext: Record<string, unknown>;- readonly sessionState: DurableSessionState;- readonly stateCursor?: SessionStateCursor;-}): Promise<InlineTurnOutcome> {- const acceptedDeploymentId = readAcceptedDeploymentId(input.delivery);- if (acceptedDeploymentId === undefined) return { kind: "child" };-- const cursor =- input.stateCursor ??- new SessionStateCursor({- serializedContext: input.serializedContext,- sessionState: input.sessionState,- });- const control = new InlineTurnControl({- bufferedDeliveries: input.bufferedDeliveries,- bufferedSessionControls: input.bufferedSessionControls,- cancelledTaskIds: input.cancelledTaskIds,- commandInbox: input.commandInbox,- expectedTurnId: activeTurnId(input.sessionState.emissionState),- seenTaskDeliveries: input.seenTaskDeliveries,- stateCursor: cursor,- });- let nextStepInput: TurnStepPayload | undefined = input.delivery;-- while (true) {- const beforeStep = {- serializedContext: cursor.serializedContext,- sessionState: cursor.sessionState,- };- const result = await control.waitForStep(- turnStep({- abortSignal: control.signal,- acceptedDeploymentId,- input: nextStepInput,- parentWritable: input.parentWritable,- serializedContext: cursor.serializedContext,- sessionState: cursor.sessionState,- }),- );-- if (result.requiresChildDispatch === true) {- return { initialCancellation: control.initialCancellation, kind: "child" };- }-- const initialStep = { beforeStep, result } satisfies InitialTurnStep;- if (- control.initialCancellation !== undefined ||- result.action === "cancelled" ||- (result.backgroundTasks?.length ?? 0) > 0- ) {- return continueOutcome(control, initialStep);- }-- if (result.action === "done") {- return {- action: {- isError: result.isError,- kind: "done",- output: result.output ?? "",- serializedContext: result.serializedContext,- sessionState: result.sessionState,- usage: result.usage,- usageDelta: result.usageDelta,- },- kind: "result",- };- }-- if (result.action === "park" && result.pendingCoordinationCallIds !== undefined) {- return continueOutcome(control, initialStep);- }-- if (result.action === "park") {- const canPark =- result.hasPendingAuthorization ||- (result.hasPendingInputBatch && input.capabilities?.requestInput === true) ||- input.mode === "conversation";- if (!canPark) return continueOutcome(control, initialStep);- return {- action: {- authorizationAttemptIds: result.authorizationAttemptIds,- authorizationNames: result.authorizationNames,- kind: "park",- serializedContext: result.serializedContext,- sessionState: result.sessionState,- settled: result.settled,- },- kind: "result",- };- }-- const previousContinuationToken = cursor.sessionState.continuationToken;- cursor.adoptState(result);- if (- cursor.sessionState.continuationToken !== "" &&- cursor.sessionState.continuationToken !== previousContinuationToken- ) {- await input.commandInbox.rekeyContinuation(cursor.sessionState.continuationToken);- }- nextStepInput = undefined;- }-}--function continueOutcome(- control: InlineTurnControl,- initialStep: InitialTurnStep,-): Exclude<InlineTurnOutcome, { readonly kind: "result" }> {- return {- initialCancellation: control.initialCancellation,- initialStep,- kind: "continue",- };-}--class InlineTurnControl {- private readonly bufferedDeliveries: DeliverHookPayload[];- private readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;- private readonly cancelledTaskIds: Set<string>;- private readonly commandInbox: SessionCommandInbox;- private readonly controller = new AbortController();- private readonly expectedTurnId: string;- private readonly seenTaskDeliveries: Set<string>;- private readonly stateCursor: SessionStateCursor;- private cancellation: TurnCancelPayload | undefined;-- constructor(input: {- readonly bufferedDeliveries: DeliverHookPayload[];- readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;- readonly cancelledTaskIds?: Set<string>;- readonly commandInbox: SessionCommandInbox;- readonly expectedTurnId: string;- readonly seenTaskDeliveries?: Set<string>;- readonly stateCursor: SessionStateCursor;- }) {- this.bufferedDeliveries = input.bufferedDeliveries;- this.bufferedSessionControls = input.bufferedSessionControls;- this.cancelledTaskIds = input.cancelledTaskIds ?? new Set();- this.commandInbox = input.commandInbox;- this.expectedTurnId = input.expectedTurnId;- this.seenTaskDeliveries = input.seenTaskDeliveries ?? new Set();- this.stateCursor = input.stateCursor;- }-- get initialCancellation(): TurnCancelPayload | undefined {- return this.cancellation;- }-- get signal(): AbortSignal {- return this.controller.signal;- }-- async waitForStep(step: Promise<DurableStepResult>): Promise<DurableStepResult> {- const settled = step.then((result) => ({ kind: "step" as const, result }));- while (true) {- const winner = await Promise.race([- settled,- this.commandInbox.next().then((result) => ({ kind: "command" as const, result })),- ]);- if (winner.kind === "step") return winner.result;- if (winner.result.done) {- throw new Error("Session command inbox closed before the inline turn step settled.");- }- this.commandInbox.consumeNext();- await this.handle(winner.result.value);- }- }-- private abort(payload: TurnCancelPayload): void {- if (this.controller.signal.aborted) return;- this.cancellation = payload;- this.controller.abort(new TurnCancelledError());- }-- private acceptTaskDelivery(command: DeliverHookPayload): boolean {- const deliveryId = command.taskDeliveryId ?? command.caller?.taskId;- if (deliveryId === undefined) return true;- if (this.originatesFromCancelledTask(deliveryId)) return false;- if (this.seenTaskDeliveries.has(deliveryId)) return false;- this.seenTaskDeliveries.add(deliveryId);- return true;- }-- private async handle(value: SessionInboxPayload): Promise<void> {- if (value.kind === "runtime-action-result") return;- let command: DecodedSessionInbox;- try {- command = sessionInboxWire.decode(value);- } catch (error) {- if (!(error instanceof SessionInboxWireError)) throw error;- await reportDroppedWirePayloadStep({ detail: error.message, family: "session-inbox" });- return;- }-- if (command.kind === "deliver") {- if (!this.acceptTaskDelivery(command)) return;- this.bufferedDeliveries.push(command);- if (command.turnPolicy === "steer" && deliveryHasMessage(command)) this.abort({});- return;- }- if (command.kind === "clear" || command.kind === "compact") {- this.bufferedSessionControls.push(command.kind);- return;- }- if (command.kind === "session-timeout") {- this.bufferedSessionControls.push("expired");- return;- }- if (command.kind === "reset") {- this.bufferedSessionControls.push("reset");- this.abort({});- return;- }- if (command.kind === "cancel") {- if ("tasks" in command && command.tasks === true) {- await cancelAllIndexedSessionTasksStep({- serializedContext: this.stateCursor.serializedContext,- sessionState: this.stateCursor.sessionState,- });- }- if (command.taskId !== undefined) this.discardTaskDeliveries(command.taskId);- const turnId =- command.taskId !== undefined &&- command.turnId !== undefined &&- command.turnId !== this.expectedTurnId- ? undefined- : command.turnId;- if (turnId === undefined || turnId === this.expectedTurnId) {- const payload =- turnId === undefined ? { tasks: command.tasks } : { tasks: command.tasks, turnId };- this.abort(payload);- }- }- }-- private discardTaskDeliveries(taskId: string): void {- this.cancelledTaskIds.add(taskId);- const kept = this.bufferedDeliveries.filter((delivery) => !this.shouldDiscard(delivery));- this.bufferedDeliveries.splice(0, this.bufferedDeliveries.length, ...kept);- }-- private originatesFromCancelledTask(deliveryId: string): boolean {- return [...this.cancelledTaskIds].some(- (taskId) => deliveryId === taskId || deliveryId.startsWith(`${taskId}:`),- );- }-- private shouldDiscard(delivery: DeliverHookPayload): boolean {- const deliveryId = delivery.taskDeliveryId ?? delivery.caller?.taskId;- return deliveryId !== undefined && this.originatesFromCancelledTask(deliveryId);- }-}--function deliveryHasMessage(delivery: DeliverHookPayload): boolean {- return delivery.payloads.some((payload) => payload.message !== undefined);-}diff --git a/packages/eve/src/execution/legacy-session-history.integration.test.ts b/packages/eve/src/execution/legacy-session-history.integration.test.tsdeleted file mode 100644index 2608168f5..000000000--- a/packages/eve/src/execution/legacy-session-history.integration.test.ts+++ /dev/null@@ -1,84 +0,0 @@-import { describe, expect, it } from "vitest";--import { migrateDurableSessionSnapshot } from "#execution/durable-session-migrations/snapshot.js";-import {- createDurableSessionState,- type DurableSessionSnapshot,- readDurableSession,-} from "#execution/durable-session-store.js";-import {- createSession,- hydrateDurableSession,- projectToDurableSession,-} from "#execution/session.js";-import { validateHarnessModelMessages } from "#harness/messages.js";-import { genAiInputMessagesAttribute } from "#tracing/agent-otel-content.js";--const turnAgent = {- id: "test-agent",- instructions: ["Be concise."],- model: { id: "test-model" },- tools: [],- workspaceSpec: { rootEntries: [] },-};--describe("pre-0.54 durable history", () => {- it("restores old user and framework messages without inventing provenance", async () => {- const attachment = new URL("https://example.com/report.pdf");- const history = [- { content: "Please summarize the report.", role: "user" },- { content: "A background task completed.", role: "user" },- {- content: [{ data: attachment, mediaType: "application/pdf", type: "file" }],- legacyField: "retained",- metadata: { retained: true },- role: "user",- },- { content: "Here is the summary.", role: "assistant" },- { content: "Be concise.", kind: "context.instruction", role: "user" },- ];- const initial = createSession({- continuationToken: "test-token",- sessionId: "test-session",- turnAgent,- });- const state = createDurableSessionState({ session: initial });- const legacySnapshot = {- ...state.snapshot,- retained: "snapshot field",- session: { ...projectToDurableSession(initial), history },- } as DurableSessionSnapshot;-- const durable = await readDurableSession({ ...state, snapshot: legacySnapshot });- const resumed = hydrateDurableSession({ durable, turnAgent });-- expect(resumed.history).toEqual([- ...history.slice(0, 3).map((message) => ({ ...message, kind: "legacy.unknown" })),- ...history.slice(3),- ]);- expect(history[0]).not.toHaveProperty("kind");- expect(genAiInputMessagesAttribute(resumed.history)).toContain('"kind":"legacy.unknown"');-- const saved = createDurableSessionState({ session: resumed });- expect(saved.version).toBe(state.version);- expect(saved.snapshot?.version).toBe(state.snapshot?.version);- expect(await readDurableSession(saved)).toEqual(durable);-- const migrated = migrateDurableSessionSnapshot(legacySnapshot);- expect(migrated).toHaveProperty("retained", "snapshot field");- });-- it("does not repair malformed explicit kinds or relax new-message validation", () => {- expect(() => validateHarnessModelMessages([{ content: "New input", role: "user" }])).toThrow(- "Expected every user-role model message to have a kind.",- );- expect(() =>- migrateDurableSessionSnapshot({- session: {- history: [{ content: "Old input", kind: "invalid", role: "user" }],- },- version: 1,- }),- ).toThrow("Expected every user-role model message to have a kind.");- });-});diff --git a/packages/eve/src/execution/legacy-session/authorization.test.ts b/packages/eve/src/execution/legacy-session/authorization.test.tsnew file mode 100644index 000000000..15c0c92f2--- /dev/null+++ b/packages/eve/src/execution/legacy-session/authorization.test.ts@@ -0,0 +1,55 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";+import { resumeAuthorizationCallback, handleExpiredLegacyAuthorization } from "./authorization.js";+const mocks = vi.hoisted(() => ({ resolve: vi.fn(), resume: vi.fn() }));+vi.mock("#internal/workflow/runtime.js", () => ({ resumeHook: mocks.resume }));+vi.mock("./inbox.js", async (original) => ({+ ...(await original<typeof import("./inbox.js")>()),+ resolveLegacyInbox: mocks.resolve,+}));+beforeEach(() => vi.resetAllMocks());+const payload = {+ kind: "authorization-callback" as const,+ payloads: [+ {+ authorizationCallback: {+ attemptId: "attempt",+ connectionName: "weather",+ callback: { method: "GET", params: { code: "test" } },+ },+ },+ ],+};+function missingCurrentInbox(token: string) {+ mocks.resume.mockRejectedValueOnce(new HookNotFoundError(token));+}+describe("authorization cutover", () => {+ it("delivers current callbacks without historical lookup", async () => {+ mocks.resume.mockResolvedValue({ runId: "current" });+ await resumeAuthorizationCallback("eve:inbox:v1:current", payload);+ expect(mocks.resolve).not.toHaveBeenCalled();+ expect(mocks.resume).toHaveBeenCalledExactlyOnceWith("eve:inbox:v1:current", payload);+ });+ it("rejects historical callbacks after import without queuing them on the new owner", async () => {+ missingCurrentInbox("old");+ mocks.resolve.mockResolvedValue({ current: true });+ await expect(resumeAuthorizationCallback("old", payload)).rejects.toThrow("interrupted");+ expect(mocks.resume).toHaveBeenCalledExactlyOnceWith("old", payload);+ });+ it("uses the historical wire envelope before import", async () => {+ missingCurrentInbox("old");+ mocks.resolve.mockResolvedValue({+ current: false,+ hook: { token: "old", metadata: { sessionInboxWireVersion: 3 } },+ });+ await resumeAuthorizationCallback("old", payload);+ expect(mocks.resume).toHaveBeenCalledTimes(2);+ expect(mocks.resume).toHaveBeenLastCalledWith(+ "old",+ expect.objectContaining({ kind: "deliver", version: 3, payloads: payload.payloads }),+ );+ });+ it("expires historical URLs that do not identify an authorization attempt", async () => {+ expect((await handleExpiredLegacyAuthorization()).status).toBe(410);+ });+});diff --git a/packages/eve/src/execution/legacy-session/authorization.ts b/packages/eve/src/execution/legacy-session/authorization.tsnew file mode 100644index 000000000..1989fcd38--- /dev/null+++ b/packages/eve/src/execution/legacy-session/authorization.ts@@ -0,0 +1,46 @@+import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";+import type { AuthorizationCallbackPayload } from "#execution/session-inbox/inbox.js";+import { resumeHook } from "#internal/workflow/runtime.js";+import { isObject } from "#shared/guards.js";+import { encodeLegacyCommand, resolveLegacyInbox } from "./inbox.js";++/**+ * Delivers an authorization callback to the hook named in its URL. Current+ * URLs carry a physical hook token (a session inbox or a workflow-tool+ * callback); URLs minted by a pre-cutover driver carry that driver's own+ * logical token, which is re-encoded for it or rejected once imported.+ */+export async function resumeAuthorizationCallback(+ token: string,+ payload: AuthorizationCallbackPayload,+): Promise<void> {+ try {+ await resumeHook(token, payload);+ return;+ } catch (error) {+ if (!HookNotFoundError.is(error)) throw error;+ }+ const target = await resolveLegacyInbox(token);+ if (target.current)+ throw new Error(+ "Authorization was interrupted by the session upgrade. Request authorization again.",+ );+ const metadata = await target.hook.metadata;+ await resumeHook(+ target.hook.token,+ encodeLegacyCommand(+ { kind: "deliver", payloads: payload.payloads },+ isObject(metadata) ? metadata.sessionInboxWireVersion : undefined,+ ),+ );+}++export async function handleExpiredLegacyAuthorization(): Promise<Response> {+ return Response.json(+ {+ ok: false,+ error: "This authorization link predates the session upgrade. Request authorization again.",+ },+ { status: 410 },+ );+}diff --git a/packages/eve/src/execution/legacy-session/completion-step.test.ts b/packages/eve/src/execution/legacy-session/completion-step.test.tsnew file mode 100644index 000000000..3626008d8--- /dev/null+++ b/packages/eve/src/execution/legacy-session/completion-step.test.ts@@ -0,0 +1,64 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";+import { completeLegacyDriverStep } from "./completion-step.js";+import { importConversation } from "./snapshot.js";+const { resume } = vi.hoisted(() => ({ resume: vi.fn() }));+vi.mock("#internal/workflow/runtime.js", () => ({ resumeHook: resume }));+beforeEach(() => vi.resetAllMocks());+function fixture() {+ const close = vi.fn();+ const session = {+ sessionId: "old",+ continuationToken: "",+ history: [],+ agent: { system: "old" },+ };+ return {+ close,+ completionToken: "old:completion",+ serializedContext: { "eve.sessionCallback": { url: "https://example.com/callback" } },+ sessionState: importConversation(session),+ sessionWritable: new WritableStream<Uint8Array>({ close }),+ };+}+describe("original driver finalization", () => {+ it("closes the original stream and sends one historical completion with the original callback context", async () => {+ const { close, ...prepared } = fixture();+ const result = {+ output: "failed",+ isError: true,+ usage: { inputTokens: 12, outputTokens: 3, cacheReadTokens: 0, cacheWriteTokens: 0 },+ };+ await completeLegacyDriverStep({ ...prepared, result });+ expect(close).toHaveBeenCalledOnce();+ expect(resume).toHaveBeenCalledExactlyOnceWith("old:completion", {+ kind: "turn-result",+ action: {+ kind: "done",+ ...result,+ serializedContext: prepared.serializedContext,+ sessionState: {+ ...prepared.sessionState,+ snapshot: { version: 1, session: prepared.sessionState.snapshot.session },+ },+ },+ });+ expect(close.mock.invocationCallOrder[0]).toBeLessThan(resume.mock.invocationCallOrder[0]!);+ });+ it("tolerates an already-finished original driver", async () => {+ const { close: _close, ...prepared } = fixture();+ resume.mockRejectedValue(new HookNotFoundError("old:completion"));+ await expect(+ completeLegacyDriverStep({ ...prepared, result: { output: "" } }),+ ).resolves.toBeUndefined();+ expect(resume).toHaveBeenCalledOnce();+ });+ it("surfaces uncertain completion writes for durable step retry", async () => {+ const { close: _close, ...prepared } = fixture();+ resume.mockRejectedValue(new Error("wake failed"));+ await expect(completeLegacyDriverStep({ ...prepared, result: { output: "" } })).rejects.toThrow(+ "wake failed",+ );+ expect(resume).toHaveBeenCalledOnce();+ });+});diff --git a/packages/eve/src/execution/legacy-session/completion-step.ts b/packages/eve/src/execution/legacy-session/completion-step.tsnew file mode 100644index 000000000..2dcc87fdb--- /dev/null+++ b/packages/eve/src/execution/legacy-session/completion-step.ts@@ -0,0 +1,37 @@+import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";+import type { DurableSessionState } from "#execution/durable-session-store.js";+import { resumeHook } from "#internal/workflow/runtime.js";+import type { WorkflowEntryResult } from "#execution/session/entry-input.js";++/** The old driver owns final notifications for the dispatch that became this session. */+export async function completeLegacyDriverStep(input: {+ readonly completionToken: string;+ readonly result: WorkflowEntryResult;+ readonly serializedContext: Record<string, unknown>;+ readonly sessionState: DurableSessionState;+ readonly sessionWritable: WritableStream<Uint8Array>;+}): Promise<void> {+ "use step";+ const writer = input.sessionWritable.getWriter();+ try {+ await writer.close();+ } finally {+ writer.releaseLock();+ }+ try {+ await resumeHook(input.completionToken, {+ kind: "turn-result",+ action: {+ kind: "done",+ ...input.result,+ serializedContext: input.serializedContext,+ sessionState: {+ ...input.sessionState,+ snapshot: { version: 1, session: input.sessionState.snapshot.session },+ },+ },+ });+ } catch (error) {+ if (!HookNotFoundError.is(error)) throw error;+ }+}diff --git a/packages/eve/src/execution/legacy-session/import.integration.test.ts b/packages/eve/src/execution/legacy-session/import.integration.test.tsnew file mode 100644index 000000000..0f3d54722--- /dev/null+++ b/packages/eve/src/execution/legacy-session/import.integration.test.ts@@ -0,0 +1,254 @@+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 { 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";+import { getWorld, getHookByToken, start } from "#internal/workflow/runtime.js";+import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";+import { createWorkflowRuntime } from "#execution/workflow-runtime.js";+import { resumeSessionInbox, resolveSessionInbox } from "#execution/session-inbox/resume.js";+import {+ sessionCommandHookToken,+ sessionInboxHookToken,+} from "#execution/session-inbox/address.js";++describe("legacy session import", () => {+ it.each([+ { inputVersion: 1 as const, inboxVersion: 1 },+ { inputVersion: 1 as const, inboxVersion: 3 },+ { inputVersion: 2 as const, inboxVersion: 7 },+ { inputVersion: 2 as const, inboxVersion: 7, duplicateImport: true },+ { inputVersion: 2 as const, inboxVersion: 7, committedInput: true },+ ])(+ "imports $inputVersion / inbox $inboxVersion / duplicate $duplicateImport / committed $committedInput",+ async (variant) => {+ const runtime = await createTestRuntime({ agent: { name: "legacy-import-current" } });+ {+ await runtime.run(async () => {+ const alias = `http:legacy-${variant.inputVersion}-${variant.inboxVersion}-${variant.duplicateImport}-${variant.committedInput}`;+ const driver = await start(legacySessionDriverWorkflow, [+ {+ alias,+ ...variant,+ sessionTimeoutMs: false,+ serializedContext: {+ "eve.auth": null,+ "eve.bundle": { source: createBundledRuntimeCompiledArtifactsSource() },+ "eve.channel": { kind: "http", state: {} },+ "eve.mode": "conversation",+ },+ },+ ]);+ const stream = captureTurnEvents(driver);+ try {+ await waitForHook(driver, { token: `eve:session:${driver.runId}:inbox` });+ await resumeSessionInbox(+ { sessionId: driver.runId },+ { kind: "send", payload: { message: "Alice asks to continue the blue project." } },+ );+ const first = await stream.nextTurn();+ if (variant.committedInput) {+ expect(filterEventsByType(first, "turn.started")).toHaveLength(0);+ expect(filterEventsByType(first, "step.started")[0]?.data.turnId).toBe("turn_7");+ } else expect(filterEventsByType(first, "turn.started")[0]?.data.turnId).toBe("turn_7");+ expect(filterEventsByType(first, "session.started")).toHaveLength(0);+ expect(filterEventsByType(first, "session.failed")).toHaveLength(0);+ expect(filterEventsByType(first, "message.received")).toHaveLength(+ variant.committedInput ? 0 : 1,+ );+ const owner = await getHookByToken(+ sessionInboxHookToken(sessionCommandHookToken(driver.runId)),+ );+ expect(owner.runId).not.toBe(driver.runId);+ expect(await driver.status).toBe("running");+ await expect(resolveSessionInbox(alias)).resolves.toEqual({ sessionId: driver.runId });+ await resumeSessionInbox(alias, {+ kind: "send",+ payload: { message: "Bob asks for the next update." },+ });+ const second = await stream.nextTurn();+ expect(filterEventsByType(second, "turn.started")).toHaveLength(1);+ expect(+ (await getHookByToken(sessionInboxHookToken(sessionCommandHookToken(driver.runId))))+ .runId,+ ).toBe(owner.runId);+ await vi.waitFor(+ async () => {+ const steps = await (+ await getWorld()+ ).steps.list({+ runId: owner.runId,+ resolveData: "all",+ pagination: { limit: 1000 },+ });+ const checkpoints: DurableStepResult[] = [];+ for (const step of steps.data) {+ if (step.stepName.endsWith("//turnStep") && step.output !== undefined) {+ checkpoints.push(+ await hydrateStepReturnValue(step.output, owner.runId, undefined),+ );+ }+ }+ const saved = checkpoints.find((result) =>+ result.sessionState.snapshot.session.history.some(+ (message) =>+ message.role === "user" &&+ JSON.stringify(message.content).includes("Bob asks for the next update."),+ ),+ )?.sessionState.snapshot.session;+ expect(saved).toBeDefined();+ expect(saved!.agent.system).not.toBe("previous deployment");+ expect(saved!.state?.["app.color"]).toBe("blue");+ expect(+ saved!.history.filter(+ (message) =>+ message.role === "user" &&+ JSON.stringify(message.content).includes(+ "Alice asks to continue the blue project.",+ ),+ ),+ ).toHaveLength(1);+ expect(saved!.history[0]).toMatchObject({+ role: "user",+ content: "Alice selected blue for the project.",+ });+ },+ { timeout: 5000 },+ );+ await resumeSessionInbox({ sessionId: driver.runId }, { kind: "reset" });+ const terminal = await stream.nextTurn();+ expect(filterEventsByType(terminal, "session.completed")).toHaveLength(1);+ await expect(driver.returnValue).resolves.toMatchObject({ kind: "done" });+ await expect(stream.nextTurn()).rejects.toThrow(+ "closed before reaching a turn boundary",+ );+ } finally {+ stream.dispose();+ if ((await driver.status) === "running") await driver.cancel();+ }+ });+ }+ },+ );+});++describe("unsupported drivers", () => {+ it("reports a pre-0.45 driver as inactive instead of misdelivering", async () => {+ const runtime = await createTestRuntime({ agent: { name: "legacy-unsupported" } });+ await runtime.run(async () => {+ const alias = "http:legacy-unversioned";+ const driver = await start(legacySessionDriverWorkflow, [+ { alias, sessionTimeoutMs: false, serializedContext: legacyContext() },+ ]);+ try {+ await waitForHook(driver, { token: `eve:session:${driver.runId}:inbox` });+ const workflowRuntime = createWorkflowRuntime({+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),+ });+ await expect(+ workflowRuntime.dispatchContinuation({+ command: { kind: "send", payload: { message: "Alice continues." } },+ continuationToken: alias,+ }),+ ).resolves.toEqual({ status: "session_not_active" });+ expect(await driver.status).toBe("running");+ } finally {+ if ((await driver.status) === "running") await driver.cancel();+ }+ });+ });+});++describe("imported session lifetime", () => {+ it("hands off again using a current checkpoint and completes the original stream", async () => {+ const runtime = await createTestRuntime({ agent: { name: "legacy-handoff" } });+ await runtime.run(async () => {+ const driver = await start(legacySessionDriverWorkflow, [+ {+ alias: "",+ inboxVersion: 7,+ sessionTimeoutMs: 60_000,+ serializedContext: legacyContext(),+ },+ ]);+ const stream = captureTurnEvents(driver);+ try {+ await waitForHook(driver, { token: `eve:session:${driver.runId}:inbox` });+ await resumeSessionInbox(+ { sessionId: driver.runId },+ { kind: "send", payload: { message: "Alice continues." } },+ );+ await stream.nextTurn();+ const importedOwner = await getHookByToken(+ sessionInboxHookToken(sessionCommandHookToken(driver.runId)),+ );+ await resumeSessionInbox(+ { sessionId: driver.runId },+ {+ kind: "send",+ payload: { message: "Bob continues on the next deployment." },+ delivery: {+ acceptedDeploymentId: "dpl_successor",+ channelKind: "http",+ channelName: "test",+ deliveryId: "second",+ },+ },+ );+ await stream.nextTurn();+ const successor = await getHookByToken(+ sessionInboxHookToken(sessionCommandHookToken(driver.runId)),+ );+ expect(successor.runId).not.toBe(importedOwner.runId);+ expect(await driver.status).toBe("running");+ await resumeSessionInbox({ sessionId: driver.runId }, { kind: "cancel" });+ await resumeSessionInbox(+ { sessionId: driver.runId },+ { kind: "send", payload: { message: "Alice resumes after cancellation." } },+ );+ expect(filterEventsByType(await stream.nextTurn(), "turn.started")).toHaveLength(1);+ await resumeSessionInbox({ sessionId: driver.runId }, { kind: "reset" });+ expect(filterEventsByType(await stream.nextTurn(), "session.completed")).toHaveLength(1);+ await expect(driver.returnValue).resolves.toMatchObject({ kind: "done" });+ await expect(stream.nextTurn()).rejects.toThrow("closed before reaching a turn boundary");+ } finally {+ stream.dispose();+ if ((await driver.status) === "running") await driver.cancel();+ }+ });+ });+ it("expires after the renewed configured lifetime", async () => {+ const runtime = await createTestRuntime({ agent: { name: "legacy-timeout" } });+ await runtime.run(async () => {+ const driver = await start(legacySessionDriverWorkflow, [+ { alias: "", inboxVersion: 7, sessionTimeoutMs: 1, serializedContext: legacyContext() },+ ]);+ const stream = captureTurnEvents(driver);+ try {+ await waitForHook(driver, { token: `eve:session:${driver.runId}:inbox` });+ await resumeSessionInbox(+ { sessionId: driver.runId },+ { kind: "send", payload: { message: "Alice continues the conversation." } },+ );+ const events = await stream.nextTurn();+ if (!events.some((event) => event.type === "session.completed"))+ events.push(...(await stream.nextTurn()));+ expect(filterEventsByType(events, "session.completed")).toHaveLength(1);+ await expect(driver.returnValue).resolves.toMatchObject({ kind: "done" });+ } finally {+ stream.dispose();+ if ((await driver.status) === "running") await driver.cancel();+ }+ });+ });+});+function legacyContext() {+ return {+ "eve.auth": null,+ "eve.bundle": { source: createBundledRuntimeCompiledArtifactsSource() },+ "eve.channel": { kind: "http", state: {} },+ "eve.mode": "conversation",+ };+}diff --git a/packages/eve/src/execution/legacy-session/inbox.test.ts b/packages/eve/src/execution/legacy-session/inbox.test.tsnew file mode 100644index 000000000..8cb38dab4--- /dev/null+++ b/packages/eve/src/execution/legacy-session/inbox.test.ts@@ -0,0 +1,71 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";+import { sessionInboxHookToken } from "#execution/session-inbox/address.js";+import { sessionCommandHookToken } from "#execution/session-inbox/address.js";+import { encodeLegacyCommand, resumeLegacyInbox, UnsupportedLegacySessionError } from "./inbox.js";+const { get, resume } = vi.hoisted(() => ({ get: vi.fn(), resume: vi.fn() }));+vi.mock("#internal/workflow/runtime.js", () => ({ getHookByToken: get, resumeHook: resume }));+beforeEach(() => {+ get.mockReset();+ resume.mockReset();+});+describe("legacy ingress", () => {+ it.each([1, 2, 3, 4, 5, 6, 7])("encodes generation %s", (version) => {+ const value = encodeLegacyCommand(+ {+ kind: "send",+ payload: { message: "Alice continues." },+ delivery: {+ acceptedDeploymentId: "new",+ channelKind: "http",+ channelName: "test",+ deliveryId: "delivery",+ },+ },+ version,+ );+ expect(value).toMatchObject({+ kind: "deliver",+ version,+ payload: { message: "Alice continues." },+ payloads: [{ message: "Alice continues." }],+ });+ if (version >= 3)+ expect(value).toHaveProperty("deliveryMetadata.0.acceptedDeploymentId", "new");+ else expect(value).not.toHaveProperty("deliveryMetadata.0.acceptedDeploymentId");+ });+ it.each([undefined, 0])("rejects unversioned inbox generation %s", (version) => {+ const command = { kind: "send" as const, payload: { message: "hello" } };+ expect(() => encodeLegacyCommand(command, version)).toThrow(UnsupportedLegacySessionError);+ });+ it("routes an old alias to its imported owner before writing", async () => {+ const token = sessionInboxHookToken(sessionCommandHookToken("old"));+ get.mockImplementation(async (name: string) =>+ name === "slack:old"+ ? { runId: "old", token: name, metadata: { sessionInboxWireVersion: 7 } }+ : { runId: "new", token, metadata: { sessionId: "old" } },+ );+ resume.mockResolvedValue({ runId: "new" });+ const receipt = await resumeLegacyInbox("slack:old", { kind: "clear" });+ expect(resume).toHaveBeenCalledExactlyOnceWith(token, { kind: "clear" });+ await expect(receipt.sessionId).resolves.toBe("old");+ });+ it("delivers to an original driver when it has not imported yet", async () => {+ get.mockImplementation(async (token: string) => {+ if (token.startsWith("eve:inbox:")) throw new HookNotFoundError(token);+ return { runId: "old", token, metadata: { sessionInboxWireVersion: 7 } };+ });+ resume.mockResolvedValue({ runId: "old" });+ await resumeLegacyInbox("slack:old", { kind: "send", payload: { message: "hello" } });+ expect(resume).toHaveBeenCalledExactlyOnceWith(+ "slack:old",+ expect.objectContaining({ kind: "deliver", version: 7 }),+ );+ });+ it("does not retry ambiguous delivery errors", async () => {+ get.mockResolvedValue({ runId: "old", token: "alias", metadata: {} });+ resume.mockRejectedValue(new Error("accepted but wake failed"));+ await expect(resumeLegacyInbox("alias", { kind: "clear" })).rejects.toThrow("wake failed");+ expect(resume).toHaveBeenCalledOnce();+ });+});diff --git a/packages/eve/src/execution/legacy-session/inbox.ts b/packages/eve/src/execution/legacy-session/inbox.tsnew file mode 100644index 000000000..dc3d73bbc--- /dev/null+++ b/packages/eve/src/execution/legacy-session/inbox.ts@@ -0,0 +1,137 @@+import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";+import type {+ DeliverHookPayload,+ SessionCommand,+ SessionTimeoutHookPayload,+} from "#channel/types.js";+import { coalesceDeliverPayloads } from "#execution/deliver-payloads.js";+import {+ sessionCommandHookToken,+ sessionInboxHookToken,+} from "#execution/session-inbox/address.js";+import { getHookByToken, resumeHook } from "#internal/workflow/runtime.js";+import { isObject } from "#shared/guards.js";++type Command = DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload;+type Hook = Awaited<ReturnType<typeof getHookByToken>>;++/** Reported as an inactive session so the channel starts a fresh one. */+export class UnsupportedLegacySessionError extends Error {+ constructor() {+ super("This session predates eve 0.45 and cannot be continued. Start a new session.");+ this.name = "UnsupportedLegacySessionError";+ }+}++/**+ * Oldest driver wire version still accepted. Drivers started before eve 0.45+ * used an unversioned envelope; those sessions report themselves inactive so+ * the channel starts a fresh session instead of misdelivering.+ */+const MIN_LEGACY_WIRE_VERSION = 1;+const MAX_LEGACY_WIRE_VERSION = 7;++/**+ * Finds the pre-cutover hook for a logical token. Once that session has been+ * imported, its current-generation inbox owns delivery and `current` is true.+ */+export async function resolveLegacyInbox(+ token: string,+): Promise<{ hook: Hook; sessionId: string; current: boolean }> {+ const legacy = await getHookByToken(token);+ const metadata = await legacy.metadata;+ const sessionId =+ isObject(metadata) && typeof metadata.sessionId === "string"+ ? metadata.sessionId+ : legacy.runId;+ try {+ const hook = await getHookByToken(sessionInboxHookToken(sessionCommandHookToken(sessionId)));+ return { hook, sessionId, current: true };+ } catch (error) {+ if (!HookNotFoundError.is(error)) throw error;+ return { hook: legacy, sessionId, current: false };+ }+}++export async function resumeLegacyInbox(token: string, command: Command) {+ const target = await resolveLegacyInbox(token);+ let payload: unknown = command;+ if (!target.current) {+ const metadata = await target.hook.metadata;+ payload = encodeLegacyCommand(+ command,+ isObject(metadata) ? metadata.sessionInboxWireVersion : undefined,+ );+ }+ const hook = await resumeHook(target.hook.token, payload);+ return { ownerRunId: hook.runId, sessionId: Promise.resolve(target.sessionId) };+}++/** Frozen producer projection for driver wire versions 1–7; old consumers validate for themselves. */+export function encodeLegacyCommand(command: Command, declaredVersion: unknown): unknown {+ const version = declaredVersion;+ if (+ typeof version !== "number" ||+ !Number.isInteger(version) ||+ version < MIN_LEGACY_WIRE_VERSION ||+ version > MAX_LEGACY_WIRE_VERSION+ ) {+ throw new UnsupportedLegacySessionError();+ }+ if (command.kind !== "send" && command.kind !== "deliver") {+ const value: Record<string, unknown> = { ...command, version };+ if (command.kind === "cancel" && version < 6) {+ if (command.tasks === true)+ throw new Error("This session cannot cancel owned tasks before import.");+ delete value.tasks;+ }+ return value;+ }+ const payloads = (command.kind === "send" ? [command.payload] : command.payloads).map(+ (payload) => {+ if (payload.task === undefined || version >= 5) return payload;+ const {+ agentRequests: _agentRequests,+ inputRequests: _inputRequests,+ ...task+ } = payload.task;+ return { ...payload, task };+ },+ );+ let caller = command.caller;+ if (caller?.activityObserver !== undefined && version < 7) {+ const { activityObserver, ...rest } = caller;+ if (version < 2) caller = rest;+ else {+ const workIdentity =+ activityObserver.workIdentity === undefined+ ? undefined+ : { ...activityObserver.workIdentity };+ if (workIdentity !== undefined) delete workIdentity.label;+ caller = { ...rest, activityObserver: { ...activityObserver, workIdentity } };+ }+ }+ let deliveryMetadata =+ command.kind === "send"+ ? command.delivery === undefined+ ? undefined+ : [{ ...command.delivery, payloadIndex: 0 }]+ : command.deliveryMetadata;+ if (version < 3 && deliveryMetadata !== undefined) {+ deliveryMetadata = deliveryMetadata.map(+ ({ acceptedDeploymentId: _deployment, ...metadata }) => metadata,+ );+ }+ return {+ auth: command.auth,+ caller,+ deliveryMetadata,+ kind: "deliver",+ payload: coalesceDeliverPayloads(payloads),+ payloads,+ requestId: command.requestId,+ taskDeliveryId: command.taskDeliveryId,+ turnPolicy: command.turnPolicy,+ version,+ };+}diff --git a/packages/eve/src/execution/legacy-session/input.test.ts b/packages/eve/src/execution/legacy-session/input.test.tsnew file mode 100644index 000000000..f1ced2aa6--- /dev/null+++ b/packages/eve/src/execution/legacy-session/input.test.ts@@ -0,0 +1,69 @@+import { describe, expect, it } from "vitest";+import { readLegacyTurnInput } from "./input.js";+const step = {+ parentWritable: {},+ sessionState: { sessionId: "old" },+ serializedContext: {},+ input: { kind: "deliver", payloads: [{ message: "Alice asks to continue." }] },+};+describe("legacy turn input", () => {+ it.each([1, 2])("imports version %s", (version) => {+ expect(+ readLegacyTurnInput({+ version,+ stepInput: step,+ completionToken: "old:turn:0",+ mode: "conversation",+ }).delivery,+ ).toEqual(step.input);+ });+ it("rejects an unversioned driver input", () => {+ expect(() =>+ readLegacyTurnInput({+ ...step,+ delivery: step.input,+ completionToken: "old:turn:0",+ mode: "conversation",+ }),+ ).toThrow("Unsupported legacy turn input version.");+ });+ it("adopts a committed inline step without appending its input again", () => {+ const committed = {+ sessionState: { sessionId: "old", snapshot: "committed" },+ serializedContext: { committed: true },+ };+ const input = readLegacyTurnInput({+ version: 2,+ stepInput: step,+ completionToken: "old:turn:0",+ mode: "conversation",+ initialStep: { beforeStep: step, result: committed },+ });+ expect(input.sessionState).toEqual(committed.sessionState);+ expect(input.serializedContext).toEqual(committed.serializedContext);+ expect(input.delivery).toBeUndefined();+ });+ it("uses the final committed checkpoint instead of the earlier background-task checkpoint", () => {+ const finalState = { sessionId: "old", snapshot: "final" };+ const input = readLegacyTurnInput({+ version: 2,+ stepInput: step,+ completionToken: "old:turn:0",+ mode: "conversation",+ initialStep: {+ result: {+ action: "park",+ sessionState: finalState,+ serializedContext: { final: true },+ backgroundTaskState: { sessionId: "old", snapshot: "before" },+ },+ },+ });+ expect(input.sessionState).toEqual(finalState);+ expect(input.delivery).toBeUndefined();+ });+ it("rejects unknown formats before publishing an owner", () => {+ expect(() => readLegacyTurnInput({ version: 3 })).toThrow("Unsupported");+ expect(() => readLegacyTurnInput({ version: 2 })).toThrow("Invalid");+ });+});diff --git a/packages/eve/src/execution/legacy-session/input.ts b/packages/eve/src/execution/legacy-session/input.tsnew file mode 100644index 000000000..d96524e0c--- /dev/null+++ b/packages/eve/src/execution/legacy-session/input.ts@@ -0,0 +1,75 @@+import type { DeliverHookPayload, SessionCapabilities } from "#channel/types.js";+import type { AgentWorkflowRetentionDefinition } from "#shared/agent-definition.js";+import type { RunMode } from "#shared/run-mode.js";+import { isObject } from "#shared/guards.js";++export interface LegacyTurnInput {+ readonly completionToken: string;+ readonly capabilities?: SessionCapabilities;+ readonly mode: RunMode;+ readonly retention?: AgentWorkflowRetentionDefinition;+ readonly sessionWritable: WritableStream<Uint8Array>;+ readonly serializedContext: Record<string, unknown>;+ readonly sessionState: Record<string, unknown> & { sessionId: string };+ /** Only an uncommitted `deliver` continues as the first turn; controls and results were the driver's. */+ readonly delivery: DeliverHookPayload | undefined;+ readonly inputCommitted: boolean;+}++/** Reads a versioned turn-workflow input from a pre-cutover driver (eve 0.45 – 0.55). */+export function readLegacyTurnInput(value: unknown): LegacyTurnInput {+ if (!isObject(value) || (value.version !== 1 && value.version !== 2))+ throw new Error("Unsupported legacy turn input version.");+ const step = value.stepInput;+ if (+ !isObject(step) ||+ typeof value.completionToken !== "string" ||+ !value.completionToken ||+ (value.mode !== "conversation" && value.mode !== "task")+ )+ throw new Error("Invalid legacy turn input.");+ const committed =+ isObject(value.initialStep) && isObject(value.initialStep.result)+ ? value.initialStep.result+ : undefined;+ const state =+ (committed?.action === "cancelled" ? committed.backgroundTaskState : undefined) ??+ committed?.sessionState ??+ committed?.backgroundTaskState ??+ step.sessionState;+ const context =+ committed?.serializedContext ?? committed?.backgroundTaskContext ?? step.serializedContext;+ if (+ !isObject(state) ||+ typeof state.sessionId !== "string" ||+ !state.sessionId ||+ !isObject(context) ||+ step.parentWritable === undefined+ )+ throw new Error("Legacy turn input has no session checkpoint or output stream.");+ const delivery = step.input;+ if (+ committed === undefined &&+ delivery !== undefined &&+ (!isObject(delivery) ||+ !["deliver", "clear", "compact", "runtime-action-result"].includes(String(delivery.kind)) ||+ (delivery.kind === "deliver" && !Array.isArray(delivery.payloads)))+ )+ throw new Error("Unsupported legacy turn delivery.");+ const uncommittedDelivery =+ committed === undefined && isObject(delivery) && delivery.kind === "deliver"+ ? (delivery as DeliverHookPayload | Record<string, unknown>)+ : undefined;+ return {+ completionToken: value.completionToken,+ mode: value.mode,+ capabilities: value.capabilities as SessionCapabilities | undefined,+ retention: value.retention as AgentWorkflowRetentionDefinition | undefined,+ // The former driver's wire field; the stream is the session's, not a parent's.+ sessionWritable: step.parentWritable as WritableStream<Uint8Array>,+ serializedContext: context,+ sessionState: state as LegacyTurnInput["sessionState"],+ delivery: uncommittedDelivery as DeliverHookPayload | undefined,+ inputCommitted: committed !== undefined,+ };+}diff --git a/packages/eve/src/execution/legacy-session/interrupt-step.test.ts b/packages/eve/src/execution/legacy-session/interrupt-step.test.tsnew file mode 100644index 000000000..389fdcb8d--- /dev/null+++ b/packages/eve/src/execution/legacy-session/interrupt-step.test.ts@@ -0,0 +1,88 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { EntityConflictError } from "#compiled/@workflow/errors/index.js";+import { interruptLegacySessionStep } from "./interrupt-step.js";+import { importConversation } from "./snapshot.js";+import type { PreparedLegacySession } from "./prepare-step.js";+import { isInboxToolResultFromRecordedWorkflowToolRun } from "#harness/workflow-tool-runs.js";+const mocks = vi.hoisted(() => ({ cancel: vi.fn(), children: vi.fn(), settle: vi.fn() }));+vi.mock("#internal/workflow/runtime.js", () => ({+ cancelRun: mocks.cancel,+ getWorld: async () => ({}),+}));+vi.mock("#execution/terminate-child-sessions-step.js", () => ({+ terminateChildSessionsStep: mocks.children,+}));+vi.mock("#execution/settle-cancelled-turn-step.js", () => ({+ settleCancelledTurnStep: mocks.settle,+}));+beforeEach(() => vi.resetAllMocks());+function fixture(turnId = ""): PreparedLegacySession {+ const session = {+ sessionId: "original",+ continuationToken: "",+ history: [],+ agent: { system: "old" },+ state: {+ "eve.runtime.workflowToolRuns": [+ { runId: "tool-run", callId: "call", toolName: "tool", hookToken: "tool-hook" },+ ],+ "eve.harness.emission": { sessionStarted: true, turnId, sequence: 4, stepIndex: 2 },+ },+ };+ return {+ originalSession: session,+ sessionState: importConversation(session),+ serializedContext: {},+ sessionTimeoutMs: false,+ deploymentId: "new",+ input: {+ retention: undefined,+ mode: "conversation",+ completionToken: "old:completion",+ sessionWritable: new WritableStream(),+ serializedContext: {},+ sessionState: { sessionId: "original" },+ delivery: undefined,+ inputCommitted: false,+ },+ };+}+describe("legacy pending work", () => {+ it("cancels discoverable runs and leaves their late results without an owner", async () => {+ const prepared = fixture();+ const result = await interruptLegacySessionStep(prepared);+ expect(mocks.children).toHaveBeenCalledOnce();+ expect(mocks.cancel).toHaveBeenCalledExactlyOnceWith({}, "tool-run", {+ cancelReason: "Session upgraded",+ });+ expect(result.sessionState.snapshot.session.state).not.toHaveProperty(+ "eve.runtime.workflowToolRuns",+ );+ expect(+ isInboxToolResultFromRecordedWorkflowToolRun(result.sessionState.snapshot.session.state, {+ kind: "tool-result",+ callId: "call",+ toolName: "tool",+ output: "late",+ }),+ ).toBe(false);+ expect(mocks.settle).not.toHaveBeenCalled();+ });+ it("settles an open turn once after stopping its work", async () => {+ const prepared = fixture("turn_4");+ mocks.settle.mockResolvedValue({ sessionState: prepared.sessionState, serializedContext: {} });+ await interruptLegacySessionStep(prepared);+ expect(mocks.settle).toHaveBeenCalledExactlyOnceWith({+ sessionWritable: prepared.input.sessionWritable,+ sessionState: prepared.sessionState,+ serializedContext: {},+ });+ expect(mocks.cancel.mock.invocationCallOrder[0]).toBeLessThan(+ mocks.settle.mock.invocationCallOrder[0]!,+ );+ });+ it("tolerates work that finished while the import was being prepared", async () => {+ mocks.cancel.mockRejectedValue(new EntityConflictError("already finished"));+ await expect(interruptLegacySessionStep(fixture())).resolves.toBeDefined();+ });+});diff --git a/packages/eve/src/execution/legacy-session/interrupt-step.ts b/packages/eve/src/execution/legacy-session/interrupt-step.tsnew file mode 100644index 000000000..6d136bf9f--- /dev/null+++ b/packages/eve/src/execution/legacy-session/interrupt-step.ts@@ -0,0 +1,86 @@+import {+ EntityConflictError,+ RunExpiredError,+ WorkflowRunNotFoundError,+} from "#compiled/@workflow/errors/index.js";+import { isObject } from "#shared/guards.js";+import { createLogger, logError } from "#internal/logging.js";+import { walkCauseChain } from "#shared/errors.js";+import { cancelRun, getWorld } from "#internal/workflow/runtime.js";+import { getWorkflowToolRuns } from "#harness/workflow-tool-runs.js";+import { terminateChildSessionsStep } from "#execution/terminate-child-sessions-step.js";+import { settleCancelledTurnStep } from "#execution/settle-cancelled-turn-step.js";+import type { PreparedLegacySession } from "./prepare-step.js";++/** Only the elected importer may stop work or append cancellation events. */+export async function interruptLegacySessionStep(prepared: PreparedLegacySession) {+ "use step";+ const originalState = {+ ...prepared.sessionState,+ snapshot: {+ session: {+ ...prepared.originalSession,+ history: prepared.sessionState.snapshot.session.history,+ },+ },+ };+ try {+ await terminateChildSessionsStep({+ sessionState: originalState,+ serializedContext: prepared.serializedContext,+ });+ } catch (error) {+ logError(+ createLogger("execution.legacy-session"),+ "could not cooperatively stop legacy children",+ error,+ );+ }+ const world = await getWorld();+ const state = prepared.originalSession.state;+ const runIds = new Set(getWorkflowToolRuns(state).map((run) => run.runId));+ const handles = state?.["eve.agent.handles"];+ if (isObject(handles) && Array.isArray(handles.handles)) {+ for (const handle of handles.handles) {+ if (+ isObject(handle) &&+ isObject(handle.address) &&+ (handle.address.kind === "agent/local" || handle.address.kind === "agent/self") &&+ typeof handle.address.sessionId === "string"+ )+ runIds.add(handle.address.sessionId);+ }+ }+ const tasks = state?.["eve.tasks"];+ if (isObject(tasks) && Array.isArray(tasks.tasks)) {+ for (const task of tasks.tasks) {+ if (isObject(task) && typeof task.taskRunId === "string") runIds.add(task.taskRunId);+ }+ }+ for (const runId of runIds) {+ if (!runId || runId === prepared.sessionState.sessionId) continue;+ try {+ await cancelRun(world, runId, { cancelReason: "Session upgraded" });+ } catch (error) {+ if (+ ![...walkCauseChain(error)].some(+ (cause) =>+ EntityConflictError.is(cause) ||+ RunExpiredError.is(cause) ||+ WorkflowRunNotFoundError.is(cause),+ )+ )+ throw error;+ }+ }+ if (prepared.input.inputCommitted || prepared.sessionState.emissionState.turnId === "")+ return {+ sessionState: prepared.sessionState,+ serializedContext: prepared.serializedContext,+ };+ return await settleCancelledTurnStep({+ sessionWritable: prepared.input.sessionWritable,+ serializedContext: prepared.serializedContext,+ sessionState: prepared.sessionState,+ });+}diff --git a/packages/eve/src/execution/legacy-session/prepare-step.test.ts b/packages/eve/src/execution/legacy-session/prepare-step.test.tsnew file mode 100644index 000000000..d2789335c--- /dev/null+++ b/packages/eve/src/execution/legacy-session/prepare-step.test.ts@@ -0,0 +1,67 @@+import { DEFAULT_SESSION_TIMEOUT_MS } from "#execution/session/timeout.js";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { prepareLegacySessionStep } from "./prepare-step.js";+const mocks = vi.hoisted(() => ({ run: vi.fn(), hydrate: vi.fn(), encryption: vi.fn() }));+vi.mock("#internal/workflow/runtime.js", () => ({+ getWorld: async () => ({ runs: { get: mocks.run }, getDeploymentId: async () => "new" }),+ resolveRunEncryptionKey: mocks.encryption,+}));+vi.mock("#compiled/@workflow/core/serialization.js", () => ({+ hydrateWorkflowArguments: mocks.hydrate,+}));+const session = {+ sessionId: "original",+ continuationToken: "alias",+ history: [],+ agent: { system: "old" },+};+const input = {+ completionToken: "original:turn",+ mode: "task",+ version: 2,+ stepInput: {+ input: { kind: "deliver", payloads: [] },+ parentWritable: {},+ sessionState: { sessionId: "original", snapshot: { version: 1, session } },+ serializedContext: {+ "eve.sessionCallback": { url: "https://example.com/callback" },+ "eve.channel": {+ kind: "subagent",+ state: { parentContinuationToken: "parent", callId: "call" },+ },+ "app.identity": "Alice",+ },+ },+};+beforeEach(() => {+ vi.resetAllMocks();+ mocks.run.mockResolvedValue({+ runId: "original",+ input: "encrypted",+ createdAt: new Date(500),+ startedAt: new Date(1000),+ });+ mocks.encryption.mockResolvedValue("key");+ vi.stubEnv("VERCEL_DEPLOYMENT_ID", "new");+});+afterEach(() => vi.unstubAllEnvs());+describe("legacy session preparation", () => {+ it.each([false, 5000, undefined])(+ "retains the configured timeout duration (%s)",+ async (sessionTimeoutMs) => {+ mocks.hydrate.mockResolvedValue([{ sessionTimeoutMs, retention: 0 }]);+ const result = await prepareLegacySessionStep(input);+ expect(result.input.retention).toBe(0);+ expect(mocks.hydrate).toHaveBeenCalledWith("encrypted", "original", "key");+ expect(result.sessionTimeoutMs).toBe(sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS);+ expect(result.serializedContext).toMatchObject({+ "eve.sessionId": "original",+ "eve.sessionInbox": { sessionId: "original" },+ "app.identity": "Alice",+ "eve.channel": { state: { parentContinuationToken: "", callId: "call" } },+ });+ expect(result.serializedContext).not.toHaveProperty("eve.sessionCallback");+ expect(result.input.serializedContext).toEqual(input.stepInput.serializedContext);+ },+ );+});diff --git a/packages/eve/src/execution/legacy-session/prepare-step.ts b/packages/eve/src/execution/legacy-session/prepare-step.tsnew file mode 100644index 000000000..7f2983aba--- /dev/null+++ b/packages/eve/src/execution/legacy-session/prepare-step.ts@@ -0,0 +1,58 @@+import { hydrateWorkflowArguments } from "#compiled/@workflow/core/serialization.js";+import { getWorld, resolveRunEncryptionKey } from "#internal/workflow/runtime.js";+import { DEFAULT_SESSION_TIMEOUT_MS } from "#execution/session/timeout.js";+import { readLegacyTurnInput, type LegacyTurnInput } from "./input.js";+import { readLegacySnapshot, importConversation } from "./snapshot.js";+import { SESSION_INBOX_CONTEXT_KEY } from "#execution/session-inbox/address.js";+import { isObject } from "#shared/guards.js";++/** Persist the import before publishing its current-generation inbox. */+export async function prepareLegacySessionStep(rawInput: unknown) {+ "use step";+ const input = readLegacyTurnInput(rawInput);+ const originalSession = readLegacySnapshot(input.sessionState);+ const sessionState = importConversation(originalSession);+ const world = await getWorld();+ const run = await world.runs.get(sessionState.sessionId);+ const args: unknown = await hydrateWorkflowArguments(+ run.input,+ run.runId,+ await resolveRunEncryptionKey(world, run),+ );+ const driverInput = Array.isArray(args) && isObject(args[0]) ? args[0] : undefined;+ if (driverInput === undefined) throw new Error("Cannot read the original session timeout.");+ const timeout = driverInput.sessionTimeoutMs;+ if (+ timeout !== undefined &&+ timeout !== false &&+ (typeof timeout !== "number" || !Number.isFinite(timeout) || timeout < 0)+ )+ throw new Error("Invalid original session timeout.");+ const sessionTimeoutMs = timeout ?? DEFAULT_SESSION_TIMEOUT_MS;+ const serializedContext: Record<string, unknown> = {+ ...input.serializedContext,+ "eve.sessionId": sessionState.sessionId,+ [SESSION_INBOX_CONTEXT_KEY]: { sessionId: sessionState.sessionId },+ };+ delete serializedContext["eve.sessionCallback"];+ const channel = serializedContext["eve.channel"];+ if (isObject(channel) && channel.kind === "subagent" && isObject(channel.state)) {+ serializedContext["eve.channel"] = {+ ...channel,+ state: { ...channel.state, parentContinuationToken: "" },+ };+ }+ return {+ input: {+ ...input,+ retention: input.retention ?? (driverInput.retention as LegacyTurnInput["retention"]),+ },+ originalSession,+ sessionState,+ serializedContext,+ sessionTimeoutMs: sessionTimeoutMs as number | false,+ deploymentId: process.env.VERCEL_DEPLOYMENT_ID?.trim() || (await world.getDeploymentId()),+ };+}+export type PreparedLegacySession = Awaited<ReturnType<typeof prepareLegacySessionStep>>;+export type { LegacyTurnInput };diff --git a/packages/eve/src/execution/legacy-session/snapshot.test.ts b/packages/eve/src/execution/legacy-session/snapshot.test.tsnew file mode 100644index 000000000..e1efb681f--- /dev/null+++ b/packages/eve/src/execution/legacy-session/snapshot.test.ts@@ -0,0 +1,91 @@+import { describe, expect, it } from "vitest";+import { importConversation, normalizeHistory } from "./snapshot.js";+import type { LegacySession } from "./snapshot.js";+describe("conversation import", () => {+ it("preserves authored state, budget, emission coordinates and storage", () => {+ const session: LegacySession = {+ sessionId: "old",+ continuationToken: "slack:thread",+ history: [{ role: "user", content: "Alice chose blue." }],+ agent: { system: "old prompt" },+ limits: { maxInputTokensPerSession: 40 },+ sandboxState: { initialized: false, session: null },+ state: {+ "app.color": "blue",+ "eve.runtime.pendingCoordinationBatch": { callId: "old" },+ "eve.agent.handles": { handles: [] },+ "eve.harness.turnUsage": { session: { inputTokens: 42 } },+ "eve.harness.emission": {+ sequence: 9,+ stepIndex: 3,+ turnId: "turn_8",+ sessionStarted: true,+ },+ },+ };+ const result = importConversation(session);+ expect(result.snapshot.session).toMatchObject({+ sessionId: "old",+ limits: session.limits,+ sandboxState: session.sandboxState,+ state: {+ "app.color": "blue",+ "eve.harness.turnUsage": session.state!["eve.harness.turnUsage"],+ },+ });+ expect(result.snapshot.session.state).not.toHaveProperty(+ "eve.runtime.pendingCoordinationBatch",+ );+ expect(result.snapshot.session.state).not.toHaveProperty("eve.agent.handles");+ expect(result.emissionState.sequence).toBe(9);+ expect(result.snapshot.session.history[0]).toMatchObject({+ kind: "user",+ content: "Alice chose blue.",+ });+ });+ it("settles unfinished tool calls without repeating completed calls", () => {+ const history = normalizeHistory([+ {+ role: "assistant",+ content: [+ { type: "tool-call", toolCallId: "a", toolName: "work", input: {} },+ { type: "tool-call", toolCallId: "b", toolName: "work", input: {} },+ ],+ },+ {+ role: "tool",+ content: [+ {+ type: "tool-result",+ toolCallId: "a",+ toolName: "work",+ output: { type: "text", value: "done" },+ },+ ],+ },+ { role: "user", content: "Bob asks for an update." },+ ]);+ expect(history).toHaveLength(4);+ expect(history[2]).toMatchObject({+ role: "tool",+ content: [{ toolCallId: "b", output: { type: "error-text" } }],+ });+ expect(history[3]).toMatchObject({ role: "user", content: "Bob asks for an update." });+ });+ it("removes abandoned approval requests and settles their tool calls", () => {+ const history = normalizeHistory([+ {+ role: "assistant",+ content: [+ { type: "tool-call", toolCallId: "call", toolName: "work", input: {} },+ { type: "tool-approval-request", approvalId: "approval", toolCallId: "call" },+ ],+ },+ ]);+ expect(JSON.stringify(history)).not.toContain("approval");+ expect(history[1]).toMatchObject({+ role: "tool",+ content: [{ toolCallId: "call", output: { type: "error-text" } }],+ });+ });+});diff --git a/packages/eve/src/execution/legacy-session/snapshot.ts b/packages/eve/src/execution/legacy-session/snapshot.tsnew file mode 100644index 000000000..066de0268--- /dev/null+++ b/packages/eve/src/execution/legacy-session/snapshot.ts@@ -0,0 +1,104 @@+import type { ModelMessage } from "ai";+import { getHarnessEmissionState } from "#harness/emission.js";+import { isUserMessageKind, validateHarnessModelMessages } from "#harness/messages.js";+import type { DurableSession, DurableSessionState } from "#execution/durable-session-store.js";+import { isObject } from "#shared/guards.js";++export type LegacySession = Omit<DurableSession, "history"> & { readonly history: ModelMessage[] };++const PRESERVED_FRAMEWORK_STATE = new Set([+ "eve.harness.emission",+ "eve.harness.turnUsage",+ "eve.harness.reportedSessionUsage",+ "eve.harness.sessionRuntimeTokenLimit",+]);++/** Reads the driver's embedded snapshot; every supported driver carries one. */+export function readLegacySnapshot(+ state: Record<string, unknown> & { sessionId: string },+): LegacySession {+ const snapshot = state.snapshot;+ if (+ !isObject(snapshot) ||+ snapshot.version !== 1 ||+ !isObject(snapshot.session) ||+ snapshot.session.sessionId !== state.sessionId ||+ !Array.isArray(snapshot.session.history)+ )+ throw new Error("Unsupported legacy session snapshot.");+ const session: unknown = snapshot.session;+ return session as LegacySession;+}++/** Keep committed conversation data, but no pre-cutover execution registries. */+export function importConversation(session: LegacySession): DurableSessionState {+ const state = Object.fromEntries(+ Object.entries(session.state ?? {}).filter(+ ([key]) => !key.startsWith("eve.") || PRESERVED_FRAMEWORK_STATE.has(key),+ ),+ );+ const history = normalizeHistory(session.history);+ const emissionState = getHarnessEmissionState(state);+ const imported = { ...session, history, state };+ return {+ version: 1,+ sessionId: session.sessionId,+ continuationToken: session.continuationToken,+ hasProxyInputRequests: false,+ emissionState,+ snapshot: { session: imported },+ };+}++export function normalizeHistory(messages: readonly ModelMessage[]) {+ const history: ModelMessage[] = [];+ const pending = new Map<string, string>();+ const settle = () => {+ if (pending.size === 0) return;+ history.push({+ role: "tool",+ content: [...pending].map(([toolCallId, toolName]) => ({+ type: "tool-result" as const,+ toolCallId,+ toolName,+ output: {+ type: "error-text" as const,+ value: "Interrupted by the session upgrade. Start this work again if it is still needed.",+ },+ })),+ });+ pending.clear();+ };+ for (const original of messages) {+ let message = original;+ if (message.role === "assistant" && Array.isArray(message.content)) {+ message = {+ ...message,+ content: message.content.filter((part) => part.type !== "tool-approval-request"),+ };+ } else if (message.role === "tool") {+ message = {+ ...message,+ content: message.content.filter((part) => part.type !== "tool-approval-response"),+ };+ if (message.content.length === 0) continue;+ }+ if (message.role !== "tool") settle();+ if (message.role === "assistant" && Array.isArray(message.content)) {+ for (const part of message.content)+ if (part.type === "tool-call") pending.set(part.toolCallId, part.toolName);+ }+ if (message.role === "tool") {+ for (const part of message.content)+ if (part.type === "tool-result") pending.delete(part.toolCallId);+ }+ const kind = (message as { kind?: unknown }).kind;+ history.push(+ message.role === "user" && !isUserMessageKind(kind)+ ? ({ ...message, kind: "user" } as ModelMessage)+ : message,+ );+ }+ settle();+ return validateHarnessModelMessages(history);+}diff --git a/packages/eve/src/execution/legacy-session/turn-workflow.ts b/packages/eve/src/execution/legacy-session/turn-workflow.tsnew file mode 100644index 000000000..7fa622cbc--- /dev/null+++ b/packages/eve/src/execution/legacy-session/turn-workflow.ts@@ -0,0 +1,77 @@+import { isHookConflictError } from "#execution/hook-ownership.js";+import { sessionHookTokens } from "#execution/session/hook-tokens.js";+import { sessionCommandHookToken } from "#execution/session-inbox/address.js";+import { createSessionInbox } from "#execution/session-inbox/inbox.js";+import { failSession, runPreparedSession } from "#execution/session/program.js";+import { sessionTimeoutDeadline } from "#execution/session/timeout.js";+import { completeLegacyDriverStep } from "./completion-step.js";+import { interruptLegacySessionStep } from "./interrupt-step.js";+import { prepareLegacySessionStep } from "./prepare-step.js";++/**+ * Historical dispatch name. Drivers from the former driver/turn execution+ * model start this workflow for each turn. It imports the session once —+ * persisting the conversation, claiming the current-generation inbox, and+ * interrupting pending work — then runs the current owner program. The old+ * driver stays parked as the stream anchor and hears the final result.+ */+export async function turnWorkflow(rawInput: unknown): Promise<void> {+ "use workflow";+ const prepared = await prepareLegacySessionStep(rawInput);+ const { sessionId } = prepared.sessionState;+ const inbox = createSessionInbox(sessionId);+ try {+ await inbox.claimSessionHook(sessionCommandHookToken(sessionId));+ } catch (error) {+ // Another importer already owns this session; its driver will hear from it.+ if (isHookConflictError(error)) return;+ throw error;+ }+ const { mode, sessionWritable } = prepared.input;+ let interrupted;+ try {+ await inbox.claimSessionHooks(sessionHookTokens(prepared));+ interrupted = await interruptLegacySessionStep(prepared);+ } catch (error) {+ await inbox.dispose();+ return await failSession({+ error,+ mode,+ serializedContext: prepared.serializedContext,+ sessionId,+ sessionState: prepared.sessionState,+ sessionWritable,+ });+ }+ await runPreparedSession(+ {+ anchor: {+ kind: "self",+ notify: (result) =>+ completeLegacyDriverStep({+ completionToken: prepared.input.completionToken,+ result,+ serializedContext: prepared.serializedContext,+ sessionState: prepared.sessionState,+ sessionWritable,+ }),+ },+ caller: undefined,+ capabilities: prepared.input.capabilities,+ deploymentId: prepared.deploymentId,+ initialInput:+ prepared.input.delivery === undefined+ ? undefined+ : { ...prepared.input.delivery, caller: undefined },+ mode,+ retention: prepared.input.retention,+ serializedContext: interrupted.serializedContext,+ sessionId,+ sessionState: interrupted.sessionState,+ sessionTimeoutMs: prepared.sessionTimeoutMs,+ sessionTimeoutDeadline: sessionTimeoutDeadline(prepared.sessionTimeoutMs, Date.now()),+ sessionWritable,+ },+ inbox,+ );+}diff --git a/packages/eve/src/execution/model-call-batching.ts b/packages/eve/src/execution/model-call-batching.tsindex 49e54de0b..001b24c8d 100644--- a/packages/eve/src/execution/model-call-batching.ts+++ b/packages/eve/src/execution/model-call-batching.ts@@ -1,4 +1,4 @@-import { derivePendingState } from "#execution/pending-turn-state.js";+import { derivePendingState } from "#execution/session/pending-turn-state.js";import type { HarnessSession, StepInput, StepResult } from "#harness/types.js";export async function runModelCallBatch(input: {diff --git a/packages/eve/src/execution/next-driver-action.ts b/packages/eve/src/execution/next-driver-action.tsdeleted file mode 100644index 3835b0167..000000000--- a/packages/eve/src/execution/next-driver-action.ts+++ /dev/null@@ -1,93 +0,0 @@-/**- * Closed-contract dispatch surface between session-mutating step bodies- * (the accepting deployment when stamped, otherwise the driver's deployment)- * and the durable driver workflow (pinned to whichever deployment called- * `start()`).- *- * The driver matches on `kind` and follows a fixed playbook per arm.- * Adding a new arm is breaking (pinned drivers can't dispatch an- * unknown `kind`); adding optional fields inside an existing arm is- * forward-compatible because the driver passes the action through by- * reference and devalue preserves unknown POJO fields. Do not- * destructure-and-rebuild a `NextDriverAction` — full destructuring- * strips unknown fields.- */-import type { DurableSessionState } from "#execution/durable-session-store.js";-import type { SettledTurn, StepResult } from "#harness/types.js";-import type { TokenUsage } from "#shared/token-usage.js";--interface DurableStepResultFields {- /** Pre-step context plus only the observability continuation owned by background tasks. */- readonly backgroundTaskContext?: Record<string, unknown>;- readonly backgroundTaskState?: DurableSessionState;- readonly backgroundTasks?: StepResult["backgroundTasks"];- /** The guarded inline step deferred before mutating state. */- readonly requiresChildDispatch?: true;- readonly serializedContext: Record<string, unknown>;- readonly sessionState: DurableSessionState;-}--/** Result returned by a turn step to its durable driver workflow. */-export type DurableStepResult = (- | {- readonly action: "continue" | "done";- readonly output?: unknown;- readonly isError?: boolean;- readonly usage?: TokenUsage;- readonly usageDelta?: TokenUsage;- }- | { readonly action: "cancelled" }- | {- readonly action: "park";- readonly authorizationAttemptIds?: readonly string[];- readonly authorizationNames?: readonly string[];- readonly hasPendingAuthorization: boolean;- readonly hasPendingInputBatch: boolean;- readonly pendingCoordinationCallIds?: readonly string[];- readonly settled?: SettledTurn;- }-) &- DurableStepResultFields;--/** Discriminated union the driver workflow body dispatches on. */-export type NextDriverAction =- | {- readonly kind: "done";- readonly output: unknown;- readonly isError?: boolean;- readonly sessionState: DurableSessionState;- readonly serializedContext: Record<string, unknown>;- /** Session-total token usage spent by the completed session. */- readonly usage?: TokenUsage;- /**- * Usage the final turn added beyond what earlier settled turns already- * reported; forwarded through the same pinned-driver-safe- * optional-field pattern as `cancelled`.- */- readonly usageDelta?: TokenUsage;- }- | {- readonly kind: "park";- readonly sessionState: DurableSessionState;- readonly serializedContext: Record<string, unknown>;- readonly authorizationAttemptIds?: readonly string[];- readonly authorizationNames?: readonly string[];- /**- * Set when the parked turn was cancelled: the driver runs- * `settleCancelledTurnStep` before the normal park playbook. An- * optional field rather than a new arm so pinned drivers keep- * working.- */- readonly cancelled?: true;- /**- * Settled user-facing answer forwarded through the same pinned-driver-safe- * optional-field pattern as `cancelled`.- */- readonly settled?: SettledTurn;- }- | {- readonly kind: "dispatch-coordination";- readonly pendingCallIds: readonly string[];- readonly sessionState: DurableSessionState;- readonly serializedContext: Record<string, unknown>;- };diff --git a/packages/eve/src/execution/parked-delivery-wait.ts b/packages/eve/src/execution/parked-delivery-wait.tsdeleted file mode 100644index a2c76aab7..000000000--- a/packages/eve/src/execution/parked-delivery-wait.ts+++ /dev/null@@ -1,355 +0,0 @@-import type { DeliverHookPayload, DeliverPayload } from "#channel/types.js";-import { jsonValuesEqual } from "#shared/json.js";-import { cancelAllIndexedSessionTasksStep } from "#execution/cancel-indexed-session-tasks-step.js";-import { routeDeliverToChildren } from "#execution/route-child-delivery.js";-import type { SessionCommandInbox } from "#execution/session-command-inbox.js";-import type { SessionStateCursor } from "#execution/session-state-cursor.js";-import { reportDroppedWirePayloadStep } from "#execution/report-dropped-wire-payload-step.js";-import {- sessionInboxWire,- SessionInboxWireError,- type DecodedSessionInbox,-} from "#execution/wire/session-inbox-wire.js";-import { coalesceDeliveries } from "#harness/messages.js";-import { getSessionTaskCohorts } from "#tasks/session-task-cohorts.js";--type NextSessionAction =- | { readonly kind: "clear" }- | { readonly kind: "compact" }- | { readonly kind: "expired" }- | { readonly kind: "reset" }- | AuthorizationCallbackInstruction- | {- readonly delivery: DeliverHookPayload | null;- readonly kind: "delivery";- };--/** One authorization-callback read surfaced during a parked wait. */-export interface AuthorizationCallbackInstruction {- readonly kind: "authorization";- /** True when the authorization hook closed; no further callbacks can arrive. */- readonly closed: boolean;- readonly payloads: readonly DeliverPayload[];-}--/** What the parked driver should do with the next session activity. */-export type NextTurnInstruction =- | { readonly kind: "clear" }- | { readonly kind: "compact" }- | { readonly kind: "expired" }- | { readonly kind: "reset" }- | { readonly kind: "closed" }- | { readonly kind: "cancel-turn" }- | AuthorizationCallbackInstruction- | {- readonly kind: "turn";- readonly delivery: DeliverHookPayload;- };--/**- * Awaits the next delivery that requires driver action while the session- * is parked. Deliveries fully routed to a descendant leave the parent with- * no turn to run, so this keeps waiting until a delivery produces a parent- * turn, a cancellation, expiry, or hook closure. The wait is unbounded by- * design: a parked session lives until something addresses it.- *- * With `awaitAuthorizationCallbacks`, the inbox's authorization window stays- * open for the whole wait — including iterations that consume activity- * without producing a parent turn (no-op cancels, fully-routed descendant- * deliveries) — so an open challenge's callback surfaces as an- * `"authorization"` instruction no matter when it arrives.- *- * Routing steps mutate durable state; each transition is adopted into the- * caller-owned `stateCursor`, so returns carry only the instruction kind.- */-export async function nextTurnDelivery(input: {- readonly awaitAuthorizationCallbacks?: boolean;- readonly bufferedDeliveries: DeliverHookPayload[];- readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;- readonly cancelledTaskIds?: Set<string>;- readonly commandInbox: SessionCommandInbox;- readonly deferDeliveries?: boolean;- readonly driverWritable: WritableStream<Uint8Array>;- readonly seenTaskDeliveries?: Set<string>;- readonly stateCursor: SessionStateCursor;-}): Promise<NextTurnInstruction> {- if (input.awaitAuthorizationCallbacks !== true) {- return await awaitNextTurnDelivery(input);- }-- input.commandInbox.setAuthorizationWindow(true);- try {- return await awaitNextTurnDelivery(input);- } finally {- input.commandInbox.setAuthorizationWindow(false);- }-}--async function awaitNextTurnDelivery(input: {- readonly bufferedDeliveries: DeliverHookPayload[];- readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;- readonly cancelledTaskIds?: Set<string>;- readonly commandInbox: SessionCommandInbox;- readonly deferDeliveries?: boolean;- readonly driverWritable: WritableStream<Uint8Array>;- readonly seenTaskDeliveries?: Set<string>;- readonly stateCursor: SessionStateCursor;-}): Promise<NextTurnInstruction> {- const cancelledTaskIds = input.cancelledTaskIds ?? new Set<string>();- const seenTaskDeliveries = input.seenTaskDeliveries ?? new Set<string>();- while (true) {- const nextAction = await waitForNextSessionAction({- bufferedDeliveries: input.bufferedDeliveries,- bufferedSessionControls: input.bufferedSessionControls,- cancelledTaskIds,- commandInbox: input.commandInbox,- deferDeliveries: input.deferDeliveries,- seenTaskDeliveries,- stateCursor: input.stateCursor,- });-- if (nextAction.kind === "authorization") {- return nextAction;- }-- if (nextAction.kind !== "delivery") {- return { kind: nextAction.kind };- }-- const deliver = nextAction.delivery;- if (deliver === null) {- return { kind: "closed" };- }-- const routed = await routeDeliverToChildren({- delivery: deliver,- parentWritable: input.driverWritable,- serializedContext: input.stateCursor.serializedContext,- sessionState: input.stateCursor.sessionState,- });- input.stateCursor.adoptState(routed);-- if (routed.kind === "cancel-turn") {- return { kind: "cancel-turn" };- }-- if (routed.remainder === undefined) {- // Fully routed to a descendant; keep waiting.- continue;- }-- return { delivery: routed.remainder, kind: "turn" };- }-}--async function waitForNextSessionAction(input: {- readonly bufferedDeliveries: DeliverHookPayload[];- readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;- readonly cancelledTaskIds: Set<string>;- readonly commandInbox: SessionCommandInbox;- readonly deferDeliveries?: boolean;- readonly seenTaskDeliveries: Set<string>;- readonly stateCursor: SessionStateCursor;-}): Promise<NextSessionAction> {- const pendingSessionControl = input.bufferedSessionControls.shift();- if (pendingSessionControl !== undefined) {- return { kind: pendingSessionControl };- }-- while (true) {- if (input.deferDeliveries !== true && !input.commandInbox.hasReadyAuthorization()) {- const delivery = takeBufferedTurnDelivery(- input.bufferedDeliveries,- getSessionTaskCohorts(input.stateCursor.sessionState.snapshot?.session.state),- input.cancelledTaskIds,- );- if (delivery !== undefined) return { delivery, kind: "delivery" };- }-- const { result: first, source } = await input.commandInbox.nextWithSource();- input.commandInbox.consumeNext();-- if (source === "authorization") {- if (first.done) {- return { closed: true, kind: "authorization", payloads: [] };- }- return {- closed: false,- kind: "authorization",- payloads: first.value.kind === "deliver" ? first.value.payloads : [],- };- }-- if (first.done) {- return { delivery: null, kind: "delivery" };- }-- // Runtime-action results use the active turn's private inbox. A late value- // can still surface through an old session alias, where the driver has- // always ignored it rather than treating it as a session command.- if (first.value.kind === "runtime-action-result") {- continue;- }-- let decoded: DecodedSessionInbox;- try {- decoded = sessionInboxWire.decode(first.value);- } catch (error) {- if (!(error instanceof SessionInboxWireError)) throw error;- // A lost delivery with an operator-visible signal is the designed- // failure; reinterpreting an unknown payload is the bug. Stay parked.- await reportDroppedWirePayloadStep({ detail: error.message, family: "session-inbox" });- continue;- }-- if (decoded.kind === "session-timeout") {- return { kind: "expired" };- }-- if (decoded.kind === "clear" || decoded.kind === "compact" || decoded.kind === "reset") {- return { kind: decoded.kind };- }-- if (decoded.kind === "cancel") {- if ("tasks" in decoded && decoded.tasks === true) {- await cancelAllIndexedSessionTasksStep({- serializedContext: input.stateCursor.serializedContext,- sessionState: input.stateCursor.sessionState,- });- }- if (decoded.taskId !== undefined) {- input.cancelledTaskIds.add(decoded.taskId);- const kept = input.bufferedDeliveries.filter(- (delivery) => !isCancelledTaskDelivery(delivery, input.cancelledTaskIds),- );- input.bufferedDeliveries.splice(0, input.bufferedDeliveries.length, ...kept);- }- continue;- }-- const deliveryId = decoded.taskDeliveryId ?? decoded.caller?.taskId;- if (deliveryId !== undefined && isCancelledTaskDeliveryId(deliveryId, input.cancelledTaskIds)) {- continue;- }- if (deliveryId !== undefined) {- if (input.seenTaskDeliveries.has(deliveryId)) continue;- input.seenTaskDeliveries.add(deliveryId);- }-- input.bufferedDeliveries.push(decoded);- }-}--function isCancelledTaskDelivery(- delivery: DeliverHookPayload,- cancelledTaskIds: ReadonlySet<string>,-): boolean {- const deliveryId = delivery.taskDeliveryId ?? delivery.caller?.taskId;- return deliveryId !== undefined && isCancelledTaskDeliveryId(deliveryId, cancelledTaskIds);-}--function isCancelledTaskDeliveryId(- deliveryId: string,- cancelledTaskIds: ReadonlySet<string>,-): boolean {- return [...cancelledTaskIds].some(- (taskId) => deliveryId === taskId || deliveryId.startsWith(`${taskId}:`),- );-}--function takeBufferedTurnDelivery(- bufferedDeliveries: DeliverHookPayload[],- cohorts: ReturnType<typeof getSessionTaskCohorts>,- cancelledTaskIds: ReadonlySet<string>,-): DeliverHookPayload | undefined {- const retained = bufferedDeliveries.filter(- (delivery) => !isCancelledTaskDelivery(delivery, cancelledTaskIds),- );- bufferedDeliveries.splice(0, bufferedDeliveries.length, ...retained);-- const completed = new Set(- bufferedDeliveries.flatMap((delivery) => {- const taskId = completionTaskId(delivery);- return taskId === undefined ? [] : [taskId];- }),- );- const pendingCohorts = new Set<string>();- for (const [taskId, cohort] of cohorts) {- if (!cohort.settled && !completed.has(taskId) && !cancelledTaskIds.has(taskId)) {- pendingCohorts.add(cohort.cohortId);- }- }- let index = bufferedDeliveries.findIndex((delivery) => {- const cohort = completionCohort(delivery, cohorts);- return cohort === undefined || !pendingCohorts.has(cohort);- });- if (index < 0) return undefined;- const readyCohort = completionCohort(bufferedDeliveries[index]!, cohorts);- if (readyCohort !== undefined) {- const lastSibling = bufferedDeliveries.findLastIndex(- (delivery) => completionCohort(delivery, cohorts) === readyCohort,- );- // Settlement must apply before terminal views release its claimed handle.- // Process intervening deliveries first, then re-evaluate the cohort.- const boundary = bufferedDeliveries.findIndex(- (delivery, position) =>- position > index &&- position < lastSibling &&- completionCohort(delivery, cohorts) === undefined,- );- if (boundary >= 0) index = boundary;- }- const first = bufferedDeliveries.splice(index, 1)[0]!;- const cohort = completionCohort(first, cohorts);- if (cohort !== undefined) {- const siblings = bufferedDeliveries.filter(- (delivery) => completionCohort(delivery, cohorts) === cohort,- );- const remaining = bufferedDeliveries.filter(- (delivery) => completionCohort(delivery, cohorts) !== cohort,- );- bufferedDeliveries.splice(0, bufferedDeliveries.length, ...remaining);- return coalesceDeliveries([first, ...siblings]);- }-- const authenticated = first.auth != null && first.auth.principalType !== "anonymous";- const turnDeliveries = [first];- let caller = first.caller;- while (bufferedDeliveries.length > index) {- const next = bufferedDeliveries[index];- if (- next === undefined ||- first.taskDeliveryId !== undefined ||- next.taskDeliveryId !== undefined ||- !authenticated ||- !jsonValuesEqual(first.auth, next.auth) ||- (caller !== undefined && next.caller !== undefined)- ) {- break;- }-- const delivery = bufferedDeliveries.splice(index, 1)[0];- if (delivery === undefined) {- throw new Error("Buffered turn delivery disappeared while partitioning.");- }- turnDeliveries.push(delivery);- caller ??= delivery.caller;- }-- return coalesceDeliveries(turnDeliveries);-}--/** Only successful sibling notifications can share their existing cohort context. */-function completionCohort(- delivery: DeliverHookPayload,- cohorts: ReturnType<typeof getSessionTaskCohorts>,-): string | undefined {- const taskId = completionTaskId(delivery);- return taskId === undefined ? undefined : cohorts.get(taskId)?.cohortId;-}--function completionTaskId(delivery: DeliverHookPayload): string | undefined {- const suffix = ":ready:completed";- if (delivery.caller !== undefined || !delivery.taskDeliveryId?.endsWith(suffix)) return undefined;- return delivery.taskDeliveryId.slice(0, -suffix.length);-}diff --git a/packages/eve/src/execution/proxied-deliver-step.ts b/packages/eve/src/execution/proxied-deliver-step.tsindex 84bb5f05b..190cc8c42 100644--- a/packages/eve/src/execution/proxied-deliver-step.ts+++ b/packages/eve/src/execution/proxied-deliver-step.ts@@ -1,5 +1,5 @@-import type { SessionInboxAddress } from "#execution/wire/session-inbox-contract.js";-import type { DeliverHookPayload, DeliverPayload, SessionAuthContext } from "#channel/types.js";+import type { SessionInboxAddress } from "#execution/session-inbox/address.js";+import type { DeliverHookPayload, DeliverPayload } from "#channel/types.js";import { coalesceDeliverPayloads } from "#execution/deliver-payloads.js";import {type DurableSessionState,@@ -8,7 +8,7 @@ import {} from "#execution/durable-session-store.js";import { routeDeliverPayload } from "#subagents/hitl-proxy.js";import { sendTaskInboundPayload } from "#execution/tasks/parent/run-parent.js";-import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";+import { resumeSessionInbox } from "#execution/session-inbox/resume.js";import { resumeWorkflowToolRunAnswers } from "#execution/tools/workflow/answer.js";import type { AnswerHookRoute } from "#harness/proxy-input-requests.js";import type { InputResponse } from "#shared/input.js";@@ -31,19 +31,6 @@ export type RoutedDeliverResult =readonly sessionState: DurableSessionState;};-type LegacyRoutedDeliverResult =- | {- readonly kind: "cancel-turn";- readonly serializedContext: Record<string, unknown>;- readonly sessionState: DurableSessionState;- }- | {- readonly kind: "continue";- readonly remainder: DeliverPayload | undefined;- readonly serializedContext: Record<string, unknown>;- readonly sessionState: DurableSessionState;- };-interface ChildBucket {readonly answerHook?: AnswerHookRoute;readonly childContinuationToken: string;@@ -57,43 +44,15 @@ interface ChildBucket {}/** Splits an envelope and validates task routes before forwarding descendant input. */-export function routeProxiedDeliverStep(input: {+export async function routeProxiedDeliverStep(input: {readonly delivery: DeliverHookPayload;- readonly parentWritable: WritableStream<Uint8Array>;+ readonly sessionWritable: WritableStream<Uint8Array>;readonly serializedContext?: Record<string, unknown>;readonly sessionState: DurableSessionState;-}): Promise<RoutedDeliverResult>;-export function routeProxiedDeliverStep(input: {- readonly auth?: SessionAuthContext | null;- readonly parentWritable: WritableStream<Uint8Array>;- readonly payload: DeliverPayload;- readonly serializedContext?: Record<string, unknown>;- readonly sessionState: DurableSessionState;-}): Promise<LegacyRoutedDeliverResult>;-export async function routeProxiedDeliverStep(- input:- | {- readonly delivery: DeliverHookPayload;- readonly parentWritable: WritableStream<Uint8Array>;- readonly serializedContext?: Record<string, unknown>;- readonly sessionState: DurableSessionState;- }- | {- readonly auth?: SessionAuthContext | null;- readonly parentWritable: WritableStream<Uint8Array>;- readonly payload: DeliverPayload;- readonly serializedContext?: Record<string, unknown>;- readonly sessionState: DurableSessionState;- },-): Promise<LegacyRoutedDeliverResult | RoutedDeliverResult> {+}): Promise<RoutedDeliverResult> {"use step";-- let durableSession = await readDurableSession(input.sessionState);- const legacyInput = !("delivery" in input);- const sourceDelivery: DeliverHookPayload =- "delivery" in input- ? input.delivery- : { auth: input.auth, kind: "deliver", payloads: [input.payload] };+ let durableSession = readDurableSession(input.sessionState);+ const sourceDelivery = input.delivery;const parentPayloads = new Map<number, DeliverPayload>();const children = new Map<string, ChildBucket>();let parentAction: { readonly kind: "cancel-turn" } | undefined;@@ -216,13 +175,11 @@ export async function routeProxiedDeliverStep(const remainder =orderedParentPayloads.length === 0? undefined- : legacyInput- ? coalesceDeliverPayloads(orderedParentPayloads.map(([, payload]) => payload))- : {- ...sourceDelivery,- deliveryMetadata: parentMetadata.length === 0 ? undefined : parentMetadata,- payloads: orderedParentPayloads.map(([, payload]) => payload),- };+ : {+ ...sourceDelivery,+ deliveryMetadata: parentMetadata.length === 0 ? undefined : parentMetadata,+ payloads: orderedParentPayloads.map(([, payload]) => payload),+ };return { ...context, kind: "continue", remainder };}diff --git a/packages/eve/src/execution/reconcile-session-continuation-token.test.ts b/packages/eve/src/execution/reconcile-session-continuation-token.test.tsindex 1cf473bf9..a7f74321a 100644--- a/packages/eve/src/execution/reconcile-session-continuation-token.test.ts+++ b/packages/eve/src/execution/reconcile-session-continuation-token.test.ts@@ -35,8 +35,8 @@ describe("reconcileSessionContinuationToken", () => {expect(next).toBe(session);});- it("re-stamps the session's continuation token when a handler called continuation.rekey", () => {- // The session handle's `continuation.rekey(...)` writes through+ it("re-stamps the session's continuation token when a handler called continuation.alias", () => {+ // The session handle's `continuation.alias(...)` writes through// to ContinuationTokenKey during the step. After the step,// reconcile picks the new token up and stamps it onto the// HarnessSession the workflow body reads back.diff --git a/packages/eve/src/execution/reconcile-session-continuation-token.ts b/packages/eve/src/execution/reconcile-session-continuation-token.tsindex b84b668cc..c3d3491a8 100644--- a/packages/eve/src/execution/reconcile-session-continuation-token.ts+++ b/packages/eve/src/execution/reconcile-session-continuation-token.ts@@ -2,7 +2,7 @@ import type { ContextAccessor } from "#context/key.js";import { ContinuationTokenKey } from "#context/keys.js";import type { HarnessSession } from "#harness/types.js";-/** Re-stamps a session after a channel handler changes its continuation token. */+/** Re-stamps a session after a channel handler selects a new current continuation address. */export function reconcileSessionContinuationToken(ctx: ContextAccessor,session: HarnessSession,diff --git a/packages/eve/src/execution/report-dropped-wire-payload-step.ts b/packages/eve/src/execution/report-dropped-wire-payload-step.tsindex 49f286fdc..2abee1284 100644--- a/packages/eve/src/execution/report-dropped-wire-payload-step.ts+++ b/packages/eve/src/execution/report-dropped-wire-payload-step.ts@@ -6,7 +6,7 @@ const log = createLogger("execution.wire");* Surfaces a durable payload dropped by a wire codec's decode.** Workflow-context consumers cannot log directly — the logging module pulls- * Node builtins the workflow driver bundle must not contain — so the report+ * Node builtins the session owner bundle must not contain — so the report* crosses a step boundary. The recorded step also leaves a durable trace in* the run's event log, which is the operator-visible half of the "drop* loudly, never reinterpret" wire contract.diff --git a/packages/eve/src/execution/route-child-delivery.test.ts b/packages/eve/src/execution/route-child-delivery.test.tsindex 0f3833d72..d2721188a 100644--- a/packages/eve/src/execution/route-child-delivery.test.ts+++ b/packages/eve/src/execution/route-child-delivery.test.ts@@ -1,3 +1,4 @@+import { createTestSessionState } from "#internal/testing/session-state.js";import { beforeEach, describe, expect, it, vi } from "vitest";import { routeDeliverToChildren } from "#execution/route-child-delivery.js";@@ -36,13 +37,14 @@ vi.mock("#execution/tools/workflow/resume-hook-step.js", () => ({resumeHookStep: vi.fn(),}));-const state = (hasProxyInputRequests: boolean): DurableSessionState => ({- continuationToken: "parent-token",- emissionState: { sequence: 0, sessionStarted: true, stepIndex: 0, turnId: "" },- hasProxyInputRequests,- sessionId: "parent-session",- version: 1,-});+const state = (hasProxyInputRequests: boolean): DurableSessionState =>+ createTestSessionState({+ continuationToken: "parent-token",+ emissionState: { sequence: 0, sessionStarted: true, stepIndex: 0, turnId: "" },+ hasProxyInputRequests,+ sessionId: "parent-session",+ version: 1,+ });const taskRequest = {replyTo: "eve:workflow-tool-run-answer:run-1:0",@@ -83,7 +85,7 @@ describe("task HITL delivery routing", () => {kind: "deliver",payloads: [{ task: { inputRequests: [taskRequest] } }],},- parentWritable: new WritableStream<Uint8Array>(),+ sessionWritable: new WritableStream<Uint8Array>(),serializedContext: {},sessionState: state(false),});@@ -120,7 +122,7 @@ describe("task HITL delivery routing", () => {kind: "deliver",payloads: [{ task: { views: [view] } }],},- parentWritable: new WritableStream<Uint8Array>(),+ sessionWritable: new WritableStream<Uint8Array>(),serializedContext: { trace: "open" },sessionState: state(false),});@@ -149,7 +151,7 @@ describe("task HITL delivery routing", () => {kind: "deliver",payloads: [{ task: { inputRequests: [{ ...taskRequest, taskId: "foreign-task" }] } }],},- parentWritable: new WritableStream<Uint8Array>(),+ sessionWritable: new WritableStream<Uint8Array>(),serializedContext: {},sessionState: state(false),});@@ -194,7 +196,7 @@ describe("task HITL delivery routing", () => {},],},- parentWritable: new WritableStream<Uint8Array>(),+ sessionWritable: new WritableStream<Uint8Array>(),serializedContext: {},sessionState: state(false),});@@ -251,7 +253,7 @@ describe("task HITL delivery routing", () => {},],},- parentWritable: new WritableStream<Uint8Array>(),+ sessionWritable: new WritableStream<Uint8Array>(),serializedContext: { source: "parent" },sessionState: state(false),});@@ -303,7 +305,7 @@ describe("task HITL delivery routing", () => {taskDeliveryId: "task-delivery-1",turnPolicy: "queue",},- parentWritable: new WritableStream<Uint8Array>(),+ sessionWritable: new WritableStream<Uint8Array>(),serializedContext: {},sessionState: routedState,});diff --git a/packages/eve/src/execution/route-child-delivery.ts b/packages/eve/src/execution/route-child-delivery.tsindex e910036cb..297f1b753 100644--- a/packages/eve/src/execution/route-child-delivery.ts+++ b/packages/eve/src/execution/route-child-delivery.ts@@ -23,12 +23,12 @@ import { applyTaskAgentRequest } from "#execution/tools/subagent/task-agent-requ** Short-circuits via `hasProxyInputRequests` so the common no-active-descendant* path skips a durable step boundary. Lives in its own non-step module so both- * the driver and the active turn can share it (a `"use step"` module cannot+ * the owner and the active turn can share it (a `"use step"` module cannot* re-export plain helpers into a workflow body).*/export async function routeDeliverToChildren(input: {readonly delivery: DeliverHookPayload;- readonly parentWritable: WritableStream<Uint8Array>;+ readonly sessionWritable: WritableStream<Uint8Array>;readonly sessionState: DurableSessionState;readonly serializedContext: Record<string, unknown>;}): Promise<RoutedDeliverResult> {@@ -44,7 +44,7 @@ export async function routeDeliverToChildren(input: {sessionState = recorded.sessionState;if (!recorded.accepted) continue;const emitted = await emitRecordedTaskInputRequestStep({- parentWritable: input.parentWritable,+ sessionWritable: input.sessionWritable,request: recorded.request,serializedContext,sessionState,@@ -57,7 +57,7 @@ export async function routeDeliverToChildren(input: {const applied = await applyTaskAgentRequest({ ...request, ownerId: request.taskId },{- parentWritable: input.parentWritable,+ sessionWritable: input.sessionWritable,serializedContext,sessionState,},@@ -73,7 +73,7 @@ export async function routeDeliverToChildren(input: {if (!accepted) continue;const emitted = await runProxySubagentEventStep({hookPayload: delivery.hookPayload,- parentWritable: input.parentWritable,+ sessionWritable: input.sessionWritable,serializedContext,sessionState,});@@ -130,7 +130,7 @@ export async function routeDeliverToChildren(input: {return await routeProxiedDeliverStep({delivery,- parentWritable: input.parentWritable,+ sessionWritable: input.sessionWritable,serializedContext,sessionState,});diff --git a/packages/eve/src/execution/runtime-context.test.ts b/packages/eve/src/execution/runtime-context.test.tsindex be6b88806..1d8b6fd0c 100644--- a/packages/eve/src/execution/runtime-context.test.ts+++ b/packages/eve/src/execution/runtime-context.test.ts@@ -3,6 +3,7 @@ import { ContextContainer, contextStorage, loadContext } from "#context/containeimport {AuthKey,ChannelInstrumentationKey,+ ContinuationHookTokensKey,ContinuationTokenKey,ParentTraceContextKey,type Session,@@ -166,6 +167,7 @@ describe("buildRunContext", () => {});expect(ctx.require(AuthKey)).toEqual(testAuth);+ expect(ctx.require(ContinuationHookTokensKey)).toEqual(["t"]);expect(ctx.get(SessionIdKey)).toBeUndefined();});@@ -246,6 +248,7 @@ describe("buildRunContext", () => {});expect(ctx.get(ContinuationTokenKey)).toBeUndefined();+ expect(ctx.get(ContinuationHookTokensKey)).toBeUndefined();});it("does not throw when channel has no onContext", () => {diff --git a/packages/eve/src/execution/runtime-context.ts b/packages/eve/src/execution/runtime-context.tsindex 8561fb2f1..cec27d17f 100644--- a/packages/eve/src/execution/runtime-context.ts+++ b/packages/eve/src/execution/runtime-context.ts@@ -7,6 +7,7 @@ import {ChannelInstrumentationKey,ChannelDeliveryKey,ChannelRequestIdKey,+ ContinuationHookTokensKey,ContinuationTokenKey,ConversationIdKey,DynamicSubagentAgentConfigKey,@@ -63,6 +64,7 @@ export function buildRunContext(input: {if (run.continuationToken !== undefined) {ctx.set(ContinuationTokenKey, run.continuationToken);+ ctx.set(ContinuationHookTokensKey, [run.continuationToken]);}ctx.set(ModeKey, run.mode);ctx.set(AuthKey, auth);diff --git a/packages/eve/src/execution/session-command-inbox.integration.test.ts b/packages/eve/src/execution/session-command-inbox.integration.test.tsdeleted file mode 100644index e13dbc928..000000000--- a/packages/eve/src/execution/session-command-inbox.integration.test.ts+++ /dev/null@@ -1,234 +0,0 @@-import { describe, expect, it } from "vitest";--import { createWorkflowRuntime } from "#execution/workflow-runtime.js";-import { sessionCommandInboxWorkflow } from "#internal/testing/session-command-inbox-workflow.js";-import { legacySessionDeliveryWorkflow } from "#internal/testing/legacy-session-delivery-workflow.js";-import { midCohortSessionDeliveryWorkflow } from "#internal/testing/mid-cohort-session-delivery-workflow.js";-import { waitForHook } from "#internal/testing/workflow-test-helpers.js";-import { getHookByToken, getWorld, resumeHook, start } from "#internal/workflow/runtime.js";-import { sessionCommandHookToken } from "#execution/session-command-token.js";-import { SESSION_INBOX_WIRE_VERSION } from "#execution/wire/session-inbox-contract.js";-import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";--describe("session command inbox integration", () => {- it("resumes a legacy delivery-only workflow from a current send command", async () => {- const token = "http:session-command-inbox:legacy-delivery";- const run = await start(legacySessionDeliveryWorkflow, [{ token }]);-- try {- await waitForHook({ runId: run.runId }, { token });- const runtime = createWorkflowRuntime({- compiledArtifactsSource: {} as RuntimeCompiledArtifactsSource,- });-- await expect(- runtime.dispatchContinuation({- command: {- delivery: {- channelKind: "channel:http",- channelName: "http",- deliveryId: "legacy-delivery",- },- kind: "send",- payload: { message: "legacy-compatible" },- },- continuationToken: token,- }),- ).resolves.toEqual({- sessionId: run.runId,- status: "accepted",- deliveryId: "legacy-delivery",- });- await expect(run.returnValue).resolves.toBe("legacy-compatible");- } finally {- const status = await run.status;- if (status === "pending" || status === "running") await run.cancel();- }- });-- it("resumes a 0.30.5–0.30.8 parked consumer from a current send command", async () => {- const token = "http:session-command-inbox:mid-cohort-delivery";- const run = await start(midCohortSessionDeliveryWorkflow, [{ token }]);-- try {- await waitForHook({ runId: run.runId }, { token });- const runtime = createWorkflowRuntime({- compiledArtifactsSource: {} as RuntimeCompiledArtifactsSource,- });-- await expect(- runtime.dispatchContinuation({- command: {- delivery: {- channelKind: "channel:http",- channelName: "http",- deliveryId: "mid-cohort-delivery",- },- kind: "send",- payload: { message: "mid-cohort-compatible" },- },- continuationToken: token,- }),- ).resolves.toEqual({- sessionId: run.runId,- status: "accepted",- deliveryId: "mid-cohort-delivery",- });- await expect(run.returnValue).resolves.toBe("mid-cohort-compatible");- } finally {- const status = await run.status;- if (status === "pending" || status === "running") await run.cancel();- }- });-- it("stamps the consumer wire version onto inbox hooks, readable pre-resume", async () => {- const channelToken = "http:session-command-inbox:version-stamp";- const run = await start(sessionCommandInboxWorkflow, [{ token: channelToken }]);- const stableToken = sessionCommandHookToken(run.runId);-- try {- await Promise.all([- waitForHook({ runId: run.runId }, { token: stableToken }),- waitForHook({ runId: run.runId }, { token: channelToken }),- ]);-- for (const token of [stableToken, channelToken]) {- const hook = await getHookByToken(token);- const metadata = (await hook.metadata) as { sessionInboxWireVersion?: unknown } | undefined;- expect(metadata?.sessionInboxWireVersion, `hook ${token}`).toBe(SESSION_INBOX_WIRE_VERSION);- }- } finally {- const status = await run.status;- if (status === "pending" || status === "running") await run.cancel();- }- });-- it("accepts commands alternately through the stable ID and channel aliases", async () => {- const channelToken = "http:session-command-inbox:both-aliases";- const run = await start(sessionCommandInboxWorkflow, [{ token: channelToken }]);- const stableToken = sessionCommandHookToken(run.runId);-- try {- await Promise.all([- waitForHook({ runId: run.runId }, { token: stableToken }),- waitForHook({ runId: run.runId }, { token: channelToken }),- ]);-- await resumeHook(stableToken, { kind: "send", payload: { message: "by id" } });- await resumeHook(channelToken, {- kind: "deliver",- payloads: [{ message: "by channel" }],- });-- await expect(run.returnValue).resolves.toEqual(["by id", "by channel"]);- } finally {- const status = await run.status;- if (status === "pending" || status === "running") await run.cancel();- }- });-- it.each([- ["old then replacement", ["old", "replacement"] as const],- ["replacement then old", ["replacement", "old"] as const],- ])("preserves sends committed %s during rekey", async (_label, order) => {- const suffix = order.join("-");- const oldToken = `http:session-command-inbox:${suffix}:old`;- const replacementToken = `http:session-command-inbox:${suffix}:replacement`;- const disposal = await pauseHookDisposal(oldToken);- const run = await start(sessionCommandInboxWorkflow, [- { nextToken: replacementToken, token: oldToken },- ]);-- try {- await withTimeout(disposal.started, "old-alias disposal");- await Promise.all([- waitForHook({ runId: run.runId }, { token: oldToken }),- waitForHook({ runId: run.runId }, { token: replacementToken }),- ]);-- const tokens = { old: oldToken, replacement: replacementToken };- for (const owner of order) {- await resumeHook(tokens[owner], { kind: "send", payload: { message: owner } });- }-- disposal.release();- await withTimeout(disposal.finished, "old-alias disposal completion");-- await expect(- resumeHook(oldToken, { kind: "send", payload: { message: "too late" } }),- ).rejects.toMatchObject({ name: "HookNotFoundError" });- await expect(run.returnValue).resolves.toEqual(order);- } finally {- disposal.release();- disposal.restore();- const status = await run.status;- if (status === "pending" || status === "running") await run.cancel();- }- });-});--async function pauseHookDisposal(token: string): Promise<{- readonly finished: Promise<void>;- readonly started: Promise<void>;- release(): void;- restore(): void;-}> {- const world = await getWorld();- const events = world.events as {- create(...args: unknown[]): Promise<unknown>;- };- const originalCreate = events.create.bind(events);- const started = createDeferred();- const release = createDeferred();- const finished = createDeferred();-- events.create = async (...args: unknown[]): Promise<unknown> => {- const event = args[1] as { readonly correlationId?: string; readonly eventType?: string };- if (event.eventType === "hook_disposed" && event.correlationId !== undefined) {- const hook = await world.hooks.get(event.correlationId);- if (hook.token === token) {- started.resolve();- await release.promise;- try {- return await originalCreate(...args);- } finally {- finished.resolve();- }- }- }- return await originalCreate(...args);- };-- return {- finished: finished.promise,- release: release.resolve,- restore() {- events.create = originalCreate;- },- started: started.promise,- };-}--function createDeferred(): { readonly promise: Promise<void>; resolve(): void } {- let resolve!: () => void;- const promise = new Promise<void>((next) => {- resolve = next;- });- return { promise, resolve };-}--async function withTimeout<T>(promise: Promise<T>, label: string): Promise<T> {- let timeout: ReturnType<typeof setTimeout> | undefined;- try {- return await Promise.race([- promise,- new Promise<never>((_resolve, reject) => {- timeout = setTimeout(() => {- reject(new Error(`Timed out waiting for ${label}.`));- }, 10_000);- }),- ]);- } finally {- if (timeout !== undefined) clearTimeout(timeout);- }-}diff --git a/packages/eve/src/execution/session-command-inbox.test.ts b/packages/eve/src/execution/session-command-inbox.test.tsdeleted file mode 100644index 434da7062..000000000--- a/packages/eve/src/execution/session-command-inbox.test.ts+++ /dev/null@@ -1,350 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--import {- createSessionCommandInbox,- type SessionInboxPayload,-} from "#execution/session-command-inbox.js";--const createHookMock = vi.fn();--vi.mock("#compiled/@workflow/core/index.js", () => ({- createHook: (...args: unknown[]) => createHookMock(...args),- getWritable: vi.fn(),-}));--describe("createSessionCommandInbox", () => {- beforeEach(() => {- createHookMock.mockReset();- });-- it("multiplexes the stable session inbox and continuation alias", async () => {- installHooks(- createMockHook({ reads: [Promise.resolve(resolved(send("by id")))], token: "stable" }),- createMockHook({- reads: [Promise.resolve(resolved({ kind: "clear" }))],- token: "channel",- }),- );- const inbox = createSessionCommandInbox();-- await inbox.claimStable("stable");- await inbox.rekeyContinuation("channel");-- await expect(inbox.next()).resolves.toEqual(resolved(send("by id")));- inbox.consumeNext();- await expect(inbox.next()).resolves.toEqual(resolved({ kind: "clear" }));- inbox.consumeNext();- await inbox.dispose();- });-- it("retains a committed read from the previous alias across rekey", async () => {- const oldRead = createDeferred<IteratorResult<SessionInboxPayload>>();- const replacementRead = createDeferred<IteratorResult<SessionInboxPayload>>();- const stable = createMockHook({ token: "stable" });- const oldAlias = createMockHook({ reads: [oldRead.promise], token: "old" });- const replacement = createMockHook({- reads: [replacementRead.promise],- token: "replacement",- });- installHooks(stable, oldAlias, replacement);- const inbox = createSessionCommandInbox();-- await inbox.claimStable("stable");- await inbox.rekeyContinuation("old");- const pending = inbox.next();- await inbox.rekeyContinuation("replacement");-- oldRead.resolve(resolved(send("old")));- await expect(pending).resolves.toEqual(resolved(send("old")));- inbox.consumeNext();-- replacementRead.resolve(resolved(send("replacement")));- await expect(inbox.next()).resolves.toEqual(resolved(send("replacement")));- inbox.consumeNext();- await inbox.dispose();-- expect(stable.dispose).toHaveBeenCalledOnce();- expect(oldAlias.dispose).toHaveBeenCalledOnce();- expect(replacement.dispose).toHaveBeenCalledOnce();- });-- it("adds a first continuation alias to an existing stable wait", async () => {- installHooks(- createMockHook({ token: "stable" }),- createMockHook({- reads: [Promise.resolve(resolved(send("anchored")))],- token: "channel",- }),- );- const inbox = createSessionCommandInbox();-- await inbox.claimStable("stable");- const pending = inbox.next();- await inbox.rekeyContinuation("channel");-- await expect(pending).resolves.toEqual(resolved(send("anchored")));- inbox.consumeNext();- await inbox.dispose();- });-- it("disposes a conflicting continuation candidate without releasing current ownership", async () => {- const stable = createMockHook({ token: "stable" });- const current = createMockHook({ token: "current" });- const candidate = createMockHook({- conflict: { runId: "wrun_owner" },- token: "candidate",- });- installHooks(stable, current, candidate);- const inbox = createSessionCommandInbox();-- await inbox.claimStable("stable");- await inbox.rekeyContinuation("current");- await expect(inbox.rekeyContinuation("candidate")).rejects.toMatchObject({- conflictingRunId: "wrun_owner",- name: "HookConflictError",- token: "candidate",- });-- expect(candidate.dispose).toHaveBeenCalledOnce();- expect(current.dispose).not.toHaveBeenCalled();- await inbox.dispose();- expect(current.dispose).toHaveBeenCalledOnce();- });-- it("never permits the stable session token to change", async () => {- const stable = createMockHook({ token: "stable" });- installHooks(stable);- const inbox = createSessionCommandInbox();-- await inbox.claimStable("stable");- await inbox.claimStable("stable");- await expect(inbox.claimStable("different")).rejects.toThrow(- "A session command inbox cannot change its stable token.",- );- expect(createHookMock).toHaveBeenCalledOnce();- expect(createHookMock).toHaveBeenCalledWith({- metadata: { sessionInboxWireVersion: 7, workflowTaskAuthorization: true },- token: "stable",- });- await inbox.dispose();- });-- it("disposes active hooks without closing pending iterators", async () => {- const stable = createMockHook({ token: "stable" });- const alias = createMockHook({ token: "channel" });- installHooks(stable, alias);- const inbox = createSessionCommandInbox();-- await inbox.claimStable("stable");- await inbox.rekeyContinuation("channel");- void inbox.next();- await inbox.dispose();- await inbox.dispose();-- expect(stable.dispose).toHaveBeenCalledOnce();- expect(alias.dispose).toHaveBeenCalledOnce();- expect(stable.return).not.toHaveBeenCalled();- expect(alias.return).not.toHaveBeenCalled();- });-- it("stashes authorization callbacks while the window is closed", async () => {- const sessionRead = createDeferred<IteratorResult<SessionInboxPayload>>();- installHooks(- createMockHook({ reads: [sessionRead.promise], token: "stable" }),- createMockHook({- reads: [Promise.resolve(resolved(authCallback("weather")))],- token: "session:auth",- }),- );- const inbox = createSessionCommandInbox();- await inbox.claimStable("stable");- await inbox.claimAuthorization("session:auth");-- // The callback resolves first, but only session activity surfaces.- const pending = inbox.nextWithSource();- sessionRead.resolve(resolved(send("while closed")));- await expect(pending).resolves.toEqual({- result: resolved(send("while closed")),- source: "session",- });- inbox.consumeNext();-- inbox.setAuthorizationWindow(true);- await expect(inbox.nextWithSource()).resolves.toEqual({- result: resolved(authCallback("weather")),- source: "authorization",- });- inbox.consumeNext();- inbox.setAuthorizationWindow(false);- await inbox.dispose();- });-- it("re-stashes an unconsumed authorization read when the window closes", async () => {- installHooks(- createMockHook({ reads: [Promise.resolve(resolved(send("first")))], token: "stable" }),- createMockHook({- reads: [Promise.resolve(resolved(authCallback("weather")))],- token: "session:auth",- }),- );- const inbox = createSessionCommandInbox();- await inbox.claimStable("stable");- await inbox.claimAuthorization("session:auth");-- // Window open: the session read arrives first and is offered; the- // callback read resolves behind it and waits enqueued.- inbox.setAuthorizationWindow(true);- await expect(inbox.nextWithSource()).resolves.toEqual({- result: resolved(send("first")),- source: "session",- });- expect(inbox.hasReadyAuthorization()).toBe(false);- inbox.setAuthorizationWindow(false);- inbox.consumeNext();-- // Window closed: the stashed callback never surfaces as session activity.- const closedRead = inbox.nextWithSource();- let settled = false;- void closedRead.then(() => {- settled = true;- });- await Promise.resolve();- expect(settled).toBe(false);-- // Reopening surfaces the same stashed callback exactly once.- inbox.setAuthorizationWindow(true);- await expect(closedRead).resolves.toEqual({- result: resolved(authCallback("weather")),- source: "authorization",- });- inbox.consumeNext();- await inbox.dispose();- });-- it("lets an older callback supersede an unconsumed offered session read", async () => {- const sessionRead = createDeferred<IteratorResult<SessionInboxPayload>>();- installHooks(- createMockHook({ reads: [sessionRead.promise], token: "stable" }),- createMockHook({- reads: [Promise.resolve(resolved(authCallback("weather")))],- token: "session:auth",- }),- );- const inbox = createSessionCommandInbox();- await inbox.claimStable("stable");- await inbox.claimAuthorization("session:auth");-- const losingRead = inbox.nextWithSource();- await Promise.resolve();- sessionRead.resolve(resolved(send("later session read")));- await expect(losingRead).resolves.toEqual({- result: resolved(send("later session read")),- source: "session",- });-- inbox.setAuthorizationWindow(true);- expect(inbox.hasReadyAuthorization()).toBe(true);- await expect(inbox.nextWithSource()).resolves.toEqual({- result: resolved(authCallback("weather")),- source: "authorization",- });- inbox.consumeNext();- inbox.setAuthorizationWindow(false);-- await expect(inbox.nextWithSource()).resolves.toEqual({- result: resolved(send("later session read")),- source: "session",- });- inbox.consumeNext();- await inbox.dispose();- });-- it("disposes the authorization hook with the inbox", async () => {- const auth = createMockHook({ token: "session:auth" });- installHooks(createMockHook({ token: "stable" }), auth);- const inbox = createSessionCommandInbox();-- await inbox.claimStable("stable");- await inbox.claimAuthorization("session:auth");- await inbox.dispose();-- expect(auth.dispose).toHaveBeenCalledOnce();- expect(auth.return).not.toHaveBeenCalled();- });-});--function authCallback(connectionName: string): SessionInboxPayload {- return {- kind: "deliver",- payloads: [- {- authorizationCallback: {- callback: { method: "GET", params: { code: "abc" } },- connectionName,- },- },- ],- };-}--interface MockHook {- readonly dispose: ReturnType<typeof vi.fn>;- readonly hook: unknown;- readonly return: ReturnType<typeof vi.fn>;- readonly token: string;-}--function createMockHook(input: {- readonly conflict?: { readonly runId: string } | null;- readonly reads?: readonly Promise<IteratorResult<SessionInboxPayload>>[];- readonly token: string;-}): MockHook {- const reads = [...(input.reads ?? [])];- const dispose = vi.fn();- const iteratorReturn = vi.fn(async () => ({ done: true, value: undefined }) as const);- const hook = Object.assign(new Promise<SessionInboxPayload>(() => {}), {- [Symbol.asyncIterator]() {- return {- next: vi.fn(- () =>- reads.shift() ??- new Promise<IteratorResult<SessionInboxPayload>>(() => {- // Intentionally pending.- }),- ),- return: iteratorReturn,- };- },- dispose,- getConflict: vi.fn(async () => input.conflict ?? null),- token: input.token,- });- return { dispose, hook, return: iteratorReturn, token: input.token };-}--function installHooks(...hooks: readonly MockHook[]): void {- const queue = [...hooks];- createHookMock.mockImplementation((options: { readonly token: string }) => {- const hook = queue.shift();- if (hook === undefined || hook.token !== options.token) {- throw new Error(`Unexpected hook token "${options.token}".`);- }- return hook.hook;- });-}--function send(message: string): SessionInboxPayload {- return { kind: "send", payload: { message } };-}--function resolved(value: SessionInboxPayload): IteratorResult<SessionInboxPayload> {- return { done: false, value };-}--function createDeferred<T>(): { readonly promise: Promise<T>; resolve(value: T): void } {- let resolve!: (value: T) => void;- const promise = new Promise<T>((next) => {- resolve = next;- });- return { promise, resolve };-}diff --git a/packages/eve/src/execution/session-command-inbox.ts b/packages/eve/src/execution/session-command-inbox.tsdeleted file mode 100644index 2f4c43b6b..000000000--- a/packages/eve/src/execution/session-command-inbox.ts+++ /dev/null@@ -1,333 +0,0 @@-import { createHook, type Hook } from "#compiled/@workflow/core/index.js";--import type {- DeliverHookPayload,- RuntimeActionResultHookPayload,- SessionCommand,- SessionTimeoutHookPayload,-} from "#channel/types.js";-import { claimHookOwnership, disposeHook } from "#execution/hook-ownership.js";-import {- SESSION_INBOX_WIRE_VERSION,- SESSION_INBOX_WIRE_VERSION_METADATA_KEY,- WORKFLOW_TASK_AUTHORIZATION_METADATA_KEY,-} from "#execution/wire/session-inbox-contract.js";-/**- * Payloads accepted by a session driver's stable and channel aliases.- *- * This union is the hook's transport typing only. The driver routes payloads- * after the inbox surfaces them; the inbox owns no command semantics.- */-export type SessionInboxPayload =- | DeliverHookPayload- | RuntimeActionResultHookPayload- | SessionCommand- | SessionTimeoutHookPayload;--interface HookRead {- readonly order: number;- readonly result: IteratorResult<SessionInboxPayload>;- readonly state: SessionCommandHookState;-}--interface SessionCommandHookState {- readonly hook: Hook<SessionInboxPayload>;- readonly iterator: AsyncIterator<SessionInboxPayload>;- closed: boolean;- enabled: boolean;- pending: boolean;- retired: boolean;- resolved?: HookRead;-}--/** Which hook family produced an inbox read. */-export type SessionInboxSource = "authorization" | "session";--/**- * Multiplexes one stable session hook, one rekeyable channel alias, and one- * window-gated authorization-callback hook.- */-export interface SessionCommandInbox {- /**- * Claims the session's authorization-callback hook as an inbox source.- * Its reads stay stashed until {@link setAuthorizationWindow} opens, so- * callbacks never surface as ordinary session activity.- */- claimAuthorization(token: string): Promise<void>;- claimStable(token: string): Promise<void>;- consumeNext(): void;- /** Whether an authorization read is already eligible to be consumed. */- hasReadyAuthorization(): boolean;- next(): Promise<IteratorResult<SessionInboxPayload>>;- /**- * Like {@link next} but reports which hook family produced the read.- * Reads surface in one arrival order across every source, which keeps- * waits that interleave authorization callbacks with ordinary session- * activity deterministic under workflow replay.- */- nextWithSource(): Promise<{- result: IteratorResult<SessionInboxPayload>;- source: SessionInboxSource;- }>;- rekeyContinuation(token: string): Promise<void>;- /** Opens or closes the surfacing window for authorization-callback reads. */- setAuthorizationWindow(open: boolean): void;-}--/** Adds workflow-entry lifecycle ownership to a session command inbox. */-export interface SessionCommandInboxHandle extends SessionCommandInbox {- dispose(): Promise<void>;-}--/**- * Creates the command inbox owned by one session driver.- *- * The stable hook is retained for the session's lifetime. Rekeying replaces- * only the channel alias. Reads already committed to a retired alias remain in- * the multiplexed queue and are consumed exactly once.- */-export function createSessionCommandInbox(): SessionCommandInboxHandle {- let stable: SessionCommandHookState | undefined;- let continuation: SessionCommandHookState | undefined;- let authorization: SessionCommandHookState | undefined;- const retired: SessionCommandHookState[] = [];- const ready: HookRead[] = [];- let nextOrder = 0;- let offered: Promise<IteratorResult<SessionInboxPayload>> | null = null;- let offeredRead: HookRead | undefined;- let wake: (() => void) | undefined;- const enqueue = (read: HookRead): void => {- ready.push(read);- ready.sort((left, right) => left.order - right.order);- wake?.();- wake = undefined;- };-- const arm = (state: SessionCommandHookState): void => {- if (state.closed || state.pending) return;-- state.pending = true;- state.resolved = undefined;- const next = state.retired- ? Promise.resolve(state.hook).then((value): IteratorResult<SessionInboxPayload> => ({- done: false,- value,- }))- : state.iterator.next();- void next.then(- (result) => {- const read: HookRead = { order: nextOrder++, result, state };- state.resolved = read;- if (state.enabled) enqueue(read);- },- () => {- // Retired hooks reject after their committed payloads are exhausted.- },- );- };-- const enable = (state: SessionCommandHookState): void => {- state.enabled = true;- if (state.resolved !== undefined) enqueue(state.resolved);- };-- const createState = (token: string): SessionCommandHookState => {- // Stamp the consumer's wire capability so producers can select an encoder- // pre-resume. Hooks created before this stamp carry no wire marker:- // markerless means the consumer predates the capability and accepts a- // legacy shape.- const hook = createHook<SessionInboxPayload>({- metadata: {- [SESSION_INBOX_WIRE_VERSION_METADATA_KEY]: SESSION_INBOX_WIRE_VERSION,- [WORKFLOW_TASK_AUTHORIZATION_METADATA_KEY]: true,- },- token,- });- return {- closed: false,- enabled: false,- hook,- iterator: hook[Symbol.asyncIterator](),- pending: false,- retired: false,- };- };-- const states = (): readonly SessionCommandHookState[] =>- [stable, continuation, authorization, ...retired].filter(- (state): state is SessionCommandHookState => state !== undefined,- );-- const nextRead = (): Promise<IteratorResult<SessionInboxPayload>> => {- if (stable === undefined) {- throw new Error("Cannot wait for session commands before claiming the stable inbox.");- }-- if (offered !== null) return offered;-- const current = states();- for (const state of current) arm(state);-- if (current.every((state) => state.closed)) {- offeredRead = {- order: nextOrder++,- result: { done: true, value: undefined },- state: stable,- };- offered = Promise.resolve(offeredRead.result);- return offered;- }-- offered = (async () => {- while (ready.length === 0) {- await new Promise<void>((resolve) => {- wake = resolve;- });- }-- const read = ready.shift()!;- offeredRead = read;- return read.result;- })();- return offered;- };-- return {- async claimAuthorization(token: string): Promise<void> {- if (authorization !== undefined) {- if (authorization.hook.token === token) return;- throw new Error("A session command inbox cannot change its authorization token.");- }-- const candidate = createState(token);- await claimHookOwnership(candidate.hook);- // Stays disabled until the driver opens the authorization window;- // resolved reads stash on the state and enqueue when it opens.- authorization = candidate;- },-- async claimStable(token: string): Promise<void> {- if (stable !== undefined) {- if (stable.hook.token === token) return;- throw new Error("A session command inbox cannot change its stable token.");- }-- const candidate = createState(token);- await claimHookOwnership(candidate.hook);- enable(candidate);- stable = candidate;- },-- consumeNext(): void {- if (offeredRead === undefined) {- throw new Error("Cannot consume a session command before it resolves.");- }-- offeredRead.state.pending = false;- offeredRead.state.resolved = undefined;- if (offeredRead.result.done) offeredRead.state.closed = true;- offeredRead = undefined;- offered = null;- },-- async dispose(): Promise<void> {- // Disposed without closing iterators: a session cancelled while a- // durable read is in flight only honors `return()` after that read- // settles, so hooks are swept instead.- const active = [continuation, stable, authorization].filter(- (state): state is SessionCommandHookState => state !== undefined,- );- continuation = undefined;- stable = undefined;- authorization = undefined;- await Promise.all(active.map(async (state) => await disposeHook(state.hook)));- },-- hasReadyAuthorization(): boolean {- if (authorization?.enabled !== true || authorization.resolved === undefined) return false;- if (offeredRead !== undefined) return offeredRead.state === authorization;- return ready[0]?.state === authorization;- },-- next: nextRead,-- async nextWithSource(): Promise<{- result: IteratorResult<SessionInboxPayload>;- source: SessionInboxSource;- }> {- const result = await nextRead();- return {- result,- source:- offeredRead !== undefined && offeredRead.state === authorization- ? "authorization"- : "session",- };- },-- setAuthorizationWindow(open: boolean): void {- if (authorization === undefined) {- if (open) {- throw new Error("Cannot open the authorization window before claiming its hook.");- }- return;- }- if (open) {- if (!authorization.enabled) enable(authorization);- if (- offeredRead !== undefined &&- offeredRead.state !== authorization &&- authorization.resolved !== undefined &&- authorization.resolved.order < offeredRead.order- ) {- enqueue(offeredRead);- offeredRead = undefined;- offered = null;- }- if (offered !== null) arm(authorization);- return;- }- authorization.enabled = false;- // Un-surface a stashed read that was enqueued but not consumed so it- // re-enqueues when the window reopens. Callers close the window only- // after consuming any authorization read they were offered.- const enqueued = ready.findIndex((read) => read.state === authorization);- if (enqueued !== -1) ready.splice(enqueued, 1);- },-- async rekeyContinuation(token: string): Promise<void> {- if (!token || continuation?.hook.token === token) return;-- const candidate = createState(token);- if (continuation === undefined) {- await claimHookOwnership(candidate.hook);- enable(candidate);- continuation = candidate;- if (offered !== null) arm(candidate);- return;- }-- arm(candidate);- await claimHookOwnership(candidate.hook);- enable(candidate);-- const previous = continuation;- continuation = candidate;- arm(previous);- try {- await disposeHook(previous.hook);- } catch (error) {- continuation = undefined;- try {- await disposeHook(candidate.hook);- } catch {- // The previous-alias release failure is authoritative.- }- throw error;- }-- previous.retired = true;- retired.push(previous);- },- };-}diff --git a/packages/eve/src/execution/session-command-token.ts b/packages/eve/src/execution/session-command-token.tsdeleted file mode 100644index 73122b9b6..000000000--- a/packages/eve/src/execution/session-command-token.ts+++ /dev/null@@ -1,19 +0,0 @@-const SESSION_COMMAND_NAMESPACE = "eve:session";--/** Returns whether a token belongs to eve's framework-reserved session command namespace. */-export function isReservedSessionCommandToken(token: string): boolean {- return token.startsWith(`${SESSION_COMMAND_NAMESPACE}:`);-}--/** Returns whether a token is the stable command inbox for one workflow run. */-export function isSessionCommandHookToken(token: string): boolean {- const prefix = `${SESSION_COMMAND_NAMESPACE}:`;- const suffix = ":inbox";- if (!token.startsWith(prefix) || !token.endsWith(suffix)) return false;- return !token.slice(prefix.length, -suffix.length).includes(":");-}--/** Derives the framework-reserved stable command inbox token for a session. */-export function sessionCommandHookToken(sessionId: string): string {- return `${SESSION_COMMAND_NAMESPACE}:${sessionId}:inbox`;-}diff --git a/packages/eve/src/execution/session-inbox/address.ts b/packages/eve/src/execution/session-inbox/address.tsnew file mode 100644index 000000000..6a24c1985--- /dev/null+++ b/packages/eve/src/execution/session-inbox/address.ts@@ -0,0 +1,45 @@+/** Serialized-context key advertising a session's stable inbox. */+export const SESSION_INBOX_CONTEXT_KEY = "eve.sessionInbox";++/** Hook metadata key that keeps public identity separate from hook ownership. */+export const SESSION_INBOX_SESSION_ID_METADATA_KEY = "sessionId";++/** Stable inbox coordinates. The owner and deployment are intentionally absent. */+export interface SessionInboxAddress {+ readonly sessionId: string;+}++export function isSessionInboxAddress(value: unknown): value is SessionInboxAddress {+ return (+ value !== null &&+ typeof value === "object" &&+ "sessionId" in value &&+ typeof value.sessionId === "string" &&+ value.sessionId.length > 0 &&+ !value.sessionId.includes(":")+ );+}++/** Returns whether a token belongs to eve's framework-reserved session namespace. */+export function isReservedSessionCommandToken(token: string): boolean {+ return token.startsWith("eve:session:") || token.startsWith("eve:inbox:");+}++/** Logical stable command inbox token for a session. */+export function sessionCommandHookToken(sessionId: string): string {+ return `eve:session:${sessionId}:inbox`;+}++/**+ * Physical hook token for a logical session address. Applied exactly where a+ * hook is created or resumed, so current-generation hooks stay disjoint from+ * hooks owned by pre-cutover drivers that used the logical token directly.+ */+export function sessionInboxHookToken(token: string): string {+ return `eve:inbox:v1:${token}`;+}++/** Marker a releasing owner leaves so ingress can tell "handoff in progress" from "no session". */+export function sessionHandoffMarkerToken(token: string): string {+ return `eve:inbox:handoff:${token}`;+}diff --git a/packages/eve/src/execution/session-inbox/inbox.integration.test.ts b/packages/eve/src/execution/session-inbox/inbox.integration.test.tsnew file mode 100644index 000000000..d06c9018f--- /dev/null+++ b/packages/eve/src/execution/session-inbox/inbox.integration.test.ts@@ -0,0 +1,112 @@+import { describe, expect, it } from "vitest";++import { sessionCommandInboxWorkflow } from "#internal/testing/session-inbox-workflow.js";+import { sessionHookPumpWorkflow } from "#internal/testing/session-hook-pump-workflow.js";+import { waitForHook } from "#internal/testing/workflow-test-helpers.js";+import { getHookByToken, resumeHook, start } from "#internal/workflow/runtime.js";+import { sessionCommandHookToken } from "#execution/session-inbox/address.js";+import {+ SESSION_INBOX_SESSION_ID_METADATA_KEY,+ sessionInboxHookToken,+} from "#execution/session-inbox/address.js";++describe("session command inbox integration", () => {+ it("pumps a burst across aliases while the owner waits on an independent hook", async () => {+ const aliases = ["http:pump:first", "http:pump:second"];+ const releaseToken = "pump:release";+ const run = await start(sessionHookPumpWorkflow, [{ aliases, releaseToken }]);+ const tokens = [sessionCommandHookToken(run.runId), ...aliases].map(sessionInboxHookToken);+ try {+ for (const token of [...tokens, releaseToken]) await waitForHook(run, { token });+ const messages = ["one", "two", "three", "four", "five", "six"].map((message) => ({+ kind: "send",+ payload: { message },+ }));+ for (const [index, message] of messages.entries())+ await resumeHook(tokens[index % tokens.length]!, message);+ await resumeHook(releaseToken, undefined);+ await expect(run.returnValue).resolves.toEqual(messages);+ } finally {+ if ((await run.status) === "running") await run.cancel();+ }+ });++ it("stamps the public session id onto every inbox hook", async () => {+ const channelToken = "http:session-inbox:session-id";+ const run = await start(sessionCommandInboxWorkflow, [{ token: channelToken }]);+ const stableToken = sessionInboxHookToken(sessionCommandHookToken(run.runId));++ try {+ await Promise.all([+ waitForHook({ runId: run.runId }, { token: stableToken }),+ waitForHook({ runId: run.runId }, { token: sessionInboxHookToken(channelToken) }),+ ]);++ for (const token of [stableToken, sessionInboxHookToken(channelToken)]) {+ const hook = await getHookByToken(token);+ const metadata = (await hook.metadata) as Record<string, unknown> | undefined;+ expect(metadata?.[SESSION_INBOX_SESSION_ID_METADATA_KEY], `hook ${token}`).toBe(run.runId);+ }+ } finally {+ const status = await run.status;+ if (status === "pending" || status === "running") await run.cancel();+ }+ });++ it("accepts commands alternately through the stable ID and channel aliases", async () => {+ const channelToken = "http:session-inbox:both-aliases";+ const run = await start(sessionCommandInboxWorkflow, [{ token: channelToken }]);+ const stableToken = sessionInboxHookToken(sessionCommandHookToken(run.runId));++ try {+ await Promise.all([+ waitForHook({ runId: run.runId }, { token: stableToken }),+ waitForHook({ runId: run.runId }, { token: sessionInboxHookToken(channelToken) }),+ ]);++ await resumeHook(stableToken, { kind: "send", payload: { message: "by id" } });+ await resumeHook(sessionInboxHookToken(channelToken), {+ kind: "deliver",+ payloads: [{ message: "by channel" }],+ });++ await expect(run.returnValue).resolves.toEqual(["by id", "by channel"]);+ } finally {+ const status = await run.status;+ if (status === "pending" || status === "running") await run.cancel();+ }+ });++ it("keeps every claimed continuation address active", async () => {+ const oldToken = "http:session-inbox:additive:old";+ const replacementToken = "http:session-inbox:additive:replacement";+ const run = await start(sessionCommandInboxWorkflow, [+ { messageCount: 3, nextToken: replacementToken, token: oldToken },+ ]);++ try {+ await Promise.all([+ waitForHook({ runId: run.runId }, { token: sessionInboxHookToken(oldToken) }),+ waitForHook({ runId: run.runId }, { token: sessionInboxHookToken(replacementToken) }),+ ]);++ await resumeHook(sessionInboxHookToken(replacementToken), {+ kind: "send",+ payload: { message: "replacement" },+ });+ await resumeHook(sessionInboxHookToken(oldToken), {+ kind: "send",+ payload: { message: "old" },+ });+ await resumeHook(sessionInboxHookToken(replacementToken), {+ kind: "send",+ payload: { message: "replacement again" },+ });++ await expect(run.returnValue).resolves.toEqual(["replacement", "old", "replacement again"]);+ } finally {+ const status = await run.status;+ if (status === "pending" || status === "running") await run.cancel();+ }+ });+});diff --git a/packages/eve/src/execution/session-inbox/inbox.test.ts b/packages/eve/src/execution/session-inbox/inbox.test.tsnew file mode 100644index 000000000..17bf5768a--- /dev/null+++ b/packages/eve/src/execution/session-inbox/inbox.test.ts@@ -0,0 +1,465 @@+import { sessionInboxHookToken } from "#execution/session-inbox/address.js";+import { beforeEach, describe, expect, it, vi } from "vitest";++import {+ createSessionInbox,+ type SessionInboxHandle,+ type SessionInboxPayload,+} from "#execution/session-inbox/inbox.js";++async function readResult(inbox: SessionInboxHandle): Promise<IteratorResult<SessionInboxPayload>> {+ const value = await inbox.next();+ return value === undefined ? { done: true, value: undefined } : { done: false, value };+}++/** Resolves with the first interrupt the pump pushes to `onInterrupt`. */+function nextInterrupt(inbox: SessionInboxHandle): Promise<SessionInboxPayload> {+ return new Promise((resolve) => {+ const unsubscribe = inbox.onInterrupt((payload) => {+ unsubscribe();+ resolve(payload);+ });+ });+}++function hookTokens(inbox: SessionInboxHandle): readonly string[] {+ return inbox.claimedTokens;+}++const createHookMock = vi.fn();++vi.mock("#execution/session-inbox/release-step.js", () => ({+ releaseSessionHooksStep: vi.fn(async () => {}),+}));++vi.mock("#compiled/@workflow/core/index.js", () => ({+ createHook: (...args: unknown[]) => createHookMock(...args),+ getWritable: vi.fn(),+ getWorkflowMetadata: () => ({ workflowRunId: "owner-1" }),+}));++describe("createSessionInbox", () => {+ beforeEach(() => {+ createHookMock.mockReset();+ });++ it("multiplexes the stable session inbox and continuation alias", async () => {+ installHooks(+ createMockHook({ reads: [Promise.resolve(resolved(send("by id")))], token: "stable" }),+ createMockHook({+ reads: [Promise.resolve(resolved({ kind: "clear" }))],+ token: "channel",+ }),+ );+ const inbox = createSessionInbox("session-1");++ await inbox.claimSessionHook("stable");+ await inbox.claimSessionHook("channel");++ await expect(readResult(inbox)).resolves.toEqual(resolved(send("by id")));+ await expect(readResult(inbox)).resolves.toEqual(resolved({ kind: "clear" }));+ await inbox.dispose();+ });++ it("pushes cancellation to interrupt handlers without consuming messages awaiting a committed boundary", async () => {+ installHooks(+ createMockHook({+ token: "stable",+ reads: [+ Promise.resolve(resolved(send("steer me"))),+ Promise.resolve(resolved({ kind: "cancel", turnId: "turn-1" })),+ ],+ }),+ );+ const inbox = createSessionInbox("session-1");+ const interrupt = nextInterrupt(inbox);+ await inbox.claimSessionHook("stable");+ await expect(interrupt).resolves.toEqual({ kind: "cancel", turnId: "turn-1" });+ expect(inbox.drain()).toEqual([send("steer me"), { kind: "cancel", turnId: "turn-1" }]);+ await inbox.dispose();+ });++ it("retains tool traffic and gated callbacks in the same stable queue", async () => {+ const report: SessionInboxPayload = {+ kind: "report",+ from: {+ callId: "call",+ execution: "blocking",+ input: {},+ runId: "tool-run",+ sequence: 0,+ stepIndex: 0,+ toolName: "work",+ turnId: "turn-1",+ },+ update: "working",+ };+ installHooks(+ createMockHook({+ token: "stable",+ reads: [+ Promise.resolve(resolved(authCallback("weather"))),+ Promise.resolve(resolved(report)),+ Promise.resolve(resolved(send("hello"))),+ ],+ }),+ );+ const inbox = createSessionInbox("session-1");+ await inbox.claimSessionHook("stable");+ await expect(readResult(inbox)).resolves.toEqual(resolved(authCallback("weather")));+ await expect(readResult(inbox)).resolves.toEqual(resolved(report));+ await expect(readResult(inbox)).resolves.toEqual(resolved(send("hello")));+ expect(inbox.drain()).toEqual([]);+ expect(createHookMock).toHaveBeenCalledOnce();+ expect(await inbox.release()).toEqual([]);+ });++ it("keeps a pushed cancellation queued for the consumer", async () => {+ const input = createDeferred<IteratorResult<SessionInboxPayload>>();+ installHooks(createMockHook({ token: "stable", reads: [input.promise] }));+ const inbox = createSessionInbox("session-1");+ await inbox.claimSessionHook("stable");+ const interrupt = nextInterrupt(inbox);+ input.resolve(resolved({ kind: "cancel" }));+ await expect(interrupt).resolves.toEqual({ kind: "cancel" });+ expect(inbox.drain()).toEqual([{ kind: "cancel" }]);+ expect(await inbox.release()).toEqual([]);+ });++ it("stops notifying an unsubscribed interrupt handler", async () => {+ const first = createDeferred<IteratorResult<SessionInboxPayload>>();+ const second = createDeferred<IteratorResult<SessionInboxPayload>>();+ installHooks(createMockHook({ token: "stable", reads: [first.promise, second.promise] }));+ const inbox = createSessionInbox("session-1");+ await inbox.claimSessionHook("stable");+ const handler = vi.fn();+ const unsubscribe = inbox.onInterrupt(handler);+ first.resolve(resolved({ kind: "cancel", turnId: "turn-1" }));+ await first.promise;+ unsubscribe();+ second.resolve(resolved({ kind: "reset" }));+ await second.promise;+ expect(handler).toHaveBeenCalledExactlyOnceWith({ kind: "cancel", turnId: "turn-1" });+ expect(inbox.drain()).toEqual([{ kind: "cancel", turnId: "turn-1" }, { kind: "reset" }]);+ await inbox.dispose();+ });++ it("pumps several messages before the owner reads and drains them exactly once", async () => {+ const first = createDeferred<IteratorResult<SessionInboxPayload>>();+ const second = createDeferred<IteratorResult<SessionInboxPayload>>();+ const third = createDeferred<IteratorResult<SessionInboxPayload>>();+ installHooks(+ createMockHook({ token: "stable", reads: [first.promise, third.promise] }),+ createMockHook({ token: "alias", reads: [second.promise] }),+ );+ const inbox = createSessionInbox("session-1");+ await inbox.claimSessionHook("stable");+ await inbox.claimSessionHook("alias");+ first.resolve(resolved(send("first")));+ await first.promise;+ second.resolve(resolved(send("second")));+ await second.promise;+ third.resolve(resolved(send("third")));+ await third.promise;+ expect(inbox.drain()).toEqual([send("first"), send("second"), send("third")]);+ expect(inbox.drain()).toEqual([]);+ expect(await inbox.release()).toEqual([]);+ });++ it("keeps pumping so a cancel behind a burst of unread messages still interrupts", async () => {+ const burst = Array.from({ length: 1500 }, (_, index) =>+ Promise.resolve(resolved(send(`message ${String(index)}`))),+ );+ installHooks(+ createMockHook({+ token: "stable",+ reads: [...burst, Promise.resolve(resolved({ kind: "cancel" }))],+ }),+ );+ const inbox = createSessionInbox("session-1");+ const interrupt = nextInterrupt(inbox);+ await inbox.claimSessionHook("stable");++ await expect(interrupt).resolves.toEqual({ kind: "cancel" });+ expect(inbox.drain()).toHaveLength(1501);+ await inbox.dispose();+ });++ it("surfaces a failed reader instead of silently leaving the owner asleep", async () => {+ const read = createDeferred<IteratorResult<SessionInboxPayload>>();+ installHooks(createMockHook({ token: "stable", reads: [read.promise] }));+ const inbox = createSessionInbox("session-1");+ await inbox.claimSessionHook("stable");+ const pending = expect(readResult(inbox)).rejects.toThrow("reader failed");+ read.reject(new Error("reader failed"));+ await pending;+ await inbox.dispose();+ });++ it("accounts for an accepted unread command before releasing ownership", async () => {+ installHooks(+ createMockHook({+ reads: [Promise.resolve(resolved(send("during release")))],+ token: "stable",+ }),+ );+ const inbox = createSessionInbox("session-1");+ await inbox.claimSessionHook("stable");++ await expect(inbox.release()).resolves.toEqual([send("during release")]);+ });++ it("restores released payloads ahead of commands accepted after reclaiming", async () => {+ installHooks(+ createMockHook({ reads: [Promise.resolve(resolved(send("released")))], token: "stable" }),+ createMockHook({+ reads: [Promise.resolve(resolved(send("after reclaim")))],+ token: "stable",+ }),+ );+ const inbox = createSessionInbox("session-1");+ await inbox.claimSessionHook("stable");+ const released = await inbox.release();+ expect(released).toEqual([send("released")]);++ await inbox.claimSessionHook("stable");+ await vi.waitFor(() => expect(inbox.hasPending()).toBe(true));+ inbox.restore([...released, send("second released")]);++ expect(inbox.drain()).toEqual([+ send("released"),+ send("second released"),+ send("after reclaim"),+ ]);+ await inbox.dispose();+ });++ it("keeps every continuation alias active after later claims", async () => {+ const oldRead = createDeferred<IteratorResult<SessionInboxPayload>>();+ const replacementRead = createDeferred<IteratorResult<SessionInboxPayload>>();+ const stable = createMockHook({ token: "stable" });+ const oldAlias = createMockHook({ reads: [oldRead.promise], token: "old" });+ const replacement = createMockHook({+ reads: [replacementRead.promise],+ token: "replacement",+ });+ installHooks(stable, oldAlias, replacement);+ const inbox = createSessionInbox("session-1");++ await inbox.claimSessionHook("stable");+ await inbox.claimSessionHook("old");+ const pending = readResult(inbox);+ await inbox.claimSessionHook("replacement");++ oldRead.resolve(resolved(send("old")));+ await expect(pending).resolves.toEqual(resolved(send("old")));++ replacementRead.resolve(resolved(send("replacement")));+ await expect(readResult(inbox)).resolves.toEqual(resolved(send("replacement")));+ await inbox.dispose();++ expect(stable.dispose).toHaveBeenCalledOnce();+ expect(oldAlias.dispose).toHaveBeenCalledOnce();+ expect(replacement.dispose).toHaveBeenCalledOnce();+ });++ it("adds a first continuation alias to an existing stable wait", async () => {+ installHooks(+ createMockHook({ token: "stable" }),+ createMockHook({+ reads: [Promise.resolve(resolved(send("anchored")))],+ token: "channel",+ }),+ );+ const inbox = createSessionInbox("session-1");++ await inbox.claimSessionHook("stable");+ const pending = readResult(inbox);+ await inbox.claimSessionHook("channel");++ await expect(pending).resolves.toEqual(resolved(send("anchored")));+ await inbox.dispose();+ });++ it("disposes a conflicting continuation candidate without releasing current ownership", async () => {+ const stable = createMockHook({ token: "stable" });+ const current = createMockHook({ token: "current" });+ const candidate = createMockHook({+ conflict: { runId: "wrun_owner" },+ token: "candidate",+ });+ installHooks(stable, current, candidate);+ const inbox = createSessionInbox("session-1");++ await inbox.claimSessionHook("stable");+ await inbox.claimSessionHook("current");+ await expect(inbox.claimSessionHook("candidate")).rejects.toMatchObject({+ conflictingRunId: "wrun_owner",+ name: "HookConflictError",+ token: "candidate",+ });++ expect(candidate.dispose).toHaveBeenCalledOnce();+ expect(current.dispose).not.toHaveBeenCalled();+ await inbox.dispose();+ expect(current.dispose).toHaveBeenCalledOnce();+ });++ it("deduplicates session hooks and preserves their claim order", async () => {+ const stable = createMockHook({ token: "stable" });+ const channel = createMockHook({ token: "channel" });+ installHooks(stable, channel);+ const inbox = createSessionInbox("session-1");++ await inbox.claimSessionHook("stable");+ await inbox.claimSessionHook("stable");+ await inbox.claimSessionHook("channel");+ expect(hookTokens(inbox)).toEqual(["stable", "channel"]);+ expect(createHookMock).toHaveBeenCalledTimes(2);+ expect(createHookMock).toHaveBeenCalledWith({+ metadata: { sessionId: "session-1" },+ token: sessionInboxHookToken("stable"),+ });+ await inbox.dispose();+ });++ it("waits for registration when two callers claim the same address", async () => {+ const registration = Promise.withResolvers<null>();+ installHooks(createMockHook({ token: "stable", registration: registration.promise }));+ const inbox = createSessionInbox("session-1");+ const first = inbox.claimSessionHook("stable");+ let secondSettled = false;+ const second = inbox.claimSessionHook("stable").then(() => {+ secondSettled = true;+ });+ await Promise.resolve();+ expect(secondSettled).toBe(false);+ registration.resolve(null);+ await Promise.all([first, second]);+ expect(createHookMock).toHaveBeenCalledOnce();+ await inbox.dispose();+ });++ it("rejects empty tokens", async () => {+ installHooks(createMockHook({ token: "stable" }), createMockHook({ token: "auth" }));+ const inbox = createSessionInbox("session-1");+ await expect(inbox.claimSessionHook("")).rejects.toThrow("nonempty");+ await inbox.claimSessionHook("stable");+ await inbox.dispose();+ });++ it("bounds the address set without charging repeated claims", async () => {+ const tokens = Array.from({ length: 256 }, (_, index) => `token-${index}`);+ installHooks(...tokens.map((token) => createMockHook({ token })));+ const inbox = createSessionInbox("session-1");+ for (const token of tokens) await inbox.claimSessionHook(token);+ await inbox.claimSessionHook(tokens[0]!);+ await expect(inbox.claimSessionHook("one-too-many")).rejects.toThrow("at most 256");+ expect(hookTokens(inbox)).toEqual(tokens);+ await inbox.dispose();+ });++ it("disposes active hooks without closing pending iterators", async () => {+ const stable = createMockHook({ token: "stable" });+ const alias = createMockHook({ token: "channel" });+ installHooks(stable, alias);+ const inbox = createSessionInbox("session-1");++ await inbox.claimSessionHook("stable");+ await inbox.claimSessionHook("channel");+ void inbox.next();+ await inbox.dispose();+ await inbox.dispose();++ expect(stable.dispose).toHaveBeenCalledOnce();+ expect(alias.dispose).toHaveBeenCalledOnce();+ expect(stable.return).not.toHaveBeenCalled();+ expect(alias.return).not.toHaveBeenCalled();+ });++ it("disposes every alias with the inbox", async () => {+ const auth = createMockHook({ token: "alias" });+ installHooks(createMockHook({ token: "stable" }), auth);+ const inbox = createSessionInbox("session-1");++ await inbox.claimSessionHook("stable");+ await inbox.claimSessionHook("alias");+ await inbox.dispose();++ expect(auth.dispose).toHaveBeenCalledOnce();+ expect(auth.return).not.toHaveBeenCalled();+ });+});++function authCallback(connectionName: string): SessionInboxPayload {+ return {+ kind: "authorization-callback",+ payloads: [+ {+ authorizationCallback: {+ callback: { method: "GET", params: { code: "abc" } },+ connectionName,+ },+ },+ ],+ };+}++interface MockHook {+ readonly dispose: ReturnType<typeof vi.fn>;+ readonly hook: unknown;+ readonly return: ReturnType<typeof vi.fn>;+ readonly token: string;+}++function createMockHook(input: {+ readonly registration?: Promise<null>;+ readonly conflict?: { readonly runId: string } | null;+ readonly reads?: readonly Promise<IteratorResult<SessionInboxPayload>>[];+ readonly token: string;+}): MockHook {+ const reads = [...(input.reads ?? [])];+ const dispose = vi.fn();+ const iteratorReturn = vi.fn(async () => ({ done: true, value: undefined }) as const);+ const hook = Object.assign(new Promise<SessionInboxPayload>(() => {}), {+ [Symbol.asyncIterator]() {+ return {+ next: vi.fn(+ () =>+ reads.shift() ??+ new Promise<IteratorResult<SessionInboxPayload>>(() => {+ // Intentionally pending.+ }),+ ),+ return: iteratorReturn,+ };+ },+ dispose,+ getConflict: vi.fn(async () => input.registration ?? input.conflict ?? null),+ token: input.token,+ });+ return { dispose, hook, return: iteratorReturn, token: input.token };+}++function installHooks(...hooks: readonly MockHook[]): void {+ const queue = [...hooks];+ createHookMock.mockImplementation((options: { readonly token: string }) => {+ const hook = queue.shift();+ if (hook === undefined || sessionInboxHookToken(hook.token) !== options.token) {+ throw new Error(`Unexpected hook token "${options.token}".`);+ }+ return hook.hook;+ });+}++function send(message: string): SessionInboxPayload {+ return { kind: "send", payload: { message } };+}++function resolved(value: SessionInboxPayload): IteratorResult<SessionInboxPayload> {+ return { done: false, value };+}++function createDeferred<T>() {+ return Promise.withResolvers<T>();+}diff --git a/packages/eve/src/execution/session-inbox/inbox.ts b/packages/eve/src/execution/session-inbox/inbox.tsnew file mode 100644index 000000000..4d98c22e7--- /dev/null+++ b/packages/eve/src/execution/session-inbox/inbox.ts@@ -0,0 +1,205 @@+import { sessionInboxHookToken } from "#execution/session-inbox/address.js";+import { createHook, getWorkflowMetadata, type Hook } from "#compiled/@workflow/core/index.js";+import { releaseSessionHooksStep } from "#execution/session-inbox/release-step.js";++import type { DeliverPayload, HookPayload, SessionCommand } from "#channel/types.js";+import { claimHookOwnership, disposeHook } from "#execution/hook-ownership.js";+import type { WorkflowToolRunMessage } from "#execution/tools/workflow/messages.js";++/** All session addresses accept the same protocol. Callback routes construct+ * their own message kind; they never accept arbitrary session commands. */+export interface AuthorizationCallbackPayload {+ readonly kind: "authorization-callback";+ readonly payloads: DeliverPayload[];+}++export type SessionInboxPayload =+ | HookPayload+ | SessionCommand+ | WorkflowToolRunMessage+ | AuthorizationCallbackPayload;++interface Source {+ readonly token: string;+ readonly hook: Hook<SessionInboxPayload>;+ registered?: Promise<void>;+ stopping: boolean;+ closed: boolean;+}++export interface SessionInboxReader {+ /**+ * Waits for and removes the next accepted payload in arrival order, or+ * `undefined` once every hook is released. Only one consumer waits at a+ * time; the owner program is strictly sequential.+ */+ next(): Promise<SessionInboxPayload | undefined>;+ /** Removes every payload accepted so far, in arrival order. */+ drain(): SessionInboxPayload[];+ hasPending(): boolean;+ /**+ * Called from the pump the moment an interrupt (`cancel`, `reset`,+ * `session-timeout`) is accepted, ahead of any consumer read. Handlers must+ * be synchronous and idempotent. The payload stays in the queue so the+ * consumer still processes it in order.+ */+ onInterrupt(handler: (payload: SessionInboxPayload) => void): () => void;+ restore(payloads: readonly SessionInboxPayload[]): void;+}++export interface SessionInboxOwnership {+ /** Logical tokens currently claimed, in claim order. */+ readonly claimedTokens: readonly string[];+ claimSessionHook(token: string): Promise<void>;+ /** Registers every token as one batch; all claims settle before the first failure propagates. */+ claimSessionHooks(tokens: readonly string[]): Promise<void>;+}+export interface SessionInbox extends SessionInboxReader, SessionInboxOwnership {}+export interface SessionInboxHandle extends SessionInbox {+ dispose(): Promise<void>;+ /** Disposes every hook and returns each payload the hooks accepted but the owner never read. */+ release(): Promise<SessionInboxPayload[]>;+}++export function isInterrupt(value: SessionInboxPayload): boolean {+ return value.kind === "cancel" || value.kind === "reset" || value.kind === "session-timeout";+}++/**+ * One FIFO queue for the session lifetime, fed by a continuous reader per+ * claimed hook. The pump never waits on queue depth: interrupts share each+ * hook's ordered stream, so any backpressure on ordinary payloads would also+ * hold back the cancel behind them. Accepted payloads are already durable on+ * the hook, so the queue is a mirror rather than the source of truth.+ */+export function createSessionInbox(sessionId: string): SessionInboxHandle {+ const sources: Source[] = [];+ const queue: SessionInboxPayload[] = [];+ const waiters = new Set<() => void>();+ const interruptHandlers = new Set<(payload: SessionInboxPayload) => void>();+ let failure: { error: unknown } | undefined;++ const notify = (): void => {+ for (const resolve of waiters) resolve();+ waiters.clear();+ };+ const wait = (): Promise<void> => new Promise((resolve) => waiters.add(resolve));+ const closed = (): boolean => sources.every((source) => source.closed || source.stopping);++ // The SDK abandons (never settles) a read that is in flight when the hook+ // is disposed, so the loop exits on `stopping` rather than on `done`.+ const pump = async (source: Source): Promise<void> => {+ const iterator = source.hook[Symbol.asyncIterator]();+ try {+ while (!source.stopping) {+ const result = await iterator.next();+ if (result.done) break;+ queue.push(result.value);+ if (isInterrupt(result.value))+ for (const handler of interruptHandlers) handler(result.value);+ notify();+ }+ } catch (error) {+ if (!source.stopping) failure = { error };+ } finally {+ source.closed = true;+ notify();+ }+ };++ const stop = async (): Promise<SessionInboxPayload[]> => {+ const released = sources.splice(0);+ for (const source of released) source.stopping = true;+ notify();+ await Promise.all(released.map(({ hook }) => disposeHook(hook)));+ const accepted = queue.splice(0);+ notify();+ return accepted;+ };++ const claimSessionHook = async (token: string): Promise<void> => {+ if (!token) throw new Error("A session alias requires a nonempty continuation token.");+ const existing = sources.find((source) => source.token === token);+ if (existing !== undefined) return await existing.registered;+ if (sources.length >= 256) throw new Error("A session may claim at most 256 addresses.");+ const source: Source = {+ token,+ hook: createHook<SessionInboxPayload>({+ token: sessionInboxHookToken(token),+ metadata: { sessionId },+ }),+ stopping: false,+ closed: false,+ };+ // Reserve the slot before awaiting registration: parallel claims retain+ // deterministic order and duplicate calls cannot create another hook.+ sources.push(source);+ try {+ source.registered = claimHookOwnership(source.hook);+ await source.registered;+ void pump(source);+ } catch (error) {+ sources.splice(sources.indexOf(source), 1);+ throw error;+ }+ };++ return {+ get claimedTokens() {+ return sources.map(({ token }) => token);+ },+ claimSessionHook,+ async claimSessionHooks(tokens) {+ const outcomes = await Promise.allSettled([...new Set(tokens)].map(claimSessionHook));+ for (const outcome of outcomes) if (outcome.status === "rejected") throw outcome.reason;+ },+ async next() {+ while (true) {+ if (failure !== undefined) throw failure.error;+ if (queue.length > 0) return queue.shift();+ if (closed()) return undefined;+ await wait();+ }+ },+ drain() {+ if (failure !== undefined) throw failure.error;+ return queue.splice(0);+ },+ hasPending() {+ if (failure !== undefined) throw failure.error;+ return queue.length > 0;+ },+ onInterrupt(handler) {+ interruptHandlers.add(handler);+ return () => interruptHandlers.delete(handler);+ },+ restore(payloads) {+ if (sources.length === 0)+ throw new Error("Cannot restore session commands before reclaiming the session hooks.");+ // Restored payloads were accepted before anything the reclaimed pumps+ // have enqueued since, so they must precede the current queue.+ queue.unshift(...payloads);+ notify();+ },+ async dispose() {+ // Accepted-but-unread payloads are dropped: disposal ends the session.+ await stop();+ },+ async release() {+ // Commit disposal durably before the readers stop: the SDK delivers every+ // hook event accepted before that commit to the iterators first, so the+ // queue holds each accepted payload when `stop()` drains it.+ if (sources.length > 0) {+ await releaseSessionHooksStep({+ ownerRunId: getWorkflowMetadata().workflowRunId,+ tokens: sources.map(({ hook }) => hook.token),+ });+ }+ return await stop();+ },+ };+}++export function isWorkflowMessage(value: SessionInboxPayload): value is WorkflowToolRunMessage {+ return value.kind === "report" || value.kind === "request" || value.kind === "outcome";+}diff --git a/packages/eve/src/execution/session-inbox/protocol.test.ts b/packages/eve/src/execution/session-inbox/protocol.test.tsnew file mode 100644index 000000000..e85289bae--- /dev/null+++ b/packages/eve/src/execution/session-inbox/protocol.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from "vitest";++import {+ decodeSessionInboxPayload,+ SessionInboxPayloadError,+} from "#execution/session-inbox/protocol.js";++describe("session inbox payloads", () => {+ it("normalizes send into the current delivery shape", () => {+ expect(+ decodeSessionInboxPayload({+ delivery: { deliveryId: "delivery-1" },+ kind: "send",+ payload: { message: "hello" },+ }),+ ).toEqual({+ auth: undefined,+ caller: undefined,+ deliveryMetadata: [{ deliveryId: "delivery-1", payloadIndex: 0 }],+ kind: "deliver",+ payloads: [{ message: "hello" }],+ requestId: undefined,+ taskDeliveryId: undefined,+ turnPolicy: undefined,+ });+ });++ it("accepts only current delivery and control kinds", () => {+ expect(decodeSessionInboxPayload({ kind: "deliver", payloads: [] })).toEqual({+ kind: "deliver",+ payloads: [],+ });+ expect(() => decodeSessionInboxPayload({ kind: "legacy-send" })).toThrowError(+ SessionInboxPayloadError,+ );+ });+});diff --git a/packages/eve/src/execution/session-inbox/protocol.ts b/packages/eve/src/execution/session-inbox/protocol.tsnew file mode 100644index 000000000..dcb46541b--- /dev/null+++ b/packages/eve/src/execution/session-inbox/protocol.ts@@ -0,0 +1,61 @@+import type {+ DeliverHookPayload,+ SessionCommand,+ SessionTimeoutHookPayload,+} from "#channel/types.js";++export type DecodedSessionInbox =+ | DeliverHookPayload+ | SessionTimeoutHookPayload+ | Extract<SessionCommand, { readonly kind: "cancel" | "clear" | "compact" | "reset" }>;++/** Invalid current-generation inbox payload. Historical wire shapes are not accepted. */+export class SessionInboxPayloadError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "SessionInboxPayloadError";+ }+}++/** Normalizes the one authored `send` convenience command into a delivery. */+export function decodeSessionInboxPayload(value: unknown): DecodedSessionInbox {+ if (value === null || typeof value !== "object" || !("kind" in value)) {+ throw new SessionInboxPayloadError("Session inbox payload must be an object with a kind.");+ }+ const payload = value as Record<string, unknown>;+ switch (payload.kind) {+ case "send": {+ if (payload.payload === null || typeof payload.payload !== "object") {+ throw new SessionInboxPayloadError("Session send payload must be an object.");+ }+ const command = value as Extract<SessionCommand, { readonly kind: "send" }>;+ return {+ auth: command.auth,+ caller: command.caller,+ deliveryMetadata:+ command.delivery === undefined ? undefined : [{ ...command.delivery, payloadIndex: 0 }],+ kind: "deliver",+ payloads: [command.payload],+ requestId: command.requestId,+ taskDeliveryId: command.taskDeliveryId,+ turnPolicy: command.turnPolicy,+ };+ }+ case "deliver": {+ if (!Array.isArray(payload.payloads)) {+ throw new SessionInboxPayloadError("Session delivery payloads must be an array.");+ }+ return value as DeliverHookPayload;+ }+ case "cancel":+ case "clear":+ case "compact":+ case "reset":+ case "session-timeout":+ return value as DecodedSessionInbox;+ default:+ throw new SessionInboxPayloadError(+ `Unsupported session inbox payload kind ${JSON.stringify(payload.kind)}.`,+ );+ }+}diff --git a/packages/eve/src/execution/session-inbox/release-step.test.ts b/packages/eve/src/execution/session-inbox/release-step.test.tsnew file mode 100644index 000000000..d48192ad0--- /dev/null+++ b/packages/eve/src/execution/session-inbox/release-step.test.ts@@ -0,0 +1,60 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";+import { releaseSessionHooksStep } from "./release-step.js";++const mocks = vi.hoisted(() => ({ create: vi.fn(), getByToken: vi.fn() }));+vi.mock("#internal/workflow/runtime.js", () => ({+ getWorld: async () => ({+ events: { create: mocks.create },+ hooks: { getByToken: mocks.getByToken },+ }),+}));++beforeEach(() => vi.resetAllMocks());++describe("releaseSessionHooksStep", () => {+ it("commits disposal for each exact owned hook", async () => {+ mocks.getByToken.mockImplementation(async (token: string) => ({+ hookId: `hook-${token}`,+ runId: "owner",+ specVersion: 7,+ }));+ await releaseSessionHooksStep({ ownerRunId: "owner", tokens: ["stable", "alias"] });+ for (const token of ["stable", "alias"]) {+ expect(mocks.create).toHaveBeenCalledWith("owner", {+ correlationId: `hook-${token}`,+ eventData: { token },+ eventType: "hook_disposed",+ specVersion: 7,+ });+ }+ });++ it("finishes a retry after an earlier attempt released part of the hook set", async () => {+ mocks.getByToken.mockRejectedValueOnce(new HookNotFoundError("stable"));+ mocks.getByToken.mockResolvedValueOnce({+ hookId: "hook-alias",+ runId: "owner",+ specVersion: 7,+ });+ await releaseSessionHooksStep({ ownerRunId: "owner", tokens: ["stable", "alias"] });+ expect(mocks.create).toHaveBeenCalledOnce();+ });++ it("never disposes another owner's claim", async () => {+ mocks.getByToken.mockResolvedValue({ hookId: "new-claim", runId: "successor" });+ await expect(+ releaseSessionHooksStep({ ownerRunId: "owner", tokens: ["stable"] }),+ ).rejects.toThrow("owned by another workflow");+ expect(mocks.create).not.toHaveBeenCalled();+ });++ it("propagates disposal failures so the reader is not stopped early", async () => {+ mocks.getByToken.mockResolvedValue({ hookId: "claim", runId: "owner", specVersion: 7 });+ const failure = new Error("storage unavailable");+ mocks.create.mockRejectedValue(failure);+ await expect(releaseSessionHooksStep({ ownerRunId: "owner", tokens: ["stable"] })).rejects.toBe(+ failure,+ );+ });+});diff --git a/packages/eve/src/execution/session-inbox/release-step.ts b/packages/eve/src/execution/session-inbox/release-step.tsnew file mode 100644index 000000000..6b2d74426--- /dev/null+++ b/packages/eve/src/execution/session-inbox/release-step.ts@@ -0,0 +1,33 @@+import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";+import { getWorld } from "#internal/workflow/runtime.js";++/** Commit disposal before readers stop: Workflow delivers earlier hook events before this step resolves. */+export async function releaseSessionHooksStep(input: {+ readonly ownerRunId: string;+ readonly tokens: readonly string[];+}): Promise<void> {+ "use step";++ const world = await getWorld();+ const outcomes = await Promise.allSettled(+ input.tokens.map(async (token) => {+ let hook;+ try {+ hook = await world.hooks.getByToken(token);+ } catch (error) {+ if (HookNotFoundError.is(error)) return;+ throw error;+ }+ if (hook.runId !== input.ownerRunId) {+ throw new Error("Cannot release a session hook owned by another workflow.");+ }+ await world.events.create(input.ownerRunId, {+ correlationId: hook.hookId,+ eventData: { token },+ eventType: "hook_disposed",+ specVersion: hook.specVersion,+ });+ }),+ );+ for (const outcome of outcomes) if (outcome.status === "rejected") throw outcome.reason;+}diff --git a/packages/eve/src/execution/session-inbox/resume.test.ts b/packages/eve/src/execution/session-inbox/resume.test.tsnew file mode 100644index 000000000..54ae66e67--- /dev/null+++ b/packages/eve/src/execution/session-inbox/resume.test.ts@@ -0,0 +1,81 @@+import { sessionInboxHookToken } from "#execution/session-inbox/address.js";+import { afterEach, describe, expect, it, vi } from "vitest";++import { sessionCommandHookToken } from "#execution/session-inbox/address.js";+import { resumeSessionInbox } from "#execution/session-inbox/resume.js";++const resumeHookMock = vi.fn();++vi.mock("#internal/workflow/runtime.js", () => ({+ resumeHook: (...args: unknown[]) => resumeHookMock(...args),+}));++afterEach(() => {+ resumeHookMock.mockReset();+});++describe("session inbox resume", () => {+ it("resumes the current owner while preserving public session identity", async () => {+ const token = sessionCommandHookToken("session-1");+ const hook = sessionHook("owner-2", token, { sessionId: "session-1" });+ resumeHookMock.mockResolvedValue(hook);++ const receipt = await resumeSessionInbox(token, { kind: "clear" });+ expect(receipt.ownerRunId).toBe("owner-2");+ await expect(receipt.sessionId).resolves.toBe("session-1");+ expect(resumeHookMock).toHaveBeenCalledWith(sessionInboxHookToken(token), { kind: "clear" });+ });++ it("resolves a saved public address through the stable token", async () => {+ const token = sessionCommandHookToken("session-1");+ const hook = sessionHook("owner-2", token, { sessionId: "session-1" });+ resumeHookMock.mockResolvedValue(hook);++ await resumeSessionInbox({ sessionId: "session-1" }, { kind: "compact" });+ expect(resumeHookMock).toHaveBeenCalledWith(sessionInboxHookToken(token), { kind: "compact" });+ });+ it("does not hydrate metadata until an accepted alias caller asks for identity", async () => {+ const metadata = vi.fn(() => Promise.resolve({ sessionId: "anchor" }));+ const acceptance = Promise.withResolvers<{+ readonly runId: string;+ readonly metadata: Promise<unknown>;+ }>();+ resumeHookMock.mockReturnValue(acceptance.promise);+ const delivery = resumeSessionInbox("channel:alias", { kind: "clear" });+ expect(metadata).not.toHaveBeenCalled();+ acceptance.resolve({+ runId: "successor",+ get metadata() {+ return metadata();+ },+ });+ const receipt = await delivery;+ expect(metadata).not.toHaveBeenCalled();+ await expect(receipt.sessionId).resolves.toBe("anchor");+ await expect(receipt.sessionId).resolves.toBe("anchor");+ expect(metadata).toHaveBeenCalledOnce();+ expect(resumeHookMock).toHaveBeenCalledOnce();+ });++ it("never reads metadata for a known session address", async () => {+ resumeHookMock.mockResolvedValue({+ runId: "successor",+ get metadata() {+ throw new Error("Metadata must not be read");+ },+ });+ const receipt = await resumeSessionInbox({ sessionId: "anchor" }, { kind: "clear" });+ await expect(receipt.sessionId).resolves.toBe("anchor");+ });++ it("does not substitute the executor for missing session identity", async () => {+ resumeHookMock.mockResolvedValue({ runId: "successor", metadata: Promise.resolve(undefined) });+ const receipt = await resumeSessionInbox("alias", { kind: "clear" });+ await expect(receipt.sessionId).rejects.toThrow("command accepted");+ expect(resumeHookMock).toHaveBeenCalledOnce();+ });+});++function sessionHook(runId: string, token: string, metadata: Record<string, unknown>) {+ return { metadata: Promise.resolve(metadata), runId, token };+}diff --git a/packages/eve/src/execution/session-inbox/resume.ts b/packages/eve/src/execution/session-inbox/resume.tsnew file mode 100644index 000000000..f84fe3bb1--- /dev/null+++ b/packages/eve/src/execution/session-inbox/resume.ts@@ -0,0 +1,122 @@+import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";+import type {+ DeliverHookPayload,+ SessionCommand,+ SessionTimeoutHookPayload,+} from "#channel/types.js";+import {+ resolveLegacyInbox,+ resumeLegacyInbox,+ UnsupportedLegacySessionError,+} from "#execution/legacy-session/inbox.js";+import {+ isSessionInboxAddress,+ SESSION_INBOX_SESSION_ID_METADATA_KEY,+ sessionCommandHookToken,+ sessionHandoffMarkerToken,+ sessionInboxHookToken,+ type SessionInboxAddress,+} from "#execution/session-inbox/address.js";+import { getHookByToken, resumeHook } from "#internal/workflow/runtime.js";+import { isObject } from "#shared/guards.js";++/** Longest a delivery waits for a mid-handoff successor to claim its hooks. */+const HANDOFF_RETRY_WINDOW_MS = 5_000;+const HANDOFF_RETRY_INTERVAL_MS = 20;++export interface ResumedSessionInboxHook {+ readonly ownerRunId: string;+ /** Lazy identity resolution; delivery never needs to decrypt hook metadata. */+ readonly sessionId: Promise<string>;+}++/**+ * Resumes the current owner with the current command shape. During a+ * deployment handoff the address is briefly unowned; the releasing owner+ * leaves a marker for that interval, so delivery retries instead of+ * reporting the session gone and letting a channel start a replacement.+ */+export async function resumeSessionInbox(+ address: string | SessionInboxAddress,+ command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload,+): Promise<ResumedSessionInboxHook> {+ const token = logicalToken(address);+ const deadline = Date.now() + HANDOFF_RETRY_WINDOW_MS;+ while (true) {+ let hook;+ try {+ hook = await resumeHook(sessionInboxHookToken(token), command);+ } catch (error) {+ if (!HookNotFoundError.is(error)) throw error;+ if (await isHandoffInProgress(token, deadline)) continue;+ return await resumeLegacyInbox(token, command).catch(rethrowUnsupportedAsNotFound);+ }+ let identity: Promise<string> | undefined;+ return {+ ownerRunId: hook.runId,+ get sessionId() {+ return (identity ??= (async () => {+ try {+ return typeof address === "string"+ ? requireSessionId(await hook.metadata)+ : address.sessionId;+ } catch (cause) {+ // A failed identity read must never cause a second delivery.+ throw new AcceptedSessionIdentityError(cause);+ }+ })());+ },+ };+ }+}++export class AcceptedSessionIdentityError extends Error {+ constructor(cause: unknown) {+ super("Session command accepted, but its session identity could not be resolved.", { cause });+ this.name = "AcceptedSessionIdentityError";+ }+}++export function requireSessionId(metadata: unknown): string {+ const value = isObject(metadata) ? metadata[SESSION_INBOX_SESSION_ID_METADATA_KEY] : undefined;+ if (typeof value !== "string" || value.length === 0)+ throw new Error("Session hook metadata is missing its session ID.");+ return value;+}++export async function resolveSessionInbox(token: string): Promise<{ sessionId: string }> {+ try {+ const hook = await getHookByToken(sessionInboxHookToken(token));+ return { sessionId: requireSessionId(await hook.metadata) };+ } catch (error) {+ if (!HookNotFoundError.is(error)) throw error;+ const target = await resolveLegacyInbox(token);+ return { sessionId: target.sessionId };+ }+}++/** A driver too old to import is, for every caller, a session that no longer exists. */+function rethrowUnsupportedAsNotFound(error: unknown): never {+ if (error instanceof UnsupportedLegacySessionError) throw new HookNotFoundError(error.message);+ throw error;+}++function logicalToken(address: string | SessionInboxAddress): string {+ if (typeof address === "string") return address;+ if (!isSessionInboxAddress(address))+ throw new Error("Session inbox target has an invalid address.");+ return sessionCommandHookToken(address.sessionId);+}++/** Waits one retry interval when a handoff marker exists; false once the window closes or no marker exists. */+async function isHandoffInProgress(token: string, deadline: number): Promise<boolean> {+ if (Date.now() >= deadline) return false;+ try {+ await getHookByToken(sessionHandoffMarkerToken(token));+ } catch (error) {+ if (HookNotFoundError.is(error)) return false;+ throw error;+ }+ await new Promise<void>((resolve) => setTimeout(resolve, HANDOFF_RETRY_INTERVAL_MS));+ return true;+}diff --git a/packages/eve/src/execution/session-limit-cancellation.integration.test.ts b/packages/eve/src/execution/session-limit-cancellation.integration.test.tsindex fac72a353..e8d8d344d 100644--- a/packages/eve/src/execution/session-limit-cancellation.integration.test.ts+++ b/packages/eve/src/execution/session-limit-cancellation.integration.test.ts@@ -1,3 +1,4 @@+import { sessionInboxHookToken } from "#execution/session-inbox/address.js";import { describe, expect, it } from "vitest";import { resumeHook, start } from "#internal/workflow/runtime.js";@@ -8,7 +9,7 @@ import {filterEventsByType,} from "#internal/testing/events.js";import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";-import { workflowEntry } from "#execution/workflow-entry.js";+import { workflowEntry } from "#execution/session/entry.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";/**@@ -56,7 +57,11 @@ async function deliver(const deadline = Date.now() + timeout;while (true) {try {- await resumeHook(continuationToken, { auth: null, kind: "send", payload });+ await resumeHook(sessionInboxHookToken(continuationToken), {+ auth: null,+ kind: "send",+ payload,+ });return;} catch (error) {if (Date.now() > deadline) throw error;@@ -85,6 +90,8 @@ describe("session-limit continuation decline integration", () => {await runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: "Hello there" },serializedContext: buildSerializedContext({channelKind: "http",diff --git a/packages/eve/src/execution/session-reset.integration.test.ts b/packages/eve/src/execution/session-reset.integration.test.tsindex 0a47d74c2..16b092208 100644--- a/packages/eve/src/execution/session-reset.integration.test.ts+++ b/packages/eve/src/execution/session-reset.integration.test.ts@@ -1,10 +1,11 @@+import { sessionInboxHookToken } from "#execution/session-inbox/address.js";import { describe, expect, it } from "vitest";import { ContextContainer, contextStorage } from "#context/container.js";import { SessionKey } from "#context/keys.js";import { ensureSandboxAccess } from "#execution/sandbox/ensure.js";import { clearActiveSandboxHandlesForTest } from "#execution/sandbox/active-handles.js";-import { sessionCommandInboxWorkflow } from "#internal/testing/session-command-inbox-workflow.js";+import { sessionCommandInboxWorkflow } from "#internal/testing/session-inbox-workflow.js";import { waitForHook } from "#internal/testing/workflow-test-helpers.js";import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";import { start } from "#internal/workflow/runtime.js";@@ -25,7 +26,7 @@ describe("session reset integration", () => {const first = await start(sessionCommandInboxWorkflow, [{ token: continuationToken }]);try {- await waitForHook(first, { token: continuationToken });+ await waitForHook(first, { token: sessionInboxHookToken(continuationToken) });await expect(sandboxes.open(first.runId)).resolves.toMatchObject({ id: "sandbox-1" });await expect(@@ -40,7 +41,9 @@ describe("session reset integration", () => {const second = await start(sessionCommandInboxWorkflow, [{ token: continuationToken }]);try {- await expect(waitForHook(second, { token: continuationToken })).resolves.toMatchObject({+ await expect(+ waitForHook(second, { token: sessionInboxHookToken(continuationToken) }),+ ).resolves.toMatchObject({runId: second.runId,});await expect(runtime.resolveContinuation(continuationToken)).resolves.toEqual({diff --git a/packages/eve/src/execution/session-state-cursor.ts b/packages/eve/src/execution/session-state-cursor.tsdeleted file mode 100644index 119caab8f..000000000--- a/packages/eve/src/execution/session-state-cursor.ts+++ /dev/null@@ -1,41 +0,0 @@-import type { DurableSessionState } from "#execution/durable-session-store.js";--/** A durable-state transition; absent fields keep the cursor's current value. */-export interface SessionStateTransition {- readonly serializedContext?: Record<string, unknown>;- readonly sessionState?: DurableSessionState;-}--/**- * Owns the mutable serialized-context / session-state pair that durable- * steps thread through a run. Holders adopt each step's transition instead- * of rebinding both values by hand at every callsite.- */-export class SessionStateCursor {- private currentSerializedContext: Record<string, unknown>;- private currentSessionState: DurableSessionState;-- constructor(input: {- readonly serializedContext: Record<string, unknown>;- readonly sessionState: DurableSessionState;- }) {- this.currentSerializedContext = input.serializedContext;- this.currentSessionState = input.sessionState;- }-- /** Latest adopted serialized runtime context. */- get serializedContext(): Record<string, unknown> {- return this.currentSerializedContext;- }-- /** Latest adopted durable session state. */- get sessionState(): DurableSessionState {- return this.currentSessionState;- }-- /** Adopts a state transition; fields a step did not change carry forward. */- adoptState(transition: SessionStateTransition): void {- this.currentSerializedContext = transition.serializedContext ?? this.currentSerializedContext;- this.currentSessionState = transition.sessionState ?? this.currentSessionState;- }-}diff --git a/packages/eve/src/execution/session-timeout.ts b/packages/eve/src/execution/session-timeout.tsdeleted file mode 100644index ced5b1a53..000000000--- a/packages/eve/src/execution/session-timeout.ts+++ /dev/null@@ -1,2 +0,0 @@-/** Default absolute lifetime of one durable session. */-export const DEFAULT_SESSION_TIMEOUT_MS = 30 * 24 * 60 * 60 * 1_000;diff --git a/packages/eve/src/execution/turn-workflow-tool-run.ts b/packages/eve/src/execution/session-workflow-tool-run.tssimilarity index 91%rename from packages/eve/src/execution/turn-workflow-tool-run.tsrename to packages/eve/src/execution/session-workflow-tool-run.tsindex 84fe44823..1f68dd5b1 100644--- a/packages/eve/src/execution/turn-workflow-tool-run.ts+++ b/packages/eve/src/execution/session-workflow-tool-run.ts@@ -5,7 +5,7 @@ import type {WorkflowToolRunRequestMessage,} from "#execution/tools/workflow/messages.js";import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";-import type { TurnExecutionCursor } from "#execution/turn-execution-cursor.js";+import type { SessionStateCursor } from "#execution/session/state-cursor.js";import { applyTaskAgentRequest } from "#execution/tools/subagent/task-agent-requests.js";import { cancelAgentInvocationOwnerStep } from "#execution/tools/subagent/task-cancel.js";import { releaseAgentInvocationOwnerStep } from "#execution/tools/subagent/invoke-step.js";@@ -29,7 +29,7 @@ import type {interface HandlerInput<T> {readonly callbackMetadataUrl: string;- readonly cursor: TurnExecutionCursor;+ readonly cursor: SessionStateCursor;readonly message: T;}@@ -46,7 +46,7 @@ export async function handleWorkflowToolRunMessage(case "report":await emitWorkflowToolRunReportStep({from: message.from,- parentWritable: input.cursor.parentWritable,+ sessionWritable: input.cursor.sessionWritable,update: message.update,});return undefined;@@ -63,7 +63,7 @@ async function handleWorkflowToolRunOutcome(): Promise<RuntimeActionResult | undefined> {const { cursor, message } = input;const recorded = findWorkflowToolRun(- cursor.sessionState.snapshot?.session.state,+ cursor.sessionState.snapshot.session.state,message.from.callId,);if (recorded?.runId !== message.from.runId) return undefined;@@ -85,12 +85,12 @@ async function handleWorkflowToolRunOutcome(ownerId: message.from.runId,sessionState: cursor.sessionState,});- await cursor.adopt({+ await cursor.apply({serializedContext: cursor.serializedContext,sessionState: released.sessionState,});- const sessionSnapshotState = cursor.sessionState.snapshot?.session.state;+ const sessionSnapshotState = cursor.sessionState.snapshot.session.state;const accepted =result.kind === "subagent-result"? result.callId === message.from.callId &&@@ -105,7 +105,7 @@ async function settleSubagentOutcome(const { cursor, message } = input;const result = workflowToolRunOutcomeToSubagentResult(message);if (result.origin === "child") {- await cursor.adopt(+ await cursor.apply(await applyTaskAgentRequest({accumulateUsage: false,@@ -126,7 +126,7 @@ async function handleWorkflowToolRunRequest(const { cursor, message } = input;if (message.request.kind === "agent-invoke" || message.request.kind === "agent-settled") {const recorded = findWorkflowToolRun(- cursor.sessionState.snapshot?.session.state,+ cursor.sessionState.snapshot.session.state,message.from.callId,);if (recorded?.runId !== message.from.runId) {@@ -150,7 +150,7 @@ async function handleWorkflowToolRunRequest(}return;}- await cursor.adopt(+ await cursor.apply(await applyTaskAgentRequest({accumulateUsage: message.from.resultKind !== "subagent",@@ -164,10 +164,10 @@ async function handleWorkflowToolRunRequest(return;}if (message.request.kind === "authorization-request") {- await cursor.adopt(+ await cursor.apply(await runProxySubagentEventStep({hookPayload: message.request.event,- parentWritable: cursor.parentWritable,+ sessionWritable: cursor.sessionWritable,serializedContext: cursor.serializedContext,sessionState: cursor.sessionState,}),@@ -176,13 +176,13 @@ async function handleWorkflowToolRunRequest(await resumeHookStep(message.replyTo, null, { ifPresent: true });return;}- await cursor.adopt(+ await cursor.apply(await runProxySubagentEventStep({...(message.requestCoordinates === undefined? { answerHook: { runId: message.from.runId } }: {}),hookPayload: workflowToolRunRequestToInputRequestPayload(message),- parentWritable: cursor.parentWritable,+ sessionWritable: cursor.sessionWritable,serializedContext: cursor.serializedContext,sessionState: cursor.sessionState,}),@@ -192,7 +192,7 @@ async function handleWorkflowToolRunRequest(function requestContext(input: HandlerInput<unknown>) {return {callbackBaseUrl: resolveWorkflowCallbackBaseUrl(input.callbackMetadataUrl),- parentWritable: input.cursor.parentWritable,+ sessionWritable: input.cursor.sessionWritable,serializedContext: input.cursor.serializedContext,sessionState: input.cursor.sessionState,};diff --git a/packages/eve/src/execution/session/accepted-deployment.ts b/packages/eve/src/execution/session/accepted-deployment.tsnew file mode 100644index 000000000..d72e34227--- /dev/null+++ b/packages/eve/src/execution/session/accepted-deployment.ts@@ -0,0 +1,18 @@+import type { DeliverHookPayload } from "#channel/types.js";++/** Exact trusted deployment shared by every payload in a delivery. */+export function readAcceptedDeploymentId(delivery: DeliverHookPayload): string | undefined {+ const acceptedDeploymentId = delivery.deliveryMetadata?.[0]?.acceptedDeploymentId;+ if (+ acceptedDeploymentId === undefined ||+ acceptedDeploymentId.length === 0 ||+ acceptedDeploymentId === "latest"+ ) {+ return undefined;+ }+ return delivery.deliveryMetadata?.every(+ (metadata) => metadata.acceptedDeploymentId === acceptedDeploymentId,+ )+ ? acceptedDeploymentId+ : undefined;+}diff --git a/packages/eve/src/execution/session/admission.ts b/packages/eve/src/execution/session/admission.tsnew file mode 100644index 000000000..b63e7387b--- /dev/null+++ b/packages/eve/src/execution/session/admission.ts@@ -0,0 +1,113 @@+import { getWorkflowMetadata } from "#compiled/@workflow/core/index.js";++import type { RuntimeActionResultHookPayload, SessionCommand } from "#channel/types.js";+import { cancelAllIndexedSessionTasksStep } from "#execution/cancel-indexed-session-tasks-step.js";+import type { DeliveryAdmission, SessionInputQueue } from "#execution/session/input-queue.js";+import { isWorkflowMessage, type SessionInboxPayload } from "#execution/session-inbox/inbox.js";+import {+ decodeSessionInboxPayload,+ SessionInboxPayloadError,+} from "#execution/session-inbox/protocol.js";+import { reportDroppedWirePayloadStep } from "#execution/report-dropped-wire-payload-step.js";+import type { SessionStateCursor } from "#execution/session/state-cursor.js";+import type { WorkflowToolRunMessage } from "#execution/tools/workflow/messages.js";+import { findRunningAgentHandle } from "#subagents/handles/query.js";+import { runProxySubagentEventStep } from "#subagents/event-proxy-step.js";++export type SessionCancellation = Extract<SessionCommand, { readonly kind: "cancel" }>;++/** One canonical admission result, after wire decoding but before turn policy. */+export type SessionAdmission =+ | { readonly admission: DeliveryAdmission; readonly kind: "delivery" }+ | { readonly command: SessionCancellation; readonly kind: "cancel" }+ | { readonly kind: "consumed" }+ | { readonly kind: "runtime-action-result"; readonly payload: RuntimeActionResultHookPayload }+ | { readonly kind: "workflow"; readonly message: WorkflowToolRunMessage };++/**+ * Decodes and admits one inbox payload. This boundary never decides whether a+ * delivery steers, starts a turn, or routes to a child; those are selection+ * and delivery-routing policies owned by their respective layers.+ */+export async function admitSessionInboxPayload(+ value: SessionInboxPayload,+ input: {+ readonly cursor: SessionStateCursor;+ readonly queue: SessionInputQueue;+ },+): Promise<SessionAdmission> {+ if (value.kind === "runtime-action-result")+ return { kind: "runtime-action-result", payload: value };+ if (isWorkflowMessage(value)) return { kind: "workflow", message: value };+ if (value.kind === "authorization-callback") {+ input.queue.enqueueAuthorization(value.payloads);+ return { kind: "consumed" };+ }+ if (value.kind === "subagent-input-request" || value.kind === "subagent-authorization-event") {+ const handle = findRunningAgentHandle(input.cursor.sessionState.snapshot.session.state, {+ callId: value.callId,+ });+ if (+ handle?.identity.name === value.subagentName &&+ handle.address.sessionId === value.childSessionId+ ) {+ await input.cursor.apply(+ await runProxySubagentEventStep({+ hookPayload: value,+ sessionWritable: input.cursor.sessionWritable,+ serializedContext: input.cursor.serializedContext,+ sessionState: input.cursor.sessionState,+ }),+ );+ }+ return { kind: "consumed" };+ }++ let command;+ try {+ command = decodeSessionInboxPayload(value);+ } catch (error) {+ if (!(error instanceof SessionInboxPayloadError)) throw error;+ await reportDroppedWirePayloadStep({ detail: error.message, family: "session-inbox" });+ return { kind: "consumed" };+ }++ switch (command.kind) {+ case "deliver": {+ const admission = input.queue.enqueueDelivery(command);+ return admission === undefined ? { kind: "consumed" } : { admission, kind: "delivery" };+ }+ case "clear":+ case "compact":+ input.queue.enqueueControl(command.kind);+ return { kind: "consumed" };+ case "session-timeout":+ // A previous owner's timer may fire after handoff; only this owner's deadline counts.+ if (command.ownerRunId === getWorkflowMetadata().workflowRunId) {+ input.queue.enqueueControl("expired");+ }+ return { kind: "consumed" };+ case "reset":+ input.queue.enqueueControl("reset");+ return { command: { kind: "cancel" }, kind: "cancel" };+ case "cancel":+ return { command, kind: "cancel" };+ }+}++/** Applies accepted cancellation effects after the active-turn guard passes. */+export async function applySessionCancellation(+ command: SessionCancellation,+ input: {+ readonly cursor: SessionStateCursor;+ readonly queue: SessionInputQueue;+ },+): Promise<void> {+ if (command.tasks === true) {+ await cancelAllIndexedSessionTasksStep({+ serializedContext: input.cursor.serializedContext,+ sessionState: input.cursor.sessionState,+ });+ }+ if (command.taskId !== undefined) input.queue.cancelTask(command.taskId);+}diff --git a/packages/eve/src/execution/session/entry-input.ts b/packages/eve/src/execution/session/entry-input.tsnew file mode 100644index 000000000..94dc7f97f--- /dev/null+++ b/packages/eve/src/execution/session/entry-input.ts@@ -0,0 +1,44 @@+import type { TokenUsage } from "#shared/token-usage.js";+import type { DeliverHookPayload, RunInput, SessionCommand } from "#channel/types.js";+import type { SessionCheckpoint } from "#execution/session/handoff.js";+import type { AgentWorkflowRetentionDefinition } from "#shared/agent-definition.js";++/**+ * Serializable workflow-entry input. All runtime state travels via+ * `serializedContext`, which is produced by `serializeContext(ctx)`+ * and deserialized at each `"use step"` boundary.+ */+export interface InitialWorkflowEntryInput {+ readonly activityCollectorRunId?: string;+ readonly continuationConflictCommand?: Extract<SessionCommand, { readonly kind: "send" }>;+ readonly input: RunInput["input"];+ readonly kind: "initial";+ readonly limits?: RunInput["limits"];+ readonly ownerDeploymentId: string;+ readonly retention?: AgentWorkflowRetentionDefinition;+ readonly sessionTimeoutMs?: number | false;+ readonly serializedContext: Record<string, unknown>;+ readonly taskId?: string;+}++/** A successor owner started by a previous owner during a deployment handoff. */+export interface HandoffWorkflowEntryInput {+ readonly activationToken: string;+ readonly checkpoint: SessionCheckpoint;+ /** The one delivery that triggered the handoff; processed before any later arrival. */+ readonly delivery: DeliverHookPayload;+ readonly kind: "handoff";+ readonly ownerDeploymentId: string;+ readonly sessionWritable: WritableStream<Uint8Array>;+ /** Stable public identity; also the original run that anchors the stream. */+ readonly sessionId: string;+}++export type WorkflowEntryInput = InitialWorkflowEntryInput | HandoffWorkflowEntryInput;++export interface WorkflowEntryResult {+ readonly isError?: boolean;+ readonly usage?: TokenUsage;+ readonly usageDelta?: TokenUsage;+ readonly output: unknown;+}diff --git a/packages/eve/src/execution/workflow-entry.integration.test.ts b/packages/eve/src/execution/session/entry.integration.test.tssimilarity index 58%rename from packages/eve/src/execution/workflow-entry.integration.test.tsrename to packages/eve/src/execution/session/entry.integration.test.tsindex 4f5fdeed3..173bfc97a 100644--- a/packages/eve/src/execution/workflow-entry.integration.test.ts+++ b/packages/eve/src/execution/session/entry.integration.test.ts@@ -1,19 +1,27 @@+import type { RunCreatedEventRequest } from "@workflow/world";+import { DEFAULT_SESSION_TIMEOUT_MS } from "#execution/session/timeout.js";import { afterEach, describe, expect, it, vi } from "vitest";import { getWorld, resumeHook, start } from "#internal/workflow/runtime.js";-import { hydrateWorkflowArguments } from "@workflow/core/serialization";+import {+ dehydrateWorkflowArguments,+ hydrateWorkflowArguments,+ hydrateStepReturnValue,+} from "@workflow/core/serialization";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 { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";-import { workflowEntry } from "#execution/workflow-entry.js";+import { workflowEntry } from "#execution/session/entry.js";+import { sessionInboxHookToken } from "#execution/session-inbox/address.js";+import { sessionCommandHookToken } from "#execution/session-inbox/address.js";import {buildSessionAttributes,buildSubagentRootAttributes,} from "#execution/eve-workflow-attributes.js";import { createToolExecuteWithAuth } from "#execution/tool-auth.js";-import { createWorkflowRuntime } from "#execution/workflow-runtime.js";+import { createWorkflowRuntime, waitForCommandHookOwner } from "#execution/workflow-runtime.js";import { normalizeEveAttributes } from "#runtime/attributes/normalize.js";import { ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";import { ConnectionAuthorizationRequiredError } from "#connections/errors.js";@@ -99,7 +107,7 @@ interface WeatherAuthRuntime {* A get_weather tool behind an interactive authorization: getToken always* requires sign-in, and completeAuthorization mints `weather-token` from the* `oauth-code` callback. Shared by the callback-resume and- * challenge-stays-open driver tests.+ * challenge-stays-open owner tests.*/async function createWeatherAuthRuntime(agentName: string): Promise<WeatherAuthRuntime> {let completeCalls = 0;@@ -210,6 +218,49 @@ function expectSingleTurn(events: readonly MessageStreamEvent[], turnId: string)}describe("workflowEntry integration", () => {+ it("persists model output before settlement when a stream append exceeds the SDK flush window", async () => {+ const runtime = await createTestRuntime({ agent: { name: "workflow-stream-order" } });+ const world = await getWorld();+ const append = world.streams.writeMulti!.bind(world.streams);+ let delayedAppend: Promise<void> | undefined;+ const write = vi.spyOn(world.streams, "writeMulti").mockImplementation(async (...args) => {+ if (args[1].endsWith("_user") && delayedAppend === undefined) {+ delayedAppend = new Promise((resolve) => setTimeout(resolve, 1_200));+ await delayedAppend;+ }+ return await append(...args);+ });+ try {+ await runtime.run(async () => {+ const run = await start(workflowEntry, [+ {+ kind: "initial",+ ownerDeploymentId: "dpl_inline",+ input: { message: "Say hello to Alice." },+ serializedContext: buildSerializedContext({+ channelKind: "http",+ mode: "conversation",+ }),+ },+ ]);+ const stream = captureTurnEvents(run);+ try {+ const events = await stream.nextTurn();+ expect(delayedAppend).toBeDefined();+ expect(filterEventsByType(events, "message.completed")).toHaveLength(1);+ expectSingleTurn(events, "turn_0");+ expect(events.at(-1)?.type).toBe("session.waiting");+ } finally {+ await delayedAppend;+ stream.dispose();+ await run.cancel();+ }+ });+ } finally {+ write.mockRestore();+ }+ });+it("resumes normal follow-ups after an interactive authorization callback", async () => {const { completeCalls, runtime } = await createWeatherAuthRuntime("workflow-entry-auth-followup",@@ -219,6 +270,8 @@ describe("workflowEntry integration", () => {await runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: "Use the get_weather tool to check the weather in Lisbon." },serializedContext: buildSerializedContext({auth: {@@ -258,9 +311,10 @@ describe("workflowEntry integration", () => {(event) => event.type === "session.waiting",);expect(parkBoundary.at(-1)?.type).toBe("session.waiting");+ await expectHookClaims(run.runId, [sessionCommandHookToken(run.runId), continuationToken]);- await resumeHook(`${run.runId}:auth`, {- kind: "deliver",+ await resumeHook(sessionInboxHookToken(sessionCommandHookToken(run.runId)), {+ kind: "authorization-callback",payloads: [{authorizationCallback: {@@ -300,10 +354,10 @@ describe("workflowEntry integration", () => {await waitForHook({ runId: run.runId },{- token: continuationToken,+ token: sessionInboxHookToken(continuationToken),},);- await resumeHook(continuationToken, {+ await resumeHook(sessionInboxHookToken(continuationToken), {kind: "send",payload: { message: "follow up after auth" },});@@ -337,6 +391,8 @@ describe("workflowEntry integration", () => {await runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: "Use the get_weather tool to check the weather in Lisbon." },serializedContext: buildSerializedContext({auth: {@@ -369,8 +425,11 @@ describe("workflowEntry integration", () => {// An ordinary message while the challenge is open runs as a normal// turn instead of queueing behind the callback.- await waitForHook({ runId: run.runId }, { token: continuationToken });- await resumeHook(continuationToken, {+ await waitForHook(+ { runId: run.runId },+ { token: sessionInboxHookToken(continuationToken) },+ );+ await resumeHook(sessionInboxHookToken(continuationToken), {auth: {attributes: {},authenticator: "test-idp",@@ -398,8 +457,8 @@ describe("workflowEntry integration", () => {// The callback still lands on the retained read and closes the// challenge exactly once.- await resumeHook(`${run.runId}:auth`, {- kind: "deliver",+ await resumeHook(sessionInboxHookToken(sessionCommandHookToken(run.runId)), {+ kind: "authorization-callback",payloads: [{authorizationCallback: {@@ -429,7 +488,7 @@ describe("workflowEntry integration", () => {// The granted authorization serves the next explicit tool request.// (No waitForHook here: it only reports never-received hooks, and// the continuation hook already received the intervening message.)- await resumeHook(continuationToken, {+ await resumeHook(sessionInboxHookToken(continuationToken), {auth: {attributes: {},authenticator: "test-idp",@@ -473,6 +532,8 @@ describe("workflowEntry integration", () => {await runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: "Use the get_weather tool to check the weather in Lisbon." },serializedContext: buildSerializedContext({auth: {@@ -496,13 +557,16 @@ describe("workflowEntry integration", () => {(event) => event.type === "authorization.required",);- await waitForHook({ runId: run.runId }, { token: continuationToken });- await resumeHook(continuationToken, {+ await waitForHook(+ { runId: run.runId },+ { token: sessionInboxHookToken(continuationToken) },+ );+ await resumeHook(sessionInboxHookToken(continuationToken), {kind: "send",payload: { message: "This must not become a second task turn." },});- await resumeHook(`${run.runId}:auth`, {- kind: "deliver",+ await resumeHook(sessionInboxHookToken(sessionCommandHookToken(run.runId)), {+ kind: "authorization-callback",payloads: [{authorizationCallback: {@@ -540,6 +604,8 @@ describe("workflowEntry integration", () => {await runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: "Use the get_weather tool to check the weather in Lisbon." },serializedContext: buildSerializedContext({auth: {@@ -567,8 +633,11 @@ describe("workflowEntry integration", () => {(event) => event.type === "session.waiting",);- await waitForHook({ runId: run.runId }, { token: continuationToken });- await resumeHook(continuationToken, {+ await waitForHook(+ { runId: run.runId },+ { token: sessionInboxHookToken(continuationToken) },+ );+ await resumeHook(sessionInboxHookToken(continuationToken), {kind: "send",payload: { message: "Use the get_weather tool to check the weather in Lisbon." },});@@ -591,11 +660,17 @@ describe("workflowEntry integration", () => {connectionName: "weather",},};- await resumeHook(`${run.runId}:auth`, { kind: "deliver", payloads: [stalePayload] });- await resumeHook(`${run.runId}:auth`, { kind: "deliver", payloads: [stalePayload] });+ await resumeHook(sessionInboxHookToken(sessionCommandHookToken(run.runId)), {+ kind: "authorization-callback",+ payloads: [stalePayload],+ });+ await resumeHook(sessionInboxHookToken(sessionCommandHookToken(run.runId)), {+ kind: "authorization-callback",+ payloads: [stalePayload],+ });- await resumeHook(`${run.runId}:auth`, {- kind: "deliver",+ await resumeHook(sessionInboxHookToken(sessionCommandHookToken(run.runId)), {+ kind: "authorization-callback",payloads: [{authorizationCallback: {@@ -627,6 +702,8 @@ describe("workflowEntry integration", () => {await runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: "Use the get_weather tool to check the weather in Lisbon." },serializedContext: buildSerializedContext({auth: {@@ -658,17 +735,20 @@ describe("workflowEntry integration", () => {// 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- // session activity re-parks the driver.- await waitForHook({ runId: run.runId }, { token: continuationToken });- await resumeHook(continuationToken, { kind: "cancel" });- // Let the driver consume the no-op cancel and re-enter the parked+ // session activity re-parks the owner.+ await waitForHook(+ { runId: run.runId },+ { token: sessionInboxHookToken(continuationToken) },+ );+ await resumeHook(sessionInboxHookToken(continuationToken), { kind: "cancel" });+ // Let the owner consume the no-op cancel and re-enter the parked// wait before the callback fires; back-to-back resumes could// otherwise surface the callback in the first wait iteration and// mask a wait that ignores callbacks after a consumed cancel.await new Promise((resolve) => setTimeout(resolve, 250));- await resumeHook(`${run.runId}:auth`, {- kind: "deliver",+ await resumeHook(sessionInboxHookToken(sessionCommandHookToken(run.runId)), {+ kind: "authorization-callback",payloads: [{authorizationCallback: {@@ -711,6 +791,8 @@ describe("workflowEntry integration", () => {await runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: "hello there" },serializedContext: buildSerializedContext({acceptedDeploymentId: "dpl_inline",@@ -726,14 +808,14 @@ describe("workflowEntry integration", () => {const hook = await waitForHook({ runId: run.runId },{- token: continuationToken,+ token: sessionInboxHookToken(continuationToken),},);try {const firstTurn = await stream.nextTurn();- expect(hook.token).toBe(continuationToken);+ expect(hook.token).toBe(sessionInboxHookToken(continuationToken));expect(firstTurn.at(-1)).toMatchObject({data: { continuationToken: "workflow-entry-conversation" },type: "session.waiting",@@ -806,6 +888,8 @@ describe("workflowEntry integration", () => {await runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: "hello there" },serializedContext: buildSerializedContext({channelKind: "http",@@ -820,6 +904,7 @@ describe("workflowEntry integration", () => {data: { continuationToken: run.runId },type: "session.waiting",});+ await expectHookClaims(run.runId, [sessionCommandHookToken(run.runId)]);} finally {stream.dispose();await run.cancel();@@ -834,6 +919,8 @@ describe("workflowEntry integration", () => {await runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: "identify these events" },serializedContext: buildSerializedContext({channelKind: "http",@@ -900,6 +987,8 @@ describe("workflowEntry integration", () => {await runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: "hello there" },serializedContext: buildSerializedContext({channelKind: "http",@@ -938,7 +1027,7 @@ describe("workflowEntry integration", () => {await waitForHook({ runId: replacement.id },{- token: continuationToken,+ token: sessionInboxHookToken(continuationToken),},);} finally {@@ -965,12 +1054,14 @@ describe("workflowEntry integration", () => {await runtime.run(async () => {const child = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: "delegated first turn" },serializedContext: buildSerializedContext({channelKind: "subagent",channelState: {callId: "call-1",- parentContinuationToken: childContinuationToken,+ parentContinuationToken: sessionInboxHookToken(childContinuationToken),parentSessionId: "parent-session",subagentName: "researcher",},@@ -1001,7 +1092,7 @@ describe("workflowEntry integration", () => {command: {caller: {callId: "call-2",- replyTo: { kind: "hook", token: childContinuationToken },+ replyTo: { kind: "hook", token: sessionInboxHookToken(childContinuationToken) },subagentName: "researcher",},kind: "send",@@ -1041,6 +1132,644 @@ describe("workflowEntry integration", () => {});});+ it("forwards continued-turn HITL through the rebound caller", async () => {+ const runtime = await createTestRuntime({+ agent: { name: "workflow-entry-delegated-hitl-rebind" },+ });+ const workflowRuntime = createWorkflowRuntime({+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),+ });+ const firstCallerToken = "subagent:parent-session:call-1";++ await runtime.run(async () => {+ const child = await start(workflowEntry, [+ {+ kind: "initial",+ ownerDeploymentId: "dpl_inline",+ input: { message: "delegated first turn" },+ serializedContext: {+ ...buildSerializedContext({+ channelKind: "subagent",+ channelState: {+ callId: "call-1",+ parentContinuationToken: sessionInboxHookToken(firstCallerToken),+ parentSessionId: "parent-session",+ subagentName: "researcher",+ },+ continuationToken: firstCallerToken,+ mode: "conversation",+ }),+ "eve.capabilities": { requestInput: true },+ },+ },+ ]);+ const stream = captureTurnEvents(child);++ try {+ await withTimeout(stream.nextTurn(), "delegated first turn");+ await waitForRuntimeActionResult(child.runId, "call-1");++ await expect(+ workflowRuntime.dispatchSession({+ command: {+ caller: {+ callId: "call-2",+ replyTo: {+ kind: "hook",+ token: sessionInboxHookToken(sessionCommandHookToken(child.runId)),+ },+ subagentName: "researcher",+ },+ kind: "send",+ payload: { message: "Use the ask_question tool exactly once to ask for a color." },+ },+ sessionId: child.runId,+ }),+ ).resolves.toEqual({ sessionId: child.runId, status: "accepted" });++ const secondTurn = await withTimeout(stream.nextTurn(), "delegated HITL turn");+ expect(filterEventsByType(secondTurn, "input.requested")).toHaveLength(1);+ await expect(waitForSubagentInputRequest(child.runId, "call-2")).resolves.toMatchObject({+ callId: "call-2",+ kind: "subagent-input-request",+ subagentName: "researcher",+ });+ } finally {+ stream.dispose();+ await child.cancel();+ }+ });+ }, 60_000);++ describe("deployment handoff", () => {+ const followUp = (acceptedDeploymentId: string, message: string, deliveryId: string) => ({+ auth: null,+ delivery: {+ acceptedDeploymentId,+ channelKind: "http",+ channelName: "test",+ deliveryId,+ },+ kind: "send" as const,+ payload: { message },+ });++ it.each([undefined, 60_000, false] as const)(+ "renews the configured lifetime across handoffs and keeps the original stream (%s)",+ async (sessionTimeoutMs) => {+ const runtime = await createTestRuntime({ agent: { name: "workflow-entry-handoff" } });++ await runtime.run(async () => {+ const anchor = await start(workflowEntry, [+ {+ kind: "initial",+ sessionTimeoutMs,+ ownerDeploymentId: "dpl_a",+ input: { message: "hello from a" },+ serializedContext: buildSerializedContext({+ acceptedDeploymentId: "dpl_a",+ channelKind: "http",+ mode: "conversation",+ }),+ },+ ]);+ const stream = captureTurnEvents(anchor);+ const world = await getWorld();+ const workflowRuntime = createWorkflowRuntime({+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),+ });+ let completed = false;+ try {+ expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");++ const originalTimer =+ sessionTimeoutMs === false ? undefined : await readSessionTimer(anchor.runId);++ await expect(+ workflowRuntime.dispatchSession({+ command: followUp("dpl_b", "hello from b", "delivery-b"),+ sessionId: anchor.runId,+ }),+ ).resolves.toMatchObject({ sessionId: anchor.runId, status: "accepted" });++ const secondTurn = await stream.nextTurn();+ expect(secondTurn.at(-1)?.type).toBe("session.waiting");+ expect(+ secondTurn.some(+ (event) =>+ event.type === "message.completed" &&+ event.data.message?.includes("hello from b") === true,+ ),+ ).toBe(true);++ // The stable inbox now belongs to a successor run; the original run+ // holds only its anchor (plus the SDK's abort-signal hook from its+ // own earlier turn).+ const successor = await waitForCommandHookOwner(+ sessionInboxHookToken(sessionCommandHookToken(anchor.runId)),+ );+ expect(successor.runId).not.toBe(anchor.runId);+ const successorTimer =+ sessionTimeoutMs === false ? undefined : await readSessionTimer(successor.runId);+ if (+ sessionTimeoutMs !== false &&+ originalTimer !== undefined &&+ successorTimer !== undefined+ ) {+ expect(successorTimer.deadline.getTime()).toBeGreaterThan(+ originalTimer.deadline.getTime(),+ );+ const owner = await world.runs.get(successor.runId);+ expect(successorTimer.deadline.getTime()).toBeGreaterThanOrEqual(+ (owner.startedAt ?? owner.createdAt).getTime() ++ (sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS),+ );+ await vi.waitFor(async () =>+ expect((await world.runs.get(originalTimer.runId)).status).toBe("cancelled"),+ );+ }+ // A timer from the old owner can win its race with cancellation.+ await resumeHook(sessionInboxHookToken(sessionCommandHookToken(anchor.runId)), {+ kind: "session-timeout",+ ownerRunId: anchor.runId,+ });+ const anchorHooks = await world.hooks.list({ runId: anchor.runId });+ expect(+ anchorHooks.data+ .map((hook) => hook.token)+ .filter((token) => !token.startsWith("abrt_")),+ ).toEqual([`${anchor.runId}:anchor`]);++ // A third delivery through the stable session id reaches the successor+ // and still streams on the original run.+ await expect(+ workflowRuntime.dispatchSession({+ command: followUp("dpl_b", "third message", "delivery-c"),+ sessionId: anchor.runId,+ }),+ ).resolves.toMatchObject({ status: "accepted" });+ const thirdTurn = await stream.nextTurn();+ expect(+ thirdTurn.some(+ (event) =>+ event.type === "message.completed" &&+ event.data.message?.includes("third message") === true,+ ),+ ).toBe(true);++ if (successorTimer !== undefined) {+ expect(await readSessionTimer(successor.runId)).toEqual(successorTimer);+ }+ await workflowRuntime.dispatchSession({+ command: followUp("dpl_c", "fourth message", "delivery-d"),+ sessionId: anchor.runId,+ });+ expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");+ const nextOwner = await waitForCommandHookOwner(+ sessionInboxHookToken(sessionCommandHookToken(anchor.runId)),+ );+ expect(nextOwner.runId).not.toBe(successor.runId);+ if (sessionTimeoutMs !== false && successorTimer !== undefined) {+ const nextTimer = await readSessionTimer(nextOwner.runId);+ const owner = await world.runs.get(nextOwner.runId);+ expect(nextTimer.deadline.getTime()).toBeGreaterThan(+ successorTimer.deadline.getTime(),+ );+ expect(nextTimer.deadline.getTime()).toBeGreaterThanOrEqual(+ (owner.startedAt ?? owner.createdAt).getTime() ++ (sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS),+ );+ await vi.waitFor(async () =>+ expect((await world.runs.get(successorTimer.runId)).status).toBe("cancelled"),+ );+ } else {+ for (const runId of [anchor.runId, successor.runId, nextOwner.runId]) {+ const steps = await world.steps.list({ runId });+ expect(+ steps.data.some((step) => step.stepName.endsWith("//startSessionTimeoutStep")),+ ).toBe(false);+ }+ }++ // Reset ends the session on the successor; the anchor closes the stream once.+ await workflowRuntime.dispatchSession({+ command: { kind: "reset", reason: "handoff test" },+ sessionId: anchor.runId,+ });+ await expect(anchor.returnValue).resolves.toEqual({ output: "" });+ completed = true;+ expect(await listCallerStepNames(anchor.runId)).toEqual([]);+ } finally {+ stream.dispose();+ if (!completed) await anchor.cancel();+ }+ });+ },+ );++ it("recovers the original owner when target nested-state validation fails", async () => {+ const runtime = await createTestRuntime({ agent: { name: "handoff-validation" } });+ await runtime.run(async () => {+ const anchor = await start(workflowEntry, [+ {+ kind: "initial",+ ownerDeploymentId: "dpl_a",+ sessionTimeoutMs: false,+ input: { message: "Alice opens a research session." },+ serializedContext: buildSerializedContext({+ acceptedDeploymentId: "dpl_a",+ channelKind: "http",+ mode: "conversation",+ }),+ },+ ]);+ const stream = captureTurnEvents(anchor);+ const world = await getWorld();+ const workflowRuntime = createWorkflowRuntime({+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),+ });+ const rewritten = new Map<string, Promise<unknown>>();+ let candidateId: string | undefined;+ // Model a value readable by the source but incompatible with the target.+ // Only the candidate snapshot changes; the source retains its healthy state.+ const incompatibleInput = (runId: string, encoded: unknown): Promise<unknown> => {+ let pending = rewritten.get(runId);+ if (pending === undefined) {+ pending = (async () => {+ const args = (await hydrateWorkflowArguments(encoded, runId, undefined)) as [+ import("./entry-input.js").HandoffWorkflowEntryInput,+ ];+ expect(args[0].kind).toBe("handoff");+ candidateId = runId;+ const session = args[0].checkpoint.sessionState.snapshot.session;+ Object.assign(session, {+ state: {+ ...session.state,+ "eve.tasks": {+ version: 2,+ tasks: [+ {+ taskId: "task",+ taskRunId: "run",+ taskInboxToken: 42,+ createdByTurnId: "turn",+ metadata: { kind: "tool", name: "research" },+ terminalView: {+ taskId: "task",+ metadata: { kind: "tool", name: "research" },+ status: "cancelled",+ },+ },+ ],+ },+ },+ });+ const operations: Promise<void>[] = [];+ const result = await dehydrateWorkflowArguments(args, runId, undefined, operations);+ await Promise.all(operations);+ return result;+ })();+ rewritten.set(runId, pending);+ }+ return pending;+ };+ const createEvent = world.events.create.bind(world.events);+ const created = vi.spyOn(world.events, "create").mockImplementation(async (...args) => {+ const [runId] = args;+ const event = args[1] as (typeof args)[1] | RunCreatedEventRequest;+ if (event.eventType === "run_created" && event.eventData.deploymentId === "dpl_b") {+ event.eventData.input = await incompatibleInput(runId, event.eventData.input);+ }+ return createEvent(...args);+ });+ const queue = world.queue.bind(world);+ const queued = vi.spyOn(world, "queue").mockImplementation(async (...args) => {+ const message = args[1] as {+ runId?: string;+ runInput?: { deploymentId?: string; input: unknown };+ };+ if (message.runId !== undefined && message.runInput?.deploymentId === "dpl_b") {+ message.runInput.input = await incompatibleInput(message.runId, message.runInput.input);+ }+ return queue(...args);+ });+ try {+ await stream.nextTurn();+ await workflowRuntime.dispatchSession({+ command: followUp(+ "dpl_b",+ "Bob requests the next research step.",+ "validation-trigger",+ ),+ sessionId: anchor.runId,+ });+ expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");+ expect(candidateId).toBeDefined();+ expect(+ (+ await waitForCommandHookOwner(+ sessionInboxHookToken(sessionCommandHookToken(anchor.runId)),+ )+ ).runId,+ ).toBe(anchor.runId);+ expect(+ created.mock.calls.some(+ ([runId, event]) => runId === candidateId && event.eventType === "hook_created",+ ),+ ).toBe(false);+ const candidateHooks = await world.hooks.list({ runId: candidateId! });+ expect(candidateHooks.data).toEqual([]);+ const steps = await world.steps.list({ runId: anchor.runId, resolveData: "all" });+ const turns = steps.data.filter((step) => step.stepName.endsWith("//turnStep"));+ expect(turns).toHaveLength(2);+ const histories = await Promise.all(+ turns.map(async (step) => {+ const output = await hydrateStepReturnValue(step.output, anchor.runId, undefined);+ return output.sessionState.snapshot.session.history as Array<{+ role: string;+ content: unknown;+ }>;+ }),+ );+ const deliveries = histories.map((history) =>+ history.filter(+ (message) =>+ message.role === "user" &&+ JSON.stringify(message.content).includes("Bob requests the next research step."),+ ),+ );+ expect(deliveries.map((messages) => messages.length).sort()).toEqual([0, 1]);+ } finally {+ created.mockRestore();+ queued.mockRestore();+ await workflowRuntime.dispatchSession({+ command: { kind: "reset", reason: "validation test" },+ sessionId: anchor.runId,+ });+ await anchor.returnValue;+ stream.dispose();+ }+ });+ });++ it("retains a message accepted just before durable hook disposal", async () => {+ const runtime = await createTestRuntime({ agent: { name: "workflow-entry-handoff" } });++ await runtime.run(async () => {+ const anchor = await start(workflowEntry, [+ {+ kind: "initial",+ ownerDeploymentId: "dpl_a",+ input: { message: "hello from a" },+ serializedContext: buildSerializedContext({+ acceptedDeploymentId: "dpl_a",+ channelKind: "http",+ mode: "conversation",+ }),+ },+ ]);+ const stream = captureTurnEvents(anchor);+ const world = await getWorld();+ const workflowRuntime = createWorkflowRuntime({+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),+ });+ let injected = false;+ const createEvent = world.events.create.bind(world.events);+ const spy = vi.spyOn(world.events, "create").mockImplementation(async (...args) => {+ const [runId, event] = args;+ if (+ !injected &&+ runId === anchor.runId &&+ event.eventType === "hook_disposed" &&+ event.eventData?.token === sessionInboxHookToken(sessionCommandHookToken(anchor.runId))+ ) {+ injected = true;+ for (let index = 0; index < 3; index++) {+ await resumeHook(sessionInboxHookToken(sessionCommandHookToken(anchor.runId)), {+ kind: "send",+ payload: { message: `Alice sends input ${index} during release.` },+ });+ }+ }+ return await createEvent(...args);+ });+ try {+ expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");++ await expect(+ workflowRuntime.dispatchSession({+ command: followUp("dpl_b", "hello from b", "delivery-b"),+ sessionId: anchor.runId,+ }),+ ).resolves.toMatchObject({ sessionId: anchor.runId, status: "accepted" });++ const secondTurn = await stream.nextTurn();+ expect(secondTurn.at(-1)?.type).toBe("session.waiting");+ expect(+ secondTurn.some(+ (event) =>+ event.type === "message.completed" &&+ event.data.message?.includes("hello from b") === true,+ ),+ ).toBe(true);++ expect(injected).toBe(true);+ spy.mockRestore();+ const owner = await waitForCommandHookOwner(+ sessionInboxHookToken(sessionCommandHookToken(anchor.runId)),+ );+ expect(owner.runId).toBe(anchor.runId);+ await workflowRuntime.dispatchSession({+ command: followUp("dpl_b", "Bob sends a later sentinel.", "sentinel"),+ sessionId: anchor.runId,+ });+ await stream.nextTurn();+ let saved: string | undefined;+ await vi.waitFor(+ async () => {+ const steps = await world.steps.list({+ runId: owner.runId,+ resolveData: "all",+ pagination: { limit: 1000 },+ });+ for (const step of steps.data) {+ if (!step.stepName.endsWith("//turnStep") || step.output === undefined) continue;+ const result = await hydrateStepReturnValue(step.output, owner.runId, undefined);+ const history = JSON.stringify(result.sessionState.snapshot.session.history);+ if (history.includes("Bob sends a later sentinel.")) saved = history;+ }+ expect(saved).toBeDefined();+ },+ { timeout: 5000 },+ );+ for (let index = 0; index < 3; index++) {+ expect(saved).toContain(`Alice sends input ${index} during release.`);+ }+ expect(saved!.indexOf("Alice sends input 0")).toBeLessThan(+ saved!.indexOf("Alice sends input 1"),+ );+ expect(saved!.indexOf("Alice sends input 1")).toBeLessThan(+ saved!.indexOf("Alice sends input 2"),+ );+ } finally {+ spy.mockRestore();+ stream.dispose();+ if ((await anchor.status) === "running") await anchor.cancel();+ }+ });+ });++ it("hands off an alias-addressed session and keeps the alias resolving through the gap", async () => {+ const runtime = await createTestRuntime({ agent: { name: "workflow-entry-handoff-alias" } });+ const continuationToken = "http:workflow-entry-handoff-alias";++ await runtime.run(async () => {+ const anchor = await start(workflowEntry, [+ {+ kind: "initial",+ ownerDeploymentId: "dpl_a",+ input: { message: "hello from a" },+ serializedContext: buildSerializedContext({+ acceptedDeploymentId: "dpl_a",+ channelKind: "http",+ continuationToken,+ mode: "conversation",+ }),+ },+ ]);+ const stream = captureTurnEvents(anchor);+ const world = await getWorld();+ const workflowRuntime = createWorkflowRuntime({+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),+ });+ // A channel delivery lands on the alias while the old owner has released+ // it and the successor has not yet claimed it. The handoff marker must+ // make ingress wait for the successor instead of reporting the session+ // gone (which would let the channel start a replacement session).+ let gapDelivery: Promise<unknown> | undefined;+ const createEvent = world.events.create.bind(world.events);+ const spy = vi.spyOn(world.events, "create").mockImplementation(async (...args) => {+ const [runId, event] = args;+ const created = await createEvent(...args);+ if (+ gapDelivery === undefined &&+ runId === anchor.runId &&+ event.eventType === "hook_disposed" &&+ event.eventData?.token === sessionInboxHookToken(continuationToken)+ ) {+ gapDelivery = workflowRuntime.dispatchContinuation({+ command: followUp("dpl_b", "Alice writes during the gap.", "delivery-gap"),+ continuationToken,+ });+ }+ return created;+ });+ try {+ expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");++ await expect(+ workflowRuntime.dispatchContinuation({+ command: followUp("dpl_b", "hello from b", "delivery-b"),+ continuationToken,+ }),+ ).resolves.toMatchObject({ sessionId: anchor.runId, status: "accepted" });++ const secondTurn = await stream.nextTurn();+ expect(+ secondTurn.some(+ (event) =>+ event.type === "message.completed" &&+ event.data.message?.includes("hello from b") === true,+ ),+ ).toBe(true);+ spy.mockRestore();+ expect(gapDelivery).toBeDefined();+ await expect(gapDelivery).resolves.toMatchObject({+ sessionId: anchor.runId,+ status: "accepted",+ });+ const gapTurn = await stream.nextTurn();+ expect(+ gapTurn.some(+ (event) =>+ event.type === "message.completed" &&+ event.data.message?.includes("Alice writes during the gap.") === true,+ ),+ ).toBe(true);++ const successor = await waitForCommandHookOwner(+ sessionInboxHookToken(sessionCommandHookToken(anchor.runId)),+ );+ expect(successor.runId).not.toBe(anchor.runId);+ await expect(+ waitForCommandHookOwner(sessionInboxHookToken(continuationToken)),+ ).resolves.toMatchObject({ runId: successor.runId });+ // No marker outlives the handoff.+ const markers = (await world.hooks.list({ runId: anchor.runId })).data.filter((hook) =>+ hook.token.startsWith("eve:inbox:handoff:"),+ );+ expect(markers).toEqual([]);+ // Only one session exists for this alias.+ await expect(workflowRuntime.resolveContinuation(continuationToken)).resolves.toEqual({+ sessionId: anchor.runId,+ });+ } finally {+ stream.dispose();+ await anchor.cancel();+ }+ });+ });++ it("keeps the session on the current owner when it is not idle", async () => {+ const runtime = await createTestRuntime({ agent: { name: "workflow-entry-handoff-busy" } });++ await runtime.run(async () => {+ const run = await start(workflowEntry, [+ {+ kind: "initial",+ ownerDeploymentId: "dpl_a",+ input: { message: "hello from a" },+ serializedContext: buildSerializedContext({+ acceptedDeploymentId: "dpl_a",+ channelKind: "http",+ mode: "conversation",+ }),+ },+ ]);+ const stream = captureTurnEvents(run);+ const workflowRuntime = createWorkflowRuntime({+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),+ });+ try {+ expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");++ // Two deliveries accepted back to back: the second is pending when the+ // first is evaluated, so neither may trigger a handoff.+ await Promise.all([+ workflowRuntime.dispatchSession({+ command: followUp("dpl_b", "first burst", "delivery-1"),+ sessionId: run.runId,+ }),+ workflowRuntime.dispatchSession({+ command: followUp("dpl_b", "second burst", "delivery-2"),+ sessionId: run.runId,+ }),+ ]);+ const turn = await stream.nextTurn();+ expect(turn.at(-1)?.type).toBe("session.waiting");+ expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");+ const owner = await waitForCommandHookOwner(+ sessionInboxHookToken(sessionCommandHookToken(run.runId)),+ );+ expect(owner.runId).toBe(run.runId);+ } finally {+ stream.dispose();+ await run.cancel();+ }+ });+ });+ });+it("exits a competing continuation owner before its first turn", async () => {const runtime = await createTestRuntime({ agent: { name: "workflow-entry-hook-owner" } });const continuationToken = "http:workflow-entry-hook-owner";@@ -1048,6 +1777,8 @@ describe("workflowEntry integration", () => {await runtime.run(async () => {const owner = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: "owner message" },serializedContext: buildSerializedContext({channelKind: "http",@@ -1057,13 +1788,18 @@ describe("workflowEntry integration", () => {},]);const ownerStream = captureTurnEvents(owner);- await waitForHook({ runId: owner.runId }, { token: continuationToken });+ await waitForHook(+ { runId: owner.runId },+ { token: sessionInboxHookToken(continuationToken) },+ );const firstTurn = await ownerStream.nextTurn();expect(firstTurn.at(-1)?.type).toBe("session.waiting");const contender = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",continuationConflictCommand: {auth: null,kind: "send",@@ -1111,6 +1847,8 @@ describe("workflowEntry integration", () => {await runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: "summarize this", outputSchema },serializedContext: buildSerializedContext({channelKind: "http",@@ -1124,7 +1862,7 @@ describe("workflowEntry integration", () => {await waitForHook({ runId: run.runId },{- token: continuationToken,+ token: sessionInboxHookToken(continuationToken),},);@@ -1139,7 +1877,7 @@ describe("workflowEntry integration", () => {});expect(firstTurn.at(-1)?.type).toBe("session.waiting");- await resumeHook(continuationToken, {+ await resumeHook(sessionInboxHookToken(continuationToken), {kind: "send",payload: { message: "follow up without structured output" },});@@ -1161,6 +1899,8 @@ describe("workflowEntry integration", () => {await runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: "hello there" },serializedContext: buildSerializedContext({channelKind: "http",@@ -1202,6 +1942,8 @@ describe("workflowEntry integration", () => {await runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: "hello there" },serializedContext: buildSerializedContext({channelKind: "http",@@ -1233,6 +1975,8 @@ describe("workflowEntry integration", () => {await runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: "hello there" },serializedContext: buildSerializedContext({channelKind: "http",@@ -1267,6 +2011,8 @@ describe("workflowEntry integration", () => {workflowEntry,[{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: "session tag round-trip" },serializedContext,},@@ -1323,6 +2069,8 @@ describe("workflowEntry integration", () => {workflowEntry,[{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: "subagent tag round-trip" },serializedContext,},@@ -1472,6 +2220,24 @@ async function withTimeout<T>(promise: Promise<T>, label: string): Promise<T> {}}+async function expectHookClaims(runId: string, tokens: string[]): Promise<void> {+ const events = await (+ await getWorld()+ ).events.list({+ runId,+ pagination: { limit: 1000 },+ resolveData: "all",+ });+ 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);+ expect(claims.filter((token) => !token.startsWith("abrt_")).sort()).toEqual(+ tokens.map(sessionInboxHookToken).sort(),+ );+}+async function waitForRuntimeActionResult(runId: string, callId: string): Promise<unknown> {const world = await getWorld();const deadline = Date.now() + 10_000;@@ -1503,6 +2269,36 @@ async function waitForRuntimeActionResult(runId: string, callId: string): Promis);}+async function waitForSubagentInputRequest(runId: string, callId: string): Promise<unknown> {+ const world = await getWorld();+ const deadline = Date.now() + 10_000;++ while (Date.now() < deadline) {+ const events = await world.events.list({+ pagination: { limit: 1000 },+ resolveData: "all",+ runId,+ });+ for (const event of events.data) {+ if (event.eventType !== "hook_received") continue;+ const payload = await hydrateWorkflowArguments(event.eventData.payload, runId, undefined);+ if (+ typeof payload === "object" &&+ payload !== null &&+ "kind" in payload &&+ payload.kind === "subagent-input-request" &&+ "callId" in payload &&+ payload.callId === callId+ ) {+ return payload;+ }+ }+ await new Promise((resolve) => setTimeout(resolve, 100));+ }++ throw new Error(`Timed out waiting for a subagent input request from caller "${callId}".`);+}+function hasSubagentResult(value: unknown, callId: string): boolean {if (typeof value !== "object" ||@@ -1523,3 +2319,22 @@ function hasSubagentResult(value: unknown, callId: string): boolean {result.callId === callId,);}++async function readSessionTimer(ownerRunId: string): Promise<{ runId: string; deadline: Date }> {+ const world = await getWorld();+ let timer: { runId: string; deadline: Date } | undefined;+ await vi.waitFor(async () => {+ const steps = await world.steps.list({ runId: ownerRunId, resolveData: "all" });+ const start = steps.data.find((step) => step.stepName.endsWith("//startSessionTimeoutStep"));+ expect(start?.output).toBeDefined();+ const result = (await hydrateStepReturnValue(start!.output, ownerRunId, undefined)) as {+ runId: string;+ };+ const run = await world.runs.get(result.runId);+ const [input] = (await hydrateWorkflowArguments(run.input, run.runId, undefined)) as [+ { deadline: Date },+ ];+ timer = { runId: run.runId, deadline: input.deadline };+ });+ return timer!;+}diff --git a/packages/eve/src/execution/session/entry.ts b/packages/eve/src/execution/session/entry.tsnew file mode 100644index 000000000..26953a681--- /dev/null+++ b/packages/eve/src/execution/session/entry.ts@@ -0,0 +1,242 @@+import { failSession, runPreparedSession, type SessionBoot } from "#execution/session/program.js";+import { getWorkflowMetadata, getWritable } from "#compiled/@workflow/core/index.js";++import type { DeliverHookPayload, RunInput, SessionCapabilities } from "#channel/types.js";+import { readChannelRequestId, readRootSessionId } from "#execution/eve-workflow-attributes.js";+import type { RunMode } from "#shared/run-mode.js";+import type { DurableCompiledArtifactsSource } from "#runtime/durable-compiled-artifacts-source.js";+import { resolveInitialTurnCallerStep } from "#subagents/parent-notification.js";+import { normalizeSerializableError } from "#execution/workflow-errors.js";+import { createSessionStep } from "#execution/create-session-step.js";+import { isHookConflictError } from "#execution/hook-ownership.js";+import { createSessionInbox, type SessionInboxHandle } from "#execution/session-inbox/inbox.js";+import { sessionHookTokens } from "#execution/session/hook-tokens.js";+import { DEFAULT_SESSION_TIMEOUT_MS, sessionTimeoutDeadline } from "#execution/session/timeout.js";+import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";+import { attachClientContext, readClientContext } from "#internal/client-context.js";+import { settleContinuationConflictStep } from "#execution/continuation-conflict-step.js";+import {+ SESSION_INBOX_CONTEXT_KEY,+ sessionCommandHookToken,+} from "#execution/session-inbox/address.js";+import {+ signalSessionOwnerActivationStep,+ validateSessionCheckpointStep,+} from "#execution/session/handoff-steps.js";+import type {+ HandoffWorkflowEntryInput,+ InitialWorkflowEntryInput,+ WorkflowEntryInput,+ WorkflowEntryResult,+} from "#execution/session/entry-input.js";++// workflow-entry.ts is the durable workflow body — the bundler rejects+// node built-ins here, so `internal/logging.ts` cannot be imported.+// Error logging happens inside `emitTerminalSessionFailureStep`.++/**+ * Long-lived workflow entrypoint. Handles both root sessions and+ * delegated child sessions: root sessions expose only parent+ * control-plane events; delegated children publish their full progress+ * on a child stream and resume the parked parent with a+ * `subagent-result` on completion.+ *+ * The current owner directly executes every turn. An idle owner can transfer+ * its settled checkpoint and hooks to an exact successor deployment while the+ * original run remains parked as the public stream anchor.+ */+export async function workflowEntry(input: WorkflowEntryInput): Promise<WorkflowEntryResult> {+ "use workflow";++ const boot =+ input.kind === "initial"+ ? await bootInitialOwner(input, getWorkflowMetadata().workflowRunId)+ : await bootHandoffOwner(input);+ if (boot === undefined) return { output: "" };+ const result = await runPreparedSession(boot.session, boot.inbox);+ return { output: result.output };+}++interface BootOutcome {+ readonly inbox: SessionInboxHandle;+ readonly session: SessionBoot;+}++function stampSessionIdentity(+ serializedContext: Record<string, unknown>,+ sessionId: string,+): Record<string, unknown> {+ return {+ ...serializedContext,+ "eve.sessionId": sessionId,+ [SESSION_INBOX_CONTEXT_KEY]: { sessionId },+ };+}++/** Returns `undefined` when a competing continuation owner already exists. */+async function bootInitialOwner(+ input: InitialWorkflowEntryInput,+ sessionId: string,+): Promise<BootOutcome | undefined> {+ const serializedContext = stampSessionIdentity(input.serializedContext, sessionId);+ const sessionWritable = getWritable<Uint8Array>();+ const mode = serializedContext["eve.mode"] as RunMode;+ const inbox = createSessionInbox(sessionId);+ const { workflowStartedAt } = getWorkflowMetadata();+ const sessionTimeoutMs = input.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;+ const continuationToken = (serializedContext["eve.continuationToken"] as string) || "";+ const serializedBundle = serializedContext["eve.bundle"] as {+ source: DurableCompiledArtifactsSource;+ nodeId?: string;+ };+ try {+ const [sessionCreation, stableClaim, aliasClaim] = await Promise.allSettled([+ createSessionStep({+ compiledArtifactsSource: serializedBundle.source,+ continuationToken,+ dynamicSubagentAgentConfig: serializedContext["eve.dynamicSubagentAgentConfig"] as+ | DynamicSubagentAgentConfig+ | undefined,+ inheritedLimits: input.limits,+ nodeId: serializedBundle.nodeId,+ outputSchema: input.input.outputSchema,+ rootSessionId: readRootSessionId(serializedContext),+ sessionId,+ taskId: input.taskId,+ }),+ inbox.claimSessionHook(sessionCommandHookToken(sessionId)),+ continuationToken === "" ? Promise.resolve() : inbox.claimSessionHook(continuationToken),+ ]);+ if (sessionCreation.status === "rejected") throw sessionCreation.reason;+ if (stableClaim.status === "rejected") throw stableClaim.reason;+ if (aliasClaim.status === "rejected") {+ if (!isHookConflictError(aliasClaim.reason)) throw aliasClaim.reason;+ if (+ input.activityCollectorRunId !== undefined ||+ input.continuationConflictCommand !== undefined+ ) {+ await settleContinuationConflictStep({+ activityCollectorRunId: input.activityCollectorRunId,+ command: input.continuationConflictCommand,+ continuationToken,+ });+ }+ await inbox.dispose();+ return undefined;+ }+ return {+ inbox,+ session: {+ anchor: { kind: "self" },+ caller: hasDelegatedCallerContext(serializedContext)+ ? await resolveInitialTurnCallerStep({ serializedContext })+ : undefined,+ capabilities: serializedContext["eve.capabilities"] as SessionCapabilities | undefined,+ deploymentId: input.ownerDeploymentId,+ initialInput: createInitialDelivery(input, serializedContext),+ mode,+ retention: input.retention,+ serializedContext,+ sessionId,+ sessionState: sessionCreation.value.state,+ sessionTimeoutMs,+ sessionTimeoutDeadline: sessionTimeoutDeadline(+ sessionTimeoutMs,+ workflowStartedAt.getTime(),+ ),+ sessionWritable,+ },+ };+ } catch (error) {+ await inbox.dispose();+ return await failSession({+ error,+ mode,+ serializedContext,+ sessionId,+ sessionState: undefined,+ sessionWritable,+ });+ }+}++/** Validates, claims the exact hook set, then tells the previous owner it may exit. */+async function bootHandoffOwner(+ input: HandoffWorkflowEntryInput,+): Promise<BootOutcome | undefined> {+ const { checkpoint, sessionId } = input;+ const serializedContext = stampSessionIdentity(checkpoint.serializedContext, sessionId);+ const inbox = createSessionInbox(sessionId);+ try {+ await validateSessionCheckpointStep({ checkpoint });+ await inbox.claimSessionHooks(+ sessionHookTokens({ serializedContext, sessionState: checkpoint.sessionState }),+ );+ await signalSessionOwnerActivationStep({+ activation: { kind: "active" },+ token: input.activationToken,+ });+ } catch (error) {+ const payloads = await inbox.release();+ await signalSessionOwnerActivationStep({+ activation: { error: normalizeSerializableError(error), kind: "failed", payloads },+ token: input.activationToken,+ });+ return undefined;+ }+ return {+ inbox,+ session: {+ anchor: { kind: "successor" },+ caller: input.delivery.caller,+ capabilities: checkpoint.capabilities,+ deploymentId: input.ownerDeploymentId,+ initialInput: input.delivery,+ mode: checkpoint.mode,+ retention: checkpoint.retention,+ serializedContext,+ sessionId,+ sessionState: checkpoint.sessionState,+ sessionTimeoutMs: checkpoint.sessionTimeoutMs,+ sessionTimeoutDeadline: sessionTimeoutDeadline(checkpoint.sessionTimeoutMs, Date.now()),+ sessionWritable: input.sessionWritable,+ },+ };+}++function hasDelegatedCallerContext(serializedContext: Record<string, unknown>): boolean {+ if (serializedContext["eve.sessionCallback"] !== undefined) return true;+ const channel = serializedContext["eve.channel"];+ return (+ typeof channel === "object" && channel !== null && Reflect.get(channel, "kind") === "subagent"+ );+}++function createInitialDelivery(+ input: InitialWorkflowEntryInput,+ serializedContext: Record<string, unknown>,+): DeliverHookPayload {+ return {+ deliveryMetadata:+ serializedContext["eve.channelDelivery"] === undefined+ ? undefined+ : [+ {+ ...(serializedContext["eve.channelDelivery"] as NonNullable<RunInput["delivery"]>),+ payloadIndex: 0,+ },+ ],+ kind: "deliver",+ payloads: [+ attachClientContext(+ {+ message: input.input.message,+ context: input.input.context,+ outputSchema: input.input.outputSchema,+ },+ readClientContext(input.input),+ ),+ ],+ requestId: readChannelRequestId(serializedContext),+ };+}diff --git a/packages/eve/src/execution/session/event-sink.ts b/packages/eve/src/execution/session/event-sink.tsnew file mode 100644index 000000000..8c62a9a50--- /dev/null+++ b/packages/eve/src/execution/session/event-sink.ts@@ -0,0 +1,153 @@+import { buildAdapterContext } from "#channel/adapter-context.js";+import { callAdapterEventHandler, type ChannelAdapter } from "#channel/adapter.js";+import type { ContextContainer } from "#context/container.js";+import { dispatchDynamicInstructionEvent } from "#context/dynamic-instruction-lifecycle.js";+import { dispatchDynamicModelEvent } from "#context/dynamic-model-lifecycle.js";+import { dispatchDynamicSkillEvent } from "#context/dynamic-skill-lifecycle.js";+import { dispatchDynamicSubagentEvent } from "#context/dynamic-subagent-lifecycle.js";+import { dispatchDynamicToolEvent } from "#context/dynamic-tool-lifecycle.js";+import { dispatchStreamEventHooks } from "#context/hook-lifecycle.js";+import { ScheduleIdKey, TurnDeliveryIdsKey, TurnTaskDeliveryKey } from "#context/keys.js";+import { dispatchMemoryLifecycleEvent } from "#context/memory-event-lifecycle.js";+import * as activityCohort from "#execution/activity-cohort.js";+import { setChannelContext } from "#execution/channel-context.js";+import { bindDynamicConnections } from "#execution/dynamic-connections.js";+import type { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";+import { observeSessionActivity } from "#execution/session-activity-projection.js";+import { scheduledLaunchDeliveryEvent } from "#execution/scheduled-launch-delivery.js";+import { forwardTaskEventToSessionCallback } from "#execution/task-event-callback.js";+import type { HandleEventFn } from "#harness/types.js";+import type { ExecutionInstrumentation } from "#instrumentation/runtime.js";+import {+ encodeMessageStreamEvent,+ type MessageStreamEvent,+ stampMessageStreamEvent,+ type UnstampedMessageStreamEvent,+} from "#protocol/message.js";+import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";++export interface SessionEventSinkInput {+ readonly abortSignal: AbortSignal | undefined;+ readonly adapter: ChannelAdapter;+ readonly bundle: CompiledBundle;+ readonly ctx: ContextContainer;+ readonly effectiveAgent: ReturnType<typeof resolveEffectiveAgentRuntime>;+ readonly instrumentation: ExecutionInstrumentation | undefined;+ readonly isFirstTurn: boolean;+ readonly sessionWritable: WritableStream<Uint8Array>;+ readonly sessionId: string;+}++export interface SessionEventSink {+ readonly adapterCtx: ReturnType<typeof buildAdapterContext>;+ readonly dynamicConnections: ReturnType<typeof bindDynamicConnections>;+ readonly effectiveNode: CompiledBundle["graph"]["root"];+ readonly handleEvent: HandleEventFn;+ /** Closes the parent stream; only a terminal `done` step does this. */+ close(): Promise<void>;+ /** Releases the writer lock so the next step can acquire it. Safe after `close()`. */+ release(): void;+}++/** Binds adapter context, dynamic connections, and event fan-out to one step's stream writer. */+export function createSessionEventSink(input: SessionEventSinkInput): SessionEventSink {+ const { adapter, bundle, ctx, effectiveAgent, instrumentation } = input;+ const adapterCtx = buildAdapterContext(adapter, ctx);+ const dynamicConnections = bindDynamicConnections(ctx, bundle.resolvedAgent);+ const effectiveNode = { ...bundle.graph.root, turnAgent: effectiveAgent.turnAgent };+ const writer = input.sessionWritable.getWriter();++ const emit = async (+ event: UnstampedMessageStreamEvent,+ ): Promise<{ readonly event: MessageStreamEvent; readonly suppressed: boolean }> => {+ const deliverableEvent = scheduledLaunchDeliveryEvent(event, {+ isFirstTurn: input.isFirstTurn,+ isScheduled: ctx.get(ScheduleIdKey) !== undefined,+ taskPhase: ctx.get(TurnTaskDeliveryKey),+ });+ if (deliverableEvent === undefined) {+ return {+ event: stampMessageStreamEvent(event, ctx.get(TurnDeliveryIdsKey)),+ suppressed: true,+ };+ }+ const toEmit = await callAdapterEventHandler(adapter, deliverableEvent, adapterCtx);+ setChannelContext(ctx, { ...adapter, state: { ...adapterCtx.state } });+ const stamped = stampMessageStreamEvent(toEmit, ctx.get(TurnDeliveryIdsKey));+ await writer.write(encodeMessageStreamEvent(stamped));+ return { event: stamped, suppressed: false };+ };+ const handleEvent: HandleEventFn = async (event, messages): Promise<void> => {+ activityCohort.updateActivityBlockers(ctx, event);+ const forwardedToTaskParent = await forwardTaskEventToSessionCallback(ctx, event);+ const emitted = forwardedToTaskParent+ ? { event: stampMessageStreamEvent(event, ctx.get(TurnDeliveryIdsKey)), suppressed: false }+ : await emit(event);+ const lifecycleMessages = await dispatchMemoryLifecycleEvent({+ abortSignal: input.abortSignal,+ appRoot: effectiveNode.agent?.metadata?.appRoot ?? "",+ ctx,+ event,+ instrumentation: instrumentation?.memory,+ memories: effectiveNode.agent?.memories ?? [],+ messages,+ nodeId: bundle.nodeId ?? "__root__",+ });+ void observeSessionActivity({ ctx, event: emitted.event, sessionId: input.sessionId });+ if (!emitted.suppressed) {+ await dispatchStreamEventHooks({ ctx, registry: bundle.hookRegistry, event: emitted.event });+ }+ if (emitted.event.type !== "step.started") {+ await dispatchDynamicModelEvent({+ ctx,+ dynamicModel: effectiveAgent.turnAgent.dynamicModel,+ event: emitted.event,+ messages: lifecycleMessages,+ scope: { moduleMap: bundle.moduleMap, nodeId: bundle.nodeId },+ });+ }+ await dynamicConnections.dispatch(emitted.event);+ await dispatchDynamicSubagentEvent({+ ctx,+ resolvers: bundle.subagentRegistry.dynamicResolvers ?? [],+ event: emitted.event,+ messages: lifecycleMessages,+ });+ await dispatchDynamicToolEvent({+ ctx,+ resolvers: bundle.resolvedAgent.dynamicToolResolvers ?? [],+ event: emitted.event,+ messages: lifecycleMessages,+ });+ await dispatchDynamicSkillEvent({+ ctx,+ resolvers: bundle.resolvedAgent.dynamicSkillResolvers ?? [],+ event: emitted.event,+ messages: lifecycleMessages,+ });+ await dispatchDynamicInstructionEvent({+ ctx,+ resolvers: bundle.resolvedAgent.dynamicInstructionsResolvers ?? [],+ event: emitted.event,+ messages: lifecycleMessages,+ });+ };++ let released = false;+ const release = (): void => {+ if (released) return;+ released = true;+ writer.releaseLock();+ };+ return {+ adapterCtx,+ close: async () => {+ await writer.close();+ release();+ },+ dynamicConnections,+ effectiveNode,+ handleEvent,+ release,+ };+}diff --git a/packages/eve/src/execution/session/finalization.ts b/packages/eve/src/execution/session/finalization.tsnew file mode 100644index 000000000..03c60fd9c--- /dev/null+++ b/packages/eve/src/execution/session/finalization.ts@@ -0,0 +1,119 @@+import type { TurnCaller } from "#channel/types.js";+import type { DurableSessionState } from "#execution/durable-session-store.js";+import { emitTerminalSessionCompletionStep } from "#execution/terminal-session-completion-step.js";+import { emitTerminalSessionFailureStep } from "#execution/terminal-session-failure-step.js";+import { terminateChildSessionsStep } from "#execution/terminate-child-sessions-step.js";+import type { TurnOutcome } from "#execution/session/turn-step-types.js";+import { normalizeSerializableError } from "#execution/workflow-errors.js";+import type { WorkflowEntryResult } from "#execution/session/entry-input.js";+import type { RunMode } from "#shared/run-mode.js";+import type { TokenUsage } from "#shared/token-usage.js";+import { fireSessionCallbackStep } from "#subagents/callback-step.js";+import { notifyDelegatedParentStep, notifyTurnCallerStep } from "#subagents/parent-notification.js";+import {+ createDelegatedSubagentErrorResult,+ createDelegatedSubagentSuccessResult,+} from "#subagents/parent-result.js";++/** The three ways a session ends. `done` already emitted its terminal event inside the turn. */+export type SessionTerminalOutcome =+ | { readonly kind: "done"; readonly action: TurnOutcome & { readonly kind: "done" } }+ | { readonly kind: "expired" }+ | { readonly kind: "failed"; readonly error: unknown; readonly turnId?: string };++export interface SessionFinalizationContext {+ readonly caller: TurnCaller | undefined;+ readonly cursor: {+ readonly serializedContext: Record<string, unknown>;+ readonly sessionState: DurableSessionState | undefined;+ };+ readonly mode: RunMode;+ readonly sessionWritable: WritableStream<Uint8Array>;+}++/**+ * Terminates descendants, emits the terminal protocol event when the turn has+ * not already done so, then settles whoever is waiting on this session: the+ * task callback and delegated parent in task mode, or the parked caller.+ */+export async function finalizeSession(+ outcome: SessionTerminalOutcome,+ context: SessionFinalizationContext,+): Promise<WorkflowEntryResult> {+ const { serializedContext, sessionState } = context.cursor;+ if (sessionState !== undefined) {+ await terminateChildSessionsStep({ serializedContext, sessionState });+ }+ if (outcome.kind === "expired") {+ await emitTerminalSessionCompletionStep({+ sessionWritable: context.sessionWritable,+ serializedContext,+ });+ } else if (outcome.kind === "failed") {+ await emitTerminalSessionFailureStep({+ error: normalizeSerializableError(outcome.error),+ sessionWritable: context.sessionWritable,+ serializedContext,+ turnId: outcome.turnId,+ });+ }++ const settled = settledResult(outcome);+ if (context.mode === "task") {+ await fireSessionCallbackStep({+ error: settled.isError ? settled.output : undefined,+ output: settled.isError ? undefined : settled.output,+ serializedContext,+ status: settled.isError ? "failed" : "completed",+ usage: settled.sessionUsage,+ });+ await notifyDelegatedParentStep({+ result: settled.isError+ ? createDelegatedSubagentErrorResult(serializedContext, settled.output)+ : createDelegatedSubagentSuccessResult(serializedContext, settled.output),+ serializedContext,+ usage: settled.sessionUsage,+ });+ } else if (context.caller !== undefined) {+ const notification: { isError?: boolean; output: unknown; usage?: TokenUsage } = {+ output: settled.output,+ usage: settled.turnUsage,+ };+ if (settled.isError) notification.isError = true;+ await notifyTurnCallerStep({+ caller: context.caller,+ lifecycle: "terminal",+ sessionId: sessionState?.sessionId ?? (serializedContext["eve.sessionId"] as string),+ settled: notification,+ });+ }+ return outcome.kind === "done"+ ? {+ isError: outcome.action.isError,+ output: outcome.action.output,+ usage: outcome.action.usage,+ usageDelta: outcome.action.usageDelta,+ }+ : { isError: settled.isError, output: settled.output };+}++function settledResult(outcome: SessionTerminalOutcome): {+ readonly isError: boolean;+ readonly output: unknown;+ readonly sessionUsage?: TokenUsage;+ readonly turnUsage?: TokenUsage;+} {+ switch (outcome.kind) {+ case "done":+ return {+ isError: outcome.action.isError === true,+ output: outcome.action.output,+ sessionUsage: outcome.action.usage,+ turnUsage: outcome.action.usageDelta,+ };+ case "expired":+ return { isError: false, output: "" };+ case "failed":+ return { isError: true, output: normalizeSerializableError(outcome.error) };+ }+}diff --git a/packages/eve/src/execution/session/handoff-steps.test.ts b/packages/eve/src/execution/session/handoff-steps.test.tsnew file mode 100644index 000000000..b2f9fbaae--- /dev/null+++ b/packages/eve/src/execution/session/handoff-steps.test.ts@@ -0,0 +1,99 @@+import { createTestSessionState } from "#internal/testing/session-state.js";+import { beforeEach, describe, expect, it, vi } from "vitest";++import type { SessionCheckpoint } from "#execution/session/handoff.js";+import { validateSessionCheckpointStep } from "#execution/session/handoff-steps.js";+import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";++const deserializeContextMock = vi.fn();+const readDurableSessionMock = vi.fn();++vi.mock("#context/serialize.js", () => ({+ deserializeContext: (...args: unknown[]) => deserializeContextMock(...args),+}));+vi.mock("#execution/durable-session-store.js", async (importOriginal) => ({+ ...(await importOriginal()),+ readDurableSession: (...args: unknown[]) => readDurableSessionMock(...args),+}));++describe("validateSessionCheckpointStep", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("hydrates the target bundle and durable state for a complete hook set", async () => {+ const require = vi.fn();+ deserializeContextMock.mockResolvedValue({ require });+ readDurableSessionMock.mockReturnValue({});+ const checkpoint = createCheckpoint();++ await validateSessionCheckpointStep({ checkpoint });++ expect(require).toHaveBeenCalledWith(BundleKey);+ expect(readDurableSessionMock).toHaveBeenCalledWith(checkpoint.sessionState);+ });++ it("rejects an incompatible settled task with the current checkpoint version", async () => {+ deserializeContextMock.mockResolvedValue({ require: vi.fn() });+ readDurableSessionMock.mockReturnValue({+ state: {+ "eve.tasks": {+ version: 2,+ tasks: [+ {+ taskId: "task",+ taskRunId: "run",+ taskInboxToken: 42,+ createdByTurnId: "turn",+ metadata: { kind: "tool", name: "research" },+ terminalView: {+ taskId: "task",+ metadata: { kind: "tool", name: "research" },+ status: "cancelled",+ },+ },+ ],+ },+ },+ });+ await expect(validateSessionCheckpointStep({ checkpoint: createCheckpoint() })).rejects.toThrow(+ "Corrupt task index",+ );+ });++ it("rejects a checkpoint written by a different contract version", async () => {+ const checkpoint: SessionCheckpoint = { ...createCheckpoint(), version: 2 as never };++ await expect(validateSessionCheckpointStep({ checkpoint })).rejects.toThrow(+ /Unsupported session checkpoint version 2.*Start a new session/,+ );+ expect(deserializeContextMock).not.toHaveBeenCalled();+ });++ it.each([undefined, -1, NaN, Infinity, "30000", true])(+ "rejects an invalid renewal duration (%s)",+ async (sessionTimeoutMs) => {+ const checkpoint = { ...createCheckpoint(), sessionTimeoutMs } as SessionCheckpoint;+ await expect(validateSessionCheckpointStep({ checkpoint })).rejects.toThrow(+ "invalid timeout duration",+ );+ expect(deserializeContextMock).not.toHaveBeenCalled();+ },+ );+});++function createCheckpoint(): SessionCheckpoint {+ return {+ version: 4,+ sessionTimeoutMs: false,+ mode: "conversation",+ serializedContext: {},+ sessionState: createTestSessionState({+ continuationToken: "channel:current",+ emissionState: { sequence: 0, sessionStarted: true, stepIndex: 0, turnId: "turn_0" },+ hasProxyInputRequests: false,+ sessionId: "session-1",+ version: 1,+ }),+ };+}diff --git a/packages/eve/src/execution/session/handoff-steps.ts b/packages/eve/src/execution/session/handoff-steps.tsnew file mode 100644index 000000000..7ebe51b4f--- /dev/null+++ b/packages/eve/src/execution/session/handoff-steps.ts@@ -0,0 +1,92 @@+import { deserializeContext } from "#context/serialize.js";+import { readDurableSession, type DurableSessionState } from "#execution/durable-session-store.js";+import {+ SESSION_CHECKPOINT_VERSION,+ type SessionCheckpoint,+ type SessionOwnerActivation,+} from "#execution/session/handoff.js";+import { resumeHook } from "#internal/workflow/runtime.js";+import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";+import { isObject } from "#shared/guards.js";+import { getAgentHandleStore } from "#subagents/handles/store.js";+import { getSessionTaskIndex } from "#tasks/session-index.js";++/** Parses retained work with this deployment's code before deciding whether it can move. */+export function isSessionStateIdleForHandoff(sessionState: DurableSessionState): boolean {+ const { state } = readDurableSession(sessionState);+ // Parse all entries, including terminal tasks, before any busy-work shortcut.+ const tasks = getSessionTaskIndex(state);+ const handles = getAgentHandleStore(state);++ // These registries are deleted when work settles. Their ordinary readers+ // tolerate malformed values as absent; that must not authorize a handoff.+ const pendingKeys = [+ "eve.runtime.pendingAuthorization",+ "eve.runtime.pendingInputBatch",+ "eve.runtime.pendingCoordinationBatch",+ "eve.runtime.deferredStepInput",+ "eve.harness.pendingWorkflowInterrupt",+ ];+ if (pendingKeys.some((key) => state?.[key] !== undefined)) return false;+ for (const key of ["eve.runtime.pendingInputBatches", "eve.runtime.workflowToolRuns"]) {+ const value = state?.[key];+ if (value !== undefined && (!Array.isArray(value) || value.length > 0)) return false;+ }+ const proxyRequests = state?.["eve.runtime.proxyInputRequests"];+ if (+ proxyRequests !== undefined &&+ (!isObject(proxyRequests) || Object.keys(proxyRequests).length > 0)+ )+ return false;+ return (+ (handles?.handles.length ?? 0) === 0 && tasks.every((task) => task.terminalView !== undefined)+ );+}++/** Reads durable work using the source deployment's handoff contract. */+export async function isSessionIdleForHandoffStep(input: {+ readonly sessionState: DurableSessionState;+}): Promise<boolean> {+ "use step";+ return isSessionStateIdleForHandoff(input.sessionState);+}++/** Validates a checkpoint and resolves the target deployment's compiled bundle. */+export async function validateSessionCheckpointStep(input: {+ readonly checkpoint: SessionCheckpoint;+}): Promise<void> {+ "use step";+ const { checkpoint } = input;+ if (checkpoint.version !== SESSION_CHECKPOINT_VERSION) {+ throw new Error(+ `Unsupported session checkpoint version ${JSON.stringify(checkpoint.version)}; this deployment reads version ${SESSION_CHECKPOINT_VERSION}. Start a new session on this deployment.`,+ );+ }+ const timeout = checkpoint.sessionTimeoutMs;+ if (+ timeout !== false &&+ (typeof timeout !== "number" || !Number.isFinite(timeout) || timeout < 0)+ )+ throw new Error("Session checkpoint contains an invalid timeout duration.");+ const context = await deserializeContext(checkpoint.serializedContext);+ context.require(BundleKey);+ if (!isSessionStateIdleForHandoff(checkpoint.sessionState)) {+ throw new Error("Session checkpoint contains pending work and cannot be handed off.");+ }+}++export async function signalSessionOwnerActivationStep(input: {+ readonly activation: SessionOwnerActivation;+ readonly token: string;+}): Promise<void> {+ "use step";+ await resumeHook(input.token, input.activation);+}++export async function signalSessionAnchorStep(input: {+ readonly result: { readonly output: unknown };+ readonly token: string;+}): Promise<void> {+ "use step";+ await resumeHook(input.token, input.result);+}diff --git a/packages/eve/src/execution/session/handoff.test.ts b/packages/eve/src/execution/session/handoff.test.tsnew file mode 100644index 000000000..fb24a08cf--- /dev/null+++ b/packages/eve/src/execution/session/handoff.test.ts@@ -0,0 +1,235 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import type { DeliverHookPayload } from "#channel/types.js";+import type { DurableSessionState } from "#execution/durable-session-store.js";+import { SessionHandoff, type SessionOwnerActivation } from "#execution/session/handoff.js";+import type { TurnSelection } from "#execution/session/input-queue.js";+import type { SessionInboxHandle, SessionInboxPayload } from "#execution/session-inbox/inbox.js";++const isSessionIdleForHandoffStepMock = vi.fn(async (..._args: unknown[]) => true);+const startSessionOwnerStepMock = vi.fn();+const createHookMock = vi.fn();++vi.mock("#execution/session/handoff-steps.js", () => ({+ isSessionIdleForHandoffStep: (...args: unknown[]) => isSessionIdleForHandoffStepMock(...args),+}));+vi.mock("#execution/workflow-runtime.js", () => ({+ startSessionOwnerStep: (...args: unknown[]) => startSessionOwnerStepMock(...args),+}));+vi.mock("#compiled/@workflow/core/index.js", () => ({+ createHook: (...args: unknown[]) => createHookMock(...args),+ getWorkflowMetadata: () => ({ workflowRunId: "owner-1" }),+}));++afterEach(() => {+ vi.resetAllMocks();+ isSessionIdleForHandoffStepMock.mockResolvedValue(true);+});++const STABLE = "eve:session:session-1:inbox";++describe("SessionHandoff", () => {+ it("transfers one eligible conversational trigger with a structural checkpoint", async () => {+ const handoff = createHandoff(createInbox());+ installActivation({ kind: "active" });+ startSessionOwnerStepMock.mockResolvedValue(undefined);+ const trigger = selection("deployment-b");++ await expect(handoff.tryTransfer(trigger, state())).resolves.toEqual({+ kind: "transferred",+ });+ expect(startSessionOwnerStepMock).toHaveBeenCalledWith({+ activationToken: "owner-1:handoff",+ anchorRunId: "session-1",+ checkpoint: expect.objectContaining({+ mode: "conversation",+ sessionTimeoutMs: 60_000,+ version: 4,+ }),+ delivery: trigger.delivery,+ targetDeploymentId: "deployment-b",+ });+ await expect(handoff.awaitAnchoredResult()).resolves.toEqual({ output: "done" });+ });++ it.each([+ ["same-deployment", "deployment-a"],+ ["missing-deployment", "latest"],+ ] as const)("retains ownership for %s", async (reason, deployment) => {+ installActivation({ kind: "active" });+ const handoff = createHandoff(createInbox());+ await expect(handoff.tryTransfer(selection(deployment), state())).resolves.toEqual({+ kind: "retained",+ reason,+ });+ expect(startSessionOwnerStepMock).not.toHaveBeenCalled();+ });++ it("retains ownership when the selection was not a lone fresh conversational delivery", async () => {+ installActivation({ kind: "active" });+ const inbox = createInbox();+ await expect(+ createHandoff(inbox).tryTransfer(+ { ...selection("deployment-b"), handoffEligible: false },+ state(),+ ),+ ).resolves.toEqual({ kind: "retained", reason: "busy" });+ expect(inbox.release).not.toHaveBeenCalled();+ });++ it("retains ownership when durable state still holds work", async () => {+ installActivation({ kind: "active" });+ isSessionIdleForHandoffStepMock.mockResolvedValue(false);+ const inbox = createInbox();+ await expect(+ createHandoff(inbox).tryTransfer(selection("deployment-b"), state()),+ ).resolves.toEqual({ kind: "retained", reason: "not-idle" });+ expect(inbox.release).not.toHaveBeenCalled();+ });++ it("hands off alias-bearing sessions, marking every address while it is unowned", async () => {+ const inbox = createInbox();+ installActivation({ kind: "active" });+ startSessionOwnerStepMock.mockResolvedValue(undefined);+ const aliased = state({+ continuationToken: "channel:current",+ serializedContext: { "eve.continuationHookTokens": ["channel:old", "channel:current"] },+ });++ await expect(+ createHandoff(inbox).tryTransfer(selection("deployment-b"), aliased),+ ).resolves.toEqual({+ kind: "transferred",+ });+ const markerTokens = createHookMock.mock.calls+ .map((call) => (call[0] as { token: string }).token)+ .filter((token) => token.startsWith("eve:inbox:handoff:"));+ expect(markerTokens).toEqual([+ `eve:inbox:handoff:${STABLE}`,+ "eve:inbox:handoff:channel:old",+ "eve:inbox:handoff:channel:current",+ ]);+ // Markers and the activation hook are released; the anchor stays for the parked original run.+ for (const hook of createdHooks().filter((hook) => !hook.token.endsWith(":anchor"))) {+ expect(hook.dispose).toHaveBeenCalled();+ }+ });++ it("keeps ownership and restores accepted payloads when activation fails", async () => {+ const inbox = createInbox();+ const payloads: SessionInboxPayload[] = [+ { kind: "send", payload: { message: "Alice sends the first input." } },+ { kind: "send", payload: { message: "Bob sends the second input." } },+ ];+ installActivation({ error: new Error("bundle mismatch"), kind: "failed", payloads });+ startSessionOwnerStepMock.mockResolvedValue(undefined);++ await expect(+ createHandoff(inbox).tryTransfer(+ selection("deployment-b"),+ state({ continuationToken: "channel:current" }),+ ),+ ).resolves.toEqual({ kind: "retained", reason: "activation-failed" });+ expect(inbox.claimSessionHooks).toHaveBeenCalledWith([STABLE, "channel:current"]);+ expect(inbox.restore).toHaveBeenCalledWith(payloads);+ });++ it("abandons transfer when input was accepted during release", async () => {+ installActivation({ kind: "active" });+ const accepted: SessionInboxPayload[] = [{ kind: "send", payload: { message: "late" } }];+ const inbox = createInbox({ released: accepted });++ await expect(+ createHandoff(inbox).tryTransfer(selection("deployment-b"), state()),+ ).resolves.toEqual({ kind: "retained", reason: "accepted-during-release" });+ expect(startSessionOwnerStepMock).not.toHaveBeenCalled();+ expect(inbox.restore).toHaveBeenCalledWith(accepted);+ });+});++const created: { token: string; dispose: ReturnType<typeof vi.fn> }[] = [];+function createdHooks() {+ return created;+}++function installActivation(activation: SessionOwnerActivation): void {+ created.length = 0;+ createHookMock.mockImplementation((options: { token: string }) => {+ const resolved = options.token.endsWith(":anchor") ? { output: "done" } : activation;+ const hook = Object.assign(Promise.resolve(resolved), {+ dispose: vi.fn(),+ getConflict: vi.fn(async () => null),+ token: options.token,+ });+ created.push(hook);+ return hook;+ });+}++function delivery(acceptedDeploymentId: string): DeliverHookPayload {+ return {+ deliveryMetadata:+ acceptedDeploymentId === "latest"+ ? undefined+ : [+ {+ acceptedDeploymentId,+ channelKind: "http",+ channelName: "http",+ deliveryId: `delivery-${acceptedDeploymentId}`,+ payloadIndex: 0,+ },+ ],+ kind: "deliver",+ payloads: [{ message: "hello" }],+ };+}++function selection(acceptedDeploymentId: string): TurnSelection {+ return {+ delivery: delivery(acceptedDeploymentId),+ handoffEligible: true,+ kind: "turn",+ sequences: [0],+ };+}++function state(+ input: {+ readonly continuationToken?: string;+ readonly serializedContext?: Record<string, unknown>;+ } = {},+) {+ return {+ serializedContext: input.serializedContext ?? {},+ sessionState: {+ continuationToken: input.continuationToken ?? "",+ sessionId: "session-1",+ } as DurableSessionState,+ };+}++function createHandoff(inbox: SessionInboxHandle): SessionHandoff {+ return new SessionHandoff({+ checkpoint: { mode: "conversation", sessionTimeoutMs: 60_000 },+ deploymentId: "deployment-a",+ inbox,+ isInitialOwner: true,+ sessionId: "session-1",+ });+}++function createInbox(input: { released?: SessionInboxPayload[] } = {}): SessionInboxHandle {+ return {+ claimSessionHook: vi.fn(async () => {}),+ claimSessionHooks: vi.fn(async () => {}),+ claimedTokens: [],+ dispose: vi.fn(async () => {}),+ drain: vi.fn(() => []),+ hasPending: vi.fn(() => false),+ next: vi.fn(),+ onInterrupt: vi.fn(() => () => {}),+ release: vi.fn(async () => input.released ?? []),+ restore: vi.fn(),+ };+}diff --git a/packages/eve/src/execution/session/handoff.ts b/packages/eve/src/execution/session/handoff.tsnew file mode 100644index 000000000..55779ef0f--- /dev/null+++ b/packages/eve/src/execution/session/handoff.ts@@ -0,0 +1,197 @@+import { createHook, getWorkflowMetadata, type Hook } from "#compiled/@workflow/core/index.js";++import type { DeliverHookPayload, SessionCapabilities } from "#channel/types.js";+import { readAcceptedDeploymentId } from "#execution/session/accepted-deployment.js";+import type { DurableSessionState } from "#execution/durable-session-store.js";+import { claimHookOwnership, disposeHook } from "#execution/hook-ownership.js";+import { sessionHookTokens } from "#execution/session/hook-tokens.js";+import type { SessionInboxHandle, SessionInboxPayload } from "#execution/session-inbox/inbox.js";+import type { TurnSelection } from "#execution/session/input-queue.js";+import type { WorkflowEntryResult } from "#execution/session/entry-input.js";+import { startSessionOwnerStep } from "#execution/workflow-runtime.js";+import { sessionHandoffMarkerToken } from "#execution/session-inbox/address.js";+import { isSessionIdleForHandoffStep } from "#execution/session/handoff-steps.js";+import type { AgentWorkflowRetentionDefinition } from "#shared/agent-definition.js";+import type { RunMode } from "#shared/run-mode.js";++/**+ * Cross-deployment checkpoint contract. The successor may run a different eve+ * build than the owner that produced it; bump when any field changes shape so+ * an incompatible successor rejects the handoff instead of misreading state.+ */+export const SESSION_CHECKPOINT_VERSION = 4;++/** Everything a successor needs to continue an idle session. Hooks are derived from the state. */+export interface SessionCheckpoint {+ readonly version: typeof SESSION_CHECKPOINT_VERSION;+ readonly capabilities?: SessionCapabilities;+ readonly mode: RunMode;+ readonly retention?: AgentWorkflowRetentionDefinition;+ readonly serializedContext: Record<string, unknown>;+ readonly sessionState: DurableSessionState;+ readonly sessionTimeoutMs: number | false;+}++export type SessionOwnerActivation =+ | { readonly kind: "active" }+ | {+ readonly kind: "failed";+ readonly error: unknown;+ /** Commands accepted by partial successor claims before startup failed. */+ readonly payloads: readonly SessionInboxPayload[];+ };++export type SessionTransferOutcome =+ | { readonly kind: "transferred" }+ | {+ readonly kind: "retained";+ readonly reason:+ | "same-deployment"+ | "missing-deployment"+ | "not-idle"+ | "busy"+ | "accepted-during-release"+ | "activation-failed";+ };++export interface SessionHandoffInput {+ readonly checkpoint: Omit<SessionCheckpoint, "serializedContext" | "sessionState" | "version">;+ readonly deploymentId: string;+ readonly inbox: SessionInboxHandle;+ readonly isInitialOwner: boolean;+ readonly sessionId: string;+}++export function sessionAnchorToken(sessionId: string): string {+ return `${sessionId}:anchor`;+}++/**+ * The sole boundary for moving an idle session to another exact deployment.+ * Constructed once per owner; `tryTransfer()` is attempted per eligible selection.+ * When the upstream atomic hook-handoff primitive lands, only this class changes.+ */+export class SessionHandoff {+ private readonly input: SessionHandoffInput;+ private anchor: Hook<WorkflowEntryResult> | undefined;++ constructor(input: SessionHandoffInput) {+ this.input = input;+ }++ /**+ * Attempts to move the session to the selected delivery's deployment. The+ * outcome states whether the successor activated or this owner retained the+ * session. Candidate failures recover locally rather than escaping.+ */+ async tryTransfer(+ selection: TurnSelection,+ state: Pick<SessionCheckpoint, "serializedContext" | "sessionState">,+ ): Promise<SessionTransferOutcome> {+ const { deploymentId, inbox } = this.input;+ const targetDeploymentId = readAcceptedDeploymentId(selection.delivery);+ if (targetDeploymentId === undefined) return { kind: "retained", reason: "missing-deployment" };+ if (targetDeploymentId === deploymentId) return { kind: "retained", reason: "same-deployment" };+ if (!selection.handoffEligible) return { kind: "retained", reason: "busy" };+ if (!(await isSessionIdleForHandoffStep(state)))+ return { kind: "retained", reason: "not-idle" };++ const checkpoint: SessionCheckpoint = {+ ...this.input.checkpoint,+ ...state,+ version: SESSION_CHECKPOINT_VERSION,+ };+ const tokens = sessionHookTokens(state);+ await this.ensureAnchor();++ // Markers let ingress distinguish a session mid-handoff from an address+ // nobody owns, so a concurrent channel delivery retries instead of+ // creating a replacement session on the released alias.+ const markers = tokens.map((token) =>+ createHook<never>({ token: sessionHandoffMarkerToken(token) }),+ );+ await Promise.all(markers.map((marker) => claimHookOwnership(marker)));+ try {+ const acceptedDuringRelease = await inbox.release();+ if (acceptedDuringRelease.length > 0) {+ await this.recover(tokens, acceptedDuringRelease);+ return { kind: "retained", reason: "accepted-during-release" };+ }+ let acceptedByFailedCandidate: readonly SessionInboxPayload[] = [];+ try {+ const activation = await this.startAndActivate(+ checkpoint,+ selection.delivery,+ targetDeploymentId,+ );+ if (activation.kind === "active") return { kind: "transferred" };+ acceptedByFailedCandidate = activation.payloads;+ } catch {+ // The current owner remains authoritative until activation.+ }+ await this.recover(tokens, acceptedByFailedCandidate);+ return { kind: "retained", reason: "activation-failed" };+ } finally {+ await Promise.all(markers.map((marker) => disposeHook(marker)));+ }+ }++ /** After a transfer, the original run parks until the final owner reports the session result. */+ async awaitAnchoredResult(): Promise<WorkflowEntryResult> {+ if (this.anchor === undefined) throw new Error("Session anchor was never claimed.");+ try {+ return await this.anchor;+ } finally {+ await this.disposeAnchor();+ }+ }++ async disposeAnchor(): Promise<void> {+ if (this.anchor === undefined) return;+ const anchor = this.anchor;+ this.anchor = undefined;+ await disposeHook(anchor);+ }++ /** Starts the candidate and waits for it to activate or fail. */+ private async startAndActivate(+ checkpoint: SessionCheckpoint,+ delivery: DeliverHookPayload,+ targetDeploymentId: string,+ ): Promise<SessionOwnerActivation> {+ const activation = createHook<SessionOwnerActivation>({+ token: `${getWorkflowMetadata().workflowRunId}:handoff`,+ });+ await claimHookOwnership(activation);+ try {+ await startSessionOwnerStep({+ activationToken: activation.token,+ anchorRunId: this.input.sessionId,+ checkpoint,+ delivery,+ targetDeploymentId,+ });+ return await activation;+ } finally {+ await disposeHook(activation);+ }+ }++ /** Reclaims the exact hook set and replays payloads accepted while it was released. */+ private async recover(+ tokens: readonly string[],+ payloads: readonly SessionInboxPayload[],+ ): Promise<void> {+ await this.input.inbox.claimSessionHooks(tokens);+ this.input.inbox.restore(payloads);+ }++ private async ensureAnchor(): Promise<void> {+ // Only the original run outlives successors; intermediate owners exit.+ if (!this.input.isInitialOwner || this.anchor !== undefined) return;+ this.anchor = createHook<WorkflowEntryResult>({+ token: sessionAnchorToken(this.input.sessionId),+ });+ await claimHookOwnership(this.anchor);+ }+}diff --git a/packages/eve/src/execution/session/hook-tokens.ts b/packages/eve/src/execution/session/hook-tokens.tsnew file mode 100644index 000000000..0d147bf93--- /dev/null+++ b/packages/eve/src/execution/session/hook-tokens.ts@@ -0,0 +1,23 @@+import { ContinuationHookTokensKey } from "#context/keys.js";+import type { DurableSessionState } from "#execution/durable-session-store.js";+import { sessionCommandHookToken } from "#execution/session-inbox/address.js";++/**+ * Every hook a session answers to, derived from its committed state: the+ * stable command inbox plus each continuation alias a channel handler+ * selected. This is the one source of truth for claims at boot, at every+ * state transition, and across a deployment handoff.+ */+export function sessionHookTokens(input: {+ readonly serializedContext: Record<string, unknown>;+ readonly sessionState: Pick<DurableSessionState, "continuationToken" | "sessionId">;+}): readonly string[] {+ const recorded = input.serializedContext[ContinuationHookTokensKey.name];+ const tokens = new Set<string>([sessionCommandHookToken(input.sessionState.sessionId)]);+ if (Array.isArray(recorded)) {+ for (const token of recorded)+ if (typeof token === "string" && token.length > 0) tokens.add(token);+ }+ if (input.sessionState.continuationToken !== "") tokens.add(input.sessionState.continuationToken);+ return [...tokens];+}diff --git a/packages/eve/src/execution/session/input-queue.ts b/packages/eve/src/execution/session/input-queue.tsnew file mode 100644index 000000000..f3f3ecd77--- /dev/null+++ b/packages/eve/src/execution/session/input-queue.ts@@ -0,0 +1,349 @@+import type { DeliverHookPayload, DeliverPayload } from "#channel/types.js";+import { coalesceDeliveries } from "#harness/messages.js";+import { jsonValuesEqual } from "#shared/json.js";+import type { getSessionTaskCohorts } from "#tasks/session-task-cohorts.js";++export type SessionControl = "clear" | "compact" | "expired" | "reset";++type TaskCohorts = ReturnType<typeof getSessionTaskCohorts>;++export interface DeliveryAdmission {+ readonly delivery: DeliverHookPayload;+ readonly sequence: number;+}++interface QueuedDelivery extends DeliveryAdmission {+ readonly kind: "delivery";+}++interface QueuedControl {+ readonly control: SessionControl;+ readonly kind: "control";+ readonly sequence: number;+}++interface QueuedAuthorization {+ readonly attemptId: string;+ readonly kind: "authorization";+ readonly payload: DeliverPayload;+ readonly sequence: number;+}++type QueuedSessionInput = QueuedDelivery | QueuedControl | QueuedAuthorization;++export interface TurnSelection {+ readonly delivery: DeliverHookPayload;+ /**+ * True only for a lone, callerless conversational delivery that arrived+ * while nothing else was pending. Such a delivery may move the session to+ * the deployment that accepted it.+ */+ readonly handoffEligible: boolean;+ readonly kind: "turn";+ /** Sequences of every admission folded into this turn. */+ readonly sequences: readonly number[];+}++export type SessionInputSelection =+ | TurnSelection+ | { readonly control: SessionControl; readonly kind: "control" }+ | { readonly kind: "authorization-resume"; readonly payloads: readonly DeliverPayload[] };++/**+ * Ordered, admitted session input, plus the idempotency and cancellation+ * facts for task deliveries this owner has seen. Entries are private; callers+ * receive typed admission and selection values. Everything here is rebuilt+ * deterministically on replay, and a successor never inherits it because+ * handoff requires every indexed task to be terminal.+ */+export class SessionInputQueue {+ private readonly entries: QueuedSessionInput[] = [];+ private readonly cancelledTaskIds = new Set<string>();+ private readonly seenTaskDeliveryIds = new Set<string>();+ private nextSequence = 0;++ get pendingCount(): number {+ return this.entries.length;+ }++ /** Admits a delivery unless it repeats or belongs to a cancelled task. */+ enqueueDelivery(delivery: DeliverHookPayload): DeliveryAdmission | undefined {+ const deliveryId = taskDeliveryId(delivery);+ if (deliveryId !== undefined) {+ if (this.seenTaskDeliveryIds.has(deliveryId) || this.isCancelledTaskDelivery(deliveryId)) {+ return undefined;+ }+ this.seenTaskDeliveryIds.add(deliveryId);+ }+ const admission = { delivery, sequence: this.nextSequence++ };+ this.entries.push({ ...admission, kind: "delivery" });+ return admission;+ }++ /** A caller's own task id counts as seen so its echo is not admitted twice. */+ rememberTask(taskId: string): void {+ this.seenTaskDeliveryIds.add(taskId);+ }++ isTaskCancelled(taskId: string): boolean {+ return this.cancelledTaskIds.has(taskId);+ }++ enqueueControl(control: SessionControl): void {+ this.entries.push({ control, kind: "control", sequence: this.nextSequence++ });+ }++ /** Keeps one payload per authorization attempt; a repeated callback for the same attempt is dropped. */+ enqueueAuthorization(payloads: readonly DeliverPayload[]): void {+ for (const payload of payloads) {+ const attemptId = authorizationAttemptId(payload);+ if (attemptId === undefined) continue;+ if (+ this.entries.some(+ (entry) => entry.kind === "authorization" && entry.attemptId === attemptId,+ )+ )+ continue;+ this.entries.push({+ attemptId,+ kind: "authorization",+ payload,+ sequence: this.nextSequence++,+ });+ }+ }++ delivery(sequence: number): DeliverHookPayload | undefined {+ const entry = this.entries.find(+ (candidate): candidate is QueuedDelivery =>+ candidate.kind === "delivery" && candidate.sequence === sequence,+ );+ return entry?.delivery;+ }++ replaceDelivery(sequence: number, delivery: DeliverHookPayload | undefined): void {+ const index = this.entries.findIndex(+ (entry) => entry.kind === "delivery" && entry.sequence === sequence,+ );+ if (index < 0) return;+ if (delivery === undefined) {+ this.entries.splice(index, 1);+ return;+ }+ this.entries[index] = { delivery, kind: "delivery", sequence };+ }++ /** Drops queued notifications from a cancelled task and refuses later ones. */+ cancelTask(taskId: string): void {+ this.cancelledTaskIds.add(taskId);+ this.retain(+ (entry) =>+ entry.kind !== "delivery" ||+ !isTaskDelivery(entry.delivery, (id) => id === taskId || id.startsWith(`${taskId}:`)),+ );+ }++ takeSteering(+ admitted: ReadonlySet<number>,+ callerCallId: string | undefined,+ ): TurnSelection | undefined {+ const steering = this.entries.filter(+ (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),+ );+ if (steering.length === 0) return undefined;+ this.retain((entry) => entry.kind !== "delivery" || !steering.includes(entry));+ return {+ delivery: combine(steering),+ handoffEligible: false,+ kind: "turn",+ sequences: steering.map(({ sequence }) => sequence),+ };+ }++ takeNext(+ cohorts: TaskCohorts,+ options?: {+ readonly deferDeliveries?: boolean;+ /**+ * Attempt ids of the open authorization challenge. Callbacks for other+ * attempts are stale and dropped; once every expected attempt has+ * reported, the collected payloads resume the challenge ahead of+ * ordinary input.+ */+ readonly expectedAttemptIds?: ReadonlySet<string>;+ /** Sequence of a delivery admitted while nothing else was pending. */+ readonly freshSequence?: number;+ },+ ): SessionInputSelection | undefined {+ const expected = options?.expectedAttemptIds ?? new Set<string>();+ this.retain((entry) => entry.kind !== "authorization" || expected.has(entry.attemptId));+ if (expected.size > 0) {+ const collected = new Map(+ this.entries.flatMap((entry) =>+ entry.kind === "authorization" ? [[entry.attemptId, entry.payload] as const] : [],+ ),+ );+ if ([...expected].every((attemptId) => collected.has(attemptId))) {+ this.retain((entry) => entry.kind !== "authorization");+ return {+ kind: "authorization-resume",+ payloads: [...expected].map((attemptId) => collected.get(attemptId)!),+ };+ }+ }+ const index = this.nextActionableIndex(cohorts, options?.deferDeliveries === true);+ if (index < 0) return undefined;+ return this.takeSelectionAt(index, cohorts, options?.freshSequence);+ }++ private nextActionableIndex(cohorts: TaskCohorts, deferDeliveries: boolean): number {+ const deliveries = this.entries.filter(+ (entry): entry is QueuedDelivery => entry.kind === "delivery",+ );+ const completed = new Set(+ deliveries.flatMap(({ delivery }) => {+ const taskId = completionTaskId(delivery);+ return taskId === undefined ? [] : [taskId];+ }),+ );+ const pendingCohorts = new Set<string>();+ for (const [taskId, cohort] of cohorts) {+ if (!cohort.settled && !completed.has(taskId) && !this.cancelledTaskIds.has(taskId)) {+ pendingCohorts.add(cohort.cohortId);+ }+ }+ return this.entries.findIndex((entry) => {+ if (entry.kind === "control") return true;+ if (entry.kind === "authorization" || deferDeliveries) return false;+ const cohort = completionCohort(entry.delivery, cohorts);+ return cohort === undefined || !pendingCohorts.has(cohort);+ });+ }++ private takeSelectionAt(+ index: number,+ cohorts: TaskCohorts,+ freshSequence: number | undefined,+ ): SessionInputSelection {+ const selected = this.entries[index]!;+ if (selected.kind !== "delivery") {+ this.entries.splice(index, 1);+ if (selected.kind === "control") return { control: selected.control, kind: "control" };+ return { kind: "authorization-resume", payloads: [selected.payload] };+ }+ const readyCohort = completionCohort(selected.delivery, cohorts);+ if (readyCohort !== undefined) {+ const lastSibling = this.entries.findLastIndex(+ (entry) =>+ entry.kind === "delivery" && completionCohort(entry.delivery, cohorts) === readyCohort,+ );+ const boundary = this.entries.findIndex(+ (entry, position) =>+ position > index &&+ position < lastSibling &&+ (entry.kind !== "delivery" || completionCohort(entry.delivery, cohorts) === undefined),+ );+ if (boundary >= 0) return this.takeSelectionAt(boundary, cohorts, freshSequence);+ }++ const first = this.entries.splice(index, 1)[0]!;+ if (first.kind !== "delivery") throw new Error("Selected a non-delivery entry as a turn.");+ const turnEntries = [first];+ const cohort = completionCohort(first.delivery, cohorts);+ if (cohort !== undefined) {+ const siblings = this.entries.filter(+ (entry): entry is QueuedDelivery =>+ entry.kind === "delivery" && completionCohort(entry.delivery, cohorts) === cohort,+ );+ turnEntries.push(...siblings);+ this.retain(+ (entry) =>+ entry.kind !== "delivery" || completionCohort(entry.delivery, cohorts) !== cohort,+ );+ } else {+ const authenticated =+ first.delivery.auth != null && first.delivery.auth.principalType !== "anonymous";+ let caller = first.delivery.caller;+ while (this.entries.length > index) {+ const next = this.entries[index];+ if (+ next?.kind !== "delivery" ||+ first.delivery.taskDeliveryId !== undefined ||+ next.delivery.taskDeliveryId !== undefined ||+ !authenticated ||+ !jsonValuesEqual(first.delivery.auth, next.delivery.auth) ||+ (caller !== undefined && next.delivery.caller !== undefined)+ ) {+ break;+ }+ turnEntries.push(this.entries.splice(index, 1)[0] as QueuedDelivery);+ caller ??= next.delivery.caller;+ }+ }++ const sequences = turnEntries.map(({ sequence }) => sequence);+ const combined = combine(turnEntries);+ return {+ delivery: combined,+ handoffEligible:+ sequences.length === 1 &&+ sequences[0] === freshSequence &&+ combined.caller === undefined &&+ taskDeliveryId(combined) === undefined &&+ this.entries.length === 0,+ kind: "turn",+ sequences,+ };+ }++ private isCancelledTaskDelivery(deliveryId: string): boolean {+ for (const taskId of this.cancelledTaskIds) {+ if (deliveryId === taskId || deliveryId.startsWith(`${taskId}:`)) return true;+ }+ return false;+ }++ private retain(predicate: (entry: QueuedSessionInput) => boolean): void {+ const kept = this.entries.filter(predicate);+ this.entries.splice(0, this.entries.length, ...kept);+ }+}++function combine(entries: readonly DeliveryAdmission[]): DeliverHookPayload {+ return entries.length === 1+ ? entries[0]!.delivery+ : coalesceDeliveries(entries.map(({ delivery }) => delivery));+}++function authorizationAttemptId(payload: DeliverPayload): string | undefined {+ const callback = payload["authorizationCallback"] as { readonly attemptId?: unknown } | undefined;+ return typeof callback?.attemptId === "string" ? callback.attemptId : undefined;+}++function taskDeliveryId(delivery: DeliverHookPayload): string | undefined {+ return delivery.taskDeliveryId ?? delivery.caller?.taskId;+}++function isTaskDelivery(+ delivery: DeliverHookPayload,+ predicate: (deliveryId: string) => boolean,+): boolean {+ const deliveryId = taskDeliveryId(delivery);+ return deliveryId !== undefined && predicate(deliveryId);+}++function completionCohort(delivery: DeliverHookPayload, cohorts: TaskCohorts): string | undefined {+ const taskId = completionTaskId(delivery);+ return taskId === undefined ? undefined : cohorts.get(taskId)?.cohortId;+}++function completionTaskId(delivery: DeliverHookPayload): string | undefined {+ const suffix = ":ready:completed";+ if (delivery.caller !== undefined || !delivery.taskDeliveryId?.endsWith(suffix)) return undefined;+ return delivery.taskDeliveryId.slice(0, -suffix.length);+}diff --git a/packages/eve/src/execution/parked-delivery-wait.test.ts b/packages/eve/src/execution/session/next-input.test.tssimilarity index 65%rename from packages/eve/src/execution/parked-delivery-wait.test.tsrename to packages/eve/src/execution/session/next-input.test.tsindex 9528c4277..2a0f7cb98 100644--- a/packages/eve/src/execution/parked-delivery-wait.test.ts+++ b/packages/eve/src/execution/session/next-input.test.ts@@ -1,22 +1,22 @@+import { createTestSessionState } from "#internal/testing/session-state.js";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { DeliverHookPayload, SessionAuthContext } from "#channel/types.js";-import { nextTurnDelivery } from "#execution/parked-delivery-wait.js";+import { nextTurnDelivery } from "#execution/session/next-input.js";+import { SessionInputQueue } from "#execution/session/input-queue.js";import { routeDeliverToChildren } from "#execution/route-child-delivery.js";-import type {- SessionCommandInbox,- SessionInboxPayload,- SessionInboxSource,-} from "#execution/session-command-inbox.js";-import type { DurableSessionState } from "#execution/durable-session-store.js";-import { SessionStateCursor } from "#execution/session-state-cursor.js";+import type { SessionInbox, SessionInboxPayload } from "#execution/session-inbox/inbox.js";+import { SessionStateCursor } from "#execution/session/state-cursor.js";import { cacheTerminalTaskView } from "#tasks/session-index.js";import type { TaskView } from "#tasks/types.js";-vi.mock("./route-child-delivery.js", () => ({+vi.mock("#compiled/@workflow/core/index.js", () => ({+ getWorkflowMetadata: () => ({ workflowRunId: "owner-1" }),+}));+vi.mock("../route-child-delivery.js", () => ({routeDeliverToChildren: vi.fn(),}));-vi.mock("./cancel-indexed-session-tasks-step.js", () => ({+vi.mock("../cancel-indexed-session-tasks-step.js", () => ({cancelAllIndexedSessionTasksStep: vi.fn(),}));@@ -29,95 +29,100 @@ beforeEach(() => {interface ScriptedRead {readonly result: IteratorResult<SessionInboxPayload>;- readonly source: SessionInboxSource;-}--interface MockInbox extends SessionCommandInbox {- readonly windowTransitions: boolean[];}-/**- * Scripted inbox: serves reads in order and records every authorization- * window transition so tests can assert the window spans the whole wait.- */-function createMockInbox(reads: readonly ScriptedRead[], authorizationReady = false): MockInbox {+/** Scripted inbox: serves reads in order. */+function createMockInbox(reads: readonly ScriptedRead[]): SessionInbox {const remaining = [...reads];- const windowTransitions: boolean[] = [];return {- windowTransitions,- async claimAuthorization() {},- async claimStable() {},- consumeNext() {},- hasReadyAuthorization() {- return authorizationReady;+ claimedTokens: [],+ async claimSessionHook() {},+ async claimSessionHooks() {},+ drain() {+ return remaining.splice(0).map((read) => read.result.value);},- async next() {- const read = remaining.shift();- if (read === undefined) throw new Error("Mock inbox exhausted.");- return read.result;+ hasPending() {+ return remaining.length > 0;},- async nextWithSource() {+ async next() {const read = remaining.shift();if (read === undefined) throw new Error("Mock inbox exhausted.");- return read;+ if (read.result.done) return undefined;+ return read.result.value;},- async rekeyContinuation() {},- setAuthorizationWindow(open: boolean) {- windowTransitions.push(open);+ onInterrupt() {+ return () => {};},+ restore() {},};}-function authorizationRead(): ScriptedRead {- return {- result: {- done: false,- value: {- kind: "deliver",- payloads: [- {- authorizationCallback: {- callback: { method: "GET", params: { code: "abc" } },- connectionName: "weather",- },- },- ],- } satisfies DeliverHookPayload,+const authorizationCallbackPayload = {+ kind: "authorization-callback",+ payloads: [+ {+ authorizationCallback: {+ attemptId: "attempt-1",+ callback: { method: "GET", params: { code: "abc" } },+ connectionName: "weather",+ },},- source: "authorization",- };+ ],+} satisfies SessionInboxPayload;++function authorizationRead(): ScriptedRead {+ return { result: { done: false, value: authorizationCallbackPayload } };}function cancelRead(command: Record<string, unknown> = {}): ScriptedRead {return {result: { done: false, value: { kind: "cancel", ...command } },- source: "session",};}function messageRead(message: string): ScriptedRead {return {result: { done: false, value: { kind: "send", payload: { message } } },- source: "session",};}-// Routing never runs in these tests: scripted reads stop at authorization-// instructions or exhaust before any deliver-kind turn payload.-const sessionState = { sessionId: "ses-parked-wait" } as DurableSessionState;+const sessionState = createTestSessionState({ sessionId: "ses-parked-wait" });++type WaitInput = {+ -readonly [K in keyof Parameters<typeof nextTurnDelivery>[0]]: Parameters<+ typeof nextTurnDelivery+ >[0][K];+};-function waitInput(inbox: SessionCommandInbox): Parameters<typeof nextTurnDelivery>[0] {+function waitInput(inbox: SessionInbox): WaitInput {+ const cursor = createCursor(inbox);return {- awaitAuthorizationCallbacks: true,- bufferedDeliveries: [],- bufferedSessionControls: [],- commandInbox: inbox,- driverWritable: new WritableStream<Uint8Array>(),- stateCursor: new SessionStateCursor({ serializedContext: {}, sessionState }),+ expectedAttemptIds: new Set(["attempt-1"]),+ inbox: inbox,+ cursor,+ queue: new SessionInputQueue(),};}+function createCursor(+ inbox: Pick<SessionInbox, "claimSessionHooks">,+ state = sessionState,+): SessionStateCursor {+ return new SessionStateCursor({+ inbox: inbox,+ sessionWritable: new WritableStream<Uint8Array>(),+ serializedContext: {},+ sessionState: state,+ });+}++function queueOf(...deliveries: DeliverHookPayload[]): SessionInputQueue {+ const queue = new SessionInputQueue();+ for (const delivery of deliveries) queue.enqueueDelivery(delivery);+ return queue;+}+describe("nextTurnDelivery", () => {it("batches adjacent queued deliveries with equivalent auth", async () => {const auth: SessionAuthContext = {@@ -148,7 +153,43 @@ describe("nextTurnDelivery", () => {],},});- expect(input.bufferedDeliveries).toEqual([]);+ expect(input.queue.pendingCount).toBe(0);+ });++ it("reports a sole conversation delivery with its single admission", async () => {+ const delivery: DeliverHookPayload = {+ kind: "deliver",+ payloads: [{ message: "continue on the accepting deployment" }],+ };+ const input = batchingInputFor([delivery]);++ await expect(nextTurnDelivery(input)).resolves.toMatchObject({+ delivery,+ handoffEligible: false,+ kind: "turn",+ });+ });++ it("considers a sole pumped delivery an idle handoff candidate", async () => {+ const input = batchingInputFor([]);+ const inbox = createMockInbox([messageRead("next turn")]);++ await expect(nextTurnDelivery({ ...input, inbox })).resolves.toMatchObject({+ kind: "turn",+ handoffEligible: true,+ delivery: { payloads: [{ message: "next turn" }] },+ });+ });++ it("does not hand off the first delivery in a buffered burst", async () => {+ const input = batchingInputFor([]);+ const inbox = createMockInbox([messageRead("first"), messageRead("second")]);++ await expect(nextTurnDelivery({ ...input, inbox })).resolves.toMatchObject({+ kind: "turn",+ handoffEligible: false,+ delivery: { payloads: [{ message: "first" }] },+ });});it("keeps different principals in FIFO turns without regrouping later messages", async () => {@@ -174,7 +215,7 @@ describe("nextTurnDelivery", () => {delivery: { payloads: [{ message: "alice-3" }] },kind: "turn",});- expect(input.bufferedDeliveries).toEqual([]);+ expect(input.queue.pendingCount).toBe(0);});it.each([@@ -189,8 +230,8 @@ describe("nextTurnDelivery", () => {const second = authenticatedDelivery("second", { ...auth, ...change });const input = batchingInputFor([first, second]);- await expect(nextTurnDelivery(input)).resolves.toEqual({ delivery: first, kind: "turn" });- expect(input.bufferedDeliveries).toEqual([second]);+ await expect(nextTurnDelivery(input)).resolves.toMatchObject({ delivery: first, kind: "turn" });+ expect(input.queue.pendingCount).toBe(1);});it.each([null, undefined])("does not batch deliveries with auth %j", async (auth) => {@@ -198,8 +239,8 @@ describe("nextTurnDelivery", () => {const second: DeliverHookPayload = { auth, kind: "deliver", payloads: [{ message: "second" }] };const input = batchingInputFor([first, second]);- await expect(nextTurnDelivery(input)).resolves.toEqual({ delivery: first, kind: "turn" });- expect(input.bufferedDeliveries).toEqual([second]);+ await expect(nextTurnDelivery(input)).resolves.toMatchObject({ delivery: first, kind: "turn" });+ expect(input.queue.pendingCount).toBe(1);});it("surfaces an authorization callback as its own instruction", async () => {@@ -207,11 +248,9 @@ describe("nextTurnDelivery", () => {const next = await nextTurnDelivery(waitInput(inbox));- expect(next.kind).toBe("authorization");- if (next.kind !== "authorization") throw new Error("unreachable");- expect(next.closed).toBe(false);- expect(next.payloads).toHaveLength(1);- expect(inbox.windowTransitions).toEqual([true, false]);+ expect(next.kind).toBe("authorization-resume");+ if (next.kind !== "authorization-resume") throw new Error("unreachable");+ expect(next.payloads).toEqual(authorizationCallbackPayload.payloads);});it("cancels indexed tasks and keeps waiting for ordinary parked activity", async () => {@@ -220,73 +259,50 @@ describe("nextTurnDelivery", () => {const next = await nextTurnDelivery(input);- expect(next.kind).toBe("authorization");+ expect(next.kind).toBe("authorization-resume");expect(cancelAllIndexedSessionTasksStep).toHaveBeenCalledWith({- serializedContext: input.stateCursor.serializedContext,- sessionState: input.stateCursor.sessionState,+ serializedContext: input.cursor.serializedContext,+ sessionState: input.cursor.sessionState,});});- it("keeps the authorization window open across a consumed no-op cancel", async () => {+ it("resumes authorization after a consumed no-op cancel", async () => {// A cancel with no active turn is consumed without producing a parent- // turn; the wait continues and the callback must still surface within- // the same window instead of stashing until unrelated activity.+ // turn; the wait continues and the callback must still resume the challenge.const inbox = createMockInbox([cancelRead(), authorizationRead()]);const next = await nextTurnDelivery(waitInput(inbox));- expect(next.kind).toBe("authorization");- expect(inbox.windowTransitions).toEqual([true, false]);+ expect(next.kind).toBe("authorization-resume");});it("does not let buffered deliveries bypass a ready authorization callback", async () => {- const inbox = createMockInbox([authorizationRead()], true);- const bufferedDeliveries: DeliverHookPayload[] = [- { kind: "deliver", payloads: [{ message: "later" }] },- ];+ const inbox = createMockInbox([]);+ const queue = queueOf({ kind: "deliver", payloads: [{ message: "later" }] });+ queue.enqueueAuthorization(authorizationCallbackPayload.payloads);- const next = await nextTurnDelivery({- ...waitInput(inbox),- bufferedDeliveries,- });+ const next = await nextTurnDelivery({ ...waitInput(inbox), queue });- expect(next.kind).toBe("authorization");- expect(bufferedDeliveries).toHaveLength(1);+ expect(next.kind).toBe("authorization-resume");+ expect(queue.pendingCount).toBe(1);});it("buffers task deliveries until the authorization callback arrives", async () => {const inbox = createMockInbox([messageRead("deferred"), authorizationRead()]);- const bufferedDeliveries: DeliverHookPayload[] = [];+ const queue = new SessionInputQueue();- const next = await nextTurnDelivery({- ...waitInput(inbox),- bufferedDeliveries,- deferDeliveries: true,- });+ const next = await nextTurnDelivery({ ...waitInput(inbox), queue, deferDeliveries: true });- expect(next.kind).toBe("authorization");- expect(bufferedDeliveries).toMatchObject([- { kind: "deliver", payloads: [{ message: "deferred" }] },- ]);+ expect(next.kind).toBe("authorization-resume");+ expect(queue.pendingCount).toBe(1);});- it("reports a closed authorization hook", async () => {- const inbox = createMockInbox([- { result: { done: true, value: undefined }, source: "authorization" },- ]);+ it("reports session closure while waiting for authorization", async () => {+ const inbox = createMockInbox([{ result: { done: true, value: undefined } }]);const next = await nextTurnDelivery(waitInput(inbox));- expect(next).toMatchObject({ closed: true, kind: "authorization", payloads: [] });- });-- it("never opens the window without an open challenge", async () => {- const inbox = createMockInbox([cancelRead(), cancelRead()]);-- await expect(- nextTurnDelivery({ ...waitInput(inbox), awaitAuthorizationCallbacks: false }),- ).rejects.toThrow("Mock inbox exhausted.");- expect(inbox.windowTransitions).toEqual([]);+ expect(next).toMatchObject({ kind: "closed" });});it("carries retired proxy state through fully routed parked deliveries", async () => {@@ -308,7 +324,7 @@ describe("nextTurnDelivery", () => {const next = await nextTurnDelivery({...waitInput(inbox),- awaitAuthorizationCallbacks: false,+ expectedAttemptIds: undefined,});expect(vi.mocked(routeDeliverToChildren).mock.calls[1]?.[0].sessionState).toBe(retiredState);@@ -357,18 +373,18 @@ function batchingInputFor(bufferedDeliveries: DeliverHookPayload[]) {sessionState,}),);- return { ...input, bufferedDeliveries };+ return { ...input, queue: queueOf(...bufferedDeliveries) };}describe("nextTurnDelivery routing", () => {it("keeps waiting instead of starting a parent turn for a fully routed task response", async () => {- const sessionState = {+ const sessionState = createTestSessionState({continuationToken: "token",emissionState: { sequence: 0, sessionStarted: false, stepIndex: 0, turnId: "turn" },hasProxyInputRequests: true,sessionId: "session",version: 1,- } as const;+ });const routedSessionState = { ...sessionState, hasProxyInputRequests: false };vi.mocked(routeDeliverToChildren).mockResolvedValueOnce({@@ -387,27 +403,22 @@ describe("nextTurnDelivery routing", () => {{ kind: "send" as const, payload: { inputResponses: [{ requestId: "task-request" }] } },{ kind: "send" as const, payload: { message: "ordinary" } },];- const commandInbox: SessionCommandInbox = {- claimAuthorization: vi.fn(),- claimStable: vi.fn(),- consumeNext: vi.fn(),- hasReadyAuthorization: vi.fn(() => false),- next: vi.fn(async () => ({ done: false as const, value: commands.shift()! })),- nextWithSource: vi.fn(async () => ({- result: { done: false as const, value: commands.shift()! },- source: "session" as const,- })),- rekeyContinuation: vi.fn(),- setAuthorizationWindow: vi.fn(),+ const inbox: SessionInbox = {+ claimedTokens: [],+ claimSessionHook: vi.fn(),+ claimSessionHooks: vi.fn(),+ drain: vi.fn(() => commands.splice(0)),+ hasPending: vi.fn(() => commands.length > 0),+ next: vi.fn(async () => commands.shift()),+ onInterrupt: vi.fn(() => () => {}),+ restore: vi.fn(),};- const stateCursor = new SessionStateCursor({ serializedContext: {}, sessionState });+ const cursor = createCursor(inbox, sessionState);const result = await nextTurnDelivery({- bufferedDeliveries: [],- bufferedSessionControls: [],- commandInbox,- driverWritable: new WritableStream<Uint8Array>(),- stateCursor,+ inbox,+ cursor,+ queue: new SessionInputQueue(),});expect(result).toMatchObject({@@ -415,7 +426,7 @@ describe("nextTurnDelivery routing", () => {kind: "turn",});expect(routeDeliverToChildren).toHaveBeenCalledTimes(2);- expect(stateCursor.sessionState).toBe(routedSessionState);+ expect(cursor.sessionState).toBe(routedSessionState);});});@@ -452,44 +463,42 @@ function completion(taskId: string): DeliverHookPayload {function batchingInput(count = 100, crossTurn = false) {const input = waitInput(createMockInbox([]));- input.stateCursor.adoptState({- sessionState: {- ...sessionState,- snapshot: {- version: 1,- session: {- sessionId: "session",- continuationToken: "token",- history: [],- agent: { system: "" },- state: {- "eve.tasks": {- version: 2,- tasks: Array.from({ length: count }, (_, index) => ({- taskId: `task_${index}`,- cohortId: "task_0",- taskRunId: `run-${index}`,- taskInboxToken: `inbox-${index}`,- createdByTurnId: crossTurn ? `turn-${index + 1}` : "turn-1",+ const taskSessionState = {+ ...sessionState,+ snapshot: {+ session: {+ sessionId: "session",+ continuationToken: "token",+ history: [],+ agent: { system: "" },+ state: {+ "eve.tasks": {+ version: 2,+ tasks: Array.from({ length: count }, (_, index) => ({+ taskId: `task_${index}`,+ cohortId: "task_0",+ taskRunId: `run-${index}`,+ taskInboxToken: `inbox-${index}`,+ createdByTurnId: crossTurn ? `turn-${index + 1}` : "turn-1",+ dispatchContext: { auth: { current: null, initiator: null } },+ metadata: { kind: "subagent", name: "worker" },+ })).concat([+ {+ taskId: "other-cohort",+ cohortId: "other-cohort",+ taskRunId: "other-run",+ taskInboxToken: "other-inbox",+ createdByTurnId: "turn-2",dispatchContext: { auth: { current: null, initiator: null } },metadata: { kind: "subagent", name: "worker" },- })).concat([- {- taskId: "other-cohort",- cohortId: "other-cohort",- taskRunId: "other-run",- taskInboxToken: "other-inbox",- createdByTurnId: "turn-2",- dispatchContext: { auth: { current: null, initiator: null } },- metadata: { kind: "subagent", name: "worker" },- },- ]),- },+ },+ ]),},},},},- });+ };+ input.cursor = createCursor({ claimSessionHooks: async () => {} }, taskSessionState);vi.mocked(routeDeliverToChildren).mockImplementation(async ({ delivery, sessionState, serializedContext }) => ({kind: "continue",@@ -508,8 +517,8 @@ describe("buffered task completion batching", () => {it("delivers 100 buffered sibling results and their metadata in one parent turn", async () => {const input = batchingInput();const deliveries = Array.from({ length: 100 }, (_, index) => completion(`task_${index}`));- const bufferedDeliveries = [...deliveries];- const next = await nextTurnDelivery({ ...input, bufferedDeliveries });+ const queue = queueOf(...deliveries);+ const next = await nextTurnDelivery({ ...input, queue });expect(next).toMatchObject({kind: "turn",@@ -522,7 +531,7 @@ describe("buffered task completion batching", () => {})),},});- expect(bufferedDeliveries).toEqual([]);+ expect(queue.pendingCount).toBe(0);expect(routeDeliverToChildren).toHaveBeenCalledTimes(1);});@@ -553,10 +562,10 @@ describe("buffered task completion batching", () => {const first = completion("task_0");const second = completion("task_1");const later = completion("task_3");- const bufferedDeliveries = [first, second, boundary, later];- const next = await nextTurnDelivery({ ...input, bufferedDeliveries });- expect(next).toEqual({ kind: "turn", delivery: boundary });- expect(bufferedDeliveries).toEqual([first, second, later]);+ const queue = queueOf(first, second, boundary, later);+ const next = await nextTurnDelivery({ ...input, queue });+ expect(next).toMatchObject({ kind: "turn", delivery: boundary });+ expect(queue.pendingCount).toBe(3);},);@@ -567,25 +576,25 @@ describe("buffered task completion batching", () => {const first = completion("task_0");const second = completion("task_1");const last = completion("task_2");- input.bufferedDeliveries.push(first);- input.commandInbox = createMockInbox([- { result: { done: false, value: second }, source: "session" },+ input.queue.enqueueDelivery(first);+ input.inbox = createMockInbox([+ { result: { done: false, value: second } },messageRead("user question"),- { result: { done: false, value: last }, source: "session" },+ { result: { done: false, value: last } },]);await expect(nextTurnDelivery(input)).resolves.toMatchObject({kind: "turn",delivery: { payloads: [{ message: "user question" }] },});- expect(input.bufferedDeliveries).toEqual([first, second]);+ expect(input.queue.pendingCount).toBe(2);expect(routeDeliverToChildren).toHaveBeenCalledTimes(1);await expect(nextTurnDelivery(input)).resolves.toMatchObject({kind: "turn",delivery: { payloads: [...first.payloads, ...second.payloads, ...last.payloads] },});- expect(input.bufferedDeliveries).toEqual([]);+ expect(input.queue.pendingCount).toBe(0);expect(routeDeliverToChildren).toHaveBeenCalledTimes(2);},);@@ -593,7 +602,7 @@ describe("buffered task completion batching", () => {it("batches a whole cohort when every completion arrives after the active turn", async () => {const input = batchingInput(3);const deliveries = [completion("task_0"), completion("task_1"), completion("task_2")];- input.commandInbox = createMockInbox(+ input.inbox = createMockInbox(deliveries.map((value) => ({ result: { done: false, value }, source: "session" })),);await expect(nextTurnDelivery(input)).resolves.toMatchObject({@@ -642,7 +651,7 @@ describe("buffered task completion batching", () => {},],};- input.bufferedDeliveries.push(first, settlement, last);+ for (const delivery of [first, settlement, last]) input.queue.enqueueDelivery(delivery);vi.mocked(routeDeliverToChildren).mockImplementation(async ({ delivery, sessionState, serializedContext }) => ({kind: "continue",@@ -662,7 +671,7 @@ describe("buffered task completion batching", () => {settlement,expect.objectContaining({ payloads: [...first.payloads, ...last.payloads] }),]);- expect(input.bufferedDeliveries).toEqual([]);+ expect(input.queue.pendingCount).toBe(0);});it("combines siblings across buffered deliveries from another cohort", async () => {@@ -670,13 +679,13 @@ describe("buffered task completion batching", () => {const first = completion("task_0");const last = completion("task_1");const other = completion("other-cohort");- input.bufferedDeliveries.push(first, other, last);+ for (const delivery of [first, other, last]) input.queue.enqueueDelivery(delivery);await expect(nextTurnDelivery(input)).resolves.toMatchObject({kind: "turn",delivery: { payloads: [...first.payloads, ...last.payloads] },});- expect(input.bufferedDeliveries).toEqual([other]);- await expect(nextTurnDelivery(input)).resolves.toEqual({ kind: "turn", delivery: other });+ expect(input.queue.pendingCount).toBe(1);+ await expect(nextTurnDelivery(input)).resolves.toMatchObject({ kind: "turn", delivery: other });});it.each(["clear", "compact", "reset", "session-timeout"] as const)(@@ -684,14 +693,14 @@ describe("buffered task completion batching", () => {async (kind) => {const input = batchingInput(2);const first = completion("task_0");- input.bufferedDeliveries.push(first);- input.commandInbox = createMockInbox([- { result: { done: false, value: { kind } }, source: "session" },- ]);+ input.queue.enqueueDelivery(first);+ const value: SessionInboxPayload =+ kind === "session-timeout" ? { kind, ownerRunId: "owner-1" } : { kind };+ input.inbox = createMockInbox([{ result: { done: false, value } }]);await expect(nextTurnDelivery(input)).resolves.toEqual({kind: kind === "session-timeout" ? "expired" : kind,});- expect(input.bufferedDeliveries).toEqual([first]);+ expect(input.queue.pendingCount).toBe(1);expect(routeDeliverToChildren).not.toHaveBeenCalled();},);@@ -699,16 +708,16 @@ describe("buffered task completion batching", () => {it("does not wait for a cancelled sibling whose notifications are discarded", async () => {const input = batchingInput(2);const first = completion("task_0");- input.bufferedDeliveries.push(first);- input.commandInbox = createMockInbox([cancelRead({ taskId: "task_1" })]);- await expect(nextTurnDelivery(input)).resolves.toEqual({ kind: "turn", delivery: first });+ input.queue.enqueueDelivery(first);+ input.inbox = createMockInbox([cancelRead({ taskId: "task_1" })]);+ await expect(nextTurnDelivery(input)).resolves.toMatchObject({ kind: "turn", delivery: first });});it("ignores duplicate notifications while waiting for the last sibling", async () => {const input = batchingInput(2);const first = completion("task_0");const last = completion("task_1");- input.commandInbox = createMockInbox(+ input.inbox = createMockInbox([first, first, last].map((value) => ({result: { done: false, value },source: "session",@@ -737,7 +746,7 @@ describe("buffered task completion batching", () => {taskDeliveryId: `task_1:ready:${status}`,payloads: [{ message: status, task: { views: [view] } }],};- input.bufferedDeliveries.push(first, terminal);+ for (const delivery of [first, terminal]) input.queue.enqueueDelivery(delivery);vi.mocked(routeDeliverToChildren).mockImplementation(async ({ delivery, sessionState, serializedContext }) => {const snapshot = sessionState.snapshot!;@@ -758,22 +767,25 @@ describe("buffered task completion batching", () => {};},);- await expect(nextTurnDelivery(input)).resolves.toEqual({ kind: "turn", delivery: terminal });- expect(input.bufferedDeliveries).toEqual([first]);- await expect(nextTurnDelivery(input)).resolves.toEqual({ kind: "turn", delivery: first });+ await expect(nextTurnDelivery(input)).resolves.toMatchObject({+ kind: "turn",+ delivery: terminal,+ });+ expect(input.queue.pendingCount).toBe(1);+ await expect(nextTurnDelivery(input)).resolves.toMatchObject({+ kind: "turn",+ delivery: first,+ });},);it("services ready authorization before a buffered completion batch", async () => {const input = batchingInput();- const bufferedDeliveries = [completion("task_0"), completion("task_1")];- const next = await nextTurnDelivery({- ...input,- bufferedDeliveries,- commandInbox: createMockInbox([authorizationRead()], true),- });- expect(next.kind).toBe("authorization");- expect(bufferedDeliveries).toHaveLength(2);+ const queue = queueOf(completion("task_0"), completion("task_1"));+ queue.enqueueAuthorization(authorizationCallbackPayload.payloads);+ const next = await nextTurnDelivery({ ...input, queue, inbox: createMockInbox([]) });+ expect(next.kind).toBe("authorization-resume");+ expect(queue.pendingCount).toBe(2);expect(routeDeliverToChildren).not.toHaveBeenCalled();});});diff --git a/packages/eve/src/execution/session/next-input.ts b/packages/eve/src/execution/session/next-input.tsnew file mode 100644index 000000000..a804990ed--- /dev/null+++ b/packages/eve/src/execution/session/next-input.ts@@ -0,0 +1,84 @@+import type { DeliverPayload } from "#channel/types.js";+import { routeSelectedDelivery } from "#execution/session/route-selected-delivery.js";+import type {+ SessionControl,+ SessionInputQueue,+ TurnSelection,+} from "#execution/session/input-queue.js";+import type { SessionInboxReader } from "#execution/session-inbox/inbox.js";+import {+ admitSessionInboxPayload,+ applySessionCancellation,+} from "#execution/session/admission.js";+import type { SessionStateCursor } from "#execution/session/state-cursor.js";+import type { WorkflowToolRunMessage } from "#execution/tools/workflow/messages.js";+import { getSessionTaskCohorts } from "#tasks/session-task-cohorts.js";++export type NextTurnInstruction =+ | { readonly kind: "workflow"; readonly message: WorkflowToolRunMessage }+ | { readonly kind: "authorization-resume"; readonly payloads: readonly DeliverPayload[] }+ | { readonly kind: SessionControl }+ | { readonly kind: "closed" }+ | { readonly kind: "cancel-turn" }+ | TurnSelection;++/**+ * Waits for the next input the parked owner must act on. While an+ * authorization challenge is open, its callbacks collect in the queue and+ * resume the challenge once every expected attempt has reported; ordinary+ * deliveries keep starting turns in the meantime. Fully routed descendant+ * deliveries leave nothing for the parent, so the wait continues.+ */+export async function nextTurnDelivery(input: {+ readonly inbox: SessionInboxReader;+ readonly cursor: SessionStateCursor;+ readonly deferDeliveries?: boolean;+ readonly expectedAttemptIds?: ReadonlySet<string>;+ readonly queue: SessionInputQueue;+}): Promise<NextTurnInstruction> {+ const { inbox, cursor, queue } = input;+ // A delivery admitted while the owner was fully idle (nothing queued, nothing+ // pumped) is the only kind that may move the session to another deployment.+ let freshSequence: number | undefined;+ while (true) {+ const selected = queue.takeNext(+ getSessionTaskCohorts(cursor.sessionState.snapshot.session.state),+ {+ deferDeliveries: input.deferDeliveries,+ expectedAttemptIds: input.expectedAttemptIds,+ freshSequence: inbox.hasPending() ? undefined : freshSequence,+ },+ );+ if (selected?.kind === "control") return { kind: selected.control };+ if (selected?.kind === "authorization-resume") return selected;+ if (selected?.kind === "turn") {+ const routed = await routeSelectedDelivery(selected, cursor);+ if (routed.kind === "cancel-turn") return routed;+ if (routed.kind === "consumed") continue;+ return routed;+ }++ // A delivery may already be in the pump queue by the time the owner exits+ // its committed waiting step. It is still an idle arrival when no earlier+ // input was admitted; the post-read `hasPending()` check below rejects a+ // burst with later buffered input.+ const wasIdle = queue.pendingCount === 0;+ const payload = await inbox.next();+ if (payload === undefined) return { kind: "closed" };++ const admitted = await admitSessionInboxPayload(payload, input);+ freshSequence =+ wasIdle && admitted.kind === "delivery" ? admitted.admission.sequence : undefined;+ switch (admitted.kind) {+ case "workflow":+ return { kind: "workflow", message: admitted.message };+ case "cancel":+ await applySessionCancellation(admitted.command, input);+ break;+ case "delivery":+ case "consumed":+ case "runtime-action-result":+ break;+ }+ }+}diff --git a/packages/eve/src/execution/pending-turn-state.ts b/packages/eve/src/execution/session/pending-turn-state.tssimilarity index 90%rename from packages/eve/src/execution/pending-turn-state.tsrename to packages/eve/src/execution/session/pending-turn-state.tsindex 9009c175e..44fe3ca66 100644--- a/packages/eve/src/execution/pending-turn-state.ts+++ b/packages/eve/src/execution/session/pending-turn-state.ts@@ -6,7 +6,6 @@ import type { HarnessSession } from "#harness/types.js";/** Derives the workflow fields used to select the next action at the park boundary. */export function derivePendingState(session: HarnessSession): {readonly authorizationAttemptIds?: readonly string[];- readonly authorizationNames?: readonly string[];readonly hasPendingAuthorization: boolean;readonly hasPendingInputBatch: boolean;readonly pendingCoordinationCallIds?: readonly string[];@@ -17,7 +16,6 @@ export function derivePendingState(session: HarnessSession): {authorizationAttemptIds: pendingAuth?.challenges.flatMap((challenge) =>challenge.attemptId === undefined ? [] : [challenge.attemptId],),- authorizationNames: pendingAuth?.challenges.map((challenge) => challenge.name),hasPendingAuthorization: pendingAuth !== undefined,hasPendingInputBatch: hasPendingInputBatch(session.state),};diff --git a/packages/eve/src/execution/session/program.ts b/packages/eve/src/execution/session/program.tsnew file mode 100644index 000000000..9a7c46252--- /dev/null+++ b/packages/eve/src/execution/session/program.ts@@ -0,0 +1,328 @@+import type { DeliverHookPayload, SessionCapabilities, TurnCaller } from "#channel/types.js";+import type { AgentWorkflowRetentionDefinition } from "#shared/agent-definition.js";+import type { RunMode } from "#shared/run-mode.js";+import {+ bindTurnCallerContextStep,+ notifyCancelledTaskCallerStep,+ notifyTurnCallerStep,+ resolveInitialTurnCallerStep,+} from "#subagents/parent-notification.js";+import type { DurableSessionState } from "#execution/durable-session-store.js";+import { nextTurnDelivery, type NextTurnInstruction } from "#execution/session/next-input.js";+import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-step.js";+import { SessionInputQueue } from "#execution/session/input-queue.js";+import { SessionExecution } from "#execution/session/turn.js";+import { SessionStateCursor } from "#execution/session/state-cursor.js";+import type { TurnOutcome, TurnStepPayload } from "#execution/session/turn-step-types.js";+import { settleCancelledTurnStep } from "#execution/settle-cancelled-turn-step.js";+import { finalizeSession, type SessionTerminalOutcome } from "#execution/session/finalization.js";+import { type SessionInboxHandle } from "#execution/session-inbox/inbox.js";+import { createSessionTimeoutControl } from "#execution/session/timeout-control.js";+import { SessionHandoff, sessionAnchorToken } from "#execution/session/handoff.js";+import { signalSessionAnchorStep } from "#execution/session/handoff-steps.js";+import type { WorkflowEntryResult } from "#execution/session/entry-input.js";++/** The run's own failure never carries internals; the terminal event already logged them. */+function createSafeOuterWorkflowError(): Error {+ const error = new Error("Agent workflow failed. Inspect the private session trace for details.");+ error.name = "EveWorkflowFailure";+ return error;+}++/**+ * Who to tell when this owner exits. The original run anchors the public+ * stream itself; a successor signals the original run. A `self` anchor may+ * also name a `notify` step that runs with the final result, which lets an+ * importer settle whatever predecessor still holds the stream open.+ */+export type SessionAnchor =+ | {+ readonly kind: "self";+ readonly notify?: (result: WorkflowEntryResult) => Promise<void>;+ }+ | { readonly kind: "successor" };++export interface SessionBoot {+ readonly anchor: SessionAnchor;+ readonly caller: TurnCaller | undefined;+ readonly capabilities?: SessionCapabilities;+ readonly deploymentId: string;+ readonly initialInput: DeliverHookPayload | undefined;+ readonly mode: RunMode;+ readonly retention?: AgentWorkflowRetentionDefinition;+ readonly serializedContext: Record<string, unknown>;+ readonly sessionId: string;+ readonly sessionState: DurableSessionState;+ readonly sessionTimeoutDeadline?: Date;+ readonly sessionTimeoutMs: number | false;+ readonly sessionWritable: WritableStream<Uint8Array>;+}++type SessionLoopOutcome =+ | { readonly kind: "terminal"; readonly outcome: SessionTerminalOutcome }+ | { readonly kind: "transferred" };++/** Mutable facts the crash path needs that do not live in the state cursor. */+interface SessionProgress {+ /** Delegated caller whose awaited reply is still unsettled. */+ caller: TurnCaller | undefined;+ terminalEmitted: boolean;+ /** Last dispatched turn; a crash between turns is attributed to it. */+ turnId?: string;+}++/** Runs an already prepared owner against its session's existing stream. */+export async function runPreparedSession(+ boot: SessionBoot,+ inbox: SessionInboxHandle,+): Promise<WorkflowEntryResult> {+ const cursor = new SessionStateCursor({+ inbox,+ sessionWritable: boot.sessionWritable,+ serializedContext: boot.serializedContext,+ sessionState: boot.sessionState,+ });+ const progress: SessionProgress = { caller: boot.caller, terminalEmitted: false };+ const handoff = new SessionHandoff({+ checkpoint: {+ capabilities: boot.capabilities,+ mode: boot.mode,+ retention: boot.retention,+ sessionTimeoutMs: boot.sessionTimeoutMs,+ },+ deploymentId: boot.deploymentId,+ inbox,+ isInitialOwner: boot.anchor.kind === "self",+ sessionId: boot.sessionId,+ });+ let result: WorkflowEntryResult = { output: "", isError: true };+ try {+ let loop: SessionLoopOutcome;+ try {+ loop = await runSessionLoop(boot, { cursor, handoff, inbox, progress });+ } finally {+ await inbox.dispose();+ }+ if (loop.kind === "transferred") {+ if (boot.anchor.kind !== "self") return { output: "" };+ result = await handoff.awaitAnchoredResult();+ return result;+ }+ result = await finalizeSession(loop.outcome, {+ caller: progress.caller,+ cursor,+ mode: boot.mode,+ sessionWritable: boot.sessionWritable,+ });+ progress.terminalEmitted = true;+ return result;+ } catch (error) {+ if (!progress.terminalEmitted) {+ await finalizeSession(+ { error, kind: "failed", turnId: progress.turnId },+ { caller: progress.caller, cursor, mode: boot.mode, sessionWritable: boot.sessionWritable },+ );+ }+ throw createSafeOuterWorkflowError();+ } finally {+ await reportResultToAnchor(boot, result, handoff);+ }+}++/**+ * Terminal path for a boot that failed before the session loop could run.+ * The caller is re-resolved from context because no turn ever bound it.+ */+export async function failSession(input: {+ readonly error: unknown;+ readonly mode: RunMode;+ readonly serializedContext: Record<string, unknown>;+ readonly sessionId: string;+ readonly sessionState: DurableSessionState | undefined;+ readonly sessionWritable: WritableStream<Uint8Array>;+}): Promise<never> {+ let caller: TurnCaller | undefined;+ try {+ caller = await resolveInitialTurnCallerStep({ serializedContext: input.serializedContext });+ } catch {+ // Best effort: when resolution fails again there is no reachable caller to notify.+ }+ await finalizeSession(+ { error: input.error, kind: "failed" },+ {+ caller,+ cursor: {+ serializedContext: input.serializedContext,+ sessionState: input.sessionState,+ },+ mode: input.mode,+ sessionWritable: input.sessionWritable,+ },+ );+ throw createSafeOuterWorkflowError();+}++async function reportResultToAnchor(+ boot: SessionBoot,+ result: WorkflowEntryResult,+ handoff: SessionHandoff,+): Promise<void> {+ switch (boot.anchor.kind) {+ case "self":+ await handoff.disposeAnchor();+ await boot.anchor.notify?.(result);+ return;+ case "successor":+ await signalSessionAnchorStep({ result, token: sessionAnchorToken(boot.sessionId) });+ return;+ }+}++async function runSessionLoop(+ boot: SessionBoot,+ deps: {+ readonly cursor: SessionStateCursor;+ readonly handoff: SessionHandoff;+ readonly inbox: SessionInboxHandle;+ readonly progress: SessionProgress;+ },+): Promise<SessionLoopOutcome> {+ const { cursor, handoff, inbox, progress } = deps;+ const queue = new SessionInputQueue();+ const execution = new SessionExecution({+ capabilities: boot.capabilities,+ cursor,+ inbox,+ mode: boot.mode,+ queue,+ sessionId: boot.sessionId,+ });+ const sessionTimeout =+ boot.sessionTimeoutDeadline === undefined+ ? undefined+ : createSessionTimeoutControl({+ deadline: boot.sessionTimeoutDeadline,+ sessionId: boot.sessionId,+ });++ const nextParkedActivity = async (+ expectedAttemptIds: ReadonlySet<string>,+ ): Promise<Exclude<NextTurnInstruction, { kind: "workflow" }>> => {+ while (true) {+ const next = await nextTurnDelivery({+ cursor,+ deferDeliveries: boot.mode === "task" && expectedAttemptIds.size > 0,+ expectedAttemptIds,+ inbox,+ queue,+ });+ if (next.kind !== "workflow") return next;+ await execution.handleWorkflowMessage(next.message);+ }+ };++ let turnIndex = 0;+ const runTurn = async (payload: TurnStepPayload | undefined): Promise<TurnOutcome> => {+ const caller = progress.caller;+ if (caller?.taskId !== undefined) queue.rememberTask(caller.taskId);+ if (caller !== undefined) {+ await cursor.apply({+ serializedContext: await bindTurnCallerContextStep({+ caller,+ serializedContext: cursor.serializedContext,+ }),+ });+ }+ progress.turnId = `turn_${String(turnIndex++)}`;+ return await execution.runTurn(payload);+ };+ const settleCancelledTurn = async () => {+ const settled = await settleCancelledTurnStep({+ sessionWritable: boot.sessionWritable,+ serializedContext: cursor.serializedContext,+ sessionState: cursor.sessionState,+ });+ await cursor.apply(settled);+ progress.caller = undefined;+ return settled;+ };++ try {+ const [actionResult, timerResult] = await Promise.allSettled([+ runTurn(boot.initialInput === undefined ? undefined : { delivery: boot.initialInput }),+ sessionTimeout?.start(),+ ]);+ if (timerResult.status === "rejected") throw timerResult.reason;+ if (actionResult.status === "rejected") throw actionResult.reason;+ let action: TurnOutcome = actionResult.value;++ while (true) {+ if (action.kind === "done") {+ return { kind: "terminal", outcome: { action, kind: "done" } };+ }++ if (action.cancelled === true) {+ const cancelledCaller = { caller: progress.caller, sessionId: boot.sessionId };+ const settled = await settleCancelledTurn();+ await notifyCancelledTaskCallerStep(+ settled.usage === undefined+ ? cancelledCaller+ : { ...cancelledCaller, usage: settled.usage },+ );+ } else if (action.settled !== undefined) {+ if (progress.caller !== undefined) {+ await notifyTurnCallerStep({+ caller: progress.caller,+ lifecycle: "parked",+ sessionId: boot.sessionId,+ settled: action.settled,+ });+ }+ progress.caller = undefined;+ }++ // An open authorization challenge must not wedge the session:+ // ordinary deliveries keep starting normal turns while the challenge+ // waits for its callback. The pending challenge survives intervening+ // turns because every park re-derives `authorizationAttemptIds` from+ // durable session state.+ const next = await nextParkedActivity(new Set(action.authorizationAttemptIds ?? []));++ switch (next.kind) {+ case "authorization-resume":+ action = await runTurn({ delivery: { kind: "deliver", payloads: next.payloads } });+ continue;+ case "expired":+ case "reset":+ case "closed":+ return { kind: "terminal", outcome: { kind: "expired" } };+ case "clear":+ case "compact":+ action = await runTurn({ control: next.kind });+ continue;+ case "cancel-turn":+ await cancelDescendantTurnsStep({+ serializedContext: cursor.serializedContext,+ sessionState: cursor.sessionState,+ });+ await settleCancelledTurn();+ // Re-enter with `settled` cleared: the parked answer was already+ // delivered to its caller before this wait.+ action = { ...action, settled: undefined };+ continue;+ case "turn": {+ const transfer = await handoff.tryTransfer(next, {+ serializedContext: cursor.serializedContext,+ sessionState: cursor.sessionState,+ });+ if (transfer.kind === "transferred") return { kind: "transferred" };+ if (next.delivery.caller !== undefined) progress.caller = next.delivery.caller;+ action = await runTurn({ delivery: next.delivery });+ continue;+ }+ }+ }+ } finally {+ await sessionTimeout?.dispose();+ }+}diff --git a/packages/eve/src/execution/session/route-selected-delivery.ts b/packages/eve/src/execution/session/route-selected-delivery.tsnew file mode 100644index 000000000..1a7c97273--- /dev/null+++ b/packages/eve/src/execution/session/route-selected-delivery.ts@@ -0,0 +1,25 @@+import { routeDeliverToChildren } from "#execution/route-child-delivery.js";+import type { TurnSelection } from "#execution/session/input-queue.js";+import type { SessionStateCursor } from "#execution/session/state-cursor.js";++export type RoutedTurnSelection =+ | { readonly kind: "cancel-turn" }+ | { readonly kind: "consumed" }+ | TurnSelection;++/** Routes one selected delivery exactly once, independent of active/parked mode. */+export async function routeSelectedDelivery(+ selection: TurnSelection,+ cursor: SessionStateCursor,+): Promise<RoutedTurnSelection> {+ const routed = await routeDeliverToChildren({+ delivery: selection.delivery,+ sessionWritable: cursor.sessionWritable,+ serializedContext: cursor.serializedContext,+ sessionState: cursor.sessionState,+ });+ await cursor.apply(routed);+ if (routed.kind === "cancel-turn") return { kind: "cancel-turn" };+ if (routed.remainder === undefined) return { kind: "consumed" };+ return { ...selection, delivery: routed.remainder };+}diff --git a/packages/eve/src/execution/session/state-compatibility.test.ts b/packages/eve/src/execution/session/state-compatibility.test.tsnew file mode 100644index 000000000..b240a0997--- /dev/null+++ b/packages/eve/src/execution/session/state-compatibility.test.ts@@ -0,0 +1,168 @@+import { describe, expect, it } from "vitest";+import { createTestSessionState } from "#internal/testing/session-state.js";+import { isSessionStateIdleForHandoff } from "#execution/session/handoff-steps.js";+import {+ cacheTerminalTaskView,+ getSessionTaskIndex,+ recordSessionTask,+} from "#tasks/session-index.js";+import { parseActivityWorkIdentityV1 } from "#protocol/activity.js";+import type { HarnessSession } from "#harness/types.js";++const metadata = { kind: "tool", name: "research" };+const activity = {+ id: "work",+ kind: "task" as const,+ rootSessionId: "root",+ rootTurnId: "turn",+ futureActivity: { label: "Alice's research" },+};+const task = {+ taskId: "task",+ taskRunId: "run",+ taskInboxToken: "inbox",+ createdByTurnId: "turn",+ metadata,+ activityWorkIdentity: activity,+ futureTask: { revision: 2 },+ executor: { kind: "workflow", data: {}, futureExecutor: true },+ terminalView: {+ taskId: "task",+ metadata,+ status: "completed" as const,+ lastOutput: { type: "result" as const, data: "done", futureOutput: true },+ usage: {+ inputTokens: 1,+ outputTokens: 2,+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ futureUsage: true,+ },+ executor: {+ futureExecutor: true,+ binding: { kind: "workflow", data: {}, futureBinding: true },+ },+ futureView: true,+ },+};+function checkpoint(state: Record<string, unknown>) {+ const value = createTestSessionState();+ return { ...value, snapshot: { session: { ...value.snapshot.session, state } } };+}+function session(state: Record<string, unknown>): HarnessSession {+ return {+ agent: { modelReference: { id: "model" }, system: "", tools: [] },+ compaction: { recentWindowSize: 4, threshold: 1_000_000 },+ continuationToken: "token",+ history: [],+ sessionId: "session",+ state,+ };+}+const restored = <T>(value: T): T => JSON.parse(JSON.stringify(value));++describe("additive durable state", () => {+ it("preserves task extensions through parsing, replayed creation and terminal updates", () => {+ const state = {+ "eve.tasks": { version: 2, tasks: [task], futureIndex: true },+ authored: { opaque: true },+ };+ expect(getSessionTaskIndex(restored(state))).toEqual([+ { ...task, dispatchContext: { legacy: true } },+ ]);+ expect(parseActivityWorkIdentityV1(activity)).toEqual(activity);+ const updated = recordSessionTask(session(restored(state)), {+ taskId: "task",+ taskRunId: "new-run",+ taskInboxToken: "inbox",+ createdByTurnId: "turn",+ dispatchContext: { auth: { current: null, initiator: null } },+ metadata,+ activityWorkIdentity: { id: "work", kind: "task", rootSessionId: "root", rootTurnId: "turn" },+ executor: { kind: "workflow", data: {} },+ });+ const saved = cacheTerminalTaskView(updated.state, {+ taskId: "task",+ metadata,+ status: "completed",+ lastOutput: { type: "result", data: "updated" },+ usage: { inputTokens: 3, outputTokens: 4, cacheReadTokens: 0, cacheWriteTokens: 0 },+ executor: { binding: { kind: "workflow", data: {} } },+ });+ expect(restored(saved)).toMatchObject({+ authored: { opaque: true },+ "eve.tasks": {+ futureIndex: true,+ tasks: [+ {+ futureTask: { revision: 2 },+ taskRunId: "new-run",+ activityWorkIdentity: activity,+ executor: { futureExecutor: true },+ terminalView: {+ futureView: true,+ lastOutput: { data: "updated", futureOutput: true },+ usage: { inputTokens: 3, futureUsage: true },+ executor: { futureExecutor: true, binding: { futureBinding: true } },+ },+ },+ ],+ },+ });+ expect(isSessionStateIdleForHandoff(checkpoint(restored(saved!)))).toBe(true);+ const cancelled = cacheTerminalTaskView(saved, {+ taskId: "task",+ metadata,+ status: "cancelled",+ });+ expect(getSessionTaskIndex(restored(cancelled))[0]?.terminalView).toMatchObject({+ futureView: true,+ status: "cancelled",+ });+ expect(getSessionTaskIndex(restored(cancelled))[0]?.terminalView?.lastOutput).toBeUndefined();+ });+});++describe("handoff state inspection", () => {+ it("accepts additive framework metadata and opaque authored state", () => {+ expect(+ isSessionStateIdleForHandoff(+ checkpoint({+ "eve.tasks": { version: 2, tasks: [task], futureIndex: true },+ "eve.agent.handles": { handles: [], futureStore: true },+ authored: { version: "anything", values: [null, false] },+ }),+ ),+ ).toBe(true);+ });+ it("parses settled entries before checking their terminal status", () => {+ const incompatible = { ...task, taskInboxToken: 42 };+ expect(() =>+ isSessionStateIdleForHandoff(+ checkpoint({ "eve.tasks": { version: 2, tasks: [incompatible] } }),+ ),+ ).toThrow("Corrupt task index");+ });+ it("does not skip task parsing when another registry is busy", () => {+ expect(() =>+ isSessionStateIdleForHandoff(+ checkpoint({+ "eve.runtime.pendingAuthorization": {},+ "eve.tasks": { version: 2, tasks: [{ ...task, taskRunId: null }] },+ }),+ ),+ ).toThrow("Corrupt task index");+ });+ it.each([+ ["eve.runtime.pendingAuthorization", false],+ ["eve.runtime.pendingInputBatch", {}],+ ["eve.runtime.pendingInputBatches", [null]],+ ["eve.runtime.pendingCoordinationBatch", {}],+ ["eve.runtime.workflowToolRuns", {}],+ ["eve.runtime.deferredStepInput", {}],+ ["eve.harness.pendingWorkflowInterrupt", {}],+ ["eve.runtime.proxyInputRequests", { malformed: null }],+ ])("refuses nonempty or unreadable pending work in %s", (key, value) => {+ expect(isSessionStateIdleForHandoff(checkpoint({ [key]: value }))).toBe(false);+ });+});diff --git a/packages/eve/src/execution/session/state-cursor.test.ts b/packages/eve/src/execution/session/state-cursor.test.tsnew file mode 100644index 000000000..1c5ecc850--- /dev/null+++ b/packages/eve/src/execution/session/state-cursor.test.ts@@ -0,0 +1,65 @@+import { createTestSessionState } from "#internal/testing/session-state.js";+import { describe, expect, it, vi } from "vitest";++import { ContinuationHookTokensKey } from "#context/keys.js";+import type { DurableSessionState } from "#execution/durable-session-store.js";+import { SessionStateCursor } from "#execution/session/state-cursor.js";++const stableToken = "eve:session:session-1:inbox";++describe("SessionStateCursor", () => {+ it("claims every new continuation address recorded during a step", async () => {+ const claimSessionHooks = vi.fn(async () => {});+ const inbox = {+ claimSessionHooks,+ };+ const initialState = state("channel:initial");+ const cursor = new SessionStateCursor({+ inbox,+ sessionWritable: new WritableStream<Uint8Array>(),+ serializedContext: {+ [ContinuationHookTokensKey.name]: ["channel:initial"],+ },+ sessionState: initialState,+ });+ const nextState = state("channel:third");++ await cursor.apply({+ serializedContext: {+ [ContinuationHookTokensKey.name]: ["channel:initial", "channel:second", "channel:third"],+ },+ sessionState: nextState,+ });++ expect(claimSessionHooks.mock.calls).toEqual([+ [[stableToken, "channel:initial", "channel:second", "channel:third"]],+ ]);+ expect(cursor.sessionState).toBe(nextState);+ });++ it("claims the current continuation when no address history was recorded", async () => {+ const claimSessionHooks = vi.fn(async () => {});+ const cursor = new SessionStateCursor({+ inbox: {+ claimSessionHooks,+ },+ sessionWritable: new WritableStream<Uint8Array>(),+ serializedContext: {},+ sessionState: state(""),+ });++ await cursor.apply({ sessionState: state("channel:current") });++ expect(claimSessionHooks).toHaveBeenCalledWith([stableToken, "channel:current"]);+ });+});++function state(continuationToken: string): DurableSessionState {+ return createTestSessionState({+ continuationToken,+ emissionState: { sequence: 0, sessionStarted: true, stepIndex: 0, turnId: "turn_0" },+ hasProxyInputRequests: false,+ sessionId: "session-1",+ version: 1,+ });+}diff --git a/packages/eve/src/execution/session/state-cursor.ts b/packages/eve/src/execution/session/state-cursor.tsnew file mode 100644index 000000000..ada9d8dfd--- /dev/null+++ b/packages/eve/src/execution/session/state-cursor.ts@@ -0,0 +1,63 @@+import type { DurableSessionState } from "#execution/durable-session-store.js";+import { sessionHookTokens } from "#execution/session/hook-tokens.js";+import type { SessionInboxOwnership } from "#execution/session-inbox/inbox.js";+import type { TurnStepInput, TurnStepPayload } from "#execution/session/turn-step-types.js";++/** A durable-state transition; absent fields keep the cursor's current value. */+export interface SessionStateTransition {+ readonly serializedContext?: Record<string, unknown>;+ readonly sessionState?: DurableSessionState;+}++/**+ * The one mutable serialized-context / session-state pair owned by the+ * workflow executing a session. Steps return transitions; the cursor adopts+ * them and claims any continuation address a step introduced, so every hook+ * the session answers to is registered before the next step runs.+ */+export class SessionStateCursor {+ readonly sessionWritable: WritableStream<Uint8Array>;++ private readonly inbox: Pick<SessionInboxOwnership, "claimSessionHooks">;+ private currentSerializedContext: Record<string, unknown>;+ private currentSessionState: DurableSessionState;++ constructor(input: {+ readonly inbox: Pick<SessionInboxOwnership, "claimSessionHooks">;+ readonly sessionWritable: WritableStream<Uint8Array>;+ readonly serializedContext: Record<string, unknown>;+ readonly sessionState: DurableSessionState;+ }) {+ this.inbox = input.inbox;+ this.sessionWritable = input.sessionWritable;+ this.currentSerializedContext = input.serializedContext;+ this.currentSessionState = input.sessionState;+ }++ get serializedContext(): Record<string, unknown> {+ return this.currentSerializedContext;+ }++ get sessionState(): DurableSessionState {+ return this.currentSessionState;+ }++ /** Applies a transition after claiming every continuation address it introduced. */+ async apply(transition: SessionStateTransition): Promise<void> {+ const serializedContext = transition.serializedContext ?? this.currentSerializedContext;+ const sessionState = transition.sessionState ?? this.currentSessionState;+ await this.inbox.claimSessionHooks(sessionHookTokens({ serializedContext, sessionState }));+ this.currentSerializedContext = serializedContext;+ this.currentSessionState = sessionState;+ }++ createStepInput(input: TurnStepPayload | undefined, abortSignal?: AbortSignal): TurnStepInput {+ return {+ abortSignal,+ input,+ sessionWritable: this.sessionWritable,+ serializedContext: this.currentSerializedContext,+ sessionState: this.currentSessionState,+ };+ }+}diff --git a/packages/eve/src/execution/session-timeout-control.test.ts b/packages/eve/src/execution/session/timeout-control.test.tssimilarity index 82%rename from packages/eve/src/execution/session-timeout-control.test.tsrename to packages/eve/src/execution/session/timeout-control.test.tsindex 74f250e36..e300866be 100644--- a/packages/eve/src/execution/session-timeout-control.test.ts+++ b/packages/eve/src/execution/session/timeout-control.test.ts@@ -1,16 +1,20 @@import { afterEach, describe, expect, it, vi } from "vitest";-import { createSessionTimeoutControl } from "#execution/session-timeout-control.js";+import { createSessionTimeoutControl } from "#execution/session/timeout-control.js";import {cancelSessionTimeoutStep,startSessionTimeoutStep,-} from "#execution/session-timeout-steps.js";+} from "#execution/session/timeout-steps.js";-vi.mock("./session-timeout-steps.js", () => ({+vi.mock("./timeout-steps.js", () => ({cancelSessionTimeoutStep: vi.fn(),startSessionTimeoutStep: vi.fn(),}));+vi.mock("#compiled/@workflow/core/index.js", () => ({+ getWorkflowMetadata: () => ({ workflowRunId: "owner-1" }),+}));+afterEach(() => {vi.clearAllMocks();});@@ -22,7 +26,7 @@ describe("createSessionTimeoutControl", () => {const control = createSessionTimeoutControl({deadline,- token: "eve:session:wrun_1:inbox",+ sessionId: "wrun_1",});await control.start();await control.start();@@ -30,6 +34,7 @@ describe("createSessionTimeoutControl", () => {expect(startSessionTimeoutStep).toHaveBeenCalledOnce();expect(startSessionTimeoutStep).toHaveBeenCalledWith({deadline,+ ownerRunId: "owner-1",token: "eve:session:wrun_1:inbox",});});@@ -38,7 +43,7 @@ describe("createSessionTimeoutControl", () => {vi.mocked(startSessionTimeoutStep).mockResolvedValue({ runId: "timer-run" });const control = createSessionTimeoutControl({deadline: new Date("2026-02-01T00:00:00.000Z"),- token: "eve:session:wrun_1:inbox",+ sessionId: "wrun_1",});await control.start();@@ -55,7 +60,7 @@ describe("createSessionTimeoutControl", () => {const control = createSessionTimeoutControl({deadline: new Date("2026-02-01T00:00:00.000Z"),- token: "eve:session:wrun_1:inbox",+ sessionId: "wrun_1",});await expect(control.start()).rejects.toBe(failure);diff --git a/packages/eve/src/execution/session-timeout-control.ts b/packages/eve/src/execution/session/timeout-control.tssimilarity index 64%rename from packages/eve/src/execution/session-timeout-control.tsrename to packages/eve/src/execution/session/timeout-control.tsindex 54445de91..5bb2956de 100644--- a/packages/eve/src/execution/session-timeout-control.ts+++ b/packages/eve/src/execution/session/timeout-control.ts@@ -1,7 +1,10 @@+import { getWorkflowMetadata } from "#compiled/@workflow/core/index.js";+import {cancelSessionTimeoutStep,startSessionTimeoutStep,-} from "#execution/session-timeout-steps.js";+} from "#execution/session/timeout-steps.js";+import { sessionCommandHookToken } from "#execution/session-inbox/address.js";/** Workflow-body handle that targets a durable deadline at the stable command inbox. */export interface SessionTimeoutControl {@@ -12,7 +15,7 @@ export interface SessionTimeoutControl {/** Creates a timer controller for one stable session command inbox. */export function createSessionTimeoutControl(input: {readonly deadline: Date;- readonly token: string;+ readonly sessionId: string;}): SessionTimeoutControl {let active: { readonly runId: string } | undefined;@@ -26,7 +29,11 @@ export function createSessionTimeoutControl(input: {async start(): Promise<void> {if (active !== undefined) return;- active = await startSessionTimeoutStep(input);+ active = await startSessionTimeoutStep({+ deadline: input.deadline,+ ownerRunId: getWorkflowMetadata().workflowRunId,+ token: sessionCommandHookToken(input.sessionId),+ });},};}diff --git a/packages/eve/src/execution/session-timeout-steps.test.ts b/packages/eve/src/execution/session/timeout-steps.test.tssimilarity index 79%rename from packages/eve/src/execution/session-timeout-steps.test.tsrename to packages/eve/src/execution/session/timeout-steps.test.tsindex 356fe9a85..c45575eab 100644--- a/packages/eve/src/execution/session-timeout-steps.test.ts+++ b/packages/eve/src/execution/session/timeout-steps.test.ts@@ -4,36 +4,34 @@ import {cancelSessionTimeoutStep,signalSessionTimeoutStep,startSessionTimeoutStep,-} from "#execution/session-timeout-steps.js";+} from "#execution/session/timeout-steps.js";import { sessionTimeoutWorkflowReference } from "#execution/workflow-runtime.js";const cancelRunMock = vi.fn();const getWorldMock = vi.fn();-const getHookByTokenMock = vi.fn();const resumeHookMock = vi.fn();const startMock = vi.fn();vi.mock("#compiled/@workflow/core/runtime.js", () => ({cancelRun: (...args: unknown[]) => cancelRunMock(...args),- getHookByToken: (...args: unknown[]) => getHookByTokenMock(...args),+ getHookByToken: (...args: unknown[]) => resumeHookMock(...args),getWorld: (...args: unknown[]) => getWorldMock(...args),resumeHook: (...args: unknown[]) => resumeHookMock(...args),start: (...args: unknown[]) => startMock(...args),}));const TIMEOUT_HOOK = {- metadata: { sessionInboxWireVersion: 1 },+ metadata: { sessionId: "session-1" },runId: "session-1",token: "session-1:session-timeout",};beforeEach(() => {- getHookByTokenMock.mockResolvedValue(TIMEOUT_HOOK);+ getWorldMock.mockResolvedValue({ getDeploymentId: async () => "dpl_current" });});afterEach(() => {cancelRunMock.mockReset();- getHookByTokenMock.mockReset();getWorldMock.mockReset();resumeHookMock.mockReset();startMock.mockReset();@@ -46,21 +44,24 @@ describe("session timeout steps", () => {startMock.mockResolvedValue({ runId: "timer-run" });const input = {deadline: new Date("2026-02-01T00:00:00.000Z"),+ ownerRunId: "session-1",token: "session-1:session-timeout",};await expect(startSessionTimeoutStep(input)).resolves.toEqual({ runId: "timer-run" });- expect(startMock).toHaveBeenCalledWith(sessionTimeoutWorkflowReference, [input]);+ expect(startMock).toHaveBeenCalledWith(sessionTimeoutWorkflowReference, [input], {+ deploymentId: "dpl_current",+ });});it("signals the owning session hook", async () => {resumeHookMock.mockResolvedValue({ runId: "session-1" });- await signalSessionTimeoutStep({ token: "session-1:session-timeout" });+ await signalSessionTimeoutStep({ ownerRunId: "session-1", token: "session-1:session-timeout" });- expect(resumeHookMock).toHaveBeenCalledWith(TIMEOUT_HOOK, {+ expect(resumeHookMock).toHaveBeenCalledWith(`eve:inbox:v1:${TIMEOUT_HOOK.token}`, {kind: "session-timeout",- version: 1,+ ownerRunId: "session-1",});});@@ -69,7 +70,7 @@ describe("session timeout steps", () => {resumeHookMock.mockRejectedValue(new HookNotFoundError("session-1:session-timeout"));await expect(- signalSessionTimeoutStep({ token: "session-1:session-timeout" }),+ signalSessionTimeoutStep({ ownerRunId: "session-1", token: "session-1:session-timeout" }),).resolves.toBeUndefined();});@@ -100,9 +101,9 @@ describe("session timeout steps", () => {it("propagates unexpected timeout runtime failures", async () => {const signalFailure = new Error("resume failed");resumeHookMock.mockRejectedValue(signalFailure);- await expect(signalSessionTimeoutStep({ token: "session-1:session-timeout" })).rejects.toBe(- signalFailure,- );+ await expect(+ signalSessionTimeoutStep({ ownerRunId: "session-1", token: "session-1:session-timeout" }),+ ).rejects.toBe(signalFailure);const cancelFailure = new Error("cancel failed");getWorldMock.mockResolvedValue({});diff --git a/packages/eve/src/execution/session-timeout-steps.ts b/packages/eve/src/execution/session/timeout-steps.tssimilarity index 79%rename from packages/eve/src/execution/session-timeout-steps.tsrename to packages/eve/src/execution/session/timeout-steps.tsindex 3bcc951bb..8f003ce2a 100644--- a/packages/eve/src/execution/session-timeout-steps.ts+++ b/packages/eve/src/execution/session/timeout-steps.ts@@ -9,8 +9,8 @@ import {startWorkflowOnCurrentDeployment,sessionTimeoutWorkflowReference,} from "#execution/workflow-runtime.js";-import type { SessionTimeoutWorkflowInput } from "#execution/session-timeout-workflow.js";-import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";+import type { SessionTimeoutWorkflowInput } from "#execution/session/timeout-workflow.js";+import { resumeSessionInbox } from "#execution/session-inbox/resume.js";import { cancelRun, getWorld } from "#internal/workflow/runtime.js";import { walkCauseChain } from "#shared/errors.js";@@ -24,12 +24,18 @@ export async function startSessionTimeoutStep(return { runId: run.runId };}-/** Resumes the owning driver when its durable timer elapses. */-export async function signalSessionTimeoutStep(input: { readonly token: string }): Promise<void> {+/** Resumes the owning session when its durable timer elapses. */+export async function signalSessionTimeoutStep(input: {+ readonly ownerRunId: string;+ readonly token: string;+}): Promise<void> {"use step";try {- await resumeSessionInbox(input.token, { kind: "session-timeout" });+ await resumeSessionInbox(input.token, {+ kind: "session-timeout",+ ownerRunId: input.ownerRunId,+ });} catch (error) {if (!isInactiveTimeoutTarget(error)) {throw error;diff --git a/packages/eve/src/execution/session-timeout-workflow.test.ts b/packages/eve/src/execution/session/timeout-workflow.test.tssimilarity index 74%rename from packages/eve/src/execution/session-timeout-workflow.test.tsrename to packages/eve/src/execution/session/timeout-workflow.test.tsindex 73b569f34..966c52b8f 100644--- a/packages/eve/src/execution/session-timeout-workflow.test.ts+++ b/packages/eve/src/execution/session/timeout-workflow.test.ts@@ -1,14 +1,14 @@import { afterEach, describe, expect, it, vi } from "vitest";import { sleep } from "#compiled/@workflow/core/index.js";-import { signalSessionTimeoutStep } from "#execution/session-timeout-steps.js";-import { sessionTimeoutWorkflow } from "#execution/session-timeout-workflow.js";+import { signalSessionTimeoutStep } from "#execution/session/timeout-steps.js";+import { sessionTimeoutWorkflow } from "#execution/session/timeout-workflow.js";vi.mock("#compiled/@workflow/core/index.js", () => ({sleep: vi.fn(),}));-vi.mock("./session-timeout-steps.js", () => ({+vi.mock("./timeout-steps.js", () => ({signalSessionTimeoutStep: vi.fn(),}));@@ -27,7 +27,11 @@ describe("sessionTimeoutWorkflow", () => {);const deadline = new Date("2026-02-01T00:00:00.000Z");- const timer = sessionTimeoutWorkflow({ deadline, token: "session-1:session-timeout" });+ const timer = sessionTimeoutWorkflow({+ deadline,+ ownerRunId: "session-1",+ token: "session-1:session-timeout",+ });await vi.waitFor(() => {expect(sleep).toHaveBeenCalledWith(deadline);});@@ -37,6 +41,7 @@ describe("sessionTimeoutWorkflow", () => {await timer;expect(signalSessionTimeoutStep).toHaveBeenCalledWith({+ ownerRunId: "session-1",token: "session-1:session-timeout",});});diff --git a/packages/eve/src/execution/session-timeout-workflow.ts b/packages/eve/src/execution/session/timeout-workflow.tssimilarity index 52%rename from packages/eve/src/execution/session-timeout-workflow.tsrename to packages/eve/src/execution/session/timeout-workflow.tsindex 7bfef4b44..f3f793587 100644--- a/packages/eve/src/execution/session-timeout-workflow.ts+++ b/packages/eve/src/execution/session/timeout-workflow.ts@@ -1,16 +1,18 @@import { sleep } from "#compiled/@workflow/core/index.js";-import { signalSessionTimeoutStep } from "#execution/session-timeout-steps.js";+import { signalSessionTimeoutStep } from "#execution/session/timeout-steps.js";export interface SessionTimeoutWorkflowInput {readonly deadline: Date;+ /** Owner run that armed the timer. */+ readonly ownerRunId: string;readonly token: string;}-/** Sleeps until the session deadline, then signals its driver. */+/** Sleeps until the session deadline, then signals its current owner. */export async function sessionTimeoutWorkflow(input: SessionTimeoutWorkflowInput): Promise<void> {"use workflow";await sleep(input.deadline);- await signalSessionTimeoutStep({ token: input.token });+ await signalSessionTimeoutStep({ ownerRunId: input.ownerRunId, token: input.token });}diff --git a/packages/eve/src/execution/session/timeout.ts b/packages/eve/src/execution/session/timeout.tsnew file mode 100644index 000000000..f16d06f13--- /dev/null+++ b/packages/eve/src/execution/session/timeout.ts@@ -0,0 +1,9 @@+/** Default lifetime from creation or the latest successful ownership handoff. */+export const DEFAULT_SESSION_TIMEOUT_MS = 30 * 24 * 60 * 60 * 1_000;++export function sessionTimeoutDeadline(+ timeoutMs: number | false,+ startedAtMs: number,+): Date | undefined {+ return timeoutMs === false ? undefined : new Date(startedAtMs + timeoutMs);+}diff --git a/packages/eve/src/execution/session/turn-step-result.ts b/packages/eve/src/execution/session/turn-step-result.tsnew file mode 100644index 000000000..dedcfbb84--- /dev/null+++ b/packages/eve/src/execution/session/turn-step-result.ts@@ -0,0 +1,91 @@+import { createDurableSessionState } from "#execution/durable-session-store.js";+import { derivePendingState } from "#execution/session/pending-turn-state.js";+import type { DurableStepResult } from "#execution/session/turn-step-types.js";+import { hasPendingInputBatch } from "#harness/input-requests.js";+import { getTurnUsageState, takeSessionUsageDelta, toUsage } from "#harness/turn-tag-state.js";+import type { StepResult } from "#harness/types.js";+import type { RunMode } from "#shared/run-mode.js";+import { preserveSerializedBackgroundTaskObservabilityState } from "#shared/serialized-observability-state.js";++export function resolveSessionStepResult(+ stepResult: StepResult,+ nextSerializedContext: Record<string, unknown>,+ mode: RunMode,+ beforeStepContext: Record<string, unknown>,+): DurableStepResult {+ const nextState = createDurableSessionState({ session: stepResult.session });+ const backgroundTransition =+ stepResult.backgroundTasks === undefined || stepResult.backgroundTaskSession === undefined+ ? {}+ : {+ backgroundTaskContext: preserveSerializedBackgroundTaskObservabilityState(+ beforeStepContext,+ nextSerializedContext,+ stepResult.backgroundTasks,+ ),+ backgroundTaskState: createDurableSessionState({+ session: stepResult.backgroundTaskSession,+ }),+ backgroundTasks: stepResult.backgroundTasks,+ };++ if (+ stepResult.next !== null &&+ typeof stepResult.next === "object" &&+ "done" in stepResult.next+ ) {+ if (mode === "task" && hasPendingInputBatch(stepResult.session.state)) {+ throw new Error("Task mode cannot complete while input requests remain pending.");+ }+ const sessionTotals = getTurnUsageState(stepResult.session.state)?.session;+ return {+ action: "done",+ ...backgroundTransition,+ output: stepResult.next.output,+ isError: stepResult.next.isError,+ serializedContext: nextSerializedContext,+ sessionState: nextState,+ usage: sessionTotals === undefined ? undefined : toUsage(sessionTotals),+ usageDelta: takeSessionUsageDelta(stepResult.session).delta,+ };+ }++ if (stepResult.next === null) {+ const pending = derivePendingState(stepResult.session);++ // `settledTurn` is the harness's explicit settlement verdict. Pending+ // state may predate this turn, while newly created parks omit the verdict.+ // `usage` carries only this turn's delta: the take marks the totals+ // reported, so a persistent child never re-reports earlier spend.+ if (stepResult.settledTurn !== undefined) {+ const { delta, session: reportedSession } = takeSessionUsageDelta(stepResult.session);+ return {+ action: "park",+ ...backgroundTransition,+ ...pending,+ serializedContext: nextSerializedContext,+ sessionState: createDurableSessionState({ session: reportedSession }),+ settled: {+ output: stepResult.settledTurn.output,+ isError: stepResult.settledTurn.isError,+ usage: delta,+ },+ };+ }++ return {+ action: "park",+ ...backgroundTransition,+ ...pending,+ serializedContext: nextSerializedContext,+ sessionState: nextState,+ };+ }++ return {+ action: "continue",+ ...backgroundTransition,+ serializedContext: nextSerializedContext,+ sessionState: nextState,+ };+}diff --git a/packages/eve/src/execution/session/turn-step-types.ts b/packages/eve/src/execution/session/turn-step-types.tsnew file mode 100644index 000000000..d8985fe39--- /dev/null+++ b/packages/eve/src/execution/session/turn-step-types.ts@@ -0,0 +1,77 @@+import type { DeliverHookPayload } from "#channel/types.js";+import type { DurableSessionState } from "#execution/durable-session-store.js";+import type { SettledTurn, StepResult } from "#harness/types.js";+import type { RuntimeActionResult } from "#shared/action-types.js";+import type { TokenUsage } from "#shared/token-usage.js";++/** Trusted runtime-action results collected by the session owner. */+export interface RuntimeActionResultStepInput {+ readonly acceptedAtMsByCallId?: Readonly<Record<string, number>>;+ readonly results: readonly RuntimeActionResult[];+}++/**+ * Everything one turn step may consume. A step can carry a delivery and a+ * set of runtime results together: steering accepted while a blocking action+ * was in flight is appended ahead of that action's result in the same step.+ */+export interface TurnStepPayload {+ readonly control?: "clear" | "compact";+ readonly delivery?: DeliverHookPayload;+ readonly runtimeResults?: RuntimeActionResultStepInput;+}++/** Input for one atomic, session-owner-executed turn step. */+export interface TurnStepInput {+ readonly abortSignal?: AbortSignal;+ readonly input: TurnStepPayload | undefined;+ readonly sessionWritable: WritableStream<Uint8Array>;+ readonly serializedContext: Record<string, unknown>;+ readonly sessionState: DurableSessionState;+}++interface DurableStepResultFields {+ /** Pre-step context plus the observability state owned by committed background tasks. */+ readonly backgroundTaskContext?: Record<string, unknown>;+ readonly backgroundTaskState?: DurableSessionState;+ readonly backgroundTasks?: StepResult["backgroundTasks"];+ readonly serializedContext: Record<string, unknown>;+ readonly sessionState: DurableSessionState;+}++/** Result returned by a session-mutating turn step. */+export type DurableStepResult = (+ | {+ readonly action: "continue" | "done";+ readonly output?: unknown;+ readonly isError?: boolean;+ readonly usage?: TokenUsage;+ readonly usageDelta?: TokenUsage;+ }+ | { readonly action: "cancelled" }+ | {+ readonly action: "park";+ readonly authorizationAttemptIds?: readonly string[];+ readonly hasPendingAuthorization: boolean;+ readonly hasPendingInputBatch: boolean;+ readonly pendingCoordinationCallIds?: readonly string[];+ readonly settled?: SettledTurn;+ }+) &+ DurableStepResultFields;++/** The only two ways a locally executed conversational turn can settle. */+export type TurnOutcome =+ | {+ readonly kind: "done";+ readonly output: unknown;+ readonly isError?: boolean;+ readonly usage?: TokenUsage;+ readonly usageDelta?: TokenUsage;+ }+ | {+ readonly authorizationAttemptIds?: readonly string[];+ readonly cancelled?: true;+ readonly kind: "park";+ readonly settled?: SettledTurn;+ };diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/session/turn-step.test.tssimilarity index 87%rename from packages/eve/src/execution/workflow-steps.test.tsrename to packages/eve/src/execution/session/turn-step.test.tsindex c4eac6dd9..fad8f7c5e 100644--- a/packages/eve/src/execution/workflow-steps.test.ts+++ b/packages/eve/src/execution/session/turn-step.test.ts@@ -1,3 +1,4 @@+import { createTestSessionState } from "#internal/testing/session-state.js";import type { ModelMessage } from "ai";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { ChannelAdapter, ChannelAdapterContext } from "#channel/adapter.js";@@ -13,6 +14,7 @@ import {ActivityRootTurnIdKey,AuthKey,ChannelInstrumentationKey,+ ContinuationHookTokensKey,ContinuationTokenKey,DynamicSubagentAgentConfigKey,ModeKey,@@ -48,14 +50,9 @@ import {import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";import {createDurableSessionState,- DURABLE_SESSION_VERSION,type DurableSessionState,- projectSessionState,readDurableSession,} from "#execution/durable-session-store.js";-import { createTurnWorkflowInput } from "#execution/durable-session-migrations/turn-workflow.js";-import { dispatchTurnStep } from "#execution/dispatch-turn-step.js";-import { projectToDurableSession } from "#execution/session.js";import { buildRuntimeIdentity, createExecutionNodeStep } from "#execution/node-step.js";import { defineTool } from "#tools/definition.js";import { stampDurableDynamicCallback } from "#tools/durable-callbacks.js";@@ -65,10 +62,30 @@ import { readLatestTaskView, sendTaskInboundPayload } from "#execution/tasks/parimport { recordTaskInputRequestStep } from "#execution/tasks/parent/hitl-proxy-steps.js";import { emitTerminalSessionFailureStep } from "#execution/terminal-session-failure-step.js";import { resolveEffectiveOutputSchema } from "#execution/effective-output-schema.js";-import { turnStep } from "#execution/workflow-steps.js";+import { turnStep as runTurnStep } from "#execution/session/turn-step.js";+import type { TurnStepInput, TurnStepPayload } from "#execution/session/turn-step-types.js";+import type { DeliverHookPayload } from "#channel/types.js";+import type { RuntimeActionResult } from "#shared/action-types.js";++type LegacyStepPayload =+ | DeliverHookPayload+ | { readonly kind: "clear" | "compact" }+ | { readonly kind: "runtime-action-result"; readonly results: readonly RuntimeActionResult[] };++/** Adapts the older single-kind payload shape these fixtures were written against. */+function turnStep(input: Omit<TurnStepInput, "input"> & { readonly input?: LegacyStepPayload }) {+ let payload: TurnStepPayload | undefined;+ if (input.input !== undefined) {+ payload =+ input.input.kind === "deliver"+ ? { delivery: input.input }+ : input.input.kind === "runtime-action-result"+ ? { runtimeResults: { results: input.input.results } }+ : { control: input.input.kind };+ }+ return runTurnStep({ ...input, input: payload });+}import { routeProxiedDeliverStep } from "#execution/proxied-deliver-step.js";-import { turnWorkflowReference } from "#execution/workflow-runtime.js";-import { ConversationContextKey } from "#shared/conversation-context.js";const bindSessionInstrumentationSpy = vi.hoisted(() => vi.fn());vi.mock("#instrumentation/runtime.js", async (importOriginal) => {@@ -82,15 +99,15 @@ vi.mock("#instrumentation/runtime.js", async (importOriginal) => {};});-vi.mock("./durable-session-store.js", async (importOriginal) => {- const actual = await importOriginal<typeof import("./durable-session-store.js")>();+vi.mock("../durable-session-store.js", async (importOriginal) => {+ const actual = await importOriginal<typeof import("../durable-session-store.js")>();return {...actual,- createDurableSessionState: vi.fn(),+ createDurableSessionState: vi.fn(actual.createDurableSessionState),readDurableSession: vi.fn(),};});-vi.mock("./tasks/parent/run-parent.js", () => ({+vi.mock("../tasks/parent/run-parent.js", () => ({readLatestTaskView: vi.fn(),sendTaskInboundPayload: vi.fn(),}));@@ -114,34 +131,24 @@ function installSessionStoreMocks(// off the queue. Tests that exercise multiple harness steps stack// sessions in the order the step boundaries hit them.const queue = [...sessions];- vi.mocked(readDurableSession).mockImplementation(async () => {+ vi.mocked(readDurableSession).mockImplementation(() => {const next = queue.shift() ?? sessions[sessions.length - 1];if (!next) {throw new Error("No session prepared for readDurableSession");}return next;});-- vi.mocked(createDurableSessionState).mockImplementation(({ session }) => {- return {- ...projectSessionState({ session }),- snapshot: {- session: projectToDurableSession(session),- version: DURABLE_SESSION_VERSION,- },- };- });}function createStubSessionState(overrides: Partial<DurableSessionState> = {}): DurableSessionState {- return {+ return createTestSessionState({continuationToken: "test-token",emissionState: { sequence: 0, sessionStarted: false, stepIndex: 0, turnId: "" },hasProxyInputRequests: false,sessionId: "sess-test",version: 1,...overrides,- };+ });}const DEFAULT_WORKFLOW_STREAM_NAMESPACE = "__default__";@@ -162,7 +169,7 @@ function createTestWritable(});}-vi.mock("./node-step.js", () => ({+vi.mock("../node-step.js", () => ({buildRuntimeIdentity: vi.fn(() => ({agentId: "test-agent",eveVersion: "0.0.0-test",@@ -171,12 +178,11 @@ vi.mock("./node-step.js", () => ({createExecutionNodeStep: vi.fn(),}));-vi.mock("../runtime/sessions/compiled-agent-cache.js", () => ({+vi.mock("../../runtime/sessions/compiled-agent-cache.js", () => ({getCompiledRuntimeAgentBundle: vi.fn(),}));vi.mock("#compiled/@workflow/core/runtime.js", () => ({- getHookByToken: vi.fn(async (token: string) => currentSessionHook(token)),getRun: (...args: unknown[]) => getRunMock(...args),resumeHook: (...args: unknown[]) => resumeHookMock(...args),start: (...args: unknown[]) => startMock(...args),@@ -289,6 +295,7 @@ function createStubBundle(): Awaited<ReturnType<typeof getCompiledRuntimeAgentBu}beforeEach(() => {+ resumeHookMock.mockImplementation(async (token: string) => currentSessionHook(token));vi.mocked(getCompiledRuntimeAgentBundle).mockReset().mockResolvedValue(createStubBundle());});@@ -315,7 +322,7 @@ describe("routeProxiedDeliverStep", () => {"request-1",{childContinuationToken: "stale-alias",- childSessionInbox: { sessionId: "original-child", version: 1 },+ childSessionInbox: { sessionId: "original-child" },kind: "question",},],@@ -329,8 +336,11 @@ describe("routeProxiedDeliverStep", () => {installSessionStoreMocks([session]);await routeProxiedDeliverStep({- parentWritable: createTestWritable(),- payload: { inputResponses: [{ requestId: "request-1", text: "yes" }] },+ sessionWritable: createTestWritable(),+ delivery: {+ kind: "deliver",+ payloads: [{ inputResponses: [{ requestId: "request-1", text: "yes" }] }],+ },sessionState: createStubSessionState({continuationToken: "parent-token",hasProxyInputRequests: true,@@ -339,10 +349,9 @@ describe("routeProxiedDeliverStep", () => {});expect(resumeHookMock).toHaveBeenCalledWith(- "eve:session:original-child:inbox",+ "eve:inbox:v1:eve:session:original-child:inbox",expect.objectContaining({kind: "deliver",- version: 1,payloads: [{ inputResponses: [{ requestId: "request-1", text: "yes" }] }],}),);@@ -369,10 +378,15 @@ describe("routeProxiedDeliverStep", () => {installSessionStoreMocks([session]);const result = await routeProxiedDeliverStep({- auth,- parentWritable: createTestWritable(),- payload: {- inputResponses: [{ optionId: "approve", requestId: "request-1" }],+ sessionWritable: createTestWritable(),+ delivery: {+ kind: "deliver",+ auth,+ payloads: [+ {+ inputResponses: [{ optionId: "approve", requestId: "request-1" }],+ },+ ],},sessionState: createStubSessionState({continuationToken: "parent-token",@@ -382,16 +396,11 @@ describe("routeProxiedDeliverStep", () => {});expect(result).toMatchObject({ kind: "continue", remainder: undefined });- expect(resumeHookMock).toHaveBeenCalledWith(currentSessionHook("child-token"), {+ expect(resumeHookMock).toHaveBeenCalledWith("eve:inbox:v1:child-token", {auth,- caller: undefined,+ deliveryMetadata: undefined,kind: "deliver",- payload: {- inputResponses: [{ optionId: "approve", requestId: "request-1" }],- },payloads: [{ inputResponses: [{ optionId: "approve", requestId: "request-1" }] }],- requestId: undefined,- version: 1,});});@@ -447,12 +456,12 @@ describe("routeProxiedDeliverStep", () => {const result = await routeProxiedDeliverStep({delivery,- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),sessionState: createStubSessionState({ hasProxyInputRequests: true }),});expect(resumeHookMock).toHaveBeenCalledWith(- currentSessionHook("child-token-a"),+ "eve:inbox:v1:child-token-a",expect.objectContaining({...delivery,deliveryMetadata: [expect.objectContaining({ deliveryId: "delivery-0", payloadIndex: 0 })],@@ -460,7 +469,7 @@ describe("routeProxiedDeliverStep", () => {}),);expect(resumeHookMock).toHaveBeenCalledWith(- currentSessionHook("child-token-b"),+ "eve:inbox:v1:child-token-b",expect.objectContaining({auth,caller,@@ -538,7 +547,10 @@ describe("routeProxiedDeliverStep", () => {}const taskRouteInput = {- payload: { inputResponses: [{ optionId: "approve", requestId: "task-1:request-1" }] },+ delivery: {+ kind: "deliver" as const,+ payloads: [{ inputResponses: [{ optionId: "approve", requestId: "task-1:request-1" }] }],+ },sessionState: createStubSessionState({ hasProxyInputRequests: true }),};@@ -547,7 +559,7 @@ describe("routeProxiedDeliverStep", () => {const result = await routeProxiedDeliverStep({...taskRouteInput,- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),});expect(result).toMatchObject({ kind: "continue", remainder: undefined });expect(sendTaskInboundPayload).toHaveBeenCalledWith({@@ -561,7 +573,7 @@ describe("routeProxiedDeliverStep", () => {},taskInboxToken: "task-token",});- expect(getProxyInputRequests(result.sessionState.snapshot?.session.state).size).toBe(0);+ expect(getProxyInputRequests(result.sessionState.snapshot.session.state).size).toBe(0);});it("preserves the task-owned workflow-tool answer route for its controller", async () => {@@ -569,7 +581,7 @@ describe("routeProxiedDeliverStep", () => {createTaskRouteSession({ childContinuationToken: "eve:workflow-tool-run-answer:run-1:0" }),]);- await routeProxiedDeliverStep({ ...taskRouteInput, parentWritable: createTestWritable() });+ await routeProxiedDeliverStep({ ...taskRouteInput, sessionWritable: createTestWritable() });expect(sendTaskInboundPayload).toHaveBeenCalledWith({payload: expect.objectContaining({@@ -586,7 +598,7 @@ describe("routeProxiedDeliverStep", () => {createTaskRouteSession({ childResponseUrl: "https://child.example/eve/v1/task-input/token" }),]);- await routeProxiedDeliverStep({ ...taskRouteInput, parentWritable: createTestWritable() });+ await routeProxiedDeliverStep({ ...taskRouteInput, sessionWritable: createTestWritable() });expect(sendTaskInboundPayload).toHaveBeenCalledWith({payload: expect.objectContaining({@@ -601,11 +613,12 @@ describe("routeProxiedDeliverStep", () => {installSessionStoreMocks([createTaskRouteSession({ owned: false })]);await expect(- routeProxiedDeliverStep({ ...taskRouteInput, parentWritable: createTestWritable() }),+ routeProxiedDeliverStep({ ...taskRouteInput, sessionWritable: createTestWritable() }),).resolves.toMatchObject({kind: "continue",remainder: {- inputResponses: [{ optionId: "approve", requestId: "task-1:request-1" }],+ kind: "deliver",+ payloads: [{ inputResponses: [{ optionId: "approve", requestId: "task-1:request-1" }] }],},});expect(resumeHookMock).not.toHaveBeenCalled();@@ -616,11 +629,12 @@ describe("routeProxiedDeliverStep", () => {vi.mocked(sendTaskInboundPayload).mockResolvedValueOnce("unreachable");await expect(- routeProxiedDeliverStep({ ...taskRouteInput, parentWritable: createTestWritable() }),+ routeProxiedDeliverStep({ ...taskRouteInput, sessionWritable: createTestWritable() }),).resolves.toMatchObject({kind: "continue",remainder: {- inputResponses: [{ optionId: "approve", requestId: "task-1:request-1" }],+ kind: "deliver",+ payloads: [{ inputResponses: [{ optionId: "approve", requestId: "task-1:request-1" }] }],},});});@@ -633,10 +647,10 @@ describe("routeProxiedDeliverStep", () => {.mockResolvedValueOnce("delivered");await expect(- routeProxiedDeliverStep({ ...taskRouteInput, parentWritable: createTestWritable() }),+ routeProxiedDeliverStep({ ...taskRouteInput, sessionWritable: createTestWritable() }),).rejects.toThrow("transient");await expect(- routeProxiedDeliverStep({ ...taskRouteInput, parentWritable: createTestWritable() }),+ routeProxiedDeliverStep({ ...taskRouteInput, sessionWritable: createTestWritable() }),).resolves.toMatchObject({ kind: "continue", remainder: undefined });expect(sendTaskInboundPayload).toHaveBeenCalledTimes(2);});@@ -644,7 +658,7 @@ describe("routeProxiedDeliverStep", () => {function currentSessionHook(token: string) {return {- metadata: { sessionInboxWireVersion: 1 },+ metadata: { sessionId: "child-run" },runId: "child-run",token,};@@ -722,7 +736,7 @@ describe("recordTaskInputRequestStep", () => {expect(result.accepted).toBe(true);expect(- getProxyInputRequests(result.sessionState.snapshot?.session.state).get("task-1:request-1"),+ getProxyInputRequests(result.sessionState.snapshot.session.state).get("task-1:request-1"),).toEqual({childContinuationToken: "eve:workflow-tool-run-answer:run-1:0",childRequestId: "request-1",@@ -749,213 +763,6 @@ describe("recordTaskInputRequestStep", () => {});});-describe("dispatchTurnStep", () => {- function createTurnInput(): Parameters<typeof dispatchTurnStep>[0] {- const parentWritable = createTestWritable();- const sessionState = createStubSessionState();-- return {- capabilities: undefined,- completionToken: "turn-control",- delivery: {- kind: "deliver",- payloads: [{ message: "hello" }],- requestId: "req_turn",- },- mode: "conversation",- parentWritable,- serializedContext: { state: "driver" },- sessionState,- };- }-- it("starts turn workflows on the current driver deployment without an ingress stamp", async () => {- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_driver");- const input = createTurnInput();- startMock.mockResolvedValue({ runId: "turn-run" });-- await expect(dispatchTurnStep(input)).resolves.toEqual({ runId: "turn-run" });-- expect(startMock).toHaveBeenCalledWith(- turnWorkflowReference,- [createTurnWorkflowInput(input)],- {- allowReservedAttributes: true,- attributes: {- "$eve.channel_request_id": "req_turn",- "$eve.is_otel_trace_enabled": "false",- "$eve.parent": "sess-test",- "$eve.root": "sess-test",- "$eve.is_trace_content_visible": "false",- "$eve.type": "turn",- },- deploymentId: "dpl_driver",- },- );- });-- it("starts on the accepted deployment when the dispatch step runs there", async () => {- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_current");- const baseInput = createTurnInput();- const input = {- ...baseInput,- delivery: {- ...baseInput.delivery,- deliveryMetadata: [- {- acceptedDeploymentId: "dpl_current",- channelKind: "channel:webhook",- channelName: "webhook",- deliveryId: "delivery-1",- payloadIndex: 0,- },- ],- },- };- startMock.mockResolvedValue({ runId: "turn-run" });-- await expect(dispatchTurnStep(input)).resolves.toEqual({ runId: "turn-run" });-- expect(startMock).toHaveBeenCalledWith(- turnWorkflowReference,- [createTurnWorkflowInput(input)],- expect.objectContaining({ deploymentId: "dpl_current" }),- );- });-- it("stays on the driver deployment for mixed accepted deployments", async () => {- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_current");- const baseInput = createTurnInput();- const input = {- ...baseInput,- delivery: {- ...baseInput.delivery,- deliveryMetadata: [- {- acceptedDeploymentId: "dpl_current",- channelKind: "channel:webhook",- channelName: "webhook",- deliveryId: "delivery-1",- payloadIndex: 0,- },- {- acceptedDeploymentId: "dpl_other",- channelKind: "channel:webhook",- channelName: "webhook",- deliveryId: "delivery-2",- payloadIndex: 1,- },- ],- },- };- startMock.mockResolvedValue({ runId: "turn-run" });-- await expect(dispatchTurnStep(input)).resolves.toEqual({ runId: "turn-run" });-- expect(startMock).toHaveBeenCalledWith(- turnWorkflowReference,- [createTurnWorkflowInput(input)],- expect.objectContaining({ deploymentId: "dpl_current" }),- );- });-- it("lets the development world retain its stamped generation", async () => {- vi.stubEnv("EVE_DEV", "1");- const input = createTurnInput();- input.serializedContext[ConversationContextKey.name] = {- audience: "unknown",- channel: { kind: "http" },- environment: "development",- mode: "conversation",- principalType: "anonymous",- };- startMock.mockResolvedValue({ runId: "turn-run" });-- await expect(dispatchTurnStep(input)).resolves.toEqual({ runId: "turn-run" });-- expect(startMock).toHaveBeenCalledWith(- turnWorkflowReference,- [createTurnWorkflowInput(input)],- {- allowReservedAttributes: true,- attributes: {- "$eve.channel_request_id": "req_turn",- "$eve.is_otel_trace_enabled": "false",- "$eve.parent": "sess-test",- "$eve.root": "sess-test",- "$eve.is_trace_content_visible": "true",- "$eve.type": "turn",- },- },- );- });-- it("pins turn workflows to the current deployment off production", async () => {- vi.stubEnv("VERCEL_ENV", "preview");- const input = createTurnInput();- startMock.mockResolvedValue({ runId: "turn-run" });-- await expect(dispatchTurnStep(input)).resolves.toEqual({ runId: "turn-run" });-- expect(startMock).toHaveBeenCalledTimes(1);- expect(startMock).toHaveBeenCalledWith(- turnWorkflowReference,- [createTurnWorkflowInput(input)],- {- allowReservedAttributes: true,- attributes: {- "$eve.channel_request_id": "req_turn",- "$eve.is_otel_trace_enabled": "false",- "$eve.parent": "sess-test",- "$eve.root": "sess-test",- "$eve.is_trace_content_visible": "false",- "$eve.type": "turn",- },- },- );- });-- it("targets a stamped accepting deployment even when the driver is older", async () => {- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_driver");- const baseInput = createTurnInput();- const input = {- ...baseInput,- delivery: {- ...baseInput.delivery,- deliveryMetadata: [- {- acceptedDeploymentId: "dpl_ingress",- channelKind: "channel:webhook",- channelName: "webhook",- deliveryId: "delivery-1",- payloadIndex: 0,- },- ],- },- };- startMock.mockResolvedValue({ runId: "turn-run" });-- await expect(dispatchTurnStep(input)).resolves.toEqual({ runId: "turn-run" });-- expect(startMock).toHaveBeenCalledWith(- turnWorkflowReference,- [createTurnWorkflowInput(input)],- {- allowReservedAttributes: true,- attributes: {- "$eve.channel_request_id": "req_turn",- "$eve.is_otel_trace_enabled": "false",- "$eve.parent": "sess-test",- "$eve.root": "sess-test",- "$eve.is_trace_content_visible": "false",- "$eve.type": "turn",- },- deploymentId: "dpl_ingress",- },- );- });-});-describe("dispatchCoordinationStep", () => {it("repairs an empty pending turn id from the active session turn", async () => {vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({@@ -995,7 +802,7 @@ describe("dispatchCoordinationStep", () => {const result = await dispatchCoordinationStep({action: "park",workflowToolRunOwner: { inbox: "generated-owner-token" },- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: createSerializedContext(),sessionState,});@@ -1058,7 +865,7 @@ describe("dispatchCoordinationStep", () => {dispatchCoordinationStep({action: "park",workflowToolRunOwner: { inbox: "generated-owner-token" },- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: createSerializedContext(),sessionState,}),@@ -1122,7 +929,7 @@ describe("dispatchCoordinationStep", () => {dispatchCoordinationStep({action: "park",workflowToolRunOwner: { inbox: "generated-owner-token" },- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: createSerializedContext(),sessionState,}),@@ -1199,7 +1006,7 @@ describe("dispatchCoordinationStep", () => {dispatchCoordinationStep({action: "park",workflowToolRunOwner: { inbox: "generated-owner-token" },- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: createSerializedContext(),sessionState,}),@@ -1340,7 +1147,7 @@ describe("turnStep", () => {},],},- parentWritable: writable,+ sessionWritable: writable,serializedContext,sessionState: createStubSessionState({ emissionState }),});@@ -1364,7 +1171,7 @@ describe("turnStep", () => {payloads: [{ message: "Background task task_report is completed." }],taskDeliveryId: "task_report:ready:completed",},- parentWritable: writable,+ sessionWritable: writable,serializedContext: launch.serializedContext,sessionState: launch.sessionState,});@@ -1420,7 +1227,7 @@ describe("turnStep", () => {const result = await turnStep({input: { kind: "deliver", payloads: [{ message: "run the chain" }] },- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: createSerializedContext(),sessionState: createStubSessionState(),});@@ -1432,14 +1239,14 @@ describe("turnStep", () => {undefined,undefined,]);- expect(result.sessionState.snapshot?.session.history).toEqual([+ expect(result.sessionState.snapshot.session.history).toEqual([{ content: "model call 1", role: "assistant" },{ content: "model call 2", role: "assistant" },{ content: "model call 3", role: "assistant" },]);});- it("checkpoints completed batched model calls when steering cancels the active call", async () => {+ it("checkpoints completed batched model calls when explicit cancellation aborts the active call", async () => {const bundle = createTurnStepTestBundle(100);vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(bundle);installSessionStoreMocks([createStubSession()]);@@ -1481,7 +1288,7 @@ describe("turnStep", () => {const result = await turnStep({abortSignal: controller.signal,input: { kind: "deliver", payloads: [{ message: "run a long chain" }] },- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: createSerializedContext(),sessionState: createStubSessionState(),});@@ -1489,8 +1296,8 @@ describe("turnStep", () => {expect(result.action).toBe("cancelled");expect(callCount).toBe(51);expect(result.serializedContext).toMatchObject({ [ThreadKey.name]: "completed call 50" });- expect(result.sessionState.snapshot?.session.history).toHaveLength(50);- expect(result.sessionState.snapshot?.session.history.at(-1)).toEqual({+ expect(result.sessionState.snapshot.session.history).toHaveLength(50);+ expect(result.sessionState.snapshot.session.history.at(-1)).toEqual({content: "model call 50",role: "assistant",});@@ -1510,7 +1317,7 @@ describe("turnStep", () => {const result = await turnStep({input: { kind: "deliver", payloads: [{ message: "one call" }] },- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: createSerializedContext(),sessionState: createStubSessionState(),});@@ -1544,7 +1351,7 @@ describe("turnStep", () => {const result = await turnStep({input: { kind: "deliver", payloads: [{ message: "ask first" }] },- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: createSerializedContext(),sessionState: createStubSessionState(),});@@ -1570,7 +1377,7 @@ describe("turnStep", () => {const result = await turnStep({input: { kind: "deliver", payloads: [{ message: "delegate" }] },- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: createSerializedContext(),sessionState: createStubSessionState(),});@@ -1582,7 +1389,7 @@ describe("turnStep", () => {expect(execute).toHaveBeenCalledOnce();});- it("retains coalesced delivery ownership across steps and replaces it for the next message", async () => {+ it("retains coalesced delivery ownership when a message steers the active turn", async () => {const session = createStubSession({state: {"eve.harness.emission": {@@ -1630,14 +1437,14 @@ describe("turnStep", () => {const first = await turnStep({input: delivery(["delivery-a", "delivery-b"]),- parentWritable: createTestWritable("first"),+ sessionWritable: createTestWritable("first"),serializedContext: createSerializedContext(),sessionState: createStubSessionState(),});expect(first.serializedContext[TurnDeliveryIdsKey.name]).toEqual(["delivery-a", "delivery-b"]);const resumed = await turnStep({input: undefined,- parentWritable: createTestWritable("resumed"),+ sessionWritable: createTestWritable("resumed"),serializedContext: first.serializedContext,sessionState: first.sessionState,});@@ -1647,15 +1454,19 @@ describe("turnStep", () => {]);const next = await turnStep({input: delivery(["delivery-c"]),- parentWritable: createTestWritable("next"),+ sessionWritable: createTestWritable("next"),serializedContext: resumed.serializedContext,sessionState: resumed.sessionState,});- expect(next.serializedContext[TurnDeliveryIdsKey.name]).toEqual(["delivery-c"]);+ expect(next.serializedContext[TurnDeliveryIdsKey.name]).toEqual([+ "delivery-a",+ "delivery-b",+ "delivery-c",+ ]);for (const [namespace, deliveryIds] of [["first", ["delivery-a", "delivery-b"]],["resumed", ["delivery-a", "delivery-b"]],- ["next", ["delivery-c"]],+ ["next", ["delivery-a", "delivery-b", "delivery-c"]],] as const) {const events = (workflowWritesByNamespace.get(namespace) ?? []).map((chunk) =>JSON.parse(new TextDecoder().decode(chunk as Uint8Array)),@@ -1669,29 +1480,6 @@ describe("turnStep", () => {}});- it("defers before mutation when an inline step reaches another deployment", async () => {- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_driver");- const sessionState = createStubSessionState();- const durableReadsBefore = vi.mocked(readDurableSession).mock.calls.length;-- await expect(- turnStep({- acceptedDeploymentId: "dpl_ingress",- input: { kind: "deliver", payloads: [{ message: "hello" }] },- parentWritable: createTestWritable(),- serializedContext: { state: "untouched" },- sessionState,- }),- ).resolves.toEqual({- action: "continue",- requiresChildDispatch: true,- serializedContext: { state: "untouched" },- sessionState,- });-- expect(vi.mocked(readDurableSession).mock.calls).toHaveLength(durableReadsBefore);- });-it("prepares resumed-session history before dynamic runtime refresh", async () => {const hidden = {content: "HIDE_FROM_RUNTIME_REFRESH",@@ -1784,7 +1572,7 @@ describe("turnStep", () => {await turnStep({input: { kind: "deliver", payloads: [{ message: "follow up" }] },- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: serializeContext(ctx),sessionState: createStubSessionState({emissionState: {@@ -1857,7 +1645,7 @@ describe("turnStep", () => {await expect(turnStep({input: { kind: "deliver", payloads: [{ message: "hello" }] },- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: serializeContext(ctx),sessionState: createStubSessionState(),}),@@ -1868,6 +1656,39 @@ describe("turnStep", () => {expect(workflowWritesByNamespace.get(DEFAULT_WORKFLOW_STREAM_NAMESPACE) ?? []).toEqual([]);});+ it("releases the parent stream writer when the deliver hook throws", async () => {+ const adapter: ChannelAdapter = {+ kind: "deliver-failure",+ deliver: vi.fn(async () => {+ throw new Error("deliver failed");+ }),+ };+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({+ ...createStubBundle(),+ adapterRegistry: { adaptersByKind: new Map([[adapter.kind, adapter]]) },+ } as never);+ installSessionStoreMocks([createStubSession()]);++ const ctx = new ContextContainer();+ ctx.set(AuthKey, null);+ ctx.set(BundleKey, createStubBundle());+ ctx.set(ChannelKey, adapter);+ ctx.set(ContinuationTokenKey, "deliver-failure");+ ctx.set(ModeKey, "conversation");+ ctx.set(SessionIdKey, "session-1");+ const sessionWritable = createTestWritable();++ await expect(+ turnStep({+ input: { kind: "deliver", payloads: [{ message: "hello" }] },+ sessionWritable,+ serializedContext: serializeContext(ctx),+ sessionState: createStubSessionState(),+ }),+ ).rejects.toThrow("deliver failed");+ expect(sessionWritable.locked).toBe(false);+ });+it.each([{expected: {@@ -1930,7 +1751,7 @@ describe("turnStep", () => {await turnStep({input: { auth: expected, kind: "deliver", payloads: [{ message: "follow up" }] },- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: serializeContext(ctx),sessionState: createStubSessionState(),});@@ -2051,7 +1872,7 @@ describe("turnStep", () => {await turnStep({input: { kind: "deliver", payloads: [{ message: "run the task" }] },- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: serializeContext(ctx),sessionState: createStubSessionState(),});@@ -2129,7 +1950,7 @@ describe("turnStep", () => {},],},- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: {...createSerializedContext(),[TurnDeliveryIdsKey.name]: ["previous-delivery"],@@ -2150,7 +1971,7 @@ describe("turnStep", () => {},});expect(result.serializedContext).not.toHaveProperty(ThreadKey.name);- expect(result.sessionState.snapshot?.session.history).toEqual([+ expect(result.sessionState.snapshot.session.history).toEqual([{ role: "user", content: announcement, kind: "user" },{ content: "thread=unset; user=cancel this turn", kind: "user", role: "user" },]);@@ -2189,13 +2010,13 @@ describe("turnStep", () => {kind: "deliver",payloads: [{ message: "attach:look at this" }],},- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: createSerializedContext(),sessionState: createStubSessionState(),});expect(result).toMatchObject({ action: "cancelled" });- expect(result.sessionState.snapshot?.session.history).toEqual([+ expect(result.sessionState.snapshot.session.history).toEqual([{content: [{ text: "thread=unset; user=look at this", type: "text" },@@ -2239,7 +2060,7 @@ describe("turnStep", () => {kind: "deliver",payloads: [{ message: "unrelated message" }],},- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: createSerializedContext("task"),sessionState: createStubSessionState(),}),@@ -2294,7 +2115,7 @@ describe("turnStep", () => {kind: "deliver",payloads: [{ message: "research this" }],},- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: serializeContext(ctx),sessionState: createStubSessionState(),});@@ -2353,7 +2174,7 @@ describe("turnStep", () => {kind: "deliver",payloads: [{ message: "check background work" }],},- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: createSerializedContext(),sessionState: createStubSessionState(),});@@ -2380,7 +2201,7 @@ describe("turnStep", () => {kind: "deliver",payloads: [{ message: "hello" }],},- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: createSerializedContext(),sessionState: createStubSessionState(),});@@ -2431,7 +2252,7 @@ describe("turnStep", () => {const first = await turnStep({input: { kind: "deliver", payloads: [{ message: "hello" }] },- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: createSerializedContext(),sessionState: createStubSessionState(),});@@ -2447,8 +2268,7 @@ describe("turnStep", () => {// Second turn: session totals are cumulative (150/60), but the settled// answer must only report what this turn added (50/20).- const firstSession = first.sessionState.snapshot?.session as HarnessSession;- installSessionStoreMocks([firstSession]);+ installSessionStoreMocks([first.sessionState.snapshot.session as HarnessSession]);vi.mocked(createExecutionNodeStep).mockImplementation(() => {return async (stepSession): Promise<StepResult> => ({next: null,@@ -2465,7 +2285,7 @@ describe("turnStep", () => {const second = await turnStep({input: { kind: "deliver", payloads: [{ message: "again" }] },- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: createSerializedContext(),sessionState: first.sessionState,});@@ -2511,7 +2331,7 @@ describe("turnStep", () => {kind: "deliver",payloads: [{ message: "unrelated message" }],},- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: createSerializedContext(),sessionState: createStubSessionState(),});@@ -2598,7 +2418,7 @@ describe("turnStep", () => {kind: "deliver",payloads: [{ message: "hello" }],},- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: createSerializedContext(),sessionState: createStubSessionState(),});@@ -2631,7 +2451,7 @@ describe("turnStep", () => {kind: "deliver",payloads: [{ message: "hello from turn step" }],},- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: createSerializedContext(),sessionState,});@@ -2694,7 +2514,7 @@ describe("turnStep", () => {payloads: [{ message: "Background task task_1 is completed." }],taskDeliveryId: "task_1:ready:completed",},- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: initialSerializedContext,sessionState: createStubSessionState(),});@@ -2704,13 +2524,13 @@ describe("turnStep", () => {payloads: [{ message: "Background task task_unknown is completed." }],taskDeliveryId: "task_unknown:ready:completed",},- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: first.serializedContext,sessionState: first.sessionState,});await turnStep({input: { kind: "deliver", payloads: [{ message: "What happened?" }] },- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: second.serializedContext,sessionState: second.sessionState,});@@ -2791,7 +2611,7 @@ describe("turnStep", () => {await turnStep({input: undefined,- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext,sessionState: createStubSessionState({emissionState: {@@ -2852,14 +2672,14 @@ describe("turnStep", () => {};});- const parentWritable = createTestWritable();+ const sessionWritable = createTestWritable();const sessionState = createStubSessionState();const first = await turnStep({input: {kind: "deliver",payloads: [{ message: "seed:alpha" }],},- parentWritable,+ sessionWritable,serializedContext: createSerializedContext(),sessionState,});@@ -2873,7 +2693,7 @@ describe("turnStep", () => {kind: "deliver",payloads: [{ message: "follow up" }],},- parentWritable,+ sessionWritable,serializedContext: first.serializedContext,sessionState: first.sessionState,});@@ -2936,7 +2756,7 @@ describe("turnStep", () => {kind: "deliver",payloads: [{ message: "finish up" }],},- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: createSerializedContext(),sessionState: createStubSessionState(),});@@ -3009,7 +2829,7 @@ describe("turnStep", () => {kind: "deliver",payloads: [{ message: "follow up" }],},- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: serializeContext(ctx),sessionState: createStubSessionState(),});@@ -3133,7 +2953,7 @@ describe("turnStep", () => {kind: "deliver",payloads: [{ message: "follow up" }],},- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: serializeContext(ctx),sessionState: createStubSessionState({emissionState: {@@ -3158,82 +2978,6 @@ describe("turnStep", () => {]);});- it("resumes a legacy pending authorization without attempt metadata", async () => {- const challenge = {- challenge: {- instructions: "Sign in to continue",- url: "https://idp.example/authorize",- },- hookUrl: "https://app.example/eve/v1/connections/statuspage/callback/sess-test:auth",- name: "statuspage",- resume: { nonce: "n1" },- };- const session = createStubSession({- state: setPendingAuthorization({ retained: "yes" }, { challenges: [challenge] }),- });- installSessionStoreMocks([session]);- vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({- adapterRegistry: {- adaptersByKind: new Map([[threadContextAdapter.kind, threadContextAdapter]]),- },- compiledArtifactsSource: {} as never,- graph: {- nodesByNodeId: new Map(),- root: {- sandboxRegistry: { sandbox: null },- turnAgent: TestTurnAgent,- },- },- moduleMap: { nodes: {} },- hookRegistry: createEmptyHookRegistry(),- resolvedAgent: { config: {} },- subagentRegistry: {},- toolRegistry: {},- turnAgent: TestTurnAgent,- } as never);-- let observedPendingAuth: unknown;- let observedStepInput: unknown = "not-called";- vi.mocked(createExecutionNodeStep).mockImplementation(() => {- return async (session, stepInput): Promise<StepResult> => {- observedPendingAuth = getPendingAuthorization(session.state);- observedStepInput = stepInput;- return { next: null, session };- };- });-- const result = await turnStep({- input: {- kind: "deliver",- payloads: [- {- authorizationCallback: {- callback: { code: "oauth-code" },- connectionName: "statuspage",- legacy: true,- },- },- ],- },- parentWritable: createTestWritable(),- serializedContext: createSerializedContext(),- sessionState: createStubSessionState(),- });-- expect(observedPendingAuth).toBeUndefined();- expect(observedStepInput).toBeUndefined();- expect(result).toMatchObject({- action: "park",- hasPendingAuthorization: false,- });- if (result.action === "park") {- expect(result.authorizationNames).toBeUndefined();- }- const persistedSession = vi.mocked(createDurableSessionState).mock.calls.at(-1)?.[0].session;- expect(persistedSession?.state?.retained).toBe("yes");- expect(getPendingAuthorization(persistedSession?.state)).toBeUndefined();- });-it("clears pending authorization after a matching callback resumes the turn", async () => {const challenge = {attemptId: "attempt-statuspage",@@ -3320,7 +3064,7 @@ describe("turnStep", () => {},],},- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: createSerializedContext(),sessionState: createStubSessionState(),});@@ -3332,7 +3076,7 @@ describe("turnStep", () => {hasPendingAuthorization: false,});if (result.action === "park") {- expect(result.authorizationNames).toBeUndefined();+ expect(result.authorizationAttemptIds).toBeUndefined();}const persistedSession = vi.mocked(createDurableSessionState).mock.calls.at(-1)?.[0].session;expect(persistedSession?.state?.retained).toBe("yes");@@ -3416,7 +3160,7 @@ describe("emitTerminalSessionFailureStep", () => {await emitTerminalSessionFailureStep({error,- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: serialized,});@@ -3464,7 +3208,7 @@ describe("emitTerminalSessionFailureStep", () => {await emitTerminalSessionFailureStep({error,- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: serialized,});@@ -3505,7 +3249,7 @@ describe("emitTerminalSessionFailureStep", () => {await expect(emitTerminalSessionFailureStep({error: new Error("inner"),- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: serialized,}),).resolves.toBeUndefined();@@ -3640,7 +3384,7 @@ describe("runProxySubagentEventStep", () => {const result = await runProxySubagentEventStep({hookPayload: buildHookPayload(),- parentWritable: createTestWritable(),+ sessionWritable: createTestWritable(),serializedContext: buildSerializedContextForAdapter(cachingAdapter, {acceptedForwardedTracePolicy: true,}),@@ -3648,7 +3392,7 @@ describe("runProxySubagentEventStep", () => {});// The updated serialized context must carry the adapter state- // mutation so the driver loop can thread it into the next+ // mutation so the session loop can thread it into the next// `turnStep`. The workflow-side serialization layer// projects the adapter onto its wire shape (`{ kind, state }`),// which is where we look for the cached batch.@@ -3688,11 +3432,12 @@ describe("runProxySubagentEventStep", () => {expect(writes).toHaveLength(3);});- it("re-stamps the returned session when the input.requested handler re-keys", async () => {- const rekeyingAdapter: ChannelAdapter = {+ it("returns every continuation address claimed by the input.requested handler", async () => {+ const aliasingAdapter: ChannelAdapter = {kind: "thread-context",async "input.requested"(_data, adapterCtx) {- adapterCtx.session.continuation?.rekey("proxy-rekeyed");+ adapterCtx.session.continuation?.alias("proxy-first");+ adapterCtx.session.continuation?.alias("proxy-second");},};@@ -3709,13 +3454,18 @@ describe("runProxySubagentEventStep", () => {const result = await runProxySubagentEventStep({hookPayload: buildHookPayload(),- parentWritable: createTestWritable(),- serializedContext: buildSerializedContextForAdapter(rekeyingAdapter),+ sessionWritable: createTestWritable(),+ serializedContext: buildSerializedContextForAdapter(aliasingAdapter),sessionState,});- expect(result.sessionState.continuationToken).toBe("http:proxy-rekeyed");- expect(result.serializedContext[ContinuationTokenKey.name]).toBe("http:proxy-rekeyed");+ expect(result.sessionState.continuationToken).toBe("http:proxy-second");+ expect(result.serializedContext[ContinuationTokenKey.name]).toBe("http:proxy-second");+ expect(result.serializedContext[ContinuationHookTokensKey.name]).toEqual([+ "http:proxy-test",+ "http:proxy-first",+ "http:proxy-second",+ ]);});});diff --git a/packages/eve/src/execution/session/turn-step.ts b/packages/eve/src/execution/session/turn-step.tsnew file mode 100644index 000000000..fbdd73a77--- /dev/null+++ b/packages/eve/src/execution/session/turn-step.ts@@ -0,0 +1,518 @@+import { defaultDeliverResult } from "#channel/adapter.js";+import { contextStorage } from "#context/container.js";+import {+ drainDynamicInstructionUserMessages,+ prepareDynamicInstructionPreamble,+} from "#context/dynamic-instruction-lifecycle.js";+import { refreshDynamicSessionSubagentsForRuntimeRevision } from "#context/dynamic-subagent-lifecycle.js";+import {+ rebindMissingCompiledDynamicToolCallbacks,+ refreshDynamicSessionToolsForRuntimeRevision,+} from "#context/dynamic-tool-lifecycle.js";+import {+ AuthKey,+ CapabilitiesKey,+ ChannelDeliveryKey,+ HandleEventKey,+ ModeKey,+ SessionDynamicSubagentRuntimeRevisionKey,+ SessionDynamicToolRuntimeRevisionKey,+ StaticModelReferenceKey,+ TurnTaskDeliveryKey,+ TurnDeliveryIdsKey,+} from "#context/keys.js";+import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";+import { deserializeContext, serializeContext } from "#context/serialize.js";+import {+ emitTurnPreamble,+ getHarnessEmissionState,+ isHarnessBetweenTurns,+ setHarnessEmissionState,+} from "#harness/emission.js";+import { bindSessionInstrumentation } from "#instrumentation/runtime.js";+import { RuntimeActionSettlementTimesKey } from "#harness/runtime-action-settlement-state.js";+import * as agentTraceState from "#tracing/agent-trace-context-store.js";+import { matchAuthorizationCallbacks } from "#execution/authorization-callback-match.js";+import { isTurnCancellation, throwIfTurnAborted } from "#harness/turn-cancellation.js";+import { setChannelContext } from "#execution/channel-context.js";+import { activeTurnId } from "#harness/active-turn-id.js";+import { coalesceTurnInputs, type UserModelMessage } from "#harness/messages.js";+import type { HarnessSession, StepInput, StepResult } from "#harness/types.js";+import type { DurableStepResult, TurnStepInput } from "#execution/session/turn-step-types.js";+import { resolveSessionStepResult } from "#execution/session/turn-step-result.js";+import { createSessionEventSink } from "#execution/session/event-sink.js";+import { derivePendingState } from "#execution/session/pending-turn-state.js";+import {+ createAuthorizationCompletedEvent,+ createSessionStartedEvent,+ createTurnStartedEvent,+} from "#protocol/message.js";+import {+ CallbackBaseUrlKey,+ clearPendingAuthorization,+ getPendingAuthorization,+ PendingAuthorizationResultKey,+} from "#harness/authorization.js";+import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";+import { resolveEffectiveOutputSchema } from "#execution/effective-output-schema.js";+import { createDurableSessionState, readDurableSession } from "#execution/durable-session-store.js";+import { buildRuntimeIdentity, createExecutionNodeStep } from "#execution/node-step.js";+import {+ getBackgroundTaskDelivery,+ markBackgroundTaskStepInput,+ resolveInitiatingTaskContext,+ resolveTaskDeliveryContext,+} from "#tasks/delivery-context.js";+import {+ readRetainedBackgroundToolResult,+ runBackgroundStep,+} from "#execution/tasks/parent/tool-execution.js";+import { prepareWorkflowPreambleTrace } from "#execution/workflow-trace-context.js";+import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";+import { reconcileSessionContinuationToken } from "#execution/reconcile-session-continuation-token.js";+import { hydrateDurableSession, refreshSessionFromTurnAgent } from "#execution/session.js";+import { createExecutionHistoryView } from "#execution/history-view.js";+import { resolveRuntimeCompiledArtifactsVersionedCacheKey } from "#runtime/cache-key.js";+import { createWorkflowRuntime } from "#execution/workflow-runtime.js";+import { runModelCallBatch } from "#execution/model-call-batching.js";+import {+ createCancelledModelCallBatchResult,+ type CompletedModelCallCheckpoint,+} from "#execution/cancelled-model-call-batch.js";+import * as activityCohort from "#execution/activity-cohort.js";++function channelDeliveryErrorCode(error: unknown): string {+ if (typeof error === "object" && error !== null && "code" in error) {+ const code = (error as { readonly code?: unknown }).code;+ if (typeof code === "string" && code.length > 0) return code;+ }+ return "CHANNEL_DELIVERY_FAILED";+}++export type { TurnStepInput };++/** Runs a bounded batch of harness model steps inside one durable `"use step"` boundary. */+export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResult> {+ "use step";+ return runSessionStep(rawInput);+}++async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult> {+ // The delivery as accepted, before authorization callbacks are matched out of it.+ const rawDelivery = input.input?.delivery;+ let delivery = rawDelivery;+ const runtimeResults = input.input?.runtimeResults;++ 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);++ // Populate the callback base URL so getHookUrl() works during tool+ // execution, preferring eve's active local origin over metadata fallback.+ try {+ const { getWorkflowMetadata } = await import("#compiled/@workflow/core/index.js");+ const metadata = getWorkflowMetadata();+ if (typeof metadata.url === "string") {+ ctx.set(CallbackBaseUrlKey, resolveWorkflowCallbackBaseUrl(metadata.url));+ }+ } catch {+ // Outside a workflow context (e.g. tests) — getHookUrl will return undefined.+ }++ const pendingAuth = getPendingAuthorization(durableSession.state);+ let completedAuths: ReturnType<typeof matchAuthorizationCallbacks>["matches"] | undefined;+ if (pendingAuth && delivery !== undefined) {+ const { matches, remainingPayloads } = matchAuthorizationCallbacks(+ pendingAuth,+ delivery.payloads,+ );+ delivery = { ...delivery, payloads: remainingPayloads };+ if (matches.length > 0) {+ const matchedAttemptIds = activityCohort.restoreAuthorizationActivity({+ ctx,+ matches,+ pending: pendingAuth,+ });+ const authResults = matches.map((match) => match.result);+ ctx.set(PendingAuthorizationResultKey, authResults);+ durableSession = {+ ...durableSession,+ state: clearPendingAuthorization(durableSession.state, matchedAttemptIds),+ };+ completedAuths = matches;+ if (remainingPayloads.length === 0) delivery = undefined;+ }+ }++ // Apply deliver-time auth ferried via `resumeHook` (initial-turn+ // input has no auth; it was seeded by buildRunContext).+ if (delivery?.auth !== undefined) {+ ctx.set(AuthKey, delivery.auth ?? null);+ }+ const backgroundTaskDelivery = getBackgroundTaskDelivery(delivery);+ const initialSession = hydrateDurableSession({+ compactionOverrides: {+ thresholdPercent: effectiveAgent.thresholdPercent,+ },+ durable: durableSession,+ turnAgent: effectiveAgent.turnAgent,+ });+ const history = createExecutionHistoryView(initialSession);+ const instrumentation = bindSessionInstrumentation({+ agentName: effectiveAgent.turnAgent.id,+ ctx,+ rootSessionId: initialSession.rootSessionId ?? initialSession.sessionId,+ sessionId: initialSession.sessionId,+ });+ 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({+ agentName: bundle.turnAgent.id,+ ctx,+ delivery: rawDelivery,+ rootSessionId: initialSession.rootSessionId ?? initialSession.sessionId,+ sequence: initialEmissionState.sequence,+ sessionId: initialSession.sessionId,+ turnId: activeTurnId(initialEmissionState),+ }),+ );+ }++ const failChannelDeliveries = async (error: unknown): Promise<void> => {+ await contextStorage.run(ctx, () =>+ instrumentation?.instrumentChannelDelivery({+ ctx,+ error,+ errorCode: channelDeliveryErrorCode(error),+ includeTurn: false,+ outcome: "failed",+ }),+ );+ await instrumentation?.flush();+ };+ const sink = createSessionEventSink({+ abortSignal: input.abortSignal,+ adapter,+ bundle,+ ctx,+ effectiveAgent,+ instrumentation,+ isFirstTurn: initialEmissionState.sequence === 0,+ sessionWritable: input.sessionWritable,+ sessionId: initialSession.sessionId,+ });+ const { adapterCtx, dynamicConnections, effectiveNode, handleEvent } = sink;+ try {+ // 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;+ if (delivery !== undefined) {+ const results: StepInput[] = [];+ try {+ for (const payload of delivery.payloads) {+ const result = adapter.deliver+ ? await adapter.deliver(payload, adapterCtx)+ : defaultDeliverResult(payload);++ if (result !== undefined && result !== null) {+ results.push(+ backgroundTaskDelivery === undefined ? result : markBackgroundTaskStepInput(result),+ );+ }+ }+ } catch (error) {+ await failChannelDeliveries(error);+ throw error;+ }+ resolved = results.length === 0 ? undefined : results.reduce(coalesceTurnInputs);+ }+ if (runtimeResults !== undefined) {+ if (runtimeResults.acceptedAtMsByCallId !== undefined) {+ ctx.set(RuntimeActionSettlementTimesKey, runtimeResults.acceptedAtMsByCallId);+ }+ resolved = { ...resolved, runtimeActionResults: runtimeResults.results };+ }++ let taskRootTurnId: string | undefined;+ if (resolved !== undefined && backgroundTaskDelivery !== undefined) {+ const taskContext = resolveTaskDeliveryContext({+ state: durableSession.state,+ taskDeliveryId: backgroundTaskDelivery.taskDeliveryId,+ });+ if (taskContext !== undefined) {+ ctx.set(TurnTaskDeliveryKey, taskContext.phase);+ taskRootTurnId = taskContext.rootTurnId;+ resolved = {+ ...resolved,+ context: [...(resolved.context ?? []), taskContext.context],+ };+ }+ }++ activityCohort.updateActivityRootForDelivery({+ activeTurnId: activeTurnId(initialEmissionState),+ ctx,+ delivery: rawDelivery,+ sessionState: durableSession.state,+ taskRootTurnId,+ });++ const taskDeliveryPhase = ctx.get(TurnTaskDeliveryKey);+ if (taskDeliveryPhase === "none" || taskDeliveryPhase === "initiating") {+ const taskContext = resolveInitiatingTaskContext({+ state: durableSession.state,+ turnId: activeTurnId(initialEmissionState),+ });+ if (taskContext !== undefined) {+ ctx.set(TurnTaskDeliveryKey, taskContext.phase);+ }+ }++ if (rawDelivery !== undefined) {+ const updatedAdapter = { ...adapter, state: { ...adapterCtx.state } };+ setChannelContext(ctx, updatedAdapter);+ }++ if (delivery !== undefined && resolved === undefined) {+ await contextStorage.run(ctx, () =>+ instrumentation?.instrumentChannelDelivery({+ ctx,+ includeTurn: false,+ outcome: "completed",+ }),+ );+ await instrumentation?.flush();+ const aliased = reconcileSessionContinuationToken(ctx, initialSession);+ const nextSerializedContext = serializeContext(ctx);+ const nextState =+ aliased === initialSession+ ? input.sessionState+ : createDurableSessionState({ session: aliased });++ return {+ action: "park",+ ...derivePendingState(aliased),+ serializedContext: nextSerializedContext,+ sessionState: nextState,+ };+ }++ const dynamicSubagentResolvers = bundle.subagentRegistry.dynamicResolvers ?? [];+ const dynamicToolResolvers = bundle.resolvedAgent.dynamicToolResolvers ?? [];+ const runtimeIdentity = buildRuntimeIdentity(effectiveNode);+ try {+ const deploymentId = process.env.VERCEL_DEPLOYMENT_ID?.trim();+ const dynamicRuntimeRevision = deploymentId+ ? `deployment:${deploymentId}`+ : await resolveRuntimeCompiledArtifactsVersionedCacheKey(bundle.compiledArtifactsSource);+ const sessionStarted = initialEmissionState.sessionStarted;++ ctx.setVirtualContext(StaticModelReferenceKey, effectiveAgent.turnAgent.model ?? null);+ if (!sessionStarted) {+ ctx.set(SessionDynamicSubagentRuntimeRevisionKey, dynamicRuntimeRevision);+ ctx.set(SessionDynamicToolRuntimeRevisionKey, dynamicRuntimeRevision);+ } else {+ const refreshEvent = createSessionStartedEvent({ runtime: runtimeIdentity });+ await Promise.all([+ refreshDynamicSessionSubagentsForRuntimeRevision({+ ctx,+ resolvers: dynamicSubagentResolvers,+ event: refreshEvent,+ messages: history.initial.messages,+ runtimeRevision: dynamicRuntimeRevision,+ }),+ refreshDynamicSessionToolsForRuntimeRevision({+ ctx,+ resolvers: dynamicToolResolvers,+ event: refreshEvent,+ messages: history.initial.messages,+ runtimeRevision: dynamicRuntimeRevision,+ }),+ ]);+ await rebindMissingCompiledDynamicToolCallbacks({+ ctx,+ event: createTurnStartedEvent({+ sequence: initialEmissionState.sequence,+ turnId: activeTurnId(initialEmissionState),+ }),+ messages: history.initial.messages,+ resolvers: dynamicToolResolvers,+ });+ }+ } catch (error) {+ await failChannelDeliveries(error);+ throw error;+ }++ const mode = ctx.require(ModeKey);+ const modelCallsPerStep =+ bundle.resolvedAgent.config?.experimental?.workflow?.modelCallsPerStep ?? 1;+ const capabilities = ctx.get(CapabilitiesKey);++ const runHarnessStep = async (+ lifecycleSession: HarnessSession,+ stepInput: StepInput | undefined,+ ): Promise<StepResult> => {+ const refreshedSession = refreshSessionFromTurnAgent({+ compactionOverrides: {+ thresholdPercent: effectiveAgent.thresholdPercent,+ },+ session: lifecycleSession,+ turnAgent: effectiveAgent.turnAgent,+ });+ const modelSession = refreshedSession;++ const step = createExecutionNodeStep({+ abortSignal: input.abortSignal,+ capabilities,+ clearOnly: input.input?.control === "clear",+ compactOnly: input.input?.control === "compact",+ createRuntime: createWorkflowRuntime,+ handleEvent,+ historyProjector: history.projector,+ historyView: history.prepare(modelSession),+ instrumentation,+ mode,+ modelResolutionScope: {+ moduleMap: bundle.moduleMap,+ nodeId: bundle.nodeId,+ },+ node: effectiveNode,+ });+ return step(modelSession, stepInput);+ };++ let completedModelCall: CompletedModelCallCheckpoint | undefined;+ let stepResult: StepResult;+ try {+ // A signal already aborted at entry (cancellation during an in-line+ // runtime-action wait) must settle before the park-resume stages run,+ // or the pending batch would re-park and later re-dispatch.+ throwIfTurnAborted(input.abortSignal);+ stepResult = await runModelCallBatch({+ initialInput: resolved,+ initialSession,+ modelCallsPerStep,+ runStep: async ({ firstCall, session, stepInput }) => {+ const result = await runBackgroundStep(ctx, session, async (enrichedSession) => {+ ctx.setVirtualContext(HandleEventKey, handleEvent);+ ctx.setVirtualContext(StaticModelReferenceKey, effectiveAgent.turnAgent.model ?? null);+ let schemaSession = firstCall+ ? resolveEffectiveOutputSchema({+ agentOutputSchema: effectiveAgent.turnAgent.outputSchema,+ input: resolved,+ mode,+ session: enrichedSession,+ })+ : enrichedSession;+ await dynamicConnections.rehydrate(+ getHarnessEmissionState(schemaSession.state),+ runtimeIdentity,+ isHarnessBetweenTurns(schemaSession),+ );+ if (firstCall && completedAuths) {+ let emissionState = getHarnessEmissionState(schemaSession.state);+ if (isHarnessBetweenTurns(schemaSession)) {+ prepareDynamicInstructionPreamble(ctx, history.messages(schemaSession));+ let instructionMessages: readonly UserModelMessage[] = [];+ const traceContext = await prepareWorkflowPreambleTrace({+ emissionState,+ instrumentation,+ });+ try {+ emissionState = await emitTurnPreamble(+ handleEvent,+ {},+ emissionState,+ runtimeIdentity,+ traceContext,+ );+ } finally {+ instructionMessages = drainDynamicInstructionUserMessages(ctx);+ schemaSession = {+ ...schemaSession,+ history: [...schemaSession.history, ...instructionMessages],+ };+ }+ schemaSession = setHarnessEmissionState(schemaSession, emissionState);+ }+ for (const { authorization, result } of completedAuths) {+ const candidateId = pendingAuth?.challenges.find(+ (challenge) => challenge.attemptId === result.attemptId,+ )?.candidateId;+ await handleEvent(+ createAuthorizationCompletedEvent({+ attemptId: result.attemptId,+ authorization,+ candidateId,+ name: result.name,+ outcome: "authorized",+ sequence: emissionState.sequence,+ stepIndex: emissionState.stepIndex,+ turnId: emissionState.turnId,+ }),+ );+ }+ }++ return runHarnessStep(schemaSession, stepInput);+ });+ throwIfTurnAborted(input.abortSignal);+ completedModelCall = { result, serializedContext: serializeContext(ctx) };+ return result;+ },+ });+ } catch (error) {+ if (!isTurnCancellation(error) && input.abortSignal?.aborted !== true) {+ await failChannelDeliveries(error);+ throw error;+ }+ const retained = readRetainedBackgroundToolResult(ctx);+ instrumentation?.rememberBackgroundTasks(retained?.backgroundTasks ?? []);+ return createCancelledModelCallBatchResult({+ beforeBatchContext: input.serializedContext,+ checkpoint: completedModelCall,+ ctx,+ initialSession,+ stepInput: resolved,+ });+ }++ instrumentation?.rememberBackgroundTasks(stepResult.backgroundTasks ?? []);+ // Re-stamp the current address after handlers add a continuation alias.+ const aliased = reconcileSessionContinuationToken(ctx, stepResult.session);+ agentTraceState.pruneAgentTraceState(ctx, aliased.sessionId, aliased.state);+ const nextSerializedContext = serializeContext(ctx);+ stepResult = { ...stepResult, session: aliased };++ const durableResult = resolveSessionStepResult(+ stepResult,+ nextSerializedContext,+ mode,+ input.serializedContext,+ );+ if (durableResult.action === "done") await sink.close();+ return durableResult;+ } finally {+ sink.release();+ }+}diff --git a/packages/eve/src/execution/session/turn.test.ts b/packages/eve/src/execution/session/turn.test.tsnew file mode 100644index 000000000..426b078b4--- /dev/null+++ b/packages/eve/src/execution/session/turn.test.ts@@ -0,0 +1,441 @@+import { createTestSessionState } from "#internal/testing/session-state.js";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { DurableSessionState } from "#execution/durable-session-store.js";+import type { SessionInbox, SessionInboxPayload } from "#execution/session-inbox/inbox.js";+import { SessionInputQueue } from "#execution/session/input-queue.js";+import { SessionExecution } from "#execution/session/turn.js";+import { SessionStateCursor } from "#execution/session/state-cursor.js";+import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-step.js";+import { acknowledgeDelegatedTasksStep } from "#execution/tasks/parent/delegate.js";+import { turnStep } from "#execution/session/turn-step.js";+import type { DeliverHookPayload } from "#channel/types.js";+import { dispatchCoordinationStep } from "#execution/coordination-dispatch-step.js";+import { routeDeliverToChildren } from "#execution/route-child-delivery.js";++vi.mock("#compiled/@workflow/core/index.js", async (importOriginal) => ({+ ...(await importOriginal()),+ getWorkflowMetadata: () => ({ url: "https://parent.example" }),+}));+vi.mock("#execution/coordination-dispatch-step.js", () => ({ dispatchCoordinationStep: vi.fn() }));++vi.mock("#execution/session/turn-step.js", () => ({+ turnStep: vi.fn(),+}));+vi.mock("#execution/tasks/parent/delegate.js", () => ({+ acknowledgeDelegatedTasksStep: vi.fn(),+}));+vi.mock("#execution/cancel-descendant-turns-step.js", () => ({+ cancelDescendantTurnsStep: vi.fn(),+}));+vi.mock("#execution/route-child-delivery.js", () => ({+ routeDeliverToChildren: vi.fn(),+}));++beforeEach(() => {+ vi.mocked(routeDeliverToChildren)+ .mockReset()+ .mockImplementation(async ({ delivery, serializedContext, sessionState }) => ({+ kind: "continue",+ remainder: delivery,+ serializedContext,+ sessionState,+ }));+});+afterEach(() => vi.restoreAllMocks());++describe("SessionExecution background task checkpoints", () => {+ it("cancels an admitted workflow action when cancellation already arrived at the step boundary", async () => {+ const sessionState = state("");+ const inbox: SessionInbox = {+ claimedTokens: [],+ claimSessionHook: vi.fn(),+ claimSessionHooks: vi.fn(),+ drain: vi+ .fn()+ .mockReturnValueOnce([{ kind: "cancel" }])+ .mockReturnValue([]),+ hasPending: vi.fn(() => false),+ next: vi.fn(() => new Promise<never>(() => {})),+ onInterrupt: vi.fn(() => () => {}),+ restore: vi.fn(),+ };+ const execution = createExecution({ inbox, sessionState });+ vi.mocked(turnStep)+ .mockReset()+ .mockResolvedValue({+ action: "park",+ pendingCoordinationCallIds: ["hold-call"],+ hasPendingAuthorization: false,+ hasPendingInputBatch: false,+ serializedContext: {},+ sessionState,+ });+ vi.mocked(dispatchCoordinationStep).mockResolvedValue({+ results: [],+ pendingTasks: [],+ sessionState,+ });++ await expect(+ execution.runTurn({+ delivery: { kind: "deliver", payloads: [{ message: "Start Alice's deployment" }] },+ }),+ ).resolves.toMatchObject({ cancelled: true, kind: "park" });+ expect(dispatchCoordinationStep).toHaveBeenCalledTimes(1);+ expect(inbox.next).not.toHaveBeenCalled();+ expect(cancelDescendantTurnsStep).toHaveBeenCalledWith({ serializedContext: {}, sessionState });+ });++ it("consumes the cancelling command while retaining accepted follow-ups", async () => {+ const sessionState = state("");+ const queue = new SessionInputQueue();+ const followUp: DeliverHookPayload = {+ kind: "deliver",+ payloads: [{ message: "Continue after cancellation." }],+ turnPolicy: "queue",+ };+ let interrupt: ((payload: SessionInboxPayload) => void) | undefined;+ const inbox: SessionInbox = {+ claimedTokens: [],+ claimSessionHook: vi.fn(),+ claimSessionHooks: vi.fn(),+ drain: vi+ .fn()+ .mockReturnValueOnce([followUp, { kind: "cancel" }])+ .mockReturnValue([]),+ hasPending: vi.fn(() => false),+ next: vi.fn(() => new Promise<never>(() => {})),+ onInterrupt: vi.fn((handler) => {+ interrupt = handler;+ return () => {};+ }),+ restore: vi.fn(),+ };+ const execution = createExecution({ inbox, queue, sessionState });+ vi.mocked(turnStep).mockImplementationOnce(async (input) => {+ interrupt?.({ kind: "cancel" });+ await vi.waitFor(() => expect(input.abortSignal?.aborted).toBe(true));+ return {+ action: "cancelled",+ serializedContext: input.serializedContext,+ sessionState: input.sessionState,+ };+ });++ await expect(+ execution.runTurn({+ delivery: { kind: "deliver", payloads: [{ message: "Start the work." }] },+ }),+ ).resolves.toEqual({ cancelled: true, kind: "park" });++ expect(inbox.restore).not.toHaveBeenCalled();+ expect(queue.takeNext(new Map())).toMatchObject({ delivery: followUp, kind: "turn" });+ });++ it("steers a continuing turn with user input while retaining background notifications for cohort routing", async () => {+ const background: DeliverHookPayload = {+ kind: "deliver",+ taskDeliveryId: "task-1:completed",+ payloads: [{ message: "Background task task-1 is completed." }],+ };+ const steering: DeliverHookPayload = {+ kind: "deliver",+ payloads: [{ message: "Include Alice's update." }],+ };+ const queue = new SessionInputQueue();+ const inbox: SessionInbox = {+ claimedTokens: [],+ claimSessionHook: vi.fn(),+ claimSessionHooks: vi.fn(),+ drain: vi.fn().mockReturnValueOnce([background, steering]).mockReturnValue([]),+ hasPending: vi.fn(() => false),+ next: vi.fn(() => new Promise<never>(() => {})),+ onInterrupt: vi.fn(() => () => {}),+ restore: vi.fn(),+ };+ const execution = createExecution({ inbox, queue, sessionState: state("") });+ vi.mocked(turnStep)+ .mockReset()+ .mockImplementationOnce(async (input) => ({+ action: "continue",+ serializedContext: input.serializedContext,+ sessionState: input.sessionState,+ }))+ .mockImplementation(async (input) => ({+ action: "park",+ hasPendingAuthorization: false,+ hasPendingInputBatch: false,+ serializedContext: input.serializedContext,+ sessionState: input.sessionState,+ }));++ await execution.runTurn({+ delivery: { kind: "deliver", payloads: [{ message: "Start the work." }] },+ });++ expect(turnStep).toHaveBeenCalledTimes(2);+ expect(vi.mocked(turnStep).mock.calls[1]?.[0].input).toEqual({ delivery: steering });+ expect(queue.pendingCount).toBe(1);+ });++ it("applies steering accepted during a blocking action before its result continues the turn", async () => {+ const sessionState = state("");+ const steering: DeliverHookPayload = {+ kind: "deliver",+ payloads: [{ message: "Include Alice's update." }],+ };+ const actionResult = {+ callId: "hold-call",+ kind: "tool-result" as const,+ output: { deployed: true },+ toolName: "deploy",+ };+ const inbox: SessionInbox = {+ claimedTokens: [],+ claimSessionHook: vi.fn(),+ claimSessionHooks: vi.fn(),+ drain: vi.fn().mockReturnValueOnce([steering]).mockReturnValue([]),+ hasPending: vi.fn(() => false),+ next: vi.fn(() => new Promise<never>(() => {})),+ onInterrupt: vi.fn(() => () => {}),+ restore: vi.fn(),+ };+ const execution = createExecution({ inbox, sessionState });+ vi.mocked(turnStep)+ .mockReset()+ .mockResolvedValueOnce({+ action: "park",+ hasPendingAuthorization: false,+ hasPendingInputBatch: false,+ pendingCoordinationCallIds: ["hold-call"],+ serializedContext: {},+ sessionState,+ })+ .mockResolvedValueOnce({+ action: "done",+ output: "done",+ serializedContext: {},+ sessionState,+ });+ vi.mocked(dispatchCoordinationStep)+ .mockReset()+ .mockResolvedValue({+ pendingTasks: [],+ results: [actionResult],+ sessionState,+ });++ await expect(+ execution.runTurn({+ delivery: { kind: "deliver", payloads: [{ message: "Start the work." }] },+ }),+ ).resolves.toMatchObject({ kind: "done", output: "done" });++ // Steering and the blocking action's result travel in one step, steering first.+ expect(turnStep).toHaveBeenCalledTimes(2);+ expect(vi.mocked(turnStep).mock.calls[1]?.[0].input).toMatchObject({+ delivery: steering,+ runtimeResults: { results: [actionResult] },+ });+ expect(dispatchCoordinationStep).toHaveBeenCalledTimes(1);+ });++ it("treats input that arrives after a settled turn as the next turn", async () => {+ const followUp: DeliverHookPayload = {+ kind: "deliver",+ payloads: [{ message: "One more thing." }],+ };+ const queue = new SessionInputQueue();+ const inbox: SessionInbox = {+ claimedTokens: [],+ claimSessionHook: vi.fn(),+ claimSessionHooks: vi.fn(),+ drain: vi.fn().mockReturnValueOnce([followUp]).mockReturnValue([]),+ hasPending: vi.fn(() => false),+ next: vi.fn(() => new Promise<never>(() => {})),+ onInterrupt: vi.fn(() => () => {}),+ restore: vi.fn(),+ };+ const execution = createExecution({ inbox, queue, sessionState: state("") });+ vi.mocked(turnStep)+ .mockReset()+ .mockImplementation(async (input) => ({+ action: "park",+ hasPendingAuthorization: false,+ hasPendingInputBatch: false,+ serializedContext: input.serializedContext,+ sessionState: input.sessionState,+ settled: { output: "Done." },+ }));++ await expect(+ execution.runTurn({+ delivery: { kind: "deliver", payloads: [{ message: "Start the work." }] },+ }),+ ).resolves.toMatchObject({ kind: "park", settled: { output: "Done." } });++ expect(turnStep).toHaveBeenCalledTimes(1);+ expect(queue.pendingCount).toBe(1);+ });++ it("routes a task-owned answer to a descendant while waiting for runtime results", async () => {+ const sessionState = { ...state(""), hasProxyInputRequests: true };+ const taskAnswer: DeliverHookPayload = {+ kind: "deliver",+ payloads: [{ inputResponses: [{ requestId: "child-request", text: "blue" }] }],+ taskDeliveryId: "task-1:child-request",+ };+ const runtimePayloads = [taskAnswer, { kind: "cancel" as const }];+ const queue = new SessionInputQueue();+ const inbox: SessionInbox = {+ claimedTokens: [],+ claimSessionHook: vi.fn(),+ claimSessionHooks: vi.fn(),+ drain: vi.fn(() => []),+ hasPending: vi.fn(() => false),+ next: vi.fn(async () => runtimePayloads.shift()),+ onInterrupt: vi.fn(() => () => {}),+ restore: vi.fn(),+ };+ const execution = createExecution({ inbox, queue, sessionState });+ vi.mocked(turnStep).mockResolvedValue({+ action: "park",+ hasPendingAuthorization: false,+ hasPendingInputBatch: false,+ pendingCoordinationCallIds: ["child-call"],+ serializedContext: {},+ sessionState,+ });+ vi.mocked(dispatchCoordinationStep).mockResolvedValue({+ pendingTasks: [],+ results: [],+ sessionState,+ });+ vi.mocked(routeDeliverToChildren).mockResolvedValue({+ kind: "continue",+ remainder: undefined,+ serializedContext: {},+ sessionState: { ...sessionState, hasProxyInputRequests: false },+ });++ await expect(+ execution.runTurn({+ delivery: { kind: "deliver", payloads: [{ message: "Start the work." }] },+ }),+ ).resolves.toEqual({ cancelled: true, kind: "park" });++ expect(routeDeliverToChildren).toHaveBeenCalledWith(+ expect.objectContaining({ delivery: taskAnswer }),+ );+ expect(queue.pendingCount).toBe(0);+ });++ it.each(["cancelled", "done"] as const)(+ "retains task observability when a %s step races cancellation",+ async (action) => {+ const initialState = state("");+ const backgroundState = state("http:background");+ const completedState = state("http:completed");+ const tasks = [+ { callId: "call-1", taskId: "task-1", taskInboxToken: "inbox-1", taskRunId: "run-1" },+ ];+ const observability = {+ "eve.harness.agentTrace": { actions: { "action-1": {} }, sessions: {}, turns: {} },+ "eve.harness.instrumentationActionScopes": {+ "action-1": { scope: { turnId: "turn_0" }, taskId: "task-1" },+ },+ "eve.harness.instrumentationState": { "sink\0action-1": { value: "open" } },+ };+ const backgroundContext = { ...observability, state: "before" };+ const completedContext = { ...observability, state: "completed" };+ let interrupt: ((payload: SessionInboxPayload) => void) | undefined;+ const inbox: SessionInbox = {+ claimedTokens: [],+ claimSessionHook: vi.fn(),+ claimSessionHooks: vi.fn(),+ drain: vi+ .fn()+ .mockReturnValueOnce([{ kind: "cancel" }])+ .mockReturnValue([]),+ hasPending: vi.fn(() => false),+ next: vi.fn(() => new Promise<never>(() => {})),+ onInterrupt: vi.fn((handler) => {+ interrupt = handler;+ return () => {};+ }),+ restore: vi.fn(),+ };+ const execution = createExecution({+ inbox,+ serializedContext: { state: "before" },+ sessionState: initialState,+ });+ const apply = vi.spyOn(SessionStateCursor.prototype, "apply");+ vi.mocked(acknowledgeDelegatedTasksStep).mockImplementation(async () => {+ expect(execution.cursor.serializedContext).toEqual(backgroundContext);+ expect(execution.cursor.sessionState).toBe(backgroundState);+ });+ vi.mocked(turnStep).mockImplementationOnce(async (input) => {+ // The pump pushes the accepted cancel while this step is still running.+ interrupt?.({ kind: "cancel" });+ await vi.waitFor(() => expect(input.abortSignal?.aborted).toBe(true));+ return {+ action,+ backgroundTaskContext: backgroundContext,+ backgroundTaskState: backgroundState,+ backgroundTasks: tasks,+ serializedContext: completedContext,+ sessionState: completedState,+ };+ });++ const result = await execution.runTurn({+ delivery: { kind: "deliver", payloads: [{ message: "work" }] },+ });+ expect(result).toEqual({+ cancelled: true,+ kind: "park",+ });+ expect(apply.mock.calls[0]?.[0]).toEqual({+ serializedContext: backgroundContext,+ sessionState: backgroundState,+ });+ expect(acknowledgeDelegatedTasksStep).toHaveBeenCalledWith({ tasks });+ expect(cancelDescendantTurnsStep).toHaveBeenCalledWith({+ serializedContext: completedContext,+ sessionState: backgroundState,+ });+ },+ );+});++function createExecution(input: {+ readonly inbox: SessionInbox;+ readonly queue?: SessionInputQueue;+ readonly serializedContext?: Record<string, unknown>;+ readonly sessionState: DurableSessionState;+}): SessionExecution {+ const cursor = new SessionStateCursor({+ inbox: input.inbox,+ sessionWritable: new WritableStream<Uint8Array>(),+ serializedContext: input.serializedContext ?? {},+ sessionState: input.sessionState,+ });+ return new SessionExecution({+ cursor,+ inbox: input.inbox,+ mode: "conversation",+ queue: input.queue ?? new SessionInputQueue(),+ sessionId: input.sessionState.sessionId,+ });+}++function state(continuationToken: string): DurableSessionState {+ return createTestSessionState({+ continuationToken,+ emissionState: { sequence: 0, sessionStarted: true, stepIndex: 0, turnId: "turn_0" },+ hasProxyInputRequests: false,+ sessionId: "session-1",+ version: 1,+ });+}diff --git a/packages/eve/src/execution/session/turn.ts b/packages/eve/src/execution/session/turn.tsnew file mode 100644index 000000000..dc65eed4d--- /dev/null+++ b/packages/eve/src/execution/session/turn.ts@@ -0,0 +1,396 @@+import { getWorkflowMetadata } from "#compiled/@workflow/core/index.js";++import type { DeliverHookPayload, SessionCapabilities } from "#channel/types.js";+import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-step.js";+import { 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 {+ sessionCommandHookToken,+ sessionInboxHookToken,+} from "#execution/session-inbox/address.js";+import type { SessionInboxPayload, SessionInboxReader } from "#execution/session-inbox/inbox.js";+import {+ admitSessionInboxPayload,+ applySessionCancellation,+} from "#execution/session/admission.js";+import type { SessionStateCursor } from "#execution/session/state-cursor.js";+import { acknowledgeDelegatedTasksStep } from "#execution/tasks/parent/delegate.js";+import { handleWorkflowToolRunMessage } from "#execution/session-workflow-tool-run.js";+import type { WorkflowToolRunMessage } from "#execution/tools/workflow/messages.js";+import type {+ DurableStepResult,+ RuntimeActionResultStepInput,+ TurnOutcome,+ TurnStepPayload,+} from "#execution/session/turn-step-types.js";+import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";+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 {+ isInboxSubagentResultFromRecordedWorkflowToolRun,+ isInboxToolResultFromRecordedWorkflowToolRun,+} from "#harness/workflow-tool-runs.js";+import { isInboxSubagentResultFromRunningHandle } from "#subagents/handles/query.js";+import { resolveRuntimeActionResultsForCallIds } from "#runtime/actions/results.js";+import type { RunMode } from "#shared/run-mode.js";+import type { RuntimeActionResult } from "#shared/action-types.js";++const TASK_MODE_WAIT_ERROR_MESSAGE = "Task mode cannot wait for follow-up input (`next: null`).";++export interface SessionExecutionInput {+ readonly capabilities?: SessionCapabilities;+ readonly cursor: SessionStateCursor;+ readonly inbox: SessionInboxReader;+ readonly mode: RunMode;+ readonly queue: SessionInputQueue;+ readonly sessionId: string;+}++/**+ * Executes conversational turns inside the owning session workflow: runs+ * `turnStep`, services the inbox at committed boundaries, coordinates waits,+ * and settles locally. There is no child run and no transport protocol.+ */+export class SessionExecution {+ private readonly input: SessionExecutionInput;++ constructor(input: SessionExecutionInput) {+ this.input = input;+ }++ get cursor(): SessionStateCursor {+ return this.input.cursor;+ }++ async runTurn(delivery: TurnStepPayload | undefined): Promise<TurnOutcome> {+ const turn = new ActiveTurn(this.input, delivery?.delivery?.caller?.callId);+ try {+ return await this.runTurnSteps(turn, delivery);+ } finally {+ turn.dispose();+ }+ }++ private async runTurnSteps(+ turn: ActiveTurn,+ delivery: TurnStepPayload | undefined,+ ): Promise<TurnOutcome> {+ let nextStepInput: TurnStepPayload | undefined = delivery;++ while (true) {+ const { cursor } = this.input;+ const beforeStepContext = cursor.serializedContext;+ const result: DurableStepResult = await turnStep(+ cursor.createStepInput(nextStepInput, turn.signal),+ );+ const pendingCallIds =+ result.action === "park" ? result.pendingCoordinationCallIds : undefined;+ const hasBackgroundTasks = (result.backgroundTasks?.length ?? 0) > 0;++ if (hasBackgroundTasks) {+ if (result.backgroundTaskState === undefined) {+ throw new Error("Background tasks were returned without their committed session state.");+ }+ await cursor.apply({+ serializedContext: result.backgroundTaskContext ?? beforeStepContext,+ sessionState: result.backgroundTaskState,+ });+ await acknowledgeDelegatedTasksStep({ tasks: result.backgroundTasks ?? [] });+ }++ await cursor.apply({+ serializedContext: result.serializedContext,+ sessionState:+ result.action === "cancelled" || turn.signal.aborted+ ? (result.backgroundTaskState ?? result.sessionState)+ : result.sessionState,+ });+ await turn.admitBoundary();++ if (result.action === "cancelled") return await this.finishCancelledTurn();+ if (turn.signal.aborted && (pendingCallIds === undefined || hasBackgroundTasks)) {+ return await this.finishCancelledTurn();+ }++ if (result.action === "done") {+ return {+ isError: result.isError,+ kind: "done",+ output: result.output ?? "",+ usage: result.usage,+ usageDelta: result.usageDelta,+ };+ }++ if (pendingCallIds !== undefined && result.action === "park") {+ const dispatchResult = await dispatchCoordinationStep({+ action: result.action,+ callbackBaseUrl: resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url),+ workflowToolRunOwner: {+ inbox: sessionInboxHookToken(sessionCommandHookToken(this.input.sessionId)),+ },+ sessionWritable: cursor.sessionWritable,+ serializedContext: cursor.serializedContext,+ sessionState: cursor.sessionState,+ });+ const initialAcceptedAtMs = dispatchResult.results.length === 0 ? undefined : Date.now();+ await cursor.apply(dispatchResult);+ await acknowledgeDelegatedTasksStep({ tasks: dispatchResult.pendingTasks });++ const runtimeResults = await this.waitForRuntimeActionResults({+ initialAcceptedAtMs,+ initialResults: dispatchResult.results,+ pendingCallIds,+ turn,+ });+ if (runtimeResults === "cancelled") return await this.finishCancelledTurn();+ // Steering accepted during the wait is appended ahead of the result in+ // the same step, so the model sees it before the blocking action resolves.+ nextStepInput = { delivery: await turn.takeSteering(), runtimeResults };+ continue;+ }++ if (result.action === "park") {+ const canPark =+ result.hasPendingAuthorization ||+ (result.hasPendingInputBatch && this.input.capabilities?.requestInput === true) ||+ this.input.mode === "conversation";+ if (!canPark) throw new Error(TASK_MODE_WAIT_ERROR_MESSAGE);+ return {+ authorizationAttemptIds: result.authorizationAttemptIds,+ kind: "park",+ settled: result.settled,+ };+ }++ const steering = await turn.takeSteering();+ nextStepInput = steering === undefined ? undefined : { delivery: steering };+ }+ }++ async handleWorkflowMessage(+ message: WorkflowToolRunMessage,+ ): Promise<RuntimeActionResult | undefined> {+ return await handleWorkflowToolRunMessage({+ callbackMetadataUrl: getWorkflowMetadata().url,+ cursor: this.input.cursor,+ message,+ });+ }++ private async finishCancelledTurn(): Promise<TurnOutcome> {+ const { cursor } = this.input;+ await cancelDescendantTurnsStep({+ serializedContext: cursor.serializedContext,+ sessionState: cursor.sessionState,+ });+ return { cancelled: true, kind: "park" };+ }++ private async waitForRuntimeActionResults(input: {+ readonly initialAcceptedAtMs: number | undefined;+ readonly initialResults: readonly RuntimeActionResult[];+ readonly pendingCallIds: readonly string[];+ readonly turn: ActiveTurn;+ }): Promise<RuntimeActionResultStepInput | "cancelled"> {+ const results: RuntimeActionResult[] = [...input.initialResults];+ const acceptedAtMsByCallId = new Map<string, number>();+ if (input.initialAcceptedAtMs !== undefined) {+ for (const result of results)+ acceptedAtMsByCallId.set(result.callId, input.initialAcceptedAtMs);+ }++ while (true) {+ const ready = resolveRuntimeActionResultsForCallIds({+ pendingCallIds: input.pendingCallIds,+ results,+ });+ if (ready !== undefined) {+ return {+ acceptedAtMsByCallId: Object.fromEntries(+ ready.map((result) => [result.callId, acceptedAtMsByCallId.get(result.callId)!]),+ ),+ results: ready,+ };+ }++ const next = await input.turn.nextRuntimeEvent();+ if (next === "cancelled") return next;+ if (next.kind === "runtime-action-result") {+ const snapshot = this.input.cursor.sessionState.snapshot.session.state;+ const accepted = next.results.filter((result) => {+ if (result.kind === "tool-result") {+ return isInboxToolResultFromRecordedWorkflowToolRun(snapshot, result);+ }+ if (result.kind !== "subagent-result") return false;+ return (+ (result.origin === "child" &&+ isInboxSubagentResultFromRunningHandle(snapshot, result)) ||+ isInboxSubagentResultFromRecordedWorkflowToolRun(snapshot, result)+ );+ });+ if (accepted.length > 0) {+ const acceptedAtMs = Date.now();+ results.push(...accepted);+ for (const result of accepted) acceptedAtMsByCallId.set(result.callId, acceptedAtMs);+ }+ continue;+ }++ const result = await this.handleWorkflowMessage(next.message);+ if (result !== undefined) {+ results.push(result);+ acceptedAtMsByCallId.set(result.callId, Date.now());+ }+ }+ }+}++type RuntimeEvent =+ | { readonly kind: "runtime-action-result"; readonly results: readonly RuntimeActionResult[] }+ | { readonly kind: "workflow"; readonly message: WorkflowToolRunMessage }+ | "cancelled";++/**+ * Admission policy, cancellation, and steering for one active turn.+ * Deliveries admitted while a model step runs stay in the shared queue until+ * 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.+ */+class ActiveTurn {+ private readonly admitted = new Set<number>();+ private readonly routedToChildren = new Set<number>();+ private readonly runtimeResults: RuntimeEvent[] = [];+ private readonly controller = new AbortController();+ private readonly expectedTurnId: string;+ private readonly input: SessionExecutionInput;+ private readonly callerCallId: string | undefined;+ private readonly unsubscribe: () => void;++ constructor(input: SessionExecutionInput, callerCallId: string | undefined) {+ this.input = input;+ this.callerCallId = callerCallId;+ this.expectedTurnId = activeTurnId(input.cursor.sessionState.emissionState);+ this.unsubscribe = input.inbox.onInterrupt((payload) => {+ if (this.cancelsThisTurn(payload)) this.abort();+ });+ }++ get signal(): AbortSignal {+ return this.controller.signal;+ }++ dispose(): void {+ this.unsubscribe();+ }++ /** Admits everything the pump accepted while the last step ran. */+ async admitBoundary(): Promise<void> {+ const pending = this.input.inbox.drain();+ for (const payload of pending) await this.admit(payload);+ }++ /** Steering admitted during this turn, routed to children first and coalesced. */+ async takeSteering(): Promise<DeliverHookPayload | undefined> {+ const steering: DeliverHookPayload[] = [];+ while (true) {+ const selection = this.input.queue.takeSteering(this.admitted, this.callerCallId);+ if (selection === undefined) break;+ for (const sequence of selection.sequences) this.admitted.delete(sequence);+ const routed = await routeSelectedDelivery(selection, this.input.cursor);+ if (routed.kind === "cancel-turn") {+ this.abort();+ break;+ }+ if (routed.kind === "turn") steering.push(routed.delivery);+ }+ if (steering.length === 0) return undefined;+ return steering.length === 1 ? steering[0] : coalesceDeliveries(steering);+ }++ /** Next runtime result or workflow message, admitting inbox traffic while waiting. */+ async nextRuntimeEvent(): Promise<RuntimeEvent> {+ while (true) {+ if (this.signal.aborted) return "cancelled";+ const event = this.runtimeResults.shift();+ if (event !== undefined) return event;+ const payload = await this.input.inbox.next();+ if (payload === undefined)+ throw new Error("Session inbox closed before runtime actions completed.");+ await this.admit(payload);+ await this.routeAdmittedToChildren();+ }+ }++ private cancelsThisTurn(payload: SessionInboxPayload): boolean {+ if (payload.kind === "reset") return true;+ if (payload.kind !== "cancel") return false;+ return payload.turnId === undefined || payload.turnId === this.expectedTurnId;+ }++ private async admit(value: SessionInboxPayload): Promise<void> {+ const admitted = await admitSessionInboxPayload(value, this.input);+ switch (admitted.kind) {+ case "delivery":+ this.admitted.add(admitted.admission.sequence);+ return;+ case "runtime-action-result":+ this.runtimeResults.push({+ kind: "runtime-action-result",+ results: admitted.payload.results,+ });+ return;+ case "workflow":+ this.runtimeResults.push({ kind: "workflow", message: admitted.message });+ return;+ case "cancel":+ if (!this.cancelsThisTurn(value)) return;+ await applySessionCancellation(admitted.command, this.input);+ this.abort();+ return;+ case "consumed":+ return;+ }+ }++ /** During a runtime wait, descendant-bound answers cannot wait for the boundary. */+ private async routeAdmittedToChildren(): Promise<void> {+ for (const sequence of this.admitted) {+ if (this.routedToChildren.has(sequence)) continue;+ const delivery = this.input.queue.delivery(sequence);+ if (delivery === undefined) {+ this.admitted.delete(sequence);+ continue;+ }+ this.routedToChildren.add(sequence);+ const routed = await routeDeliverToChildren({+ delivery,+ sessionWritable: this.input.cursor.sessionWritable,+ serializedContext: this.input.cursor.serializedContext,+ sessionState: this.input.cursor.sessionState,+ });+ await this.input.cursor.apply(routed);+ if (routed.kind === "cancel-turn") {+ this.input.queue.replaceDelivery(sequence, undefined);+ this.admitted.delete(sequence);+ this.abort();+ return;+ }+ this.input.queue.replaceDelivery(sequence, routed.remainder);+ if (routed.remainder === undefined) this.admitted.delete(sequence);+ }+ }++ private abort(): void {+ if (this.controller.signal.aborted) return;+ this.controller.abort(new TurnCancelledError());+ }+}diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts b/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.tsindex 1dab3e347..92423a03c 100644--- a/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts+++ b/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts@@ -135,14 +135,14 @@ describe("settleCancelledTurnStep handle store", () => {await runtime.run(async () => {const result = await settleCancelledTurnStep({- parentWritable: new WritableStream<Uint8Array>({ write() {} }),+ sessionWritable: new WritableStream<Uint8Array>({ write() {} }),serializedContext: buildSerializedContext(),sessionState: createDurableSessionState({session: createCancelledTurnSession([RUNNING_HANDLE, PARKED_HANDLE]),}),});- expect(getAgentHandleStore(result.sessionState.snapshot?.session.state)).toEqual({+ expect(getAgentHandleStore(result.sessionState.snapshot.session.state)).toEqual({handles: [{address: RUNNING_HANDLE.address,@@ -153,7 +153,7 @@ describe("settleCancelledTurnStep handle store", () => {PARKED_HANDLE,],});- expect(result.sessionState.snapshot?.session.outputSchema).toBeUndefined();+ expect(result.sessionState.snapshot.session.outputSchema).toBeUndefined();expect(bindSessionInstrumentationSpy).toHaveBeenCalledWith(expect.objectContaining({ agentName: "settle-cancel-handles" }),);@@ -172,12 +172,12 @@ describe("settleCancelledTurnStep handle store", () => {toolName: "Workflow",});const result = await settleCancelledTurnStep({- parentWritable: new WritableStream<Uint8Array>({ write() {} }),+ sessionWritable: new WritableStream<Uint8Array>({ write() {} }),serializedContext: buildSerializedContext(),sessionState: createDurableSessionState({ session }),});- expect(getAgentHandleStore(result.sessionState.snapshot?.session.state)).toEqual({+ expect(getAgentHandleStore(result.sessionState.snapshot.session.state)).toEqual({handles: [{address: CLAIMED_HANDLE.address,diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.ts b/packages/eve/src/execution/settle-cancelled-turn-step.tsindex 06e7795e7..e32494105 100644--- a/packages/eve/src/execution/settle-cancelled-turn-step.ts+++ b/packages/eve/src/execution/settle-cancelled-turn-step.ts@@ -52,17 +52,17 @@ export interface CancelledTurnSettleResult {/*** Settles one cancelled turn: emits `turn.cancelled` → `session.waiting`,* drops pending coordination state, and persists the between-turns- * session. Runs in the *driver* run, whose wake sources exclude the+ * session. Runs in the owner, whose wake sources exclude the* cancel hook, so a queued cancel wake cannot re-dispatch it.*/export async function settleCancelledTurnStep(input: {- readonly parentWritable: WritableStream<Uint8Array>;+ readonly sessionWritable: WritableStream<Uint8Array>;readonly serializedContext: Record<string, unknown>;readonly sessionState: DurableSessionState;}): Promise<CancelledTurnSettleResult> {"use step";- const durableSession = await readDurableSession(input.sessionState);+ const durableSession = readDurableSession(input.sessionState);const ctx = await deserializeContext(input.serializedContext);const adapter = ctx.require(ChannelKey);const adapterCtx = buildAdapterContext(adapter, ctx);@@ -97,7 +97,7 @@ export async function settleCancelledTurnStep(input: {!stoppedAtDescendantLimit;if (!alreadyEpilogued) {- const writer = input.parentWritable.getWriter();+ const writer = input.sessionWritable.getWriter();try {const scoped = await withContextScope(ctx, session, async (enrichedSession) => {const baseEmit = async (event: UnstampedMessageStreamEvent): Promise<void> => {diff --git a/packages/eve/src/execution/stable-workflow-names.ts b/packages/eve/src/execution/stable-workflow-names.tsindex 9e38e27c2..689834f59 100644--- a/packages/eve/src/execution/stable-workflow-names.ts+++ b/packages/eve/src/execution/stable-workflow-names.ts@@ -3,8 +3,8 @@* an explicitly stamped deployment can find them across eve versions.* Dependency-free so the bundler can import it.*/-export const WORKFLOW_ENTRY_NAME = "workflowEntry";export const TURN_WORKFLOW_NAME = "turnWorkflow";+export const WORKFLOW_ENTRY_NAME = "workflowEntry";export const SESSION_TIMEOUT_WORKFLOW_NAME = "sessionTimeoutWorkflow";export const TASK_RUN_WORKFLOW_NAME = "taskRunWorkflow";export const WORKFLOW_TOOL_RUN_WORKFLOW_NAME = "workflowToolRunWorkflow";diff --git a/packages/eve/src/execution/task-input-response-route.ts b/packages/eve/src/execution/task-input-response-route.tsindex e461731a8..5eda6dff8 100644--- a/packages/eve/src/execution/task-input-response-route.ts+++ b/packages/eve/src/execution/task-input-response-route.ts@@ -1,5 +1,5 @@import { readTaskInputTargetToken } from "#execution/task-input-capability.js";-import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";+import { resumeSessionInbox } from "#execution/session-inbox/resume.js";import type { RouteContext } from "#public/definitions/channel.js";import type { InputResponse } from "#shared/input.js";diff --git a/packages/eve/src/execution/tasks/child/steps.test.ts b/packages/eve/src/execution/tasks/child/steps.test.tsindex 992dc6184..4c3708825 100644--- a/packages/eve/src/execution/tasks/child/steps.test.ts+++ b/packages/eve/src/execution/tasks/child/steps.test.ts@@ -9,7 +9,7 @@ import {} from "#execution/tasks/child/steps.js";import { resumeWorkflowToolRunAnswers } from "#execution/tools/workflow/answer.js";import type { TaskView } from "#tasks/types.js";-import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";+import { resumeSessionInbox } from "#execution/session-inbox/resume.js";import { getWritable } from "#compiled/@workflow/core/index.js";import { submitActivity } from "#execution/submit-activity.js";@@ -19,7 +19,7 @@ vi.mock("#compiled/@workflow/core/index.js", async (importOriginal) => ({}));vi.mock("#execution/submit-activity.js", () => ({ submitActivity: vi.fn() }));-vi.mock("#execution/wire/session-inbox-resume.js", () => ({ resumeSessionInbox: vi.fn() }));+vi.mock("#execution/session-inbox/resume.js", () => ({ resumeSessionInbox: vi.fn() }));vi.mock("#execution/tools/workflow/answer.js", () => ({resumeWorkflowToolRunAnswers: vi.fn(),}));diff --git a/packages/eve/src/execution/tasks/child/steps.ts b/packages/eve/src/execution/tasks/child/steps.tsindex 59814b2a9..44cdba717 100644--- a/packages/eve/src/execution/tasks/child/steps.ts+++ b/packages/eve/src/execution/tasks/child/steps.ts@@ -7,7 +7,7 @@ import type {import type { WorkflowToolRunTaskInputRequest } from "./workflow.js";import { submitActivity } from "#execution/submit-activity.js";import { isTaskWorkflowTargetGone } from "#execution/tasks/workflow-target.js";-import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";+import { resumeSessionInbox } from "#execution/session-inbox/resume.js";import { resumeWorkflowToolRunAnswers } from "#execution/tools/workflow/answer.js";import type { AnswerHookRoute } from "#harness/proxy-input-requests.js";import { createLogger } from "#internal/logging.js";@@ -107,7 +107,7 @@ export async function appendTaskProgressStep(input: {** Rides the ordinary session delivery path: a parked parent starts a* turn carrying this message, while an active turn observes it at the- * next safe boundary through the driver's normal delivery routing. A+ * next safe boundary through the owner's normal delivery routing. A* parent whose session already ended is a tolerated no-op.*/export async function wakeTaskParentStep(input: {diff --git a/packages/eve/src/execution/tasks/parent/delegate.ts b/packages/eve/src/execution/tasks/parent/delegate.tsindex 7d352ebd0..b04ba5acd 100644--- a/packages/eve/src/execution/tasks/parent/delegate.ts+++ b/packages/eve/src/execution/tasks/parent/delegate.ts@@ -13,7 +13,7 @@ import {startTaskRun,waitForTaskCommandOwner,} from "#execution/tasks/parent/run-parent.js";-import { sessionCommandHookToken } from "#execution/session-command-token.js";+import { sessionCommandHookToken } from "#execution/session-inbox/address.js";import type { JsonValue } from "#shared/json.js";import type { TaskExecutorBinding } from "#tools/task.js";import { deriveTaskInboxToken, deriveTaskId } from "#tasks/task-id.js";diff --git a/packages/eve/src/execution/tasks/parent/dispatch.test.ts b/packages/eve/src/execution/tasks/parent/dispatch.test.tsindex 89a6827cd..b21f7fba4 100644--- a/packages/eve/src/execution/tasks/parent/dispatch.test.ts+++ b/packages/eve/src/execution/tasks/parent/dispatch.test.ts@@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { cancelOwnedTask, isTaskControlAction } from "#execution/tasks/parent/dispatch.js";import { readLatestTaskView, sendTaskCommand } from "#execution/tasks/parent/run-parent.js";import { cancelWorkflowToolRun } from "#execution/tools/workflow/cancel.js";-import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";+import { resumeSessionInbox } from "#execution/session-inbox/resume.js";const { cancelRun, getRun } = vi.hoisted(() => ({cancelRun: vi.fn(),@@ -15,7 +15,7 @@ vi.mock("#execution/tasks/parent/run-parent.js", () => ({sendTaskCommand: vi.fn(),}));vi.mock("#execution/tools/workflow/cancel.js", () => ({ cancelWorkflowToolRun: vi.fn() }));-vi.mock("#execution/wire/session-inbox-resume.js", () => ({ resumeSessionInbox: vi.fn() }));+vi.mock("#execution/session-inbox/resume.js", () => ({ resumeSessionInbox: vi.fn() }));vi.mock("#internal/workflow/runtime.js", () => ({cancelRun,getRun,diff --git a/packages/eve/src/execution/tasks/parent/dispatch.ts b/packages/eve/src/execution/tasks/parent/dispatch.tsindex d50e62554..eceb86760 100644--- a/packages/eve/src/execution/tasks/parent/dispatch.ts+++ b/packages/eve/src/execution/tasks/parent/dispatch.ts@@ -9,7 +9,7 @@ import {import type { BackgroundTask } from "#execution/tasks/parent/delegate.js";import { sendTaskCommand } from "#execution/tasks/parent/run-parent.js";import { wakeTaskParentStep } from "#execution/tasks/child/steps.js";-import { sessionCommandHookToken } from "#execution/session-command-token.js";+import { sessionCommandHookToken } from "#execution/session-inbox/address.js";import {cancelTaskOwnedWork,type TaskExecutorCancel,diff --git a/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.test.ts b/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.test.tsindex 5cfb36b95..f0f74dbb4 100644--- a/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.test.ts+++ b/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.test.ts@@ -1,3 +1,4 @@+import { createTestSessionState } from "#internal/testing/session-state.js";import { beforeEach, describe, expect, it, vi } from "vitest";import { ContextContainer } from "#context/container.js";@@ -18,7 +19,10 @@ import { getSessionTaskIndex } from "#tasks/session-index.js";const flushInstrumentation = vi.hoisted(() => vi.fn());const publishBackgroundTaskSettlements = vi.hoisted(() => vi.fn());-vi.mock("#execution/durable-session-store.js", () => ({ readDurableSession: vi.fn() }));+vi.mock("#execution/durable-session-store.js", async (importOriginal) => ({+ ...(await importOriginal()),+ readDurableSession: vi.fn(),+}));vi.mock("#execution/tasks/parent/run-parent.js", () => ({ readLatestTaskView: vi.fn() }));vi.mock("#instrumentation/runtime.js", () => ({bindSessionInstrumentation: vi.fn(),@@ -52,19 +56,19 @@ const request = {turnId: "turn-1",};-const sessionState = {+const sessionState = createTestSessionState({continuationToken: "parent-token",emissionState: { sequence: 0, sessionStarted: true, stepIndex: 0, turnId: "turn-1" },hasProxyInputRequests: false,sessionId: "parent-session",version: 1,-} as const;+});const remoteReplyTo = "eve:eve:op:0123456789abcdef0123456789abcdef";describe("recordTaskInputRequestStep", () => {beforeEach(() => {vi.resetAllMocks();- vi.mocked(readDurableSession).mockResolvedValue({+ vi.mocked(readDurableSession).mockReturnValue({agent: { system: "" },continuationToken: "parent-token",history: [],@@ -103,7 +107,7 @@ describe("recordTaskInputRequestStep", () => {sessionState: { hasProxyInputRequests: true },});expect(- getProxyInputRequests(result.sessionState.snapshot?.session.state).get("task-1:req-1"),+ getProxyInputRequests(result.sessionState.snapshot.session.state).get("task-1:req-1"),).toEqual({childContinuationToken: request.replyTo,childRequestId: "req-1",@@ -127,7 +131,7 @@ describe("recordTaskInputRequestStep", () => {});it("records a narrowed remote response route for a claimed remote child", async () => {- vi.mocked(readDurableSession).mockResolvedValue({+ vi.mocked(readDurableSession).mockReturnValue({agent: { system: "" },continuationToken: "parent-token",history: [],@@ -181,7 +185,7 @@ describe("recordTaskInputRequestStep", () => {const result = await recordTaskInputRequestStep({ request: remoteRequest, sessionState });expect(- getProxyInputRequests(result.sessionState.snapshot?.session.state).get("task-1:remote-req"),+ getProxyInputRequests(result.sessionState.snapshot.session.state).get("task-1:remote-req"),).toMatchObject({childResponseUrl:"https://remote.example/eve/v1/task-input/eve%3Atask-input%3A0123456789abcdef0123456789abcdef",@@ -199,7 +203,7 @@ describe("recordTerminalTaskViewsStep", () => {});it("caches an owned terminal view and releases the task's agent lease", async () => {- vi.mocked(readDurableSession).mockResolvedValue({+ vi.mocked(readDurableSession).mockReturnValue({agent: { system: "" },continuationToken: "parent-token",history: [],@@ -249,7 +253,7 @@ describe("recordTerminalTaskViewsStep", () => {sessionState,views: [view],});- const state = result.sessionState.snapshot?.session.state;+ const state = result.sessionState.snapshot.session.state;expect(getSessionTaskIndex(state)[0]?.terminalView).toEqual(view);expect(getAgentHandleStore(state)?.handles).toEqual([@@ -268,7 +272,7 @@ describe("recordTerminalTaskViewsStep", () => {const context = new ContextContainer();context.set(BundleKey, bundle);const serializedContext = serializeContext(context);- vi.mocked(readDurableSession).mockResolvedValue({+ vi.mocked(readDurableSession).mockReturnValue({agent: { system: "" },continuationToken: "parent-token",history: [],diff --git a/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts b/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.tsindex 5ef2e907f..bacab73bc 100644--- a/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts+++ b/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts@@ -1,6 +1,10 @@import { contextStorage } from "#context/container.js";import { deserializeContext, serializeContext } from "#context/serialize.js";-import { type DurableSessionState, readDurableSession } from "#execution/durable-session-store.js";+import {+ type DurableSessionState,+ readDurableSession,+ replaceDurableSessionSnapshot,+} from "#execution/durable-session-store.js";import { readLatestTaskView } from "#execution/tasks/parent/run-parent.js";import { createTaskInputCapabilityToken } from "#execution/task-input-capability.js";import { createRemoteTaskInputCallbackUrl } from "#execution/workflow-callback-url.js";@@ -35,7 +39,7 @@ export async function recordTaskInputRequestStep(input: {> {"use step";- const durableSession = await readDurableSession(input.sessionState);+ const durableSession = readDurableSession(input.sessionState);const entry = findSessionTaskEntry(durableSession.state, input.request.taskId);const requests = input.request.requests ?? [input.request.request];if (entry === undefined || requests.length === 0 || !requests.every(isInputRequest)) {@@ -94,14 +98,10 @@ export async function recordTaskInputRequestStep(input: {return {accepted: true,request,- sessionState: {- ...input.sessionState,- hasProxyInputRequests: true,- snapshot: {- session: { ...durableSession, state },- version: input.sessionState.version,- },- },+ sessionState: replaceDurableSessionSnapshot({+ session: { ...durableSession, state },+ state: input.sessionState,+ }),};}@@ -115,7 +115,7 @@ export async function recordTerminalTaskViewsStep(input: {readonly sessionState: DurableSessionState;}> {"use step";- const durableSession = await readDurableSession(input.sessionState);+ const durableSession = readDurableSession(input.sessionState);let session = durableSession;const acceptedViews: TaskView[] = [];for (const view of input.views) {@@ -136,13 +136,7 @@ export async function recordTerminalTaskViewsStep(input: {const sessionState =session === durableSession? input.sessionState- : {- ...input.sessionState,- snapshot: {- session,- version: input.sessionState.version,- },- };+ : replaceDurableSessionSnapshot({ session, state: input.sessionState });return { serializedContext, sessionState };}diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts b/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.tsindex c5d7d08b6..5059ab605 100644--- a/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts+++ b/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts@@ -3,13 +3,16 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import type { ActivityObserverConfig } from "#channel/types.js";import { ContextContainer, contextStorage } from "#context/container.js";import { ActivityObserverKey, SessionKey, type SessionAuth } from "#context/keys.js";-import { cancelOwnedTask } from "#execution/tasks/parent/dispatch.js";-import { startTaskRun, waitForTaskCommandOwner } from "#execution/tasks/parent/run-parent.js";+import {+ sendTaskCommand,+ startTaskRun,+ waitForTaskCommandOwner,+} from "#execution/tasks/parent/run-parent.js";import {backgroundToolExecutionProvider,readRetainedBackgroundToolResult,} from "#execution/tasks/parent/tool-execution.js";-import { cancelBackgroundAgentTask } from "#execution/tools/subagent/task-cancel.js";+import { steerBackgroundAgent } from "#execution/tools/subagent/steer.js";import {BackgroundToolExecutorKey,createBackgroundToolCallBatch,@@ -18,17 +21,8 @@ import { setHarnessEmissionState } from "#harness/emission-state.js";import { TurnCancelledError } from "#harness/turn-cancellation.js";import type { HarnessSession } from "#harness/types.js";import { getAgentHandleStore, setAgentHandleStore } from "#subagents/handles/store.js";-import { applyTaskAgentHandleCommand } from "#subagents/handles/transitions.js";import { getSessionTaskIndex, recordSessionTask } from "#tasks/session-index.js";-import { getHookByToken } from "#internal/workflow/runtime.js";-import { sessionCommandHookToken } from "#execution/session-command-token.js";--vi.mock("#internal/workflow/runtime.js", async (importOriginal) => ({- ...(await importOriginal<typeof import("#internal/workflow/runtime.js")>()),- getHookByToken: vi.fn(),-}));-vi.mock("#execution/tasks/parent/dispatch.js", () => ({ cancelOwnedTask: vi.fn() }));-vi.mock("#execution/tools/subagent/task-cancel.js", () => ({ cancelBackgroundAgentTask: vi.fn() }));+vi.mock("#execution/tools/subagent/steer.js", () => ({ steerBackgroundAgent: vi.fn() }));vi.mock("#execution/tasks/parent/run-parent.js", () => ({sendTaskCommand: vi.fn(async () => "delivered"),startTaskRun: vi.fn(),@@ -57,11 +51,6 @@ const entry = {taskInboxToken: "original-task-inbox",taskRunId: "original-task-run",};-const cancelledView = {- metadata: entry.metadata,- status: "cancelled" as const,- taskId: entry.taskId,-};function createSession(owned = true): HarnessSession {const session = setHarnessEmissionState(@@ -134,12 +123,36 @@ async function createScope(describe("background subagent steering", () => {beforeEach(() => {vi.clearAllMocks();- vi.mocked(cancelOwnedTask).mockResolvedValue(cancelledView);+ vi.mocked(steerBackgroundAgent).mockResolvedValue(undefined);vi.mocked(startTaskRun).mockResolvedValue(undefined as never);vi.mocked(waitForTaskCommandOwner).mockResolvedValue({ runId: "steering-task-run" } as never);- vi.mocked(getHookByToken).mockResolvedValue({- metadata: { workflowTaskAuthorization: true },- } as never);+ });++ it("steers the existing child without replacing its task, claim, or receipt", async () => {+ const scope = await createScope();+ const receipt = await scope.execute();+ expect(steerBackgroundAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ handle,+ callId: "steering-call",+ input: { agentId: identity.id, message: "Use the updated instruction" },+ }),+ );+ expect(receipt).toEqual({ agentId: identity.id, status: "working", taskId: entry.taskId });+ const session = await scope.commit();+ expect(getAgentHandleStore(session.state)?.handles).toEqual([handle]);+ expect(getSessionTaskIndex(session.state)).toEqual([entry]);+ expect(startTaskRun).not.toHaveBeenCalled();+ expect(waitForTaskCommandOwner).not.toHaveBeenCalled();+ expect(sendTaskCommand).not.toHaveBeenCalled();+ });++ it("keeps the original claim and starts no replacement when delivery fails", async () => {+ const scope = await createScope();+ vi.mocked(steerBackgroundAgent).mockRejectedValueOnce(new Error("Delivery failed"));+ await expect(scope.execute()).rejects.toThrow("Delivery failed");+ expect(startTaskRun).not.toHaveBeenCalled();+ expect(getAgentHandleStore((await scope.commit()).state)?.handles).toEqual([handle]);});it("persists the creating turn's auth on the background task", async () => {@@ -156,7 +169,7 @@ describe("background subagent steering", () => {initiator: creatorInitiator,});- await scope.execute();+ await scope.execute("new-call", "");const committed = await scope.commit();const task = getSessionTaskIndex(committed.state).find((candidate) => candidate.taskId !== entry.taskId,@@ -194,7 +207,7 @@ describe("background subagent steering", () => {initiator: sessionInitiator,});- await scope.execute();+ await scope.execute("new-call", "");const committed = await scope.commit();const task = getSessionTaskIndex(committed.state).find((candidate) => candidate.taskId !== entry.taskId,@@ -205,26 +218,6 @@ describe("background subagent steering", () => {});});- it.each([- { metadata: undefined, supported: false },- { metadata: { sessionInboxWireVersion: 6 }, supported: false },- { metadata: { workflowTaskAuthorization: "true" }, supported: false },- { metadata: { workflowTaskAuthorization: true }, supported: true },- ])(- "passes the receiving driver's auth support to the task ($supported)",- async ({ metadata, supported }) => {- vi.mocked(getHookByToken).mockResolvedValue({ metadata } as never);- const scope = await createScope();- await expect(scope.execute()).resolves.toMatchObject({ status: "working" });- expect(getHookByToken).toHaveBeenCalledWith(sessionCommandHookToken("parent"));- expect(startTaskRun).toHaveBeenCalledWith(- expect.objectContaining({- workflow: expect.objectContaining({ authorizationSupported: supported }),- }),- );- },- );-it.each(["subagent", "tool"] as const)("persists agent-backed activity identity only (%s)",async (resultKind) => {@@ -239,7 +232,7 @@ describe("background subagent steering", () => {};const scope = await createScope(createSession(), activityObserver);- await scope.execute("steering-call", identity.id, identity.name, resultKind);+ await scope.execute("new-call", "", identity.name, resultKind);const committed = await scope.commit();const task = getSessionTaskIndex(committed.state).find((candidate) => candidate.taskId !== entry.taskId,@@ -251,7 +244,7 @@ describe("background subagent steering", () => {return;}expect(task?.activityWorkIdentity).toMatchObject({- callId: "steering-call",+ callId: "new-call",kind: "task",name: "research",parentId: "work:root",@@ -273,14 +266,14 @@ describe("background subagent steering", () => {};const scope = await createScope(createSession(), activityObserver);- await scope.execute("steering-call", identity.id, identity.name, "subagent", (input) => {+ await scope.execute("new-call", "", identity.name, "subagent", (input) => {(input as { message: string }).message = "Mutated";return "Investigator";});expect(startTaskRun).toHaveBeenCalledWith(expect.objectContaining({workflow: expect.objectContaining({- input: { agentId: identity.id, message: "Use the updated instruction" },+ input: { agentId: "", message: "Use the updated instruction" },}),}),);@@ -295,51 +288,13 @@ describe("background subagent steering", () => {});});- it("cancels the old task before starting a new task in the same child", async () => {- const scope = await createScope();- const cancellation = Promise.withResolvers<typeof cancelledView>();- vi.mocked(cancelOwnedTask).mockReturnValue(cancellation.promise);- const steering = scope.execute();- expect(startTaskRun).not.toHaveBeenCalled();- expect(cancelOwnedTask).toHaveBeenCalledWith(- expect.objectContaining({- cancelOwnedWork: cancelBackgroundAgentTask,- entry,- serializedContext: {},- }),- );-- cancellation.resolve(cancelledView);- const receipt = await steering;- expect(receipt).toMatchObject({ agentId: identity.id, status: "working" });- const session = await scope.commit();- const claimed = getAgentHandleStore(session.state)?.handles[0];- expect(claimed).toMatchObject({ address, identity, phase: "claimed", callId: "steering-call" });- expect(claimed).not.toHaveProperty("ownerId", entry.taskId);- expect(getSessionTaskIndex(session.state)).toHaveLength(2);-- const released = applyTaskAgentHandleCommand(session, {- kind: "release-owner",- ownerId: entry.taskId,- });- expect(released.session).toBe(session);- });-- it("keeps the original claim and starts no replacement when cancellation fails", async () => {- const scope = await createScope();- vi.mocked(cancelOwnedTask).mockRejectedValue(new Error("Cancellation did not commit"));- await expect(scope.execute()).rejects.toThrow("Cancellation did not commit");- expect(startTaskRun).not.toHaveBeenCalled();- expect(getAgentHandleStore((await scope.commit()).state)?.handles).toEqual([handle]);- });-- it("does not cancel a task outside the parent task index", async () => {+ it("does not steer a task outside the parent task index", async () => {const scope = await createScope(createSession(false));await expect(scope.execute()).rejects.toThrow("AGENT_BUSY");- expect(cancelOwnedTask).not.toHaveBeenCalled();+ expect(steerBackgroundAgent).not.toHaveBeenCalled();});- it("does not cancel a task associated with another child", async () => {+ it("does not steer a task associated with another child", async () => {const scope = await createScope(recordSessionTask(createSession(), {...entry,@@ -347,18 +302,18 @@ describe("background subagent steering", () => {}),);await expect(scope.execute()).rejects.toThrow("AGENT_BUSY");- expect(cancelOwnedTask).not.toHaveBeenCalled();+ expect(steerBackgroundAgent).not.toHaveBeenCalled();});- it("rejects a different subagent tool before cancellation", async () => {+ it("rejects a different subagent tool before delivery", async () => {const scope = await createScope();await expect(scope.execute("call-1", identity.id, "another-tool")).rejects.toThrow("AGENT_MISMATCH",);- expect(cancelOwnedTask).not.toHaveBeenCalled();+ expect(steerBackgroundAgent).not.toHaveBeenCalled();});- it("rejects a different local/remote target before cancellation", async () => {+ it("rejects a different local/remote target before delivery", async () => {const session = createSession();const scope = await createScope({...session,@@ -377,7 +332,7 @@ describe("background subagent steering", () => {}),});await expect(scope.execute()).rejects.toThrow("AGENT_MISMATCH");- expect(cancelOwnedTask).not.toHaveBeenCalled();+ expect(steerBackgroundAgent).not.toHaveBeenCalled();});it("does not steer a reservation before the child has an address", async () => {@@ -390,10 +345,10 @@ describe("background subagent steering", () => {}),});await expect(scope.execute()).rejects.toThrow("AGENT_BUSY");- expect(cancelOwnedTask).not.toHaveBeenCalled();+ expect(steerBackgroundAgent).not.toHaveBeenCalled();});- it("preserves a different child's claim made while cancellation was pending", async () => {+ it("preserves a different child's claim made while steering was pending", async () => {const second = {address: { ...address, sessionId: "second-session" },identity: { ...identity, id: "agent-2" },@@ -404,14 +359,14 @@ describe("background subagent steering", () => {...session,state: setAgentHandleStore(session.state, { handles: [handle, second] }),});- const cancellation = Promise.withResolvers<typeof cancelledView>();- vi.mocked(cancelOwnedTask).mockReturnValue(cancellation.promise);+ const delivery = Promise.withResolvers<void>();+ vi.mocked(steerBackgroundAgent).mockReturnValueOnce(delivery.promise);const first = scope.execute();await scope.execute("second-call", second.identity.id);- cancellation.resolve(cancelledView);+ delivery.resolve();await first;expect(getAgentHandleStore((await scope.commit()).state)?.handles).toEqual([- expect.objectContaining({ identity, phase: "claimed", callId: "steering-call" }),+ handle,expect.objectContaining({identity: second.identity,phase: "claimed",@@ -420,61 +375,41 @@ describe("background subagent steering", () => {]);});- it("rejects competing steering before it can send a delayed child cancellation", async () => {+ it("accepts concurrent steering without transferring ownership", async () => {const scope = await createScope();- const cancellation = Promise.withResolvers<typeof cancelledView>();- const delayedCancellation = Promise.withResolvers<typeof cancelledView>();- vi.mocked(cancelOwnedTask).mockImplementation(() =>- vi.mocked(cancelOwnedTask).mock.calls.length === 1- ? cancellation.promise- : delayedCancellation.promise,- );- const first = scope.execute("first-call");- const second = scope.execute("second-call");- const settled = Promise.allSettled([first, second]);- try {- expect(cancelOwnedTask).toHaveBeenCalledTimes(1);- await expect(second).rejects.toThrow("AGENT_BUSY");- expect(startTaskRun).not.toHaveBeenCalled();- } finally {- cancellation.resolve(cancelledView);- delayedCancellation.resolve(cancelledView);- await settled;- }- const results = await settled;- expect(results.map((result) => result.status)).toEqual(["fulfilled", "rejected"]);- expect(startTaskRun).toHaveBeenCalledTimes(1);- expect(getAgentHandleStore((await scope.commit()).state)?.handles[0]).toMatchObject({- callId: "first-call",- });+ const receipts = await Promise.all([scope.execute("first-call"), scope.execute("second-call")]);+ expect(receipts).toEqual([+ { agentId: identity.id, status: "working", taskId: entry.taskId },+ { agentId: identity.id, status: "working", taskId: entry.taskId },+ ]);+ expect(steerBackgroundAgent).toHaveBeenCalledTimes(2);+ expect(startTaskRun).not.toHaveBeenCalled();+ expect(getAgentHandleStore((await scope.commit()).state)?.handles).toEqual([handle]);});- it("allows another steering attempt after cancellation fails", async () => {+ it("allows another steering attempt after delivery fails", async () => {const scope = await createScope();- vi.mocked(cancelOwnedTask).mockRejectedValueOnce(new Error("Child cancellation failed"));- await expect(scope.execute("first-call")).rejects.toThrow("Child cancellation failed");+ vi.mocked(steerBackgroundAgent).mockRejectedValueOnce(new Error("Delivery failed"));+ await expect(scope.execute("first-call")).rejects.toThrow("Delivery failed");await expect(scope.execute("retry-call")).resolves.toMatchObject({agentId: identity.id,status: "working",});- expect(cancelOwnedTask).toHaveBeenCalledTimes(2);- expect(startTaskRun).toHaveBeenCalledTimes(1);- expect(getAgentHandleStore((await scope.commit()).state)?.handles[0]).toMatchObject({- callId: "retry-call",- });+ expect(steerBackgroundAgent).toHaveBeenCalledTimes(2);+ expect(startTaskRun).not.toHaveBeenCalled();+ expect(getAgentHandleStore((await scope.commit()).state)?.handles).toEqual([handle]);});- it("retains the released child if the parent turn is cancelled before the replacement starts", async () => {- const scope = await createScope();- const cancellation = new TurnCancelledError();- vi.mocked(startTaskRun).mockRejectedValueOnce(cancellation);- await expect(scope.execute()).rejects.toThrow(cancellation);- await scope.rollback(cancellation);- const retained = scope.retained();- expect(retained?.backgroundTasks).toEqual([]);- expect(getAgentHandleStore(retained?.backgroundTaskSession.state)?.handles).toEqual([- { address, identity, phase: "available" },- ]);- });+ it.each([new Error("Parent step failed"), new TurnCancelledError()])(+ "does not compensate the pre-existing task on rollback: %s",+ async (cause) => {+ const scope = await createScope();+ await scope.execute();+ await scope.rollback(cause);+ expect(sendTaskCommand).not.toHaveBeenCalled();+ expect(getAgentHandleStore((await scope.commit()).state)?.handles).toEqual([handle]);+ expect(scope.retained()).toBeUndefined();+ },+ );});diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.ts b/packages/eve/src/execution/tasks/parent/tool-execution.tsindex 1c77e289b..f02c51e04 100644--- a/packages/eve/src/execution/tasks/parent/tool-execution.ts+++ b/packages/eve/src/execution/tasks/parent/tool-execution.ts@@ -4,7 +4,6 @@ import { ActivityObserverKey } from "#context/keys.js";import type { FrameworkContextProvider } from "#context/provider.js";import { runStep } from "#context/run-step.js";import { buildCallbackContext } from "#context/build-callback-context.js";-import { serializeContext } from "#context/serialize.js";import { isAuthorizationSignal } from "#harness/authorization.js";import { activeTurnId } from "#harness/active-turn-id.js";import { getHarnessEmissionState } from "#harness/emission.js";@@ -38,8 +37,7 @@ import {startTaskRun,waitForTaskCommandOwner,} from "#execution/tasks/parent/run-parent.js";-import { sessionCommandHookToken } from "#execution/session-command-token.js";-import { sessionDriverSupportsWorkflowTaskAuthorization } from "#execution/wire/session-inbox-resume.js";+import { sessionCommandHookToken } from "#execution/session-inbox/address.js";import { projectSubagentTask } from "#execution/tasks/parent/subagent-task-projection.js";import { deriveAgentOperationId } from "#subagents/handles/operation-id.js";import { AGENT_BUSY, AGENT_MISMATCH, AGENT_UNREACHABLE } from "#subagents/agent-handle-errors.js";@@ -51,8 +49,7 @@ import {type AgentHandleStoreCommandResult,} from "#subagents/handles/store.js";import { applyTaskAgentHandleCommand } from "#subagents/handles/transitions.js";-import { cancelOwnedTask } from "#execution/tasks/parent/dispatch.js";-import { cancelBackgroundAgentTask } from "#execution/tools/subagent/task-cancel.js";+import { steerBackgroundAgent } from "#execution/tools/subagent/steer.js";const IN_PROCESS_WORKFLOW_EXECUTOR = { data: {}, kind: "workflow-task" } as const;@@ -142,7 +139,6 @@ export function readRetainedBackgroundToolResult(class BackgroundToolExecutionScope implements BackgroundToolExecutor {private readonly executions = new Map<string, Promise<unknown>>();private readonly records: BackgroundToolExecutionRecord[] = [];- private readonly steeringAgents = new Set<string>();private agentHandleSession: HarnessSession;private agentHandlesChanged = false;private retained = false;@@ -287,6 +283,10 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {const emission = getHarnessEmissionState(this.initialSession.state);const ctx = loadContext();const started = await this.startTask({ ctx, emission, input, record });+ if (started.kind === "steered") {+ record.settled = true;+ return started.receipt;+ }const task = started.task;record.task = task;@@ -333,10 +333,21 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {readonly toolInput: unknown;};readonly record: BackgroundToolExecutionRecord;- }): Promise<{- readonly receipt?: { readonly agentId: string };- readonly task: BackgroundTask;- }> {+ }): Promise<+ | {+ readonly kind: "started";+ readonly receipt?: { readonly agentId: string };+ readonly task: BackgroundTask;+ }+ | {+ readonly kind: "steered";+ readonly receipt: {+ readonly agentId: string;+ readonly taskId: string;+ readonly status: "working";+ };+ }+ > {const workflow =input.input.definition.workflowId === undefined? undefined@@ -408,6 +419,7 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {};if (workflow === undefined) {return {+ kind: "started",task: await beginBackgroundTask({activityObserver: taskInput.activityObserver,callId: taskInput.callId,@@ -460,18 +472,37 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {parentSessionId: taskInput.parentSessionId,parentTurnId,});- const claim = await this.claimAgentForSteering(- {- agentId: subagentProjection.metadata.agentId,- callId: taskInput.callId,- expectedTarget: subagentProjection.metadata.mode,- invokedName: subagentProjection.metadata.name,- kind: "claim",- operationId,- ownerId: task.taskId,- },- input.ctx,- );+ const claim = this.applyAgentHandleCommand({+ agentId: subagentProjection.metadata.agentId,+ callId: taskInput.callId,+ expectedTarget: subagentProjection.metadata.mode,+ invokedName: subagentProjection.metadata.name,+ kind: "claim",+ operationId,+ ownerId: task.taskId,+ });+ if (claim.kind === "busy" && claim.handle.phase === "claimed") {+ const handle = claim.handle;+ const entry = findSessionTaskEntry(this.agentHandleSession.state, handle.ownerId);+ if (+ entry?.metadata.kind === "subagent" &&+ entry.metadata.agentId === handle.identity.id &&+ entry.metadata.name === handle.identity.name &&+ entry.terminalView === undefined+ ) {+ await steerBackgroundAgent({+ ctx: input.ctx,+ handle,+ callId: taskInput.callId,+ input: workflowInput,+ session: this.agentHandleSession,+ });+ return {+ kind: "steered",+ receipt: { agentId: handle.identity.id, taskId: entry.taskId, status: "working" },+ };+ }+ }if (!readClaimedHandle(claim)) {throwAgentClaimError(subagentProjection.metadata.agentId, claim);} else {@@ -487,9 +518,6 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {parentContinuationToken: sessionCommandHookToken(this.initialSession.sessionId),taskInboxToken: task.taskInboxToken,workflow: {- authorizationSupported: await sessionDriverSupportsWorkflowTaskAuthorization(- this.initialSession.sessionId,- ),callId: taskInput.callId,executeInput: workflow.executeInput?.(workflowInput),input: workflowInput,@@ -509,52 +537,13 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {};input.record.task = backgroundTask;if (workflow.resultKind !== "subagent") {- return { task: backgroundTask };+ return { kind: "started", task: backgroundTask };}if (subagentProjection === undefined) {- return { task: backgroundTask };- }- if (subagentProjection.identity === undefined) {- return { receipt: subagentProjection.receipt, task: backgroundTask };- }- return { receipt: subagentProjection.receipt, task: backgroundTask };- }-- private async claimAgentForSteering(- command: Extract<AgentHandleStoreCommand, { kind: "claim" }>,- ctx: ReturnType<typeof loadContext>,- ): Promise<AgentHandleStoreCommandResult> {- const claim = this.applyAgentHandleCommand(command);- if (claim.kind !== "busy" || claim.handle.phase !== "claimed") return claim;-- const handle = claim.handle;- if (this.steeringAgents.has(handle.identity.id)) return claim;-- const entry = findSessionTaskEntry(this.agentHandleSession.state, handle.ownerId);- if (- entry?.metadata.kind !== "subagent" ||- entry.metadata.agentId !== handle.identity.id ||- entry.metadata.name !== handle.identity.name- ) {- return claim;- }-- this.steeringAgents.add(handle.identity.id);- try {- await cancelOwnedTask({- cancelOwnedWork: cancelBackgroundAgentTask,- entry,- serializedContext: serializeContext(ctx),- session: this.agentHandleSession,- });- // Other calls in this batch may have changed the store while cancellation- // was pending. Release only the old owner, then claim the current handle.- this.applyAgentHandleCommand({ kind: "release-owner", ownerId: handle.ownerId });- return this.applyAgentHandleCommand(command);- } finally {- this.steeringAgents.delete(handle.identity.id);+ return { kind: "started", task: backgroundTask };}+ return { kind: "started", receipt: subagentProjection.receipt, task: backgroundTask };}private applyAgentHandleCommand(command: AgentHandleStoreCommand): AgentHandleStoreCommandResult {diff --git a/packages/eve/src/execution/terminal-session-completion-step.ts b/packages/eve/src/execution/terminal-session-completion-step.tsindex 9ea12182c..f0cb2c926 100644--- a/packages/eve/src/execution/terminal-session-completion-step.ts+++ b/packages/eve/src/execution/terminal-session-completion-step.ts@@ -3,7 +3,7 @@ import { createSessionCompletedEvent } from "#protocol/message.js";/** Emits a terminal `session.completed` outside a turn. */export async function emitTerminalSessionCompletionStep(input: {- readonly parentWritable: WritableStream<Uint8Array>;+ readonly sessionWritable: WritableStream<Uint8Array>;readonly serializedContext: Record<string, unknown>;}): Promise<void> {"use step";diff --git a/packages/eve/src/execution/terminal-session-event.ts b/packages/eve/src/execution/terminal-session-event.tsindex 5d25f020f..24d156c8d 100644--- a/packages/eve/src/execution/terminal-session-event.ts+++ b/packages/eve/src/execution/terminal-session-event.ts@@ -24,7 +24,7 @@ type TerminalSessionEvent = Extract<export async function emitTerminalSessionEvent(input: {readonly errorId?: string;readonly event: TerminalSessionEvent;- readonly parentWritable: WritableStream<Uint8Array>;+ readonly sessionWritable: WritableStream<Uint8Array>;readonly serializedContext: Record<string, unknown>;readonly turnId?: string;}): Promise<void> {@@ -58,7 +58,7 @@ export async function emitTerminalSessionEvent(input: {}try {- const writer = input.parentWritable.getWriter();+ const writer = input.sessionWritable.getWriter();try {await writer.write(encodeMessageStreamEvent(stampMessageStreamEvent(event)));} finally {diff --git a/packages/eve/src/execution/terminal-session-failure-step.ts b/packages/eve/src/execution/terminal-session-failure-step.tsindex 020b2bba5..6f8b810c0 100644--- a/packages/eve/src/execution/terminal-session-failure-step.ts+++ b/packages/eve/src/execution/terminal-session-failure-step.ts@@ -8,7 +8,7 @@ const log = createLogger("execution.workflow-entry");/** Emits a terminal `session.failed` to the adapter and durable stream. */export async function emitTerminalSessionFailureStep(input: {readonly error: unknown;- readonly parentWritable: WritableStream<Uint8Array>;+ readonly sessionWritable: WritableStream<Uint8Array>;readonly serializedContext: Record<string, unknown>;readonly turnId?: string;}): Promise<void> {@@ -42,7 +42,7 @@ export async function emitTerminalSessionFailureStep(input: {await emitTerminalSessionEvent({errorId: typeof details.errorId === "string" ? details.errorId : undefined,event: createSessionFailedEvent({ code, details, message, sessionId }),- parentWritable: input.parentWritable,+ sessionWritable: input.sessionWritable,serializedContext: input.serializedContext,turnId: input.turnId,});diff --git a/packages/eve/src/execution/terminate-child-sessions-step.test.ts b/packages/eve/src/execution/terminate-child-sessions-step.test.tsindex 40472d1c1..389675892 100644--- a/packages/eve/src/execution/terminate-child-sessions-step.test.ts+++ b/packages/eve/src/execution/terminate-child-sessions-step.test.ts@@ -469,7 +469,6 @@ function makeSessionState([SESSION_TASKS_STATE_KEY]: { tasks, version: 2 },},},- version: 1,},version: 1,};diff --git a/packages/eve/src/execution/terminate-child-sessions-step.ts b/packages/eve/src/execution/terminate-child-sessions-step.tsindex 32dc7093c..22d79284b 100644--- a/packages/eve/src/execution/terminate-child-sessions-step.ts+++ b/packages/eve/src/execution/terminate-child-sessions-step.ts@@ -33,7 +33,7 @@ export async function terminateChildSessionsStep(input: {let session;try {- session = await readDurableSession(input.sessionState);+ session = readDurableSession(input.sessionState);} catch (error) {logError(log, "failed to read child sessions for termination", error, {parentSessionId: input.sessionState.sessionId,diff --git a/packages/eve/src/execution/tool-auth.integration.test.ts b/packages/eve/src/execution/tool-auth.integration.test.tsindex fe47cb873..239d6fa72 100644--- a/packages/eve/src/execution/tool-auth.integration.test.ts+++ b/packages/eve/src/execution/tool-auth.integration.test.ts@@ -372,7 +372,7 @@ describe("tool-hosted authorization", () => {expect(isAuthorizationSignal(result)).toBe(true);if (!isAuthorizationSignal(result)) throw new Error("expected signal");expect(receivedCallbackUrl).toBe(- `http://localhost:2000/eve/v1/connections/search_notion__mcp.notion.com_notion/callback/${result.challenges[0]?.attemptId}/session_auth%3Aauth`,+ `http://localhost:2000/eve/v1/connections/search_notion__mcp.notion.com_notion/callback/${result.challenges[0]?.attemptId}/eve%3Ainbox%3Av1%3Aeve%3Asession%3Asession_auth%3Ainbox`,);expect(result.challenges[0]?.hookUrl).toBe(receivedCallbackUrl);});diff --git a/packages/eve/src/execution/tools/subagent/accept-event-step.test.ts b/packages/eve/src/execution/tools/subagent/accept-event-step.test.tsindex f48644f3b..474987a7b 100644--- a/packages/eve/src/execution/tools/subagent/accept-event-step.test.ts+++ b/packages/eve/src/execution/tools/subagent/accept-event-step.test.ts@@ -1,3 +1,4 @@+import { createTestSessionState } from "#internal/testing/session-state.js";import { beforeEach, describe, expect, it, vi } from "vitest";import { readDurableSession } from "#execution/durable-session-store.js";@@ -5,16 +6,19 @@ import { readLatestTaskView } from "#execution/tasks/parent/run-parent.js";import { acceptTaskAuthorizationEventStep } from "#execution/tools/subagent/accept-event-step.js";import { setAgentHandleStore } from "#subagents/handles/store.js";-vi.mock("#execution/durable-session-store.js", () => ({ readDurableSession: vi.fn() }));+vi.mock("#execution/durable-session-store.js", async (importOriginal) => ({+ ...(await importOriginal()),+ readDurableSession: vi.fn(),+}));vi.mock("#execution/tasks/parent/run-parent.js", () => ({ readLatestTaskView: vi.fn() }));-const sessionState = {+const sessionState = createTestSessionState({continuationToken: "parent-token",emissionState: { sequence: 0, sessionStarted: true, stepIndex: 0, turnId: "turn-1" },hasProxyInputRequests: false,sessionId: "parent-session",version: 1,-} as const;+});const hookPayload = {callId: "call-1",childSessionId: "child-1",@@ -48,7 +52,7 @@ const taskIndex = {};function mockSession(handles: readonly unknown[]): void {- vi.mocked(readDurableSession).mockResolvedValue({+ vi.mocked(readDurableSession).mockReturnValue({agent: { system: "" },continuationToken: "parent-token",history: [],diff --git a/packages/eve/src/execution/tools/subagent/accept-event-step.ts b/packages/eve/src/execution/tools/subagent/accept-event-step.tsindex 9b571d359..d0194e6cf 100644--- a/packages/eve/src/execution/tools/subagent/accept-event-step.ts+++ b/packages/eve/src/execution/tools/subagent/accept-event-step.ts@@ -12,7 +12,7 @@ export async function acceptTaskAuthorizationEventStep(input: {"use step";const { hookPayload, taskId } = input.delivery;- const durableSession = await readDurableSession(input.sessionState);+ const durableSession = readDurableSession(input.sessionState);const entry = findSessionTaskEntry(durableSession.state, taskId);if (entry === undefined) return false;diff --git a/packages/eve/src/execution/tools/subagent/emit-called-step.ts b/packages/eve/src/execution/tools/subagent/emit-called-step.tsindex c96975fc1..342dab379 100644--- a/packages/eve/src/execution/tools/subagent/emit-called-step.ts+++ b/packages/eve/src/execution/tools/subagent/emit-called-step.ts@@ -11,7 +11,7 @@ import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";/** Emits an already-projected task-owned `subagent.called` event on the parent stream. */export async function emitTaskSubagentCalledStep(input: {readonly event: UnstampedMessageStreamEvent;- readonly parentWritable: WritableStream<Uint8Array>;+ readonly sessionWritable: WritableStream<Uint8Array>;readonly serializedContext: Record<string, unknown>;}): Promise<{ readonly serializedContext: Record<string, unknown> }> {"use step";@@ -23,7 +23,7 @@ export async function emitTaskSubagentCalledStep(input: {input.event,buildAdapterContext(adapter, ctx),);- const writer = input.parentWritable.getWriter();+ const writer = input.sessionWritable.getWriter();try {await writer.write(encodeMessageStreamEvent(stampMessageStreamEvent(emitted)));} finally {diff --git a/packages/eve/src/execution/tools/subagent/invoke-agent.test.ts b/packages/eve/src/execution/tools/subagent/invoke-agent.test.tsindex 61dc69f43..90858f994 100644--- a/packages/eve/src/execution/tools/subagent/invoke-agent.test.ts+++ b/packages/eve/src/execution/tools/subagent/invoke-agent.test.ts@@ -64,7 +64,6 @@ describe("background agent invocation routing", () => {});const ctx = { abortSignal: controller.signal, callId: "call-1" } as ToolContext;attachWorkflowToolRunContext(ctx, {- admission: Promise.resolve({ status: "accepted" }),from: {callId: "call-1",execution: "background",@@ -129,7 +128,6 @@ describe("background agent invocation routing", () => {};const ctx = { callId: "call-1" } as ToolContext;attachWorkflowToolRunContext(ctx, {- admission: Promise.resolve({ status: "accepted" }),from,owner: {inbox: "owner-inbox",@@ -215,59 +213,6 @@ describe("background agent invocation routing", () => {]);});- it("does not send the invocation before the owning task is admitted", async () => {- const admission = Promise.withResolvers<{ readonly status: "accepted" }>();- const replies: AgentInvocationReply[] = [- {- kind: "runtime-action-result",- results: [- {- callId: "call-1:agent-reply",- kind: "subagent-result",- origin: "child",- output: "done",- subagentName: "research",- } as never,- ],- },- ];- mocks.createHook.mockReturnValue({- [Symbol.asyncIterator]: () => ({- next: async () =>- replies.length > 0- ? { done: false as const, value: replies.shift()! }- : { done: true as const, value: undefined },- }),- token: "agent-reply",- });- const ctx = { callId: "call-1" } as ToolContext;- attachWorkflowToolRunContext(ctx, {- admission: admission.promise,- from: {- callId: "call-1",- execution: "background",- input: { message: "Find it" },- runId: "run-1",- sequence: 0,- stepIndex: 0,- toolName: "research",- turnId: "turn-1",- },- owner: {- inbox: "owner-inbox",- },- });-- const result = agent(ctx, "research", { message: "Find it" });- await Promise.resolve();- expect(mocks.createHook).not.toHaveBeenCalled();- expect(mocks.resumeHook).not.toHaveBeenCalled();-- admission.resolve({ status: "accepted" });- await expect(result).resolves.toBe("done");- expect(mocks.resumeHook).toHaveBeenCalledTimes(2);- });-it("waits for agent calls inside a blocking workflow tool", async () => {const result = {callId: "call-1:agent-reply",@@ -388,7 +333,7 @@ describe("background agent invocation routing", () => {callId: "call-1",childContinuationToken: "child-continuation",childSessionId: "child-1",- childSessionInbox: advertiseInbox ? { sessionId: "child-1", version: 1 } : undefined,+ childSessionInbox: advertiseInbox ? { sessionId: "child-1" } : undefined,event: {requests: [{@@ -448,7 +393,6 @@ describe("background agent invocation routing", () => {};const ctx = { callId: "call-1" } as ToolContext;attachWorkflowToolRunContext(ctx, {- admission: Promise.resolve({ status: "accepted" }),from,owner: {inbox: "owner-inbox",@@ -460,7 +404,7 @@ describe("background agent invocation routing", () => {expect(mocks.resumeHook).toHaveBeenNthCalledWith(2, "owner-inbox", {kind: "request",from,- replyTo: advertiseInbox ? "eve:session:child-1:inbox" : "child-continuation",+ replyTo: advertiseInbox ? "eve:inbox:v1:eve:session:child-1:inbox" : "child-continuation",request: {kind: "input-batch",requests: [expect.objectContaining({ requestId: "approval-1" })],@@ -470,7 +414,7 @@ describe("background agent invocation routing", () => {expect(mocks.resumeHook).toHaveBeenNthCalledWith(3, "owner-inbox", {kind: "request",from,- replyTo: advertiseInbox ? "eve:session:child-1:inbox" : "child-continuation",+ replyTo: advertiseInbox ? "eve:inbox:v1:eve:session:child-1:inbox" : "child-continuation",request: {kind: "input-batch",requests: [expect.objectContaining({ requestId: "approval-2" })],@@ -533,7 +477,6 @@ describe("background agent invocation routing", () => {};const ctx = { callId: "call-1" } as ToolContext;attachWorkflowToolRunContext(ctx, {- admission: Promise.resolve({ status: "accepted" }),from,owner: {inbox: "owner-inbox",diff --git a/packages/eve/src/execution/tools/subagent/invoke-agent.ts b/packages/eve/src/execution/tools/subagent/invoke-agent.tsindex d52496376..026b34fff 100644--- a/packages/eve/src/execution/tools/subagent/invoke-agent.ts+++ b/packages/eve/src/execution/tools/subagent/invoke-agent.ts@@ -5,17 +5,16 @@ import type {SubagentAuthorizationEventHookPayload,SubagentInputRequestHookPayload,} from "#channel/types.js";-import {- readWorkflowToolRunAdmission,- readWorkflowToolRunOwner,- readWorkflowToolRunRef,-} from "#execution/tools/workflow/ask.js";+import { readWorkflowToolRunOwner, readWorkflowToolRunRef } from "#execution/tools/workflow/ask.js";import { resumeHookStep } from "#execution/tools/workflow/resume-hook-step.js";import type { RuntimeSubagentChildResult, RuntimeSubagentResult } from "#shared/action-types.js";import type { JsonValue } from "#shared/json.js";import type { JsonObject } from "#shared/json.js";import { disposeHook } from "#execution/hook-ownership.js";-import { sessionCommandHookToken } from "#execution/session-command-token.js";+import {+ sessionCommandHookToken,+ sessionInboxHookToken,+} from "#execution/session-inbox/address.js";import type { AgentInput } from "#tools/workflow-definition.js";import type { ToolContext } from "#tools/definition.js";@@ -28,7 +27,7 @@ export type InternalAgentInput = {/*** Asks the owning session to spawn an agent for a workflow tool run. Spawning- * needs owner-held material (auth, capabilities, admission, the agent handle+ * needs owner-held material (auth, capabilities, the agent handle* store) that a workflow tool body never has.*/export interface AgentInvocationRequest {@@ -87,11 +86,6 @@ export async function invokeAgent(validateAgentInput(input);const run = readWorkflowToolRunRef(ctx);const owner = readWorkflowToolRunOwner(ctx);- const admission = readWorkflowToolRunAdmission(ctx);- if (admission !== undefined) {- const admitted = await admission;- if (admitted.status === "rejected") throw new Error(admitted.reason);- }const replies = createHook<AgentInvocationReply>();const invocationId = options.invocationId ?? `${ctx.callId}:${replies.token}`;try {@@ -131,9 +125,11 @@ export async function invokeAgent(await resumeHookStep(owner.inbox, {kind: "request",from: run,+ // Current session inboxes use their physical token. A remote child's+ // create-once operation hook is already a narrowed reply capability.replyTo:reply.childSessionInbox?.sessionId === reply.childSessionId- ? sessionCommandHookToken(reply.childSessionInbox.sessionId)+ ? sessionInboxHookToken(sessionCommandHookToken(reply.childSessionInbox.sessionId)): reply.childContinuationToken,request: {kind: "input-batch",diff --git a/packages/eve/src/execution/tools/subagent/invoke-origin.test.ts b/packages/eve/src/execution/tools/subagent/invoke-origin.test.tsnew file mode 100644index 000000000..8bc84df63--- /dev/null+++ b/packages/eve/src/execution/tools/subagent/invoke-origin.test.ts@@ -0,0 +1,81 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { ContextContainer } from "#context/container.js";+import { deserializeContext } from "#context/serialize.js";+import { prepareActionDispatch } from "#execution/coordination-dispatch-shared.js";+import { createDurableSessionState } from "#execution/durable-session-store.js";+import { setHarnessEmissionState } from "#harness/emission-state.js";+import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";+import { recordSessionTask } from "#tasks/session-index.js";+import { prepareOwnerAgentInvocation } from "./invoke-preparation.js";++vi.mock("#context/serialize.js", () => ({ deserializeContext: vi.fn() }));+vi.mock("#execution/coordination-dispatch-shared.js", () => ({ prepareActionDispatch: vi.fn() }));++describe("background invocation origin", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ const ctx = new ContextContainer();+ ctx.set(BundleKey, {+ subagentRegistry: {+ subagentsByName: new Map([+ [+ "research",+ {+ definition: {+ kind: "subagent",+ name: "research",+ nodeId: "research",+ description: "Research",+ },+ },+ ],+ ]),+ },+ } as never);+ vi.mocked(deserializeContext).mockResolvedValue(ctx);+ });++ it.each([true, false])(+ "uses the task's creating turn after the parent advances: task=%s",+ async (background) => {+ const session = recordSessionTask(+ setHarnessEmissionState(+ {+ agent: { dynamicModel: true, system: "", tools: [] },+ compaction: { recentWindowSize: 5, threshold: 10_000 },+ continuationToken: "parent-token",+ history: [],+ sessionId: "parent",+ },+ { sessionStarted: true, sequence: 3, stepIndex: 2, turnId: "turn-3" },+ ),+ {+ taskId: "task",+ taskRunId: "task-run",+ taskInboxToken: "task-inbox",+ createdByTurnId: "turn-1",+ createdByStepIndex: 0,+ dispatchContext: { auth: { current: null, initiator: null } },+ metadata: { kind: "subagent", name: "research", agentId: "agent" },+ },+ );+ await prepareOwnerAgentInvocation({+ invocation: { target: "research", message: "Review Alice's plan" },+ invocationId: "original-call",+ serializedContext: {},+ sessionState: createDurableSessionState({ session }),+ taskId: background ? "task" : undefined,+ });+ expect(prepareActionDispatch).toHaveBeenCalledWith(+ expect.objectContaining({+ batch: expect.objectContaining({+ event: expect.objectContaining({+ turnId: background ? "turn-1" : "turn-3",+ stepIndex: background ? 0 : 2,+ }),+ }),+ }),+ );+ },+ );+});diff --git a/packages/eve/src/execution/tools/subagent/invoke-preparation.ts b/packages/eve/src/execution/tools/subagent/invoke-preparation.tsindex c01824848..30c643158 100644--- a/packages/eve/src/execution/tools/subagent/invoke-preparation.ts+++ b/packages/eve/src/execution/tools/subagent/invoke-preparation.ts@@ -38,6 +38,7 @@ import {import type { SubagentStartTarget } from "#execution/tools/subagent/start.js";import type { SubagentInputSource } from "#subagents/tool.js";import { createLogger } from "#internal/logging.js";+import { findSessionTaskEntry } from "#tasks/session-index.js";const log = createLogger("execution.agent-invocation");@@ -58,10 +59,15 @@ export async function prepareOwnerAgentInvocation(input: {readonly knownAgentIds?: readonly string[];readonly serializedContext: Record<string, unknown>;readonly sessionState: DurableSessionState;+ readonly taskId?: string;}): Promise<Omit<PreparedCoordinationDispatch<OwnerAgentDispatchPlanEntry>, "sessionState">> {- const durableSession = await readDurableSession(input.sessionState);+ const durableSession = readDurableSession(input.sessionState);const ctx = await deserializeContext(input.serializedContext);const event = getHarnessEmissionState(durableSession.state);+ const task =+ input.taskId === undefined+ ? undefined+ : findSessionTaskEntry(durableSession.state, input.taskId);const action = resolveAgentInvocationAction({ctx,input: input.invocation,@@ -70,7 +76,11 @@ export async function prepareOwnerAgentInvocation(input: {return await prepareActionDispatch({batch: {requests: [action],- event: { ...event, turnId: activeTurnId(event) },+ event: {+ ...event,+ stepIndex: task?.createdByStepIndex ?? event.stepIndex,+ turnId: task?.createdByTurnId ?? activeTurnId(event),+ },},ctx,durableSession,@@ -228,8 +238,8 @@ function isRecursiveAgentAction();}-function resolveAgentInvocationAction(input: {- readonly ctx: Awaited<ReturnType<typeof deserializeContext>>;+export function resolveAgentInvocationAction(input: {+ readonly ctx: ContextReader;readonly input: AgentInvocationRequest["input"];readonly invocationId: string;}): RuntimeAgentDispatchRequest {diff --git a/packages/eve/src/execution/tools/subagent/invoke-step.integration.test.ts b/packages/eve/src/execution/tools/subagent/invoke-step.integration.test.tsindex f76e3ca09..4fff302f7 100644--- a/packages/eve/src/execution/tools/subagent/invoke-step.integration.test.ts+++ b/packages/eve/src/execution/tools/subagent/invoke-step.integration.test.ts@@ -30,7 +30,7 @@ describe("blocking workflow agent continuation", () => {beforeEach(() => {vi.clearAllMocks();vi.mocked(prepareOwnerAgentInvocation).mockImplementation(async (input) => {- const session = await readDurableSession(input.sessionState);+ const session = readDurableSession(input.sessionState);return {adapter: {},adapterCtx: {},@@ -188,7 +188,7 @@ describe("blocking workflow agent continuation", () => {});expect(dispatched).toMatchObject({ agentId: identity.id, kind: "dispatched" });if (dispatched.kind !== "dispatched") throw new Error("Expected dispatch.");- const claimed = getAgentHandleStore(dispatched.sessionState.snapshot?.session.state)?.handles;+ const claimed = getAgentHandleStore(dispatched.sessionState.snapshot.session.state)?.handles;expect(claimed).toEqual([expect.objectContaining({ identity, ownerId: "workflow-run-1", phase: "claimed" }),]);@@ -216,7 +216,7 @@ describe("blocking workflow agent continuation", () => {sessionState: dispatched.sessionState,});sessionState = settled.sessionState;- expect(getAgentHandleStore(sessionState.snapshot?.session.state)?.handles).toEqual([+ expect(getAgentHandleStore(sessionState.snapshot.session.state)?.handles).toEqual([{ address, identity, phase: "available" },]);}diff --git a/packages/eve/src/execution/tools/subagent/invoke-step.test.ts b/packages/eve/src/execution/tools/subagent/invoke-step.test.tsindex 42781fe7f..5f4419466 100644--- a/packages/eve/src/execution/tools/subagent/invoke-step.test.ts+++ b/packages/eve/src/execution/tools/subagent/invoke-step.test.ts@@ -98,7 +98,7 @@ const called = {};beforeEach(() => {vi.clearAllMocks();- vi.mocked(readDurableSession).mockResolvedValue(session as never);+ vi.mocked(readDurableSession).mockReturnValue(session as never);});describe("owner agent invocation dispatch", () => {@@ -118,12 +118,11 @@ describe("owner agent invocation dispatch", () => {phase: "claimed",ownerId: "task-1",}),- parentToken: "agent-reply",- taskId: "task-1",+ reply: { kind: "reply", parentToken: "agent-reply", taskId: "task-1" },}),);expect(dispatched).toMatchObject({ agentId: "agent-1", kind: "dispatched" });- expect(getAgentHandleStore(dispatched.sessionState.snapshot?.session.state)?.handles).toEqual([+ expect(getAgentHandleStore(dispatched.sessionState.snapshot.session.state)?.handles).toEqual([expect.objectContaining({identity: availableRecord.identity,phase: "claimed",@@ -144,7 +143,7 @@ describe("owner agent invocation dispatch", () => {...session,state: setAgentHandleStore(undefined, { handles: [claimed] }),};- vi.mocked(readDurableSession).mockResolvedValue(claimedSession as never);+ vi.mocked(readDurableSession).mockReturnValue(claimedSession as never);vi.mocked(prepareOwnerAgentInvocation).mockResolvedValue({...prepared,session: claimedSession,@@ -181,7 +180,7 @@ describe("owner agent invocation dispatch", () => {expect(first.kind).toBe("dispatched");const firstHandle =first.kind === "dispatched"- ? getAgentHandleStore(first.sessionState.snapshot?.session.state)?.handles[0]+ ? getAgentHandleStore(first.sessionState.snapshot.session.state)?.handles[0]: undefined;expect(firstHandle).toMatchObject({identity: { id: "agent-1" },@@ -189,7 +188,7 @@ describe("owner agent invocation dispatch", () => {phase: "claimed",});- vi.mocked(readDurableSession).mockResolvedValue({+ vi.mocked(readDurableSession).mockReturnValue({...session,state: setAgentHandleStore(undefined, { handles: [availableRecord] }),} as never);@@ -262,7 +261,7 @@ describe("owner agent invocation dispatch", () => {taskInboxToken: "task-token",taskRunId: "task-run",});- vi.mocked(readDurableSession).mockResolvedValue(indexedSession as never);+ vi.mocked(readDurableSession).mockReturnValue(indexedSession as never);vi.mocked(readLatestTaskView).mockResolvedValue({metadata: { kind: "subagent", name: "research" },status: "working",@@ -352,7 +351,7 @@ describe("owner agent invocation dispatch", () => {taskInboxToken: "task-token",taskRunId: "task-run",});- vi.mocked(readDurableSession).mockResolvedValue(indexedSession as never);+ vi.mocked(readDurableSession).mockReturnValue(indexedSession as never);vi.mocked(readLatestTaskView).mockResolvedValue({metadata: { kind: "subagent", name: "research" },status: "working",@@ -391,7 +390,7 @@ describe("owner agent invocation dispatch", () => {});it("rejects only nested dispatch for a legacy task without creator context", async () => {- vi.mocked(readDurableSession).mockResolvedValue({+ vi.mocked(readDurableSession).mockReturnValue({...session,state: {...session.state,@@ -446,7 +445,7 @@ describe("owner agent invocation dispatch", () => {phase: "reserved" as const,ownerId: "task-1",};- vi.mocked(readDurableSession).mockResolvedValue({+ vi.mocked(readDurableSession).mockReturnValue({...session,state: setAgentHandleStore(undefined, { handles: [reserved] }),} as never);@@ -478,7 +477,7 @@ describe("owner agent invocation dispatch", () => {}),}),);- expect(getAgentHandleStore(dispatched.sessionState.snapshot?.session.state)?.handles).toEqual(+ expect(getAgentHandleStore(dispatched.sessionState.snapshot.session.state)?.handles).toEqual(expect.arrayContaining([expect.objectContaining({ ownerId: "task-1", phase: "claimed" })]),);});@@ -492,7 +491,7 @@ describe("task-owned agent settlement", () => {phase: "claimed" as const,ownerId: "task-1",};- vi.mocked(readDurableSession).mockResolvedValue({+ vi.mocked(readDurableSession).mockReturnValue({...session,state: setAgentHandleStore(undefined, { handles: [claimed] }),} as never);@@ -521,8 +520,7 @@ describe("task-owned agent settlement", () => {taskId: "task-1",});- const handles =- getAgentHandleStore(settled.sessionState.snapshot?.session.state)?.handles ?? [];+ const handles = getAgentHandleStore(settled.sessionState.snapshot.session.state)?.handles ?? [];expect(handles).toEqual(kind === "parked" ? [expect.objectContaining({ phase: "available" })] : [],);@@ -535,7 +533,7 @@ describe("task-owned agent settlement", () => {ownerId: "workflow-run-1",phase: "claimed" as const,};- vi.mocked(readDurableSession).mockResolvedValue({+ vi.mocked(readDurableSession).mockReturnValue({...session,state: setAgentHandleStore(undefined, { handles: [claimed] }),} as never);@@ -545,7 +543,7 @@ describe("task-owned agent settlement", () => {sessionState: {} as never,});- expect(getAgentHandleStore(released.sessionState.snapshot?.session.state)?.handles).toEqual([+ expect(getAgentHandleStore(released.sessionState.snapshot.session.state)?.handles).toEqual([availableRecord,]);});@@ -557,7 +555,7 @@ describe("task-owned agent settlement", () => {ownerId: "workflow-run-1",phase: "claimed" as const,};- vi.mocked(readDurableSession).mockResolvedValue({+ vi.mocked(readDurableSession).mockReturnValue({...session,state: setAgentHandleStore(undefined, { handles: [claimed] }),} as never);@@ -568,7 +566,7 @@ describe("task-owned agent settlement", () => {sessionState: {} as never,});- expect(getAgentHandleStore(released.sessionState.snapshot?.session.state)?.handles).toEqual([+ expect(getAgentHandleStore(released.sessionState.snapshot.session.state)?.handles).toEqual([{address: availableRecord.address,identity: availableRecord.identity,@@ -585,7 +583,7 @@ describe("task-owned agent settlement", () => {phase: "claimed" as const,ownerId: "workflow-run-1",};- vi.mocked(readDurableSession).mockResolvedValue({+ vi.mocked(readDurableSession).mockReturnValue({...session,state: setAgentHandleStore(undefined, { handles: [claimed] }),} as never);@@ -613,7 +611,7 @@ describe("task-owned agent settlement", () => {sessionState: {} as never,});- expect(getAgentHandleStore(settled.sessionState.snapshot?.session.state)?.handles).toEqual([+ expect(getAgentHandleStore(settled.sessionState.snapshot.session.state)?.handles).toEqual([{address: availableRecord.address,identity: availableRecord.identity,diff --git a/packages/eve/src/execution/tools/subagent/invoke-step.ts b/packages/eve/src/execution/tools/subagent/invoke-step.tsindex e7a96131b..5daa651ad 100644--- a/packages/eve/src/execution/tools/subagent/invoke-step.ts+++ b/packages/eve/src/execution/tools/subagent/invoke-step.ts@@ -97,7 +97,7 @@ export async function dispatchAgentInvocation(input: {readonly invocationContext?: Record<string, unknown>;readonly taskId?: string | undefined;}): Promise<AgentInvocationDispatchResult> {- const durableSession = await readDurableSession(input.sessionState);+ const durableSession = readDurableSession(input.sessionState);const agentHandles = getAgentHandleStore(durableSession.state)?.handles ?? [];const prepared = await prepareOwnerAgentInvocation({invocation: input.request.input,@@ -105,6 +105,7 @@ export async function dispatchAgentInvocation(input: {knownAgentIds: agentHandles.map((handle) => handle.identity.id),serializedContext: input.invocationContext ?? input.serializedContext,sessionState: input.sessionState,+ taskId: input.taskId,});const entry = prepared.plan[0];if (entry === undefined) {@@ -203,9 +204,11 @@ export async function dispatchAgentInvocation(input: {auth: prepared.auth,bundle,currentSession: session,- parentToken: input.replyTo,handle: claimed,- taskId: input.taskId,+ reply:+ input.taskId === undefined+ ? { kind: "reply", parentToken: input.replyTo }+ : { kind: "reply", parentToken: input.replyTo, taskId: input.taskId },});if (outcome.kind === "error" && outcome.deliveryPermanent === true) {applyHandleCommand({ agentId: entry.agentId, kind: "remove", ownerId: input.ownerId });@@ -345,7 +348,7 @@ export async function dispatchTaskAgentInvocationStep(let activityWorkIdentity: ActivityWorkIdentityV1 | undefined;let taskDispatchContext: TaskAgentDispatchContext | undefined;if (input.taskId !== undefined) {- const session = await readDurableSession(input.sessionState);+ const session = readDurableSession(input.sessionState);const entry = findSessionTaskEntry(session.state, input.taskId);if (entry === undefined) return { kind: "not-admitted", sessionState: input.sessionState };const view = await readLatestTaskView({ taskRunId: entry.taskRunId });@@ -425,7 +428,7 @@ export async function settleTaskAgentInvocationStep(input: {}> {"use step";- const durable = await readDurableSession(input.sessionState);+ const durable = readDurableSession(input.sessionState);const serializedContext = await flushAgentInvocationTraces(settleAgentInvocationTrace({acceptedAtMs: Date.now(),@@ -500,7 +503,7 @@ export async function releaseAgentInvocationOwnerStep(input: {}): Promise<{ readonly sessionState: DurableSessionState }> {"use step";- const durable = await readDurableSession(input.sessionState);+ const durable = readDurableSession(input.sessionState);const session = input.cancelled? abandonAgentInvocationOwners(durable, new Set([input.ownerId])): applyTaskAgentHandleCommand(durable, {diff --git a/packages/eve/src/execution/tools/subagent/steer.ts b/packages/eve/src/execution/tools/subagent/steer.tsnew file mode 100644index 000000000..dd8094df1--- /dev/null+++ b/packages/eve/src/execution/tools/subagent/steer.ts@@ -0,0 +1,46 @@+import type { ContextReader } from "#context/key.js";+import { AuthKey } from "#context/keys.js";+import { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";+import type { HarnessSession } from "#harness/types.js";+import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";+import type { JsonObject } from "#shared/json.js";+import { createAgentContinuationBundle } from "#subagents/continuation-bundle.js";+import { dispatchToClaimedAgentAddress } from "#subagents/handle-dispatch.js";+import type { TaskOwnedAgentHandle } from "#subagents/handles/store.js";+import { normalizeRequestedOutputSchema } from "#subagents/invocation.js";+import { resolveAgentInvocationAction } from "./invoke-preparation.js";++export async function steerBackgroundAgent(input: {+ readonly ctx: ContextReader;+ readonly handle: Extract<TaskOwnedAgentHandle, { phase: "claimed" }>;+ readonly callId: string;+ readonly input: JsonObject;+ readonly session: HarnessSession;+}): Promise<void> {+ const action = resolveAgentInvocationAction({+ ctx: input.ctx,+ invocationId: input.callId,+ input: {+ agentId: input.handle.identity.id,+ message: typeof input.input.message === "string" ? input.input.message : "",+ outputSchema: normalizeRequestedOutputSchema(input.input.outputSchema),+ target: input.handle.identity.name,+ },+ });+ const dynamic = getDynamicSubagentSelection(input.ctx, input.handle.identity.nodeId);+ const outcome = await dispatchToClaimedAgentAddress({+ action,+ auth: input.ctx.get(AuthKey) ?? null,+ bundle: createAgentContinuationBundle({+ action,+ bundle: input.ctx.require(BundleKey),+ dynamicRemoteAgent: dynamic?.kind === "remote" ? dynamic.remoteAgent : undefined,+ }),+ currentSession: input.session,+ handle: input.handle,+ reply: { kind: "steer" },+ });+ if (outcome.kind === "error") {+ throw new Error(JSON.stringify(outcome.result.output));+ }+}diff --git a/packages/eve/src/execution/tools/subagent/task-activity.integration.test.ts b/packages/eve/src/execution/tools/subagent/task-activity.integration.test.tsindex d56581382..64c4a3a52 100644--- a/packages/eve/src/execution/tools/subagent/task-activity.integration.test.ts+++ b/packages/eve/src/execution/tools/subagent/task-activity.integration.test.ts@@ -279,8 +279,7 @@ describe("task-owned subagent activity", () => {ownerId: "task-b",phase: "claimed",},- parentToken: "task-b-reply",- taskId: "task-b",+ reply: { kind: "reply", parentToken: "task-b-reply", taskId: "task-b" },});expect(result.kind).toBe("called");let caller: TurnCaller | undefined;@@ -289,11 +288,15 @@ describe("task-owned subagent activity", () => {const request = continueRemote.mock.calls[0]![0];const parsed = parseActivityObserverField(request.activityObserver);if (parsed === undefined || parsed instanceof Response) throw new Error("Invalid observer");- expect(validateActivityObserverBinding(parsed, request.callback)).toBeUndefined();+ const callback = request.callback;+ if (callback === undefined) throw new Error("Expected callback");+ expect(validateActivityObserverBinding(parsed, callback)).toBeUndefined();caller = {- ...request.callback,+ callId: callback.callId,activityObserver: parsed,- replyTo: { kind: "callback", token: request.callback.token, url: request.callback.url },+ subagentName: callback.subagentName,+ taskId: callback.taskId,+ replyTo: { kind: "callback", token: callback.token, url: callback.url },};}const context = await bindTurnCallerContextStep({diff --git a/packages/eve/src/execution/tools/subagent/task-agent-requests.test.ts b/packages/eve/src/execution/tools/subagent/task-agent-requests.test.tsindex f0b52b9e7..f8201998c 100644--- a/packages/eve/src/execution/tools/subagent/task-agent-requests.test.ts+++ b/packages/eve/src/execution/tools/subagent/task-agent-requests.test.ts@@ -48,7 +48,7 @@ describe("workflow-owned agent requests", () => {replyTo: "reply",request: { kind: "agent-settled" as const, result },};- const context = { parentWritable: {} as never, serializedContext, sessionState };+ const context = { sessionWritable: {} as never, serializedContext, sessionState };const settled = await applyTaskAgentRequest(delivery, context);expect(settleTaskAgentInvocationStep).toHaveBeenCalledWith({@@ -95,12 +95,12 @@ describe("workflow-owned agent requests", () => {kind: "agent-invoke",},},- { parentWritable: {} as never, serializedContext, sessionState },+ { sessionWritable: {} as never, serializedContext, sessionState },);expect(emitTaskSubagentCalledStep).toHaveBeenCalledWith({event,- parentWritable: {},+ sessionWritable: {},serializedContext,});expect(applied.serializedContext).toBe(serializedContext);diff --git a/packages/eve/src/execution/tools/subagent/task-agent-requests.ts b/packages/eve/src/execution/tools/subagent/task-agent-requests.tsindex 80aa0e0c7..edb828778 100644--- a/packages/eve/src/execution/tools/subagent/task-agent-requests.ts+++ b/packages/eve/src/execution/tools/subagent/task-agent-requests.ts@@ -16,7 +16,7 @@ export interface AgentRequestDelivery {}export interface TaskAgentRequestContext {- readonly parentWritable: WritableStream<Uint8Array>;+ readonly sessionWritable: WritableStream<Uint8Array>;readonly serializedContext: Record<string, unknown>;readonly sessionState: DurableSessionState;}@@ -64,7 +64,7 @@ export async function applyTaskAgentRequest(case "dispatched": {const emitted = await emitTaskSubagentCalledStep({event: dispatched.event,- parentWritable: ctx.parentWritable,+ sessionWritable: ctx.sessionWritable,serializedContext: dispatched.serializedContext ?? ctx.serializedContext,});return {diff --git a/packages/eve/src/execution/tools/subagent/task-cancel.ts b/packages/eve/src/execution/tools/subagent/task-cancel.tsindex c34753aec..ebcb258a1 100644--- a/packages/eve/src/execution/tools/subagent/task-cancel.ts+++ b/packages/eve/src/execution/tools/subagent/task-cancel.ts@@ -46,7 +46,7 @@ export async function cancelAgentInvocationOwnerStep(input: {}): Promise<void> {"use step";- const session = await readDurableSession(input.sessionState);+ const session = readDurableSession(input.sessionState);const handles = (getAgentHandleStore(session.state)?.handles ?? []).filter((candidate): candidate is Extract<AgentHandle, { phase: "claimed" }> =>candidate.phase === "claimed" && candidate.ownerId === input.ownerId,diff --git a/packages/eve/src/execution/tools/workflow/ask.ts b/packages/eve/src/execution/tools/workflow/ask.tsindex ace2d7b36..1f56a5fa4 100644--- a/packages/eve/src/execution/tools/workflow/ask.ts+++ b/packages/eve/src/execution/tools/workflow/ask.ts@@ -13,11 +13,6 @@ import { workflowToolContextErrorMessage } from "#shared/workflow-tool-context.jconst WORKFLOW_TOOL_RUN_CONTEXT = Symbol.for("eve.workflow-tool-run.context");export interface WorkflowToolRunContext {- readonly authorizationSupported?: boolean;- /** Compatibility for already-started two-run background workflows. */- readonly admission?: Promise<- { readonly status: "accepted" } | { readonly status: "rejected"; readonly reason: string }- >;readonly from: WorkflowToolRunRef;readonly owner: WorkflowToolRunOwner;}@@ -61,12 +56,6 @@ export function readWorkflowToolRunOwner(ctx: ToolContext): WorkflowToolRunOwnerreturn readWorkflowToolRunContext(ctx, "agent").owner;}-export function readWorkflowToolRunAdmission(- ctx: ToolContext,-): WorkflowToolRunContext["admission"] {- return readWorkflowToolRunContext(ctx, "agent").admission;-}-/** Returns an answer hook which may be awaited or raced with another workflow operation. */export function ask(ctx: ToolContext, request: ToolInputRequest): Hook<ToolInputResponse> {const context = readWorkflowToolRunContext(ctx, "ask");diff --git a/packages/eve/src/execution/tools/workflow/body.test.ts b/packages/eve/src/execution/tools/workflow/body.test.tsindex 05ee1d715..1700cea13 100644--- a/packages/eve/src/execution/tools/workflow/body.test.ts+++ b/packages/eve/src/execution/tools/workflow/body.test.ts@@ -2,10 +2,7 @@ import { expect, it, vi } from "vitest";import type { ToolContext } from "#tools/definition.js";import type { WorkflowToolContext } from "#tools/workflow-definition.js";import { executeWorkflowBody, type WorkflowBodyInput } from "#execution/tools/workflow/body.js";-import {- findWorkflowToolRunContext,- readWorkflowToolRunRef,-} from "#execution/tools/workflow/ask.js";+import { readWorkflowToolRunRef } from "#execution/tools/workflow/ask.js";const mocks = vi.hoisted(() => ({ execute: vi.fn(), agent: vi.fn(), ask: vi.fn() }));vi.mock("#execution/workflow-registry.js", () => ({ readRegisteredWorkflow: () => mocks.execute }));@@ -47,40 +44,3 @@ it("binds workflow-only methods to the run context", async () => {reportCount: 0,});});--it.each([- { execution: "background", authorizationSupported: undefined, expected: false },- { execution: "background", authorizationSupported: false, expected: false },- { execution: "background", authorizationSupported: true, expected: true },- { execution: "blocking", authorizationSupported: undefined, expected: true },-] as const)(- "binds auth support to the actual owner ($execution, $authorizationSupported)",- async ({ execution, authorizationSupported, expected }) => {- mocks.execute.mockImplementation(async (_input, ctx) => {- expect(findWorkflowToolRunContext(ctx)?.authorizationSupported).toBe(expected);- return "done";- });- await expect(- executeWorkflowBody(- {- authorizationSupported,- callId: "call",- input: {},- session: {- id: "session",- auth: { current: null, initiator: null },- turn: { id: "turn", sequence: 1 },- },- stepIndex: 0,- taskId: "task",- toolName: "deploy",- workflowId: "workflow//test//execute",- owner: { inbox: "inbox" },- execution,- runId: "run",- },- new AbortController().signal,- ),- ).resolves.toMatchObject({ outcome: { status: "completed", output: "done" } });- },-);diff --git a/packages/eve/src/execution/tools/workflow/body.ts b/packages/eve/src/execution/tools/workflow/body.tsindex 0b251930d..6c0fff26a 100644--- a/packages/eve/src/execution/tools/workflow/body.ts+++ b/packages/eve/src/execution/tools/workflow/body.ts@@ -18,8 +18,6 @@ import type { ToolContext } from "#tools/definition.js";import { createTaskMessage, type TaskExec } from "#tools/task.js";export interface WorkflowBodyDefinition {- /** Advertised by the parent driver; absent on runs started before this capability. */- readonly authorizationSupported?: boolean;readonly callId: string;readonly executeInput?: JsonValue;readonly input: JsonObject;@@ -59,7 +57,6 @@ export async function executeWorkflowBody(attachWorkflowToolRunContext(ctx, {from,owner: input.owner,- authorizationSupported: input.execution === "blocking" || input.authorizationSupported === true,});let reportCount = 0;diff --git a/packages/eve/src/execution/tools/workflow/emit-workflow-tool-run-report-step.ts b/packages/eve/src/execution/tools/workflow/emit-workflow-tool-run-report-step.tsindex ac9b832c4..b5d4775ee 100644--- a/packages/eve/src/execution/tools/workflow/emit-workflow-tool-run-report-step.ts+++ b/packages/eve/src/execution/tools/workflow/emit-workflow-tool-run-report-step.ts@@ -9,7 +9,7 @@ import type { JsonValue } from "#shared/json.js";export async function emitWorkflowToolRunReportStep(input: {readonly from: WorkflowToolRunRef;- readonly parentWritable: WritableStream<Uint8Array>;+ readonly sessionWritable: WritableStream<Uint8Array>;readonly update: JsonValue;}): Promise<void> {"use step";@@ -24,7 +24,7 @@ export async function emitWorkflowToolRunReportStep(input: {stepIndex: input.from.stepIndex,turnId: input.from.turnId,});- const writer = input.parentWritable.getWriter();+ const writer = input.sessionWritable.getWriter();try {await writer.write(encodeMessageStreamEvent(stampMessageStreamEvent(event)));} finally {diff --git a/packages/eve/src/execution/tools/workflow/messages.ts b/packages/eve/src/execution/tools/workflow/messages.tsindex d6b7b5ec1..95830d247 100644--- a/packages/eve/src/execution/tools/workflow/messages.ts+++ b/packages/eve/src/execution/tools/workflow/messages.ts@@ -1,5 +1,3 @@-import { defineHook } from "#compiled/@workflow/core/index.js";-import type { SubagentAuthorizationEventHookPayload } from "#channel/types.js";import type {AgentInvocationRequest,@@ -95,8 +93,6 @@ export type WorkflowToolRunMessage =| ({ readonly kind: "request" } & WorkflowToolRunRequestMessage)| ({ readonly kind: "outcome" } & WorkflowToolRunOutcomeMessage);-export const workflowToolRunHook = defineHook<WorkflowToolRunMessage>();-export type WorkflowToolRunControlMessage = { readonly kind: "cancel"; readonly reason: string };export function isWorkflowToolRunControlMessage(diff --git a/packages/eve/src/execution/tools/workflow/owner.ts b/packages/eve/src/execution/tools/workflow/owner.tsindex 54bb3fc36..a3a44787b 100644--- a/packages/eve/src/execution/tools/workflow/owner.ts+++ b/packages/eve/src/execution/tools/workflow/owner.ts@@ -1,21 +1,25 @@-import {- workflowToolRunHook,- type WorkflowToolRunMessage,- type WorkflowToolRunOwner,+import { createHook } from "#compiled/@workflow/core/index.js";+import type {+ WorkflowToolRunMessage,+ WorkflowToolRunOwner,} from "#execution/tools/workflow/messages.js";import {- type ChannelReader,createChannelReader,+ type ChannelReader,} from "#execution/tools/workflow/owner-channels.js";+import { disposeHook } from "#execution/hook-ownership.js";export interface WorkflowToolRunOwnerInbox {+ dispose(): Promise<void>;readonly owner: WorkflowToolRunOwner;readonly reader: ChannelReader<"workflow", WorkflowToolRunMessage>;}+/** Background task workflows have their own lifecycle, outside a session inbox. */export function openWorkflowToolRunOwnerInbox(): WorkflowToolRunOwnerInbox {- const hook = workflowToolRunHook.create();+ const hook = createHook<WorkflowToolRunMessage>();return {+ dispose: () => disposeHook(hook),owner: { inbox: hook.token },reader: createChannelReader("workflow", hook),};diff --git a/packages/eve/src/execution/tools/workflow/resume-hook-step.ts b/packages/eve/src/execution/tools/workflow/resume-hook-step.tsindex 3f1c74b5e..5414bd988 100644--- a/packages/eve/src/execution/tools/workflow/resume-hook-step.ts+++ b/packages/eve/src/execution/tools/workflow/resume-hook-step.ts@@ -1,7 +1,7 @@import { isTaskWorkflowTargetGone } from "#execution/tasks/workflow-target.js";import { resumeHook } from "#internal/workflow/runtime.js";-/** `resumeHook` as a step, so the runtime API stays out of the driver. */+/** `resumeHook` as a step, so the runtime API stays out of the owner. */export async function resumeHookStep(token: string,payload: unknown,diff --git a/packages/eve/src/execution/tools/workflow/step-context.ts b/packages/eve/src/execution/tools/workflow/step-context.tsindex c6818a645..0a008f3ff 100644--- a/packages/eve/src/execution/tools/workflow/step-context.ts+++ b/packages/eve/src/execution/tools/workflow/step-context.ts@@ -7,7 +7,6 @@ export type WorkflowStepAuthorizationResult = AuthorizationResult & {};export interface WorkflowStepContext {- readonly authorizationSupported: boolean;readonly callId: string;readonly toolName: string;readonly session: SessionContext["session"];diff --git a/packages/eve/src/execution/tools/workflow/step-execution.test.ts b/packages/eve/src/execution/tools/workflow/step-execution.test.tsindex c1bd8e55b..f2d31cc57 100644--- a/packages/eve/src/execution/tools/workflow/step-execution.test.ts+++ b/packages/eve/src/execution/tools/workflow/step-execution.test.ts@@ -47,7 +47,6 @@ function context(user = "user-1"): WorkflowStepContext {principalType: "user" as const,};return {- authorizationSupported: true,baseUrl: "https://agent.example",token: `callback-${user}`,authorizationResults: [],@@ -80,41 +79,6 @@ describe("workflow step authorization", () => {durable.entries.clear();});afterEach(() => vi.unstubAllEnvs());- it.each(["getToken", "requireAuth"] as const)(- "rejects %s before calling the provider when the parent driver lacks authorization support",- async (method) => {- const provider = {- principalType: "user" as const,- getToken: vi.fn(async () => ({ token: "secret" })),- startAuthorization: vi.fn(),- completeAuthorization: vi.fn(),- };- await expect(- runStep(async (ctx) => ctx[method](provider), {- ...context(),- authorizationSupported: false,- }),- ).rejects.toMatchObject({- fatal: true,- retryable: false,- reason: "workflow_task_authorization_unsupported",- message: expect.stringContaining("Start a new session"),- });- expect(provider.getToken).not.toHaveBeenCalled();- expect(provider.startAuthorization).not.toHaveBeenCalled();- expect(provider.completeAuthorization).not.toHaveBeenCalled();- },- );-- it("runs steps that do not use auth when the parent driver lacks authorization support", async () => {- await expect(- runStep(async (ctx) => ({ session: ctx.session.id }), {- ...context(),- authorizationSupported: false,- }),- ).resolves.toMatchObject({ kind: "result", output: { session: "session-1" } });- });-it("does not exchange a consumed code again when the rest of the step retries", async () => {let exchanged = false;const complete = vi.fn(async () => {diff --git a/packages/eve/src/execution/tools/workflow/step-execution.ts b/packages/eve/src/execution/tools/workflow/step-execution.tsindex e4f97cc79..79a8fbc4b 100644--- a/packages/eve/src/execution/tools/workflow/step-execution.ts+++ b/packages/eve/src/execution/tools/workflow/step-execution.ts@@ -1,10 +1,7 @@import { getStepMetadata } from "#compiled/@workflow/core/index.js";import { ContextContainer, contextStorage } from "#context/container.js";import { AuthKey, InitiatorAuthKey, SessionIdKey, SessionKey } from "#context/keys.js";-import {- ConnectionAuthorizationFailedError,- isConnectionAuthorizationFailedError,-} from "#connections/errors.js";+import { isConnectionAuthorizationFailedError } from "#connections/errors.js";import {isAuthorizationSignal,PendingAuthorizationResultKey,@@ -42,20 +39,13 @@ export function withWorkflowStepAuthorization(execute: (...args: never[]) => unkscope: input.toolName,completeAuthorization: completeWorkflowStepAuthorization,});- const unavailable = (): never => {- throw new ConnectionAuthorizationFailedError(input.toolName, {- message: `Background workflow tool "${input.toolName}" cannot use ctx.getToken or ctx.requireAuth in this session because its driver predates workflow-task authorization. Start a new session and try again.`,- reason: "workflow_task_authorization_unsupported",- retryable: false,- });- };const ctx = {...buildBaseToolContext({toolName: input.toolName,options: { abortSignal: input.abortSignal, toolCallId: input.callId },}),- getToken: input.authorizationSupported ? auth.getToken : unavailable,- requireAuth: input.authorizationSupported ? auth.requireAuth : unavailable,+ getToken: auth.getToken,+ requireAuth: auth.requireAuth,};let output: unknown;try {diff --git a/packages/eve/src/execution/tools/workflow/step.ts b/packages/eve/src/execution/tools/workflow/step.tsindex 4b1bf780e..c58d183e7 100644--- a/packages/eve/src/execution/tools/workflow/step.ts+++ b/packages/eve/src/execution/tools/workflow/step.ts@@ -78,7 +78,6 @@ async function executeAuthorizedStep(ctx,execute,receiver,- run,});} catch (error) {if (!ctx.abortSignal.aborted) {@@ -121,11 +120,9 @@ async function invokeAuthorizedStep(input: {readonly ctx: ToolContext;readonly execute: (invocation: WorkflowStepInvocation) => Promise<unknown>;readonly receiver: unknown;- readonly run: WorkflowToolRunContext;}): Promise<WorkflowStepResult> {- const { args, authorizationResults, callbackToken, ctx, execute, receiver, run } = input;+ const { args, authorizationResults, callbackToken, ctx, execute, receiver } = input;const context: WorkflowStepContext = {- authorizationSupported: run.authorizationSupported === true,callId: ctx.callId,toolName: ctx.toolName,session: ctx.session,diff --git a/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts b/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.tsindex 833ae455e..3160ebc18 100644--- a/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts+++ b/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts@@ -2,10 +2,10 @@ import { hydrateWorkflowReturnValue } from "@workflow/core/serialization";import { afterEach, describe, expect, it, vi } from "vitest";import { handleConnectionCallbackRequest } from "#execution/connections/callback-route.js";-import { sessionCommandHookToken } from "#execution/session-command-token.js";+import { sessionCommandHookToken } from "#execution/session-inbox/address.js";import { executeSleepTool, SLEEP_INPUT_SCHEMA } from "#execution/tools/sleep.js";-import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";-import { workflowEntry } from "#execution/workflow-entry.js";+import { resumeSessionInbox } from "#execution/session-inbox/resume.js";+import { workflowEntry } from "#execution/session/entry.js";import { createTestRuntime, type TestRuntime } from "#internal/testing/app-harness.js";import { captureTurnEvents, filterEventsByType } from "#internal/testing/events.js";import {@@ -19,7 +19,6 @@ import {reportingDeployWorkflow,stepThenRaceWorkflow,stepReferenceWorkflow,- workflowAuthorizationCapabilityProbe,} from "#internal/testing/workflow-tool-fixtures.js";import { waitForHook } from "#internal/testing/workflow-test-helpers.js";import { getRun, getWorld, start } from "#internal/workflow/runtime.js";@@ -143,59 +142,6 @@ function eventsText(events: readonly { readonly data?: unknown }[]): string {}describe("workflow step authorization", () => {- it.each(["blocking", "background"] as const)(- "runs %s auth with no advertised driver support",- async (execution) => {- const runtime = await createWorkflowToolRuntime({- agentName: "workflow-step-old-driver",- execute: authorizedDeployWorkflow,- toolName: "deploy_service",- });- await runtime.run(async () => {- const workflowId = Reflect.get(authorizedDeployWorkflow, "workflowId");- if (typeof workflowId !== "string") throw new Error("Missing fixture workflow id");- const auth = {- attributes: {},- authenticator: "test-idp",- issuer: "test-idp",- principalId: "user-1",- principalType: "user" as const,- };- const run = await start(workflowAuthorizationCapabilityProbe, [- {- callId: "auth-call",- execution,- input: { service: "preauthorized" },- owner: { inbox: "unused-owner-inbox" },- session: {- auth: { current: auth, initiator: auth },- id: "old-session",- turn: { id: "new-turn", sequence: 1 },- },- stepIndex: 0,- taskId: "auth-task",- toolName: "deploy_service",- workflowId,- },- ]);- const result = await run.returnValue;- if (execution === "background") {- expect(result.outcome).toMatchObject({- status: "failed",- error: { message: expect.stringContaining("Start a new session") },- });- } else {- expect(result.outcome).toMatchObject({- status: "completed",- output: { authenticatedAs: "user-1" },- });- }- expect(JSON.stringify(result)).not.toContain("secret:");- });- },- 60_000,- );-it.each([false, true])("resolves a user token inside a step (background=%s)",async (background) => {@@ -208,6 +154,8 @@ describe("workflow step authorization", () => {await runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: 'Run deploy_service with service "preauthorized"' },serializedContext: {...buildSerializedContext({@@ -260,6 +208,8 @@ describe("workflow step authorization", () => {await runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: `Run deploy_service with service "${service}"` },serializedContext: {...buildSerializedContext({@@ -378,6 +328,8 @@ describe("workflow step authorization", () => {await runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: `Run deploy_service with service "${disposition}"` },serializedContext: {...buildSerializedContext({@@ -467,6 +419,8 @@ describe("workflow tools", () => {const output = await runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: 'Run deploy_service with service "api"' },serializedContext: buildSerializedContext({continuationToken: "schedule:step-reference",@@ -490,6 +444,8 @@ describe("workflow tools", () => {const output = await runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: "Run sleep" },serializedContext: buildSerializedContext({continuationToken: "schedule:workflow-tool-sleep",@@ -514,6 +470,8 @@ describe("workflow tools", () => {const output = await runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: 'Run deploy_service with service "api"' },serializedContext: buildSerializedContext({continuationToken: "schedule:workflow-tool-wait",@@ -539,6 +497,8 @@ describe("workflow tools", () => {const output = await runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: 'Run deploy_service with service "api"' },serializedContext: buildSerializedContext({continuationToken: "schedule:workflow-tool-fail",@@ -553,84 +513,76 @@ describe("workflow tools", () => {expect(output).toContain("deploy of api exploded");});- it.each(["inline", "child"] as const)(- "routes workflow reports, human input, and outcome on the %s owner",- async (owner) => {- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_inline");- const runtime = await createWorkflowToolRuntime({- agentName: "workflow-tool-hitl",- execute: confirmDeployWorkflow,- toolName: "confirm_deploy",- });+ it("routes workflow reports, human input, and outcome through the session owner", async () => {+ vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_inline");+ const runtime = await createWorkflowToolRuntime({+ agentName: "workflow-tool-hitl",+ execute: confirmDeployWorkflow,+ toolName: "confirm_deploy",+ });- await runtime.run(async () => {- const run = await start(workflowEntry, [- {- input: { message: 'Run confirm_deploy with service "api"' },- serializedContext: buildSerializedContext({- acceptedDeploymentId: owner === "inline" ? "dpl_inline" : undefined,- continuationToken: "http:workflow-tool-hitl",- mode: "conversation",- requestInput: true,- }),- },- ]);- const stream = captureTurnEvents(run);+ await runtime.run(async () => {+ const run = await start(workflowEntry, [+ {+ kind: "initial",+ ownerDeploymentId: "dpl_inline",+ input: { message: 'Run confirm_deploy with service "api"' },+ serializedContext: buildSerializedContext({+ acceptedDeploymentId: "dpl_inline",+ continuationToken: "http:workflow-tool-hitl",+ mode: "conversation",+ requestInput: true,+ }),+ },+ ]);+ const stream = captureTurnEvents(run);- try {- const asked = await stream.nextTurn();- const world = await getWorld();- const parentHooks = (await world.hooks.list({ runId: run.runId })).data;- expect(- parentHooks.some((hook) => hook.token === `${run.runId}:turn-control:0:inbox`),- ).toBe(owner === "inline");- expect(- filterEventsByType(asked, "action.partial").map((event) => event.data.result.output),- ).toEqual(["awaiting approval"]);- const requested = filterEventsByType(asked, "input.requested");- expect(requested).toHaveLength(1);- const request = (requested[0] as InputRequestedStreamEvent).data.requests[0]!;- expect(request).toMatchObject({- action: { input: { service: "api" }, kind: "tool-call", toolName: "confirm_deploy" },- display: "confirmation",- kind: "question",- prompt: "Apply plan:api?",- });- expect(request.options?.map((option) => option.id)).toEqual(["approve", "cancel"]);+ try {+ const asked = await stream.nextTurn();+ expect(+ filterEventsByType(asked, "action.partial").map((event) => event.data.result.output),+ ).toEqual(["awaiting approval"]);+ const requested = filterEventsByType(asked, "input.requested");+ expect(requested).toHaveLength(1);+ const request = (requested[0] as InputRequestedStreamEvent).data.requests[0]!;+ expect(request).toMatchObject({+ action: { input: { service: "api" }, kind: "tool-call", toolName: "confirm_deploy" },+ display: "confirmation",+ kind: "question",+ prompt: "Apply plan:api?",+ });+ expect(request.options?.map((option) => option.id)).toEqual(["approve", "cancel"]);- const commandToken = sessionCommandHookToken(run.runId);- await waitForHook(run, { token: commandToken });- await resumeSessionInbox(commandToken, {- kind: "send",- payload: { inputResponses: [{ optionId: "approve", requestId: request.requestId }] },- });+ const commandToken = sessionCommandHookToken(run.runId);+ await resumeSessionInbox(commandToken, {+ kind: "send",+ payload: { inputResponses: [{ optionId: "approve", requestId: request.requestId }] },+ });- const answered = await stream.nextTurn();- const progress = answered.findIndex(- (event) =>- event.type === "action.partial" && event.data.result.output === "approval received",- );- const resultIndex = answered.findIndex(- (event) =>- event.type === "action.result" &&- event.data.result.kind === "tool-result" &&- event.data.result.toolName === "confirm_deploy",- );- expect(progress).toBeGreaterThanOrEqual(0);- expect(resultIndex).toBeGreaterThan(progress);- const results = filterEventsByType(answered, "action.result");- expect(results.map((event) => JSON.stringify(event.data.result.output))).toContainEqual(- JSON.stringify({ approved: true, service: "api" }),- );- expect(filterEventsByType(answered, "turn.failed")).toHaveLength(0);- } finally {- stream.dispose();- await run.cancel();- }- });- },- 60_000,- );+ const answered = await stream.nextTurn();+ const progress = answered.findIndex(+ (event) =>+ event.type === "action.partial" && event.data.result.output === "approval received",+ );+ const resultIndex = answered.findIndex(+ (event) =>+ event.type === "action.result" &&+ event.data.result.kind === "tool-result" &&+ event.data.result.toolName === "confirm_deploy",+ );+ expect(progress).toBeGreaterThanOrEqual(0);+ expect(resultIndex).toBeGreaterThan(progress);+ const results = filterEventsByType(answered, "action.result");+ expect(results.map((event) => JSON.stringify(event.data.result.output))).toContainEqual(+ JSON.stringify({ approved: true, service: "api" }),+ );+ expect(filterEventsByType(answered, "turn.failed")).toHaveLength(0);+ } finally {+ stream.dispose();+ await run.cancel();+ }+ });+ }, 60_000);it("times out a hook raced against a sleep when it is not resumed", async () => {const runtime = await createWorkflowToolRuntime({@@ -642,6 +594,8 @@ describe("workflow tools", () => {await runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: "Run deploy_service" },serializedContext: buildSerializedContext({continuationToken: "http:workflow-tool-deadline",@@ -674,6 +628,8 @@ describe("workflow tools", () => {await runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: 'Run confirm_deploy with service "api"' },serializedContext: buildSerializedContext({continuationToken: "http:workflow-tool-ask-deadline",@@ -708,115 +664,110 @@ describe("workflow tools", () => {});}, 30_000);- it.each(["inline", "child"] as const)(- "cancels the run when the waiting turn is cancelled and lets the body clean up (%s)",- async (owner) => {- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_inline");- const runtime = await createWorkflowToolRuntime({- agentName: "workflow-tool-cancel",- execute: holdUntilAbortedWorkflow,- toolName: "deploy_service",- });+ it("cancels the run when the waiting turn is cancelled and lets the body clean up", async () => {+ vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_inline");+ const runtime = await createWorkflowToolRuntime({+ agentName: "workflow-tool-cancel",+ execute: holdUntilAbortedWorkflow,+ toolName: "deploy_service",+ });- await runtime.run(async () => {- const before = await listWorkflowToolRunIds();- const run = await start(workflowEntry, [- {- input: { message: 'Run deploy_service with service "api"' },- serializedContext: buildSerializedContext({- acceptedDeploymentId: owner === "inline" ? "dpl_inline" : undefined,- continuationToken: "http:workflow-tool-cancel",- mode: "conversation",- }),- },- ]);- const stream = captureTurnEvents(run);+ await runtime.run(async () => {+ const before = await listWorkflowToolRunIds();+ const run = await start(workflowEntry, [+ {+ kind: "initial",+ ownerDeploymentId: "dpl_inline",+ input: { message: 'Run deploy_service with service "api"' },+ serializedContext: buildSerializedContext({+ acceptedDeploymentId: "dpl_inline",+ continuationToken: "http:workflow-tool-cancel",+ mode: "conversation",+ }),+ },+ ]);+ const stream = captureTurnEvents(run);- try {- const workflowToolRunId = await waitForNewWorkflowToolRun(before);- await waitForHook({ runId: workflowToolRunId });- const commandToken = sessionCommandHookToken(run.runId);- await waitForHook(run, { token: commandToken });- await resumeSessionInbox(commandToken, { kind: "cancel", turnId: "turn_0" });-- // The body is holding in a step that received ctx.abortSignal, so the- // run ends well inside its grace period once the step rejects and- // `finally` runs; a run that ignored the signal would still be running.- expect(await waitForWorkflowToolRunTerminal(workflowToolRunId)).toBe("completed");-- await resumeSessionInbox(commandToken, {- kind: "send",- payload: { message: "Thanks, no deploy today." },- });- const next = await stream.nextTurn();- expect(filterEventsByType(next, "turn.started")).toHaveLength(1);- expect(filterEventsByType(next, "turn.failed")).toHaveLength(0);- expect(next.at(-1)?.type).toBe("session.waiting");- } finally {- stream.dispose();- await run.cancel();- }- });- },- 60_000,- );+ try {+ const workflowToolRunId = await waitForNewWorkflowToolRun(before);+ await waitForHook({ runId: workflowToolRunId });+ const commandToken = sessionCommandHookToken(run.runId);+ await resumeSessionInbox(commandToken, { kind: "cancel", turnId: "turn_0" });- it.each(["inline", "child"] as const)(- "runs a background workflow tool as its task's executor (%s)",- async (owner) => {- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_inline");- const runtime = await createWorkflowToolRuntime({- agentName: "workflow-tool-background",- execute: backgroundDeployWorkflow,- toolName: "report_deploy",- });+ // The body is holding in a step that received ctx.abortSignal, so the+ // run ends well inside its grace period once the step rejects and+ // `finally` runs; a run that ignored the signal would still be running.+ expect(await waitForWorkflowToolRunTerminal(workflowToolRunId)).toBe("completed");- await runtime.run(async () => {- enableBackgroundTool(runtime, "report_deploy");+ await resumeSessionInbox(commandToken, {+ kind: "send",+ payload: { message: "Thanks, no deploy today." },+ });+ const next = await stream.nextTurn();+ expect(filterEventsByType(next, "turn.started")).toHaveLength(1);+ expect(filterEventsByType(next, "turn.failed")).toHaveLength(0);+ expect(next.at(-1)?.type).toBe("session.waiting");+ } finally {+ stream.dispose();+ await run.cancel();+ }+ });+ }, 60_000);- const run = await start(workflowEntry, [- {- input: { message: 'Run report_deploy with service "api"' },- serializedContext: buildSerializedContext({- acceptedDeploymentId: owner === "inline" ? "dpl_inline" : undefined,- continuationToken: "http:workflow-tool-background",- mode: "conversation",- }),- },- ]);- const stream = captureTurnEvents(run);+ it("runs a background workflow tool as its task's executor", async () => {+ vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_inline");+ const runtime = await createWorkflowToolRuntime({+ agentName: "workflow-tool-background",+ execute: backgroundDeployWorkflow,+ toolName: "report_deploy",+ });- try {- const receiptTurn = await stream.nextTurn();- const receipt = filterEventsByType(receiptTurn, "action.result").find(- (event) => event.data.result.kind === "tool-result",- );- expect(receipt?.data.result.output).toMatchObject({ status: "working" });- expect(filterEventsByType(receiptTurn, "turn.failed")).toHaveLength(0);+ await runtime.run(async () => {+ enableBackgroundTool(runtime, "report_deploy");- const notifications: string[] = [];- for (- let turn = 0;- turn < 3 && !notifications.some((text) => text.includes("is completed"));- turn += 1- ) {- const woken = await stream.nextTurn();- expect(filterEventsByType(woken, "turn.failed")).toHaveLength(0);- notifications.push(eventsText(filterEventsByType(woken, "message.received")));- }- const text = notifications.join("\n");- expect(text).toContain("Review plan:api");- expect(text).not.toContain("update: planned api");- expect(text).toContain("is completed");- expect(text).toContain("plan:api");- } finally {- stream.dispose();- await run.cancel();+ const run = await start(workflowEntry, [+ {+ kind: "initial",+ ownerDeploymentId: "dpl_inline",+ input: { message: 'Run report_deploy with service "api"' },+ serializedContext: buildSerializedContext({+ acceptedDeploymentId: "dpl_inline",+ continuationToken: "http:workflow-tool-background",+ mode: "conversation",+ }),+ },+ ]);+ const stream = captureTurnEvents(run);++ try {+ const receiptTurn = await stream.nextTurn();+ const receipt = filterEventsByType(receiptTurn, "action.result").find(+ (event) => event.data.result.kind === "tool-result",+ );+ expect(receipt?.data.result.output).toMatchObject({ status: "working" });+ expect(filterEventsByType(receiptTurn, "turn.failed")).toHaveLength(0);++ const notifications: string[] = [];+ for (+ let turn = 0;+ turn < 3 && !notifications.some((text) => text.includes("is completed"));+ turn += 1+ ) {+ const woken = await stream.nextTurn();+ expect(filterEventsByType(woken, "turn.failed")).toHaveLength(0);+ notifications.push(eventsText(filterEventsByType(woken, "message.received")));}- });- },- 90_000,- );+ const text = notifications.join("\n");+ expect(text).toContain("Review plan:api");+ expect(text).not.toContain("update: planned api");+ expect(text).toContain("is completed");+ expect(text).toContain("plan:api");+ } finally {+ stream.dispose();+ await run.cancel();+ }+ });+ }, 90_000);it("streams a waiting tool's yields as action.partial and settles with its return", async () => {const runtime = await createWorkflowToolRuntime({@@ -828,6 +779,8 @@ describe("workflow tools", () => {await runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: 'Run deploy_service with service "api"' },serializedContext: buildSerializedContext({continuationToken: "http:workflow-tool-progress",@@ -866,6 +819,8 @@ describe("workflow tools", () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: 'Run deploy_service with service "api"' },serializedContext: buildSerializedContext({continuationToken: "http:workflow-tool-background-fail",@@ -911,6 +866,8 @@ describe("workflow tools", () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: 'Run confirm_deploy with service "api"' },serializedContext: buildSerializedContext({continuationToken: "http:workflow-tool-background-hitl",diff --git a/packages/eve/src/execution/turn-cancellation-control.test.ts b/packages/eve/src/execution/turn-cancellation-control.test.tsdeleted file mode 100644index 3cd48c7d8..000000000--- a/packages/eve/src/execution/turn-cancellation-control.test.ts+++ /dev/null@@ -1,189 +0,0 @@-import { afterEach, describe, expect, it, vi } from "vitest";--import { createTurnCancellationControl } from "#execution/turn-cancellation-control.js";-import { turnCancellationHookToken } from "#execution/turn-cancellation-token.js";-import { TurnCancelledError } from "#harness/turn-cancellation.js";--const createHookMock = vi.fn();--vi.mock("#compiled/@workflow/core/index.js", () => ({- createHook: (...args: unknown[]) => createHookMock(...args),-}));--function installCancelHook(options: {- readonly conflict?: { readonly runId: string } | null;- readonly payloads?: readonly unknown[];-}): { dispose: ReturnType<typeof vi.fn> } {- const queue = [...(options.payloads ?? [])];- const dispose = vi.fn();- createHookMock.mockReturnValue({- token: "session-1:cancel",- getConflict: vi.fn(async () => options.conflict ?? null),- dispose,- [Symbol.asyncIterator](): AsyncIterator<unknown> {- return {- next: () => {- const value = queue.shift();- return value === undefined- ? new Promise<IteratorResult<unknown>>(() => {})- : Promise.resolve({ done: false, value });- },- return: vi.fn(async () => ({ done: true, value: undefined })),- };- },- });- return { dispose };-}--async function settles(promise: Promise<unknown>): Promise<boolean> {- return await Promise.race([- promise.then(() => true),- new Promise<boolean>((resolve) => setTimeout(() => resolve(false), 25)),- ]);-}--describe("turnCancellationHookToken", () => {- it("derives a private token from the turn control token", () => {- expect(turnCancellationHookToken("wrun_abc:turn-control:1")).toBe(- "wrun_abc:turn-control:1:cancel",- );- });-});--describe("createTurnCancellationControl", () => {- afterEach(() => {- createHookMock.mockReset();- });-- it("returns undefined when the token is claimed by another run", async () => {- installCancelHook({ conflict: { runId: "wrun_stale" } });-- const control = await createTurnCancellationControl({- controlToken: "session-1",- expectedTurnId: "turn_0",- });-- expect(control).toBeUndefined();- });-- it("aborts the turn signal on a cancel without a turn guard", async () => {- installCancelHook({ payloads: [{}] });-- const control = await createTurnCancellationControl({- controlToken: "session-1",- expectedTurnId: "turn_0",- });-- await expect(control!.requested).resolves.toBe("cancel");- expect(control!.signal.aborted).toBe(true);- expect(control!.signal.reason).toBeInstanceOf(TurnCancelledError);- });-- it("aborts on a cancel whose guard matches the active turn", async () => {- installCancelHook({ payloads: [{ turnId: "turn_2" }] });-- const control = await createTurnCancellationControl({- controlToken: "session-1",- expectedTurnId: "turn_2",- });-- await expect(control!.requested).resolves.toBe("cancel");- expect(control!.signal.aborted).toBe(true);- });-- it("starts aborted when inline execution already consumed cancellation", async () => {- installCancelHook({ payloads: [] });-- const control = await createTurnCancellationControl({- controlToken: "session-1",- expectedTurnId: "turn_2",- initialPayload: { turnId: "turn_2" },- });-- await expect(control!.requested).resolves.toBe("cancel");- expect(control!.signal.aborted).toBe(true);- expect(control!.signal.reason).toBeInstanceOf(TurnCancelledError);- });-- it("consumes a stale turn guard as a no-op and honors the next matching cancel", async () => {- installCancelHook({ payloads: [{ turnId: "turn_99" }, { turnId: "turn_2" }] });-- const control = await createTurnCancellationControl({- controlToken: "session-1",- expectedTurnId: "turn_2",- });-- await expect(control!.requested).resolves.toBe("cancel");- expect(control!.signal.aborted).toBe(true);- });-- it("never aborts when only mismatched guards arrive", async () => {- installCancelHook({ payloads: [{ turnId: "turn_99" }] });-- const control = await createTurnCancellationControl({- controlToken: "session-1",- expectedTurnId: "turn_2",- });-- expect(await settles(control!.requested)).toBe(false);- expect(control!.signal.aborted).toBe(false);- });-- it("flips the signal in the same microtask that consumes the payload", async () => {- // A wake replays a journaled cancel and a completed step in one drain,- // payload first; the settle check reads `signal.aborted` one microtask- // later, so a `.then`-chained abort would lose to it.- let releasePayload!: (result: IteratorResult<unknown>) => void;- const firstRead = new Promise<IteratorResult<unknown>>((resolve) => {- releasePayload = resolve;- });- let delivered = false;- createHookMock.mockReturnValue({- token: "session-1:cancel",- getConflict: vi.fn(async () => null),- dispose: vi.fn(),- [Symbol.asyncIterator](): AsyncIterator<unknown> {- return {- next: () => {- if (delivered) return new Promise<IteratorResult<unknown>>(() => {});- delivered = true;- return firstRead;- },- return: vi.fn(async () => ({ done: true, value: undefined })),- };- },- });-- const control = await createTurnCancellationControl({- controlToken: "session-1",- expectedTurnId: "turn_0",- });-- let releaseStep!: () => void;- const step = new Promise<void>((resolve) => {- releaseStep = resolve;- });- const abortedAtStepContinuation = step.then(() => control!.signal.aborted);-- // Journal order: the cancel payload resolves before the step result.- releasePayload({ done: false, value: {} });- releaseStep();-- await expect(abortedAtStepContinuation).resolves.toBe(true);- await expect(control!.requested).resolves.toBe("cancel");- });-- it("disposes idempotently", async () => {- const { dispose } = installCancelHook({});-- const control = await createTurnCancellationControl({- controlToken: "session-1",- expectedTurnId: "turn_0",- });-- await control!.dispose();- await control!.dispose();-- expect(dispose).toHaveBeenCalledTimes(1);- });-});diff --git a/packages/eve/src/execution/turn-cancellation-control.ts b/packages/eve/src/execution/turn-cancellation-control.tsdeleted file mode 100644index 3c792d6a5..000000000--- a/packages/eve/src/execution/turn-cancellation-control.ts+++ /dev/null@@ -1,106 +0,0 @@-import { createHook } from "#compiled/@workflow/core/index.js";--import { claimHookOwnership, disposeHook, isHookConflictError } from "#execution/hook-ownership.js";-import {- turnCancellationHookToken,- type TurnCancelPayload,-} from "#execution/turn-cancellation-token.js";-import { TurnCancelledError } from "#harness/turn-cancellation.js";--/**- * Owns one turn's cancellation surface inside the turn workflow: the- * turn-private cancel hook and the durable `AbortController` whose- * signal is serialized into every `turnStep`. Must be created inside a- * `"use workflow"` body.- */-export interface TurnCancellationControl {- /** Turn signal to serialize into each `turnStep` input. */- readonly signal: AbortSignal;- /**- * Resolves `"cancel"` once a matching cancel payload is consumed and- * the signal aborted. Race it against turn-owned awaits — never- * `await` it alone.- */- readonly payload: Promise<TurnCancelPayload>;- readonly requested: Promise<"cancel">;- /** Disposes the hook, abandoning any outstanding read. Idempotent. */- dispose(): Promise<void>;-}--/**- * Creates and claims the private cancel hook for one turn workflow run.- * Returns `undefined` when the token is still claimed by a crashed prior- * run — the turn then runs uncancellable rather than failing.- */-export async function createTurnCancellationControl(input: {- readonly controlToken: string;- readonly expectedTurnId: string;- readonly initialPayload?: TurnCancelPayload;-}): Promise<TurnCancellationControl | undefined> {- const hook = createHook<TurnCancelPayload>({- token: turnCancellationHookToken(input.controlToken),- });- // Hook promises and iterators share one durable cursor. Create the- // iterator before claiming so conflict replay is consumed by- // getConflict(), not a later iterator read.- const iterator = hook[Symbol.asyncIterator]();-- try {- await claimHookOwnership(hook);- } catch (error) {- if (isHookConflictError(error)) return undefined;- throw error;- }-- const controller = new AbortController();- // The abort must fire inside the read continuation — not a chained- // `.then` — so the signal is already flipped when a same-drain- // continuation (the turn loop's settle check) reads it; one microtask- // later and an ordinary completion swallows the cancel.- const abort = () => controller.abort(new TurnCancelledError());- const initiallyCancelled =- input.initialPayload !== undefined &&- matchesActiveTurn(input.initialPayload, input.expectedTurnId);- if (initiallyCancelled) abort();- const payload = initiallyCancelled- ? Promise.resolve(input.initialPayload!)- : consumeMatchingCancel(iterator, input.expectedTurnId, abort);-- let disposed = false;- return {- payload,- signal: controller.signal,- requested: payload.then(() => "cancel" as const),- async dispose(): Promise<void> {- if (disposed) return;- disposed = true;- // Never `iterator.return()`: it would await the pending durable- // read forever, leaving the run `running` and its hooks unswept.- await disposeHook(hook);- },- };-}--// Mismatched turn guards are consumed as no-ops; each read is durable,-// so the skip sequence replays deterministically. `onCancel` fires inside-// the matching read's continuation (see the abort ordering note above).-async function consumeMatchingCancel(- iterator: AsyncIterator<TurnCancelPayload>,- expectedTurnId: string,- onCancel: () => void,-): Promise<TurnCancelPayload> {- while (true) {- const next = await iterator.next();- if (next.done) return await new Promise<never>(() => {});- if (matchesActiveTurn(next.value, expectedTurnId)) {- onCancel();- return next.value;- }- }-}--function matchesActiveTurn(payload: unknown, expectedTurnId: string): boolean {- if (typeof payload !== "object" || payload === null) return true;- const guard = (payload as TurnCancelPayload).turnId;- return guard === undefined || guard === expectedTurnId;-}diff --git a/packages/eve/src/execution/turn-cancellation-token.ts b/packages/eve/src/execution/turn-cancellation-token.tsdeleted file mode 100644index 33cddf0f4..000000000--- a/packages/eve/src/execution/turn-cancellation-token.ts+++ /dev/null@@ -1,13 +0,0 @@-/** Derives the private cancellation hook token for one dispatched turn. */-export function turnCancellationHookToken(controlToken: string): string {- return `${controlToken}:cancel`;-}--/**- * Payload accepted by the private turn cancel hook. A mismatched `turnId` is a- * benign no-op; omitting it targets whichever turn owns the hook.- */-export interface TurnCancelPayload {- readonly tasks?: boolean;- readonly turnId?: string;-}diff --git a/packages/eve/src/execution/turn-cancellation.integration.test.ts b/packages/eve/src/execution/turn-cancellation.integration.test.tsindex 50e8e24b8..6f0f37b6a 100644--- a/packages/eve/src/execution/turn-cancellation.integration.test.ts+++ b/packages/eve/src/execution/turn-cancellation.integration.test.ts@@ -1,3 +1,4 @@+import { sessionInboxHookToken } from "#execution/session-inbox/address.js";import { describe, expect, it } from "vitest";import { getWorld, resumeHook, start } from "#internal/workflow/runtime.js";@@ -11,9 +12,8 @@ import {import { waitForHook } from "#internal/testing/workflow-test-helpers.js";import { ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";-import { sessionCommandHookToken } from "#execution/session-command-token.js";-import { turnCancellationHookToken } from "#execution/turn-cancellation-token.js";-import { workflowEntry } from "#execution/workflow-entry.js";+import { sessionCommandHookToken } from "#execution/session-inbox/address.js";+import { workflowEntry } from "#execution/session/entry.js";import { createWorkflowRuntime } from "#execution/workflow-runtime.js";import { createEveSessionCancelRoutePath } from "#protocol/routes.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";@@ -57,13 +57,17 @@ function buildSerializedContext(overrides: {* aborts, then rejects with the signal's reason — the deterministic* mid-turn anchor for cancellation tests.*/-function buildWaitForCancelTool(onStart: () => void, onAbort: () => void): ResolvedToolDefinition {+function buildWaitForCancelTool(+ onStart: () => void,+ onAbort: () => void,+ completion?: Promise<void>,+): ResolvedToolDefinition {return {description: "Waits until the turn is cancelled.",execute: (_input: unknown, rawCtx: unknown) => {const ctx = rawCtx as ToolContext;onStart();- return new Promise((_resolve, reject) => {+ return new Promise((resolve, reject) => {const abort = (): void => {onAbort();reject(ctx.abortSignal.reason);@@ -73,6 +77,10 @@ function buildWaitForCancelTool(onStart: () => void, onAbort: () => void): Resolreturn;}ctx.abortSignal.addEventListener("abort", abort, { once: true });+ void completion?.then(() => {+ ctx.abortSignal.removeEventListener("abort", abort);+ resolve("Work completed successfully.");+ });});},inputSchema: toInputSchema({ additionalProperties: false, properties: {}, type: "object" }),@@ -91,7 +99,10 @@ interface WaitToolFixture {toolStarts(): number;}-async function createWaitToolRuntime(agentName: string): Promise<WaitToolFixture> {+async function createWaitToolRuntime(+ agentName: string,+ completion?: Promise<void>,+): Promise<WaitToolFixture> {let aborts = 0;let starts = 0;let resolveStarted: (() => void) | undefined;@@ -106,6 +117,7 @@ async function createWaitToolRuntime(agentName: string): Promise<WaitToolFixture() => {aborts += 1;},+ completion,);const runtime = await createTestRuntime({agent: { name: agentName },@@ -209,7 +221,7 @@ async function waitForHookByToken(token: string, timeout = 15_000): Promise<{ ru/*** The retry canary: an aborted `turnStep` settles by *returning*, so the- * turn workflow run must record no `step_failed`/`step_retrying` events+ * owning session run must record no `step_failed`/`step_retrying` events* (nothing thrown ever crosses the step boundary) and at most one* `step_completed` per correlation id. Duplicate `step_started` entries* are allowed: the runtime may supersede an aborted attempt and@@ -313,7 +325,7 @@ async function expectCancelResponse(}describe("turn cancellation integration", () => {- it("settles an abort-shaped memory recall error as cancellation after steering", async () => {+ it("settles an abort-shaped memory recall error after explicit cancellation", async () => {const fixture = await createAbortRecallRuntime("turn-steer-memory-recall", {waitForAbort: true,});@@ -332,6 +344,8 @@ describe("turn cancellation integration", () => {await fixture.runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: "remember this interrupted request" },serializedContext: buildSerializedContext({channelKind: "http",@@ -343,12 +357,12 @@ describe("turn cancellation integration", () => {const stream = captureTurnEvents(run);try {- await waitForHookByToken(continuationToken);- const cancelHook = await waitForHookByToken(- turnCancellationHookToken(`${run.runId}:turn-control:0`),- );+ await waitForHookByToken(sessionInboxHookToken(continuationToken));await fixture.recallStarted;+ await resumeHook(sessionInboxHookToken(sessionCommandHookToken(run.runId)), {+ kind: "cancel",+ });await expect(address.send("replacement after recall abort", { auth: null }),).resolves.toMatchObject({ id: run.runId });@@ -362,7 +376,7 @@ describe("turn cancellation integration", () => {]),).toBe(true);expectNoFailureEvents(cancelledTurn);- await expectNoStepRetries(cancelHook.runId);+ await expectNoStepRetries(run.runId);const replacementTurn = await stream.nextTurn();expect(filterEventsByType(replacementTurn, "turn.started")).toHaveLength(1);@@ -395,6 +409,8 @@ describe("turn cancellation integration", () => {await fixture.runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: "fail memory recall" },serializedContext: buildSerializedContext({channelKind: "http",@@ -417,69 +433,77 @@ describe("turn cancellation integration", () => {});});- it("buffers a default steering message before replacing the active turn", async () => {- const fixture = await createWaitToolRuntime("turn-steer-message");- const rawToken = "turn-steer-message";- const continuationToken = `http:${rawToken}`;- const workflowRuntime = createWorkflowRuntime({- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),- });- const address = createChannelAddress({- adapter: { kind: "http" },- channelName: "http",- continuationToken: rawToken,- runtime: workflowRuntime,- });-- await fixture.runtime.run(async () => {- const run = await start(workflowEntry, [- {- input: { message: `Use the ${WAIT_TOOL_NAME} tool.` },- serializedContext: buildSerializedContext({- channelKind: "http",- continuationToken,- mode: "conversation",- }),- },- ]);- const stream = captureTurnEvents(run);-- try {- await waitForHookByToken(continuationToken);- await fixture.toolStarted;-- await expect(- address.send("replacement after steer", { auth: null }),- ).resolves.toMatchObject({ id: run.runId });-- const cancelledTurn = await stream.nextTurn();- expect(- containsEventSequence(cancelledTurn, [- "turn.started",- "turn.cancelled",- "session.waiting",- ]),- ).toBe(true);- expect(fixture.toolAborts()).toBe(1);+ it.each([+ { turnPolicy: undefined, turnCount: 1 },+ { turnPolicy: "steer" as const, turnCount: 1 },+ { turnPolicy: "queue" as const, turnCount: 2 },+ ])(+ "admits $turnPolicy deliveries without aborting ($turnCount turns)",+ async ({ turnPolicy, turnCount }) => {+ let finishWork!: () => void;+ const completion = new Promise<void>((resolve) => {+ finishWork = resolve;+ });+ const fixture = await createWaitToolRuntime("turn-steer-message", completion);+ const rawToken = "turn-steer-message";+ const continuationToken = `http:${rawToken}`;+ const workflowRuntime = createWorkflowRuntime({+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),+ });+ const address = createChannelAddress({+ adapter: { kind: "http" },+ channelName: "http",+ continuationToken: rawToken,+ runtime: workflowRuntime,+ });- const replacementTurn = await stream.nextTurn();- expect(filterEventsByType(replacementTurn, "turn.started")).toHaveLength(1);- expect(filterEventsByType(replacementTurn, "turn.cancelled")).toHaveLength(0);- expectNoFailureEvents(replacementTurn);- expect(- replacementTurn.some(- (event) =>- event.type === "message.received" &&- typeof event.data.message === "string" &&- event.data.message.includes("replacement after steer"),- ),- ).toBe(true);- } finally {- stream.dispose();- await run.cancel();- }- });- }, 60_000);+ await fixture.runtime.run(async () => {+ const run = await start(workflowEntry, [+ {+ kind: "initial",+ ownerDeploymentId: "dpl_inline",+ input: { message: `Use the ${WAIT_TOOL_NAME} tool.` },+ serializedContext: buildSerializedContext({+ channelKind: "http",+ continuationToken,+ mode: "conversation",+ }),+ },+ ]);+ const stream = captureTurnEvents(run);++ try {+ await waitForHookByToken(sessionInboxHookToken(continuationToken));+ await fixture.toolStarted;++ await expect(+ address.send("follow-up after work", { auth: null, turnPolicy }),+ ).resolves.toMatchObject({ id: run.runId });++ finishWork();+ const events = await stream.nextTurn();+ if (turnCount === 2) events.push(...(await stream.nextTurn()));+ expect(fixture.toolAborts()).toBe(0);+ expect(filterEventsByType(events, "turn.started")).toHaveLength(turnCount);+ expect(filterEventsByType(events, "turn.cancelled")).toHaveLength(0);+ expectNoFailureEvents(events);+ expect(+ events.some(+ (event) =>+ event.type === "message.received" &&+ typeof event.data.message === "string" &&+ event.data.message.includes("follow-up after work"),+ ),+ ).toBe(true);+ } finally {+ finishWork();+ stream.dispose();+ await run.cancel();+ }+ });+ },+ 60_000,+ );it("cancels a turn mid-tool and accepts the next message normally", async () => {const fixture = await createWaitToolRuntime("turn-cancel-tool");@@ -488,6 +512,8 @@ describe("turn cancellation integration", () => {await fixture.runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: `Use the ${WAIT_TOOL_NAME} tool.` },serializedContext: buildSerializedContext({channelKind: "http",@@ -499,10 +525,7 @@ describe("turn cancellation integration", () => {const stream = captureTurnEvents(run);try {- const commandToken = sessionCommandHookToken(run.runId);- const cancelHook = await waitForHookByToken(- turnCancellationHookToken(`${run.runId}:turn-control:0`),- );+ const commandToken = sessionInboxHookToken(sessionCommandHookToken(run.runId));await waitForHookByToken(commandToken);await fixture.toolStarted;// A matching turn guard cancels the observed turn (the first@@ -512,7 +535,7 @@ describe("turn cancellation integration", () => {const cancelledTurn = await stream.nextTurn();// A duplicate cancel after the turn settled is consumed by the- // parked driver and must not disturb the session.+ // parked owner and must not disturb the session.await resumeHook(commandToken, { kind: "cancel" });expect(cancelledTurn.at(-1)?.type).toBe("session.waiting");@@ -531,10 +554,13 @@ describe("turn cancellation integration", () => {expectNoFailureEvents(cancelledTurn);expect(fixture.toolStarts()).toBe(1);- await expectNoStepRetries(cancelHook.runId);+ await expectNoStepRetries(run.runId);- await waitForHook({ runId: run.runId }, { token: continuationToken });- await resumeHook(continuationToken, {+ await waitForHook(+ { runId: run.runId },+ { token: sessionInboxHookToken(continuationToken) },+ );+ await resumeHook(sessionInboxHookToken(continuationToken), {kind: "send",payload: { message: "follow up after cancel" },});@@ -570,6 +596,8 @@ describe("turn cancellation integration", () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: `Use the ${WAIT_TOOL_NAME} tool.` },serializedContext: buildSerializedContext({channelKind: "http",@@ -581,7 +609,7 @@ describe("turn cancellation integration", () => {const stream = captureTurnEvents(run);try {- await waitForHookByToken(sessionCommandHookToken(run.runId));+ await waitForHookByToken(sessionInboxHookToken(sessionCommandHookToken(run.runId)));await fixture.toolStarted;const cancelled = await cancelViaRoute(run.runId);@@ -609,8 +637,11 @@ describe("turn cancellation integration", () => {const duplicate = await cancelViaRoute(run.runId, { turnId: started.data.turnId });await expectCancelResponse(duplicate, { sessionId: run.runId, status: "accepted" });- await waitForHook({ runId: run.runId }, { token: continuationToken });- await resumeHook(continuationToken, {+ await waitForHook(+ { runId: run.runId },+ { token: sessionInboxHookToken(continuationToken) },+ );+ await resumeHook(sessionInboxHookToken(continuationToken), {kind: "send",payload: { message: "follow up after route cancel" },});@@ -658,6 +689,8 @@ describe("turn cancellation integration", () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: `Use the ${WAIT_TOOL_NAME} tool.` },serializedContext: buildSerializedContext({channelKind: "http",@@ -669,7 +702,7 @@ describe("turn cancellation integration", () => {const stream = captureTurnEvents(run);try {- await waitForHookByToken(continuationToken);+ await waitForHookByToken(sessionInboxHookToken(continuationToken));await fixture.toolStarted;await expect(address(rawToken).cancel()).resolves.toEqual({@@ -731,6 +764,8 @@ describe("turn cancellation integration", () => {await fixture.runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: `Use the ${WAIT_TOOL_NAME} tool.` },serializedContext: buildSerializedContext({channelKind: "http",@@ -742,7 +777,7 @@ describe("turn cancellation integration", () => {const stream = captureTurnEvents(run);try {- const cancelToken = sessionCommandHookToken(run.runId);+ const cancelToken = sessionInboxHookToken(sessionCommandHookToken(run.runId));await waitForHookByToken(cancelToken);await fixture.toolStarted;@@ -778,6 +813,8 @@ describe("turn cancellation integration", () => {await runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: "hello there" },serializedContext: buildSerializedContext({channelKind: "http",@@ -793,11 +830,16 @@ describe("turn cancellation integration", () => {expect(firstTurn.at(-1)?.type).toBe("session.waiting");expect(filterEventsByType(firstTurn, "turn.completed")).toHaveLength(1);- // The stable inbox accepts a late cancel and the parked driver consumes it as a no-op.- await resumeHook(sessionCommandHookToken(run.runId), { kind: "cancel" });+ // The stable inbox accepts a late cancel and the parked owner consumes it as a no-op.+ await resumeHook(sessionInboxHookToken(sessionCommandHookToken(run.runId)), {+ kind: "cancel",+ });- await waitForHook({ runId: run.runId }, { token: continuationToken });- await resumeHook(continuationToken, {+ await waitForHook(+ { runId: run.runId },+ { token: sessionInboxHookToken(continuationToken) },+ );+ await resumeHook(sessionInboxHookToken(continuationToken), {kind: "send",payload: { message: "follow up after late cancel" },});@@ -820,65 +862,4 @@ describe("turn cancellation integration", () => {}});});-- it("completes settled turn runs so the world sweeps their hooks", async () => {- const runtime = await createTestRuntime({ agent: { name: "turn-cancel-sweep" } });- const continuationToken = "http:turn-cancel-sweep";-- await runtime.run(async () => {- const run = await start(workflowEntry, [- {- input: { message: "first turn" },- serializedContext: buildSerializedContext({- channelKind: "http",- continuationToken,- mode: "conversation",- }),- },- ]);- const stream = captureTurnEvents(run);-- try {- expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");-- await waitForHook({ runId: run.runId }, { token: continuationToken });- await resumeHook(continuationToken, {- kind: "send",- payload: { message: "second turn" },- });- expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");-- // Teardown must not await the cancel hook's outstanding read: a- // turn run that never returns stays `running` forever and its- // hooks are never swept. With the session parked, no cancel hook- // may remain in the world.- const world = await getWorld();- const deadline = Date.now() + 15_000;- let completedTurnRuns = 0;- let cancelHooks = 0;- while (Date.now() < deadline) {- const cancelToken0 = turnCancellationHookToken(`${run.runId}:turn-control:0`);- const cancelHook0 = await world.hooks.getByToken(cancelToken0).catch(() => null);- cancelHooks = cancelHook0 === null ? 0 : 1;-- const runsPage = await world.runs.list({ pagination: { limit: 100 } });- completedTurnRuns = runsPage.data.filter(- (row: { status?: string; workflowName?: string }) =>- row.workflowName?.includes("turnWorkflow") === true && row.status === "completed",- ).length;-- if (completedTurnRuns >= 1 && cancelHooks === 0) break;- await new Promise((resolve) => setTimeout(resolve, 100));- }-- // The first turn settled a full turn ago: its run must have- // completed and its cancel hook must be gone from the world.- expect(completedTurnRuns).toBeGreaterThanOrEqual(1);- expect(cancelHooks).toBe(0);- } finally {- stream.dispose();- await run.cancel();- }- });- }, 60_000);});diff --git a/packages/eve/src/execution/turn-control-protocol.test.ts b/packages/eve/src/execution/turn-control-protocol.test.tsdeleted file mode 100644index ebf7c68d3..000000000--- a/packages/eve/src/execution/turn-control-protocol.test.ts+++ /dev/null@@ -1,34 +0,0 @@-import { describe, expect, it, vi } from "vitest";--import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";-import { sendTurnControlStep } from "#execution/turn-control-protocol.js";-import { resumeHook } from "#internal/workflow/runtime.js";--vi.mock("#compiled/@workflow/core/runtime.js", () => ({- resumeHook: vi.fn(),-}));--describe("sendTurnControlStep", () => {- it("ignores an obsolete send after the session driver releases its hook", async () => {- vi.mocked(resumeHook).mockRejectedValue(new HookNotFoundError("turn-control"));-- await expect(- sendTurnControlStep({- controlToken: "turn-control",- payload: { kind: "turn-delivery-cancelled", requestId: "delivery-1" },- }),- ).resolves.toBeUndefined();- });-- it("propagates unexpected delivery failures", async () => {- const failure = new Error("world unavailable");- vi.mocked(resumeHook).mockRejectedValue(failure);-- await expect(- sendTurnControlStep({- controlToken: "turn-control",- payload: { kind: "turn-delivery-cancelled", requestId: "delivery-1" },- }),- ).rejects.toBe(failure);- });-});diff --git a/packages/eve/src/execution/turn-control-protocol.ts b/packages/eve/src/execution/turn-control-protocol.tsdeleted file mode 100644index ac39d4a75..000000000--- a/packages/eve/src/execution/turn-control-protocol.ts+++ /dev/null@@ -1,48 +0,0 @@-import type { DeliverHookPayload, HookPayload } from "#channel/types.js";-import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";-import type { NextDriverAction } from "#execution/next-driver-action.js";-import { resumeHook } from "#internal/workflow/runtime.js";--/** Payloads delivered to the private inbox owned by one active turn. */-export type TurnInboxPayload =- | Exclude<HookPayload, DeliverHookPayload>- | {- readonly delivery: DeliverHookPayload;- readonly kind: "driver-delivery";- readonly requestId: string;- };--/** Control payloads emitted from an active turn to its session driver. */-export type TurnControlPayload =- | {- readonly action: NextDriverAction;- readonly bufferedDeliveries?: readonly DeliverHookPayload[];- readonly kind: "turn-result";- }- | { readonly kind: "turn-error"; readonly error: unknown }- | { readonly continuationToken: string; readonly kind: "turn-continuation-token" }- | {- readonly continuationToken: string;- readonly inboxToken: string;- readonly kind: "turn-delivery-request";- readonly requestId: string;- }- | { readonly kind: "turn-delivery-accepted"; readonly requestId: string }- | { readonly kind: "turn-delivery-cancelled"; readonly requestId: string };--/** Sends one lifecycle payload to the session driver's control hook. */-export async function sendTurnControlStep(input: {- readonly controlToken: string;- readonly payload: TurnControlPayload;-}): Promise<void> {- "use step";-- try {- await resumeHook(input.controlToken, input.payload);- } catch (error) {- // Reset and timeout terminally stop the session driver while its child- // turn may still be unwinding. A final at-least-once control send then- // has no receiver and is already obsolete.- if (!HookNotFoundError.is(error)) throw error;- }-}diff --git a/packages/eve/src/execution/turn-control-receiver.test.ts b/packages/eve/src/execution/turn-control-receiver.test.tsdeleted file mode 100644index 1fa278881..000000000--- a/packages/eve/src/execution/turn-control-receiver.test.ts+++ /dev/null@@ -1,388 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--import type { DeliverHookPayload } from "#channel/types.js";-import type { DurableSessionState } from "#execution/durable-session-store.js";-import { cancelAllIndexedSessionTasksStep } from "#execution/cancel-indexed-session-tasks-step.js";-import { SessionStateCursor } from "#execution/session-state-cursor.js";-import { forwardTurnCancellationStep } from "#execution/forward-turn-cancellation-step.js";-import { forwardTurnDeliveryStep } from "#execution/forward-turn-delivery-step.js";-import { reportDroppedWirePayloadStep } from "#execution/report-dropped-wire-payload-step.js";-import type { SessionCommandInbox, SessionInboxPayload } from "#execution/session-command-inbox.js";-import type { TurnControlPayload } from "#execution/turn-control-protocol.js";-import { TurnControlReceiver } from "#execution/turn-control-receiver.js";--const createHookMock = vi.fn();--vi.mock("#compiled/@workflow/core/index.js", () => ({- createHook: (...args: unknown[]) => createHookMock(...args),-}));--vi.mock("./cancel-indexed-session-tasks-step.js", () => ({- cancelAllIndexedSessionTasksStep: vi.fn(),-}));--vi.mock("./forward-turn-delivery-step.js", () => ({- forwardTurnDeliveryStep: vi.fn(),-}));--vi.mock("./forward-turn-cancellation-step.js", () => ({- forwardTurnCancellationStep: vi.fn(),-}));--vi.mock("./report-dropped-wire-payload-step.js", () => ({- reportDroppedWirePayloadStep: vi.fn(),-}));--describe("TurnControlReceiver", () => {- beforeEach(() => {- vi.clearAllMocks();- createHookMock.mockReset();- });-- it("forwards a buffered delivery and consumes it once the turn accepts", async () => {- const delivery: DeliverHookPayload = {- kind: "deliver",- payloads: [{ inputResponses: [{ optionId: "yes", requestId: "input-1" }] }],- };- installControlHook([- deliveryRequest("req-1"),- { kind: "turn-delivery-accepted", requestId: "req-1" },- parkResult(),- ]);- const bufferedDeliveries: DeliverHookPayload[] = [delivery];-- const action = await runReceiver(bufferedDeliveries);-- expect(forwardTurnDeliveryStep).toHaveBeenCalledWith({- inboxToken: "turn-inbox",- payload: { delivery, kind: "driver-delivery", requestId: "req-1" },- });- expect(action.kind).toBe("park");- expect(bufferedDeliveries).toEqual([]);- });-- it("re-buffers the outstanding delivery when the turn cancels its request", async () => {- const delivery: DeliverHookPayload = {- kind: "deliver",- payloads: [{ inputResponses: [{ optionId: "yes", requestId: "input-1" }] }],- };- installControlHook([- deliveryRequest("req-1"),- { kind: "turn-delivery-cancelled", requestId: "req-1" },- parkResult(),- ]);- const bufferedDeliveries: DeliverHookPayload[] = [delivery];-- const action = await runReceiver(bufferedDeliveries);-- expect(forwardTurnDeliveryStep).toHaveBeenCalledOnce();- expect(action.kind).toBe("park");- expect(bufferedDeliveries).toEqual([delivery]);- });-- it("keeps earlier remainders ahead of an unresolved delivery when the turn terminates", async () => {- const outstanding: DeliverHookPayload = {- kind: "deliver",- payloads: [{ inputResponses: [{ optionId: "yes", requestId: "input-1" }] }],- };- const earlierRemainder: DeliverHookPayload = {- kind: "deliver",- payloads: [{ message: "earlier remainder" }],- };- installControlHook([- deliveryRequest("req-1"),- {- action: { kind: "done", output: "bye", serializedContext: {}, sessionState: createState() },- bufferedDeliveries: [earlierRemainder],- kind: "turn-result",- },- ]);- const bufferedDeliveries: DeliverHookPayload[] = [outstanding];-- const action = await runReceiver(bufferedDeliveries);-- expect(action).toMatchObject({ kind: "done", output: "bye" });- expect(bufferedDeliveries).toEqual([earlierRemainder, outstanding]);- });-- it("hands the turn's remainders back ahead of existing buffered deliveries", async () => {- const earlier: DeliverHookPayload = { kind: "deliver", payloads: [{ message: "earlier" }] };- const handBack: DeliverHookPayload = { kind: "deliver", payloads: [{ message: "from-turn" }] };- installControlHook([{ ...parkResult(), bufferedDeliveries: [handBack] }]);- const bufferedDeliveries: DeliverHookPayload[] = [earlier];-- await runReceiver(bufferedDeliveries);-- expect(bufferedDeliveries.map((item) => item.payloads[0]?.message)).toEqual([- "from-turn",- "earlier",- ]);- });-- it("rethrows a rebuilt error when the turn reports a failure", async () => {- installControlHook([{ error: { message: "boom", name: "TurnError" }, kind: "turn-error" }]);-- await expect(runReceiver([])).rejects.toThrow("boom");- });-- it("buffers current and legacy sends that arrive during a turn", async () => {- installControlHook([parkResult()], true);- const bufferedDeliveries: DeliverHookPayload[] = [];- const bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset"> = [];-- const action = await runReceiver(bufferedDeliveries, {- bufferedSessionControls,- commandInbox: createCommandInbox([- { kind: "send", payload: { message: "follow up" } },- { kind: "deliver", payloads: [{ message: "legacy follow up" }] },- { kind: "clear" },- { kind: "compact" },- { kind: "session-timeout" },- ]),- });-- expect(action.kind).toBe("park");- // Decode normalizes: the wire-only mirror and `v` never reach buffers.- expect(bufferedDeliveries).toEqual([- {- auth: undefined,- caller: undefined,- kind: "deliver",- payloads: [{ message: "follow up" }],- requestId: undefined,- turnPolicy: undefined,- },- { kind: "deliver", payloads: [{ message: "legacy follow up" }] },- ]);- expect(bufferedSessionControls).toEqual(["clear", "compact", "expired"]);- });-- it("consumes a replayed task delivery only once", async () => {- installControlHook([parkResult()], true);- const bufferedDeliveries: DeliverHookPayload[] = [];- const caller = {- callId: "call-task",- replyTo: { kind: "hook" as const, token: "task-token" },- subagentName: "research",- taskId: "task-1",- };-- await runReceiver(bufferedDeliveries, {- commandInbox: createCommandInbox([- { caller, kind: "send", payload: { message: "once" } },- { caller, kind: "send", payload: { message: "duplicate" } },- ]),- seenTaskDeliveries: new Set(),- });-- expect(bufferedDeliveries.map((delivery) => delivery.payloads[0]?.message)).toEqual(["once"]);- });-- it("deduplicates a replayed task response without dropping a different partial response", async () => {- installControlHook([parkResult()], true);- const bufferedDeliveries: DeliverHookPayload[] = [];-- await runReceiver(bufferedDeliveries, {- commandInbox: createCommandInbox([- {- kind: "send",- payload: { inputResponses: [{ requestId: "q1" }] },- taskDeliveryId: "task-1:q1",- },- {- kind: "send",- payload: { inputResponses: [{ requestId: "q1" }] },- taskDeliveryId: "task-1:q1",- },- {- kind: "send",- payload: { inputResponses: [{ requestId: "q2" }] },- taskDeliveryId: "task-1:q2",- },- ]),- seenTaskDeliveries: new Set(),- });-- expect(- bufferedDeliveries.map((delivery) => delivery.payloads[0]?.inputResponses?.[0]?.requestId),- ).toEqual(["q1", "q2"]);- });-- it("discards queued deliveries when their task is cancelled", async () => {- installControlHook([parkResult()], true);- const bufferedDeliveries: DeliverHookPayload[] = [];-- await runReceiver(bufferedDeliveries, {- commandInbox: createCommandInbox([- {- kind: "send",- payload: { inputResponses: [{ requestId: "q1" }] },- taskDeliveryId: "task-1:q1",- },- { kind: "cancel", taskId: "task-1", turnId: "turn_3" },- ]),- seenTaskDeliveries: new Set(),- });-- expect(bufferedDeliveries).toEqual([]);- expect(forwardTurnCancellationStep).toHaveBeenCalledWith({- payload: {},- token: "turn-control:cancel",- });- });-- it("drops an unknown wire version loudly and keeps consuming the inbox", async () => {- installControlHook([parkResult()], true);- const bufferedDeliveries: DeliverHookPayload[] = [];-- const action = await runReceiver(bufferedDeliveries, {- commandInbox: createCommandInbox([- { kind: "deliver", payloads: [{ message: "from the future" }], version: 99 } as never,- { kind: "send", payload: { message: "still delivered" } },- ]),- });-- expect(action.kind).toBe("park");- expect(reportDroppedWirePayloadStep).toHaveBeenCalledOnce();- expect(bufferedDeliveries).toEqual([- {- auth: undefined,- caller: undefined,- kind: "deliver",- payloads: [{ message: "still delivered" }],- requestId: undefined,- turnPolicy: undefined,- },- ]);- });-- it("cancels indexed tasks and preserves active turn cancellation", async () => {- installControlHook([parkResult()], true);-- await runReceiver([], {- commandInbox: createCommandInbox([{ kind: "cancel", tasks: true } as never]),- });-- expect(cancelAllIndexedSessionTasksStep).toHaveBeenCalledWith({- serializedContext: {},- sessionState: expect.objectContaining({ sessionId: "session" }),- });- expect(forwardTurnCancellationStep).toHaveBeenCalledWith({- payload: { tasks: true },- token: "turn-control:cancel",- });- });-- it("forwards cancel and reset through the active turn's private hook", async () => {- installControlHook([parkResult()], true);- const bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset"> = [];-- const action = await runReceiver([], {- bufferedSessionControls,- commandInbox: createCommandInbox([- { kind: "cancel", turnId: "turn_3" },- { kind: "reset", reason: "Start over" },- ]),- });-- expect(action.kind).toBe("park");- expect(forwardTurnCancellationStep).toHaveBeenNthCalledWith(1, {- payload: { turnId: "turn_3" },- token: "turn-control:cancel",- });- expect(forwardTurnCancellationStep).toHaveBeenNthCalledWith(2, {- payload: {},- token: "turn-control:cancel",- });- expect(bufferedSessionControls).toEqual(["reset"]);- });-});--function runReceiver(- bufferedDeliveries: DeliverHookPayload[],- options: {- readonly bufferedSessionControls?: Array<"clear" | "compact" | "expired" | "reset">;- readonly commandInbox?: SessionCommandInbox;- readonly seenTaskDeliveries?: Set<string>;- } = {},-): ReturnType<TurnControlReceiver["waitForAction"]> {- const receiver = new TurnControlReceiver({- bufferedDeliveries,- bufferedSessionControls: options.bufferedSessionControls ?? [],- commandInbox: options.commandInbox ?? createCommandInbox(),- expectedTurnId: "turn_0",- seenTaskDeliveries: options.seenTaskDeliveries,- stateCursor: new SessionStateCursor({ serializedContext: {}, sessionState: createState() }),- token: "turn-control",- });- return receiver.waitForAction().finally(() => receiver.dispose());-}--function deliveryRequest(requestId: string): TurnControlPayload {- return {- continuationToken: "http:test",- inboxToken: "turn-inbox",- kind: "turn-delivery-request",- requestId,- };-}--function parkResult(): Extract<TurnControlPayload, { readonly kind: "turn-result" }> {- return {- action: { kind: "park", serializedContext: {}, sessionState: createState() },- kind: "turn-result",- };-}--function createCommandInbox(- values: readonly SessionInboxPayload[] = [],- overrides: Partial<SessionCommandInbox> = {},-): SessionCommandInbox {- const queue = [...values];- return {- claimAuthorization: vi.fn(),- claimStable: vi.fn(),- consumeNext: vi.fn(),- hasReadyAuthorization: vi.fn(() => false),- next: vi.fn(() => {- const value = queue.shift();- return value === undefined- ? new Promise<IteratorResult<SessionInboxPayload>>(() => {})- : Promise.resolve({ done: false, value });- }),- nextWithSource: vi.fn(() =>- Promise.reject(new Error("nextWithSource is not modeled by this test inbox.")),- ),- rekeyContinuation: vi.fn(),- setAuthorizationWindow: vi.fn(),- ...overrides,- };-}--function installControlHook(values: readonly TurnControlPayload[], delayed = false): void {- const queue = [...values];- createHookMock.mockReturnValue({- token: "turn-control",- dispose: vi.fn(),- [Symbol.asyncIterator]() {- return {- next: async () => {- if (delayed) await new Promise<void>((resolve) => setTimeout(resolve, 0));- const value = queue.shift();- return value === undefined ? { done: true, value: undefined } : { done: false, value };- },- return: vi.fn(async () => ({ done: true, value: undefined })),- };- },- });-}--function createState(): DurableSessionState {- return {- continuationToken: "http:test",- emissionState: { sequence: 0, sessionStarted: false, stepIndex: 0, turnId: "" },- hasProxyInputRequests: false,- sessionId: "session",- version: 1,- };-}diff --git a/packages/eve/src/execution/turn-control-receiver.ts b/packages/eve/src/execution/turn-control-receiver.tsdeleted file mode 100644index 653158781..000000000--- a/packages/eve/src/execution/turn-control-receiver.ts+++ /dev/null@@ -1,388 +0,0 @@-import { createHook, type Hook } from "#compiled/@workflow/core/index.js";--import type { DeliverHookPayload } from "#channel/types.js";-import { cancelAllIndexedSessionTasksStep } from "#execution/cancel-indexed-session-tasks-step.js";-import { forwardTurnCancellationStep } from "#execution/forward-turn-cancellation-step.js";-import type { TurnControlPayload } from "#execution/turn-control-protocol.js";-import { forwardTurnDeliveryStep } from "#execution/forward-turn-delivery-step.js";-import { closeHookIterator, disposeHook } from "#execution/hook-ownership.js";-import type { NextDriverAction } from "#execution/next-driver-action.js";-import type { SessionCommandInbox } from "#execution/session-command-inbox.js";-import type { SessionStateCursor } from "#execution/session-state-cursor.js";-import { turnCancellationHookToken } from "#execution/turn-cancellation-token.js";-import { reportDroppedWirePayloadStep } from "#execution/report-dropped-wire-payload-step.js";-import {- sessionInboxWire,- SessionInboxWireError,- type DecodedSessionInbox,-} from "#execution/wire/session-inbox-wire.js";-import { rebuildSerializableError } from "#execution/workflow-errors.js";--type DeliveryRequest = Extract<TurnControlPayload, { readonly kind: "turn-delivery-request" }>;--export type TurnDriverAction = NextDriverAction;--/** Owns one turn's driver-side control hook and public-delivery relay state. */-export class TurnControlReceiver {- private readonly bufferedDeliveries: DeliverHookPayload[];- private readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;- private readonly commandInbox: SessionCommandInbox;- private readonly control: Hook<TurnControlPayload>;- private readonly controlIterator: AsyncIterator<TurnControlPayload>;- private readonly expectedTurnId: string;- private readonly cancelledTaskIds: Set<string>;- private readonly seenTaskDeliveries: Set<string>;- private readonly stateCursor: SessionStateCursor;- private pendingControl: Promise<IteratorResult<TurnControlPayload>> | null = null;-- constructor(input: {- readonly bufferedDeliveries: DeliverHookPayload[];- readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;- readonly cancelledTaskIds?: Set<string>;- readonly commandInbox: SessionCommandInbox;- readonly expectedTurnId: string;- readonly seenTaskDeliveries?: Set<string>;- readonly stateCursor: SessionStateCursor;- readonly token: string;- }) {- this.bufferedDeliveries = input.bufferedDeliveries;- this.bufferedSessionControls = input.bufferedSessionControls;- this.cancelledTaskIds = input.cancelledTaskIds ?? new Set();- this.commandInbox = input.commandInbox;- this.seenTaskDeliveries = input.seenTaskDeliveries ?? new Set();- this.stateCursor = input.stateCursor;- this.control = createHook<TurnControlPayload>({ token: input.token });- this.controlIterator = this.control[Symbol.asyncIterator]();- this.expectedTurnId = input.expectedTurnId;- }-- /** Token passed to the turn workflow so it can publish control messages. */- get token(): string {- return this.control.token;- }-- /** Releases the turn control hook and its iterator. */- async dispose(): Promise<void> {- await closeHookIterator(this.controlIterator);- await disposeHook(this.control);- }-- /** Services control messages until the active turn returns its terminal driver action. */- async waitForAction(): Promise<TurnDriverAction> {- while (true) {- const winner = await this.nextControlOrCommand();- if (winner.kind === "command") {- const terminal = await this.handleSessionCommand(winner.command);- if (terminal !== undefined) return terminal;- continue;- }- const payload = winner.payload;-- const terminal = this.readTerminalControl(payload);- if (terminal !== undefined) return terminal;-- if (payload.kind === "turn-delivery-request") {- const resolved = await this.serviceDeliveryRequest(payload);- if (resolved !== undefined) return resolved;- }- }- }-- private async handleSessionCommand(- command: DecodedSessionInbox,- ): Promise<TurnDriverAction | undefined> {- if (command.kind === "deliver") {- if (!this.acceptTaskDelivery(command)) return undefined;- await this.bufferDelivery(command);- return undefined;- }- if (command.kind === "clear" || command.kind === "compact") {- this.bufferedSessionControls.push(command.kind);- return undefined;- }- if (command.kind === "session-timeout") {- this.bufferedSessionControls.push("expired");- return undefined;- }- if (command.kind === "cancel") {- if ("tasks" in command && command.tasks === true) {- await cancelAllIndexedSessionTasksStep({- serializedContext: this.stateCursor.serializedContext,- sessionState: this.stateCursor.sessionState,- });- }- if (command.taskId !== undefined) this.discardTaskDeliveries(command.taskId);- const turnId =- command.taskId !== undefined &&- command.turnId !== undefined &&- command.turnId !== this.expectedTurnId- ? undefined- : command.turnId;- const payload: { tasks?: boolean; turnId?: string } = { tasks: command.tasks };- if (turnId !== undefined) payload.turnId = turnId;- await forwardTurnCancellationStep({- payload,- token: turnCancellationHookToken(this.control.token),- });- return undefined;- }- if (command.kind === "reset") {- await forwardTurnCancellationStep({- payload: {},- token: turnCancellationHookToken(this.control.token),- });- this.bufferedSessionControls.push("reset");- return undefined;- }- return unsupportedSessionCommand(command);- }-- private async bufferDelivery(delivery: DeliverHookPayload): Promise<void> {- this.bufferedDeliveries.push(delivery);- if (delivery.turnPolicy !== "steer" || !deliveryHasMessage(delivery)) return;-- await forwardTurnCancellationStep({- payload: {},- token: turnCancellationHookToken(this.control.token),- });- }-- private bufferTurnDeliveries(- payload: Extract<TurnControlPayload, { readonly kind: "turn-result" }>,- ): void {- if (payload.bufferedDeliveries !== undefined) {- this.bufferedDeliveries.unshift(- ...payload.bufferedDeliveries.filter((delivery) => !this.shouldDiscard(delivery)),- );- }- }-- private consumeControl(): void {- this.pendingControl = null;- }-- private getControlPromise(): Promise<IteratorResult<TurnControlPayload>> {- this.pendingControl ??= this.controlIterator.next();- return this.pendingControl;- }-- private async nextControlOrCommand(): Promise<- | { readonly command: DecodedSessionInbox; readonly kind: "command" }- | { readonly kind: "control"; readonly payload: TurnControlPayload }- > {- const winner = await Promise.race([- this.getControlPromise().then((value) => ({ kind: "control" as const, value })),- this.commandInbox.next().then((value) => ({ kind: "command" as const, value })),- ]);-- if (winner.kind === "command") {- if (winner.value.done) {- throw new Error("Session command inbox closed before the active turn settled.");- }- this.commandInbox.consumeNext();- // Runtime-action results belong to the active turn's private inbox. A- // late value on a retired session alias stays ignorable, but it is not- // part of the versioned session-command wire family.- if (winner.value.value.kind === "runtime-action-result") {- return await this.nextControlOrCommand();- }- try {- return { command: sessionInboxWire.decode(winner.value.value), kind: "command" };- } catch (error) {- if (!(error instanceof SessionInboxWireError)) throw error;- // Drop loudly and keep servicing the turn; see sessionInboxWire.decode.- await reportDroppedWirePayloadStep({ detail: error.message, family: "session-inbox" });- return await this.nextControlOrCommand();- }- }-- this.consumeControl();- if (winner.value.done) {- throw new Error("Turn control hook closed before delivering a result.");- }- const payload = winner.value.value;- if (payload.kind === "turn-error") throw rebuildSerializableError(payload.error);- if (payload.kind === "turn-continuation-token") {- await this.commandInbox.rekeyContinuation(payload.continuationToken);- return await this.nextControlOrCommand();- }- return { kind: "control", payload };- }-- private readTerminalControl(payload: TurnControlPayload): NextDriverAction | undefined {- if (payload.kind === "turn-error") throw rebuildSerializableError(payload.error);- if (payload.kind !== "turn-result") return undefined;- this.bufferTurnDeliveries(payload);- return payload.action;- }-- private async serviceDeliveryRequest(- request: DeliveryRequest,- ): Promise<TurnDriverAction | undefined> {- await this.commandInbox.rekeyContinuation(request.continuationToken);-- let delivery = this.takeInputResponseDelivery();- while (delivery === undefined) {- const winner = await Promise.race([- this.getControlPromise().then((value) => ({ kind: "control" as const, value })),- this.commandInbox.next().then((value) => ({ kind: "command" as const, value })),- ]);-- if (winner.kind === "control") {- this.consumeControl();- if (winner.value.done) {- throw new Error("Turn control hook closed during a delivery request.");- }- if (winner.value.value.kind === "turn-continuation-token") {- await this.commandInbox.rekeyContinuation(winner.value.value.continuationToken);- continue;- }- const terminal = this.readTerminalControl(winner.value.value);- if (terminal !== undefined) return terminal;- if (- winner.value.value.kind === "turn-delivery-cancelled" &&- winner.value.value.requestId === request.requestId- ) {- return undefined;- }- continue;- }-- if (winner.value.done) {- throw new Error("Session command inbox closed during a turn delivery request.");- }-- this.commandInbox.consumeNext();- if (winner.value.value.kind === "runtime-action-result") {- continue;- }- let decoded: DecodedSessionInbox;- try {- decoded = sessionInboxWire.decode(winner.value.value);- } catch (error) {- if (!(error instanceof SessionInboxWireError)) throw error;- // Drop loudly and keep servicing the request; see sessionInboxWire.decode.- await reportDroppedWirePayloadStep({ detail: error.message, family: "session-inbox" });- continue;- }- if (decoded.kind === "deliver") {- if (!this.acceptTaskDelivery(decoded)) continue;- if (deliveryHasMessage(decoded)) {- await this.bufferDelivery(decoded);- } else {- delivery = decoded;- }- continue;- }- const terminal = await this.handleSessionCommand(decoded);- if (terminal !== undefined) return terminal;- }-- // Forwarding is provisional until the turn acknowledges it. If the inbox is- // already gone (the turn ended or was replaced), the turn's terminal or- // cancellation still re-buffers the delivery for the next parent turn.- try {- await forwardTurnDeliveryStep({- inboxToken: request.inboxToken,- payload: {- delivery,- kind: "driver-delivery",- requestId: request.requestId,- },- });- } catch (error) {- if (!(error instanceof Error && error.name === "HookNotFoundError")) throw error;- }-- return await this.awaitForwardedDelivery(request.requestId, delivery);- }-- private takeInputResponseDelivery(): DeliverHookPayload | undefined {- const index = this.bufferedDeliveries.findIndex((delivery) => !deliveryHasMessage(delivery));- if (index === -1) return undefined;- return this.bufferedDeliveries.splice(index, 1)[0];- }-- /**- * Waits for the active turn to resolve a forwarded delivery. The turn either- * accepts it (consumed) or releases it on cancellation or termination, in- * which case the delivery returns behind remainders from earlier deliveries- * accepted by the turn and ahead of deliveries that arrived later.- */- private async awaitForwardedDelivery(- requestId: string,- outstanding: DeliverHookPayload,- ): Promise<TurnDriverAction | undefined> {- while (true) {- const winner = await this.nextControlOrCommand();- if (winner.kind === "command") {- const terminal = await this.handleSessionCommand(winner.command);- if (terminal !== undefined) {- if (!this.shouldDiscard(outstanding)) this.bufferedDeliveries.unshift(outstanding);- return terminal;- }- continue;- }- const payload = winner.payload;-- if (payload.kind === "turn-delivery-accepted") {- if (payload.requestId === requestId) return undefined;- continue;- }-- if (payload.kind === "turn-delivery-cancelled" && payload.requestId === requestId) {- if (!this.shouldDiscard(outstanding)) this.bufferedDeliveries.unshift(outstanding);- return undefined;- }-- if (payload.kind === "turn-result") {- if (!this.shouldDiscard(outstanding)) this.bufferedDeliveries.unshift(outstanding);- }-- const terminal = this.readTerminalControl(payload);- if (terminal !== undefined) return terminal;- }- }-- private acceptTaskDelivery(command: DeliverHookPayload): boolean {- const deliveryId = command.taskDeliveryId ?? command.caller?.taskId;- if (deliveryId === undefined) return true;- if (this.originatesFromCancelledTask(deliveryId)) return false;- if (this.seenTaskDeliveries.has(deliveryId)) return false;- this.seenTaskDeliveries.add(deliveryId);- return true;- }-- private discardTaskDeliveries(taskId: string): void {- this.cancelledTaskIds.add(taskId);- const kept = this.bufferedDeliveries.filter((delivery) => !this.shouldDiscard(delivery));- this.bufferedDeliveries.splice(0, this.bufferedDeliveries.length, ...kept);- }-- private originatesFromCancelledTask(deliveryId: string): boolean {- return [...this.cancelledTaskIds].some((taskId) =>- deliveryOriginatesFromTask(deliveryId, taskId),- );- }-- private shouldDiscard(delivery: DeliverHookPayload): boolean {- const deliveryId = delivery.taskDeliveryId ?? delivery.caller?.taskId;- return deliveryId !== undefined && this.originatesFromCancelledTask(deliveryId);- }-}--/**- * Task delivery ids are either a bare task id (the `caller.taskId` fallback)- * or `${taskId}:${discriminator}` as minted in tasks/child/steps.ts.- */-function deliveryOriginatesFromTask(deliveryId: string, taskId: string): boolean {- return deliveryId === taskId || deliveryId.startsWith(`${taskId}:`);-}--function deliveryHasMessage(delivery: DeliverHookPayload): boolean {- return delivery.payloads.some((payload) => payload.message !== undefined);-}--function unsupportedSessionCommand(command: never): never {- throw new Error(`Unsupported session command: ${JSON.stringify(command)}`);-}diff --git a/packages/eve/src/execution/turn-dispatch.test.ts b/packages/eve/src/execution/turn-dispatch.test.tsdeleted file mode 100644index fd0f0216c..000000000--- a/packages/eve/src/execution/turn-dispatch.test.ts+++ /dev/null@@ -1,618 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--import type { DeliverHookPayload } from "#channel/types.js";-import type { DurableSessionState } from "#execution/durable-session-store.js";-import { cancelAllIndexedSessionTasksStep } from "#execution/cancel-indexed-session-tasks-step.js";-import { dispatchTurnStep } from "#execution/dispatch-turn-step.js";-import { forwardTurnCancellationStep } from "#execution/forward-turn-cancellation-step.js";-import { forwardTurnDeliveryStep } from "#execution/forward-turn-delivery-step.js";-import { runTurnOwnedWorkflow } from "#execution/turn-workflow.js";-import { dispatchAndAwaitTurn } from "#execution/turn-dispatch.js";-import type { SessionCommandInbox, SessionInboxPayload } from "#execution/session-command-inbox.js";-import type { TurnControlPayload } from "#execution/turn-control-protocol.js";-import { turnStep } from "#execution/workflow-steps.js";--const createHookMock = vi.fn();--vi.mock("#compiled/@workflow/core/index.js", () => ({- createHook: (...args: unknown[]) => createHookMock(...args),-}));--vi.mock("./cancel-indexed-session-tasks-step.js", () => ({- cancelAllIndexedSessionTasksStep: vi.fn(),-}));--vi.mock("./dispatch-turn-step.js", () => ({- dispatchTurnStep: vi.fn(async () => ({ runId: "turn-run" })),-}));--vi.mock("./forward-turn-delivery-step.js", () => ({- forwardTurnDeliveryStep: vi.fn(),-}));--vi.mock("./forward-turn-cancellation-step.js", () => ({- forwardTurnCancellationStep: vi.fn(),-}));--vi.mock("./turn-workflow.js", () => ({- runTurnOwnedWorkflow: vi.fn(),-}));--vi.mock("./workflow-steps.js", () => ({- turnStep: vi.fn(),-}));--describe("dispatchAndAwaitTurn", () => {- beforeEach(() => {- vi.clearAllMocks();- createHookMock.mockReset();- vi.mocked(runTurnOwnedWorkflow).mockImplementation(async (_input, onReady) => onReady?.());- });-- it("rekeys the public hook when the active turn changes its continuation token", async () => {- const state = createState("slack:C1:T1");- installControlHook([- { continuationToken: "slack:C1:T1", kind: "turn-continuation-token" },- {- action: { kind: "park", serializedContext: {}, sessionState: state },- kind: "turn-result",- },- ]);- const rekeyHook = vi.fn();- const commandInbox = createCommandInbox({ rekeyContinuation: rekeyHook });-- await dispatchAndAwaitTurn({- bufferedDeliveries: [],- bufferedSessionControls: [],- commandInbox,- controlToken: "turn-control",- delivery: { kind: "deliver", payloads: [{ message: "start" }] },- mode: "conversation",- parentWritable: new WritableStream<Uint8Array>(),- serializedContext: {},- sessionState: createState("slack:C1:"),- });-- expect(rekeyHook).toHaveBeenCalledWith("slack:C1:T1");- });-- it("rekeys while a turn delivery request is already waiting", async () => {- const state = createState("slack:C1:T1");- installControlHook([- {- continuationToken: "slack:C1:",- inboxToken: "turn-inbox",- kind: "turn-delivery-request",- requestId: "request-1",- },- { continuationToken: "slack:C1:T1", kind: "turn-continuation-token" },- { kind: "turn-delivery-cancelled", requestId: "request-1" },- {- action: { kind: "park", serializedContext: {}, sessionState: state },- kind: "turn-result",- },- ]);- const rekeyHook = vi.fn();- const commandInbox = createCommandInbox({ rekeyContinuation: rekeyHook });-- await dispatchAndAwaitTurn({- bufferedDeliveries: [],- bufferedSessionControls: [],- commandInbox,- controlToken: "turn-control",- delivery: { kind: "deliver", payloads: [{ message: "start" }] },- mode: "conversation",- parentWritable: new WritableStream<Uint8Array>(),- serializedContext: {},- sessionState: createState("slack:C1:"),- });-- expect(rekeyHook).toHaveBeenCalledWith("slack:C1:T1");- });-- it("keeps earlier turn remainders ahead of later cancelled deliveries", async () => {- const state = createState("http:test");- let releaseCancellation: (() => void) | undefined;- const forwarded = new Promise<void>((resolve) => {- releaseCancellation = resolve;- });- vi.mocked(forwardTurnDeliveryStep).mockImplementation(async () => releaseCancellation?.());-- let controlIndex = 0;- createHookMock.mockReturnValue(- createMockHook(async () => {- controlIndex += 1;- if (controlIndex === 1) {- return {- done: false,- value: {- continuationToken: "http:test",- inboxToken: "turn-inbox",- kind: "turn-delivery-request",- requestId: "request-1",- },- };- }- if (controlIndex === 2) {- await forwarded;- return {- done: false,- value: { kind: "turn-delivery-cancelled", requestId: "request-1" },- };- }- return {- done: false,- value: {- action: { kind: "park", serializedContext: {}, sessionState: state },- bufferedDeliveries: [{ kind: "deliver", payloads: [{ message: "earlier remainder" }] }],- kind: "turn-result",- },- };- }),- );-- const bufferedDeliveries: DeliverHookPayload[] = [];- await dispatchAndAwaitTurn({- bufferedDeliveries,- bufferedSessionControls: [],- commandInbox: createCommandInbox({- next: async () => ({- done: false,- value: {- kind: "send",- payload: { inputResponses: [{ optionId: "yes", requestId: "input-1" }] },- },- }),- }),- controlToken: "turn-control",- delivery: { kind: "deliver", payloads: [{ message: "start" }] },- mode: "conversation",- parentWritable: new WritableStream<Uint8Array>(),- serializedContext: {},- sessionState: state,- });-- expect(bufferedDeliveries).toEqual([- { kind: "deliver", payloads: [{ message: "earlier remainder" }] },- expect.objectContaining({- payloads: [{ inputResponses: [{ optionId: "yes", requestId: "input-1" }] }],- }),- ]);- });-- it("re-buffers a forwarded delivery when the turn inbox is already gone", async () => {- const state = createState("http:test");- const delivery: DeliverHookPayload = {- kind: "deliver",- payloads: [{ inputResponses: [{ optionId: "yes", requestId: "input-1" }] }],- };- vi.mocked(forwardTurnDeliveryStep).mockRejectedValue(- Object.assign(new Error("inbox gone"), { name: "HookNotFoundError" }),- );- installControlHook([- {- continuationToken: "http:test",- inboxToken: "turn-inbox",- kind: "turn-delivery-request",- requestId: "request-1",- },- {- action: { kind: "park", serializedContext: {}, sessionState: state },- kind: "turn-result",- },- ]);-- const bufferedDeliveries: DeliverHookPayload[] = [delivery];- const turn = await dispatchAndAwaitTurn({- bufferedDeliveries,- bufferedSessionControls: [],- commandInbox: createCommandInbox(),- controlToken: "turn-control",- delivery: { kind: "deliver", payloads: [{ message: "start" }] },- mode: "conversation",- parentWritable: new WritableStream<Uint8Array>(),- serializedContext: {},- sessionState: state,- });-- expect(forwardTurnDeliveryStep).toHaveBeenCalledOnce();- expect(turn.action.kind).toBe("park");- expect(bufferedDeliveries).toEqual([delivery]);- });-- it("defers control-hook disposal until the caller invokes dispose()", async () => {- const state = createState("http:test");- installControlHook([- {- action: { kind: "park", serializedContext: {}, sessionState: state },- kind: "turn-result",- },- ]);-- const turn = await dispatchAndAwaitTurn({- bufferedDeliveries: [],- bufferedSessionControls: [],- commandInbox: createCommandInbox(),- controlToken: "turn-control",- delivery: { kind: "deliver", payloads: [{ message: "start" }] },- mode: "conversation",- parentWritable: new WritableStream<Uint8Array>(),- serializedContext: {},- sessionState: state,- });-- // The turn run's final control send is at-least-once; a late- // duplicate resume must land on a live hook (see DispatchedTurn).- const hook = createHookMock.mock.results[0]?.value as { dispose: ReturnType<typeof vi.fn> };- expect(hook.dispose).not.toHaveBeenCalled();- await turn.dispose();- expect(hook.dispose).toHaveBeenCalledOnce();- });-- it("settles an ordinary same-deployment turn without a child workflow", async () => {- const state = createState("http:test");- vi.mocked(turnStep).mockResolvedValueOnce({- action: "park",- hasPendingAuthorization: false,- hasPendingInputBatch: false,- serializedContext: { state: "settled" },- sessionState: state,- settled: { output: "ok" },- });-- const turn = await dispatchAndAwaitTurn({- bufferedDeliveries: [],- bufferedSessionControls: [],- commandInbox: createCommandInbox(),- controlToken: "turn-control",- delivery: createAcceptedDelivery(),- mode: "conversation",- parentWritable: new WritableStream<Uint8Array>(),- serializedContext: { state: "start" },- sessionState: state,- });-- expect(turn.action).toMatchObject({ kind: "park", settled: { output: "ok" } });- expect(turnStep).toHaveBeenCalledWith(- expect.objectContaining({ acceptedDeploymentId: "dpl_current" }),- );- expect(dispatchTurnStep).not.toHaveBeenCalled();- expect(createHookMock).not.toHaveBeenCalled();- });-- it("cancels indexed tasks from an inline turn and preserves turn cancellation", async () => {- const state = createState("http:test");- vi.mocked(turnStep).mockImplementation(async ({ abortSignal }) => {- await new Promise<void>((resolve) => abortSignal?.addEventListener("abort", () => resolve()));- return {- action: "cancelled",- serializedContext: { state: "cancelled" },- sessionState: state,- };- });- let delivered = false;- const commandInbox = createCommandInbox({- next: vi.fn(async () => {- if (!delivered) {- delivered = true;- return { done: false as const, value: { kind: "cancel", tasks: true } as never };- }- return await new Promise<IteratorResult<SessionInboxPayload>>(() => {});- }),- });- installControlHook([- {- action: { cancelled: true, kind: "park", serializedContext: {}, sessionState: state },- kind: "turn-result",- },- ]);-- await dispatchAndAwaitTurn({- bufferedDeliveries: [],- bufferedSessionControls: [],- commandInbox,- controlToken: "turn-control",- delivery: createAcceptedDelivery(),- mode: "conversation",- parentWritable: new WritableStream<Uint8Array>(),- serializedContext: { state: "start" },- sessionState: state,- });-- expect(cancelAllIndexedSessionTasksStep).toHaveBeenCalledWith({- serializedContext: { state: "start" },- sessionState: state,- });- expect(dispatchTurnStep).not.toHaveBeenCalled();- expect(runTurnOwnedWorkflow).toHaveBeenCalledWith(- expect.objectContaining({ initialCancellation: { tasks: true } }),- expect.any(Function),- );- });-- it("keeps ordinary tool-loop continuations inline", async () => {- const firstState = createState("http:test:rekeyed");- const finalState = createState("http:test:rekeyed");- vi.mocked(turnStep)- .mockResolvedValueOnce({- action: "continue",- serializedContext: { state: "continued" },- sessionState: firstState,- })- .mockResolvedValueOnce({- action: "done",- output: "complete",- serializedContext: { state: "done" },- sessionState: finalState,- });- const commandInbox = createCommandInbox();-- const turn = await dispatchAndAwaitTurn({- bufferedDeliveries: [],- bufferedSessionControls: [],- commandInbox,- controlToken: "turn-control",- delivery: createAcceptedDelivery(),- mode: "conversation",- parentWritable: new WritableStream<Uint8Array>(),- serializedContext: { state: "start" },- sessionState: createState("http:test"),- });-- expect(turn.action).toMatchObject({ kind: "done", output: "complete" });- expect(vi.mocked(turnStep).mock.calls[1]?.[0].input).toBeUndefined();- expect(commandInbox.rekeyContinuation).toHaveBeenCalledWith("http:test:rekeyed");- expect(dispatchTurnStep).not.toHaveBeenCalled();- });-- it("runs coordination on the parent from an already-completed inline step", async () => {- const state = createState("http:test");- const result = {- action: "park" as const,- hasPendingAuthorization: false,- hasPendingInputBatch: false,- pendingCoordinationCallIds: ["call-1"],- serializedContext: { state: "pending" },- sessionState: state,- };- vi.mocked(turnStep).mockResolvedValueOnce(result);- installControlHook([- {- action: { kind: "park", serializedContext: result.serializedContext, sessionState: state },- kind: "turn-result",- },- ]);-- await dispatchAndAwaitTurn({- bufferedDeliveries: [],- bufferedSessionControls: [],- commandInbox: createCommandInbox(),- controlToken: "turn-control",- delivery: createAcceptedDelivery(),- mode: "conversation",- parentWritable: new WritableStream<Uint8Array>(),- serializedContext: { state: "start" },- sessionState: state,- });-- expect(dispatchTurnStep).not.toHaveBeenCalled();- expect(runTurnOwnedWorkflow).toHaveBeenCalledWith(- expect.objectContaining({- initialStep: {- beforeStep: expect.objectContaining({ serializedContext: { state: "start" } }),- result,- },- }),- expect.any(Function),- );- });-- it("waits for inline hook initialization before forwarding a queued cancel", async () => {- const state = createState("http:test");- const command = Promise.withResolvers<IteratorResult<SessionInboxPayload>>();- const forwarded = Promise.withResolvers<void>();- vi.mocked(turnStep).mockResolvedValueOnce({- action: "park",- hasPendingAuthorization: false,- hasPendingInputBatch: false,- pendingCoordinationCallIds: ["call-1"],- serializedContext: {},- sessionState: state,- });- vi.mocked(forwardTurnCancellationStep).mockImplementationOnce(async () => {- forwarded.resolve();- return true;- });- createHookMock.mockReturnValue(- createMockHook(async () => {- await forwarded.promise;- return {- done: false,- value: {- action: { cancelled: true, kind: "park", serializedContext: {}, sessionState: state },- kind: "turn-result",- },- };- }),- );- vi.mocked(runTurnOwnedWorkflow).mockImplementationOnce(async (_input, onReady) => {- command.resolve({ done: false, value: { kind: "cancel" } });- await new Promise((resolve) => setTimeout(resolve, 0));- expect(forwardTurnCancellationStep).not.toHaveBeenCalled();- onReady?.();- });- let consumed = false;-- const turn = await dispatchAndAwaitTurn({- bufferedDeliveries: [],- bufferedSessionControls: [],- commandInbox: createCommandInbox({- next: () => (consumed ? new Promise(() => {}) : command.promise),- consumeNext: () => {- consumed = true;- },- }),- controlToken: "turn-control",- delivery: createAcceptedDelivery(),- mode: "conversation",- parentWritable: new WritableStream<Uint8Array>(),- serializedContext: {},- sessionState: state,- });-- expect(turn.action).toMatchObject({ cancelled: true });- expect(forwardTurnCancellationStep).toHaveBeenCalledExactlyOnceWith({- payload: { tasks: undefined },- token: "turn-control:cancel",- });- });-- it("defers a guarded deployment mismatch without consuming the delivery", async () => {- const state = createState("http:test");- vi.mocked(turnStep).mockResolvedValueOnce({- action: "continue",- requiresChildDispatch: true,- serializedContext: { state: "start" },- sessionState: state,- });- installControlHook([- {- action: { kind: "park", serializedContext: {}, sessionState: state },- kind: "turn-result",- },- ]);-- await dispatchAndAwaitTurn({- bufferedDeliveries: [],- bufferedSessionControls: [],- commandInbox: createCommandInbox(),- controlToken: "turn-control",- delivery: createAcceptedDelivery(),- mode: "conversation",- parentWritable: new WritableStream<Uint8Array>(),- serializedContext: { state: "start" },- sessionState: state,- });-- expect(dispatchTurnStep).toHaveBeenCalledWith(- expect.objectContaining({ initialStep: undefined }),- );- });-- it("carries inline cancellation into the shared turn runner on the parent", async () => {- const state = createState("http:test");- vi.mocked(turnStep).mockImplementationOnce(async (input) => {- await vi.waitFor(() => expect(input.abortSignal?.aborted).toBe(true));- return {- action: "cancelled",- serializedContext: { state: "cancelled" },- sessionState: state,- };- });- let delivered = false;- const commandInbox = createCommandInbox({- next: vi.fn(async () => {- if (!delivered) {- delivered = true;- return { done: false as const, value: { kind: "cancel" as const } };- }- return await new Promise<IteratorResult<SessionInboxPayload>>(() => {});- }),- });- installControlHook([- {- action: { cancelled: true, kind: "park", serializedContext: {}, sessionState: state },- kind: "turn-result",- },- ]);-- await dispatchAndAwaitTurn({- bufferedDeliveries: [],- bufferedSessionControls: [],- commandInbox,- controlToken: "turn-control",- delivery: createAcceptedDelivery(),- mode: "conversation",- parentWritable: new WritableStream<Uint8Array>(),- serializedContext: { state: "start" },- sessionState: state,- });-- expect(dispatchTurnStep).not.toHaveBeenCalled();- expect(runTurnOwnedWorkflow).toHaveBeenCalledWith(- expect.objectContaining({- initialCancellation: {},- initialStep: expect.objectContaining({- result: expect.objectContaining({ action: "cancelled" }),- }),- }),- expect.any(Function),- );- expect(commandInbox.consumeNext).toHaveBeenCalledOnce();- });-});--function createCommandInbox(overrides: Partial<SessionCommandInbox> = {}): SessionCommandInbox {- return {- claimAuthorization: vi.fn(),- claimStable: vi.fn(),- consumeNext: vi.fn(),- hasReadyAuthorization: vi.fn(() => false),- next: vi.fn(() => new Promise<IteratorResult<SessionInboxPayload>>(() => {})),- nextWithSource: vi.fn(() =>- Promise.reject(new Error("nextWithSource is not modeled by this test inbox.")),- ),- rekeyContinuation: vi.fn(),- setAuthorizationWindow: vi.fn(),- ...overrides,- };-}--function installControlHook(values: readonly TurnControlPayload[]): void {- const queue = [...values];- createHookMock.mockReturnValue(- createMockHook(async () => {- const value = queue.shift();- return value === undefined ? { done: true, value: undefined } : { done: false, value };- }),- );-}--function createMockHook(next: () => Promise<IteratorResult<TurnControlPayload>>): unknown {- return {- token: "turn-control",- dispose: vi.fn(),- [Symbol.asyncIterator]() {- return {- next,- return: vi.fn(async () => ({ done: true, value: undefined })),- };- },- };-}--function createState(continuationToken: string): DurableSessionState {- return {- continuationToken,- emissionState: { sequence: 0, sessionStarted: false, stepIndex: 0, turnId: "" },- hasProxyInputRequests: false,- sessionId: "session",- version: 1,- };-}--function createAcceptedDelivery(): DeliverHookPayload {- return {- deliveryMetadata: [- {- acceptedDeploymentId: "dpl_current",- channelKind: "channel:test",- channelName: "test",- deliveryId: "delivery-1",- payloadIndex: 0,- },- ],- kind: "deliver",- payloads: [{ message: "start" }],- };-}diff --git a/packages/eve/src/execution/turn-dispatch.ts b/packages/eve/src/execution/turn-dispatch.tsdeleted file mode 100644index e517882a6..000000000--- a/packages/eve/src/execution/turn-dispatch.ts+++ /dev/null@@ -1,122 +0,0 @@-import type { DeliverHookPayload, HookPayload, SessionCapabilities } from "#channel/types.js";-import { dispatchTurnStep } from "#execution/dispatch-turn-step.js";-import { TurnControlReceiver } from "#execution/turn-control-receiver.js";-import type { DurableSessionState } from "#execution/durable-session-store.js";-import {- createTurnWorkflowInput,- type InitialTurnStep,- type TurnWorkflowDispatchInput,-} from "#execution/durable-session-migrations/turn-workflow.js";-import { runInlineTurn } from "#execution/inline-turn.js";-import type { SessionCommandInbox } from "#execution/session-command-inbox.js";-import { SessionStateCursor } from "#execution/session-state-cursor.js";-import type { TurnCancelPayload } from "#execution/turn-cancellation-token.js";-import type { TurnDriverAction } from "#execution/turn-control-receiver.js";-import type { AgentWorkflowRetentionDefinition } from "#shared/agent-definition.js";-import type { RunMode } from "#shared/run-mode.js";-import { activeTurnId } from "#harness/active-turn-id.js";-import { runTurnOwnedWorkflow } from "#execution/turn-workflow.js";--/** One settled turn: its terminal driver action plus deferred hook cleanup. */-export interface DispatchedTurn {- readonly action: TurnDriverAction;- /**- * Disposes the turn's control hook. Deferred until the *next* turn- * settles (or the session ends): the turn run's final control send is- * at-least-once, and `sendTurnControlStep` does not treat- * `HookNotFoundError` as benign, so a late duplicate resume must land- * on a live hook. By the next settle, the previous run has completed- * and can no longer re-send.- */- dispose(): Promise<void>;-}--/** Dispatches one turn and services its private-inbox control protocol until it terminates. */-interface TurnDispatchInput {- readonly bufferedDeliveries: DeliverHookPayload[];- readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;- readonly capabilities?: SessionCapabilities;- readonly cancelledTaskIds?: Set<string>;- readonly controlToken: string;- readonly delivery: HookPayload;- readonly commandInbox: SessionCommandInbox;- readonly mode: RunMode;- readonly parentWritable: WritableStream<Uint8Array>;- readonly retention?: AgentWorkflowRetentionDefinition;- readonly serializedContext: Record<string, unknown>;- readonly seenTaskDeliveries?: Set<string>;- readonly sessionState: DurableSessionState;- readonly stateCursor?: SessionStateCursor;-}--export async function dispatchAndAwaitTurn(input: TurnDispatchInput): Promise<DispatchedTurn> {- const stateCursor =- input.stateCursor ??- new SessionStateCursor({- serializedContext: input.serializedContext,- sessionState: input.sessionState,- });- const inline = await runInlineTurn({ ...input, stateCursor });- if (inline.kind === "result") {- return { action: inline.action, async dispose() {} };- }- return await runAndAwaitTurn({- ...input,- inline: inline.kind === "continue",- initialCancellation: inline.initialCancellation,- stateCursor,- initialStep: inline.initialStep,- });-}--async function runAndAwaitTurn(- input: TurnDispatchInput & {- readonly inline: boolean;- readonly initialCancellation?: TurnCancelPayload;- readonly initialStep?: InitialTurnStep;- },-): Promise<DispatchedTurn> {- const control = new TurnControlReceiver({- bufferedDeliveries: input.bufferedDeliveries,- bufferedSessionControls: input.bufferedSessionControls,- cancelledTaskIds: input.cancelledTaskIds,- commandInbox: input.commandInbox,- expectedTurnId: activeTurnId(input.sessionState.emissionState),- seenTaskDeliveries: input.seenTaskDeliveries ?? new Set(),- stateCursor: input.stateCursor!,- token: input.controlToken,- });-- try {- const turnInput = {- capabilities: input.capabilities,- completionToken: control.token,- delivery: input.delivery,- initialCancellation: input.initialCancellation,- initialStep: input.initialStep,- mode: input.mode,- parentWritable: input.parentWritable,- retention: input.retention,- serializedContext: input.serializedContext,- sessionState: input.sessionState,- } satisfies TurnWorkflowDispatchInput;- let action: TurnDriverAction;- if (input.inline) {- // Hook claims can suspend. Do not let a queued command allocate steps- // midway through initialization: warm execution and cold replay can order- // those allocations differently.- const ready = Promise.withResolvers<void>();- [action] = await Promise.all([- ready.promise.then(() => control.waitForAction()),- runTurnOwnedWorkflow(createTurnWorkflowInput(turnInput), ready.resolve),- ]);- } else {- await dispatchTurnStep(turnInput);- action = await control.waitForAction();- }- return { action, dispose: () => control.dispose() };- } catch (error) {- await control.dispose();- throw error;- }-}diff --git a/packages/eve/src/execution/turn-execution-cursor.test.ts b/packages/eve/src/execution/turn-execution-cursor.test.tsdeleted file mode 100644index 04a815bf5..000000000--- a/packages/eve/src/execution/turn-execution-cursor.test.ts+++ /dev/null@@ -1,85 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--import { sendTurnControlStep } from "#execution/turn-control-protocol.js";-import type { DurableSessionState } from "#execution/durable-session-store.js";-import { TurnExecutionCursor } from "#execution/turn-execution-cursor.js";--vi.mock("./turn-control-protocol.js", () => ({- sendTurnControlStep: vi.fn(),-}));--describe("TurnExecutionCursor", () => {- beforeEach(() => {- vi.clearAllMocks();- });-- it("adopts transitions and reports each continuation token once", async () => {- const parentWritable = new WritableStream<Uint8Array>();- const cursor = new TurnExecutionCursor({- controlToken: "turn-control",- parentWritable,- serializedContext: { revision: 1 },- sessionState: createState("slack:C1:"),- });- const anchoredState = createState("slack:C1:T1");-- await cursor.adopt({ serializedContext: { revision: 2 }, sessionState: anchoredState });- await cursor.adopt({ sessionState: anchoredState });-- expect(sendTurnControlStep).toHaveBeenCalledOnce();- expect(sendTurnControlStep).toHaveBeenCalledWith({- controlToken: "turn-control",- payload: {- continuationToken: "slack:C1:T1",- kind: "turn-continuation-token",- },- });- expect(cursor.createStepInput(undefined)).toEqual({- input: undefined,- parentWritable,- serializedContext: { revision: 2 },- sessionState: anchoredState,- });- });-- it("publishes a terminal transition without a redundant token update", async () => {- const cursor = new TurnExecutionCursor({- controlToken: "turn-control",- parentWritable: new WritableStream<Uint8Array>(),- serializedContext: { revision: 1 },- sessionState: createState("slack:C1:"),- });- const finalState = createState("slack:C1:T1");-- await cursor.finish(- { serializedContext: { revision: 2 }, sessionState: finalState },- { kind: "done", output: "ok" },- [{ kind: "deliver", payloads: [{ message: "queued" }] }],- );-- expect(sendTurnControlStep).toHaveBeenCalledOnce();- expect(sendTurnControlStep).toHaveBeenCalledWith({- controlToken: "turn-control",- payload: {- action: {- kind: "done",- output: "ok",- serializedContext: { revision: 2 },- sessionState: finalState,- },- bufferedDeliveries: [{ kind: "deliver", payloads: [{ message: "queued" }] }],- kind: "turn-result",- },- });- });-});--function createState(continuationToken: string): DurableSessionState {- return {- continuationToken,- emissionState: { sequence: 0, sessionStarted: false, stepIndex: 0, turnId: "" },- hasProxyInputRequests: false,- sessionId: "session",- version: 1,- };-}diff --git a/packages/eve/src/execution/turn-execution-cursor.ts b/packages/eve/src/execution/turn-execution-cursor.tsdeleted file mode 100644index bdd082320..000000000--- a/packages/eve/src/execution/turn-execution-cursor.ts+++ /dev/null@@ -1,101 +0,0 @@-import type { DeliverHookPayload } from "#channel/types.js";-import type { TurnControlPayload } from "#execution/turn-control-protocol.js";-import { sendTurnControlStep } from "#execution/turn-control-protocol.js";-import type { DurableSessionState } from "#execution/durable-session-store.js";-import type {- TurnStepInput,- TurnStepPayload,-} from "#execution/durable-session-migrations/turn-workflow.js";-import { SessionStateCursor } from "#execution/session-state-cursor.js";-import type { SettledTurn } from "#harness/types.js";-import type { TokenUsage } from "#shared/token-usage.js";--interface TurnTransition {- readonly serializedContext?: Record<string, unknown>;- readonly sessionState: DurableSessionState;-}--type TurnTerminalAction =- | {- readonly isError?: boolean;- readonly kind: "done";- readonly output: unknown;- readonly usage?: TokenUsage;- readonly usageDelta?: TokenUsage;- }- | {- readonly authorizationAttemptIds?: readonly string[];- readonly authorizationNames?: readonly string[];- readonly cancelled?: true;- readonly kind: "park";- readonly settled?: SettledTurn;- };--/** Owns the mutable durable state cursor for one active turn workflow. */-export class TurnExecutionCursor extends SessionStateCursor {- readonly controlToken: string;- readonly parentWritable: WritableStream<Uint8Array>;-- private lastReportedContinuationToken: string;-- constructor(input: {- readonly controlToken: string;- readonly parentWritable: WritableStream<Uint8Array>;- readonly serializedContext: Record<string, unknown>;- readonly sessionState: DurableSessionState;- }) {- super({ serializedContext: input.serializedContext, sessionState: input.sessionState });- this.controlToken = input.controlToken;- this.lastReportedContinuationToken = input.sessionState.continuationToken;- this.parentWritable = input.parentWritable;- }-- /** Adopts a state transition and reports any continuation-token change once. */- async adopt(transition: TurnTransition): Promise<void> {- this.adoptState(transition);-- const nextToken = transition.sessionState.continuationToken;- if (nextToken === "" || nextToken === this.lastReportedContinuationToken) return;-- this.lastReportedContinuationToken = nextToken;- await this.send({ continuationToken: nextToken, kind: "turn-continuation-token" });- }-- /** Builds the next atomic turn-step input from the cursor's current state. */- createStepInput(input: TurnStepPayload | undefined, abortSignal?: AbortSignal): TurnStepInput {- return {- abortSignal,- input,- parentWritable: this.parentWritable,- serializedContext: this.serializedContext,- sessionState: this.sessionState,- };- }-- /**- * Adopts a terminal turn transition and publishes it as the turn result.- * The result already carries the final session state, so no separate- * continuation-token update is sent.- */- async finish(- transition: TurnTransition,- action: TurnTerminalAction,- bufferedDeliveries: readonly DeliverHookPayload[],- ): Promise<void> {- this.adoptState(transition);- await this.send({- action: {- ...action,- serializedContext: this.serializedContext,- sessionState: this.sessionState,- },- bufferedDeliveries: bufferedDeliveries.length === 0 ? undefined : [...bufferedDeliveries],- kind: "turn-result",- });- }-- /** Sends one control payload to the session driver. */- async send(payload: TurnControlPayload): Promise<void> {- await sendTurnControlStep({ controlToken: this.controlToken, payload });- }-}diff --git a/packages/eve/src/execution/turn-workflow.test.ts b/packages/eve/src/execution/turn-workflow.test.tsdeleted file mode 100644index df692fad8..000000000--- a/packages/eve/src/execution/turn-workflow.test.ts+++ /dev/null@@ -1,1721 +0,0 @@-import { afterEach, describe, expect, it, vi } from "vitest";--import type { HookPayload } from "#channel/types.js";-import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-step.js";-import { dispatchCoordinationStep } from "#execution/coordination-dispatch-step.js";-import type { DurableSessionState } from "#execution/durable-session-store.js";-import { acknowledgeDelegatedTasksStep } from "#execution/tasks/parent/delegate.js";-import { applyTaskAgentRequest } from "#execution/tools/subagent/task-agent-requests.js";-import { releaseAgentInvocationOwnerStep } from "#execution/tools/subagent/invoke-step.js";-import { cancelAgentInvocationOwnerStep } from "#execution/tools/subagent/task-cancel.js";-import { runProxySubagentEventStep } from "#subagents/event-proxy-step.js";-import { turnWorkflow } from "#execution/turn-workflow.js";-import {- TURN_WORKFLOW_INPUT_VERSION,- type TurnWorkflowInput,-} from "#execution/durable-session-migrations/turn-workflow.js";-import { routeDeliverToChildren } from "#execution/route-child-delivery.js";-import { TurnExecutionCursor } from "#execution/turn-execution-cursor.js";-import { turnStep } from "#execution/workflow-steps.js";-import { AGENT_HANDLES_STATE_KEY } from "#subagents/handles/store.js";-import type { HarnessSession } from "#harness/types.js";-import { recordWorkflowToolRun } from "#harness/workflow-tool-runs.js";--const resumeHookMock = vi.fn();-const createHookMock = vi.fn();-const definedHookPayloads = new Map<string, readonly unknown[]>();--function createDefinedHookMock(token: string, values: readonly unknown[]): unknown {- const queue = [...values];- return {- token,- getConflict: vi.fn(async () => null),- dispose: vi.fn(),- [Symbol.asyncIterator](): AsyncIterator<unknown> {- return {- next: vi.fn(async () => {- const value = queue.shift();- return value === undefined ? await new Promise<never>(() => {}) : { done: false, value };- }),- return: vi.fn(async () => ({ done: true, value: undefined })),- };- },- };-}--vi.mock("#compiled/@workflow/core/index.js", () => ({- createHook: (...args: unknown[]) => createHookMock(...args),- defineHook: () => ({- create: (options?: { readonly token?: string }) => {- const token = options?.token ?? "generated-owner-token";- return createDefinedHookMock(token, definedHookPayloads.get(token) ?? []);- },- resume: async () => null,- }),- getWorkflowMetadata: vi.fn(() => ({ url: "https://eve.example.com" })),-}));--vi.mock("#compiled/@workflow/core/runtime.js", () => ({- resumeHook: (...args: unknown[]) => resumeHookMock(...args),-}));--vi.mock("./route-child-delivery.js", () => ({- routeDeliverToChildren: vi.fn(),-}));--vi.mock("../subagents/event-proxy-step.js", () => ({- runProxySubagentEventStep: vi.fn(),-}));--vi.mock("./workflow-steps.js", () => ({- turnStep: vi.fn(),-}));--vi.mock("#execution/coordination-dispatch-step.js", () => ({- dispatchCoordinationStep: vi.fn(),-}));--vi.mock("./cancel-descendant-turns-step.js", () => ({- cancelDescendantTurnsStep: vi.fn(),-}));--vi.mock("./tasks/parent/delegate.js", () => ({- acknowledgeDelegatedTasksStep: vi.fn(),-}));--vi.mock("./tools/subagent/task-agent-requests.js", () => ({- applyTaskAgentRequest: vi.fn(),-}));--vi.mock("./tools/subagent/invoke-step.js", () => ({- releaseAgentInvocationOwnerStep: vi.fn(),-}));--vi.mock("./tools/subagent/task-cancel.js", () => ({- cancelAgentInvocationOwnerStep: vi.fn(),-}));--vi.mock("./workflow-callback-url.js", () => ({- resolveWorkflowCallbackBaseUrl: vi.fn((metadataUrl: string) => metadataUrl),-}));--describe("turnWorkflow", () => {- afterEach(() => {- vi.clearAllMocks();- resumeHookMock.mockReset();- createHookMock.mockReset();- vi.mocked(applyTaskAgentRequest).mockReset();- vi.mocked(releaseAgentInvocationOwnerStep).mockReset();- vi.mocked(cancelAgentInvocationOwnerStep).mockReset();- definedHookPayloads.clear();- });-- it("notifies the driver when a turn completes", async () => {- const sessionState = createSessionState();- vi.mocked(turnStep).mockResolvedValueOnce({- action: "done",- output: "ok",- serializedContext: { state: "done" },- sessionState,- });-- const { input, parentWritable } = createInput({ sessionState });- await turnWorkflow(input);-- expect(turnStep).toHaveBeenCalledWith({- input: input.stepInput.input,- parentWritable,- serializedContext: input.stepInput.serializedContext,- sessionState,- });- expect(resumeHookMock).toHaveBeenCalledWith("turn-token", {- action: {- kind: "done",- output: "ok",- serializedContext: { state: "done" },- sessionState,- },- kind: "turn-result",- });- });-- it("continues from an inline step result without executing it twice", async () => {- const initialState = createSessionState();- const finalState = createSessionState({ continuationToken: "http:continued" });- installInbox([]);- const { input } = createInput({- driverCapabilities: { cancelledTurnSettle: true, turnInbox: true },- sessionState: initialState,- });-- await turnWorkflow({- ...input,- initialStep: {- beforeStep: {- serializedContext: input.stepInput.serializedContext,- sessionState: initialState,- },- result: {- action: "done",- output: "already complete",- serializedContext: { state: "done" },- sessionState: finalState,- },- },- });-- expect(turnStep).not.toHaveBeenCalled();- expect(resumeHookMock).toHaveBeenCalledWith(- "turn-token",- expect.objectContaining({- action: expect.objectContaining({ kind: "done", output: "already complete" }),- kind: "turn-result",- }),- );- });-- it("checkpoints completed inline state when cancellation wins", async () => {- const initialState = createSessionState({ continuationToken: "http:initial" });- const beforeStepState = createSessionState({ continuationToken: "http:inline-checkpoint" });- const completedState = createSessionState({ continuationToken: "http:completed" });- installInbox([]);- const { input } = createInput({- driverCapabilities: { cancelledTurnSettle: true, turnInbox: true },- sessionState: initialState,- });-- await turnWorkflow({- ...input,- initialCancellation: {},- initialStep: {- beforeStep: {- serializedContext: { state: "inline-checkpoint" },- sessionState: beforeStepState,- },- result: {- action: "done",- output: "must not complete",- serializedContext: { state: "done" },- sessionState: completedState,- },- },- });-- expect(cancelDescendantTurnsStep).toHaveBeenCalledWith({- serializedContext: { state: "done" },- sessionState: completedState,- });- expect(resumeHookMock).toHaveBeenCalledWith(- "turn-token",- expect.objectContaining({- action: expect.objectContaining({- cancelled: true,- kind: "park",- sessionState: completedState,- }),- kind: "turn-result",- }),- );- });-- it("migrates a pre-version (unversioned) input and runs the first turn step", async () => {- const sessionState = createSessionState();- const parentWritable = new WritableStream<Uint8Array>();- const delivery = {- kind: "deliver",- payloads: [{ message: "hello" }],- } satisfies HookPayload;- vi.mocked(turnStep).mockResolvedValueOnce({- action: "done",- output: "ok",- serializedContext: { state: "done" },- sessionState,- });-- await turnWorkflow({- capabilities: undefined,- completionToken: "turn-token",- delivery,- mode: "conversation",- parentWritable,- serializedContext: { state: "start" },- sessionState,- });-- expect(turnStep).toHaveBeenCalledWith({- input: delivery,- parentWritable,- serializedContext: { state: "start" },- sessionState,- });- expect(resumeHookMock).toHaveBeenCalledWith(- "turn-token",- expect.objectContaining({ kind: "turn-result" }),- );- });-- it("keeps tool-loop continuations inside the same turn workflow", async () => {- const sessionState = createSessionState();- vi.mocked(turnStep)- .mockResolvedValueOnce({- action: "continue",- serializedContext: { state: "continued" },- sessionState,- })- .mockResolvedValueOnce({- action: "done",- output: "after continue",- serializedContext: { state: "done" },- sessionState,- });-- const { input } = createInput({ sessionState });- await turnWorkflow(input);-- expect(vi.mocked(turnStep).mock.calls[0]?.[0].input).toBe(input.stepInput.input);- expect(vi.mocked(turnStep).mock.calls[1]?.[0].input).toBeUndefined();- expect(resumeHookMock).toHaveBeenCalledWith(- "turn-token",- expect.objectContaining({- action: expect.objectContaining({ kind: "done", output: "after continue" }),- kind: "turn-result",- }),- );- });-- it("parks when an authorization is pending", async () => {- const sessionState = createSessionState();- vi.mocked(turnStep).mockResolvedValueOnce({- action: "park",- hasPendingAuthorization: true,- hasPendingInputBatch: false,- serializedContext: { state: "needs-auth" },- sessionState,- });-- const { input } = createInput({- mode: "task",- sessionState,- });- await turnWorkflow(input);-- expect(resumeHookMock).toHaveBeenCalledWith(- "turn-token",- expect.objectContaining({- action: expect.objectContaining({- kind: "park",- sessionState,- }),- kind: "turn-result",- }),- );- });-- it("dispatches runtime actions when a runtime action batch is pending", async () => {- const sessionState = createSessionState();- vi.mocked(turnStep).mockResolvedValueOnce({- action: "park",- hasPendingAuthorization: false,- hasPendingInputBatch: false,- pendingCoordinationCallIds: ["call-1"],- serializedContext: { state: "pending-runtime-action" },- sessionState,- });-- const { input } = createInput({ mode: "task", sessionState });- await turnWorkflow(input);-- expect(resumeHookMock).toHaveBeenCalledWith("turn-token", {- action: {- kind: "dispatch-coordination",- pendingCallIds: ["call-1"],- serializedContext: { state: "pending-runtime-action" },- sessionState,- },- kind: "turn-result",- });- });-- it("parks for pending input when the channel supports input requests", async () => {- const sessionState = createSessionState();- vi.mocked(turnStep).mockResolvedValueOnce({- action: "park",- hasPendingAuthorization: false,- hasPendingInputBatch: true,- serializedContext: { state: "pending-input" },- sessionState,- });-- const { input } = createInput({- capabilities: { requestInput: true },- mode: "task",- sessionState,- });- await turnWorkflow(input);-- expect(resumeHookMock).toHaveBeenCalledWith(- "turn-token",- expect.objectContaining({- action: expect.objectContaining({- kind: "park",- serializedContext: { state: "pending-input" },- }),- kind: "turn-result",- }),- );- });-- it("reports task-mode waits as turn errors", async () => {- const sessionState = createSessionState();- vi.mocked(turnStep).mockResolvedValueOnce({- action: "park",- hasPendingAuthorization: false,- hasPendingInputBatch: false,- serializedContext: { state: "task-wait" },- sessionState,- });-- const { input } = createInput({ mode: "task", sessionState });- await expect(turnWorkflow(input)).rejects.toThrow();-- expect(resumeHookMock).toHaveBeenCalledTimes(1);- expect(resumeHookMock.mock.calls[0]?.[0]).toBe("turn-token");- expect(resumeHookMock.mock.calls[0]?.[1]).toMatchObject({- kind: "turn-error",- });- });-- it("reports a cancelled turn as a park with the cancelled marker", async () => {- const sessionState = createSessionState();- const cancelledState = createSessionState({ continuationToken: "cancelled-state" });- installInbox([]);- vi.mocked(turnStep).mockResolvedValueOnce({- action: "cancelled",- serializedContext: { state: "cancelled" },- sessionState: cancelledState,- });-- // Task mode on purpose: cancellation bypasses the `canPark` gate.- const { input } = createInput({- driverCapabilities: { cancelledTurnSettle: true, turnInbox: true },- mode: "task",- sessionState,- });- await turnWorkflow(input);-- expect(vi.mocked(turnStep).mock.calls[0]?.[0].abortSignal).toBeInstanceOf(AbortSignal);- expect(cancelDescendantTurnsStep).toHaveBeenCalledWith({- serializedContext: { state: "cancelled" },- sessionState: cancelledState,- });- // The command inbox forwards cancellation to this turn-private hook.- expect(cancelHookTokens()).toEqual(["turn-token:cancel"]);- // The cancelled step has already rolled its context back to the allowed- // carve-outs, which must reach the driver cancellation epilogue.- expect(resumeHookMock).toHaveBeenCalledWith("turn-token", {- action: {- cancelled: true,- kind: "park",- serializedContext: { state: "cancelled" },- sessionState: cancelledState,- },- kind: "turn-result",- });- expect(resumeHookMock.mock.calls.filter((call) => call[1]?.kind === "turn-error")).toEqual([]);- });-- it("commits and releases background tasks before settling a cancelled turn", async () => {- const initialState = createSessionState({ continuationToken: "http:parent" });- const backgroundState = createSessionState({ continuationToken: "http:parent:background" });- const backgroundContext = {- "eve.harness.agentTrace": { actions: { "action-1": {} }, sessions: {}, turns: {} },- "eve.harness.instrumentationActionScopes": {- "action-1": { scope: { turnId: "turn-1" }, taskId: "task-1" },- },- "eve.harness.instrumentationState": { "sink\0action-1": { value: "open" } },- };- const backgroundTasks = [- {- taskId: "task-1",- taskInboxToken: "task-inbox-1",- taskRunId: "task-run-1",- },- ];- const adopt = vi.spyOn(TurnExecutionCursor.prototype, "adopt");- installInbox([]);- vi.mocked(turnStep).mockResolvedValueOnce({- action: "cancelled",- backgroundTaskContext: { ...backgroundContext, state: "start" },- backgroundTaskState: backgroundState,- backgroundTasks,- serializedContext: { ...backgroundContext, state: "cancelled" },- sessionState: initialState,- });-- const { input } = createInput({- driverCapabilities: { cancelledTurnSettle: true, turnInbox: true },- mode: "task",- sessionState: initialState,- });- await turnWorkflow(input);-- expect(acknowledgeDelegatedTasksStep).toHaveBeenCalledWith({ tasks: backgroundTasks });- expect(adopt.mock.calls[0]?.[0]).toEqual({- serializedContext: { ...backgroundContext, state: "start" },- sessionState: backgroundState,- });- expect(cancelDescendantTurnsStep).toHaveBeenCalledWith({- serializedContext: { ...backgroundContext, state: "cancelled" },- sessionState: backgroundState,- });- adopt.mockRestore();- });-- it("checkpoints a durable turn step that finishes as cancellation arrives", async () => {- const sessionState = createSessionState();- const completedState = createSessionState({ continuationToken: "completed-state" });- installInbox([], { cancelPayloads: [{}] });- vi.mocked(turnStep).mockImplementationOnce(async (stepInput) => {- await vi.waitFor(() => expect(stepInput.abortSignal?.aborted).toBe(true));- return {- action: "continue",- serializedContext: { state: "completed" },- sessionState: completedState,- };- });-- const { input } = createInput({- driverCapabilities: { cancelledTurnSettle: true, turnInbox: true },- sessionState,- });- await turnWorkflow(input);-- expect(cancelDescendantTurnsStep).toHaveBeenCalledWith({- serializedContext: { state: "completed" },- sessionState: completedState,- });- expect(resumeHookMock).toHaveBeenCalledWith("turn-token", {- action: {- cancelled: true,- kind: "park",- serializedContext: { state: "completed" },- sessionState: completedState,- },- kind: "turn-result",- });- expect(resumeHookMock).not.toHaveBeenCalledWith(- "turn-token",- expect.objectContaining({- action: expect.objectContaining({ kind: "done" }),- }),- );- });-- it("checkpoints background task observability when cancellation arrives after a step", async () => {- const sessionState = createSessionState();- const backgroundState = createSessionState({ continuationToken: "http:background" });- const backgroundTasks = [- {- taskId: "task-1",- taskInboxToken: "task-inbox-1",- taskRunId: "task-run-1",- },- ];- const backgroundContext = {- "eve.harness.agentTrace": { actions: { "action-1": {} }, sessions: {}, turns: {} },- "eve.harness.instrumentationActionScopes": {- "action-1": { scope: { turnId: "turn-1" }, taskId: "task-1" },- },- };- const completedContext = { ...backgroundContext, state: "completed" };- installInbox([], { cancelPayloads: [{}] });- vi.mocked(turnStep).mockImplementationOnce(async (stepInput) => {- await vi.waitFor(() => expect(stepInput.abortSignal?.aborted).toBe(true));- return {- action: "done",- backgroundTaskContext: { ...backgroundContext, state: "start" },- backgroundTaskState: backgroundState,- backgroundTasks,- output: "must not complete",- serializedContext: completedContext,- sessionState,- };- });-- const { input } = createInput({- driverCapabilities: { cancelledTurnSettle: true, turnInbox: true },- sessionState,- });- await turnWorkflow(input);-- expect(cancelDescendantTurnsStep).toHaveBeenCalledWith({- serializedContext: completedContext,- sessionState: backgroundState,- });- expect(resumeHookMock).toHaveBeenCalledWith("turn-token", {- action: {- cancelled: true,- kind: "park",- serializedContext: completedContext,- sessionState: backgroundState,- },- kind: "turn-result",- });- expect(acknowledgeDelegatedTasksStep).toHaveBeenCalledWith({ tasks: backgroundTasks });- expect(resumeHookMock).not.toHaveBeenCalledWith(- "turn-token",- expect.objectContaining({- action: expect.objectContaining({ kind: "done" }),- }),- );- });-- it("runs uncancellable when the session cancel token is claimed by another run", async () => {- const sessionState = createSessionState();- installInbox([], { cancelConflict: { runId: "wrun_stale_prior_turn" } });- vi.mocked(turnStep).mockResolvedValueOnce({- action: "done",- output: "ok",- serializedContext: { state: "done" },- sessionState,- });-- const { input } = createInput({- driverCapabilities: { cancelledTurnSettle: true, turnInbox: true },- sessionState,- });- await turnWorkflow(input);-- // The stale claim degrades cancellation instead of failing the turn.- expect(vi.mocked(turnStep).mock.calls[0]?.[0].abortSignal).toBeUndefined();- expect(resumeHookMock).toHaveBeenCalledWith(- "turn-token",- expect.objectContaining({ kind: "turn-result" }),- );- expect(resumeHookMock.mock.calls.filter((call) => call[1]?.kind === "turn-error")).toEqual([]);- });-- it("disposes the session cancel hook before publishing the turn result", async () => {- const sessionState = createSessionState();- installInbox([]);- vi.mocked(turnStep).mockResolvedValueOnce({- action: "done",- output: "ok",- serializedContext: { state: "done" },- sessionState,- });-- const { input } = createInput({- driverCapabilities: { cancelledTurnSettle: true, turnInbox: true },- sessionState,- });- await turnWorkflow(input);-- // The next turn must never race this run's teardown, so disposal- // precedes the terminal send.- const cancelHook = createHookMock.mock.results.find(- (result) => (result.value as { token?: string }).token === "turn-token:cancel",- )?.value as { dispose: ReturnType<typeof vi.fn> };- const resultCall = resumeHookMock.mock.calls.findIndex(- (call) => call[1]?.kind === "turn-result",- );- expect(cancelHook.dispose).toHaveBeenCalled();- expect(cancelHook.dispose.mock.invocationCallOrder[0]).toBeLessThan(- resumeHookMock.mock.invocationCallOrder[resultCall]!,- );- });-- it("registers no cancel hook when the driver cannot settle cancelled parks", async () => {- const sessionState = createSessionState();- installInbox([]);- vi.mocked(turnStep).mockResolvedValueOnce({- action: "done",- output: "ok",- serializedContext: { state: "done" },- sessionState,- });-- const { input } = createInput({ driverCapabilities: { turnInbox: true }, sessionState });- await turnWorkflow(input);-- expect(vi.mocked(turnStep).mock.calls[0]?.[0].abortSignal).toBeUndefined();- expect(cancelHookTokens()).toEqual([]);- });-- it("registers a cancel hook for a task session without a continuation alias", async () => {- const sessionState = createSessionState({ continuationToken: "" });- installInbox([]);- vi.mocked(turnStep).mockResolvedValueOnce({- action: "done",- output: "ok",- serializedContext: { state: "done" },- sessionState,- });-- const { input } = createInput({- driverCapabilities: { cancelledTurnSettle: true, turnInbox: true },- mode: "task",- sessionState,- });- await turnWorkflow(input);-- expect(vi.mocked(turnStep).mock.calls[0]?.[0].abortSignal).toBeInstanceOf(AbortSignal);- expect(cancelHookTokens()).toEqual(["turn-token:cancel"]);- });-- it("deduplicates concurrent turn workflows through inbox ownership", async () => {- const sessionState = createSessionState();- const ownerInbox = createInboxMock([]);- const duplicateInbox = createInboxMock([], {- conflict: { runId: "wrun_owner" },- });- installHookDispatch([ownerInbox, duplicateInbox]);- vi.mocked(turnStep).mockResolvedValueOnce({- action: "done",- output: "ok",- serializedContext: { state: "done" },- sessionState,- });-- const { input } = createInput({- driverCapabilities: { turnInbox: true },- sessionState,- });- await Promise.all([turnWorkflow(input), turnWorkflow(input)]);-- expect(turnStep).toHaveBeenCalledOnce();- expect(- resumeHookMock.mock.calls.filter((call) => call[1]?.kind === "turn-result"),- ).toHaveLength(1);- expect(resumeHookMock.mock.calls.filter((call) => call[1]?.kind === "turn-error")).toEqual([]);- expect(ownerInbox.dispose).toHaveBeenCalledOnce();- expect(duplicateInbox.dispose).toHaveBeenCalledOnce();- expect(ownerInbox.createIterator).toHaveBeenCalledOnce();- expect(duplicateInbox.createIterator).toHaveBeenCalledOnce();- });-- it("deduplicates a cross-realm inbox conflict rejection", async () => {- const inbox = installInbox([], {- claimError: {- conflictingRunId: "wrun_owner",- name: "HookConflictError",- token: "turn-token:inbox",- },- });- const { input } = createInput({ driverCapabilities: { turnInbox: true } });-- await turnWorkflow(input);-- expect(turnStep).not.toHaveBeenCalled();- expect(resumeHookMock).not.toHaveBeenCalled();- expect(inbox.dispose).toHaveBeenCalledOnce();- expect(inbox.createIterator).toHaveBeenCalledOnce();- });-- it("reports non-conflict inbox claim failures to the driver", async () => {- const failure = new Error("hook storage unavailable");- const inbox = installInbox([], { claimError: failure });- const { input } = createInput({ driverCapabilities: { turnInbox: true } });-- await expect(turnWorkflow(input)).rejects.toBe(failure);-- expect(turnStep).not.toHaveBeenCalled();- expect(resumeHookMock).toHaveBeenCalledTimes(1);- expect(resumeHookMock.mock.calls[0]?.[0]).toBe("turn-token");- expect(resumeHookMock.mock.calls[0]?.[1]).toMatchObject({ kind: "turn-error" });- expect(inbox.dispose).toHaveBeenCalledOnce();- expect(inbox.createIterator).toHaveBeenCalledOnce();- });-- it("waits for dispatch adoption before cascading a cancellation", async () => {- const initialState = createSessionState({ continuationToken: "http:parent" });- const pendingState = createSessionState({ continuationToken: "http:parent:turn" });- const adoptedState = createSessionState({ continuationToken: "http:parent:turn:adopted" });- let finishDispatch:- | ((value: {- results: readonly [];- sessionState: DurableSessionState;- pendingTasks: readonly [];- }) => void)- | undefined;- const dispatchResult = new Promise<{- results: readonly [];- sessionState: DurableSessionState;- pendingTasks: readonly [];- }>((resolve) => {- finishDispatch = resolve;- });- installInbox([], { cancelPayloads: [{}], stayOpen: true });- vi.mocked(dispatchCoordinationStep).mockReturnValue(dispatchResult);- vi.mocked(turnStep)- .mockResolvedValueOnce({- action: "park",- hasPendingAuthorization: false,- hasPendingInputBatch: false,- pendingCoordinationCallIds: ["call-1"],- serializedContext: { state: "pending" },- sessionState: pendingState,- })- .mockResolvedValueOnce({- action: "cancelled",- serializedContext: { state: "cancelled" },- sessionState: adoptedState,- });-- const { input } = createInput({- driverCapabilities: { cancelledTurnSettle: true, turnInbox: true },- mode: "task",- sessionState: initialState,- });- const workflow = turnWorkflow(input);- await vi.waitFor(() => expect(dispatchCoordinationStep).toHaveBeenCalledOnce());- expect(cancelDescendantTurnsStep).not.toHaveBeenCalled();-- finishDispatch?.({ results: [], sessionState: adoptedState, pendingTasks: [] });- await workflow;-- expect(vi.mocked(turnStep).mock.calls[1]?.[0].abortSignal?.aborted).toBe(true);- expect(cancelDescendantTurnsStep).toHaveBeenCalledWith({- serializedContext: { state: "cancelled" },- sessionState: adoptedState,- });- expect(vi.mocked(dispatchCoordinationStep).mock.invocationCallOrder[0]).toBeLessThan(- vi.mocked(cancelDescendantTurnsStep).mock.invocationCallOrder[0]!,- );- });-- it("proxies child HITL and pulls the response through the active turn", async () => {- const runningChildren = [{ callId: "call-1", sessionId: "child-session" }];- const pendingState = createSessionState();- const proxyState = withRunningChildren(- createSessionState({ hasProxyInputRequests: true }),- runningChildren,- );- const retiredProxyState = withRunningChildren(createSessionState(), runningChildren);- const completedState = createSessionState();- const requestId = "turn-token:inbox:delivery:0";- installInbox([- {- callId: "call-1",- childContinuationToken: "subagent:parent:call-1",- childSessionId: "child-session",- event: { requests: [], sequence: 0, stepIndex: 0, turnId: "turn_0" },- kind: "subagent-input-request",- subagentName: "delegate",- },- {- delivery: {- kind: "deliver",- payloads: [{ inputResponses: [{ optionId: "approve", requestId: "approval-1" }] }],- },- kind: "driver-delivery",- requestId,- },- {- kind: "runtime-action-result",- results: [- {- callId: "call-1",- kind: "subagent-result",- origin: "child",- output: "approved child output",- subagentName: "delegate",- },- ],- },- ]);- vi.mocked(dispatchCoordinationStep).mockResolvedValue({- results: [],- sessionState: withRunningChildren(pendingState, runningChildren),- pendingTasks: [],- });- vi.mocked(runProxySubagentEventStep).mockResolvedValue({- serializedContext: { state: "proxied" },- sessionState: proxyState,- });- vi.mocked(routeDeliverToChildren).mockResolvedValue({- kind: "continue",- remainder: undefined,- serializedContext: { state: "proxied" },- sessionState: retiredProxyState,- });- vi.mocked(turnStep)- .mockResolvedValueOnce({- action: "park",- hasPendingAuthorization: false,- hasPendingInputBatch: false,- pendingCoordinationCallIds: ["call-1"],- serializedContext: { state: "pending" },- sessionState: pendingState,- })- .mockResolvedValueOnce({- action: "done",- output: "done",- serializedContext: { state: "done" },- sessionState: completedState,- });-- const { input } = createInput({- driverCapabilities: { turnInbox: true },- mode: "task",- sessionState: pendingState,- });- await turnWorkflow(input);-- expect(runProxySubagentEventStep).toHaveBeenCalledOnce();- expect(resumeHookMock).toHaveBeenCalledWith("turn-token", {- continuationToken: "http:test",- inboxToken: "turn-token:inbox",- kind: "turn-delivery-request",- requestId,- });- expect(resumeHookMock).toHaveBeenCalledWith("turn-token", {- kind: "turn-delivery-accepted",- requestId,- });- expect(routeDeliverToChildren).toHaveBeenCalledWith(- expect.objectContaining({- delivery: {- kind: "deliver",- payloads: [{ inputResponses: [{ optionId: "approve", requestId: "approval-1" }] }],- },- sessionState: proxyState,- }),- );- expect(vi.mocked(turnStep).mock.calls[1]?.[0].sessionState).toBe(retiredProxyState);- });-- it("marks workflow-tool owner-channel input requests as answer hooks", async () => {- const pendingState = createSessionState();- const dispatchedState = withWorkflowToolRun(createSessionState());- const proxyState = withWorkflowToolRun(createSessionState({ hasProxyInputRequests: true }));- const retiredProxyState = withWorkflowToolRun(createSessionState());- const completedState = createSessionState();- const answerToken = "eve:workflow-tool-run-answer:run-1:0";- const requestId = "turn-token:inbox:delivery:0";- const workflowRequest = {- kind: "request",- from: {- callId: "call-1",- execution: "blocking" as const,- input: { service: "api" },- runId: "run-1",- sequence: 0,- stepIndex: 1,- toolName: "confirm_deploy",- turnId: "turn_0",- },- replyTo: answerToken,- request: {- options: [- { id: "approve", label: "Approve" },- { id: "reject", label: "Reject" },- ],- prompt: "Approve deploy?",- },- };- definedHookPayloads.set("generated-owner-token", [workflowRequest]);- installInbox([- {- delivery: {- kind: "deliver",- payloads: [{ inputResponses: [{ optionId: "approve", requestId: answerToken }] }],- },- kind: "driver-delivery",- requestId,- },- {- kind: "runtime-action-result",- results: [- {- callId: "call-1",- kind: "tool-result",- output: { approved: true, service: "api" },- toolName: "confirm_deploy",- },- ],- },- ]);- vi.mocked(dispatchCoordinationStep).mockResolvedValue({- results: [],- sessionState: dispatchedState,- pendingTasks: [],- });- vi.mocked(runProxySubagentEventStep).mockResolvedValue({- serializedContext: { state: "proxied" },- sessionState: proxyState,- });- vi.mocked(routeDeliverToChildren).mockResolvedValue({- kind: "continue",- remainder: undefined,- serializedContext: { state: "proxied" },- sessionState: retiredProxyState,- });- vi.mocked(turnStep)- .mockResolvedValueOnce({- action: "park",- hasPendingAuthorization: false,- hasPendingInputBatch: false,- pendingCoordinationCallIds: ["call-1"],- serializedContext: { state: "pending" },- sessionState: pendingState,- })- .mockResolvedValueOnce({- action: "done",- output: "done",- serializedContext: { state: "done" },- sessionState: completedState,- });-- const { input, parentWritable } = createInput({- driverCapabilities: { turnInbox: true },- mode: "task",- sessionState: pendingState,- });- await turnWorkflow(input);-- expect(runProxySubagentEventStep).toHaveBeenCalledWith({- answerHook: { runId: "run-1" },- hookPayload: expect.objectContaining({- childContinuationToken: answerToken,- childSessionId: "run-1",- kind: "subagent-input-request",- }),- parentWritable,- serializedContext: { state: "pending" },- sessionState: dispatchedState,- });- expect(routeDeliverToChildren).toHaveBeenCalledWith(- expect.objectContaining({- delivery: {- kind: "deliver",- payloads: [{ inputResponses: [{ optionId: "approve", requestId: answerToken }] }],- },- sessionState: proxyState,- }),- );- expect(vi.mocked(turnStep).mock.calls[1]?.[0].input).toEqual({- acceptedAtMsByCallId: { "call-1": expect.any(Number) },- kind: "runtime-action-result",- results: [- {- callId: "call-1",- kind: "tool-result",- output: { approved: true, service: "api" },- toolName: "confirm_deploy",- },- ],- });- });-- it("routes blocking workflow agent lifecycle requests through the recorded run owner", async () => {- const pendingState = createSessionState();- const dispatchedState = withWorkflowToolRun(createSessionState(), "research");- const invokedState = withWorkflowToolRun(createSessionState(), "research");- const settledState = withWorkflowToolRun(createSessionState(), "research");- const completedState = createSessionState();- const childResult = {- callId: "call-1",- kind: "subagent-result" as const,- origin: "child" as const,- outcome: {- kind: "parked" as const,- result: { kind: "succeeded" as const, output: "done" },- usageDelta: {- cacheReadTokens: 0,- cacheWriteTokens: 0,- inputTokens: 0,- outputTokens: 0,- },- },- output: "done",- subagentName: "research",- };- definedHookPayloads.set("generated-owner-token", [- {- kind: "request",- from: {- callId: "call-1",- execution: "blocking",- input: {},- resultKind: "subagent",- runId: "run-1",- sequence: 0,- stepIndex: 0,- toolName: "research",- turnId: "turn_0",- },- replyTo: "agent-reply",- request: {- input: { message: "Find it", target: "research" },- invocationId: "call-1",- kind: "agent-invoke",- },- },- {- kind: "request",- from: {- callId: "call-1",- execution: "blocking",- input: {},- resultKind: "subagent",- runId: "run-1",- sequence: 0,- stepIndex: 0,- toolName: "research",- turnId: "turn_0",- },- replyTo: "agent-reply",- request: { kind: "agent-settled", result: childResult },- },- {- kind: "outcome",- from: {- callId: "call-1",- execution: "blocking",- input: {},- resultKind: "subagent",- runId: "run-1",- sequence: 0,- stepIndex: 0,- toolName: "research",- turnId: "turn_0",- },- result: { output: childResult, status: "completed" },- },- ]);- installInbox([], { stayOpen: true });- vi.mocked(dispatchCoordinationStep).mockResolvedValue({- results: [],- sessionState: dispatchedState,- pendingTasks: [],- });- vi.mocked(applyTaskAgentRequest)- .mockResolvedValueOnce({ serializedContext: {}, sessionState: invokedState })- .mockResolvedValue({ serializedContext: {}, sessionState: settledState });- vi.mocked(releaseAgentInvocationOwnerStep).mockResolvedValue({ sessionState: settledState });- vi.mocked(turnStep)- .mockResolvedValueOnce({- action: "park",- hasPendingAuthorization: false,- hasPendingInputBatch: false,- pendingCoordinationCallIds: ["call-1"],- serializedContext: {},- sessionState: pendingState,- })- .mockResolvedValueOnce({- action: "done",- output: "done",- serializedContext: {},- sessionState: completedState,- });-- const { input } = createInput({- driverCapabilities: { turnInbox: true },- mode: "task",- sessionState: pendingState,- });- await turnWorkflow(input);-- expect(vi.mocked(applyTaskAgentRequest).mock.calls.map(([delivery]) => delivery)).toEqual([- expect.objectContaining({- ownerId: "run-1",- request: {- kind: "agent-invoke",- invocationId: "call-1",- input: expect.any(Object),- },- }),- expect.objectContaining({- ownerId: "run-1",- replyTo: "agent-reply",- request: { kind: "agent-settled", result: childResult },- }),- expect.objectContaining({- ownerId: "run-1",- replyTo: "run-1",- request: { kind: "agent-settled", result: childResult },- }),- ]);- });-- it("drops an unbound legacy child event before proxying it", async () => {- const pendingState = createSessionState();- installInbox([- {- callId: "call-1",- childContinuationToken: "child-token",- childSessionId: "wrong-child",- event: { requests: [], sequence: 0, stepIndex: 0, turnId: "turn_0" },- kind: "subagent-input-request",- subagentName: "delegate",- },- {- kind: "runtime-action-result",- results: [- {- callId: "call-1",- kind: "subagent-result",- origin: "child",- output: "child output",- subagentName: "delegate",- },- ],- },- ]);- vi.mocked(dispatchCoordinationStep).mockResolvedValue({- results: [],- sessionState: withRunningChildren(pendingState, [- { callId: "call-1", sessionId: "child-session" },- ]),- pendingTasks: [],- });- vi.mocked(turnStep)- .mockResolvedValueOnce({- action: "park",- hasPendingAuthorization: false,- hasPendingInputBatch: false,- pendingCoordinationCallIds: ["call-1"],- serializedContext: {},- sessionState: pendingState,- })- .mockResolvedValueOnce({- action: "done",- output: "done",- serializedContext: {},- sessionState: createSessionState(),- });-- const { input } = createInput({- driverCapabilities: { turnInbox: true },- mode: "task",- sessionState: pendingState,- });- await turnWorkflow(input);-- expect(runProxySubagentEventStep).not.toHaveBeenCalled();- });-- it("lets the parent cancel after a descendant consumes a session-limit Stop response", async () => {- const pendingState = withRunningChildren(createSessionState(), [- { callId: "call-1", sessionId: "child-session" },- ]);- const proxyState = createSessionState({ hasProxyInputRequests: true });- const retiredProxyState = createSessionState();- const requestId = "child-limit-request";- installInbox([- {- callId: "call-1",- childContinuationToken: "subagent:parent:call-1",- childSessionId: "child-session",- event: { requests: [], sequence: 0, stepIndex: 1, turnId: "turn_0" },- kind: "subagent-input-request",- subagentName: "delegate",- },- {- delivery: {- kind: "deliver",- payloads: [{ inputResponses: [{ optionId: "stop", requestId }] }],- },- kind: "driver-delivery",- requestId: "turn-token:inbox:delivery:0",- },- ]);- vi.mocked(dispatchCoordinationStep).mockResolvedValue({- results: [],- sessionState: pendingState,- pendingTasks: [],- });- vi.mocked(runProxySubagentEventStep).mockResolvedValue({- serializedContext: { state: "proxied" },- sessionState: proxyState,- });- vi.mocked(routeDeliverToChildren).mockResolvedValue({- kind: "cancel-turn",- serializedContext: { state: "proxied" },- sessionState: retiredProxyState,- });- vi.mocked(turnStep).mockResolvedValueOnce({- action: "park",- hasPendingAuthorization: false,- hasPendingInputBatch: false,- pendingCoordinationCallIds: ["call-1"],- serializedContext: { state: "pending" },- sessionState: pendingState,- });-- const { input } = createInput({- driverCapabilities: { cancelledTurnSettle: true, turnInbox: true },- mode: "conversation",- sessionState: pendingState,- });- await turnWorkflow(input);-- expect(cancelDescendantTurnsStep).toHaveBeenCalledWith({- serializedContext: { state: "proxied" },- sessionState: retiredProxyState,- });- expect(turnStep).toHaveBeenCalledOnce();- expect(resumeHookMock).toHaveBeenCalledWith("turn-token", {- action: {- cancelled: true,- kind: "park",- serializedContext: { state: "proxied" },- sessionState: retiredProxyState,- },- kind: "turn-result",- });- });-- it("proxies child authorization lifecycle events while continuing to await its result", async () => {- const runningChildren = [{ callId: "call-1", sessionId: "child-session" }];- const pendingState = createSessionState();- const requiredState = withRunningChildren(createSessionState(), runningChildren);- const completedAuthState = withRunningChildren(createSessionState(), runningChildren);- const completedState = createSessionState();- const requiredEvent = {- data: {- authorization: { displayName: "Linear", url: "https://idp.example/authorize" },- description: "Authorization required for linear",- name: "linear",- sequence: 0,- stepIndex: 1,- turnId: "turn_0",- webhookUrl: "https://eve.example/connections/linear/callback/child%3Aauth",- },- type: "authorization.required" as const,- };- const completedEvent = {- data: {- authorization: { displayName: "Linear", url: "https://idp.example/authorize" },- name: "linear",- outcome: "authorized" as const,- sequence: 0,- stepIndex: 2,- turnId: "turn_0",- },- type: "authorization.completed" as const,- };- installInbox([- {- callId: "call-1",- childSessionId: "child-session",- event: requiredEvent,- kind: "subagent-authorization-event",- subagentName: "delegate",- },- {- callId: "call-1",- childSessionId: "child-session",- event: completedEvent,- kind: "subagent-authorization-event",- subagentName: "delegate",- },- {- kind: "runtime-action-result",- results: [- {- callId: "call-1",- kind: "subagent-result",- origin: "child",- output: "authorized child output",- subagentName: "delegate",- },- ],- },- ]);- const dispatchedState = withRunningChildren(pendingState, runningChildren);- vi.mocked(dispatchCoordinationStep).mockResolvedValue({- results: [],- sessionState: dispatchedState,- pendingTasks: [],- });- vi.mocked(runProxySubagentEventStep)- .mockResolvedValueOnce({- serializedContext: { state: "auth-required" },- sessionState: requiredState,- })- .mockResolvedValueOnce({- serializedContext: { state: "auth-completed" },- sessionState: completedAuthState,- });- vi.mocked(turnStep)- .mockResolvedValueOnce({- action: "park",- hasPendingAuthorization: false,- hasPendingInputBatch: false,- pendingCoordinationCallIds: ["call-1"],- serializedContext: { state: "pending" },- sessionState: pendingState,- })- .mockResolvedValueOnce({- action: "done",- output: "done",- serializedContext: { state: "done" },- sessionState: completedState,- });-- const { input, parentWritable } = createInput({- driverCapabilities: { turnInbox: true },- mode: "task",- sessionState: pendingState,- });- await turnWorkflow(input);-- expect(vi.mocked(runProxySubagentEventStep).mock.calls).toEqual([- [- {- hookPayload: expect.objectContaining({ event: requiredEvent }),- parentWritable,- serializedContext: { state: "pending" },- sessionState: dispatchedState,- },- ],- [- {- hookPayload: expect.objectContaining({ event: completedEvent }),- parentWritable,- serializedContext: { state: "auth-required" },- sessionState: requiredState,- },- ],- ]);- expect(vi.mocked(turnStep).mock.calls[1]?.[0]).toMatchObject({- input: {- kind: "runtime-action-result",- results: [expect.objectContaining({ output: "authorized child output" })],- },- serializedContext: { state: "auth-completed" },- sessionState: completedAuthState,- });- expect(resumeHookMock).not.toHaveBeenCalledWith(- "turn-token",- expect.objectContaining({ kind: "turn-delivery-request" }),- );- expect(routeDeliverToChildren).not.toHaveBeenCalled();- expect(- resumeHookMock.mock.calls.filter((call) => call[1]?.kind === "turn-result"),- ).toHaveLength(1);- });-- it("mints a unique delivery request id per wait so a stale forward is not re-accepted", async () => {- const pendingState = createSessionState({ hasProxyInputRequests: true });- const completedState = createSessionState();- // The first wait resolves on its child result while a delivery forwarded for- // request `:delivery:0` is still queued behind it. The second wait must mint- // a fresh id so that stale forward is dropped, not mistaken for its response.- installInbox([- {- kind: "runtime-action-result",- results: [- {- callId: "call-1",- kind: "subagent-result",- origin: "child",- output: "first",- subagentName: "delegate",- },- ],- },- {- delivery: {- kind: "deliver",- payloads: [{ inputResponses: [{ optionId: "approve", requestId: "approval-1" }] }],- },- kind: "driver-delivery",- requestId: "turn-token:inbox:delivery:0",- },- {- kind: "runtime-action-result",- results: [- {- callId: "call-2",- kind: "subagent-result",- origin: "child",- output: "second",- subagentName: "delegate",- },- ],- },- ]);- vi.mocked(dispatchCoordinationStep).mockResolvedValue({- results: [],- sessionState: withRunningChildren(pendingState, [- { callId: "call-1", sessionId: "child-session-1" },- { callId: "call-2", sessionId: "child-session-2" },- ]),- pendingTasks: [],- });- vi.mocked(routeDeliverToChildren).mockResolvedValue({- kind: "continue",- remainder: undefined,- serializedContext: {},- sessionState: pendingState,- });- vi.mocked(turnStep)- .mockResolvedValueOnce({- action: "park",- hasPendingAuthorization: false,- hasPendingInputBatch: false,- pendingCoordinationCallIds: ["call-1"],- serializedContext: { state: "batch-1" },- sessionState: pendingState,- })- .mockResolvedValueOnce({- action: "park",- hasPendingAuthorization: false,- hasPendingInputBatch: false,- pendingCoordinationCallIds: ["call-2"],- serializedContext: { state: "batch-2" },- sessionState: pendingState,- })- .mockResolvedValueOnce({- action: "done",- output: "done",- serializedContext: { state: "done" },- sessionState: completedState,- });-- const { input } = createInput({- driverCapabilities: { turnInbox: true },- mode: "task",- sessionState: pendingState,- });- await turnWorkflow(input);-- const deliveryRequestIds = resumeHookMock.mock.calls- .filter((call) => call[1]?.kind === "turn-delivery-request")- .map((call) => call[1]?.requestId);- expect(deliveryRequestIds).toEqual([- "turn-token:inbox:delivery:0",- "turn-token:inbox:delivery:1",- ]);- expect(resumeHookMock).not.toHaveBeenCalledWith(- "turn-token",- expect.objectContaining({ kind: "turn-delivery-accepted" }),- );- expect(routeDeliverToChildren).not.toHaveBeenCalled();- });-});--interface InboxMock {- readonly createIterator: ReturnType<typeof vi.fn>;- readonly dispose: ReturnType<typeof vi.fn>;- readonly hook: unknown;-}--function installInbox(- values: readonly unknown[],- options: {- readonly cancelConflict?: { readonly runId: string } | null;- readonly cancelPayloads?: readonly unknown[];- readonly claimError?: unknown;- readonly conflict?: { readonly runId: string } | null;- readonly stayOpen?: boolean;- } = {},-): InboxMock {- const inbox = createInboxMock(values, options);- installHookDispatch([inbox], {- conflict: options.cancelConflict ?? null,- payloads: options.cancelPayloads ?? [],- });- return inbox;-}--/**- * Routes inbox tokens to the queued inbox mocks and `:cancel` tokens to- * cancel hooks (inert by default — their reads never resolve, so no- * cancellation is ever observed unless a test provides payloads or a- * claim conflict via `cancelOptions`).- */-function installHookDispatch(- inboxes: readonly InboxMock[],- cancelOptions: {- readonly conflict?: { readonly runId: string } | null;- readonly payloads?: readonly unknown[];- } = {},-): void {- const queue = [...inboxes];- createHookMock.mockImplementation((input: { token: string }) =>- input.token.endsWith(":cancel")- ? createCancelHookMock(input.token, cancelOptions)- : queue.shift()?.hook,- );-}--function cancelHookTokens(): string[] {- return createHookMock.mock.calls- .map((call) => (call[0] as { token: string }).token)- .filter((token) => token.endsWith(":cancel"));-}--function createCancelHookMock(- token: string,- options: {- readonly conflict?: { readonly runId: string } | null;- readonly payloads?: readonly unknown[];- } = {},-): unknown {- const queue = [...(options.payloads ?? [])];- return {- token,- getConflict: vi.fn(async () => options.conflict ?? null),- dispose: vi.fn(),- [Symbol.asyncIterator](): AsyncIterator<unknown> {- return {- next: () => {- const value = queue.shift();- return value === undefined- ? new Promise<IteratorResult<unknown>>(() => {})- : Promise.resolve({ done: false, value });- },- return: vi.fn(async () => ({ done: true, value: undefined })),- };- },- };-}--function createInboxMock(- values: readonly unknown[],- options: {- readonly claimError?: unknown;- readonly conflict?: { readonly runId: string } | null;- readonly stayOpen?: boolean;- } = {},-): InboxMock {- const queue = [...values];- const dispose = vi.fn();- const createIterator = vi.fn(() => ({- next: vi.fn(async () => {- const value = queue.shift();- if (value !== undefined) return { done: false, value };- if (options.stayOpen === true) return await new Promise<never>(() => {});- return { done: true, value: undefined };- }),- return: vi.fn(async () => ({ done: true, value: undefined })),- }));- const hook = {- token: "turn-token:inbox",- getConflict: vi.fn(async () => {- if (options.claimError !== undefined) throw options.claimError;- return options.conflict ?? null;- }),- dispose,- [Symbol.asyncIterator](): AsyncIterator<unknown> {- return createIterator();- },- };- return { createIterator, dispose, hook };-}--function createInput(- overrides: Partial<Omit<TurnWorkflowInput, "stepInput" | "version">> & {- readonly sessionState?: DurableSessionState;- } = {},-): {- readonly input: TurnWorkflowInput;- readonly parentWritable: WritableStream<Uint8Array>;-} {- const { sessionState = createSessionState(), ...workflowOverrides } = overrides;- const parentWritable = new WritableStream<Uint8Array>();- return {- input: {- capabilities: undefined,- completionToken: "turn-token",- mode: "conversation",- stepInput: {- input: { kind: "deliver", payloads: [{ message: "hello" }] } satisfies HookPayload,- parentWritable,- serializedContext: { state: "start" },- sessionState,- },- ...workflowOverrides,- version: TURN_WORKFLOW_INPUT_VERSION,- },- parentWritable,- };-}--function createSessionState(overrides: Partial<DurableSessionState> = {}): DurableSessionState {- return {- continuationToken: "http:test",- emissionState: { sequence: 0, sessionStarted: false, stepIndex: 0, turnId: "" },- hasProxyInputRequests: false,- sessionId: "wrun_test_123",- version: 1,- ...overrides,- };-}--/**- * Embeds a snapshot whose handle store owns each child as `running`, the- * shape the dispatch step commits: inbox results only resolve the wait when- * a running handle binds their callId to their claimed sessionId.- */-function withRunningChildren(- state: DurableSessionState,- children: readonly { readonly callId: string; readonly sessionId: string }[],-): DurableSessionState {- return {- ...state,- snapshot: {- session: {- agent: { system: "" },- continuationToken: state.continuationToken,- history: [],- sessionId: state.sessionId,- state: {- [AGENT_HANDLES_STATE_KEY]: {- handles: children.map((child) => ({- address: {- continuationToken: `subagent:parent:${child.callId}`,- kind: "agent/local",- sessionId: child.sessionId,- },- identity: {- id: `ag_delegate:${child.callId}`,- name: "delegate",- nodeId: "subagents/delegate",- },- operation: {- callId: child.callId,- id: `op-${child.callId}`,- kind: "start",- parentTurnId: "turn_0",- },- phase: "running",- })),- },- },- },- version: 1,- },- };-}--function withWorkflowToolRun(- state: DurableSessionState,- toolName = "confirm_deploy",-): DurableSessionState {- const baseSession: HarnessSession = {- agent: { dynamicModel: true, system: "", tools: [] },- compaction: { recentWindowSize: 5, threshold: 10_000 },- continuationToken: state.continuationToken,- history: [],- sessionId: state.sessionId,- };- const session = recordWorkflowToolRun(baseSession, {- callId: "call-1",- hookToken: "eve:workflow-tool-run:run-1",- runId: "run-1",- resultKind: toolName === "research" ? "subagent" : undefined,- toolName,- });- return {- ...state,- snapshot: {- session,- version: 1,- },- };-}diff --git a/packages/eve/src/execution/turn-workflow.ts b/packages/eve/src/execution/turn-workflow.tsdeleted file mode 100644index f6b426ec3..000000000--- a/packages/eve/src/execution/turn-workflow.ts+++ /dev/null@@ -1,545 +0,0 @@-import {- findRunningAgentHandle,- isInboxSubagentResultFromRunningHandle,-} from "#subagents/handles/query.js";-import {- isInboxSubagentResultFromRecordedWorkflowToolRun,- isInboxToolResultFromRecordedWorkflowToolRun,-} from "#harness/workflow-tool-runs.js";-import { createHook, getWorkflowMetadata } from "#compiled/@workflow/core/index.js";--import type { DeliverHookPayload } from "#channel/types.js";-import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-step.js";-import { cancelAllIndexedSessionTasksStep } from "#execution/cancel-indexed-session-tasks-step.js";-import { sendTurnControlStep, type TurnInboxPayload } from "#execution/turn-control-protocol.js";-import { dispatchCoordinationStep } from "#execution/coordination-dispatch-step.js";-import { acknowledgeDelegatedTasksStep } from "#execution/tasks/parent/delegate.js";-import {- migrateTurnWorkflowInput,- type TurnStepInput,- type TurnWorkflowInput,-} from "#execution/durable-session-migrations/turn-workflow.js";-import { claimHookOwnership, disposeHook, isHookConflictError } from "#execution/hook-ownership.js";-import type { NextDriverAction } from "#execution/next-driver-action.js";-import { routeDeliverToChildren } from "#execution/route-child-delivery.js";-import { runProxySubagentEventStep } from "#subagents/event-proxy-step.js";-import {- type ChannelReader,- createChannelReader,- raceChannelReads,-} from "#execution/tools/workflow/owner-channels.js";-import {- openWorkflowToolRunOwnerInbox,- type WorkflowToolRunOwnerInbox,-} from "#execution/tools/workflow/owner.js";-import {- createTurnCancellationControl,- type TurnCancellationControl,-} from "#execution/turn-cancellation-control.js";-import { TurnExecutionCursor } from "#execution/turn-execution-cursor.js";-import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";-import { normalizeSerializableError } from "#execution/workflow-errors.js";-import { turnStep } from "#execution/workflow-steps.js";-import { activeTurnId } from "#harness/active-turn-id.js";-import { resolveRuntimeActionResultsForCallIds } from "#runtime/actions/results.js";-import type { RuntimeActionResult } from "#shared/action-types.js";-import { handleWorkflowToolRunMessage } from "#execution/turn-workflow-tool-run.js";--const TASK_MODE_WAIT_ERROR_MESSAGE = "Task mode cannot wait for follow-up input (`next: null`).";--export type { TurnWorkflowInput };--/**- * Runs one complete logical turn, including child-agent waits when supported.- *- * The turn-owned path also owns turn cancellation: resuming the- * turn-private cancel hook (`{completionToken}:cancel`) mid-turn aborts the- * signal serialized into every `turnStep` and settles the turn as- * `turn.cancelled` → `session.waiting` — never as a failure. A late or- * guard-mismatched cancel is a benign no-op.- */-export async function turnWorkflow(rawInput: unknown): Promise<void> {- "use workflow";-- const input = migrateTurnWorkflowInput(rawInput);-- if (input.driverCapabilities?.turnInbox !== true) {- return runLegacyTurnWorkflow(input);- }-- return runTurnOwnedWorkflow(input);-}--export async function runTurnOwnedWorkflow(- input: TurnWorkflowInput,- onReady?: () => void,-): Promise<void> {- const inbox = createHook<TurnInboxPayload>({ token: `${input.completionToken}:inbox` });- // Hook promises and iterators share one durable cursor. Create the iterator before- // claiming so conflict replay is consumed by getConflict(), not a later iterator read.- const inboxReader = createChannelReader("inbox", inbox);- let initialStep = input.initialStep;- const cursor = new TurnExecutionCursor({- controlToken: input.completionToken,- parentWritable: input.stepInput.parentWritable,- serializedContext:- initialStep?.beforeStep.serializedContext ?? input.stepInput.serializedContext,- sessionState: initialStep?.beforeStep.sessionState ?? input.stepInput.sessionState,- });- // Delivery request ids stay unique across every wait in this turn. A forwarded- // delivery left unconsumed when one wait resolves would otherwise reuse a later- // wait's id and be mis-accepted as that wait's response.- let deliveryRequestSeq = 0;- const nextDeliveryRequestId = (): string =>- `${inbox.token}:delivery:${String(deliveryRequestSeq++)}`;- const bufferedDeliveries: DeliverHookPayload[] = [];- let nextStepInput = input.stepInput.input;- let ownsInbox = false;- let cancellation: TurnCancellationControl | undefined;-- try {- try {- await claimHookOwnership(inbox);- ownsInbox = true;- } catch (error) {- if (isHookConflictError(error)) return;- throw error;- }-- const workflowToolRunInbox = openWorkflowToolRunOwnerInbox();- const readers: TurnReaders = [workflowToolRunInbox.reader, inboxReader];-- // Claimed after the inbox claim so a losing duplicate run never- // contends for the session cancel token.- if (input.driverCapabilities?.cancelledTurnSettle === true) {- cancellation = await createTurnCancellationControl({- controlToken: input.completionToken,- expectedTurnId: activeTurnId(cursor.sessionState.emissionState),- initialPayload: input.initialCancellation,- });- }-- onReady?.();-- while (true) {- const beforeStep = initialStep?.beforeStep ?? {- serializedContext: cursor.serializedContext,- sessionState: cursor.sessionState,- };- const result =- initialStep?.result ??- (await turnStep(cursor.createStepInput(nextStepInput, cancellation?.signal)));- initialStep = undefined;- const pendingCallIds =- result.action === "park" ? result.pendingCoordinationCallIds : undefined;- const hasBackgroundTasks = (result.backgroundTasks?.length ?? 0) > 0;-- if (hasBackgroundTasks) {- if (result.backgroundTaskState === undefined) {- throw new Error("Background tasks were returned without their committed session state.");- }- await cursor.adopt({- serializedContext: result.backgroundTaskContext ?? beforeStep.serializedContext,- sessionState: result.backgroundTaskState,- });- await acknowledgeDelegatedTasksStep({ tasks: result.backgroundTasks ?? [] });- }-- // A cancel observed while the step was returning must still win: the- // step may have missed the abort and completed normally. Pending- // runtime-action batches are exempt — their wait observes the signal.- if (result.action === "cancelled") {- // The cancelled step returns its latest safe checkpoint: completed- // model calls survive, while the active model-and-tool cycle does not.- // Adopt it before the driver emits the cancellation epilogue.- await cursor.adopt({- serializedContext: result.serializedContext,- sessionState: result.backgroundTaskState ?? result.sessionState,- });- await finishCancelledTurn({ bufferedDeliveries, cancellation, cursor });- return;- }-- if (- cancellation?.signal.aborted === true &&- (pendingCallIds === undefined || hasBackgroundTasks)- ) {- // Some worlds cannot interrupt a running step, so it may complete just- // as cancellation arrives. Its successful return is already a durable- // boundary: preserve it, then settle cancellation before another step.- await cursor.adopt({- serializedContext: result.serializedContext,- sessionState: result.backgroundTaskState ?? result.sessionState,- });- // No `canPark` check here: that gate rejects model-authored waits- // (`next: null`) in task mode, whereas every session can resume by- // stable ID after a cancelled turn. The epilogue runs in the driver- // (`settleCancelledTurnStep`), not as a step in this run, where queued- // cancel wakes could re-dispatch it.- await finishCancelledTurn({ bufferedDeliveries, cancellation, cursor });- return;- }-- if (result.action === "done") {- await cancellation?.dispose();- await cursor.finish(- result,- {- kind: "done",- output: result.output ?? "",- isError: result.isError,- usage: result.usage,- usageDelta: result.usageDelta,- },- bufferedDeliveries,- );- return;- }-- if (pendingCallIds !== undefined && result.action === "park") {- await cursor.adopt(result);- const dispatchResult = await dispatchCoordinationStep({- action: result.action,- callbackBaseUrl: resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url),- workflowToolRunOwner: workflowToolRunInbox.owner,- parentWritable: cursor.parentWritable,- serializedContext: cursor.serializedContext,- sessionState: cursor.sessionState,- });- const initialAcceptedAtMs = dispatchResult.results.length === 0 ? undefined : Date.now();- await cursor.adopt(dispatchResult);- await acknowledgeDelegatedTasksStep({ tasks: dispatchResult.pendingTasks });-- const results = await waitForRuntimeActionResults({- bufferedDeliveries,- cancellation,- cursor,- inboxToken: inbox.token,- initialAcceptedAtMs,- initialResults: dispatchResult.results,- nextDeliveryRequestId,- readers,- pendingCallIds,- });- if (results === "cancelled") {- // The next turnStep observes the aborted signal and settles- // through the `cancelled` arm above.- nextStepInput = undefined;- continue;- }- if (results === "cancel-turn") {- await finishCancelledTurn({ bufferedDeliveries, cancellation, cursor });- return;- }- nextStepInput = { kind: "runtime-action-result", ...results };- continue;- }-- if (result.action === "park") {- const canPark =- result.hasPendingAuthorization ||- (result.hasPendingInputBatch && input.capabilities?.requestInput === true) ||- input.mode === "conversation";-- if (!canPark) throw new Error(TASK_MODE_WAIT_ERROR_MESSAGE);-- await cancellation?.dispose();- await cursor.finish(- result,- {- authorizationAttemptIds: result.authorizationAttemptIds,- authorizationNames: result.authorizationNames,- kind: "park",- settled: result.settled,- },- bufferedDeliveries,- );- return;- }-- await cursor.adopt(result);- nextStepInput = undefined;- }- } catch (error) {- await cursor.send({ error: normalizeSerializableError(error), kind: "turn-error" });- throw error;- } finally {- // Dispose-only teardown: `iterator.return()` would await a pending- // durable read that never settles, leaving this run `running` forever- // and its hooks unswept. The cancel token is disposed *before* each- // terminal result publishes so the next turn's claim never races this- // run's teardown; this backstop covers the error path.- if (cancellation !== undefined) await cancellation.dispose();- if (ownsInbox) await disposeHook(inbox);- }-}--type TurnReaders = readonly [- WorkflowToolRunOwnerInbox["reader"],- ChannelReader<"inbox", TurnInboxPayload>,-];--async function finishCancelledTurn(input: {- readonly bufferedDeliveries: readonly DeliverHookPayload[];- readonly cancellation: TurnCancellationControl | undefined;- readonly cursor: TurnExecutionCursor;-}): Promise<void> {- const cancellation =- input.cancellation?.signal.aborted === true ? await input.cancellation.payload : undefined;- if (cancellation?.tasks === true) {- await cancelAllIndexedSessionTasksStep({- serializedContext: input.cursor.serializedContext,- sessionState: input.cursor.sessionState,- });- }- await cancelDescendantTurnsStep({- serializedContext: input.cursor.serializedContext,- sessionState: input.cursor.sessionState,- });- await input.cancellation?.dispose();- await input.cursor.finish(- { sessionState: input.cursor.sessionState },- { cancelled: true, kind: "park" },- input.bufferedDeliveries,- );-}--// These sentinels stay outside `RuntimeActionResult`. That union is the-// schema-validated wire type projected into harness resume calls; these are-// turn-workflow control outcomes that never leave the workflow.-interface AcceptedRuntimeActionBatch {- readonly acceptedAtMsByCallId: Readonly<Record<string, number>>;- readonly results: readonly RuntimeActionResult[];-}--async function waitForRuntimeActionResults(input: {- readonly bufferedDeliveries: DeliverHookPayload[];- readonly cancellation: TurnCancellationControl | undefined;- readonly cursor: TurnExecutionCursor;- readonly inboxToken: string;- readonly initialAcceptedAtMs: number | undefined;- readonly initialResults: readonly RuntimeActionResult[];- readonly nextDeliveryRequestId: () => string;- readonly pendingCallIds: readonly string[];- readonly readers: TurnReaders;-}): Promise<AcceptedRuntimeActionBatch | "cancelled" | "cancel-turn"> {- let pendingDeliveryRequest: string | undefined;- const results: RuntimeActionResult[] = [...input.initialResults];- const acceptedAtMsByCallId = new Map<string, number>();- if (input.initialAcceptedAtMs !== undefined) {- for (const result of input.initialResults) {- acceptedAtMsByCallId.set(result.callId, input.initialAcceptedAtMs);- }- }-- while (true) {- const ready = resolveRuntimeActionResultsForCallIds({- pendingCallIds: input.pendingCallIds,- results,- });- if (ready !== undefined) {- if (pendingDeliveryRequest !== undefined) {- // The entry may already be racing public input against this wait.- // Cancellation keeps that input available for the next parent turn.- await input.cursor.send({- kind: "turn-delivery-cancelled",- requestId: pendingDeliveryRequest,- });- }- return {- acceptedAtMsByCallId: Object.fromEntries(- ready.map((result) => [result.callId, acceptedAtMsByCallId.get(result.callId)!]),- ),- results: ready,- };- }-- if (input.cursor.sessionState.hasProxyInputRequests && pendingDeliveryRequest === undefined) {- pendingDeliveryRequest = input.nextDeliveryRequestId();- await input.cursor.send({- continuationToken: input.cursor.sessionState.continuationToken,- inboxToken: input.inboxToken,- kind: "turn-delivery-request",- requestId: pendingDeliveryRequest,- });- }-- // A read that loses to a cancel stays pending and is dropped by disposal- // in teardown.- const read = await raceChannelReads(input.readers, input.cancellation?.requested);- if (read === "cancel") {- if (pendingDeliveryRequest !== undefined) {- // Release the raced public input back to the driver so it stays- // available for the next turn.- await input.cursor.send({- kind: "turn-delivery-cancelled",- requestId: pendingDeliveryRequest,- });- }- return "cancelled";- }- if (read.next.done) throw new Error("Turn inbox closed before runtime actions completed.");-- if (read.channel === "workflow") {- const result = await handleWorkflowToolRunMessage({- callbackMetadataUrl: getWorkflowMetadata().url,- cursor: input.cursor,- message: read.next.value,- });- if (result !== undefined) {- results.push(result);- acceptedAtMsByCallId.set(result.callId, Date.now());- }- continue;- }-- const value = read.next.value;- if (value.kind === "runtime-action-result") {- // The inbox token is shared by every callee in the batch, so an inbox- // result must bind to the adopted session snapshot: a subagent result- // to a running agent handle carrying its callId, a tool result to the- // workflow tool run recorded for its callId. Anything else — a callee settling a- // sibling's call, or a result for a callId whose dispatch failed — is- // dropped; the genuine result (or the dispatch error already in- // `results`) still resolves the wait.- const sessionSnapshotState = input.cursor.sessionState.snapshot?.session.state;- const accepted = value.results.filter((result) =>- result.kind === "tool-result"- ? isInboxToolResultFromRecordedWorkflowToolRun(sessionSnapshotState, result)- : (result.origin === "child" &&- isInboxSubagentResultFromRunningHandle(sessionSnapshotState, result)) ||- isInboxSubagentResultFromRecordedWorkflowToolRun(sessionSnapshotState, result),- );- if (accepted.length > 0) {- const acceptedAtMs = Date.now();- results.push(...accepted);- for (const result of accepted) {- acceptedAtMsByCallId.set(result.callId, acceptedAtMs);- }- }- continue;- }-- if (value.kind === "subagent-input-request" || value.kind === "subagent-authorization-event") {- const handle = findRunningAgentHandle(input.cursor.sessionState.snapshot?.session.state, {- callId: value.callId,- });- if (- handle?.identity.name !== value.subagentName ||- handle.address.sessionId !== value.childSessionId- ) {- continue;- }- const proxyResult = await runProxySubagentEventStep({- hookPayload: value,- parentWritable: input.cursor.parentWritable,- serializedContext: input.cursor.serializedContext,- sessionState: input.cursor.sessionState,- });- await input.cursor.adopt(proxyResult);- continue;- }-- // Only `driver-delivery` reaches the inbox for public input: children- // resume it with results/HITL, and the driver relays public deliveries- // through the request handshake. A stale, non-matching request id means- // the turn already resolved and the driver re-buffered the delivery.- if (value.kind === "driver-delivery" && value.requestId === pendingDeliveryRequest) {- await input.cursor.send({ kind: "turn-delivery-accepted", requestId: value.requestId });- pendingDeliveryRequest = undefined;-- const routed = await routeDeliverToChildren({- delivery: value.delivery,- parentWritable: input.cursor.parentWritable,- serializedContext: input.cursor.serializedContext,- sessionState: input.cursor.sessionState,- });- await input.cursor.adopt({- serializedContext: routed.serializedContext ?? input.cursor.serializedContext,- sessionState: routed.sessionState ?? input.cursor.sessionState,- });- if (routed.kind === "cancel-turn") {- return routed.kind;- }- if (routed.remainder !== undefined) {- input.bufferedDeliveries.push(routed.remainder);- }- }- }-}--async function runLegacyTurnWorkflow(input: TurnWorkflowInput): Promise<void> {- let currentStepInput: TurnStepInput = input.stepInput;-- try {- while (true) {- const result = await turnStep(currentStepInput);-- if (result.action === "done") {- await sendTurnControlStep({- controlToken: input.completionToken,- payload: {- action: {- kind: "done",- output: result.output ?? "",- isError: result.isError,- serializedContext: result.serializedContext,- sessionState: result.sessionState,- usage: result.usage,- usageDelta: result.usageDelta,- },- kind: "turn-result",- },- });- return;- }-- if (result.action === "park") {- const pendingCallIds = result.pendingCoordinationCallIds;- const canPark =- pendingCallIds !== undefined ||- result.hasPendingAuthorization ||- (result.hasPendingInputBatch && input.capabilities?.requestInput === true) ||- input.mode === "conversation";-- if (!canPark) throw new Error(TASK_MODE_WAIT_ERROR_MESSAGE);-- const action: NextDriverAction =- pendingCallIds !== undefined- ? {- kind: "dispatch-coordination",- pendingCallIds,- serializedContext: result.serializedContext,- sessionState: result.sessionState,- }- : {- kind: "park",- serializedContext: result.serializedContext,- sessionState: result.sessionState,- authorizationAttemptIds: result.authorizationAttemptIds,- authorizationNames: result.authorizationNames,- settled: result.settled,- };-- await sendTurnControlStep({- controlToken: input.completionToken,- payload: { action, kind: "turn-result" },- });- return;- }-- currentStepInput = {- input: undefined,- parentWritable: currentStepInput.parentWritable,- serializedContext: result.serializedContext,- sessionState: result.sessionState,- };- }- } catch (error) {- await sendTurnControlStep({- controlToken: input.completionToken,- payload: { error: normalizeSerializableError(error), kind: "turn-error" },- });- throw error;- }-}diff --git a/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v1.test.ts.snap b/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v1.test.ts.snapdeleted file mode 100644index a21ccccaa..000000000--- a/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v1.test.ts.snap+++ /dev/null@@ -1,3 +0,0 @@-// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html--exports[`session inbox wire v1 > pins the complete schema byte for byte 1`] = `"{"$schema":"https://json-schema.org/draft/2020-12/schema","oneOf":[{"additionalProperties":false,"properties":{"auth":{"anyOf":[{"additionalProperties":false,"properties":{"attributes":{"additionalProperties":{"anyOf":[{"type":"string"},{"items":{"type":"string"},"type":"array"}]},"propertyNames":{"type":"string"},"type":"object"},"authenticator":{"type":"string"},"issuer":{"type":"string"},"principalId":{"type":"string"},"principalType":{"type":"string"},"subject":{"type":"string"}},"required":["attributes","authenticator","principalId","principalType"],"type":"object"},{"type":"null"}]},"caller":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"replyTo":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"hook","type":"string"},"token":{"type":"string"}},"required":["kind","token"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"callback","type":"string"},"token":{"type":"string"},"url":{"type":"string"}},"required":["kind","token","url"],"type":"object"}]},"subagentName":{"type":"string"},"taskId":{"type":"string"}},"required":["callId","replyTo","subagentName"],"type":"object"},"deliveryMetadata":{"items":{"additionalProperties":false,"properties":{"channelKind":{"type":"string"},"channelName":{"type":"string"},"deliveryId":{"type":"string"},"payloadIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"requestId":{"type":"string"},"requestTraceContext":{"additionalProperties":false,"properties":{"spanId":{"type":"string"},"traceFlags":{"type":"number"},"traceId":{"type":"string"}},"required":["spanId","traceFlags","traceId"],"type":"object"}},"required":["channelKind","channelName","deliveryId","payloadIndex"],"type":"object"},"type":"array"},"kind":{"const":"deliver","type":"string"},"payload":{"additionalProperties":{},"properties":{"context":{"items":{"type":"string"},"type":"array"},"inputResponses":{"items":{"additionalProperties":false,"properties":{"optionId":{"type":"string"},"requestId":{"type":"string"},"text":{"type":"string"}},"required":["requestId"],"type":"object"},"type":"array"},"message":{"anyOf":[{"type":"string"},{"items":{"oneOf":[{"additionalProperties":false,"properties":{"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"text":{"type":"string"},"type":{"const":"text","type":"string"}},"required":["text","type"],"type":"object"},{"additionalProperties":false,"properties":{"image":{},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"image","type":"string"}},"required":["image","type"],"type":"object"},{"additionalProperties":false,"properties":{"data":{},"filename":{"type":"string"},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"file","type":"string"}},"required":["data","mediaType","type"],"type":"object"}]},"type":"array"}]},"outputSchema":{},"task":{"additionalProperties":false,"properties":{"authorizationEvents":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childSessionId":{"type":"string"},"event":{},"kind":{"const":"subagent-authorization-event","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"inputRequests":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childContinuationToken":{"type":"string"},"childSessionId":{"type":"string"},"event":{"additionalProperties":false,"properties":{"requests":{"items":{"additionalProperties":false,"properties":{"action":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"input":{},"kind":{"const":"tool-call","type":"string"},"toolName":{"type":"string"}},"required":["callId","input","kind","toolName"],"type":"object"},"allowFreeform":{"description":"Whether the user may answer with freeform text instead of selecting one of the provided options.","type":"boolean"},"display":{"description":"Rendering hint: the channel uses this to pick a UX treatment.","enum":["confirmation","select","text"],"type":"string"},"kind":{"description":"Framework-owned request source used to resolve, route, and render the response.","enum":["question","session-limit","tool-approval"],"type":"string"},"options":{"description":"Selectable answer options to present to the user.","items":{"additionalProperties":false,"properties":{"description":{"description":"Optional additional context for this option.","type":"string"},"id":{"description":"Stable identifier for the option.","type":"string"},"label":{"description":"User-facing label for the option.","type":"string"},"style":{"description":"Visual treatment hint for the option.","enum":["primary","danger","default"],"type":"string"}},"required":["id","label"],"type":"object"},"type":"array"},"prompt":{"description":"The prompt to present to the user.","type":"string"},"requestId":{"description":"Stable identifier for this request.","type":"string"}},"required":["action","kind","prompt","requestId"],"type":"object"},"type":"array"},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"turnId":{"type":"string"}},"required":["requests","sequence","stepIndex","turnId"],"type":"object"},"kind":{"const":"subagent-input-request","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childContinuationToken","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"views":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"working","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"inputRequests":{"items":{},"type":"array"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"input_required","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","inputRequests","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"result","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"completed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"error","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"failed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"cancelled","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"}]},"type":"array"}},"type":"object"}},"type":"object"},"payloads":{"items":{"additionalProperties":{},"properties":{"context":{"items":{"type":"string"},"type":"array"},"inputResponses":{"items":{"additionalProperties":false,"properties":{"optionId":{"type":"string"},"requestId":{"type":"string"},"text":{"type":"string"}},"required":["requestId"],"type":"object"},"type":"array"},"message":{"anyOf":[{"type":"string"},{"items":{"oneOf":[{"additionalProperties":false,"properties":{"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"text":{"type":"string"},"type":{"const":"text","type":"string"}},"required":["text","type"],"type":"object"},{"additionalProperties":false,"properties":{"image":{},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"image","type":"string"}},"required":["image","type"],"type":"object"},{"additionalProperties":false,"properties":{"data":{},"filename":{"type":"string"},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"file","type":"string"}},"required":["data","mediaType","type"],"type":"object"}]},"type":"array"}]},"outputSchema":{},"task":{"additionalProperties":false,"properties":{"authorizationEvents":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childSessionId":{"type":"string"},"event":{},"kind":{"const":"subagent-authorization-event","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"inputRequests":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childContinuationToken":{"type":"string"},"childSessionId":{"type":"string"},"event":{"additionalProperties":false,"properties":{"requests":{"items":{"additionalProperties":false,"properties":{"action":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"input":{},"kind":{"const":"tool-call","type":"string"},"toolName":{"type":"string"}},"required":["callId","input","kind","toolName"],"type":"object"},"allowFreeform":{"description":"Whether the user may answer with freeform text instead of selecting one of the provided options.","type":"boolean"},"display":{"description":"Rendering hint: the channel uses this to pick a UX treatment.","enum":["confirmation","select","text"],"type":"string"},"kind":{"description":"Framework-owned request source used to resolve, route, and render the response.","enum":["question","session-limit","tool-approval"],"type":"string"},"options":{"description":"Selectable answer options to present to the user.","items":{"additionalProperties":false,"properties":{"description":{"description":"Optional additional context for this option.","type":"string"},"id":{"description":"Stable identifier for the option.","type":"string"},"label":{"description":"User-facing label for the option.","type":"string"},"style":{"description":"Visual treatment hint for the option.","enum":["primary","danger","default"],"type":"string"}},"required":["id","label"],"type":"object"},"type":"array"},"prompt":{"description":"The prompt to present to the user.","type":"string"},"requestId":{"description":"Stable identifier for this request.","type":"string"}},"required":["action","kind","prompt","requestId"],"type":"object"},"type":"array"},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"turnId":{"type":"string"}},"required":["requests","sequence","stepIndex","turnId"],"type":"object"},"kind":{"const":"subagent-input-request","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childContinuationToken","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"views":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"working","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"inputRequests":{"items":{},"type":"array"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"input_required","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","inputRequests","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"result","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"completed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"error","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"failed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"cancelled","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"}]},"type":"array"}},"type":"object"}},"type":"object"},"type":"array"},"requestId":{"type":"string"},"taskDeliveryId":{"type":"string"},"turnPolicy":{"enum":["queue","steer"],"type":"string"},"version":{"const":1,"type":"number"}},"required":["kind","payloads","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"session-timeout","type":"string"},"version":{"const":1,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"clear","type":"string"},"version":{"const":1,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"compact","type":"string"},"version":{"const":1,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"reset","type":"string"},"reason":{"type":"string"},"version":{"const":1,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"cancel","type":"string"},"taskId":{"type":"string"},"turnId":{"type":"string"},"version":{"const":1,"type":"number"}},"required":["kind","version"],"type":"object"}]}"`;diff --git a/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v2.test.ts.snap b/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v2.test.ts.snapdeleted file mode 100644index e53761386..000000000--- a/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v2.test.ts.snap+++ /dev/null@@ -1,3 +0,0 @@-// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html--exports[`session inbox wire v2 > pins the complete schema byte for byte 1`] = `"{"$schema":"https://json-schema.org/draft/2020-12/schema","oneOf":[{"additionalProperties":false,"properties":{"auth":{"anyOf":[{"additionalProperties":false,"properties":{"attributes":{"additionalProperties":{"anyOf":[{"type":"string"},{"items":{"type":"string"},"type":"array"}]},"propertyNames":{"type":"string"},"type":"object"},"authenticator":{"type":"string"},"issuer":{"type":"string"},"principalId":{"type":"string"},"principalType":{"type":"string"},"subject":{"type":"string"}},"required":["attributes","authenticator","principalId","principalType"],"type":"object"},{"type":"null"}]},"caller":{"additionalProperties":false,"properties":{"activityObserver":{"additionalProperties":false,"properties":{"sink":{"additionalProperties":false,"properties":{"url":{"type":"string"},"version":{"const":1,"type":"number"}},"required":["url","version"],"type":"object"},"workIdentity":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"id":{"type":"string"},"kind":{"enum":["root-turn","subagent","remote-agent","task"],"type":"string"},"name":{"type":"string"},"parentId":{"type":"string"},"rootSessionId":{"type":"string"},"rootTurnId":{"type":"string"},"sessionId":{"type":"string"},"turnId":{"type":"string"}},"required":["id","kind","rootSessionId","rootTurnId"],"type":"object"}},"required":["sink"],"type":"object"},"callId":{"type":"string"},"replyTo":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"hook","type":"string"},"token":{"type":"string"}},"required":["kind","token"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"callback","type":"string"},"token":{"type":"string"},"url":{"type":"string"}},"required":["kind","token","url"],"type":"object"}]},"subagentName":{"type":"string"},"taskId":{"type":"string"}},"required":["callId","replyTo","subagentName"],"type":"object"},"deliveryMetadata":{"items":{"additionalProperties":false,"properties":{"channelKind":{"type":"string"},"channelName":{"type":"string"},"deliveryId":{"type":"string"},"payloadIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"requestId":{"type":"string"},"requestTraceContext":{"additionalProperties":false,"properties":{"spanId":{"type":"string"},"traceFlags":{"type":"number"},"traceId":{"type":"string"}},"required":["spanId","traceFlags","traceId"],"type":"object"}},"required":["channelKind","channelName","deliveryId","payloadIndex"],"type":"object"},"type":"array"},"kind":{"const":"deliver","type":"string"},"payload":{"additionalProperties":{},"properties":{"context":{"items":{"type":"string"},"type":"array"},"inputResponses":{"items":{"additionalProperties":false,"properties":{"optionId":{"type":"string"},"requestId":{"type":"string"},"text":{"type":"string"}},"required":["requestId"],"type":"object"},"type":"array"},"message":{"anyOf":[{"type":"string"},{"items":{"oneOf":[{"additionalProperties":false,"properties":{"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"text":{"type":"string"},"type":{"const":"text","type":"string"}},"required":["text","type"],"type":"object"},{"additionalProperties":false,"properties":{"image":{},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"image","type":"string"}},"required":["image","type"],"type":"object"},{"additionalProperties":false,"properties":{"data":{},"filename":{"type":"string"},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"file","type":"string"}},"required":["data","mediaType","type"],"type":"object"}]},"type":"array"}]},"outputSchema":{},"task":{"additionalProperties":false,"properties":{"authorizationEvents":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childSessionId":{"type":"string"},"event":{},"kind":{"const":"subagent-authorization-event","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"inputRequests":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childContinuationToken":{"type":"string"},"childSessionId":{"type":"string"},"event":{"additionalProperties":false,"properties":{"requests":{"items":{"additionalProperties":false,"properties":{"action":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"input":{},"kind":{"const":"tool-call","type":"string"},"toolName":{"type":"string"}},"required":["callId","input","kind","toolName"],"type":"object"},"allowFreeform":{"description":"Whether the user may answer with freeform text instead of selecting one of the provided options.","type":"boolean"},"display":{"description":"Rendering hint: the channel uses this to pick a UX treatment.","enum":["confirmation","select","text"],"type":"string"},"kind":{"description":"Framework-owned request source used to resolve, route, and render the response.","enum":["question","session-limit","tool-approval"],"type":"string"},"options":{"description":"Selectable answer options to present to the user.","items":{"additionalProperties":false,"properties":{"description":{"description":"Optional additional context for this option.","type":"string"},"id":{"description":"Stable identifier for the option.","type":"string"},"label":{"description":"User-facing label for the option.","type":"string"},"style":{"description":"Visual treatment hint for the option.","enum":["primary","danger","default"],"type":"string"}},"required":["id","label"],"type":"object"},"type":"array"},"prompt":{"description":"The prompt to present to the user.","type":"string"},"requestId":{"description":"Stable identifier for this request.","type":"string"}},"required":["action","kind","prompt","requestId"],"type":"object"},"type":"array"},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"turnId":{"type":"string"}},"required":["requests","sequence","stepIndex","turnId"],"type":"object"},"kind":{"const":"subagent-input-request","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childContinuationToken","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"views":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"working","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"inputRequests":{"items":{},"type":"array"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"input_required","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","inputRequests","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"result","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"completed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"error","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"failed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"cancelled","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"}]},"type":"array"}},"type":"object"}},"type":"object"},"payloads":{"items":{"additionalProperties":{},"properties":{"context":{"items":{"type":"string"},"type":"array"},"inputResponses":{"items":{"additionalProperties":false,"properties":{"optionId":{"type":"string"},"requestId":{"type":"string"},"text":{"type":"string"}},"required":["requestId"],"type":"object"},"type":"array"},"message":{"anyOf":[{"type":"string"},{"items":{"oneOf":[{"additionalProperties":false,"properties":{"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"text":{"type":"string"},"type":{"const":"text","type":"string"}},"required":["text","type"],"type":"object"},{"additionalProperties":false,"properties":{"image":{},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"image","type":"string"}},"required":["image","type"],"type":"object"},{"additionalProperties":false,"properties":{"data":{},"filename":{"type":"string"},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"file","type":"string"}},"required":["data","mediaType","type"],"type":"object"}]},"type":"array"}]},"outputSchema":{},"task":{"additionalProperties":false,"properties":{"authorizationEvents":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childSessionId":{"type":"string"},"event":{},"kind":{"const":"subagent-authorization-event","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"inputRequests":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childContinuationToken":{"type":"string"},"childSessionId":{"type":"string"},"event":{"additionalProperties":false,"properties":{"requests":{"items":{"additionalProperties":false,"properties":{"action":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"input":{},"kind":{"const":"tool-call","type":"string"},"toolName":{"type":"string"}},"required":["callId","input","kind","toolName"],"type":"object"},"allowFreeform":{"description":"Whether the user may answer with freeform text instead of selecting one of the provided options.","type":"boolean"},"display":{"description":"Rendering hint: the channel uses this to pick a UX treatment.","enum":["confirmation","select","text"],"type":"string"},"kind":{"description":"Framework-owned request source used to resolve, route, and render the response.","enum":["question","session-limit","tool-approval"],"type":"string"},"options":{"description":"Selectable answer options to present to the user.","items":{"additionalProperties":false,"properties":{"description":{"description":"Optional additional context for this option.","type":"string"},"id":{"description":"Stable identifier for the option.","type":"string"},"label":{"description":"User-facing label for the option.","type":"string"},"style":{"description":"Visual treatment hint for the option.","enum":["primary","danger","default"],"type":"string"}},"required":["id","label"],"type":"object"},"type":"array"},"prompt":{"description":"The prompt to present to the user.","type":"string"},"requestId":{"description":"Stable identifier for this request.","type":"string"}},"required":["action","kind","prompt","requestId"],"type":"object"},"type":"array"},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"turnId":{"type":"string"}},"required":["requests","sequence","stepIndex","turnId"],"type":"object"},"kind":{"const":"subagent-input-request","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childContinuationToken","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"views":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"working","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"inputRequests":{"items":{},"type":"array"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"input_required","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","inputRequests","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"result","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"completed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"error","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"failed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"cancelled","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"}]},"type":"array"}},"type":"object"}},"type":"object"},"type":"array"},"requestId":{"type":"string"},"taskDeliveryId":{"type":"string"},"turnPolicy":{"enum":["queue","steer"],"type":"string"},"version":{"const":2,"type":"number"}},"required":["kind","payload","payloads","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"session-timeout","type":"string"},"version":{"const":2,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"clear","type":"string"},"version":{"const":2,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"compact","type":"string"},"version":{"const":2,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"reset","type":"string"},"reason":{"type":"string"},"version":{"const":2,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"cancel","type":"string"},"taskId":{"type":"string"},"turnId":{"type":"string"},"version":{"const":2,"type":"number"}},"required":["kind","version"],"type":"object"}]}"`;diff --git a/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v3.test.ts.snap b/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v3.test.ts.snapdeleted file mode 100644index 31a68197b..000000000--- a/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v3.test.ts.snap+++ /dev/null@@ -1,3 +0,0 @@-// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html--exports[`session inbox wire v3 > pins the complete schema byte for byte 1`] = `"{"$schema":"https://json-schema.org/draft/2020-12/schema","oneOf":[{"additionalProperties":false,"properties":{"auth":{"anyOf":[{"additionalProperties":false,"properties":{"attributes":{"additionalProperties":{"anyOf":[{"type":"string"},{"items":{"type":"string"},"type":"array"}]},"propertyNames":{"type":"string"},"type":"object"},"authenticator":{"type":"string"},"issuer":{"type":"string"},"principalId":{"type":"string"},"principalType":{"type":"string"},"subject":{"type":"string"}},"required":["attributes","authenticator","principalId","principalType"],"type":"object"},{"type":"null"}]},"caller":{"additionalProperties":false,"properties":{"activityObserver":{"additionalProperties":false,"properties":{"sink":{"additionalProperties":false,"properties":{"url":{"type":"string"},"version":{"const":1,"type":"number"}},"required":["url","version"],"type":"object"},"workIdentity":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"id":{"type":"string"},"kind":{"enum":["root-turn","subagent","remote-agent","task"],"type":"string"},"name":{"type":"string"},"parentId":{"type":"string"},"rootSessionId":{"type":"string"},"rootTurnId":{"type":"string"},"sessionId":{"type":"string"},"turnId":{"type":"string"}},"required":["id","kind","rootSessionId","rootTurnId"],"type":"object"}},"required":["sink"],"type":"object"},"callId":{"type":"string"},"replyTo":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"hook","type":"string"},"token":{"type":"string"}},"required":["kind","token"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"callback","type":"string"},"token":{"type":"string"},"url":{"type":"string"}},"required":["kind","token","url"],"type":"object"}]},"subagentName":{"type":"string"},"taskId":{"type":"string"}},"required":["callId","replyTo","subagentName"],"type":"object"},"deliveryMetadata":{"items":{"additionalProperties":false,"properties":{"acceptedDeploymentId":{"type":"string"},"channelKind":{"type":"string"},"channelName":{"type":"string"},"deliveryId":{"type":"string"},"payloadIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"requestId":{"type":"string"},"requestTraceContext":{"additionalProperties":false,"properties":{"spanId":{"type":"string"},"traceFlags":{"type":"number"},"traceId":{"type":"string"}},"required":["spanId","traceFlags","traceId"],"type":"object"}},"required":["channelKind","channelName","deliveryId","payloadIndex"],"type":"object"},"type":"array"},"kind":{"const":"deliver","type":"string"},"payload":{"additionalProperties":{},"properties":{"context":{"items":{"type":"string"},"type":"array"},"inputResponses":{"items":{"additionalProperties":false,"properties":{"optionId":{"type":"string"},"requestId":{"type":"string"},"text":{"type":"string"}},"required":["requestId"],"type":"object"},"type":"array"},"message":{"anyOf":[{"type":"string"},{"items":{"oneOf":[{"additionalProperties":false,"properties":{"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"text":{"type":"string"},"type":{"const":"text","type":"string"}},"required":["text","type"],"type":"object"},{"additionalProperties":false,"properties":{"image":{},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"image","type":"string"}},"required":["image","type"],"type":"object"},{"additionalProperties":false,"properties":{"data":{},"filename":{"type":"string"},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"file","type":"string"}},"required":["data","mediaType","type"],"type":"object"}]},"type":"array"}]},"outputSchema":{},"task":{"additionalProperties":false,"properties":{"authorizationEvents":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childSessionId":{"type":"string"},"event":{},"kind":{"const":"subagent-authorization-event","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"inputRequests":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childContinuationToken":{"type":"string"},"childSessionId":{"type":"string"},"event":{"additionalProperties":false,"properties":{"requests":{"items":{"additionalProperties":false,"properties":{"action":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"input":{},"kind":{"const":"tool-call","type":"string"},"toolName":{"type":"string"}},"required":["callId","input","kind","toolName"],"type":"object"},"allowFreeform":{"description":"Whether the user may answer with freeform text instead of selecting one of the provided options.","type":"boolean"},"display":{"description":"Rendering hint: the channel uses this to pick a UX treatment.","enum":["confirmation","select","text"],"type":"string"},"kind":{"description":"Framework-owned request source used to resolve, route, and render the response.","enum":["question","session-limit","tool-approval"],"type":"string"},"options":{"description":"Selectable answer options to present to the user.","items":{"additionalProperties":false,"properties":{"description":{"description":"Optional additional context for this option.","type":"string"},"id":{"description":"Stable identifier for the option.","type":"string"},"label":{"description":"User-facing label for the option.","type":"string"},"style":{"description":"Visual treatment hint for the option.","enum":["primary","danger","default"],"type":"string"}},"required":["id","label"],"type":"object"},"type":"array"},"prompt":{"description":"The prompt to present to the user.","type":"string"},"requestId":{"description":"Stable identifier for this request.","type":"string"}},"required":["action","kind","prompt","requestId"],"type":"object"},"type":"array"},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"turnId":{"type":"string"}},"required":["requests","sequence","stepIndex","turnId"],"type":"object"},"kind":{"const":"subagent-input-request","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childContinuationToken","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"views":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"working","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"inputRequests":{"items":{},"type":"array"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"input_required","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","inputRequests","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"result","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"completed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"error","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"failed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"cancelled","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"}]},"type":"array"}},"type":"object"}},"type":"object"},"payloads":{"items":{"additionalProperties":{},"properties":{"context":{"items":{"type":"string"},"type":"array"},"inputResponses":{"items":{"additionalProperties":false,"properties":{"optionId":{"type":"string"},"requestId":{"type":"string"},"text":{"type":"string"}},"required":["requestId"],"type":"object"},"type":"array"},"message":{"anyOf":[{"type":"string"},{"items":{"oneOf":[{"additionalProperties":false,"properties":{"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"text":{"type":"string"},"type":{"const":"text","type":"string"}},"required":["text","type"],"type":"object"},{"additionalProperties":false,"properties":{"image":{},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"image","type":"string"}},"required":["image","type"],"type":"object"},{"additionalProperties":false,"properties":{"data":{},"filename":{"type":"string"},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"file","type":"string"}},"required":["data","mediaType","type"],"type":"object"}]},"type":"array"}]},"outputSchema":{},"task":{"additionalProperties":false,"properties":{"authorizationEvents":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childSessionId":{"type":"string"},"event":{},"kind":{"const":"subagent-authorization-event","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"inputRequests":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childContinuationToken":{"type":"string"},"childSessionId":{"type":"string"},"event":{"additionalProperties":false,"properties":{"requests":{"items":{"additionalProperties":false,"properties":{"action":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"input":{},"kind":{"const":"tool-call","type":"string"},"toolName":{"type":"string"}},"required":["callId","input","kind","toolName"],"type":"object"},"allowFreeform":{"description":"Whether the user may answer with freeform text instead of selecting one of the provided options.","type":"boolean"},"display":{"description":"Rendering hint: the channel uses this to pick a UX treatment.","enum":["confirmation","select","text"],"type":"string"},"kind":{"description":"Framework-owned request source used to resolve, route, and render the response.","enum":["question","session-limit","tool-approval"],"type":"string"},"options":{"description":"Selectable answer options to present to the user.","items":{"additionalProperties":false,"properties":{"description":{"description":"Optional additional context for this option.","type":"string"},"id":{"description":"Stable identifier for the option.","type":"string"},"label":{"description":"User-facing label for the option.","type":"string"},"style":{"description":"Visual treatment hint for the option.","enum":["primary","danger","default"],"type":"string"}},"required":["id","label"],"type":"object"},"type":"array"},"prompt":{"description":"The prompt to present to the user.","type":"string"},"requestId":{"description":"Stable identifier for this request.","type":"string"}},"required":["action","kind","prompt","requestId"],"type":"object"},"type":"array"},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"turnId":{"type":"string"}},"required":["requests","sequence","stepIndex","turnId"],"type":"object"},"kind":{"const":"subagent-input-request","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childContinuationToken","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"views":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"working","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"inputRequests":{"items":{},"type":"array"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"input_required","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","inputRequests","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"result","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"completed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"error","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"failed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"cancelled","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"}]},"type":"array"}},"type":"object"}},"type":"object"},"type":"array"},"requestId":{"type":"string"},"taskDeliveryId":{"type":"string"},"turnPolicy":{"enum":["queue","steer"],"type":"string"},"version":{"const":3,"type":"number"}},"required":["kind","payload","payloads","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"session-timeout","type":"string"},"version":{"const":3,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"clear","type":"string"},"version":{"const":3,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"compact","type":"string"},"version":{"const":3,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"reset","type":"string"},"reason":{"type":"string"},"version":{"const":3,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"cancel","type":"string"},"taskId":{"type":"string"},"turnId":{"type":"string"},"version":{"const":3,"type":"number"}},"required":["kind","version"],"type":"object"}]}"`;diff --git a/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v4.test.ts.snap b/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v4.test.ts.snapdeleted file mode 100644index 577ab11cb..000000000--- a/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v4.test.ts.snap+++ /dev/null@@ -1,3 +0,0 @@-// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html--exports[`session inbox wire v4 > pins the complete schema byte for byte 1`] = `"{"$defs":{"__schema0":{"anyOf":[{"type":"null"},{"type":"boolean"},{"type":"number"},{"type":"string"},{"items":{"$ref":"#/$defs/__schema0"},"type":"array"},{"additionalProperties":{"$ref":"#/$defs/__schema0"},"propertyNames":{"type":"string"},"type":"object"}]}},"$schema":"https://json-schema.org/draft/2020-12/schema","oneOf":[{"additionalProperties":false,"properties":{"auth":{"anyOf":[{"additionalProperties":false,"properties":{"attributes":{"additionalProperties":{"anyOf":[{"type":"string"},{"items":{"type":"string"},"type":"array"}]},"propertyNames":{"type":"string"},"type":"object"},"authenticator":{"type":"string"},"issuer":{"type":"string"},"principalId":{"type":"string"},"principalType":{"type":"string"},"subject":{"type":"string"}},"required":["attributes","authenticator","principalId","principalType"],"type":"object"},{"type":"null"}]},"caller":{"additionalProperties":false,"properties":{"activityObserver":{"additionalProperties":false,"properties":{"sink":{"additionalProperties":false,"properties":{"url":{"type":"string"},"version":{"const":1,"type":"number"}},"required":["url","version"],"type":"object"},"workIdentity":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"id":{"type":"string"},"kind":{"enum":["root-turn","subagent","remote-agent","task"],"type":"string"},"name":{"type":"string"},"parentId":{"type":"string"},"rootSessionId":{"type":"string"},"rootTurnId":{"type":"string"},"sessionId":{"type":"string"},"turnId":{"type":"string"}},"required":["id","kind","rootSessionId","rootTurnId"],"type":"object"}},"required":["sink"],"type":"object"},"callId":{"type":"string"},"replyTo":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"hook","type":"string"},"token":{"type":"string"}},"required":["kind","token"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"callback","type":"string"},"token":{"type":"string"},"url":{"type":"string"}},"required":["kind","token","url"],"type":"object"}]},"subagentName":{"type":"string"},"taskId":{"type":"string"}},"required":["callId","replyTo","subagentName"],"type":"object"},"deliveryMetadata":{"items":{"additionalProperties":false,"properties":{"acceptedDeploymentId":{"type":"string"},"channelKind":{"type":"string"},"channelName":{"type":"string"},"deliveryId":{"type":"string"},"payloadIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"requestId":{"type":"string"},"requestTraceContext":{"additionalProperties":false,"properties":{"spanId":{"type":"string"},"traceFlags":{"type":"number"},"traceId":{"type":"string"}},"required":["spanId","traceFlags","traceId"],"type":"object"}},"required":["channelKind","channelName","deliveryId","payloadIndex"],"type":"object"},"type":"array"},"kind":{"const":"deliver","type":"string"},"payload":{"additionalProperties":{},"properties":{"context":{"items":{"type":"string"},"type":"array"},"inputResponses":{"items":{"additionalProperties":false,"properties":{"optionId":{"type":"string"},"requestId":{"type":"string"},"text":{"type":"string"}},"required":["requestId"],"type":"object"},"type":"array"},"message":{"anyOf":[{"type":"string"},{"items":{"oneOf":[{"additionalProperties":false,"properties":{"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"text":{"type":"string"},"type":{"const":"text","type":"string"}},"required":["text","type"],"type":"object"},{"additionalProperties":false,"properties":{"image":{},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"image","type":"string"}},"required":["image","type"],"type":"object"},{"additionalProperties":false,"properties":{"data":{},"filename":{"type":"string"},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"file","type":"string"}},"required":["data","mediaType","type"],"type":"object"}]},"type":"array"}]},"outputSchema":{},"task":{"additionalProperties":false,"properties":{"agentRequests":{"items":{"additionalProperties":false,"properties":{"replyTo":{"type":"string"},"request":{"oneOf":[{"additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"message":{"type":"string"},"outputSchema":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"target":{"type":"string"}},"required":["message","target"],"type":"object"},"invocationId":{"type":"string"},"kind":{"const":"agent-invoke","type":"string"}},"required":["input","invocationId","kind"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"agent-settled","type":"string"},"result":{"additionalProperties":false,"properties":{"backgroundTask":{"additionalProperties":false,"properties":{"status":{"const":"working","type":"string"},"taskId":{"type":"string"}},"required":["status","taskId"],"type":"object"},"callId":{"type":"string"},"isError":{"type":"boolean"},"kind":{"const":"subagent-result","type":"string"},"origin":{"const":"child","type":"string"},"outcome":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"parked","type":"string"},"result":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"succeeded","type":"string"},"output":{"$ref":"#/$defs/__schema0"}},"required":["kind","output"],"type":"object"},{"additionalProperties":false,"properties":{"error":{"$ref":"#/$defs/__schema0"},"kind":{"const":"failed","type":"string"}},"required":["error","kind"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"cancelled","type":"string"}},"required":["kind"],"type":"object"}]},"usageDelta":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["kind","result","usageDelta"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"terminal","type":"string"},"result":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"succeeded","type":"string"},"output":{"$ref":"#/$defs/__schema0"}},"required":["kind","output"],"type":"object"},{"additionalProperties":false,"properties":{"error":{"$ref":"#/$defs/__schema0"},"kind":{"const":"failed","type":"string"}},"required":["error","kind"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"cancelled","type":"string"}},"required":["kind"],"type":"object"}]},"usageDelta":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["kind","result","usageDelta"],"type":"object"}]},"output":{},"subagentName":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["callId","kind","origin","outcome","output","subagentName"],"type":"object"}},"required":["kind","result"],"type":"object"}]},"taskId":{"type":"string"}},"required":["replyTo","request","taskId"],"type":"object"},"type":"array"},"authorizationEvents":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childSessionId":{"type":"string"},"event":{},"kind":{"const":"subagent-authorization-event","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"inputRequests":{"items":{"anyOf":[{"additionalProperties":{},"properties":{"replyTo":{"type":"string"},"request":{},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"taskId":{"type":"string"},"turnId":{"type":"string"}},"required":["replyTo","sequence","stepIndex","taskId","turnId","request"],"type":"object"},{"additionalProperties":{},"properties":{"replyTo":{"type":"string"},"requests":{"items":{},"type":"array"},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"taskId":{"type":"string"},"turnId":{"type":"string"}},"required":["replyTo","sequence","stepIndex","taskId","turnId","requests"],"type":"object"}]},"type":"array"},"views":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"working","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"inputRequests":{"items":{},"type":"array"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"input_required","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","inputRequests","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"result","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"completed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"error","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"failed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"cancelled","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"}]},"type":"array"}},"type":"object"}},"type":"object"},"payloads":{"items":{"additionalProperties":{},"properties":{"context":{"items":{"type":"string"},"type":"array"},"inputResponses":{"items":{"additionalProperties":false,"properties":{"optionId":{"type":"string"},"requestId":{"type":"string"},"text":{"type":"string"}},"required":["requestId"],"type":"object"},"type":"array"},"message":{"anyOf":[{"type":"string"},{"items":{"oneOf":[{"additionalProperties":false,"properties":{"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"text":{"type":"string"},"type":{"const":"text","type":"string"}},"required":["text","type"],"type":"object"},{"additionalProperties":false,"properties":{"image":{},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"image","type":"string"}},"required":["image","type"],"type":"object"},{"additionalProperties":false,"properties":{"data":{},"filename":{"type":"string"},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"file","type":"string"}},"required":["data","mediaType","type"],"type":"object"}]},"type":"array"}]},"outputSchema":{},"task":{"additionalProperties":false,"properties":{"agentRequests":{"items":{"additionalProperties":false,"properties":{"replyTo":{"type":"string"},"request":{"oneOf":[{"additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"message":{"type":"string"},"outputSchema":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"target":{"type":"string"}},"required":["message","target"],"type":"object"},"invocationId":{"type":"string"},"kind":{"const":"agent-invoke","type":"string"}},"required":["input","invocationId","kind"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"agent-settled","type":"string"},"result":{"additionalProperties":false,"properties":{"backgroundTask":{"additionalProperties":false,"properties":{"status":{"const":"working","type":"string"},"taskId":{"type":"string"}},"required":["status","taskId"],"type":"object"},"callId":{"type":"string"},"isError":{"type":"boolean"},"kind":{"const":"subagent-result","type":"string"},"origin":{"const":"child","type":"string"},"outcome":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"parked","type":"string"},"result":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"succeeded","type":"string"},"output":{"$ref":"#/$defs/__schema0"}},"required":["kind","output"],"type":"object"},{"additionalProperties":false,"properties":{"error":{"$ref":"#/$defs/__schema0"},"kind":{"const":"failed","type":"string"}},"required":["error","kind"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"cancelled","type":"string"}},"required":["kind"],"type":"object"}]},"usageDelta":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["kind","result","usageDelta"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"terminal","type":"string"},"result":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"succeeded","type":"string"},"output":{"$ref":"#/$defs/__schema0"}},"required":["kind","output"],"type":"object"},{"additionalProperties":false,"properties":{"error":{"$ref":"#/$defs/__schema0"},"kind":{"const":"failed","type":"string"}},"required":["error","kind"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"cancelled","type":"string"}},"required":["kind"],"type":"object"}]},"usageDelta":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["kind","result","usageDelta"],"type":"object"}]},"output":{},"subagentName":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["callId","kind","origin","outcome","output","subagentName"],"type":"object"}},"required":["kind","result"],"type":"object"}]},"taskId":{"type":"string"}},"required":["replyTo","request","taskId"],"type":"object"},"type":"array"},"authorizationEvents":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childSessionId":{"type":"string"},"event":{},"kind":{"const":"subagent-authorization-event","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"inputRequests":{"items":{"anyOf":[{"additionalProperties":{},"properties":{"replyTo":{"type":"string"},"request":{},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"taskId":{"type":"string"},"turnId":{"type":"string"}},"required":["replyTo","sequence","stepIndex","taskId","turnId","request"],"type":"object"},{"additionalProperties":{},"properties":{"replyTo":{"type":"string"},"requests":{"items":{},"type":"array"},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"taskId":{"type":"string"},"turnId":{"type":"string"}},"required":["replyTo","sequence","stepIndex","taskId","turnId","requests"],"type":"object"}]},"type":"array"},"views":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"working","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"inputRequests":{"items":{},"type":"array"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"input_required","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","inputRequests","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"result","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"completed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"error","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"failed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"cancelled","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"}]},"type":"array"}},"type":"object"}},"type":"object"},"type":"array"},"requestId":{"type":"string"},"taskDeliveryId":{"type":"string"},"turnPolicy":{"enum":["queue","steer"],"type":"string"},"version":{"const":4,"type":"number"}},"required":["kind","payload","payloads","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"session-timeout","type":"string"},"version":{"const":4,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"clear","type":"string"},"version":{"const":4,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"compact","type":"string"},"version":{"const":4,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"reset","type":"string"},"reason":{"type":"string"},"version":{"const":4,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"cancel","type":"string"},"taskId":{"type":"string"},"turnId":{"type":"string"},"version":{"const":4,"type":"number"}},"required":["kind","version"],"type":"object"}]}"`;diff --git a/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v5.test.ts.snap b/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v5.test.ts.snapdeleted file mode 100644index 15932d3d5..000000000--- a/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v5.test.ts.snap+++ /dev/null@@ -1,3 +0,0 @@-// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html--exports[`session inbox wire v5 > pins the complete schema byte for byte 1`] = `"{"$schema":"https://json-schema.org/draft/2020-12/schema","oneOf":[{"additionalProperties":false,"properties":{"auth":{"anyOf":[{"additionalProperties":false,"properties":{"attributes":{"additionalProperties":{"anyOf":[{"type":"string"},{"items":{"type":"string"},"type":"array"}]},"propertyNames":{"type":"string"},"type":"object"},"authenticator":{"type":"string"},"issuer":{"type":"string"},"principalId":{"type":"string"},"principalType":{"type":"string"},"subject":{"type":"string"}},"required":["attributes","authenticator","principalId","principalType"],"type":"object"},{"type":"null"}]},"caller":{"additionalProperties":false,"properties":{"activityObserver":{"additionalProperties":false,"properties":{"sink":{"additionalProperties":false,"properties":{"url":{"type":"string"},"version":{"const":1,"type":"number"}},"required":["url","version"],"type":"object"},"workIdentity":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"id":{"type":"string"},"kind":{"enum":["root-turn","subagent","remote-agent","task"],"type":"string"},"name":{"type":"string"},"parentId":{"type":"string"},"rootSessionId":{"type":"string"},"rootTurnId":{"type":"string"},"sessionId":{"type":"string"},"turnId":{"type":"string"}},"required":["id","kind","rootSessionId","rootTurnId"],"type":"object"}},"required":["sink"],"type":"object"},"callId":{"type":"string"},"replyTo":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"hook","type":"string"},"token":{"type":"string"}},"required":["kind","token"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"callback","type":"string"},"token":{"type":"string"},"url":{"type":"string"}},"required":["kind","token","url"],"type":"object"}]},"subagentName":{"type":"string"},"taskId":{"type":"string"}},"required":["callId","replyTo","subagentName"],"type":"object"},"deliveryMetadata":{"items":{"additionalProperties":false,"properties":{"acceptedDeploymentId":{"type":"string"},"channelKind":{"type":"string"},"channelName":{"type":"string"},"deliveryId":{"type":"string"},"payloadIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"requestId":{"type":"string"},"requestTraceContext":{"additionalProperties":false,"properties":{"spanId":{"type":"string"},"traceFlags":{"type":"number"},"traceId":{"type":"string"}},"required":["spanId","traceFlags","traceId"],"type":"object"}},"required":["channelKind","channelName","deliveryId","payloadIndex"],"type":"object"},"type":"array"},"kind":{"const":"deliver","type":"string"},"payload":{"additionalProperties":{},"properties":{"context":{"items":{"type":"string"},"type":"array"},"inputResponses":{"items":{"additionalProperties":false,"properties":{"optionId":{"type":"string"},"requestId":{"type":"string"},"text":{"type":"string"}},"required":["requestId"],"type":"object"},"type":"array"},"message":{"anyOf":[{"type":"string"},{"items":{"oneOf":[{"additionalProperties":false,"properties":{"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"text":{"type":"string"},"type":{"const":"text","type":"string"}},"required":["text","type"],"type":"object"},{"additionalProperties":false,"properties":{"image":{},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"image","type":"string"}},"required":["image","type"],"type":"object"},{"additionalProperties":false,"properties":{"data":{},"filename":{"type":"string"},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"file","type":"string"}},"required":["data","mediaType","type"],"type":"object"}]},"type":"array"}]},"outputSchema":{},"task":{"additionalProperties":false,"properties":{"agentRequests":{"items":{"additionalProperties":false,"properties":{"replyTo":{"type":"string"},"request":{"oneOf":[{"additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"message":{"type":"string"},"outputSchema":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"target":{"type":"string"}},"required":["message","target"],"type":"object"},"invocationId":{"type":"string"},"kind":{"const":"agent-invoke","type":"string"}},"required":["input","invocationId","kind"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"agent-settled","type":"string"},"result":{"additionalProperties":false,"properties":{"backgroundTask":{"additionalProperties":false,"properties":{"status":{"const":"working","type":"string"},"taskId":{"type":"string"}},"required":["status","taskId"],"type":"object"},"callId":{"type":"string"},"isError":{"type":"boolean"},"kind":{"const":"subagent-result","type":"string"},"origin":{"const":"child","type":"string"},"outcome":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"parked","type":"string"},"result":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"succeeded","type":"string"},"output":{}},"required":["kind","output"],"type":"object"},{"additionalProperties":false,"properties":{"error":{},"kind":{"const":"failed","type":"string"}},"required":["error","kind"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"cancelled","type":"string"}},"required":["kind"],"type":"object"}]},"usageDelta":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"costUsd":{"minimum":0,"type":"number"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["kind","result","usageDelta"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"terminal","type":"string"},"result":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"succeeded","type":"string"},"output":{}},"required":["kind","output"],"type":"object"},{"additionalProperties":false,"properties":{"error":{},"kind":{"const":"failed","type":"string"}},"required":["error","kind"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"cancelled","type":"string"}},"required":["kind"],"type":"object"}]},"usageDelta":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"costUsd":{"minimum":0,"type":"number"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["kind","result","usageDelta"],"type":"object"}]},"output":{},"subagentName":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"costUsd":{"minimum":0,"type":"number"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["callId","kind","origin","outcome","output","subagentName"],"type":"object"}},"required":["kind","result"],"type":"object"}]},"taskId":{"type":"string"}},"required":["replyTo","request","taskId"],"type":"object"},"type":"array"},"authorizationEvents":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childSessionId":{"type":"string"},"event":{},"kind":{"const":"subagent-authorization-event","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"inputRequests":{"items":{"anyOf":[{"additionalProperties":{},"properties":{"replyTo":{"type":"string"},"request":{},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"taskId":{"type":"string"},"turnId":{"type":"string"}},"required":["replyTo","sequence","stepIndex","taskId","turnId","request"],"type":"object"},{"additionalProperties":{},"properties":{"replyTo":{"type":"string"},"requests":{"items":{},"type":"array"},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"taskId":{"type":"string"},"turnId":{"type":"string"}},"required":["replyTo","sequence","stepIndex","taskId","turnId","requests"],"type":"object"}]},"type":"array"},"views":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"working","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"costUsd":{"minimum":0,"type":"number"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"inputRequests":{"items":{},"type":"array"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"input_required","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"costUsd":{"minimum":0,"type":"number"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","inputRequests","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"result","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"completed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"costUsd":{"minimum":0,"type":"number"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"error","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"failed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"costUsd":{"minimum":0,"type":"number"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"cancelled","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"costUsd":{"minimum":0,"type":"number"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"}]},"type":"array"}},"type":"object"}},"type":"object"},"payloads":{"items":{"additionalProperties":{},"properties":{"context":{"items":{"type":"string"},"type":"array"},"inputResponses":{"items":{"additionalProperties":false,"properties":{"optionId":{"type":"string"},"requestId":{"type":"string"},"text":{"type":"string"}},"required":["requestId"],"type":"object"},"type":"array"},"message":{"anyOf":[{"type":"string"},{"items":{"oneOf":[{"additionalProperties":false,"properties":{"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"text":{"type":"string"},"type":{"const":"text","type":"string"}},"required":["text","type"],"type":"object"},{"additionalProperties":false,"properties":{"image":{},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"image","type":"string"}},"required":["image","type"],"type":"object"},{"additionalProperties":false,"properties":{"data":{},"filename":{"type":"string"},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"file","type":"string"}},"required":["data","mediaType","type"],"type":"object"}]},"type":"array"}]},"outputSchema":{},"task":{"additionalProperties":false,"properties":{"agentRequests":{"items":{"additionalProperties":false,"properties":{"replyTo":{"type":"string"},"request":{"oneOf":[{"additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"message":{"type":"string"},"outputSchema":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"target":{"type":"string"}},"required":["message","target"],"type":"object"},"invocationId":{"type":"string"},"kind":{"const":"agent-invoke","type":"string"}},"required":["input","invocationId","kind"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"agent-settled","type":"string"},"result":{"additionalProperties":false,"properties":{"backgroundTask":{"additionalProperties":false,"properties":{"status":{"const":"working","type":"string"},"taskId":{"type":"string"}},"required":["status","taskId"],"type":"object"},"callId":{"type":"string"},"isError":{"type":"boolean"},"kind":{"const":"subagent-result","type":"string"},"origin":{"const":"child","type":"string"},"outcome":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"parked","type":"string"},"result":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"succeeded","type":"string"},"output":{}},"required":["kind","output"],"type":"object"},{"additionalProperties":false,"properties":{"error":{},"kind":{"const":"failed","type":"string"}},"required":["error","kind"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"cancelled","type":"string"}},"required":["kind"],"type":"object"}]},"usageDelta":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"costUsd":{"minimum":0,"type":"number"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["kind","result","usageDelta"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"terminal","type":"string"},"result":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"succeeded","type":"string"},"output":{}},"required":["kind","output"],"type":"object"},{"additionalProperties":false,"properties":{"error":{},"kind":{"const":"failed","type":"string"}},"required":["error","kind"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"cancelled","type":"string"}},"required":["kind"],"type":"object"}]},"usageDelta":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"costUsd":{"minimum":0,"type":"number"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["kind","result","usageDelta"],"type":"object"}]},"output":{},"subagentName":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"costUsd":{"minimum":0,"type":"number"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["callId","kind","origin","outcome","output","subagentName"],"type":"object"}},"required":["kind","result"],"type":"object"}]},"taskId":{"type":"string"}},"required":["replyTo","request","taskId"],"type":"object"},"type":"array"},"authorizationEvents":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childSessionId":{"type":"string"},"event":{},"kind":{"const":"subagent-authorization-event","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"inputRequests":{"items":{"anyOf":[{"additionalProperties":{},"properties":{"replyTo":{"type":"string"},"request":{},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"taskId":{"type":"string"},"turnId":{"type":"string"}},"required":["replyTo","sequence","stepIndex","taskId","turnId","request"],"type":"object"},{"additionalProperties":{},"properties":{"replyTo":{"type":"string"},"requests":{"items":{},"type":"array"},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"taskId":{"type":"string"},"turnId":{"type":"string"}},"required":["replyTo","sequence","stepIndex","taskId","turnId","requests"],"type":"object"}]},"type":"array"},"views":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"working","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"costUsd":{"minimum":0,"type":"number"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"inputRequests":{"items":{},"type":"array"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"input_required","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"costUsd":{"minimum":0,"type":"number"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","inputRequests","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"result","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"completed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"costUsd":{"minimum":0,"type":"number"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"error","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"failed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"costUsd":{"minimum":0,"type":"number"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"cancelled","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"costUsd":{"minimum":0,"type":"number"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"}]},"type":"array"}},"type":"object"}},"type":"object"},"type":"array"},"requestId":{"type":"string"},"taskDeliveryId":{"type":"string"},"turnPolicy":{"enum":["queue","steer"],"type":"string"},"version":{"const":5,"type":"number"}},"required":["kind","payload","payloads","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"session-timeout","type":"string"},"version":{"const":5,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"clear","type":"string"},"version":{"const":5,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"compact","type":"string"},"version":{"const":5,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"reset","type":"string"},"reason":{"type":"string"},"version":{"const":5,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"cancel","type":"string"},"taskId":{"type":"string"},"turnId":{"type":"string"},"version":{"const":5,"type":"number"}},"required":["kind","version"],"type":"object"}]}"`;diff --git a/packages/eve/src/execution/wire/session-inbox-consumer-compatibility.test.ts b/packages/eve/src/execution/wire/session-inbox-consumer-compatibility.test.tsdeleted file mode 100644index 81ff0bb43..000000000--- a/packages/eve/src/execution/wire/session-inbox-consumer-compatibility.test.ts+++ /dev/null@@ -1,70 +0,0 @@-import { describe, expect, it } from "vitest";--import { sessionInboxWire } from "#execution/wire/session-inbox-encoder.js";--interface Eve0308TurnControlReceiver {- bufferedDeliveries: unknown[];- handleSessionCommand(command: unknown): Promise<unknown>;-}--interface Eve0308TurnControlReceiverConstructor {- readonly prototype: Eve0308TurnControlReceiver;-}--describe("session inbox consumer compatibility", () => {- it("loads the published eve 0.30.8 turn receiver and accepts its native send shape", async () => {- const receiver = await createEve0308TurnControlReceiver();-- await expect(- receiver.handleSessionCommand({ kind: "send", payload: { message: "follow-up" } }),- ).resolves.toBeUndefined();- expect(receiver.bufferedDeliveries).toEqual([expectedDelivery]);- });-- it("keeps current sends readable by the published eve 0.30.8 turn receiver", async () => {- const receiver = await createEve0308TurnControlReceiver();- const wire = sessionInboxWire.encode(- { kind: "send", payload: { message: "follow-up" } },- { variant: "send", version: 0 },- );-- await expect(receiver.handleSessionCommand(wire)).resolves.toBeUndefined();- expect(receiver.bufferedDeliveries).toEqual([expectedDelivery]);- });-- it("reproduces the failure when a v1 delivery is sent to the published eve 0.30.8 turn receiver", async () => {- const receiver = await createEve0308TurnControlReceiver();- const wire = sessionInboxWire.encode(- { kind: "send", payload: { message: "follow-up" } },- { version: 1 },- );-- await expect(receiver.handleSessionCommand(wire)).rejects.toThrow(- /Unsupported session command:.*deliver/,- );- expect(receiver.bufferedDeliveries).toEqual([]);- });-});--const expectedDelivery = {- auth: undefined,- caller: undefined,- kind: "deliver",- payloads: [{ message: "follow-up" }],- requestId: undefined,-};--async function createEve0308TurnControlReceiver(): Promise<Eve0308TurnControlReceiver> {- const packageEntry = import.meta.resolve("historical-eve-0-30-8");- const receiverModuleUrl = new URL("./execution/turn-control-receiver.js", packageEntry);- const receiverModule = (await import(receiverModuleUrl.href)) as {- readonly TurnControlReceiver: Eve0308TurnControlReceiverConstructor;- };- // The decoder is the compatibility boundary. Bypass construction so loading- // the published method does not also require a live 0.30.8 Workflow world.- const receiver = Object.create(- receiverModule.TurnControlReceiver.prototype,- ) as Eve0308TurnControlReceiver;- receiver.bufferedDeliveries = [];- return receiver;-}diff --git a/packages/eve/src/execution/wire/session-inbox-contract.ts b/packages/eve/src/execution/wire/session-inbox-contract.tsdeleted file mode 100644index 8770453c7..000000000--- a/packages/eve/src/execution/wire/session-inbox-contract.ts+++ /dev/null@@ -1,63 +0,0 @@-/** Every explicit session-inbox wire version still supported by producers. */-export const SESSION_INBOX_WIRE_VERSIONS = [1, 2, 3, 4, 5, 6, 7] as const;--export type SessionInboxWireVersion = (typeof SESSION_INBOX_WIRE_VERSIONS)[number];--/** Current persisted session-inbox wire version. */-export const SESSION_INBOX_WIRE_VERSION =- SESSION_INBOX_WIRE_VERSIONS[SESSION_INBOX_WIRE_VERSIONS.length - 1]!;--/** Hook metadata field advertising the consumer's inbox wire capability. */-export const SESSION_INBOX_WIRE_VERSION_METADATA_KEY = "sessionInboxWireVersion";--/**- * Hook metadata field advertising that the driver displays authorization- * events raised by a workflow task itself. Drivers pinned before this marker- * drop those events, so producers fail fast instead of waiting on a callback- * no channel will render.- */-export const WORKFLOW_TASK_AUTHORIZATION_METADATA_KEY = "workflowTaskAuthorization";--export const SESSION_INBOX_CONTEXT_KEY = "eve.sessionInbox";--/** Immutable inbox coordinates advertised by the receiving session's driver. */-export interface SessionInboxAddress {- readonly sessionId: string;- readonly version: number;-}--export function isSessionInboxAddress(value: unknown): value is SessionInboxAddress {- if (value === null || typeof value !== "object") return false;- return (- "sessionId" in value &&- typeof value.sessionId === "string" &&- value.sessionId.length > 0 &&- !value.sessionId.includes(":") &&- "version" in value &&- typeof value.version === "number" &&- Number.isSafeInteger(value.version) &&- value.version > 0- );-}--/**- * The consumer wire selected before a producer persists a payload.- *- * Version 0 had two incompatible unversioned shapes, so its historical- * variants remain explicit rather than pretending they were one protocol.- */-export type SessionInboxWireTarget =- | { readonly variant: "deliver" | "send"; readonly version: 0 }- | { readonly version: SessionInboxWireVersion };--export function isSessionInboxWireVersion(value: unknown): value is SessionInboxWireVersion {- return SESSION_INBOX_WIRE_VERSIONS.some((version) => version === value);-}--/** Raised when a session inbox value violates its versioned wire contract. */-export class SessionInboxWireError extends Error {- constructor(message: string) {- super(message);- this.name = "SessionInboxWireError";- }-}diff --git a/packages/eve/src/execution/wire/session-inbox-encoder.test.ts b/packages/eve/src/execution/wire/session-inbox-encoder.test.tsdeleted file mode 100644index a0e19e25d..000000000--- a/packages/eve/src/execution/wire/session-inbox-encoder.test.ts+++ /dev/null@@ -1,64 +0,0 @@-import { describe, expect, it } from "vitest";--import {- SessionInboxWireError,- type SessionInboxWireTarget,-} from "#execution/wire/session-inbox-contract.js";-import { sessionInboxWire } from "#execution/wire/session-inbox-encoder.js";--const legacyTargets = [- { variant: "deliver", version: 0 },- { variant: "send", version: 0 },- { version: 1 },-] satisfies readonly SessionInboxWireTarget[];-const activityObserver = {- sink: { url: "https://example.com/activity", version: 1 as const },-};--describe("session inbox encoder", () => {- it.each(- legacyTargets.flatMap(- (target) =>- [- [target, undefined],- [target, activityObserver],- ] as const,- ),- )("projects caller fields for target %o with activity observer %o", (target, observer) => {- const caller = {- activityObserver: observer,- callId: "call-1",- futureCallerField: "future-value",- replyTo: { kind: "hook" as const, token: "callback-token" },- subagentName: "researcher",- };-- const wire = sessionInboxWire.encode(- { caller, kind: "send", payload: { message: "legacy" } },- target,- );-- expect(wire).toHaveProperty("caller", {- callId: "call-1",- replyTo: { kind: "hook", token: "callback-token" },- subagentName: "researcher",- });- });-- it.each(legacyTargets)("wraps malformed caller fields for target %o", (target) => {- expect(() =>- sessionInboxWire.encode(- {- caller: {- callId: 1 as never,- replyTo: { kind: "hook", token: "callback-token" },- subagentName: "researcher",- },- kind: "send",- payload: { message: "legacy" },- },- target,- ),- ).toThrowError(SessionInboxWireError);- });-});diff --git a/packages/eve/src/execution/wire/session-inbox-encoder.ts b/packages/eve/src/execution/wire/session-inbox-encoder.tsdeleted file mode 100644index c2addce6a..000000000--- a/packages/eve/src/execution/wire/session-inbox-encoder.ts+++ /dev/null@@ -1,214 +0,0 @@-import type {- DeliverHookPayload,- SessionCommand,- SessionTimeoutHookPayload,-} from "#channel/types.js";-import {- encodeSessionCommandV1,- type SessionInboxWireV1,-} from "#execution/wire/session-inbox-wire.v1.js";-import {- encodeSessionCommandV2,- type SessionInboxWireV2,-} from "#execution/wire/session-inbox-wire.v2.js";-import {- encodeSessionCommandV3,- type SessionInboxWireV3,-} from "#execution/wire/session-inbox-wire.v3.js";-import {- isSessionInboxWireVersion,- SessionInboxWireError,- type SessionInboxWireTarget,- type SessionInboxWireVersion,-} from "#execution/wire/session-inbox-contract.js";-import { encodeSessionCommandV0 } from "#execution/wire/session-inbox-wire.v0.js";-import {- encodeSessionCommandV4,- type SessionInboxWireV4,-} from "#execution/wire/session-inbox-wire.v4.js";-import {- encodeSessionCommandV5,- type SessionInboxWireV5,-} from "#execution/wire/session-inbox-wire.v5.js";-import {- encodeSessionCommandV6,- type SessionInboxWireV6,-} from "#execution/wire/session-inbox-wire.v6.js";-import {- encodeSessionCommandV7,- type SessionInboxWireV7,-} from "#execution/wire/session-inbox-wire.v7.js";--type SessionInboxCommand = DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload;--/** Current wire type consumed after migration. */-export type SessionInboxWire = SessionInboxWireV7;--type LegacySessionInboxWireTarget = Extract<SessionInboxWireTarget, { readonly version: 0 }>;-type VersionedSessionInboxEncoder = (command: SessionInboxCommand) => unknown;--const versionedEncoders = {- 1: (command: SessionInboxCommand) =>- encodeSessionCommandV1(withoutAcceptedDeployment(withoutOwnedTaskCancellation(command))),- 2: (command: SessionInboxCommand) =>- encodeSessionCommandV2(withoutAcceptedDeployment(withoutOwnedTaskCancellation(command))),- 3: (command: SessionInboxCommand) =>- encodeSessionCommandV3(withoutOwnedTaskCancellation(command)),- 4: (command: SessionInboxCommand) =>- encodeSessionCommandV4(withoutOwnedTaskCancellation(command)),- 5: (command: SessionInboxCommand) =>- encodeSessionCommandV5(withoutOwnedTaskCancellation(command)),- 6: encodeSessionCommandV6,- 7: encodeSessionCommandV7,-} satisfies Record<SessionInboxWireVersion, VersionedSessionInboxEncoder>;--/** Encodes a command for the selected session-inbox consumer. */-function encode(command: SessionInboxCommand, target: { readonly version: 1 }): SessionInboxWireV1;-function encode(command: SessionInboxCommand, target: { readonly version: 2 }): SessionInboxWireV2;-function encode(command: SessionInboxCommand, target: { readonly version: 3 }): SessionInboxWireV3;-function encode(command: SessionInboxCommand, target: { readonly version: 4 }): SessionInboxWireV4;-function encode(command: SessionInboxCommand, target: { readonly version: 5 }): SessionInboxWireV5;-function encode(command: SessionInboxCommand, target: { readonly version: 6 }): SessionInboxWireV6;-function encode(command: SessionInboxCommand, target: { readonly version: 7 }): SessionInboxWireV7;-function encode(- command: SessionInboxCommand,- target: { readonly version: SessionInboxWireVersion },-): unknown;-function encode(- command: SessionInboxCommand,- target: LegacySessionInboxWireTarget,-): Record<string, unknown>;-function encode(- command: SessionInboxCommand,- target: SessionInboxWireTarget,-):- | SessionInboxWireV1- | SessionInboxWireV2- | SessionInboxWireV3- | SessionInboxWireV4- | SessionInboxWireV5- | SessionInboxWireV6- | SessionInboxWireV7- | Record<string, unknown>;-function encode(- command: SessionInboxCommand,- target: SessionInboxWireTarget,-):- | SessionInboxWireV1- | SessionInboxWireV2- | SessionInboxWireV3- | SessionInboxWireV4- | SessionInboxWireV5- | SessionInboxWireV6- | SessionInboxWireV7- | Record<string, unknown> {- if (command.kind === "cancel" && command.tasks === true && target.version < 6) {- throw new SessionInboxWireError(- `Cannot encode session-owned task cancellation for wire version ${target.version}.`,- );- }- const encodable = target.version < 7 ? withoutActivityLabels(command) : command;- if (target.version === 0) {- const currentTaskWire =- target.variant === "send" && encodable.kind === "send" && encodable.payload.task !== undefined- ? encodeSessionCommandV5(encodable)- : undefined;- let legacy = encodeSessionCommandV0(- encodeSessionCommandV1(- withoutCurrentTaskMessages(- withoutAcceptedDeployment(withoutOwnedTaskCancellation(encodable)),- ),- ),- target.variant,- );- if (currentTaskWire?.kind === "deliver") {- legacy = { ...legacy, payload: currentTaskWire.payload };- }- const legacyRecord = legacy as Record<string, unknown>;- const delivery = legacyRecord.delivery;- const acceptedDeploymentId = readAcceptedDeploymentId(command);- if (- target.variant !== "send" ||- acceptedDeploymentId === undefined ||- legacyRecord.kind !== "send" ||- typeof delivery !== "object" ||- delivery === null- ) {- return legacy;- }- return {- ...legacy,- delivery: { ...(delivery as Record<string, unknown>), acceptedDeploymentId },- };- }- if (isSessionInboxWireVersion(target.version)) {- return versionedEncoders[target.version](encodable) as- | SessionInboxWireV1- | SessionInboxWireV2- | SessionInboxWireV3- | SessionInboxWireV4- | SessionInboxWireV5- | SessionInboxWireV6- | SessionInboxWireV7;- }- throw new SessionInboxWireError(- `Cannot encode session inbox payload for unknown wire version ${JSON.stringify((target as { version?: unknown }).version)}.`,- );-}--function withoutActivityLabels(command: SessionInboxCommand): SessionInboxCommand {- if (- (command.kind !== "send" && command.kind !== "deliver") ||- command.caller?.activityObserver?.workIdentity?.label === undefined- ) {- return command;- }- const { label: _label, ...workIdentity } = command.caller.activityObserver.workIdentity;- return {- ...command,- caller: {- ...command.caller,- activityObserver: { ...command.caller.activityObserver, workIdentity },- },- };-}--function withoutOwnedTaskCancellation(command: SessionInboxCommand): SessionInboxCommand {- if (command.kind !== "cancel" || command.tasks === undefined) return command;- const { tasks: _tasks, ...legacy } = command;- return legacy;-}--function withoutCurrentTaskMessages(command: SessionInboxCommand): SessionInboxCommand {- if (command.kind !== "send" || command.payload.task === undefined) return command;- const {- agentRequests: _agentRequests,- inputRequests: _inputRequests,- ...task- } = command.payload.task;- return { ...command, payload: { ...command.payload, task } };-}--function withoutAcceptedDeployment(command: SessionInboxCommand): SessionInboxCommand {- if (command.kind === "send" && command.delivery?.acceptedDeploymentId !== undefined) {- const { acceptedDeploymentId: _acceptedDeploymentId, ...delivery } = command.delivery;- return { ...command, delivery };- }- if (command.kind !== "deliver" || command.deliveryMetadata === undefined) return command;- return {- ...command,- deliveryMetadata: command.deliveryMetadata.map((metadata) => {- const { acceptedDeploymentId: _acceptedDeploymentId, ...legacy } = metadata;- return legacy;- }),- };-}--function readAcceptedDeploymentId(command: SessionInboxCommand): string | undefined {- if (command.kind === "send") return command.delivery?.acceptedDeploymentId;- if (command.kind !== "deliver") return undefined;- return command.deliveryMetadata?.find((metadata) => metadata.payloadIndex === 0)- ?.acceptedDeploymentId;-}-/** Server/step-safe producer facade. */-export const sessionInboxWire = { encode } as const;diff --git a/packages/eve/src/execution/wire/session-inbox-resume.test.ts b/packages/eve/src/execution/wire/session-inbox-resume.test.tsdeleted file mode 100644index a61ea1d38..000000000--- a/packages/eve/src/execution/wire/session-inbox-resume.test.ts+++ /dev/null@@ -1,297 +0,0 @@-import { afterEach, describe, expect, it, vi } from "vitest";--import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";-import { sessionCommandHookToken } from "#execution/session-command-token.js";-import { SESSION_INBOX_WIRE_VERSIONS } from "#execution/wire/session-inbox-contract.js";-import {- resolveSessionInboxWireTarget,- resumeSessionInbox,- sessionDriverSupportsWorkflowTaskAuthorization,-} from "#execution/wire/session-inbox-resume.js";--const getHookByTokenMock = vi.fn();-const getRawHookByTokenMock = vi.fn();-const resumeHookMock = vi.fn();--vi.mock("#compiled/@workflow/core/runtime.js", () => ({- getHookByToken: (...args: unknown[]) => getHookByTokenMock(...args),- getWorld: async () => ({ hooks: { getByToken: getRawHookByTokenMock } }),- resumeHook: (...args: unknown[]) => resumeHookMock(...args),-}));--afterEach(() => {- getHookByTokenMock.mockReset();- getRawHookByTokenMock.mockReset();- resumeHookMock.mockReset();-});--describe("workflow task authorization support", () => {- it("reads the capability from lazy hook metadata", async () => {- getHookByTokenMock.mockResolvedValue(- sessionHook("session-1", sessionCommandHookToken("session-1"), {- workflowTaskAuthorization: true,- }),- );-- await expect(sessionDriverSupportsWorkflowTaskAuthorization("session-1")).resolves.toBe(true);- });-});--describe("session inbox target resolution", () => {- it.each(SESSION_INBOX_WIRE_VERSIONS)(- "uses wire version %i advertised by a stamped hook",- async (version) => {- const hook = sessionHook("session-1", "channel-1", {- sessionInboxWireVersion: version,- });-- await expect(resolveSessionInboxWireTarget(hook)).resolves.toEqual({ version });- expect(getHookByTokenMock).not.toHaveBeenCalled();- },- );-- it("selects raw send for a markerless stable hook", async () => {- const token = sessionCommandHookToken("session-1");-- await expect(resolveSessionInboxWireTarget(sessionHook("session-1", token))).resolves.toEqual({- variant: "send",- version: 0,- });- expect(getHookByTokenMock).not.toHaveBeenCalled();- });-- it("selects raw send for a markerless continuation owned by the stable-inbox cohort", async () => {- getRawHookByTokenMock.mockResolvedValue(- sessionHook("session-1", sessionCommandHookToken("session-1")),- );-- await expect(- resolveSessionInboxWireTarget(sessionHook("session-1", "continuation-1")),- ).resolves.toEqual({ variant: "send", version: 0 });- expect(getHookByTokenMock).not.toHaveBeenCalled();- });-- it("rejects a stable inbox belonging to a different run without hydrating its metadata", async () => {- getRawHookByTokenMock.mockResolvedValue({ runId: "different-run" });-- await expect(- resolveSessionInboxWireTarget(sessionHook("session-1", "continuation-1")),- ).rejects.toThrow(/belongs to run "different-run", expected "session-1"/);- expect(getHookByTokenMock).not.toHaveBeenCalled();- });-- it("selects deliver for a markerless continuation without a stable inbox", async () => {- getRawHookByTokenMock.mockRejectedValue(- new HookNotFoundError(sessionCommandHookToken("session-1")),- );-- await expect(- resolveSessionInboxWireTarget(sessionHook("session-1", "continuation-1")),- ).resolves.toEqual({ variant: "deliver", version: 0 });- });-- it("rejects an advertised unknown version before persistence", async () => {- await expect(- resolveSessionInboxWireTarget(- sessionHook("session-1", "continuation-1", { sessionInboxWireVersion: 99 }),- ),- ).rejects.toThrow(/unsupported wire version 99/);- expect(getHookByTokenMock).not.toHaveBeenCalled();- });-});--describe("resumeSessionInbox", () => {- it.each(SESSION_INBOX_WIRE_VERSIONS)(- "uses the persisted consumer version %i without reading hook metadata",- async (version) => {- await resumeSessionInbox(- { sessionId: "child-session", version },- { kind: "send", payload: { inputResponses: [{ requestId: "req-1", text: "yes" }] } },- );-- expect(getHookByTokenMock).not.toHaveBeenCalled();- expect(getRawHookByTokenMock).not.toHaveBeenCalled();- expect(resumeHookMock).toHaveBeenCalledWith(- sessionCommandHookToken("child-session"),- expect.objectContaining({ kind: "deliver", version }),- );- },- );-- it("rejects unsupported saved consumer versions before resuming", async () => {- await expect(- resumeSessionInbox({ sessionId: "child-session", version: 99 }, { kind: "clear" }),- ).rejects.toThrow(/unsupported wire version 99/);- expect(getHookByTokenMock).not.toHaveBeenCalled();- expect(resumeHookMock).not.toHaveBeenCalled();- });-- it("keeps version-sensitive cancellation checks when using a saved address", async () => {- await expect(- resumeSessionInbox(- { sessionId: "child-session", version: 5 },- { kind: "cancel", tasks: true },- ),- ).rejects.toThrow(/Cannot encode session-owned task cancellation/);- expect(resumeHookMock).not.toHaveBeenCalled();- });-- it("resumes a compatible stable inbox by token without inspecting metadata", async () => {- const token = sessionCommandHookToken("session-1");- const hook = sessionHook("session-1", token, { sessionInboxWireVersion: 2 });- resumeHookMock.mockResolvedValue(hook);-- await resumeSessionInbox(token, {- kind: "send",- payload: { message: "follow-up" },- });-- expect(getHookByTokenMock).not.toHaveBeenCalled();- expect(resumeHookMock).toHaveBeenCalledWith(token, {- auth: undefined,- caller: undefined,- delivery: undefined,- kind: "send",- payload: { message: "follow-up" },- requestId: undefined,- taskDeliveryId: undefined,- turnPolicy: undefined,- });- });-- it("strips an undefined activity observer from the stable fast path", async () => {- const token = sessionCommandHookToken("session-1");- const hook = sessionHook("session-1", token, { sessionInboxWireVersion: 2 });- resumeHookMock.mockResolvedValue(hook);-- await resumeSessionInbox(token, {- caller: {- activityObserver: undefined,- callId: "call-1",- replyTo: { kind: "hook", token: "reply-1" },- subagentName: "researcher",- },- kind: "send",- payload: { message: "follow-up" },- });-- expect(getHookByTokenMock).not.toHaveBeenCalled();- expect(resumeHookMock).toHaveBeenCalledWith(token, {- auth: undefined,- caller: {- callId: "call-1",- replyTo: { kind: "hook", token: "reply-1" },- subagentName: "researcher",- },- delivery: undefined,- kind: "send",- payload: { message: "follow-up" },- requestId: undefined,- taskDeliveryId: undefined,- turnPolicy: undefined,- });- });-- it("negotiates v6 for stable session-owned task cancellation", async () => {- const token = sessionCommandHookToken("session-1");- const hook = sessionHook("session-1", token, { sessionInboxWireVersion: 6 });- getHookByTokenMock.mockResolvedValue(hook);- resumeHookMock.mockResolvedValue(hook);-- await resumeSessionInbox(token, { kind: "cancel", tasks: true, turnId: "turn-1" });-- expect(getHookByTokenMock).toHaveBeenCalledWith(token);- expect(resumeHookMock).toHaveBeenCalledWith(hook, {- kind: "cancel",- tasks: true,- turnId: "turn-1",- version: 6,- });- });-- it.each([- ["markerless", undefined],- ["v5", { sessionInboxWireVersion: 5 }],- ])(- "rejects stable session-owned task cancellation for a %s consumer before persistence",- async (_name, metadata) => {- const token = sessionCommandHookToken("session-1");- getHookByTokenMock.mockResolvedValue(sessionHook("session-1", token, metadata));-- await expect(resumeSessionInbox(token, { kind: "cancel", tasks: true })).rejects.toThrow(- /Cannot encode session-owned task cancellation for wire version/,- );-- expect(getHookByTokenMock).toHaveBeenCalledWith(token);- expect(resumeHookMock).not.toHaveBeenCalled();- },- );-- it("encodes continuation delivery for the resolved consumer and resumes that hook", async () => {- const hook = sessionHook("session-1", "continuation-1", { sessionInboxWireVersion: 1 });- getHookByTokenMock.mockResolvedValue(hook);- resumeHookMock.mockResolvedValue(hook);-- await resumeSessionInbox("continuation-1", {- kind: "send",- payload: { message: "follow-up" },- });-- expect(getHookByTokenMock).toHaveBeenCalledWith("continuation-1");- expect(resumeHookMock).toHaveBeenCalledWith(hook, {- auth: undefined,- caller: undefined,- kind: "deliver",- payload: { message: "follow-up" },- payloads: [{ message: "follow-up" }],- requestId: undefined,- version: 1,- });- });-- it("inspects reserved session aliases outside the stable inbox", async () => {- const token = "eve:session:session-1:session-timeout";- const hook = sessionHook("session-1", token, { sessionInboxWireVersion: 1 });- getHookByTokenMock.mockResolvedValue(hook);- resumeHookMock.mockResolvedValue(hook);-- await resumeSessionInbox(token, { kind: "session-timeout" });-- expect(getHookByTokenMock).toHaveBeenCalledWith(token);- expect(resumeHookMock).toHaveBeenCalledWith(hook, {- kind: "session-timeout",- version: 1,- });- });-- it("retains metadata negotiation when a stable delivery needs the current caller wire", async () => {- const token = sessionCommandHookToken("session-1");- const hook = sessionHook("session-1", token, { sessionInboxWireVersion: 2 });- getHookByTokenMock.mockResolvedValue(hook);- resumeHookMock.mockResolvedValue(hook);-- await resumeSessionInbox(token, {- caller: {- activityObserver: { sink: { url: "https://example.com/activity", version: 1 } },- callId: "call-1",- replyTo: { kind: "hook", token: "reply-1" },- subagentName: "researcher",- },- kind: "send",- payload: { message: "follow-up" },- });-- expect(getHookByTokenMock).toHaveBeenCalledWith(token);- expect(resumeHookMock).toHaveBeenCalledWith(- hook,- expect.objectContaining({- caller: expect.objectContaining({ activityObserver: expect.any(Object) }),- version: 2,- }),- );- });-});--function sessionHook(runId: string, token: string, metadata?: unknown) {- return { metadata: Promise.resolve(metadata), runId, token } as never;-}diff --git a/packages/eve/src/execution/wire/session-inbox-resume.ts b/packages/eve/src/execution/wire/session-inbox-resume.tsdeleted file mode 100644index 16fa75f4e..000000000--- a/packages/eve/src/execution/wire/session-inbox-resume.ts+++ /dev/null@@ -1,108 +0,0 @@-import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";--import type {- DeliverHookPayload,- SessionCommand,- SessionTimeoutHookPayload,-} from "#channel/types.js";-import {- isSessionCommandHookToken,- sessionCommandHookToken,-} from "#execution/session-command-token.js";-import {- SESSION_INBOX_WIRE_VERSION_METADATA_KEY,- WORKFLOW_TASK_AUTHORIZATION_METADATA_KEY,- isSessionInboxAddress,- isSessionInboxWireVersion,- SessionInboxWireError,- type SessionInboxAddress,- type SessionInboxWireTarget,-} from "#execution/wire/session-inbox-contract.js";-import { sessionInboxWire } from "#execution/wire/session-inbox-encoder.js";-import { getHookByToken, getRawHookByToken, resumeHook } from "#internal/workflow/runtime.js";-import { isObject } from "#shared/guards.js";--type ResumedSessionInboxHook = Awaited<ReturnType<typeof resumeHook>>;--/** Resolves the consumer contract, encodes for it, and resumes that exact hook. */-export async function resumeSessionInbox(- address: string | SessionInboxAddress,- command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload,-): Promise<ResumedSessionInboxHook> {- if (typeof address !== "string") {- if (!isSessionInboxAddress(address)) {- throw new SessionInboxWireError("Session inbox target has an invalid address.");- }- if (!isSessionInboxWireVersion(address.version)) {- throw new SessionInboxWireError(- `Session inbox target declares unsupported wire version ${JSON.stringify(address.version)}.`,- );- }- return await resumeHook(- sessionCommandHookToken(address.sessionId),- sessionInboxWire.encode(command, { version: address.version }),- );- }-- const token = address;- if (isStableInboxFastPathCompatible(token, command)) {- return await resumeHook(- token,- sessionInboxWire.encode(command, { variant: "send", version: 0 }),- );- }-- const hook = await getHookByToken(token);- const target = await resolveSessionInboxWireTarget(hook);- return await resumeHook(hook, sessionInboxWire.encode(command, target));-}--function isStableInboxFastPathCompatible(- token: string,- command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload,-): boolean {- if (!isSessionCommandHookToken(token)) return false;- if (command.kind === "cancel" && command.tasks === true) return false;- return !("caller" in command && command.caller?.activityObserver !== undefined);-}--type SessionInboxHook = Awaited<ReturnType<typeof getHookByToken>>;--/** Whether the session's pinned driver displays authorization events raised by workflow tasks. */-export async function sessionDriverSupportsWorkflowTaskAuthorization(- sessionId: string,-): Promise<boolean> {- const driver = await getHookByToken(sessionCommandHookToken(sessionId));- const metadata = await driver.metadata;- return isObject(metadata) && metadata[WORKFLOW_TASK_AUTHORIZATION_METADATA_KEY] === true;-}--/** Selects the encoder understood by a persisted hook's consumer deployment. */-export async function resolveSessionInboxWireTarget(- hook: SessionInboxHook,-): Promise<SessionInboxWireTarget> {- const metadata = await hook.metadata;- if (isObject(metadata) && SESSION_INBOX_WIRE_VERSION_METADATA_KEY in metadata) {- const version = metadata[SESSION_INBOX_WIRE_VERSION_METADATA_KEY];- if (isSessionInboxWireVersion(version)) return { version };- throw new SessionInboxWireError(- `Session inbox target declares unsupported wire version ${JSON.stringify(version)}.`,- );- }-- const stableToken = sessionCommandHookToken(hook.runId);- if (hook.token === stableToken) return { variant: "send", version: 0 };-- try {- const stableHook = await getRawHookByToken(stableToken);- if (stableHook.runId !== hook.runId) {- throw new SessionInboxWireError(- `Stable session inbox ${JSON.stringify(stableToken)} belongs to run ${JSON.stringify(stableHook.runId)}, expected ${JSON.stringify(hook.runId)}.`,- );- }- return { variant: "send", version: 0 };- } catch (error) {- if (HookNotFoundError.is(error)) return { variant: "deliver", version: 0 };- throw error;- }-}diff --git a/packages/eve/src/execution/wire/session-inbox-wire.test.ts b/packages/eve/src/execution/wire/session-inbox-wire.test.tsdeleted file mode 100644index 9acb0353d..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.test.ts+++ /dev/null@@ -1,39 +0,0 @@-import { runInNewContext } from "node:vm";--import { describe, expect, it } from "vitest";--import { sessionInboxWire, SessionInboxWireError } from "#execution/wire/session-inbox-wire.js";--describe("session inbox wire policy", () => {- it("rejects a present non-numeric version before normalization", () => {- expect(() =>- sessionInboxWire.decode({ kind: "deliver", payloads: [], version: undefined }),- ).toThrowError(SessionInboxWireError);- });-- it("migrates version 5 cancel commands without enabling owned-task cancellation", () => {- expect(sessionInboxWire.decode({ kind: "cancel", version: 5 })).toEqual({- kind: "cancel",- taskId: undefined,- tasks: undefined,- turnId: undefined,- });- });-- it("normalizes cross-realm records before running pure migrations", () => {- const wire = runInNewContext(`({- caller: undefined,- kind: "deliver",- payloads: [{ message: "legacy", omitted: undefined }],- version: 1,- })`);-- expect(sessionInboxWire.decode(wire)).toEqual({- auth: undefined,- caller: undefined,- kind: "deliver",- payloads: [{ message: "legacy" }],- requestId: undefined,- });- });-});diff --git a/packages/eve/src/execution/wire/session-inbox-wire.ts b/packages/eve/src/execution/wire/session-inbox-wire.tsdeleted file mode 100644index e9f8a70c8..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.ts+++ /dev/null@@ -1,180 +0,0 @@-import type {- DeliverHookPayload,- DeliverPayload,- SessionCommand,- SessionTimeoutHookPayload,-} from "#channel/types.js";-import {- runMigrationChain,- type VersionMigration,-} from "#execution/durable-session-migrations/chain.js";-import {- SESSION_INBOX_WIRE_VERSION,- SessionInboxWireError,-} from "#execution/wire/session-inbox-contract.js";-import type { SessionInboxWire } from "#execution/wire/session-inbox-encoder.js";-import { sessionInboxWireV0Migration } from "#execution/wire/session-inbox-wire.v0.js";-import { normalizeSessionInboxWireV2 } from "#execution/wire/session-inbox-wire.v2-migration.js";-import { sessionInboxWireV1Migration } from "#execution/wire/session-inbox-wire.v2.migration.js";-import { sessionInboxWireV2Migration } from "#execution/wire/session-inbox-wire.v3.migration.js";-import { sessionInboxWireV3Migration } from "#execution/wire/session-inbox-wire.v4.migration.js";-import { sessionInboxWireV4Migration } from "#execution/wire/session-inbox-wire.v5.migration.js";-import { isObject } from "#shared/guards.js";--/**- * The session inbox wire family: every payload persisted to a session's- * durable inbox hooks crosses through `sessionInboxWire.encode` /- * `sessionInboxWire.decode`.- *- * Historic migrations live in `session-inbox-wire.vN.ts` modules; the- * current schema and encoder live in the current version module. This file- * remains the dependency-free decoder facade reached by the workflow body.- *- * See research/session-inbox-wire-schema.md and issue #1765.- */--/** A persisted inbox payload normalized for consumption; `send` never survives decode. */-export type DecodedSessionInbox =- | DeliverHookPayload- | SessionTimeoutHookPayload- | Extract<SessionCommand, { readonly kind: "cancel" | "clear" | "compact" | "reset" }>;--export { SessionInboxWireError } from "#execution/wire/session-inbox-contract.js";--/** Prefixes migration and contract failures alike, so messages read as one voice. */-const WIRE_LABEL = "session inbox payload";--const sessionInboxWireV5Migration: VersionMigration = {- from: 5,- migrate(prior) {- if (!isObject(prior)) throw new Error("session inbox wire v5 value is not an object.");- return { ...prior, version: 6 };- },- to: 6,-};--const sessionInboxWireV6Migration: VersionMigration = {- from: 6,- migrate(prior) {- if (!isObject(prior)) throw new Error("session inbox wire v6 value is not an object.");- return { ...prior, version: 7 };- },- to: 7,-};--const sessionInboxMigrations: readonly VersionMigration[] = [- sessionInboxWireV0Migration,- sessionInboxWireV1Migration,- sessionInboxWireV2Migration,- sessionInboxWireV3Migration,- sessionInboxWireV4Migration,- sessionInboxWireV5Migration,- sessionInboxWireV6Migration,-];--/**- * Decodes a persisted inbox payload or throws {@link SessionInboxWireError}.- *- * Unknown newer versions and migration-bound shape mismatches both throw: a- * lost delivery with an operator-visible signal is the designed failure; a- * reinterpreted delivery is the bug this module exists to prevent.- */-function decode(value: unknown): DecodedSessionInbox {- const declaredVersion =- typeof value === "object" && value !== null && "version" in value- ? (value as { readonly version?: unknown }).version- : undefined;- const hasDeclaredVersion = typeof value === "object" && value !== null && "version" in value;- if (hasDeclaredVersion && typeof declaredVersion !== "number") {- throw new SessionInboxWireError(`${WIRE_LABEL}: value has no numeric "version" field.`);- }- const normalized = normalizeSessionInboxWireV2(value);- if (- (declaredVersion === 1 || declaredVersion === 2 || declaredVersion === 3) &&- containsCurrentTaskMessages(normalized)- ) {- throw new SessionInboxWireError(- `${WIRE_LABEL} does not match wire version ${declaredVersion}.`,- );- }- let migrated: unknown;- try {- migrated = runMigrationChain({- initialVersion: 0,- label: WIRE_LABEL,- migrations: sessionInboxMigrations,- targetVersion: SESSION_INBOX_WIRE_VERSION,- value: normalized,- });- } catch (error) {- throw new SessionInboxWireError(error instanceof Error ? error.message : String(error));- }-- const wire = normalizeSessionInboxWireV2(migrated) as Partial<SessionInboxWire>;- if (wire.version !== SESSION_INBOX_WIRE_VERSION) {- throw new SessionInboxWireError(- `${WIRE_LABEL} declares version ${JSON.stringify(wire.version)}, expected ${SESSION_INBOX_WIRE_VERSION}.`,- );- }- if (- typeof declaredVersion === "number" &&- declaredVersion >= 2 &&- wire.kind === "deliver" &&- !("payload" in wire)- ) {- throw new SessionInboxWireError(- `${WIRE_LABEL} does not match wire version ${declaredVersion}.`,- );- }- return normalizeWire(wire as SessionInboxWire);-}--/** Workflow-safe consumer facade. */-export const sessionInboxWire = { decode } as const;--function containsCurrentTaskMessages(value: unknown): boolean {- if (!isObject(value) || value.kind !== "deliver") return false;- const payloads = Array.isArray(value.payloads) ? value.payloads : [];- return payloads.some((payload) => {- if (!isObject(payload) || !isObject(payload.task)) return false;- if (Object.hasOwn(payload.task, "agentRequests")) return true;- const inputRequests = payload.task.inputRequests;- return (- Array.isArray(inputRequests) &&- inputRequests.some(- (request) => isObject(request) && ("request" in request || "requests" in request),- )- );- });-}--/** Strips wire-only fields (`version`, the deliver mirror) for consumption. */-function normalizeWire(wire: SessionInboxWire): DecodedSessionInbox {- switch (wire.kind) {- case "deliver":- return {- auth: wire.auth,- caller: wire.caller,- deliveryMetadata: wire.deliveryMetadata,- kind: "deliver",- payloads: wire.payloads as readonly DeliverPayload[],- requestId: wire.requestId,- taskDeliveryId: wire.taskDeliveryId,- turnPolicy: wire.turnPolicy,- };- case "session-timeout":- return { kind: "session-timeout" };- case "clear":- return { kind: "clear" };- case "compact":- return { kind: "compact" };- case "reset":- return { kind: "reset", reason: wire.reason };- case "cancel":- return { kind: "cancel", taskId: wire.taskId, tasks: wire.tasks, turnId: wire.turnId };- default:- throw new SessionInboxWireError(- `${WIRE_LABEL} has an unrecognized kind ${JSON.stringify((wire as { kind?: unknown }).kind)}.`,- );- }-}diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v0.test.ts b/packages/eve/src/execution/wire/session-inbox-wire.v0.test.tsdeleted file mode 100644index 14e470316..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.v0.test.ts+++ /dev/null@@ -1,102 +0,0 @@-import { describe, expect, it } from "vitest";--import { sessionInboxWire as sessionInboxWireEncoder } from "#execution/wire/session-inbox-encoder.js";-import {- sessionInboxWire as sessionInboxWireDecoder,- SessionInboxWireError,-} from "#execution/wire/session-inbox-wire.js";--/** Every payload shape persisted before explicit wire versioning. */-const FROZEN_FIXTURES: ReadonlyArray<{- readonly name: string;- readonly payload: string;- readonly decoded: unknown;-}> = [- {- name: "legacy deliver envelope (≤0.30.4 producers)",- payload: '{"kind":"deliver","payloads":[{"message":"legacy"}]}',- decoded: { kind: "deliver", payloads: [{ message: "legacy" }] },- },- {- name: "raw send command (0.30.5–0.31.0 producers)",- payload:- '{"auth":null,"delivery":{"channelKind":"http","channelName":"web","deliveryId":"delivery-0"},"kind":"send","payload":{"message":"mid"},"requestId":"req-0","taskDeliveryId":"task-delivery-0","turnPolicy":"queue"}',- decoded: {- auth: null,- deliveryMetadata: [- {- channelKind: "http",- channelName: "web",- deliveryId: "delivery-0",- payloadIndex: 0,- },- ],- kind: "deliver",- payloads: [{ message: "mid" }],- requestId: "req-0",- taskDeliveryId: "task-delivery-0",- turnPolicy: "queue",- },- },- {- name: "unversioned cancel control",- payload: '{"kind":"cancel","turnId":"turn_1"}',- decoded: { kind: "cancel", turnId: "turn_1" },- },- {- name: "unversioned session-timeout control",- payload: '{"kind":"session-timeout"}',- decoded: { kind: "session-timeout" },- },-];--describe("session inbox wire v0", () => {- it.each(FROZEN_FIXTURES)("migrates the frozen $name fixture", ({ payload, decoded }) => {- expect(sessionInboxWireDecoder.decode(JSON.parse(payload))).toEqual(decoded);- });-- it.each([- ["a malformed legacy deliver", { kind: "deliver", payloads: "nope" }],- ["a malformed legacy send", { kind: "send", payload: "nope" }],- ["legacy send with malformed delivery metadata", { kind: "send", payload: {}, delivery: 1 }],- ["a non-object payload", "deliver"],- ])("rejects %s instead of reinterpreting it", (_name, payload) => {- expect(() => sessionInboxWireDecoder.decode(payload)).toThrowError(SessionInboxWireError);- });-- it("encodes sends for the legacy deliver cohort", () => {- expect(- sessionInboxWireEncoder.encode(- { auth: null, kind: "send", payload: { message: "legacy" }, requestId: "req-0" },- { variant: "deliver", version: 0 },- ),- ).toEqual({- auth: null,- caller: undefined,- deliveryMetadata: undefined,- kind: "deliver",- payloads: [{ message: "legacy" }],- requestId: "req-0",- taskDeliveryId: undefined,- turnPolicy: undefined,- });- });-- it("encodes sends for the legacy raw-send cohort", () => {- expect(- sessionInboxWireEncoder.encode(- { kind: "send", payload: { message: "mid" } },- { variant: "send", version: 0 },- ),- ).toEqual({- auth: undefined,- caller: undefined,- delivery: undefined,- kind: "send",- payload: { message: "mid" },- requestId: undefined,- taskDeliveryId: undefined,- turnPolicy: undefined,- });- });-});diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v0.ts b/packages/eve/src/execution/wire/session-inbox-wire.v0.tsdeleted file mode 100644index 79840dc5f..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.v0.ts+++ /dev/null@@ -1,91 +0,0 @@-import type { VersionMigration } from "#execution/durable-session-migrations/chain.js";-import type { SessionInboxWireV1 } from "#execution/wire/session-inbox-wire.v1.js";-import { isObject } from "#shared/guards.js";--/**- * Version 0 is the unversioned era. Its sole shape change is the raw `send`- * command persisted by eve 0.30.5–0.31.0; legacy `deliver` already has the- * v1 discriminator and needs only the version stamp.- *- * This module is removable once runs created by that cohort have aged out- * under the 30-day default session timeout.- */-function migrateSessionInboxWireV0(- prior: unknown,-): Record<string, unknown> & { readonly version: 1 } {- const value = prior as Record<string, unknown>;- if (value.kind === "send") return migrateLegacySend(value);-- if (- value.kind === "deliver" &&- !(Array.isArray(value.payloads) && value.payloads.every(isObject))- ) {- throw new Error("legacy deliver payload has no object-array payloads field.");- }-- return { ...value, version: 1 };-}--function migrateLegacySend(- send: Record<string, unknown>,-): Record<string, unknown> & { readonly version: 1 } {- if (!isObject(send.payload)) {- throw new Error("legacy send command has no object payload field.");- }- if (send.delivery !== undefined && !isObject(send.delivery)) {- throw new Error("legacy send command has a non-object delivery field.");- }-- return {- auth: send.auth,- caller: send.caller,- deliveryMetadata:- send.delivery === undefined ? undefined : [{ ...send.delivery, payloadIndex: 0 }],- kind: "deliver",- payload: send.payload,- payloads: [send.payload],- requestId: send.requestId,- taskDeliveryId: send.taskDeliveryId,- turnPolicy: send.turnPolicy,- version: 1,- };-}--export const sessionInboxWireV0Migration: VersionMigration = {- from: 0,- migrate: migrateSessionInboxWireV0,- to: 1,-};--/** Encodes the two incompatible shapes from the unversioned wire era. */-export function encodeSessionCommandV0(- wire: SessionInboxWireV1,- variant: "deliver" | "send",-): Omit<SessionInboxWireV1, "version"> | Record<string, unknown> {- if (wire.kind !== "deliver") {- const { version: _version, ...legacy } = wire;- return legacy;- }-- if (variant === "deliver") {- const { payload: _payload, version: _version, ...legacy } = wire;- return legacy;- }-- const deliveryMetadata = wire.deliveryMetadata?.find((metadata) => metadata.payloadIndex === 0);- let delivery: Omit<NonNullable<typeof deliveryMetadata>, "payloadIndex"> | undefined;- if (deliveryMetadata !== undefined) {- const { payloadIndex: _payloadIndex, ...value } = deliveryMetadata;- delivery = value;- }- return {- auth: wire.auth,- caller: wire.caller,- delivery,- kind: "send",- payload: wire.payload,- requestId: wire.requestId,- taskDeliveryId: wire.taskDeliveryId,- turnPolicy: wire.turnPolicy,- };-}diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v1.test.ts b/packages/eve/src/execution/wire/session-inbox-wire.v1.test.tsdeleted file mode 100644index d444e974b..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.v1.test.ts+++ /dev/null@@ -1,222 +0,0 @@-import { describe, expect, it } from "vitest";-import { z } from "#compiled/zod/index.js";--import { sessionInboxWire as sessionInboxWireEncoder } from "#execution/wire/session-inbox-encoder.js";-import { SESSION_INBOX_WIRE_VERSIONS } from "#execution/wire/session-inbox-contract.js";-import {- sessionInboxWire as sessionInboxWireDecoder,- SessionInboxWireError,-} from "#execution/wire/session-inbox-wire.js";-import { sessionInboxWireV1Schema } from "#execution/wire/session-inbox-wire.v1.js";--const FROZEN_FIXTURES = {- clear: '{"kind":"clear","version":1}',- deliver:- '{"auth":null,"kind":"deliver","payload":{"message":"wire"},"payloads":[{"message":"wire"}],"requestId":"req-wire","version":1}',-} as const;--describe("session inbox wire v1", () => {- it("accepts only its own version", () => {- expect(sessionInboxWireV1Schema.safeParse({ kind: "clear", version: 1 }).success).toBe(true);- expect(sessionInboxWireV1Schema.safeParse({ kind: "clear", version: 2 }).success).toBe(false);- });-- it.each(SESSION_INBOX_WIRE_VERSIONS)(- "encodes and decodes declared wire version %i",- (version) => {- const wire = sessionInboxWireEncoder.encode(- { kind: "send", payload: { message: "registry" } },- { version },- );-- expect(wire).toMatchObject({ version });- expect(sessionInboxWireDecoder.decode(wire)).toEqual({- auth: undefined,- caller: undefined,- kind: "deliver",- payloads: [{ message: "registry" }],- requestId: undefined,- });- },- );-- it("pins the complete schema byte for byte", () => {- expect(- stableStringify(- z.toJSONSchema(sessionInboxWireV1Schema, { io: "input", unrepresentable: "any" }),- ),- ).toMatchSnapshot();- });-- it("encodes a send as the frozen v1 delivery and round-trips", () => {- const wire = sessionInboxWireEncoder.encode(- {- auth: null,- kind: "send",- payload: { message: "wire" },- requestId: "req-wire",- },- { version: 1 },- );- expect(stableStringify(wire)).toBe(FROZEN_FIXTURES.deliver);- expect(sessionInboxWireDecoder.decode(JSON.parse(JSON.stringify(wire)))).toEqual({- auth: null,- caller: undefined,- kind: "deliver",- payloads: [{ message: "wire" }],- requestId: "req-wire",- });- });-- it("preserves the current delivery, task, caller, and turn-control fields", () => {- const caller = {- callId: "call-1",- replyTo: {- kind: "callback" as const,- token: "callback-token",- url: "https://example.com/callback",- },- subagentName: "researcher",- taskId: "task-1",- };- const task = {- views: [- {- metadata: {- agentId: "agent-1",- kind: "subagent" as const,- mode: "local" as const,- name: "researcher",- },- status: "working" as const,- taskId: "task-1",- },- {- executor: {- binding: {- data: { agentId: "agent-2", mode: "local", name: "worker" },- kind: "subagent",- },- },- lastOutput: { data: "done", type: "result" as const },- metadata: { kind: "tool", name: "worker" },- status: "completed" as const,- taskId: "task-2",- },- ],- };- const wire = sessionInboxWireEncoder.encode(- {- caller,- delivery: {- channelKind: "http",- channelName: "web",- deliveryId: "delivery-1",- requestTraceContext: { spanId: "span-1", traceFlags: 1, traceId: "trace-1" },- },- kind: "send",- payload: { task },- taskDeliveryId: "task-delivery-1",- turnPolicy: "queue",- },- { version: 1 },- );-- expect(sessionInboxWireDecoder.decode(JSON.parse(JSON.stringify(wire)))).toEqual({- auth: undefined,- caller,- deliveryMetadata: [- {- channelKind: "http",- channelName: "web",- deliveryId: "delivery-1",- payloadIndex: 0,- requestTraceContext: { spanId: "span-1", traceFlags: 1, traceId: "trace-1" },- },- ],- kind: "deliver",- payloads: [{ task }],- requestId: undefined,- taskDeliveryId: "task-delivery-1",- turnPolicy: "queue",- });- expect(- sessionInboxWireDecoder.decode(- sessionInboxWireEncoder.encode({ kind: "cancel", taskId: "task-1" }, { version: 1 }),- ),- ).toEqual({ kind: "cancel", taskId: "task-1", turnId: undefined });- });-- it("encodes controls with v1 and round-trips", () => {- const clear = sessionInboxWireEncoder.encode({ kind: "clear" }, { version: 1 });- expect(stableStringify(clear)).toBe(FROZEN_FIXTURES.clear);- expect(sessionInboxWireDecoder.decode(clear)).toEqual({ kind: "clear" });- expect(- sessionInboxWireDecoder.decode(- sessionInboxWireEncoder.encode({ kind: "session-timeout" }, { version: 1 }),- ),- ).toEqual({ kind: "session-timeout" });- expect(- sessionInboxWireDecoder.decode(- sessionInboxWireEncoder.encode({ kind: "cancel", turnId: "turn_9" }, { version: 1 }),- ),- ).toEqual({ kind: "cancel", turnId: "turn_9" });- });-- it("keeps the transitional mirror equal to the delivery", () => {- const wire = sessionInboxWireEncoder.encode(- { kind: "send", payload: { message: "m" } },- { version: 1 },- );- expect(wire.kind).toBe("deliver");- if (wire.kind === "deliver") expect(wire.payloads[0]).toEqual(wire.payload);- });-- it("does not persist undeclared command fields and preserves adapter extensions", () => {- const payload = { interaction: { slack: true }, message: "hi" };- const encoded = sessionInboxWireEncoder.encode(- { kind: "send", payload, stowaway: "must not persist" } as never,- { version: 1 },- );- expect(encoded).not.toHaveProperty("stowaway");- expect(encoded.kind === "deliver" && encoded.payloads[0]).toEqual(payload);- });-- it.each([- ["input response", { inputResponses: [{ requestId: 7 }] }],- ["context", { context: ["valid", 7] }],- ["message part", { message: [{ text: 7, type: "text" }] }],- ["output schema", { outputSchema: { invalid: () => undefined } }],- ])("rejects a malformed eve-owned %s before persistence", (_name, payload) => {- expect(() =>- sessionInboxWireEncoder.encode({ kind: "send", payload } as never, { version: 1 }),- ).toThrowError(SessionInboxWireError);- });-- it.each([- ["a future wire version", { kind: "deliver", payloads: [], version: 2 }],- ["a non-numeric version", { kind: "deliver", payloads: [], version: "1" }],- ["an unrecognized kind", { kind: "mystery", version: 1 }],- ])("rejects %s instead of reinterpreting it", (_name, payload) => {- expect(() => sessionInboxWireDecoder.decode(payload)).toThrowError(SessionInboxWireError);- });-- it("reports an unknown newer version as written by a newer deployment", () => {- expect(() =>- sessionInboxWireDecoder.decode({ kind: "deliver", payloads: [], version: 99 }),- ).toThrowError(/newer/);- });-});--function stableStringify(value: unknown): string {- return JSON.stringify(sortKeys(value));-}--function sortKeys(value: unknown): unknown {- if (Array.isArray(value)) return value.map(sortKeys);- if (typeof value !== "object" || value === null) return value;- const entries = Object.entries(value as Record<string, unknown>)- .filter(([, entry]) => entry !== undefined)- .sort(([left], [right]) => left.localeCompare(right));- return Object.fromEntries(entries.map(([key, entry]) => [key, sortKeys(entry)]));-}diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v1.ts b/packages/eve/src/execution/wire/session-inbox-wire.v1.tsdeleted file mode 100644index 7f5864f20..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.v1.ts+++ /dev/null@@ -1,302 +0,0 @@-import type { DataContent } from "ai";-import { z } from "#compiled/zod/index.js";--import type {- DeliverHookPayload,- SessionCommand,- SessionTimeoutHookPayload,- TurnCaller,-} from "#channel/types.js";-import { coalesceDeliverPayloads } from "#execution/deliver-payloads.js";-import { SessionInboxWireError } from "#execution/wire/session-inbox-contract.js";-import { inputRequestSchema, inputResponseSchema } from "#shared/input.js";-import { formatValidationError } from "#runtime/validation.js";-import { jsonObjectSchema, jsonValueSchema } from "#shared/json-schemas.js";-import { tokenUsageSchema } from "#shared/token-usage.js";-import type { TaskView } from "#tasks/types.js";--const providerOptionsSchema = z.record(z.string(), jsonObjectSchema);-const textPartSchema = z- .object({- providerOptions: providerOptionsSchema.optional(),- text: z.string(),- type: z.literal("text"),- })- .strict();-const binaryDataSchema = z.custom<DataContent | URL>(- (value) =>- typeof value === "string" ||- value instanceof Uint8Array ||- value instanceof ArrayBuffer ||- value instanceof URL,- "Expected a string, URL, Uint8Array, or ArrayBuffer.",-);-const imagePartSchema = z- .object({- image: binaryDataSchema,- mediaType: z.string().optional(),- providerOptions: providerOptionsSchema.optional(),- type: z.literal("image"),- })- .strict();-const filePartSchema = z- .object({- data: binaryDataSchema,- filename: z.string().optional(),- mediaType: z.string(),- providerOptions: providerOptionsSchema.optional(),- type: z.literal("file"),- })- .strict();-const userContentSchema = z.union([- z.string(),- z.array(z.discriminatedUnion("type", [textPartSchema, imagePartSchema, filePartSchema])),-]);--const eventCoordinateSchema = z.number().int().nonnegative();-const opaqueObjectSchema = z.custom<Record<string, unknown>>(- (value) => typeof value === "object" && value !== null && !Array.isArray(value),- "Expected an object.",-);-const subagentInputRequestHookPayloadSchema = z- .object({- callId: z.string(),- childContinuationToken: z.string(),- childSessionId: z.string(),- event: z- .object({- requests: z.array(inputRequestSchema),- sequence: eventCoordinateSchema,- stepIndex: eventCoordinateSchema,- turnId: z.string(),- })- .strict(),- kind: z.literal("subagent-input-request"),- subagentName: z.string(),- })- .strict();-const subagentAuthorizationEventHookPayloadSchema = z- .object({- callId: z.string(),- childSessionId: z.string(),- event: opaqueObjectSchema,- kind: z.literal("subagent-authorization-event"),- subagentName: z.string(),- })- .strict();-const taskMetadataSchema = z.union([- z- .object({- agentId: z.string(),- kind: z.literal("subagent"),- mode: z.enum(["local", "remote"]),- name: z.string(),- })- .strict(),- z.object({ kind: z.string(), name: z.string() }).strict(),-]);-const taskExecutorSchema = z- .object({- binding: z- .object({- data: z.record(z.string(), jsonValueSchema),- kind: z.string(),- })- .strict()- .optional(),- childSessionId: z.string().optional(),- childTurnId: z.string().optional(),- lifecycle: z.enum(["parked", "terminal"]).optional(),- })- .strict();-const taskViewBase = {- executor: taskExecutorSchema.optional(),- metadata: taskMetadataSchema,- taskId: z.string(),- usage: tokenUsageSchema.optional(),-};-const taskViewSchema: z.ZodType<TaskView> = z.discriminatedUnion("status", [- z.object({ ...taskViewBase, status: z.literal("working") }).strict(),- z- .object({- ...taskViewBase,- inputRequests: z.array(jsonValueSchema),- status: z.literal("input_required"),- })- .strict(),- z- .object({- ...taskViewBase,- lastOutput: z.object({ data: jsonValueSchema, type: z.literal("result") }).strict(),- status: z.literal("completed"),- })- .strict(),- z- .object({- ...taskViewBase,- lastOutput: z.object({ data: jsonValueSchema, type: z.literal("error") }).strict(),- status: z.literal("failed"),- })- .strict(),- z.object({ ...taskViewBase, status: z.literal("cancelled") }).strict(),-]);-const taskPayloadSchema = z- .object({- authorizationEvents: z- .array(- z- .object({- hookPayload: subagentAuthorizationEventHookPayloadSchema,- taskId: z.string(),- })- .strict(),- )- .optional(),- inputRequests: z- .array(- z- .object({ hookPayload: subagentInputRequestHookPayloadSchema, taskId: z.string() })- .strict(),- )- .optional(),- views: z.array(taskViewSchema).optional(),- })- .strict();--/**- * The complete eve-owned payload contract. Adapter fields are the explicit- * extension point and pass through unchanged; changing any declared field is- * a session-inbox wire-version change.- */-const deliverPayloadSchema = z- .object({- context: z.array(z.string()).optional(),- inputResponses: z.array(inputResponseSchema).optional(),- message: userContentSchema.optional(),- outputSchema: jsonObjectSchema.optional(),- task: taskPayloadSchema.optional(),- })- .loose();--const authSchema = z- .object({- attributes: z.record(z.string(), z.union([z.string(), z.array(z.string())])),- authenticator: z.string(),- issuer: z.string().optional(),- principalId: z.string(),- principalType: z.string(),- subject: z.string().optional(),- })- .strict();-const callerSchema = z- .object({- callId: z.string(),- replyTo: z.discriminatedUnion("kind", [- z.object({ kind: z.literal("hook"), token: z.string() }).strict(),- z.object({ kind: z.literal("callback"), token: z.string(), url: z.string() }).strict(),- ]),- subagentName: z.string(),- taskId: z.string().optional(),- })- .strict();-const callerProjectionSchema = callerSchema.strip();-const traceContextSchema = z- .object({ spanId: z.string(), traceFlags: z.number(), traceId: z.string() })- .strict();-const deliveryMetadataSchema = z- .object({- channelKind: z.string(),- channelName: z.string(),- deliveryId: z.string(),- payloadIndex: z.number().int().nonnegative(),- requestId: z.string().optional(),- requestTraceContext: traceContextSchema.optional(),- })- .strict();-const VERSION = 1;-const version = z.literal(VERSION);--/** The complete schema for persisted session-inbox wire version 1. */-export const sessionInboxWireV1Schema = z.discriminatedUnion("kind", [- z- .object({- auth: authSchema.nullable().optional(),- caller: callerSchema.optional(),- deliveryMetadata: z.array(deliveryMetadataSchema).optional(),- kind: z.literal("deliver"),- payload: deliverPayloadSchema.optional(),- payloads: z.array(deliverPayloadSchema),- requestId: z.string().optional(),- taskDeliveryId: z.string().optional(),- turnPolicy: z.enum(["queue", "steer"]).optional(),- version,- })- .strict(),- z.object({ kind: z.literal("session-timeout"), version }).strict(),- z.object({ kind: z.literal("clear"), version }).strict(),- z.object({ kind: z.literal("compact"), version }).strict(),- z.object({ kind: z.literal("reset"), reason: z.string().optional(), version }).strict(),- z- .object({- kind: z.literal("cancel"),- taskId: z.string().optional(),- turnId: z.string().optional(),- version,- })- .strict(),-]);--export type SessionInboxWireV1 = z.infer<typeof sessionInboxWireV1Schema>;--/** Builds and validates one complete version-1 wire value. */-export function encodeSessionCommandV1(- command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload,-): SessionInboxWireV1 {- const input = toV1Command(command);- const wire =- input.kind === "send"- ? {- auth: input.auth,- caller: input.caller,- deliveryMetadata:- input.delivery === undefined ? undefined : [{ ...input.delivery, payloadIndex: 0 }],- kind: "deliver" as const,- payload: input.payload,- payloads: [input.payload],- requestId: input.requestId,- taskDeliveryId: input.taskDeliveryId,- turnPolicy: input.turnPolicy,- version: VERSION,- }- : input.kind === "deliver"- ? {- ...input,- payload: coalesceDeliverPayloads(input.payloads),- version: VERSION,- }- : { ...input, version: VERSION };- const parsed = sessionInboxWireV1Schema.safeParse(wire);- if (!parsed.success) {- throw new SessionInboxWireError(- `Produced a session inbox payload that does not match wire version ${VERSION}: ${formatValidationError(parsed.error)}`,- );- }- return parsed.data;-}--function toV1Command(- command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload,-): DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload {- if (!("caller" in command) || command.caller === undefined) return command;- return { ...command, caller: toV1Caller(command.caller) };-}--function toV1Caller(caller: TurnCaller) {- const parsed = callerProjectionSchema.safeParse(caller);- if (!parsed.success) {- throw new SessionInboxWireError(- `Produced a session inbox payload that does not match wire version ${VERSION}: ${formatValidationError(parsed.error)}`,- );- }- return parsed.data;-}diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v2-migration.ts b/packages/eve/src/execution/wire/session-inbox-wire.v2-migration.tsdeleted file mode 100644index 572694f9d..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.v2-migration.ts+++ /dev/null@@ -1,25 +0,0 @@-import { isObject } from "#shared/guards.js";--/** Converts Workflow-VM records into this realm before wire consumption. */-export function normalizeSessionInboxWireV2(value: unknown, arrayFallback = false): unknown {- if (value === undefined) return arrayFallback ? null : undefined;- if (Array.isArray(value)) {- return value.map((item) => normalizeSessionInboxWireV2(item, true));- }- if (!isPlainRecord(value)) return value;- return Object.fromEntries(- Object.entries(value)- .filter((entry) => entry[1] !== undefined)- .map(([key, item]) => [key, normalizeSessionInboxWireV2(item)]),- );-}--function isPlainRecord(value: unknown): value is Record<string, unknown> {- if (!isObject(value)) return false;- const prototype = Object.getPrototypeOf(value);- return (- prototype === null ||- prototype === Object.prototype ||- Object.getPrototypeOf(prototype) === null- );-}diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v2.migration.test.ts b/packages/eve/src/execution/wire/session-inbox-wire.v2.migration.test.tsdeleted file mode 100644index 2a4b8cb01..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.v2.migration.test.ts+++ /dev/null@@ -1,43 +0,0 @@-import { describe, expect, it } from "vitest";--import { sessionInboxWireV1Migration } from "#execution/wire/session-inbox-wire.v2.migration.js";--describe("session inbox wire v2 migration", () => {- it("stamps controls with version 2", () => {- expect(sessionInboxWireV1Migration.migrate({ kind: "clear", version: 1 })).toEqual({- kind: "clear",- version: 2,- });- });-- it("adds the required payload mirror to v1 deliveries", () => {- expect(- sessionInboxWireV1Migration.migrate({- kind: "deliver",- payloads: [{ message: "legacy" }],- version: 1,- }),- ).toEqual({- kind: "deliver",- payload: {},- payloads: [{ message: "legacy" }],- version: 2,- });- });-- it("preserves an existing payload mirror", () => {- expect(- sessionInboxWireV1Migration.migrate({- kind: "deliver",- payload: { message: "legacy" },- payloads: [{ message: "legacy" }],- version: 1,- }),- ).toEqual({- kind: "deliver",- payload: { message: "legacy" },- payloads: [{ message: "legacy" }],- version: 2,- });- });-});diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v2.migration.ts b/packages/eve/src/execution/wire/session-inbox-wire.v2.migration.tsdeleted file mode 100644index b6ede102e..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.v2.migration.ts+++ /dev/null@@ -1,16 +0,0 @@-import type { VersionMigration } from "#execution/durable-session-migrations/chain.js";--/** Pure shape migration from the immutable v1 wire contract to v2. */-export const sessionInboxWireV1Migration: VersionMigration = {- from: 1,- migrate(prior) {- const value = prior as Record<string, unknown>;- const migrated: Record<string, unknown> & { readonly version: 2 } = {- ...value,- version: 2,- };- if (value.kind === "deliver" && !("payload" in value)) migrated.payload = {};- return migrated;- },- to: 2,-};diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v2.test.ts b/packages/eve/src/execution/wire/session-inbox-wire.v2.test.tsdeleted file mode 100644index 3dcac0a91..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.v2.test.ts+++ /dev/null@@ -1,243 +0,0 @@-import { runInNewContext } from "node:vm";--import { describe, expect, it } from "vitest";-import { z } from "#compiled/zod/index.js";--import { sessionInboxWire as sessionInboxWireEncoder } from "#execution/wire/session-inbox-encoder.js";-import { sessionInboxWire as sessionInboxWireDecoder } from "#execution/wire/session-inbox-wire.js";-import { sessionInboxWireV2Schema } from "#execution/wire/session-inbox-wire.v2.js";--const activityObserver = {- sink: { url: "https://example.com/eve/v1/activity/opaque-token", version: 1 as const },- workIdentity: {- callId: "call-1",- id: "work:call-1",- kind: "subagent" as const,- name: "researcher",- rootSessionId: "root",- rootTurnId: "turn",- },-};-const caller = {- activityObserver,- callId: "call-1",- replyTo: {- kind: "callback" as const,- token: "callback-token",- url: "https://example.com/callback",- },- subagentName: "researcher",-};--describe("session inbox wire v2", () => {- it("rejects empty deliveries", () => {- expect(() =>- sessionInboxWireDecoder.decode({ kind: "deliver", payloads: [], version: 2 }),- ).toThrowError();- });-- it("preserves activity observers for v2 consumers", () => {- const wire = sessionInboxWireEncoder.encode(- { caller, kind: "send", payload: { message: "observe" } },- { version: 2 },- );-- expect(wire).toMatchObject({ caller, version: 2 });- expect(sessionInboxWireDecoder.decode(JSON.parse(JSON.stringify(wire)))).toMatchObject({- caller,- kind: "deliver",- payloads: [{ message: "observe" }],- });- });-- it("round-trips task deliveries with activity observers", () => {- const task = {- views: [- {- metadata: {- agentId: "agent-1",- kind: "subagent" as const,- mode: "local" as const,- name: "researcher",- },- status: "working" as const,- taskId: "task-1",- },- ],- };- const wire = sessionInboxWireEncoder.encode(- { caller, kind: "deliver", payloads: [{ task }] },- { version: 2 },- );-- expect(sessionInboxWireDecoder.decode(JSON.parse(JSON.stringify(wire)))).toMatchObject({- caller,- kind: "deliver",- payloads: [{ task }],- });- });-- it("normalizes omitted task values to their JSON wire representation", () => {- const payload = {- task: {- inputRequests: [- {- hookPayload: {- callId: "call-1",- childContinuationToken: "continue-1",- childSessionId: "child-1",- event: {- requests: [- {- action: {- callId: "tool-1",- input: { marker: "FIRST", omitted: undefined },- kind: "tool-call",- toolName: "first_gate",- },- kind: "tool-approval",- prompt: "Approve first_gate?",- requestId: "request-1",- },- ],- sequence: 1,- stepIndex: 0,- turnId: "turn-1",- },- kind: "subagent-input-request",- subagentName: "researcher",- },- taskId: "task-1",- },- ],- views: [- {- lastOutput: { data: { omitted: undefined, status: "done" }, type: "result" },- metadata: { kind: "tool", name: "export" },- status: "completed",- taskId: "task-2",- },- ],- },- };- const wire = sessionInboxWireEncoder.encode({ kind: "send", payload } as never, { version: 2 });-- const expected = {- payloads: [- {- task: {- inputRequests: [- {- hookPayload: {- event: { requests: [{ action: { input: { marker: "FIRST" } } }] },- },- },- ],- views: [{ lastOutput: { data: { status: "done" } } }],- },- },- ],- };- expect(wire).toMatchObject(expected);- expect(sessionInboxWireDecoder.decode(wire)).toMatchObject(expected);- });-- it("normalizes plain records received from another VM realm", () => {- const data = runInNewContext(- `({ address: { sessionRef: "child" }, identity: { id: "agent" } })`,- );- const wire = sessionInboxWireEncoder.encode(- {- kind: "send",- payload: {- task: {- views: [- {- executor: { binding: { data, kind: "subagent" } },- metadata: { kind: "subagent", name: "worker" },- status: "working",- taskId: "task-1",- },- ],- },- },- } as never,- { version: 2 },- );-- expect(sessionInboxWireDecoder.decode(wire)).toMatchObject({- payloads: [- {- task: {- views: [- {- executor: {- binding: {- data: { address: { sessionRef: "child" }, identity: { id: "agent" } },- },- },- },- ],- },- },- ],- });- });-- it("omits activity observers for v1 consumers", () => {- const wire = sessionInboxWireEncoder.encode(- { caller, kind: "send", payload: { message: "legacy" } },- { version: 1 },- );-- expect(wire).toMatchObject({- caller: {- callId: "call-1",- replyTo: caller.replyTo,- subagentName: "researcher",- },- version: 1,- });- expect(wire).not.toHaveProperty("caller.activityObserver");- });-- it("migrates frozen v1 deliveries before decoding", () => {- expect(- sessionInboxWireDecoder.decode({- caller: {- callId: "call-1",- replyTo: caller.replyTo,- subagentName: "researcher",- },- kind: "deliver",- payloads: [{ message: "legacy" }],- version: 1,- }),- ).toMatchObject({- caller: {- callId: "call-1",- replyTo: caller.replyTo,- subagentName: "researcher",- },- kind: "deliver",- payloads: [{ message: "legacy" }],- });- });-- it("pins the complete schema byte for byte", () => {- expect(- stableStringify(- z.toJSONSchema(sessionInboxWireV2Schema, { io: "input", unrepresentable: "any" }),- ),- ).toMatchSnapshot();- });-});--function stableStringify(value: unknown): string {- return JSON.stringify(value, (_key, item) => {- if (item === null || typeof item !== "object" || Array.isArray(item)) return item;- return Object.fromEntries(- Object.entries(item).sort(([left], [right]) => left.localeCompare(right)),- );- });-}diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v2.ts b/packages/eve/src/execution/wire/session-inbox-wire.v2.tsdeleted file mode 100644index d4508182f..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.v2.ts+++ /dev/null@@ -1,91 +0,0 @@-import { z } from "#compiled/zod/index.js";--import type {- DeliverHookPayload,- SessionCommand,- SessionTimeoutHookPayload,-} from "#channel/types.js";-import { coalesceDeliverPayloads } from "#execution/deliver-payloads.js";-import { SessionInboxWireError } from "#execution/wire/session-inbox-contract.js";-import { sessionInboxWireV1Schema } from "#execution/wire/session-inbox-wire.v1.js";-import { normalizeSessionInboxWireV2 } from "#execution/wire/session-inbox-wire.v2-migration.js";-import { formatValidationError } from "#runtime/validation.js";--const activityWorkIdentitySchema = z- .object({- callId: z.string().optional(),- id: z.string(),- kind: z.enum(["root-turn", "subagent", "remote-agent", "task"]),- name: z.string().optional(),- parentId: z.string().optional(),- rootSessionId: z.string(),- rootTurnId: z.string(),- sessionId: z.string().optional(),- turnId: z.string().optional(),- })- .strict();-const activityObserverSchema = z- .object({- sink: z.object({ url: z.string(), version: z.literal(1) }).strict(),- workIdentity: activityWorkIdentitySchema.optional(),- })- .strict();-const v1 = sessionInboxWireV1Schema.options;-const v1Deliver = v1[0];-const v1Caller = v1Deliver.shape.caller.unwrap();-const version = z.literal(2);--/** Version 2 adds activity observer metadata to delegated callers. */-export const sessionInboxWireV2Schema = z.discriminatedUnion("kind", [- v1Deliver.extend({- caller: v1Caller.extend({ activityObserver: activityObserverSchema.optional() }).optional(),- payload: v1Deliver.shape.payload.unwrap(),- version,- }),- v1[1].extend({ version }),- v1[2].extend({ version }),- v1[3].extend({ version }),- v1[4].extend({ version }),- v1[5].extend({ version }),-]);--export type SessionInboxWireV2 = z.infer<typeof sessionInboxWireV2Schema>;--export function parseSessionInboxWireV2(value: unknown) {- return sessionInboxWireV2Schema.safeParse(normalizeSessionInboxWireV2(value));-}--/** Builds and validates one complete version-2 wire value. */-export function encodeSessionCommandV2(- command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload,-): SessionInboxWireV2 {- const wire =- command.kind === "send"- ? {- auth: command.auth,- caller: command.caller,- deliveryMetadata:- command.delivery === undefined ? undefined : [{ ...command.delivery, payloadIndex: 0 }],- kind: "deliver" as const,- payload: command.payload,- payloads: [command.payload],- requestId: command.requestId,- taskDeliveryId: command.taskDeliveryId,- turnPolicy: command.turnPolicy,- version: 2 as const,- }- : command.kind === "deliver"- ? {- ...command,- payload: coalesceDeliverPayloads(command.payloads),- version: 2 as const,- }- : { ...command, version: 2 as const };- const parsed = parseSessionInboxWireV2(wire);- if (!parsed.success) {- throw new SessionInboxWireError(- `Produced a session inbox payload that does not match wire version 2: ${formatValidationError(parsed.error)}`,- );- }- return parsed.data;-}diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v3.migration.test.ts b/packages/eve/src/execution/wire/session-inbox-wire.v3.migration.test.tsdeleted file mode 100644index daea1932a..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.v3.migration.test.ts+++ /dev/null@@ -1,28 +0,0 @@-import { describe, expect, it } from "vitest";--import { sessionInboxWireV2Migration } from "#execution/wire/session-inbox-wire.v3.migration.js";--describe("session inbox wire v3 migration", () => {- it("stamps controls with version 3", () => {- expect(sessionInboxWireV2Migration.migrate({ kind: "clear", version: 2 })).toEqual({- kind: "clear",- version: 3,- });- });-- it("preserves v2 deliveries without inventing deployment provenance", () => {- expect(- sessionInboxWireV2Migration.migrate({- kind: "deliver",- payload: { message: "legacy" },- payloads: [{ message: "legacy" }],- version: 2,- }),- ).toEqual({- kind: "deliver",- payload: { message: "legacy" },- payloads: [{ message: "legacy" }],- version: 3,- });- });-});diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v3.migration.ts b/packages/eve/src/execution/wire/session-inbox-wire.v3.migration.tsdeleted file mode 100644index f0817a52e..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.v3.migration.ts+++ /dev/null@@ -1,10 +0,0 @@-import type { VersionMigration } from "#execution/durable-session-migrations/chain.js";--/** Pure shape migration from the immutable v2 wire contract to v3. */-export const sessionInboxWireV2Migration: VersionMigration = {- from: 2,- migrate(prior) {- return { ...(prior as Record<string, unknown>), version: 3 };- },- to: 3,-};diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v3.test.ts b/packages/eve/src/execution/wire/session-inbox-wire.v3.test.tsdeleted file mode 100644index a8888c696..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.v3.test.ts+++ /dev/null@@ -1,108 +0,0 @@-import { describe, expect, it } from "vitest";-import { z } from "#compiled/zod/index.js";--import { sessionInboxWire as sessionInboxWireEncoder } from "#execution/wire/session-inbox-encoder.js";-import { sessionInboxWire as sessionInboxWireDecoder } from "#execution/wire/session-inbox-wire.js";-import { sessionInboxWireV0Migration } from "#execution/wire/session-inbox-wire.v0.js";-import { normalizeSessionInboxWireV2 } from "#execution/wire/session-inbox-wire.v2-migration.js";-import { sessionInboxWireV1Migration } from "#execution/wire/session-inbox-wire.v2.migration.js";-import { sessionInboxWireV3Schema } from "#execution/wire/session-inbox-wire.v3.js";--const delivery = {- acceptedDeploymentId: "dpl_current",- channelKind: "channel:webhook",- channelName: "webhook",- deliveryId: "delivery-1",-};--describe("session inbox wire v3", () => {- it("round-trips accepted deployment provenance", () => {- const wire = sessionInboxWireEncoder.encode(- { delivery, kind: "send", payload: { message: "hello" } },- { version: 3 },- );-- expect(wire).toMatchObject({- deliveryMetadata: [{ ...delivery, payloadIndex: 0 }],- version: 3,- });- expect(sessionInboxWireDecoder.decode(JSON.parse(JSON.stringify(wire)))).toMatchObject({- deliveryMetadata: [{ ...delivery, payloadIndex: 0 }],- kind: "deliver",- });- });-- it("omits deployment provenance for older versioned consumers", () => {- expect(- sessionInboxWireEncoder.encode(- { delivery, kind: "send", payload: { message: "hello" } },- { version: 2 },- ),- ).not.toHaveProperty("deliveryMetadata.0.acceptedDeploymentId");- });-- it("carries deployment provenance through the stable raw-send fast path", () => {- const wire = sessionInboxWireEncoder.encode(- { delivery, kind: "send", payload: { message: "hello" } },- { variant: "send", version: 0 },- );-- expect(wire).toMatchObject({ delivery, kind: "send" });- expect(sessionInboxWireDecoder.decode(JSON.parse(JSON.stringify(wire)))).toMatchObject({- deliveryMetadata: [{ ...delivery, payloadIndex: 0 }],- });- });-- it("keeps stable raw sends readable by previous v2 consumers", () => {- const wire = sessionInboxWireEncoder.encode(- { delivery, kind: "send", payload: { message: "hello" } },- { variant: "send", version: 0 },- );- const v1 = sessionInboxWireV0Migration.migrate(normalizeSessionInboxWireV2(wire));- const v2 = normalizeSessionInboxWireV2(sessionInboxWireV1Migration.migrate(v1));-- expect(v2).toMatchObject({- deliveryMetadata: [{ ...delivery, payloadIndex: 0 }],- kind: "deliver",- payloads: [{ message: "hello" }],- version: 2,- });- });-- it("migrates frozen v2 deliveries without inventing provenance", () => {- expect(- sessionInboxWireDecoder.decode({- kind: "deliver",- payload: { message: "legacy" },- payloads: [{ message: "legacy" }],- version: 2,- }),- ).toEqual({- auth: undefined,- caller: undefined,- deliveryMetadata: undefined,- kind: "deliver",- payloads: [{ message: "legacy" }],- requestId: undefined,- taskDeliveryId: undefined,- turnPolicy: undefined,- });- });-- it("pins the complete schema byte for byte", () => {- expect(- stableStringify(- z.toJSONSchema(sessionInboxWireV3Schema, { io: "input", unrepresentable: "any" }),- ),- ).toMatchSnapshot();- });-});--function stableStringify(value: unknown): string {- return JSON.stringify(value, (_key, item) => {- if (item === null || typeof item !== "object" || Array.isArray(item)) return item;- return Object.fromEntries(- Object.entries(item).sort(([left], [right]) => left.localeCompare(right)),- );- });-}diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v3.ts b/packages/eve/src/execution/wire/session-inbox-wire.v3.tsdeleted file mode 100644index 6f81e72fa..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.v3.ts+++ /dev/null@@ -1,73 +0,0 @@-import { z } from "#compiled/zod/index.js";--import type {- DeliverHookPayload,- SessionCommand,- SessionTimeoutHookPayload,-} from "#channel/types.js";-import { coalesceDeliverPayloads } from "#execution/deliver-payloads.js";-import { SessionInboxWireError } from "#execution/wire/session-inbox-contract.js";-import { normalizeSessionInboxWireV2 } from "#execution/wire/session-inbox-wire.v2-migration.js";-import { sessionInboxWireV2Schema } from "#execution/wire/session-inbox-wire.v2.js";-import { formatValidationError } from "#runtime/validation.js";--const v2 = sessionInboxWireV2Schema.options;-const v2Deliver = v2[0];-const v2DeliveryMetadata = v2Deliver.shape.deliveryMetadata.unwrap().element;-const version = z.literal(3);--/** Version 3 adds the trusted deployment that accepted each channel delivery. */-export const sessionInboxWireV3Schema = z.discriminatedUnion("kind", [- v2Deliver.extend({- deliveryMetadata: z- .array(v2DeliveryMetadata.extend({ acceptedDeploymentId: z.string().optional() }))- .optional(),- version,- }),- v2[1].extend({ version }),- v2[2].extend({ version }),- v2[3].extend({ version }),- v2[4].extend({ version }),- v2[5].extend({ version }),-]);--export type SessionInboxWireV3 = z.infer<typeof sessionInboxWireV3Schema>;--export function parseSessionInboxWireV3(value: unknown) {- return sessionInboxWireV3Schema.safeParse(normalizeSessionInboxWireV2(value));-}--/** Builds and validates one complete version-3 wire value. */-export function encodeSessionCommandV3(- command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload,-): SessionInboxWireV3 {- const wire =- command.kind === "send"- ? {- auth: command.auth,- caller: command.caller,- deliveryMetadata:- command.delivery === undefined ? undefined : [{ ...command.delivery, payloadIndex: 0 }],- kind: "deliver" as const,- payload: command.payload,- payloads: [command.payload],- requestId: command.requestId,- taskDeliveryId: command.taskDeliveryId,- turnPolicy: command.turnPolicy,- version: 3 as const,- }- : command.kind === "deliver"- ? {- ...command,- payload: coalesceDeliverPayloads(command.payloads),- version: 3 as const,- }- : { ...command, version: 3 as const };- const parsed = parseSessionInboxWireV3(wire);- if (!parsed.success) {- throw new SessionInboxWireError(- `Produced a session inbox payload that does not match wire version 3: ${formatValidationError(parsed.error)}`,- );- }- return parsed.data;-}diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v4.migration.test.ts b/packages/eve/src/execution/wire/session-inbox-wire.v4.migration.test.tsdeleted file mode 100644index c7af41e5d..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.v4.migration.test.ts+++ /dev/null@@ -1,93 +0,0 @@-import { describe, expect, it } from "vitest";--import { sessionInboxWireV3Migration } from "#execution/wire/session-inbox-wire.v4.migration.js";--describe("session inbox wire v4 migration", () => {- it("rejects malformed direct migration input", () => {- expect(() => sessionInboxWireV3Migration.migrate(null)).toThrow(- "session inbox wire v3 value is not an object",- );- });-- it("translates legacy task envelopes and preserves v3 provenance", () => {- const request = { kind: "question", prompt: "Continue?", requestId: "request-1" };- const authorization = {- callId: "call-1",- childSessionId: "child-1",- event: { type: "authorization.required" },- kind: "subagent-authorization-event",- subagentName: "research",- };- expect(- sessionInboxWireV3Migration.migrate({- deliveryMetadata: [- {- acceptedDeploymentId: "dpl_current",- channelKind: "channel:webhook",- channelName: "webhook",- deliveryId: "delivery-1",- payloadIndex: 0,- },- ],- kind: "deliver",- payload: {},- payloads: [- {- task: {- authorizationEvents: [{ hookPayload: authorization, taskId: "task-1" }],- inputRequests: [- {- hookPayload: {- childContinuationToken: "answer-hook",- event: { requests: [request], sequence: 2, stepIndex: 3, turnId: "turn-1" },- },- taskId: "task-1",- },- ],- views: [- {- executor: {- binding: { data: {}, kind: "subagent" },- childSessionId: "child-1",- lifecycle: "parked",- },- metadata: { kind: "subagent", name: "research" },- status: "working",- taskId: "task-1",- },- ],- },- },- ],- version: 3,- }),- ).toMatchObject({- deliveryMetadata: [{ acceptedDeploymentId: "dpl_current" }],- kind: "deliver",- payloads: [- {- task: {- authorizationEvents: [{ hookPayload: authorization, taskId: "task-1" }],- inputRequests: [- {- replyTo: "answer-hook",- request,- sequence: 2,- stepIndex: 3,- taskId: "task-1",- turnId: "turn-1",- },- ],- views: [- {- executor: { binding: { data: {}, kind: "subagent" } },- taskId: "task-1",- },- ],- },- },- ],- version: 4,- });- });-});diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v4.migration.ts b/packages/eve/src/execution/wire/session-inbox-wire.v4.migration.tsdeleted file mode 100644index a697f26a8..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.v4.migration.ts+++ /dev/null@@ -1,71 +0,0 @@-import type { VersionMigration } from "#execution/durable-session-migrations/chain.js";-import { isObject } from "#shared/guards.js";--/** Translates v3 task envelopes into typed workflow-run requests. */-export const sessionInboxWireV3Migration: VersionMigration = {- from: 3,- migrate(prior) {- if (!isObject(prior)) throw new Error("session inbox wire v3 value is not an object.");- if (prior.kind !== "deliver") return { ...prior, version: 4 };- return {- ...prior,- payload: migratePayload(prior.payload),- payloads: Array.isArray(prior.payloads) ? prior.payloads.map(migratePayload) : prior.payloads,- version: 4,- };- },- to: 4,-};--function migratePayload(payload: unknown): unknown {- if (!isObject(payload) || !isObject(payload.task)) return payload;- const task = payload.task;- return {- ...payload,- task: {- agentRequests: task.agentRequests,- authorizationEvents: task.authorizationEvents,- inputRequests: migrateInputRequests(task.inputRequests),- views: Array.isArray(task.views) ? task.views.map(migrateTaskView) : task.views,- },- };-}--function migrateInputRequests(value: unknown): unknown {- if (!Array.isArray(value)) return undefined;- return value.flatMap((entry) => {- if (!isObject(entry)) return [];- if ("request" in entry || "requests" in entry) return [entry];- if (!isObject(entry.hookPayload) || typeof entry.taskId !== "string") return [];- const hookPayload = entry.hookPayload;- const event = hookPayload.event;- if (- typeof hookPayload.childContinuationToken !== "string" ||- !isObject(event) ||- !Array.isArray(event.requests) ||- typeof event.sequence !== "number" ||- typeof event.stepIndex !== "number" ||- typeof event.turnId !== "string"- ) {- return [];- }- return event.requests.map((request) => ({- ...entry,- replyTo: hookPayload.childContinuationToken,- request,- sequence: event.sequence,- stepIndex: event.stepIndex,- taskId: entry.taskId,- turnId: event.turnId,- }));- });-}--function migrateTaskView(value: unknown): unknown {- if (!isObject(value) || !isObject(value.executor)) return value;- return {- ...value,- executor:- value.executor.binding === undefined ? undefined : { binding: value.executor.binding },- };-}diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v4.test.ts b/packages/eve/src/execution/wire/session-inbox-wire.v4.test.tsdeleted file mode 100644index 7c3be4d05..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.v4.test.ts+++ /dev/null@@ -1,183 +0,0 @@-import { describe, expect, it } from "vitest";-import { z } from "#compiled/zod/index.js";--import { sessionInboxWire } from "#execution/wire/session-inbox-encoder.js";-import { sessionInboxWire as sessionInboxWireDecoder } from "#execution/wire/session-inbox-wire.js";-import { sessionInboxWireV4Schema } from "#execution/wire/session-inbox-wire.v4.js";--const agentRequest = {- replyTo: "agent-reply",- request: {- input: { message: "Find it", target: "research" },- invocationId: "call-1:research",- kind: "agent-invoke" as const,- },- taskId: "task-1",-};-const authorizationEvent = {- hookPayload: {- callId: "call-1",- childSessionId: "child-1",- event: {- data: {- description: "Authorize Linear",- name: "linear",- sequence: 1,- stepIndex: 2,- turnId: "turn-child",- },- type: "authorization.required" as const,- },- kind: "subagent-authorization-event" as const,- subagentName: "research",- },- taskId: "task-1",-};-const inputRequest = {- replyTo: "answer-hook",- request: { kind: "question", prompt: "Continue?", requestId: "request-1" },- sequence: 2,- stepIndex: 3,- taskId: "task-1",- turnId: "turn-1",-};--describe("session inbox wire v4", () => {- it("round-trips task-owned agent requests, authorization events, and input requests", () => {- const task = {- agentRequests: [agentRequest],- authorizationEvents: [authorizationEvent],- inputRequests: [inputRequest],- };- const wire = sessionInboxWire.encode({ kind: "send", payload: { task } }, { version: 4 });-- expect(sessionInboxWireDecoder.decode(wire)).toMatchObject({- kind: "deliver",- payloads: [{ task }],- });- });-- it("rejects malformed task authorization events", () => {- expect(() =>- sessionInboxWire.encode(- {- kind: "send",- payload: {- task: { authorizationEvents: [{ hookPayload: { kind: "other" }, taskId: "task-1" }] },- } as never,- },- { version: 4 },- ),- ).toThrow(/wire version 4/);- });-- it.each([1, 2, 3] as const)("keeps v%i strict for task agent requests", (version) => {- expect(() =>- sessionInboxWire.encode(- { kind: "send", payload: { task: { agentRequests: [agentRequest] } } },- { version },- ),- ).toThrow(new RegExp(`wire version ${version}`));- });-- it.each([1, 2, 3] as const)(- "rejects v4 task agent requests falsely declared as immutable v%i",- (version) => {- expect(() =>- sessionInboxWireDecoder.decode({- kind: "deliver",- payload: { task: { agentRequests: [agentRequest] } },- payloads: [{ task: { agentRequests: [agentRequest] } }],- version,- }),- ).toThrow(new RegExp(`does not match wire version ${version}`));- },- );-- it.each([1, 2, 3] as const)(- "rejects v4 task input requests falsely declared as immutable v%i",- (version) => {- const { request: _request, ...inputRequestBase } = inputRequest;- for (const request of [inputRequest, { ...inputRequestBase, requests: [] }]) {- expect(() =>- sessionInboxWireDecoder.decode({- kind: "deliver",- payload: { task: { inputRequests: [request] } },- payloads: [{ task: { inputRequests: [request] } }],- version,- }),- ).toThrow(new RegExp(`does not match wire version ${version}`));- }- },- );-- it("round-trips batched task input requests", () => {- const { request: _request, ...batch } = inputRequest;- const batchedRequest = { ...batch, requests: [inputRequest.request] };-- expect(- sessionInboxWireDecoder.decode({- kind: "deliver",- payload: { task: { inputRequests: [batchedRequest] } },- payloads: [{ task: { inputRequests: [batchedRequest] } }],- version: 4,- }),- ).toMatchObject({- payloads: [{ task: { inputRequests: [batchedRequest] } }],- });- });-- it("carries current task messages through the stable raw-send fast path", () => {- const wire = sessionInboxWire.encode(- {- kind: "send",- payload: { task: { agentRequests: [agentRequest], inputRequests: [inputRequest] } },- },- { variant: "send", version: 0 },- );-- expect(wire).toMatchObject({- kind: "send",- payload: { task: { agentRequests: [agentRequest], inputRequests: [inputRequest] } },- });- expect(sessionInboxWireDecoder.decode(wire)).toMatchObject({- kind: "deliver",- payloads: [{ task: { agentRequests: [agentRequest], inputRequests: [inputRequest] } }],- });- });-- it("round-trips accepted deployment provenance", () => {- const delivery = {- acceptedDeploymentId: "dpl_current",- channelKind: "channel:webhook",- channelName: "webhook",- deliveryId: "delivery-1",- };- const wire = sessionInboxWire.encode(- { delivery, kind: "send", payload: { message: "hello" } },- { version: 4 },- );-- expect(sessionInboxWireDecoder.decode(wire)).toMatchObject({- deliveryMetadata: [{ ...delivery, payloadIndex: 0 }],- kind: "deliver",- });- });-- it("pins the complete schema byte for byte", () => {- expect(- stableStringify(- z.toJSONSchema(sessionInboxWireV4Schema, { io: "input", unrepresentable: "any" }),- ),- ).toMatchSnapshot();- });-});--function stableStringify(value: unknown): string {- return JSON.stringify(value, (_key, item) => {- if (item === null || typeof item !== "object" || Array.isArray(item)) return item;- return Object.fromEntries(- Object.entries(item).sort(([left], [right]) => left.localeCompare(right)),- );- });-}diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v4.ts b/packages/eve/src/execution/wire/session-inbox-wire.v4.tsdeleted file mode 100644index 3ae9e299f..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.v4.ts+++ /dev/null@@ -1,202 +0,0 @@-import { z } from "#compiled/zod/index.js";--import type {- DeliverHookPayload,- SessionCommand,- SessionTimeoutHookPayload,-} from "#channel/types.js";-import { coalesceDeliverPayloads } from "#execution/deliver-payloads.js";-import { SessionInboxWireError } from "#execution/wire/session-inbox-contract.js";-import { sessionInboxWireV3Schema } from "#execution/wire/session-inbox-wire.v3.js";-import { formatValidationError } from "#runtime/validation.js";-import { runtimeSubagentChildResultSchema } from "#shared/action-types.js";-import { jsonValueSchema } from "#shared/json-schemas.js";-import { tokenUsageSchema } from "#shared/token-usage.js";-import type { TaskView } from "#tasks/types.js";--const taskMetadataSchema = z- .object({- agentId: z.string().optional(),- kind: z.string(),- mode: z.enum(["local", "remote"]).optional(),- name: z.string(),- })- .strict();-const taskExecutorSchema = z- .object({- binding: z- .object({- data: z.record(z.string(), jsonValueSchema),- kind: z.string(),- })- .strict()- .optional(),- })- .strict();-const taskViewBase = {- executor: taskExecutorSchema.optional(),- metadata: taskMetadataSchema,- taskId: z.string(),- usage: tokenUsageSchema.optional(),-};-const taskViewSchema: z.ZodType<TaskView> = z.discriminatedUnion("status", [- z.object({ ...taskViewBase, status: z.literal("working") }).strict(),- z- .object({- ...taskViewBase,- inputRequests: z.array(jsonValueSchema),- status: z.literal("input_required"),- })- .strict(),- z- .object({- ...taskViewBase,- lastOutput: z.object({ data: jsonValueSchema, type: z.literal("result") }).strict(),- status: z.literal("completed"),- })- .strict(),- z- .object({- ...taskViewBase,- lastOutput: z.object({ data: jsonValueSchema, type: z.literal("error") }).strict(),- status: z.literal("failed"),- })- .strict(),- z.object({ ...taskViewBase, status: z.literal("cancelled") }).strict(),-]);-const eventCoordinateSchema = z.number().int().nonnegative();-const taskInputRequestBase = {- replyTo: z.string(),- sequence: eventCoordinateSchema,- stepIndex: eventCoordinateSchema,- taskId: z.string(),- turnId: z.string(),-};-const taskInputRequestSchema = z.union([- z- .object({- ...taskInputRequestBase,- request: jsonValueSchema,- })- .loose(),- z- .object({- ...taskInputRequestBase,- requests: z.array(jsonValueSchema),- })- .loose(),-]);-const agentInvocationInputSchema = z- .object({- agentId: z.string().optional(),- message: z.string(),- outputSchema: z.record(z.string(), jsonValueSchema).optional(),- target: z.string(),- })- .strict();-const taskAgentRequestSchema = z- .object({- replyTo: z.string(),- request: z.discriminatedUnion("kind", [- z- .object({- input: agentInvocationInputSchema,- invocationId: z.string(),- kind: z.literal("agent-invoke"),- })- .strict(),- z- .object({- kind: z.literal("agent-settled"),- result: runtimeSubagentChildResultSchema,- })- .strict(),- ]),- taskId: z.string(),- })- .strict();-const subagentAuthorizationEventHookPayloadSchema = z- .object({- callId: z.string(),- childSessionId: z.string(),- event: z.custom<Record<string, unknown>>(- (value) => typeof value === "object" && value !== null && !Array.isArray(value),- "Expected an object.",- ),- kind: z.literal("subagent-authorization-event"),- subagentName: z.string(),- })- .strict();-const taskAuthorizationEventSchema = z- .object({- hookPayload: subagentAuthorizationEventHookPayloadSchema,- taskId: z.string(),- })- .strict();-const taskPayloadV4Schema = z- .object({- agentRequests: z.array(taskAgentRequestSchema).optional(),- authorizationEvents: z.array(taskAuthorizationEventSchema).optional(),- inputRequests: z.array(taskInputRequestSchema).optional(),- views: z.array(taskViewSchema).optional(),- })- .strict();--const v3 = sessionInboxWireV3Schema.options;-const v3Deliver = v3[0];-const deliverPayloadV4Schema = v3Deliver.shape.payload.extend({- task: taskPayloadV4Schema.optional(),-});-const VERSION = 4;-const version = z.literal(VERSION);--/** Version 4 replaces executor-specific task envelopes with typed workflow-run requests. */-export const sessionInboxWireV4Schema = z.discriminatedUnion("kind", [- v3Deliver.extend({- payload: deliverPayloadV4Schema,- payloads: z.array(deliverPayloadV4Schema),- version,- }),- v3[1].extend({ version }),- v3[2].extend({ version }),- v3[3].extend({ version }),- v3[4].extend({ version }),- v3[5].extend({ version }),-]);--export type SessionInboxWireV4 = z.infer<typeof sessionInboxWireV4Schema>;--/** Builds and validates one complete version-4 wire value. */-export function encodeSessionCommandV4(- command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload,-): SessionInboxWireV4 {- const wire =- command.kind === "send"- ? {- auth: command.auth,- caller: command.caller,- deliveryMetadata:- command.delivery === undefined ? undefined : [{ ...command.delivery, payloadIndex: 0 }],- kind: "deliver" as const,- payload: command.payload,- payloads: [command.payload],- requestId: command.requestId,- taskDeliveryId: command.taskDeliveryId,- turnPolicy: command.turnPolicy,- version: VERSION,- }- : command.kind === "deliver"- ? {- ...command,- payload: coalesceDeliverPayloads(command.payloads),- version: VERSION,- }- : { ...command, version: VERSION };- const parsed = sessionInboxWireV4Schema.safeParse(wire);- if (!parsed.success) {- throw new SessionInboxWireError(- `Produced a session inbox payload that does not match wire version ${VERSION}: ${formatValidationError(parsed.error)}`,- );- }- return parsed.data;-}diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v5.migration.test.ts b/packages/eve/src/execution/wire/session-inbox-wire.v5.migration.test.tsdeleted file mode 100644index 8906b1a7d..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.v5.migration.test.ts+++ /dev/null@@ -1,27 +0,0 @@-import { describe, expect, it } from "vitest";--import { sessionInboxWireV4Migration } from "#execution/wire/session-inbox-wire.v5.migration.js";--describe("session inbox wire v5 migration", () => {- it("rejects malformed direct migration input", () => {- expect(() => sessionInboxWireV4Migration.migrate(null)).toThrow(- "session inbox wire v4 value is not an object",- );- });-- it("preserves a version-4 payload while advancing its version", () => {- expect(- sessionInboxWireV4Migration.migrate({- kind: "deliver",- payload: { message: "hello" },- payloads: [{ message: "hello" }],- version: 4,- }),- ).toEqual({- kind: "deliver",- payload: { message: "hello" },- payloads: [{ message: "hello" }],- version: 5,- });- });-});diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v5.migration.ts b/packages/eve/src/execution/wire/session-inbox-wire.v5.migration.tsdeleted file mode 100644index 0f618ac90..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.v5.migration.ts+++ /dev/null@@ -1,12 +0,0 @@-import type { VersionMigration } from "#execution/durable-session-migrations/chain.js";-import { isObject } from "#shared/guards.js";--/** Advances version-4 payloads to the additive token-cost schema. */-export const sessionInboxWireV4Migration: VersionMigration = {- from: 4,- migrate(prior) {- if (!isObject(prior)) throw new Error("session inbox wire v4 value is not an object.");- return { ...prior, version: 5 };- },- to: 5,-};diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v5.test.ts b/packages/eve/src/execution/wire/session-inbox-wire.v5.test.tsdeleted file mode 100644index c4e39a253..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.v5.test.ts+++ /dev/null@@ -1,230 +0,0 @@-import { describe, expect, it } from "vitest";-import { z } from "#compiled/zod/index.js";--import { sessionInboxWire } from "#execution/wire/session-inbox-encoder.js";-import { sessionInboxWire as sessionInboxWireDecoder } from "#execution/wire/session-inbox-wire.js";-import { sessionInboxWireV5Schema } from "#execution/wire/session-inbox-wire.v5.js";--const agentRequest = {- replyTo: "agent-reply",- request: {- input: { message: "Find it", target: "research" },- invocationId: "call-1:research",- kind: "agent-invoke" as const,- },- taskId: "task-1",-};-const authorizationEvent = {- hookPayload: {- callId: "call-1",- childSessionId: "child-1",- event: {- data: {- description: "Authorize Linear",- name: "linear",- sequence: 1,- stepIndex: 2,- turnId: "turn-child",- },- type: "authorization.required" as const,- },- kind: "subagent-authorization-event" as const,- subagentName: "research",- },- taskId: "task-1",-};-const inputRequest = {- replyTo: "answer-hook",- request: { kind: "question", prompt: "Continue?", requestId: "request-1" },- sequence: 2,- stepIndex: 3,- taskId: "task-1",- turnId: "turn-1",-};--describe("session inbox wire v5", () => {- it("round-trips task-owned agent requests, authorization events, and input requests", () => {- const task = {- agentRequests: [- agentRequest,- {- replyTo: "agent-reply",- request: {- kind: "agent-settled" as const,- result: {- callId: "call-1",- kind: "subagent-result" as const,- origin: "child" as const,- outcome: {- kind: "terminal" as const,- result: { kind: "succeeded" as const, output: "done" },- usageDelta: {- cacheReadTokens: 0,- cacheWriteTokens: 0,- costUsd: 0.25,- inputTokens: 10,- outputTokens: 2,- },- },- output: "done",- subagentName: "research",- },- },- taskId: "task-1",- },- ],- authorizationEvents: [authorizationEvent],- inputRequests: [inputRequest],- };- const wire = sessionInboxWire.encode({ kind: "send", payload: { task } }, { version: 5 });-- expect(sessionInboxWireDecoder.decode(wire)).toMatchObject({- kind: "deliver",- payloads: [{ task }],- });- });-- it("rejects malformed task authorization events", () => {- expect(() =>- sessionInboxWire.encode(- {- kind: "send",- payload: {- task: { authorizationEvents: [{ hookPayload: { kind: "other" }, taskId: "task-1" }] },- } as never,- },- { version: 5 },- ),- ).toThrow(/wire version 5/);- });-- it.each([1, 2, 3, 4] as const)("omits token cost for v%i consumers", (version) => {- const wire = sessionInboxWire.encode(- {- kind: "send",- payload: {- task: {- views: [- {- metadata: { kind: "subagent", name: "research" },- status: "working",- taskId: "task-1",- usage: {- cacheReadTokens: 0,- cacheWriteTokens: 0,- costUsd: 0.25,- inputTokens: 10,- outputTokens: 2,- },- },- ],- },- },- } as never,- { version },- ) as { payload: { task: { views: Array<{ usage: object }> } } };-- expect(wire.payload.task.views[0]?.usage).not.toHaveProperty("costUsd");- });-- it.each([1, 2, 3] as const)(- "rejects v5 task agent requests falsely declared as immutable v%i",- (version) => {- expect(() =>- sessionInboxWireDecoder.decode({- kind: "deliver",- payload: { task: { agentRequests: [agentRequest] } },- payloads: [{ task: { agentRequests: [agentRequest] } }],- version,- }),- ).toThrow(new RegExp(`does not match wire version ${version}`));- },- );-- it.each([1, 2, 3] as const)(- "rejects v5 task input requests falsely declared as immutable v%i",- (version) => {- const { request: _request, ...inputRequestBase } = inputRequest;- for (const request of [inputRequest, { ...inputRequestBase, requests: [] }]) {- expect(() =>- sessionInboxWireDecoder.decode({- kind: "deliver",- payload: { task: { inputRequests: [request] } },- payloads: [{ task: { inputRequests: [request] } }],- version,- }),- ).toThrow(new RegExp(`does not match wire version ${version}`));- }- },- );-- it("round-trips batched task input requests", () => {- const { request: _request, ...batch } = inputRequest;- const batchedRequest = { ...batch, requests: [inputRequest.request] };-- expect(- sessionInboxWireDecoder.decode({- kind: "deliver",- payload: { task: { inputRequests: [batchedRequest] } },- payloads: [{ task: { inputRequests: [batchedRequest] } }],- version: 5,- }),- ).toMatchObject({- payloads: [{ task: { inputRequests: [batchedRequest] } }],- });- });-- it("carries current task messages through the stable raw-send fast path", () => {- const wire = sessionInboxWire.encode(- {- kind: "send",- payload: { task: { agentRequests: [agentRequest], inputRequests: [inputRequest] } },- },- { variant: "send", version: 0 },- );-- expect(wire).toMatchObject({- kind: "send",- payload: { task: { agentRequests: [agentRequest], inputRequests: [inputRequest] } },- });- expect(sessionInboxWireDecoder.decode(wire)).toMatchObject({- kind: "deliver",- payloads: [{ task: { agentRequests: [agentRequest], inputRequests: [inputRequest] } }],- });- });-- it("round-trips accepted deployment provenance", () => {- const delivery = {- acceptedDeploymentId: "dpl_current",- channelKind: "channel:webhook",- channelName: "webhook",- deliveryId: "delivery-1",- };- const wire = sessionInboxWire.encode(- { delivery, kind: "send", payload: { message: "hello" } },- { version: 5 },- );-- expect(sessionInboxWireDecoder.decode(wire)).toMatchObject({- deliveryMetadata: [{ ...delivery, payloadIndex: 0 }],- kind: "deliver",- });- });-- it("pins the complete schema byte for byte", () => {- expect(- stableStringify(- z.toJSONSchema(sessionInboxWireV5Schema, { io: "input", unrepresentable: "any" }),- ),- ).toMatchSnapshot();- });-});--function stableStringify(value: unknown): string {- return JSON.stringify(value, (_key, item) => {- if (item === null || typeof item !== "object" || Array.isArray(item)) return item;- return Object.fromEntries(- Object.entries(item).sort(([left], [right]) => left.localeCompare(right)),- );- });-}diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v5.ts b/packages/eve/src/execution/wire/session-inbox-wire.v5.tsdeleted file mode 100644index 5acb0ecef..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.v5.ts+++ /dev/null@@ -1,231 +0,0 @@-import { z } from "#compiled/zod/index.js";--import type {- DeliverHookPayload,- SessionCommand,- SessionTimeoutHookPayload,-} from "#channel/types.js";-import { coalesceDeliverPayloads } from "#execution/deliver-payloads.js";-import { SessionInboxWireError } from "#execution/wire/session-inbox-contract.js";-import { sessionInboxWireV3Schema } from "#execution/wire/session-inbox-wire.v3.js";-import { formatValidationError } from "#runtime/validation.js";-import { jsonValueSchema } from "#shared/json-schemas.js";-import { tokenUsageWithCostSchema } from "#shared/token-usage.js";-import type { TaskView } from "#tasks/types.js";--const taskMetadataSchema = z- .object({- agentId: z.string().optional(),- kind: z.string(),- mode: z.enum(["local", "remote"]).optional(),- name: z.string(),- })- .strict();-const taskExecutorSchema = z- .object({- binding: z- .object({- data: z.record(z.string(), jsonValueSchema),- kind: z.string(),- })- .strict()- .optional(),- })- .strict();-const taskViewBase = {- executor: taskExecutorSchema.optional(),- metadata: taskMetadataSchema,- taskId: z.string(),- usage: tokenUsageWithCostSchema.optional(),-};-const taskViewSchema: z.ZodType<TaskView> = z.discriminatedUnion("status", [- z.object({ ...taskViewBase, status: z.literal("working") }).strict(),- z- .object({- ...taskViewBase,- inputRequests: z.array(jsonValueSchema),- status: z.literal("input_required"),- })- .strict(),- z- .object({- ...taskViewBase,- lastOutput: z.object({ data: jsonValueSchema, type: z.literal("result") }).strict(),- status: z.literal("completed"),- })- .strict(),- z- .object({- ...taskViewBase,- lastOutput: z.object({ data: jsonValueSchema, type: z.literal("error") }).strict(),- status: z.literal("failed"),- })- .strict(),- z.object({ ...taskViewBase, status: z.literal("cancelled") }).strict(),-]);-const eventCoordinateSchema = z.number().int().nonnegative();-const taskInputRequestBase = {- replyTo: z.string(),- sequence: eventCoordinateSchema,- stepIndex: eventCoordinateSchema,- taskId: z.string(),- turnId: z.string(),-};-const taskInputRequestSchema = z.union([- z- .object({- ...taskInputRequestBase,- request: jsonValueSchema,- })- .loose(),- z- .object({- ...taskInputRequestBase,- requests: z.array(jsonValueSchema),- })- .loose(),-]);-const agentInvocationInputSchema = z- .object({- agentId: z.string().optional(),- message: z.string(),- outputSchema: z.record(z.string(), jsonValueSchema).optional(),- target: z.string(),- })- .strict();-const agentTurnResultSchema = z.discriminatedUnion("kind", [- z.strictObject({ kind: z.literal("succeeded"), output: jsonValueSchema }),- z.strictObject({ error: jsonValueSchema, kind: z.literal("failed") }),- z.strictObject({ kind: z.literal("cancelled") }),-]);-const agentTurnOutcomeSchema = z.discriminatedUnion("kind", [- z.strictObject({- kind: z.literal("parked"),- result: agentTurnResultSchema,- usageDelta: tokenUsageWithCostSchema,- }),- z.strictObject({- kind: z.literal("terminal"),- result: agentTurnResultSchema,- usageDelta: tokenUsageWithCostSchema,- }),-]);-const runtimeSubagentChildResultSchema = z- .object({- backgroundTask: z.strictObject({ status: z.literal("working"), taskId: z.string() }).optional(),- callId: z.string(),- isError: z.boolean().optional(),- kind: z.literal("subagent-result"),- origin: z.literal("child"),- outcome: agentTurnOutcomeSchema,- output: jsonValueSchema,- subagentName: z.string(),- usage: tokenUsageWithCostSchema.optional(),- })- .strict();-const taskAgentRequestSchema = z- .object({- replyTo: z.string(),- request: z.discriminatedUnion("kind", [- z- .object({- input: agentInvocationInputSchema,- invocationId: z.string(),- kind: z.literal("agent-invoke"),- })- .strict(),- z- .object({- kind: z.literal("agent-settled"),- result: runtimeSubagentChildResultSchema,- })- .strict(),- ]),- taskId: z.string(),- })- .strict();-const subagentAuthorizationEventHookPayloadSchema = z- .object({- callId: z.string(),- childSessionId: z.string(),- event: z.custom<Record<string, unknown>>(- (value) => typeof value === "object" && value !== null && !Array.isArray(value),- "Expected an object.",- ),- kind: z.literal("subagent-authorization-event"),- subagentName: z.string(),- })- .strict();-const taskAuthorizationEventSchema = z- .object({- hookPayload: subagentAuthorizationEventHookPayloadSchema,- taskId: z.string(),- })- .strict();-const taskPayloadV5Schema = z- .object({- agentRequests: z.array(taskAgentRequestSchema).optional(),- authorizationEvents: z.array(taskAuthorizationEventSchema).optional(),- inputRequests: z.array(taskInputRequestSchema).optional(),- views: z.array(taskViewSchema).optional(),- })- .strict();--const v3 = sessionInboxWireV3Schema.options;-const v3Deliver = v3[0];-const deliverPayloadV5Schema = v3Deliver.shape.payload.extend({- task: taskPayloadV5Schema.optional(),-});-const VERSION = 5;-const version = z.literal(VERSION);--/** Version 5 adds model token cost to delegated usage reports. */-export const sessionInboxWireV5Schema = z.discriminatedUnion("kind", [- v3Deliver.extend({- payload: deliverPayloadV5Schema,- payloads: z.array(deliverPayloadV5Schema),- version,- }),- v3[1].extend({ version }),- v3[2].extend({ version }),- v3[3].extend({ version }),- v3[4].extend({ version }),- v3[5].extend({ version }),-]);--export type SessionInboxWireV5 = z.infer<typeof sessionInboxWireV5Schema>;--/** Builds and validates one complete version-5 wire value. */-export function encodeSessionCommandV5(- command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload,-): SessionInboxWireV5 {- const wire =- command.kind === "send"- ? {- auth: command.auth,- caller: command.caller,- deliveryMetadata:- command.delivery === undefined ? undefined : [{ ...command.delivery, payloadIndex: 0 }],- kind: "deliver" as const,- payload: command.payload,- payloads: [command.payload],- requestId: command.requestId,- taskDeliveryId: command.taskDeliveryId,- turnPolicy: command.turnPolicy,- version: VERSION,- }- : command.kind === "deliver"- ? {- ...command,- payload: coalesceDeliverPayloads(command.payloads),- version: VERSION,- }- : { ...command, version: VERSION };- const parsed = sessionInboxWireV5Schema.safeParse(wire);- if (!parsed.success) {- throw new SessionInboxWireError(- `Produced a session inbox payload that does not match wire version ${VERSION}: ${formatValidationError(parsed.error)}`,- );- }- return parsed.data;-}diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v6.test.ts b/packages/eve/src/execution/wire/session-inbox-wire.v6.test.tsdeleted file mode 100644index e120cedfc..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.v6.test.ts+++ /dev/null@@ -1,57 +0,0 @@-import { describe, expect, it } from "vitest";--import { sessionInboxWire } from "#execution/wire/session-inbox-encoder.js";-import { SessionInboxWireError } from "#execution/wire/session-inbox-contract.js";-import { sessionInboxWire as sessionInboxWireDecoder } from "#execution/wire/session-inbox-wire.js";-import { sessionInboxWireV6Schema } from "#execution/wire/session-inbox-wire.v6.js";--describe("session inbox wire v6", () => {- it("round-trips session-owned task cancellation", () => {- const wire = sessionInboxWire.encode(- { kind: "cancel", tasks: true, turnId: "turn_1" },- { version: 6 },- );-- expect(wire).toEqual({ kind: "cancel", tasks: true, turnId: "turn_1", version: 6 });- expect(sessionInboxWireDecoder.decode(wire)).toEqual({- kind: "cancel",- taskId: undefined,- tasks: true,- turnId: "turn_1",- });- });-- it("keeps the v6 cancel schema strict", () => {- expect(- sessionInboxWireV6Schema.safeParse({ kind: "cancel", tasks: "true", version: 6 }).success,- ).toBe(false);- expect(- sessionInboxWireV6Schema.safeParse({ extra: true, kind: "cancel", version: 6 }).success,- ).toBe(false);- });-- it.each([- { variant: "deliver", version: 0 } as const,- { variant: "send", version: 0 } as const,- { version: 1 } as const,- { version: 2 } as const,- { version: 3 } as const,- { version: 4 } as const,- { version: 5 } as const,- ])("fails closed when encoding tasks:true for old target %o", (target) => {- expect(() => sessionInboxWire.encode({ kind: "cancel", tasks: true }, target)).toThrowError(- SessionInboxWireError,- );- });-- it.each([1, 2, 3, 4, 5] as const)(- "preserves ordinary cancellation for v%i consumers",- (version) => {- expect(sessionInboxWire.encode({ kind: "cancel", turnId: "turn_1" }, { version })).toEqual({- kind: "cancel",- turnId: "turn_1",- version,- });- },- );-});diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v6.ts b/packages/eve/src/execution/wire/session-inbox-wire.v6.tsdeleted file mode 100644index c1f0fee32..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.v6.ts+++ /dev/null@@ -1,57 +0,0 @@-import { z } from "#compiled/zod/index.js";--import type {- DeliverHookPayload,- SessionCommand,- SessionTimeoutHookPayload,-} from "#channel/types.js";-import { SessionInboxWireError } from "#execution/wire/session-inbox-contract.js";-import {- encodeSessionCommandV5,- sessionInboxWireV5Schema,-} from "#execution/wire/session-inbox-wire.v5.js";-import { formatValidationError } from "#runtime/validation.js";--const v5 = sessionInboxWireV5Schema.options;-const v5Cancel = v5[5];-const VERSION = 6;-const version = z.literal(VERSION);--/** Version 6 adds session-owned task cancellation to the cancel command. */-export const sessionInboxWireV6Schema = z.discriminatedUnion("kind", [- v5[0].extend({ version }),- v5[1].extend({ version }),- v5[2].extend({ version }),- v5[3].extend({ version }),- v5[4].extend({ version }),- v5Cancel.extend({ tasks: z.boolean().optional(), version }),-]);--export type SessionInboxWireV6 = z.infer<typeof sessionInboxWireV6Schema>;--/** Builds and validates one complete version-6 wire value. */-export function encodeSessionCommandV6(- command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload,-): SessionInboxWireV6 {- const v5Command = withoutOwnedTaskCancellation(command);- const value: Record<string, unknown> = {- ...encodeSessionCommandV5(v5Command),- version: VERSION,- };- if (command.kind === "cancel") value.tasks = command.tasks;- const parsed = sessionInboxWireV6Schema.safeParse(value);- if (!parsed.success) {- throw new SessionInboxWireError(- `Produced a session inbox payload that does not match wire version ${VERSION}: ${formatValidationError(parsed.error)}`,- );- }- return parsed.data;-}--function withoutOwnedTaskCancellation(- command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload,-): DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload {- if (command.kind !== "cancel" || command.tasks === undefined) return command;- const { tasks: _tasks, ...v5 } = command;- return v5;-}diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v7.test.ts b/packages/eve/src/execution/wire/session-inbox-wire.v7.test.tsdeleted file mode 100644index 47868e086..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.v7.test.ts+++ /dev/null@@ -1,64 +0,0 @@-import { describe, expect, it } from "vitest";--import { sessionInboxWire } from "#execution/wire/session-inbox-encoder.js";-import { sessionInboxWire as sessionInboxWireDecoder } from "#execution/wire/session-inbox-wire.js";-import { sessionInboxWireV7Schema } from "#execution/wire/session-inbox-wire.v7.js";--const caller = {- activityObserver: {- sink: { url: "https://example.com/eve/v1/activity/opaque-token", version: 1 as const },- workIdentity: {- callId: "call-1",- id: "work:call-1",- kind: "task" as const,- label: "Investigator",- name: "researcher",- rootSessionId: "root",- rootTurnId: "turn",- },- },- callId: "call-1",- replyTo: {- kind: "callback" as const,- token: "callback-token",- url: "https://example.com/callback",- },- subagentName: "researcher",-};--describe("session inbox wire v7", () => {- it("round-trips delegated activity labels", () => {- const wire = sessionInboxWire.encode(- { caller, kind: "send", payload: { message: "observe" } },- { version: 7 },- );-- expect(wire).toMatchObject({ caller, version: 7 });- expect(sessionInboxWireDecoder.decode(JSON.parse(JSON.stringify(wire)))).toMatchObject({- caller,- kind: "deliver",- payloads: [{ message: "observe" }],- });- });-- it.each([1, 2, 3, 4, 5, 6] as const)("omits activity labels for v%i consumers", (version) => {- const wire = sessionInboxWire.encode(- { caller, kind: "send", payload: { message: "observe" } },- { version },- );-- expect(wire).not.toHaveProperty("caller.activityObserver.workIdentity.label");- });-- it("keeps the v7 deliver schema strict", () => {- expect(- sessionInboxWireV7Schema.safeParse({- caller: { ...caller, activityObserver: { ...caller.activityObserver, extra: true } },- kind: "deliver",- payload: {},- payloads: [{}],- version: 7,- }).success,- ).toBe(false);- });-});diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v7.ts b/packages/eve/src/execution/wire/session-inbox-wire.v7.tsdeleted file mode 100644index 51b84ef39..000000000--- a/packages/eve/src/execution/wire/session-inbox-wire.v7.ts+++ /dev/null@@ -1,99 +0,0 @@-import { z } from "#compiled/zod/index.js";--import type {- DeliverHookPayload,- SessionCommand,- SessionTimeoutHookPayload,-} from "#channel/types.js";-import { SessionInboxWireError } from "#execution/wire/session-inbox-contract.js";-import {- encodeSessionCommandV6,- sessionInboxWireV6Schema,-} from "#execution/wire/session-inbox-wire.v6.js";-import { formatValidationError } from "#runtime/validation.js";--const v6 = sessionInboxWireV6Schema.options;-const v6Deliver = v6[0];-const v6Caller = v6Deliver.shape.caller.unwrap();-const v6ActivityObserver = v6Caller.shape.activityObserver.unwrap();-const v6WorkIdentity = v6ActivityObserver.shape.workIdentity.unwrap();-const VERSION = 7;-const version = z.literal(VERSION);--/** Version 7 adds optional presentation labels to delegated activity work. */-export const sessionInboxWireV7Schema = z.discriminatedUnion("kind", [- v6Deliver.extend({- caller: v6Caller- .extend({- activityObserver: v6ActivityObserver- .extend({- workIdentity: v6WorkIdentity.extend({ label: z.string().optional() }).optional(),- })- .optional(),- })- .optional(),- version,- }),- v6[1].extend({ version }),- v6[2].extend({ version }),- v6[3].extend({ version }),- v6[4].extend({ version }),- v6[5].extend({ version }),-]);--export type SessionInboxWireV7 = z.infer<typeof sessionInboxWireV7Schema>;--/** Builds and validates one complete version-7 wire value. */-export function encodeSessionCommandV7(- command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload,-): SessionInboxWireV7 {- const label = readActivityLabel(command);- const encoded = encodeSessionCommandV6(withoutActivityLabel(command));- const value =- label === undefined || encoded.kind !== "deliver" || encoded.caller === undefined- ? { ...encoded, version: VERSION }- : {- ...encoded,- caller: {- ...encoded.caller,- activityObserver: {- ...encoded.caller.activityObserver!,- workIdentity: { ...encoded.caller.activityObserver!.workIdentity!, label },- },- },- version: VERSION,- };- const parsed = sessionInboxWireV7Schema.safeParse(value);- if (!parsed.success) {- throw new SessionInboxWireError(- `Produced a session inbox payload that does not match wire version ${VERSION}: ${formatValidationError(parsed.error)}`,- );- }- return parsed.data;-}--function readActivityLabel(- command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload,-): string | undefined {- return command.kind === "send" || command.kind === "deliver"- ? command.caller?.activityObserver?.workIdentity?.label- : undefined;-}--function withoutActivityLabel(- command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload,-): DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload {- if (- (command.kind !== "send" && command.kind !== "deliver") ||- command.caller?.activityObserver?.workIdentity?.label === undefined- )- return command;- const { label: _label, ...workIdentity } = command.caller.activityObserver.workIdentity;- return {- ...command,- caller: {- ...command.caller,- activityObserver: { ...command.caller.activityObserver, workIdentity },- },- };-}diff --git a/packages/eve/src/execution/workflow-entry-crash.ts b/packages/eve/src/execution/workflow-entry-crash.tsdeleted file mode 100644index 03106d193..000000000--- a/packages/eve/src/execution/workflow-entry-crash.ts+++ /dev/null@@ -1,90 +0,0 @@-import type { TurnCaller } from "#channel/types.js";-import type { DurableSessionState } from "#execution/durable-session-store.js";-import { resolveInitialTurnCallerStep } from "#subagents/parent-notification.js";--const SAFE_OUTER_WORKFLOW_FAILURE_MESSAGE =- "Agent workflow failed. Inspect the private session trace for details.";--/**- * Write-through cell owned by `workflowEntry`: written- * unconditionally by the driver loop as turns advance, read only by the- * outer catch. When the loop throws, its locals are unreachable, so this- * cell is the crash path's only view of values that changed after turn 1.- *- * Reach for this cell only when all three hold for a value:- * 1. it is produced or replaced inside the driver loop, so the entry- * function's own locals go stale;- * 2. it travels by value inside Workflow step results — there is no- * store the catch could re-read it from at crash time;- * 3. the crash path needs its latest value to discharge a cleanup- * obligation.- * If any of the three fails, read the value from where it already lives- * instead of mirroring it here.- */-export interface CrashCleanupState {- // The caller whose awaited reply is still unsettled, so the catch can- // reject it with the error instead of leaving it parked forever.- // Populated for every session; only conversation-mode paths read it.- caller: TurnCaller | undefined;- // Whether `resolveInitialTurnCallerStep` has run. `caller: undefined` is- // ambiguous on its own: it also means "resolved and later cleared because- // its reply settled". This flag lets the crash path tell that apart from- // "crashed before the caller was ever resolved", where a delegated caller- // may still be parked on this session's reply.- callerResolved: boolean;- // The latest snapshot the driver has received, so the catch can- // terminate children adopted after turn 1. Honest staleness window: the- // driver only sees state at turn boundaries, so children dispatched by a- // turn that crashed mid-flight are absent from this snapshot and escape- // crash cleanup.- lastSessionState: DurableSessionState | undefined;- // The latest context adopted from a completed turn, which carries provider- // and trace state needed by terminal instrumentation.- serializedContext: Record<string, unknown>;- // Whether the session already emitted a terminal protocol and instrumentation- // event (set here on the crash path, or by the finalization steps via- // `terminalState`), so later callback or teardown failures cannot contradict it.- terminalEmitted: boolean;- // The most recently dispatched turn, derived from the dispatch index so the- // durable workflow body does not import the harness. Never cleared on settle:- // a crash between turns is attributed to the last dispatched turn.- turnId?: string;-}--export function hasDelegatedCallerContext(serializedContext: Record<string, unknown>): boolean {- if (serializedContext["eve.sessionCallback"] !== undefined) return true;- const channel = serializedContext["eve.channel"];- return (- typeof channel === "object" && channel !== null && Reflect.get(channel, "kind") === "subagent"- );-}--/**- * Caller to reject from the crash path. Normally the resolved cell value —- * including `undefined` after a settled reply cleared it, when there is- * nothing left to notify. When the crash happened before- * `resolveInitialTurnCallerStep` ever ran (e.g. `createSessionStep` threw),- * the cell is empty even though a delegated caller may be parked on this- * session's reply, so the caller is re-resolved from the serialized context- * — which needs nothing from the failed steps. Best-effort: when resolution- * fails again there is no reachable caller to notify.- */-export async function resolveCallerForCrash(- state: CrashCleanupState,- serializedContext: Record<string, unknown>,-): Promise<TurnCaller | undefined> {- if (state.callerResolved) {- return state.caller;- }- try {- return await resolveInitialTurnCallerStep({ serializedContext });- } catch {- return undefined;- }-}--export function createSafeOuterWorkflowError(): Error {- const error = new Error(SAFE_OUTER_WORKFLOW_FAILURE_MESSAGE);- error.name = "EveWorkflowFailure";- return error;-}diff --git a/packages/eve/src/execution/workflow-entry-finalization.ts b/packages/eve/src/execution/workflow-entry-finalization.tsdeleted file mode 100644index 463ba4cbc..000000000--- a/packages/eve/src/execution/workflow-entry-finalization.ts+++ /dev/null@@ -1,102 +0,0 @@-import type { TurnCaller } from "#channel/types.js";-import { notifyDelegatedParentStep, notifyTurnCallerStep } from "#subagents/parent-notification.js";-import {- createDelegatedSubagentErrorResult,- createDelegatedSubagentSuccessResult,-} from "#subagents/parent-result.js";-import type { DurableSessionState } from "#execution/durable-session-store.js";-import type { NextDriverAction } from "#execution/next-driver-action.js";-import { fireSessionCallbackStep } from "#subagents/callback-step.js";-import { emitTerminalSessionCompletionStep } from "#execution/terminal-session-completion-step.js";-import { terminateChildSessionsStep } from "#execution/terminate-child-sessions-step.js";-import type { RunMode } from "#shared/run-mode.js";-import type { TokenUsage } from "#shared/token-usage.js";--export async function finalizeExpiredSession(input: {- readonly caller: TurnCaller | undefined;- readonly driverWritable: WritableStream<Uint8Array>;- readonly mode: RunMode;- readonly serializedContext: Record<string, unknown>;- readonly sessionState: DurableSessionState;- readonly terminalState?: { terminalEmitted: boolean };-}): Promise<{ readonly output: unknown }> {- await terminateChildSessionsStep({- serializedContext: input.serializedContext,- sessionState: input.sessionState,- });- await emitTerminalSessionCompletionStep({- parentWritable: input.driverWritable,- serializedContext: input.serializedContext,- });- if (input.terminalState !== undefined) input.terminalState.terminalEmitted = true;-- if (input.mode === "task") {- await fireSessionCallbackStep({- output: "",- serializedContext: input.serializedContext,- status: "completed",- });- await notifyDelegatedParentStep({- result: createDelegatedSubagentSuccessResult(input.serializedContext, ""),- serializedContext: input.serializedContext,- });- } else if (input.caller !== undefined) {- await notifyTurnCallerStep({- caller: input.caller,- lifecycle: "terminal",- sessionId: input.sessionState.sessionId,- settled: { output: "" },- });- }- return { output: "" };-}--export async function finalizeDone(input: {- readonly action: NextDriverAction & { readonly kind: "done" };- readonly caller: TurnCaller | undefined;- readonly mode: RunMode;- readonly terminalState?: { terminalEmitted: boolean };-}): Promise<{ readonly output: unknown }> {- const { output, serializedContext } = input.action;- const failed = input.action.isError === true;-- await terminateChildSessionsStep({- serializedContext,- sessionState: input.action.sessionState,- });- if (input.terminalState !== undefined) input.terminalState.terminalEmitted = true;- if (input.mode === "task") {- await fireSessionCallbackStep({- error: failed ? output : undefined,- output: failed ? undefined : output,- serializedContext,- status: failed ? "failed" : "completed",- usage: input.action.usage,- });- await notifyDelegatedParentStep({- result: failed- ? createDelegatedSubagentErrorResult(serializedContext, output)- : createDelegatedSubagentSuccessResult(serializedContext, output),- serializedContext,- usage: input.action.usage,- });- } else {- const settled: {- isError?: boolean;- output: unknown;- usage?: TokenUsage;- } = { output, usage: input.action.usageDelta };- if (failed) {- settled.isError = true;- }- if (input.caller !== undefined) {- await notifyTurnCallerStep({- caller: input.caller,- lifecycle: "terminal",- sessionId: input.action.sessionState.sessionId,- settled,- });- }- }- return { output };-}diff --git a/packages/eve/src/execution/workflow-entry.test.ts b/packages/eve/src/execution/workflow-entry.test.tsdeleted file mode 100644index 0b9eb5ff0..000000000--- a/packages/eve/src/execution/workflow-entry.test.ts+++ /dev/null@@ -1,2002 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { createHook } from "#compiled/@workflow/core/index.js";-import { resumeHook } from "#internal/workflow/runtime.js";--import type { HookPayload } from "#channel/types.js";-import { ChannelRequestIdKey } from "#context/keys.js";-import { createSessionStep } from "#execution/create-session-step.js";-import {- bindTurnCallerContextStep,- notifyCancelledTaskCallerStep,- notifyDelegatedParentStep,- notifyTurnCallerStep,- resolveInitialTurnCallerStep,-} from "#subagents/parent-notification.js";-import type { DurableSessionState } from "#execution/durable-session-store.js";-import { dispatchTurnStep } from "#execution/dispatch-turn-step.js";-import { fireSessionCallbackStep } from "#subagents/callback-step.js";-import { emitTerminalSessionCompletionStep } from "#execution/terminal-session-completion-step.js";-import {- createSessionTimeoutControl,- type SessionTimeoutControl,-} from "#execution/session-timeout-control.js";-import { terminateChildSessionsStep } from "#execution/terminate-child-sessions-step.js";-import type { TurnControlPayload } from "#execution/turn-control-protocol.js";-import { workflowEntry } from "#execution/workflow-entry.js";-import { routeDeliverToChildren } from "#execution/route-child-delivery.js";-import { settleCancelledTurnStep } from "#execution/settle-cancelled-turn-step.js";-import { emitTerminalSessionFailureStep } from "#execution/terminal-session-failure-step.js";-import type { SessionInboxPayload } from "#execution/session-command-inbox.js";-import { sessionCommandHookToken } from "#execution/session-command-token.js";-import { SESSION_INBOX_WIRE_VERSION } from "#execution/wire/session-inbox-contract.js";-import { settleContinuationConflictStep } from "#execution/continuation-conflict-step.js";--vi.mock("#compiled/@workflow/core/index.js", () => ({- createHook: vi.fn(),- defineHook: () => ({- create: (options?: { readonly token?: string }) => ({- [Symbol.asyncIterator]: () => ({ next: () => new Promise(() => {}) }),- dispose: async () => {},- getConflict: async () => null,- token: options?.token ?? "hook",- }),- resume: async () => null,- }),- getWorkflowMetadata: vi.fn(() => ({- url: "https://eve.example.com",- workflowRunId: "wrun_test_123",- workflowStartedAt: new Date("2026-01-01T00:00:00.000Z"),- })),- getWritable: vi.fn(- () =>- new WritableStream<Uint8Array>({- write() {},- }),- ),-}));--vi.mock("#compiled/@workflow/core/runtime.js", () => ({- resumeHook: vi.fn(),-}));--vi.mock("./create-session-step.js", () => ({- createSessionStep: vi.fn().mockResolvedValue(- createSessionStepResultForMock(- createSessionStateForMock({- continuationToken: "http:test",- sessionId: "wrun_test_123",- }),- ),- ),-}));--vi.mock("./route-child-delivery.js", () => ({- routeDeliverToChildren: vi- .fn()- .mockImplementation(async ({ delivery, serializedContext = {}, sessionState }) => ({- kind: "continue",- remainder: delivery,- serializedContext,- sessionState,- })),-}));--vi.mock("../subagents/parent-notification.js", () => ({- bindTurnCallerContextStep: vi- .fn()- .mockImplementation(async ({ serializedContext }) => serializedContext),- notifyCancelledTaskCallerStep: vi.fn().mockResolvedValue(undefined),- notifyDelegatedParentStep: vi.fn().mockResolvedValue(undefined),- notifyTurnCallerStep: vi.fn().mockResolvedValue(undefined),- resolveInitialTurnCallerStep: vi.fn().mockResolvedValue(undefined),-}));--vi.mock("./terminate-child-sessions-step.js", () => ({- terminateChildSessionsStep: vi.fn().mockResolvedValue(undefined),-}));--vi.mock("./dispatch-turn-step.js", () => ({- dispatchTurnStep: vi.fn().mockImplementation(async () => ({ runId: "turn-run" })),-}));--vi.mock("./terminal-session-failure-step.js", () => ({- emitTerminalSessionFailureStep: vi.fn().mockResolvedValue(undefined),-}));--vi.mock("./terminal-session-completion-step.js", () => ({- emitTerminalSessionCompletionStep: vi.fn().mockResolvedValue(undefined),-}));--vi.mock("./settle-cancelled-turn-step.js", () => ({- settleCancelledTurnStep: vi.fn().mockResolvedValue(undefined),-}));--vi.mock("./session-timeout-control.js", () => ({- createSessionTimeoutControl: vi.fn(),-}));--vi.mock("./continuation-conflict-step.js", () => ({- settleContinuationConflictStep: vi.fn().mockResolvedValue(undefined),-}));--function createSessionStateForMock(- overrides: Partial<DurableSessionState> = {},-): DurableSessionState {- return {- continuationToken: "http:test",- emissionState: { sequence: 0, sessionStarted: false, stepIndex: 0, turnId: "" },- hasProxyInputRequests: false,- sessionId: "wrun_test_123",- version: 1,- ...overrides,- };-}--function createSessionStepResultForMock(state: DurableSessionState) {- return {- identity: { agentId: "test-agent", nodeId: "$root" },- state,- };-}--vi.mock("../subagents/callback-step.js", () => ({- fireSessionCallbackStep: vi.fn().mockResolvedValue(undefined),-}));--interface DeliveryHookConfig {- readonly dispose?: () => void;- readonly getConflict?: () => Promise<{ readonly runId: string } | null>;- readonly next?: () => Promise<IteratorResult<SessionInboxPayload>>;- readonly return?: () => Promise<IteratorResult<SessionInboxPayload>>;- readonly token: string;- readonly values?: readonly SessionInboxPayload[];-}--interface AuthHookConfig {- readonly dispose?: () => void;- readonly getConflict?: () => Promise<{ readonly runId: string } | null>;- readonly return?: () => Promise<IteratorResult<HookPayload>>;-}--describe("workflowEntry", () => {- beforeEach(() => {- vi.stubEnv("VERCEL_PROJECT_PRODUCTION_URL", "");- vi.stubEnv("VERCEL_ENV", "");- vi.mocked(createSessionTimeoutControl).mockReturnValue(createTimeoutControl());- });-- afterEach(() => {- vi.clearAllMocks();- vi.unstubAllEnvs();- });-- it("injects the workflow run id as the canonical session id before the first turn", async () => {- const sessionState = createBaseSessionState();- const getConflict = vi.fn(async () => null);- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- installHookMocks({- deliveryHooks: [{ getConflict, token: "http:test" }],- turnControls: [- turnResult({- action: "done",- output: "ok",- serializedContext: { "eve.sessionId": "wrun_test_123" },- sessionState,- }),- ],- });-- const result = await workflowEntry({- input: { message: "hello there" },- serializedContext: {- ...createSerializedContext(),- "eve.sessionInbox": { sessionId: "producer-supplied-id", version: 99 },- },- });-- expect(result).toEqual({ output: "ok" });- expect(createSessionTimeoutControl).toHaveBeenCalledWith({- deadline: new Date("2026-01-31T00:00:00.000Z"),- token: sessionCommandHookToken("wrun_test_123"),- });- expect(createSessionStep).toHaveBeenCalledWith(- expect.objectContaining({- compiledArtifactsSource: {},- continuationToken: "http:test",- nodeId: undefined,- sessionId: "wrun_test_123",- taskId: undefined,- }),- );- expect(dispatchTurnStep).toHaveBeenCalledWith(- expect.objectContaining({- completionToken: expect.any(String),- delivery: {- kind: "deliver",- payloads: [{ message: "hello there", context: undefined }],- },- serializedContext: expect.objectContaining({- "eve.continuationToken": "http:test",- "eve.mode": "conversation",- "eve.sessionId": "wrun_test_123",- "eve.sessionInbox": { sessionId: "wrun_test_123", version: SESSION_INBOX_WIRE_VERSION },- }),- sessionState,- }),- );- expect(getConflict).toHaveBeenCalledOnce();- expect(getConflict.mock.invocationCallOrder[0]).toBeLessThan(- vi.mocked(dispatchTurnStep).mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,- );- expect(terminateChildSessionsStep).toHaveBeenCalledWith({- serializedContext: expect.any(Object),- sessionState,- });- });-- it("claims command hooks while session creation is still pending", async () => {- const sessionState = createBaseSessionState();- let resolveSessionCreation:- | ((result: ReturnType<typeof createSessionStepResultForMock>) => void)- | undefined;- vi.mocked(createSessionStep).mockReturnValueOnce(- new Promise((resolve) => {- resolveSessionCreation = resolve;- }),- );- const stableGetConflict = vi.fn(async () => null);- const authorizationGetConflict = vi.fn(async () => null);- const continuationGetConflict = vi.fn(async () => null);- installHookMocks({- authHook: { getConflict: authorizationGetConflict },- deliveryHooks: [{ getConflict: continuationGetConflict, token: "http:test" }],- stableHook: { getConflict: stableGetConflict },- turnControls: [turnResult({ action: "done", output: "ok", sessionState })],- });-- const result = workflowEntry({- input: { message: "hello there" },- serializedContext: createSerializedContext(),- });-- expect(createSessionStep).toHaveBeenCalledOnce();- expect(stableGetConflict).toHaveBeenCalledOnce();- expect(authorizationGetConflict).toHaveBeenCalledOnce();- expect(continuationGetConflict).toHaveBeenCalledOnce();- expect(dispatchTurnStep).not.toHaveBeenCalled();-- resolveSessionCreation?.(createSessionStepResultForMock(sessionState));- await expect(result).resolves.toEqual({ output: "ok" });- });-- it("omits caller resolution, binding, and settlement steps for a root turn", async () => {- const sessionState = createBaseSessionState();- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- installHookMocks({- deliveryHooks: [{ token: "http:test", values: [] }],- turnControls: [- turnResult({ action: "park", sessionState, settled: { output: "root answer" } }),- ],- });-- await expect(- workflowEntry({- input: { message: "hello" },- serializedContext: createSerializedContext(),- }),- ).resolves.toEqual({ output: "" });-- expect(resolveInitialTurnCallerStep).not.toHaveBeenCalled();- expect(bindTurnCallerContextStep).not.toHaveBeenCalled();- expect(notifyTurnCallerStep).not.toHaveBeenCalled();- });-- it("retains caller steps and task start notification for a callback task turn", async () => {- const sessionState = createBaseSessionState();- const caller = {- callId: "call-task",- replyTo: {- kind: "callback" as const,- token: "task:task-1:inbox",- url: "https://parent.example.com/callback",- },- subagentName: "researcher",- taskId: "task-1",- };- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- vi.mocked(resolveInitialTurnCallerStep).mockResolvedValueOnce(caller);- installHookMocks({- deliveryHooks: [{ token: "http:test", values: [] }],- turnControls: [- turnResult({ action: "park", sessionState, settled: { output: "task answer" } }),- ],- });- const serializedContext = createSerializedContext({- "eve.sessionCallback": {- callId: "call-task",- subagentName: "researcher",- taskId: "task-1",- token: "task:task-1:inbox",- url: "https://parent.example.com/callback",- },- });-- await expect(workflowEntry({ input: { message: "task" }, serializedContext })).resolves.toEqual(- { output: "" },- );-- expect(resolveInitialTurnCallerStep).toHaveBeenCalledExactlyOnceWith({ serializedContext });- expect(bindTurnCallerContextStep).toHaveBeenCalledExactlyOnceWith({- caller,- serializedContext: expect.objectContaining({ "eve.sessionCallback": expect.any(Object) }),- });- expect(notifyTurnCallerStep).toHaveBeenCalledExactlyOnceWith({- caller,- lifecycle: "parked",- sessionId: "wrun_test_123",- settled: { output: "task answer" },- });- });-- it("finalizes children when the durable command inbox closes", async () => {- const sessionState = createBaseSessionState();- const serializedContext = {- ...createSerializedContext(),- "eve.sessionId": "wrun_test_123",- };- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- installHookMocks({- deliveryHooks: [{ token: "http:test" }],- stableHook: {- next: vi.fn(async (): Promise<IteratorResult<SessionInboxPayload>> => ({- done: true,- value: undefined,- })),- },- turnControls: [- turnResult({- action: "park",- serializedContext,- sessionState,- }),- ],- });-- await expect(- workflowEntry({- input: { message: "hello there" },- serializedContext: createSerializedContext(),- }),- ).resolves.toEqual({ output: "" });-- expect(terminateChildSessionsStep).toHaveBeenCalledWith({- serializedContext,- sessionState,- });- expect(emitTerminalSessionCompletionStep).toHaveBeenCalledOnce();- expect(emitTerminalSessionCompletionStep).toHaveBeenCalledWith({- parentWritable: expect.any(WritableStream),- serializedContext,- });- expect(emitTerminalSessionFailureStep).not.toHaveBeenCalled();- expect(notifyTurnCallerStep).not.toHaveBeenCalled();- });-- it("completes a parked session when reset retires it", async () => {- const sessionState = createBaseSessionState();- const serializedContext = {- ...createSerializedContext(),- "eve.sessionId": "wrun_test_123",- };- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- installHookMocks({- deliveryHooks: [- {- token: "http:test",- values: [{ kind: "reset", reason: "Start over" }],- },- ],- turnControls: [- turnResult({- action: "park",- serializedContext,- sessionState,- }),- ],- });-- await expect(- workflowEntry({- input: { message: "hello there" },- serializedContext: createSerializedContext(),- }),- ).resolves.toEqual({ output: "" });-- expect(terminateChildSessionsStep).toHaveBeenCalledWith({- serializedContext,- sessionState,- });- expect(emitTerminalSessionCompletionStep).toHaveBeenCalledOnce();- expect(emitTerminalSessionCompletionStep).toHaveBeenCalledWith({- parentWritable: expect.any(WritableStream),- serializedContext,- });- expect(emitTerminalSessionFailureStep).not.toHaveBeenCalled();- expect(notifyTurnCallerStep).not.toHaveBeenCalled();- });-- it("exits a conflicting initial continuation before dispatching the first turn", async () => {- const sessionState = createBaseSessionState();- const dispose = vi.fn();- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- installHookMocks({- deliveryHooks: [- {- dispose,- getConflict: vi.fn(async () => ({ runId: "wrun_owner" })),- token: "http:test",- },- ],- turnControls: [],- });-- await expect(- workflowEntry({- activityCollectorRunId: "wrun_collector",- continuationConflictCommand: {- auth: null,- kind: "send",- payload: { message: "duplicate" },- },- input: { message: "duplicate" },- serializedContext: createSerializedContext(),- }),- ).resolves.toEqual({ output: "" });-- expect(emitTerminalSessionFailureStep).not.toHaveBeenCalled();- expect(dispatchTurnStep).not.toHaveBeenCalled();- expect(dispose).toHaveBeenCalledOnce();- expect(settleContinuationConflictStep).toHaveBeenCalledWith({- activityCollectorRunId: "wrun_collector",- command: {- auth: null,- kind: "send",- payload: { message: "duplicate" },- },- continuationToken: "http:test",- ownerSessionId: "wrun_owner",- });- });-- it("also exits when a legacy world reports the initial continuation conflict", async () => {- const sessionState = createBaseSessionState();- const dispose = vi.fn();- const fallbackError = Object.assign(new Error("legacy hook conflict"), {- name: "HookConflictError",- token: "http:test",- });- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- installHookMocks({- deliveryHooks: [- {- dispose,- getConflict: vi.fn(async () => {- throw fallbackError;- }),- token: "http:test",- },- ],- turnControls: [],- });-- await expect(- workflowEntry({- input: { message: "duplicate" },- serializedContext: createSerializedContext(),- }),- ).resolves.toEqual({ output: "" });-- expect(emitTerminalSessionFailureStep).not.toHaveBeenCalled();- expect(dispatchTurnStep).not.toHaveBeenCalled();- expect(dispose).toHaveBeenCalledOnce();- });-- it("passes the run channel request id to the first turn", async () => {- const sessionState = createBaseSessionState();- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- installHookMocks({- turnControls: [turnResult({ action: "done", output: "ok", sessionState })],- });-- await workflowEntry({- input: { message: "hello there" },- serializedContext: createSerializedContext({- [ChannelRequestIdKey.name]: "req_initial",- }),- });-- expect(vi.mocked(dispatchTurnStep).mock.calls[0]?.[0].delivery).toEqual({- requestId: "req_initial",- kind: "deliver",- payloads: [{ message: "hello there", context: undefined }],- });- });-- it("passes delegated subagent lineage and inherited limits to session creation", async () => {- const sessionState = createBaseSessionState();- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- installHookMocks({- turnControls: [turnResult({ action: "done", output: "ok", sessionState })],- });-- await workflowEntry({- input: { message: "hello there" },- limits: { maxInputTokensPerSession: 4 },- serializedContext: createSerializedContext({}),- });-- expect(createSessionStep).toHaveBeenCalledWith(- expect.objectContaining({- inheritedLimits: { maxInputTokensPerSession: 4 },- }),- );- });-- it("completes a parked session when its durable deadline elapses", async () => {- const sessionState = createBaseSessionState();- const dispose = vi.fn();- const timeoutControl = createTimeoutControl();- vi.mocked(createSessionTimeoutControl).mockReturnValueOnce(timeoutControl);- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- installHookMocks({- deliveryHooks: [- {- dispose,- next: () => new Promise<IteratorResult<SessionInboxPayload>>(() => {}),- token: "http:test",- },- ],- stableHook: { values: [{ kind: "session-timeout" }] },- turnControls: [turnResult({ action: "park", sessionState })],- });-- await expect(- workflowEntry({- input: { message: "hello there" },- serializedContext: createSerializedContext(),- sessionTimeoutMs: 1_000,- }),- ).resolves.toEqual({ output: "" });-- expect(createSessionTimeoutControl).toHaveBeenCalledWith({- deadline: new Date("2026-01-01T00:00:01.000Z"),- token: sessionCommandHookToken("wrun_test_123"),- });- expect(timeoutControl.dispose).toHaveBeenCalledOnce();- expect(terminateChildSessionsStep).toHaveBeenCalledWith({- serializedContext: expect.any(Object),- sessionState,- });- expect(emitTerminalSessionFailureStep).not.toHaveBeenCalled();- expect(emitTerminalSessionCompletionStep).toHaveBeenCalledWith({- parentWritable: expect.any(WritableStream),- serializedContext: { "eve.sessionId": "wrun_test_123" },- });- expect(dispose.mock.invocationCallOrder[0]).toBeLessThan(- vi.mocked(emitTerminalSessionCompletionStep).mock.invocationCallOrder[0] ??- Number.POSITIVE_INFINITY,- );- expect(fireSessionCallbackStep).not.toHaveBeenCalled();- expect(notifyTurnCallerStep).not.toHaveBeenCalled();- });-- it("dispatches a compact control without converting it into a delivery", async () => {- const sessionState = createBaseSessionState();- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- installHookMocks({- deliveryHooks: [- {- token: "http:test",- values: [{ kind: "compact" }, { kind: "session-timeout" }],- },- ],- turnControls: [- turnResult({ action: "park", sessionState }),- turnResult({ action: "park", sessionState }),- ],- });-- await expect(- workflowEntry({- input: { message: "hello there" },- serializedContext: createSerializedContext(),- }),- ).resolves.toEqual({ output: "" });-- expect(dispatchTurnStep).toHaveBeenCalledTimes(2);- expect(vi.mocked(dispatchTurnStep).mock.calls[1]?.[0].delivery).toEqual({ kind: "compact" });- expect(routeDeliverToChildren).not.toHaveBeenCalled();- });-- it("dispatches a clear control without converting it into a delivery", async () => {- const sessionState = createBaseSessionState();- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- installHookMocks({- deliveryHooks: [- {- token: "http:test",- values: [{ kind: "clear" }, { kind: "session-timeout" }],- },- ],- turnControls: [- turnResult({ action: "park", sessionState }),- turnResult({ action: "park", sessionState }),- ],- });-- await expect(- workflowEntry({- input: { message: "hello there" },- serializedContext: createSerializedContext(),- }),- ).resolves.toEqual({ output: "" });-- expect(dispatchTurnStep).toHaveBeenCalledTimes(2);- expect(vi.mocked(dispatchTurnStep).mock.calls[1]?.[0].delivery).toEqual({ kind: "clear" });- expect(routeDeliverToChildren).not.toHaveBeenCalled();- });-- it("completes at the deadline after the active turn settles", async () => {- const sessionState = createBaseSessionState();- const dispose = vi.fn();- let settleTurn: ((result: IteratorResult<TurnControlPayload>) => void) | undefined;- const activeTurn = new Promise<IteratorResult<TurnControlPayload>>((resolve) => {- settleTurn = resolve;- });-- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- let deliveredTimeout = false;- vi.mocked(createHook).mockImplementation((options?: { readonly token?: string }) => {- const token = options?.token ?? "";- if (isTurnCompletionToken(token)) {- return createMockHook({- next: () => activeTurn,- token,- values: [],- }) as never;- }- if (token.endsWith(":auth")) {- return createMockHook({ token, values: [] }) as never;- }- return token === sessionCommandHookToken("wrun_test_123")- ? (createMockHook({- dispose,- next: () => {- if (deliveredTimeout) {- return new Promise<IteratorResult<SessionInboxPayload>>(() => {});- }- deliveredTimeout = true;- return Promise.resolve({ done: false, value: { kind: "session-timeout" } });- },- token,- values: [],- }) as never)- : (createMockHook({- dispose,- next: () => new Promise<IteratorResult<SessionInboxPayload>>(() => {}),- token,- values: [],- }) as never);- });-- const result = workflowEntry({- input: { message: "hello there" },- serializedContext: createSerializedContext(),- sessionTimeoutMs: 1,- });-- await vi.waitFor(() => {- expect(dispatchTurnStep).toHaveBeenCalledOnce();- });- expect(emitTerminalSessionCompletionStep).not.toHaveBeenCalled();-- settleTurn?.({- done: false,- value: turnResult({ action: "park", sessionState }),- });-- await expect(result).resolves.toEqual({ output: "" });- expect(emitTerminalSessionCompletionStep).toHaveBeenCalledOnce();- });-- it("allows the session timeout to be disabled", async () => {- const sessionState = createBaseSessionState();- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- installHookMocks({- turnControls: [turnResult({ action: "done", output: "ok", sessionState })],- });-- await workflowEntry({- input: { message: "hello there" },- serializedContext: createSerializedContext(),- sessionTimeoutMs: false,- });-- expect(createSessionTimeoutControl).not.toHaveBeenCalled();- });-- it("notifies a delegated parent once when a turn fails terminally", async () => {- const sessionState = createBaseSessionState();- const caller = {- callId: "call-1",- replyTo: { kind: "hook" as const, token: "parent-token" },- subagentName: "researcher",- };- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- vi.mocked(resolveInitialTurnCallerStep).mockResolvedValueOnce(caller);- installHookMocks({- turnControls: [- {- error: { message: "persistent recoverable failure", name: "Error" },- kind: "turn-error",- },- ],- });- const serializedContext = createSerializedContext({- "eve.channel": {- kind: "subagent",- state: {- callId: "call-1",- parentContinuationToken: "parent-token",- subagentName: "researcher",- },- },- });-- await expect(- workflowEntry({- input: { message: "delegate" },- serializedContext,- }),- ).rejects.toMatchObject({- message: "Agent workflow failed. Inspect the private session trace for details.",- name: "EveWorkflowFailure",- });-- expect(emitTerminalSessionFailureStep).toHaveBeenCalledWith(- expect.objectContaining({- error: expect.objectContaining({ message: "persistent recoverable failure" }),- turnId: "turn_0",- }),- );- expect(terminateChildSessionsStep).toHaveBeenCalledWith({- serializedContext: expect.any(Object),- sessionState,- });- expect(notifyDelegatedParentStep).not.toHaveBeenCalled();- expect(notifyTurnCallerStep).toHaveBeenCalledOnce();- expect(notifyTurnCallerStep).toHaveBeenCalledWith({- caller,- lifecycle: "terminal",- sessionId: "wrun_test_123",- settled: {- isError: true,- output: expect.objectContaining({- message: "persistent recoverable failure",- name: "Error",- }),- },- });- expect(fireSessionCallbackStep).not.toHaveBeenCalled();- // The caller cell was already populated; the crash path must reuse it- // instead of resolving a second time.- expect(resolveInitialTurnCallerStep).toHaveBeenCalledOnce();- });-- it("does not emit session.failed when notification fails after terminal completion", async () => {- const sessionState = createBaseSessionState();- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- vi.mocked(fireSessionCallbackStep).mockRejectedValueOnce(new Error("callback failed"));- installHookMocks({- turnControls: [turnResult({ action: "done", output: "ok", sessionState })],- });-- await expect(- workflowEntry({- input: { message: "run task" },- serializedContext: createSerializedContext({ "eve.mode": "task" }),- }),- ).rejects.toMatchObject({ name: "EveWorkflowFailure" });-- expect(fireSessionCallbackStep).toHaveBeenCalledOnce();- expect(emitTerminalSessionFailureStep).not.toHaveBeenCalled();- expect(notifyDelegatedParentStep).not.toHaveBeenCalled();- });-- it("rejects the delegated caller when the session fails before the caller is resolved", async () => {- const caller = {- callId: "call-1",- replyTo: { kind: "hook" as const, token: "parent-token" },- subagentName: "researcher",- };- // Crash before `resolveInitialTurnCallerStep` ever runs: the cleanup- // cell is unpopulated, so the catch must re-resolve the caller from the- // serialized context or the delegated parent's call parks forever.- vi.mocked(createSessionStep).mockRejectedValueOnce(new Error("session creation failed"));- vi.mocked(resolveInitialTurnCallerStep).mockResolvedValueOnce(caller);- const stableDispose = vi.fn();- const authorizationDispose = vi.fn();- const continuationDispose = vi.fn();- installHookMocks({- authHook: { dispose: authorizationDispose },- deliveryHooks: [{ dispose: continuationDispose, token: "http:test" }],- stableHook: { dispose: stableDispose },- turnControls: [],- });- const serializedContext = createSerializedContext({- "eve.channel": {- kind: "subagent",- state: {- callId: "call-1",- parentContinuationToken: "parent-token",- subagentName: "researcher",- },- },- });-- await expect(- workflowEntry({- input: { message: "delegate" },- serializedContext,- }),- ).rejects.toMatchObject({ name: "EveWorkflowFailure" });-- expect(resolveInitialTurnCallerStep).toHaveBeenCalledOnce();- expect(notifyTurnCallerStep).toHaveBeenCalledOnce();- expect(notifyTurnCallerStep).toHaveBeenCalledWith({- caller,- lifecycle: "terminal",- sessionId: "wrun_test_123",- settled: {- isError: true,- output: expect.objectContaining({ message: "session creation failed" }),- },- });- // No snapshot was ever received, so there are no children to terminate.- expect(terminateChildSessionsStep).not.toHaveBeenCalled();- expect(stableDispose).toHaveBeenCalledOnce();- expect(authorizationDispose).toHaveBeenCalledOnce();- expect(continuationDispose).toHaveBeenCalledOnce();- });-- it("does not resolve or notify a caller when a root turn crashes", async () => {- const sessionState = createBaseSessionState();- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- installHookMocks({- turnControls: [- {- error: { message: "root turn crashed", name: "Error" },- kind: "turn-error",- },- ],- });-- await expect(- workflowEntry({- input: { message: "hello" },- serializedContext: createSerializedContext(),- }),- ).rejects.toMatchObject({ name: "EveWorkflowFailure" });-- expect(resolveInitialTurnCallerStep).not.toHaveBeenCalled();- expect(notifyTurnCallerStep).not.toHaveBeenCalled();- });-- it("notifies the latest delegated exchange when a resumed turn fails terminally", async () => {- const sessionState = createBaseSessionState();- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- const serializedContext = createSerializedContext({- "eve.channel": {- kind: "subagent",- state: {- callId: "call-original",- parentContinuationToken: "original-parent-turn",- subagentName: "researcher",- },- },- });- installHookMocks({- deliveryHooks: [- {- token: "http:test",- values: [- {- caller: {- callId: "call-latest",- replyTo: { kind: "hook", token: "latest-parent-turn" },- subagentName: "researcher",- },- kind: "send",- payload: { message: "follow up" },- },- ],- },- ],- turnControls: [- turnResult({ action: "park", sessionState }),- {- action: {- isError: true,- kind: "done",- output: "follow-up failed",- serializedContext,- sessionState,- },- kind: "turn-result",- },- ],- });-- await expect(- workflowEntry({- input: { message: "delegate" },- serializedContext,- }),- ).resolves.toEqual({ output: "follow-up failed" });-- expect(notifyTurnCallerStep).toHaveBeenCalledWith({- caller: {- callId: "call-latest",- replyTo: { kind: "hook", token: "latest-parent-turn" },- subagentName: "researcher",- },- lifecycle: "terminal",- sessionId: "wrun_test_123",- settled: {- isError: true,- output: "follow-up failed",- },- });- expect(fireSessionCallbackStep).not.toHaveBeenCalled();- });-- it("rekeys the delivery hook before notifying a delegated settled turn", async () => {- const initialState = createBaseSessionState({ continuationToken: "" });- const parkedState = createBaseSessionState({ continuationToken: "subagent:child" });- const caller = {- callId: "call-1",- replyTo: { kind: "hook" as const, token: "parent-turn" },- subagentName: "researcher",- };- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(initialState));- vi.mocked(resolveInitialTurnCallerStep).mockResolvedValueOnce(caller);- const serializedContext = createSerializedContext({- "eve.channel": {- kind: "subagent",- state: {- callId: "call-1",- parentContinuationToken: "parent-turn",- subagentName: "researcher",- },- },- "eve.continuationToken": "",- });- installHookMocks({- deliveryHooks: [{ token: "subagent:child", values: [] }],- turnControls: [- turnResult({- action: "park",- serializedContext,- sessionState: parkedState,- settled: { output: "settled answer" },- }),- ],- });-- await expect(- workflowEntry({- input: { message: "delegate" },- serializedContext,- }),- ).resolves.toEqual({ output: "" });-- const rekeyCall = vi- .mocked(createHook)- .mock.calls.find((call) => call[0]?.token === "subagent:child");- expect(rekeyCall).toBeDefined();- expect(vi.mocked(createHook).mock.invocationCallOrder.at(-1)).toBeLessThan(- vi.mocked(notifyTurnCallerStep).mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,- );- expect(notifyTurnCallerStep).toHaveBeenCalledWith({- caller,- lifecycle: "parked",- sessionId: "wrun_test_123",- settled: { output: "settled answer" },- });- });-- it("keeps the turn caller across a callerless continuation", async () => {- const sessionState = createBaseSessionState();- const caller = {- callId: "call-1",- replyTo: { kind: "hook" as const, token: "parent-turn" },- subagentName: "researcher",- };- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- vi.mocked(resolveInitialTurnCallerStep).mockResolvedValueOnce(caller);- installHookMocks({- deliveryHooks: [- {- token: "http:test",- values: [- {- kind: "send",- payload: { inputResponses: [{ optionId: "approve", requestId: "req-1" }] },- },- ],- },- ],- turnControls: [- turnResult({ action: "park", sessionState }),- turnResult({- action: "park",- sessionState,- settled: { output: "approved answer" },- }),- ],- });-- await expect(- workflowEntry({- input: { message: "delegate" },- serializedContext: createSerializedContext({- "eve.channel": {- kind: "subagent",- state: {- callId: "call-1",- parentContinuationToken: "parent-turn",- parentSessionId: "parent-session",- subagentName: "researcher",- },- },- }),- }),- ).resolves.toEqual({ output: "" });-- expect(notifyTurnCallerStep).toHaveBeenCalledExactlyOnceWith({- caller,- lifecycle: "parked",- sessionId: "wrun_test_123",- settled: { output: "approved answer" },- });- });-- it("passes the resumed channel request id to the next turn", async () => {- const sessionState = createBaseSessionState();- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- installHookMocks({- deliveryHooks: [- {- token: "http:test",- values: [- {- requestId: "req_followup",- kind: "send",- payload: { message: "follow up" },- },- ],- },- ],- turnControls: [- turnResult({ action: "park", sessionState }),- turnResult({ action: "done", output: "ok", sessionState }),- ],- });-- await workflowEntry({- input: { message: "hello there" },- serializedContext: createSerializedContext(),- });-- expect(vi.mocked(dispatchTurnStep).mock.calls[1]?.[0].delivery).toMatchObject({- auth: undefined,- requestId: "req_followup",- kind: "deliver",- payloads: [{ message: "follow up" }],- });- });-- it("supplies a requested public delivery to the active turn inbox", async () => {- const sessionState = createBaseSessionState();- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));-- let acceptForward: (() => void) | undefined;- const forwarded = new Promise<void>((resolve) => {- acceptForward = resolve;- });- vi.mocked(resumeHook).mockImplementation(async (token) => {- if (token === "turn-inbox") acceptForward?.();- return { runId: "turn-run" } as never;- });-- let completionIndex = 0;- vi.mocked(createHook).mockImplementation((options?: { readonly token?: string }) => {- const token = options?.token ?? "";- if (isTurnCompletionToken(token)) {- return createMockHook<TurnControlPayload>({- next: async () => {- completionIndex += 1;- if (completionIndex === 1) {- return {- done: false,- value: {- continuationToken: "http:test",- inboxToken: "turn-inbox",- kind: "turn-delivery-request",- requestId: "delivery-1",- },- };- }- if (completionIndex === 2) {- await forwarded;- return {- done: false,- value: { kind: "turn-delivery-accepted", requestId: "delivery-1" },- };- }- return {- done: false,- value: turnResult({ action: "done", output: "finished", sessionState }),- };- },- token,- values: [],- }) as never;- }- if (token.endsWith(":auth")) {- return createMockHook({ token, values: [] }) as never;- }- return createMockHook({- token,- values: [- {- kind: "send",- payload: { inputResponses: [{ optionId: "approve", requestId: "req-1" }] },- },- ],- }) as never;- });-- const result = await workflowEntry({- input: { message: "delegate" },- serializedContext: createSerializedContext(),- });-- expect(result).toEqual({ output: "finished" });- expect(dispatchTurnStep).toHaveBeenCalledTimes(1);- expect(resumeHook).toHaveBeenCalledWith("turn-inbox", {- delivery: {- auth: undefined,- caller: undefined,- kind: "deliver",- payloads: [{ inputResponses: [{ optionId: "approve", requestId: "req-1" }] }],- requestId: undefined,- },- kind: "driver-delivery",- requestId: "delivery-1",- });- });-- it("preserves a public delivery when the active turn cancels its request", async () => {- const sessionState = createBaseSessionState();- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));-- vi.mocked(createHook).mockImplementation((options?: { readonly token?: string }) => {- const token = options?.token ?? "";- if (token.endsWith(":turn-control:0")) {- return createMockHook({- token,- values: [- {- continuationToken: "http:test",- inboxToken: "turn-inbox",- kind: "turn-delivery-request",- requestId: "delivery-1",- },- { kind: "turn-delivery-cancelled", requestId: "delivery-1" },- turnResult({ action: "park", sessionState }),- ],- }) as never;- }- if (token.endsWith(":turn-control:1")) {- return createMockHook({- token,- values: [turnResult({ action: "done", output: "after delivery", sessionState })],- }) as never;- }- if (token.endsWith(":auth")) {- return createMockHook({ token, values: [] }) as never;- }- return createMockHook({- token,- values: [{ kind: "send", payload: { message: "not for the child" } }],- }) as never;- });-- const result = await workflowEntry({- input: { message: "delegate" },- serializedContext: createSerializedContext(),- });-- expect(result).toEqual({ output: "after delivery" });- expect(dispatchTurnStep).toHaveBeenCalledTimes(2);- expect(vi.mocked(dispatchTurnStep).mock.calls[1]?.[0].delivery).toMatchObject({- auth: undefined,- kind: "deliver",- payloads: [{ message: "not for the child" }],- requestId: undefined,- });- expect(resumeHook).not.toHaveBeenCalled();- });-- it("settles a cancelled turn in the driver and starts the next turn from the settled state", async () => {- const sessionState = createBaseSessionState({- snapshot: {- session: {- agent: { system: "" },- continuationToken: "http:test",- history: [],- sessionId: "wrun_test_123",- state: {- "eve.harness.settledTurn": { output: "stale prior answer" },- },- },- version: 1,- },- });- const settledState = createBaseSessionState({- emissionState: { sequence: 1, sessionStarted: true, stepIndex: 0, turnId: "" },- });- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- vi.mocked(settleCancelledTurnStep).mockResolvedValue({- serializedContext: { "eve.sessionId": "wrun_test_123", settled: true },- sessionState: settledState,- });- installHookMocks({- deliveryHooks: [- {- token: "http:test",- values: [{ kind: "send", payload: { message: "after cancel" } }],- },- ],- turnControls: [- {- action: {- cancelled: true,- kind: "park",- serializedContext: { "eve.sessionId": "wrun_test_123" },- sessionState,- },- kind: "turn-result",- },- turnResult({ action: "done", output: "ok", sessionState: settledState }),- ],- });-- const result = await workflowEntry({- input: { message: "hello" },- serializedContext: createSerializedContext(),- });-- expect(result).toEqual({ output: "ok" });- expect(settleCancelledTurnStep).toHaveBeenCalledExactlyOnceWith({- parentWritable: expect.any(WritableStream),- serializedContext: { "eve.sessionId": "wrun_test_123" },- sessionState,- });- expect(vi.mocked(dispatchTurnStep).mock.calls[1]?.[0]).toMatchObject({- serializedContext: { settled: true },- sessionState: settledState,- });- expect(notifyTurnCallerStep).not.toHaveBeenCalled();- });-- it("retains the active turn when cancellation settlement fails", async () => {- const sessionState = createBaseSessionState();- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- vi.mocked(settleCancelledTurnStep).mockRejectedValueOnce(new Error("settlement failed"));- installHookMocks({- turnControls: [- {- action: {- cancelled: true,- kind: "park",- serializedContext: { "eve.sessionId": "wrun_test_123" },- sessionState,- },- kind: "turn-result",- },- ],- });-- await expect(- workflowEntry({- input: { message: "hello" },- serializedContext: createSerializedContext(),- }),- ).rejects.toMatchObject({ name: "EveWorkflowFailure" });-- expect(emitTerminalSessionFailureStep).toHaveBeenCalledWith(- expect.objectContaining({- error: expect.objectContaining({ message: "settlement failed" }),- serializedContext: { "eve.sessionId": "wrun_test_123" },- turnId: "turn_0",- }),- );- });-- it("adopts cancelled-turn state before notifying its caller", async () => {- const sessionState = createBaseSessionState();- const settledState = createBaseSessionState({- emissionState: { sequence: 1, sessionStarted: true, stepIndex: 0, turnId: "" },- });- const settledContext = { "eve.sessionId": "wrun_test_123", settled: true };- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- vi.mocked(settleCancelledTurnStep).mockResolvedValue({- serializedContext: settledContext,- sessionState: settledState,- });- vi.mocked(notifyCancelledTaskCallerStep).mockRejectedValueOnce(- new Error("caller notification failed"),- );- installHookMocks({- turnControls: [- {- action: {- cancelled: true,- kind: "park",- serializedContext: { "eve.sessionId": "wrun_test_123" },- sessionState,- },- kind: "turn-result",- },- ],- });-- await expect(- workflowEntry({- input: { message: "hello" },- serializedContext: createSerializedContext(),- }),- ).rejects.toMatchObject({ name: "EveWorkflowFailure" });-- expect(emitTerminalSessionFailureStep).toHaveBeenCalledWith(- expect.objectContaining({- error: expect.objectContaining({ message: "caller notification failed" }),- serializedContext: settledContext,- turnId: "turn_0",- }),- );- });-- it("does not settle an ordinary park as cancelled", async () => {- const sessionState = createBaseSessionState();- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- installHookMocks({- deliveryHooks: [{ token: "http:test", values: [] }],- turnControls: [turnResult({ action: "park", sessionState })],- });-- const result = await workflowEntry({- input: { message: "hello" },- serializedContext: createSerializedContext(),- });-- expect(result).toEqual({ output: "" });- expect(settleCancelledTurnStep).not.toHaveBeenCalled();- });-- it("does not schedule caller notification for a settled root turn", async () => {- const sessionState = createBaseSessionState();- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- installHookMocks({- deliveryHooks: [{ token: "http:test", values: [] }],- turnControls: [- turnResult({- action: "park",- sessionState,- settled: { output: "hello" },- }),- ],- });- const serializedContext = createSerializedContext();-- await expect(- workflowEntry({- input: { message: "hello" },- serializedContext,- }),- ).resolves.toEqual({ output: "" });-- expect(notifyTurnCallerStep).not.toHaveBeenCalled();- });-- it("does not re-send a settled parent turn when a delivery routes to a child", async () => {- const sessionState = createBaseSessionState({ hasProxyInputRequests: true });- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- vi.mocked(routeDeliverToChildren).mockResolvedValueOnce({- kind: "continue",- remainder: undefined,- serializedContext: {},- sessionState,- });- installHookMocks({- deliveryHooks: [- {- token: "http:test",- values: [{ kind: "send", payload: { inputResponses: [] } }],- },- ],- turnControls: [- turnResult({- action: "park",- sessionState,- settled: { output: "already sent" },- }),- ],- });-- await expect(- workflowEntry({- input: { message: "hello" },- serializedContext: createSerializedContext(),- }),- ).resolves.toEqual({ output: "" });-- expect(notifyTurnCallerStep).not.toHaveBeenCalled();- });-- it("adopts retired proxy state before the next parked driver turn", async () => {- const sessionState = createBaseSessionState({ hasProxyInputRequests: true });- const retiredState = createBaseSessionState({ hasProxyInputRequests: false });- const completedState = createBaseSessionState();- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- vi.mocked(routeDeliverToChildren).mockResolvedValueOnce({- kind: "continue",- remainder: undefined,- serializedContext: {},- sessionState: retiredState,- });- installHookMocks({- deliveryHooks: [- {- token: "http:test",- values: [- { kind: "send", payload: { inputResponses: [] } },- { kind: "send", payload: { message: "next parent turn" } },- ],- },- ],- turnControls: [- turnResult({ action: "park", sessionState }),- turnResult({ action: "done", output: "ok", sessionState: completedState }),- ],- });-- await workflowEntry({- input: { message: "hello" },- serializedContext: createSerializedContext(),- });-- expect(vi.mocked(dispatchTurnStep).mock.calls[1]?.[0].sessionState).toBe(retiredState);- });-- it("runs concurrent caller deliveries as separate turns", async () => {- const sessionState = createBaseSessionState();- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- const firstCaller = {- callId: "call-1",- replyTo: { kind: "hook" as const, token: "caller-1" },- subagentName: "researcher",- };- const secondCaller = {- callId: "call-2",- replyTo: { kind: "hook" as const, token: "caller-2" },- subagentName: "researcher",- };- installHookMocks({- deliveryHooks: [- {- token: "http:test",- values: [],- },- ],- turnControls: [- {- action: {- kind: "park",- serializedContext: { "eve.sessionId": "wrun_test_123" },- sessionState,- },- bufferedDeliveries: [- {- caller: firstCaller,- kind: "deliver",- payloads: [{ message: "first question" }],- },- {- caller: secondCaller,- kind: "deliver",- payloads: [{ message: "second question" }],- },- ],- kind: "turn-result",- },- turnResult({- action: "park",- sessionState,- settled: { output: "first answer" },- }),- turnResult({- action: "park",- sessionState,- settled: { output: "second answer" },- }),- ],- });-- await expect(- workflowEntry({- input: { message: "initial question" },- serializedContext: createSerializedContext(),- }),- ).resolves.toEqual({ output: "" });-- expect(dispatchTurnStep).toHaveBeenCalledTimes(3);- expect(notifyTurnCallerStep).toHaveBeenNthCalledWith(1, {- caller: firstCaller,- lifecycle: "parked",- sessionId: "wrun_test_123",- settled: { output: "first answer" },- });- expect(notifyTurnCallerStep).toHaveBeenNthCalledWith(2, {- caller: secondCaller,- lifecycle: "parked",- sessionId: "wrun_test_123",- settled: { output: "second answer" },- });- });-- it("skips child routing when a turn completes without yielding to a delivery", async () => {- const sessionState = createBaseSessionState();- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));- installHookMocks({- turnControls: [- turnResult({- action: "done",- output: "ok",- serializedContext: { "eve.sessionId": "wrun_test_123" },- sessionState,- }),- ],- });-- const result = await workflowEntry({- input: { message: "hello" },- serializedContext: createSerializedContext(),- });-- expect(result).toEqual({ output: "ok" });- expect(routeDeliverToChildren).not.toHaveBeenCalled();- });-- it("parks the first hook under the re-keyed continuation token", async () => {- const baseSessionState = createBaseSessionState({ continuationToken: "slack:C01:" });- const rekeyedSessionState: DurableSessionState = {- ...baseSessionState,- continuationToken: "slack:C01:1800000000.123456",- };-- vi.mocked(createSessionStep).mockResolvedValue(- createSessionStepResultForMock(baseSessionState),- );-- const initialReturn = createIteratorReturn();- const initialDispose = vi.fn();- const rekeyedReturn = createIteratorReturn();- const rekeyedDispose = vi.fn();- installHookMocks({- deliveryHooks: [- {- dispose: initialDispose,- return: initialReturn,- token: "slack:C01:",- values: [],- },- {- dispose: rekeyedDispose,- return: rekeyedReturn,- token: "slack:C01:1800000000.123456",- values: [],- },- ],- turnControls: [turnResult({ action: "park", sessionState: rekeyedSessionState })],- });-- const result = await workflowEntry({- input: { message: "hello" },- serializedContext: createSerializedContext({- "eve.channel": { kind: "slack", state: {} },- "eve.continuationToken": "slack:C01:",- }),- });-- expect(result).toEqual({ output: "" });- // Initial hook created before the turn, then rekeyed after.- expect(nonTurnHookTokens()).toEqual(["slack:C01:", "slack:C01:1800000000.123456"]);- expect(initialReturn).not.toHaveBeenCalled();- expect(initialDispose).toHaveBeenCalledTimes(1);- expect(rekeyedReturn).not.toHaveBeenCalled();- expect(rekeyedDispose).toHaveBeenCalledTimes(1);- });-- it("defers the first delivery hook until an empty continuation token is anchored", async () => {- const baseSessionState = createBaseSessionState({ continuationToken: "" });- const anchoredSessionState: DurableSessionState = {- ...baseSessionState,- continuationToken: "slack:C01:1800000000.123456",- };-- vi.mocked(createSessionStep).mockResolvedValue(- createSessionStepResultForMock(baseSessionState),- );-- const anchoredReturn = createIteratorReturn();- const anchoredDispose = vi.fn();- installHookMocks({- deliveryHooks: [- {- dispose: anchoredDispose,- return: anchoredReturn,- token: "slack:C01:1800000000.123456",- values: [],- },- ],- turnControls: [turnResult({ action: "park", sessionState: anchoredSessionState })],- });-- const result = await workflowEntry({- input: { message: "hello" },- serializedContext: createSerializedContext({- "eve.channel": { kind: "slack", state: {} },- "eve.continuationToken": "",- }),- });-- expect(result).toEqual({ output: "" });- expect(nonTurnHookTokens()).toEqual(["slack:C01:1800000000.123456"]);- expect(anchoredReturn).not.toHaveBeenCalled();- expect(anchoredDispose).toHaveBeenCalledTimes(1);- });-- it("recreates the delivery hook when a later turn re-keys the session", async () => {- const baseSessionState = createBaseSessionState({ continuationToken: "slack:C01:" });- const rekeyedSessionState: DurableSessionState = {- ...baseSessionState,- continuationToken: "slack:C01:1800000000.123456",- };-- vi.mocked(createSessionStep).mockResolvedValue(- createSessionStepResultForMock(baseSessionState),- );-- const oldReturn = createIteratorReturn();- const oldDispose = vi.fn();- const oldGetConflict = vi.fn(async () => null);- const newReturn = createIteratorReturn();- const newDispose = vi.fn();- const newGetConflict = vi.fn(async () => null);- installHookMocks({- deliveryHooks: [- {- dispose: oldDispose,- getConflict: oldGetConflict,- return: oldReturn,- token: "slack:C01:",- values: [- {- kind: "send",- payload: { message: "follow up" },- },- ],- },- {- dispose: newDispose,- getConflict: newGetConflict,- return: newReturn,- token: "slack:C01:1800000000.123456",- values: [],- },- ],- turnControls: [- turnResult({ action: "park", sessionState: baseSessionState }),- turnResult({ action: "park", sessionState: rekeyedSessionState }),- ],- });-- const result = await workflowEntry({- input: { message: "hello" },- serializedContext: createSerializedContext({- "eve.channel": { kind: "slack", state: {} },- "eve.continuationToken": "slack:C01:",- }),- });-- expect(result).toEqual({ output: "" });- expect(nonTurnHookTokens()).toEqual(["slack:C01:", "slack:C01:1800000000.123456"]);- expect(vi.mocked(dispatchTurnStep).mock.calls[1]?.[0].delivery).toMatchObject({- kind: "deliver",- payloads: [{ message: "follow up" }],- });- expect(oldReturn).not.toHaveBeenCalled();- expect(oldDispose).toHaveBeenCalledTimes(1);- expect(newReturn).not.toHaveBeenCalled();- expect(newDispose).toHaveBeenCalledTimes(1);- expect(oldGetConflict).toHaveBeenCalledOnce();- expect(newGetConflict).toHaveBeenCalledOnce();- expect(newGetConflict.mock.invocationCallOrder[0]).toBeLessThan(- oldDispose.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,- );- });-- it("disposes the workflow hook after the loop exits", async () => {- const sessionState = createBaseSessionState();- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));-- const dispose = vi.fn();- const symbolDispose = vi.fn();- const returnIterator = createIteratorReturn();- installHookMocks({- deliveryHooks: [- {- dispose,- return: returnIterator,- token: "http:test",- values: [- {- kind: "send",- payload: { message: "follow up" },- },- ],- },- ],- symbolDispose,- turnControls: [- turnResult({ action: "park", sessionState }),- turnResult({ action: "done", output: "after resume", sessionState }),- ],- });-- const result = await workflowEntry({- input: { message: "hello there" },- serializedContext: createSerializedContext(),- });-- expect(result).toEqual({ output: "after resume" });- expect(returnIterator).not.toHaveBeenCalled();- expect(dispose).toHaveBeenCalledTimes(1);- expect(symbolDispose).not.toHaveBeenCalled();- });-- it("disposes the auth hook without closing its iterator", async () => {- const sessionState = createBaseSessionState();- vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));-- const authDispose = vi.fn();- const authReturn = createIteratorReturn();- installHookMocks({- authHook: { dispose: authDispose, return: authReturn },- turnControls: [turnResult({ action: "done", output: "ok", sessionState })],- });-- await expect(- workflowEntry({- input: { message: "hello" },- serializedContext: createSerializedContext(),- }),- ).resolves.toEqual({ output: "ok" });-- expect(authDispose).toHaveBeenCalledOnce();- expect(authReturn).not.toHaveBeenCalled();- });-});--function createSerializedContext(overrides: Record<string, unknown> = {}): Record<string, unknown> {- return {- "eve.auth": null,- "eve.bundle": { source: {} },- "eve.channel": { kind: "http", state: {} },- "eve.continuationToken": "http:test",- "eve.mode": "conversation",- ...overrides,- };-}--function createBaseSessionState(overrides: Partial<DurableSessionState> = {}): DurableSessionState {- return {- continuationToken: "http:test",- emissionState: { sequence: 0, sessionStarted: false, stepIndex: 0, turnId: "" },- hasProxyInputRequests: false,- sessionId: "wrun_test_123",- version: 1,- ...overrides,- };-}--function turnResult(input: {- readonly action: "done" | "park";- readonly output?: string;- readonly serializedContext?: Record<string, unknown>;- readonly sessionState: DurableSessionState;- readonly settled?: {- readonly output: unknown;- readonly isError?: boolean;- };-}): TurnControlPayload {- const serializedContext = input.serializedContext ?? { "eve.sessionId": "wrun_test_123" };- if (input.action === "done") {- return {- action: {- kind: "done",- output: input.output ?? "",- serializedContext,- sessionState: input.sessionState,- },- kind: "turn-result",- };- }- const park = {- kind: "park" as const,- serializedContext,- sessionState: input.sessionState,- };- return {- action: input.settled === undefined ? park : { ...park, settled: input.settled },- kind: "turn-result",- };-}--function installHookMocks(input: {- readonly authHook?: AuthHookConfig;- readonly deliveryHooks?: readonly DeliveryHookConfig[];- readonly stableHook?: Omit<DeliveryHookConfig, "token">;- readonly symbolDispose?: () => void;- readonly turnControls: readonly TurnControlPayload[];-}): void {- const turnControls = [...input.turnControls];- const deliveryHooks = [...(input.deliveryHooks ?? [])];-- vi.mocked(createHook).mockImplementation((options?: { readonly token?: string }) => {- const token = options?.token;-- if (token === undefined || isTurnCompletionToken(token)) {- const value = turnControls.shift();- return createMockHook({- token: token ?? "turn-control",- values: value === undefined ? [] : [value],- }) as never;- }-- if (token.endsWith(":auth")) {- return createMockHook({- dispose: input.authHook?.dispose,- getConflict: input.authHook?.getConflict,- return: input.authHook?.return,- token,- values: [],- }) as never;- }-- if (token === sessionCommandHookToken("wrun_test_123")) {- const values = [...(input.stableHook?.values ?? [])];- return createMockHook({- dispose: input.stableHook?.dispose,- getConflict: input.stableHook?.getConflict,- next:- input.stableHook?.next ??- (async () => {- const value = values.shift();- return value === undefined- ? await new Promise<IteratorResult<SessionInboxPayload>>(() => {})- : { done: false, value };- }),- return: input.stableHook?.return,- token,- values: [],- }) as never;- }-- const config = deliveryHooks.shift() ?? { token, values: [] };- if (config.token !== token) {- throw new Error(`Expected delivery hook token "${config.token}", received "${token}".`);- }-- return createMockHook({- dispose: config.dispose,- getConflict: config.getConflict,- next: config.next,- return: config.return,- symbolDispose: input.symbolDispose,- token,- values: config.values ?? [],- }) as never;- });-}--function createTimeoutControl(): SessionTimeoutControl {- return {- dispose: vi.fn(async () => undefined),- start: vi.fn(async () => undefined),- };-}--function createMockHook<T>(input: {- readonly dispose?: () => void;- readonly getConflict?: () => Promise<{ readonly runId: string } | null>;- readonly next?: () => Promise<IteratorResult<T>>;- readonly return?: () => Promise<IteratorResult<T>>;- readonly symbolDispose?: () => void;- readonly token: string;- readonly values: readonly T[];-}): unknown {- const values = [...input.values];- const dispose = input.dispose ?? vi.fn();- const getConflict = input.getConflict ?? vi.fn(async () => null);- const symbolDispose = input.symbolDispose ?? vi.fn();- const iteratorReturn = input.return;-- return Object.assign(Promise.resolve(undefined), {- [Symbol.asyncIterator]() {- return {- next:- input.next ??- async function next(): Promise<IteratorResult<T>> {- const value = values.shift();- if (value === undefined) {- return { done: true, value: undefined };- }- return { done: false, value };- },- return: iteratorReturn,- };- },- [Symbol.dispose]: symbolDispose,- dispose,- getConflict,- token: input.token,- });-}--function createIteratorReturn(): () => Promise<IteratorResult<never>> {- return vi.fn(async (): Promise<IteratorResult<never>> => ({- done: true,- value: undefined,- }));-}--function nonTurnHookTokens(): string[] {- return vi- .mocked(createHook)- .mock.calls.map((call) => call[0]?.token)- .filter(- (token): token is string =>- token !== undefined &&- token !== sessionCommandHookToken("wrun_test_123") &&- !token.endsWith(":auth") &&- !isTurnCompletionToken(token),- );-}--function isTurnCompletionToken(token: string): boolean {- return /:turn-control:\d+$/.test(token);-}diff --git a/packages/eve/src/execution/workflow-entry.ts b/packages/eve/src/execution/workflow-entry.tsdeleted file mode 100644index ee769869c..000000000--- a/packages/eve/src/execution/workflow-entry.ts+++ /dev/null@@ -1,618 +0,0 @@-import { getWorkflowMetadata, getWritable } from "#compiled/@workflow/core/index.js";--import type {- DeliverHookPayload,- DeliverPayload,- HookPayload,- RunInput,- SessionCommand,- SessionCapabilities,-} from "#channel/types.js";-import { readChannelRequestId, readRootSessionId } from "#execution/eve-workflow-attributes.js";-import {- createSafeOuterWorkflowError,- type CrashCleanupState,- hasDelegatedCallerContext,- resolveCallerForCrash,-} from "#execution/workflow-entry-crash.js";-import type { AgentWorkflowRetentionDefinition } from "#shared/agent-definition.js";-import type { RunMode } from "#shared/run-mode.js";-import type { DurableCompiledArtifactsSource } from "#runtime/durable-compiled-artifacts-source.js";-import {- bindTurnCallerContextStep,- notifyCancelledTaskCallerStep,- notifyDelegatedParentStep,- notifyTurnCallerStep,- resolveInitialTurnCallerStep,-} from "#subagents/parent-notification.js";-import { createDelegatedSubagentErrorResult } from "#subagents/parent-result.js";-import type { DurableSessionState } from "#execution/durable-session-store.js";-import { nextTurnDelivery, type NextTurnInstruction } from "#execution/parked-delivery-wait.js";-import { SessionStateCursor } from "#execution/session-state-cursor.js";-import { rebaseTaskAgentHandleMutations } from "#subagents/handles/rebase.js";-import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-step.js";-import { dispatchAndAwaitTurn } from "#execution/turn-dispatch.js";-import type { TurnDriverAction } from "#execution/turn-control-receiver.js";-import { normalizeSerializableError } from "#execution/workflow-errors.js";-import { createSessionStep } from "#execution/create-session-step.js";-import { settleCancelledTurnStep } from "#execution/settle-cancelled-turn-step.js";-import { emitTerminalSessionFailureStep } from "#execution/terminal-session-failure-step.js";-import { fireSessionCallbackStep } from "#subagents/callback-step.js";-import { finalizeDone, finalizeExpiredSession } from "#execution/workflow-entry-finalization.js";-import { isHookConflictError } from "#execution/hook-ownership.js";-import {- createSessionCommandInbox,- type SessionCommandInbox,-} from "#execution/session-command-inbox.js";-import { sessionCommandHookToken } from "#execution/session-command-token.js";-import { DEFAULT_SESSION_TIMEOUT_MS } from "#execution/session-timeout.js";-import { createSessionTimeoutControl } from "#execution/session-timeout-control.js";-import { terminateChildSessionsStep } from "#execution/terminate-child-sessions-step.js";-import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";-import { attachClientContext, readClientContext } from "#internal/client-context.js";-import { settleContinuationConflictStep } from "#execution/continuation-conflict-step.js";-import {- SESSION_INBOX_CONTEXT_KEY,- SESSION_INBOX_WIRE_VERSION,-} from "#execution/wire/session-inbox-contract.js";--// workflow-entry.ts is the durable workflow body — the bundler rejects-// node built-ins here, so `internal/logging.ts` cannot be imported.-// Error logging happens inside `emitTerminalSessionFailureStep`.--/**- * Serializable workflow-entry input. All runtime state travels via- * `serializedContext`, which is produced by `serializeContext(ctx)`- * and deserialized at each `"use step"` boundary.- */-export interface WorkflowEntryInput {- readonly activityCollectorRunId?: string;- readonly continuationConflictCommand?: Extract<SessionCommand, { readonly kind: "send" }>;- readonly input: RunInput["input"];- readonly limits?: RunInput["limits"];- readonly retention?: AgentWorkflowRetentionDefinition;- readonly sessionTimeoutMs?: number | false;- readonly serializedContext: Record<string, unknown>;- readonly taskId?: string;-}--export interface WorkflowEntryResult {- readonly output: unknown;-}--type DriverLoopOutcome =- | {- readonly kind: "expired";- readonly serializedContext: Record<string, unknown>;- readonly sessionState: DurableSessionState;- }- | {- readonly kind: "result";- readonly result: WorkflowEntryResult;- };--/**- * Long-lived workflow entrypoint. Handles both root sessions and- * delegated child sessions: root sessions expose only parent- * control-plane events; delegated children publish their full progress- * on a child stream and resume the parked parent with a- * `subagent-result` on completion.- *- * Owns the stable command inbox, its channel alias, and the session lifecycle; each turn-owned- * turn resolves its own runtime actions in-line and reports back only- * `done`/`park` via the closed-contract {@link NextDriverAction}. The- * only session-shape flag the driver reads (besides identity) is- * `hasProxyInputRequests`, the documented short-circuit for hook-payload- * routing to any descendant still active when the parent parks.- */-export async function workflowEntry(input: WorkflowEntryInput): Promise<WorkflowEntryResult> {- "use workflow";-- const { workflowRunId: sessionId, workflowStartedAt } = getWorkflowMetadata();- const continuationToken = (input.serializedContext["eve.continuationToken"] as string) || "";- const mode = input.serializedContext["eve.mode"] as RunMode;- const capabilities = input.serializedContext["eve.capabilities"] as- | SessionCapabilities- | undefined;- const serializedBundle = input.serializedContext["eve.bundle"] as {- source: DurableCompiledArtifactsSource;- nodeId?: string;- };-- // Seed `eve.sessionId` so the terminal failure emitter can stamp it- // onto `session.failed` even if `createSessionStep` itself throws.- input.serializedContext["eve.sessionId"] = sessionId;- // The driver stays pinned while turn steps can move to newer deployments.- input.serializedContext[SESSION_INBOX_CONTEXT_KEY] = {- sessionId,- version: SESSION_INBOX_WIRE_VERSION,- };-- const driverWritable = getWritable<Uint8Array>();- const crashCleanupState: CrashCleanupState = {- caller: undefined,- callerResolved: false,- lastSessionState: undefined,- serializedContext: input.serializedContext,- terminalEmitted: false,- };-- try {- // Derived once and reused for createSession + tag emission so the- // chain-root id can never drift between persisted session and tags.- const rootSessionIdFromParent = readRootSessionId(input.serializedContext);- const dynamicSubagentAgentConfig = input.serializedContext["eve.dynamicSubagentAgentConfig"] as- | DynamicSubagentAgentConfig- | undefined;-- const commandInbox = createSessionCommandInbox();- const stableCommandToken = sessionCommandHookToken(sessionId);- const authorizationHookToken = `${sessionId}:auth`;- let sessionState: DurableSessionState;- let outcome: DriverLoopOutcome;- try {- const [sessionCreation, stableClaim, authorizationClaim, continuationClaim] =- await Promise.allSettled([- createSessionStep({- compiledArtifactsSource: serializedBundle.source,- continuationToken,- dynamicSubagentAgentConfig,- inheritedLimits: input.limits,- nodeId: serializedBundle.nodeId,- outputSchema: input.input.outputSchema,- rootSessionId: rootSessionIdFromParent,- sessionId,- taskId: input.taskId,- }),- commandInbox.claimStable(stableCommandToken),- commandInbox.claimAuthorization(authorizationHookToken),- commandInbox.rekeyContinuation(continuationToken),- ]);-- if (sessionCreation.status === "rejected") throw sessionCreation.reason;- if (stableClaim.status === "rejected") throw stableClaim.reason;- if (authorizationClaim.status === "rejected") throw authorizationClaim.reason;- if (continuationClaim.status === "rejected") {- // Two runs can race for the same continuation alias (e.g. two messages- // hit one thread before either session owns it). Only the winner runs- // a turn; the loser forwards its `send` to the owner and exits with an- // empty result, since it produced nothing.- if (isHookConflictError(continuationClaim.reason)) {- if (- input.activityCollectorRunId !== undefined ||- input.continuationConflictCommand !== undefined- ) {- await settleContinuationConflictStep({- activityCollectorRunId: input.activityCollectorRunId,- command: input.continuationConflictCommand,- continuationToken,- ownerSessionId:- typeof continuationClaim.reason.conflictingRunId === "string"- ? continuationClaim.reason.conflictingRunId- : undefined,- });- }- return { output: "" };- }- throw continuationClaim.reason;- }-- sessionState = sessionCreation.value.state;- crashCleanupState.lastSessionState = sessionState;- crashCleanupState.caller = hasDelegatedCallerContext(input.serializedContext)- ? await resolveInitialTurnCallerStep({ serializedContext: input.serializedContext })- : undefined;- crashCleanupState.callerResolved = true;-- outcome = await runDriverLoop({- capabilities,- commandInbox,- driverWritable,- initialInput: {- deliveryMetadata:- input.serializedContext["eve.channelDelivery"] === undefined- ? undefined- : [- {- ...(input.serializedContext["eve.channelDelivery"] as NonNullable<- RunInput["delivery"]- >),- payloadIndex: 0,- },- ],- kind: "deliver",- payloads: [- attachClientContext(- {- message: input.input.message,- context: input.input.context,- outputSchema: input.input.outputSchema,- },- readClientContext(input.input),- ),- ],- requestId: readChannelRequestId(input.serializedContext),- },- crashCleanupState,- mode,- retention: input.retention,- serializedContext: input.serializedContext,- sessionState,- sessionTimeoutDeadline:- input.sessionTimeoutMs === false- ? undefined- : new Date(- workflowStartedAt.getTime() +- (input.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS),- ),- stableCommandToken,- });- } finally {- await commandInbox.dispose();- }- if (outcome.kind === "result") {- return outcome.result;- }- return await finalizeExpiredSession({- caller: crashCleanupState.caller,- driverWritable,- mode,- serializedContext: outcome.serializedContext,- sessionState: outcome.sessionState,- terminalState: crashCleanupState,- });- } catch (error) {- const terminalAlreadyEmitted = crashCleanupState.terminalEmitted;- // Safety net for failures the tool-loop harness does not already- // surface as `session.failed` (deserialization, runtime-action- // throws, adapter `deliver` throws, staging errors, etc.) so the- // channel still sees a terminal event.- if (!crashCleanupState.terminalEmitted && crashCleanupState.lastSessionState !== undefined) {- await terminateChildSessionsStep({- serializedContext: crashCleanupState.serializedContext,- sessionState: crashCleanupState.lastSessionState,- });- }- if (!crashCleanupState.terminalEmitted) {- await emitTerminalSessionFailureStep({- error: normalizeSerializableError(error),- parentWritable: driverWritable,- serializedContext: crashCleanupState.serializedContext,- turnId: crashCleanupState.turnId,- });- crashCleanupState.terminalEmitted = true;- }- if (terminalAlreadyEmitted) throw createSafeOuterWorkflowError();- if (mode === "task") {- await fireSessionCallbackStep({- error: normalizeSerializableError(error),- serializedContext: crashCleanupState.serializedContext,- status: "failed",- });- await notifyDelegatedParentStep({- result: createDelegatedSubagentErrorResult(crashCleanupState.serializedContext, error),- serializedContext: crashCleanupState.serializedContext,- });- } else if (crashCleanupState.caller !== undefined || !crashCleanupState.callerResolved) {- await notifyTurnCallerStep({- caller: await resolveCallerForCrash(crashCleanupState, crashCleanupState.serializedContext),- lifecycle: "terminal",- sessionId,- settled: { isError: true, output: error },- });- }- throw createSafeOuterWorkflowError();- }-}-async function runDriverLoop(input: {- readonly capabilities?: SessionCapabilities;- readonly commandInbox: SessionCommandInbox;- readonly driverWritable: WritableStream<Uint8Array>;- readonly initialInput: HookPayload;- readonly crashCleanupState: CrashCleanupState;- readonly mode: RunMode;- readonly retention?: AgentWorkflowRetentionDefinition;- readonly serializedContext: Record<string, unknown>;- readonly sessionState: DurableSessionState;- readonly sessionTimeoutDeadline?: Date;- readonly stableCommandToken: string;-}): Promise<DriverLoopOutcome> {- const commandInbox = input.commandInbox;- // One payload per exact authorization attempt accumulates across- // intervening turns. Replaced attempts are pruned at each park.- const collectedAuthPayloads = new Map<string, DeliverPayload>();- /**- * Waits for the next parked-session activity. While an authorization- * challenge is open (`expected > 0`), callback reads surface through the- * same single FIFO wait as ordinary session activity — one arrival order,- * which keeps the wait deterministic under workflow replay — and keep- * surfacing across wait iterations that produce no parent turn (no-op- * cancels, fully-routed descendant deliveries). Callbacks accumulate- * across intervening turns; once every expected challenge has reported- * (or the hook closed), the collected payloads resume the challenge.- */- const nextParkedActivity = async (park: {- readonly expectedAttemptIds: readonly string[];- }): Promise<- | { readonly kind: "authorization-resume"; readonly payloads: DeliverPayload[] }- | Exclude<NextTurnInstruction, { kind: "authorization" }>- > => {- const expectedAttemptIds = new Set(park.expectedAttemptIds);- for (const attemptId of collectedAuthPayloads.keys()) {- if (!expectedAttemptIds.has(attemptId)) collectedAuthPayloads.delete(attemptId);- }-- while (true) {- if (- expectedAttemptIds.size > 0 &&- [...expectedAttemptIds].every((attemptId) => collectedAuthPayloads.has(attemptId))- ) {- const payloads = [...expectedAttemptIds].map((attemptId) =>- collectedAuthPayloads.get(attemptId)!,- );- collectedAuthPayloads.clear();- return { kind: "authorization-resume", payloads };- }-- const next = await nextTurnDelivery({- awaitAuthorizationCallbacks: expectedAttemptIds.size > 0,- bufferedDeliveries,- bufferedSessionControls,- cancelledTaskIds,- commandInbox,- deferDeliveries: input.mode === "task" && expectedAttemptIds.size > 0,- driverWritable: input.driverWritable,- seenTaskDeliveries,- stateCursor,- });- if (next.kind !== "authorization") return next;-- for (const payload of next.payloads) {- const callback = payload["authorizationCallback"] as- | { readonly attemptId?: unknown }- | undefined;- if (- typeof callback?.attemptId === "string" &&- expectedAttemptIds.has(callback.attemptId) &&- !collectedAuthPayloads.has(callback.attemptId)- ) {- collectedAuthPayloads.set(callback.attemptId, payload);- }- }- if (next.closed) {- const payloads = [...collectedAuthPayloads.values()];- collectedAuthPayloads.clear();- return { kind: "authorization-resume", payloads };- }- }- };- // Fast descendant resumes can start the next turn before the prior- // control hook disposal is persisted by the Workflow SDK, so each- // turn needs its own session-scoped token.- let turnDispatchIndex = 0;- const nextTurnControlToken = (): string =>- `${input.sessionState.sessionId}:turn-control:${String(turnDispatchIndex++)}`;-- const bufferedDeliveries: DeliverHookPayload[] = [];- const bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset"> = [];- const cancelledTaskIds = new Set<string>();- const seenTaskDeliveries = new Set<string>();- const stateCursor = new SessionStateCursor({- serializedContext: input.serializedContext,- sessionState: input.sessionState,- });- const sessionTimeout =- input.sessionTimeoutDeadline === undefined- ? undefined- : createSessionTimeoutControl({- deadline: input.sessionTimeoutDeadline,- token: input.stableCommandToken,- });-- // Control-hook disposal is deferred one turn — see DispatchedTurn.- let disposeSettledTurnControl: (() => Promise<void>) | undefined;- const runTurn = async (delivery: HookPayload): Promise<TurnDriverAction> => {- const dispatchedSessionState = stateCursor.sessionState;- const caller = input.crashCleanupState.caller;- if (caller?.taskId !== undefined) {- seenTaskDeliveries.add(caller.taskId);- }- const serializedContext =- caller === undefined- ? stateCursor.serializedContext- : await bindTurnCallerContextStep({- caller,- serializedContext: stateCursor.serializedContext,- });- input.crashCleanupState.turnId = `turn_${String(turnDispatchIndex)}`;- const turn = await dispatchAndAwaitTurn({- bufferedDeliveries,- bufferedSessionControls,- cancelledTaskIds,- capabilities: input.capabilities,- commandInbox,- controlToken: nextTurnControlToken(),- delivery,- mode: input.mode,- parentWritable: input.driverWritable,- retention: input.retention,- serializedContext,- seenTaskDeliveries,- sessionState: stateCursor.sessionState,- stateCursor,- });- await disposeSettledTurnControl?.();- disposeSettledTurnControl = turn.dispose;- const action =- stateCursor.sessionState === dispatchedSessionState- ? turn.action- : rebaseTaskAgentHandleMutations(- turn.action,- stateCursor.sessionState,- dispatchedSessionState,- );- stateCursor.adoptState(action);- input.crashCleanupState.lastSessionState = stateCursor.sessionState;- input.crashCleanupState.serializedContext = stateCursor.serializedContext;- return action;- };-- try {- await sessionTimeout?.start();-- let action: TurnDriverAction = await runTurn(input.initialInput);-- while (true) {- if (action.kind === "done") {- return {- kind: "result",- result: await finalizeDone({- action,- caller: input.crashCleanupState.caller,- mode: input.mode,- terminalState: input.crashCleanupState,- }),- };- }-- if (action.kind !== "park") {- // Turn-owned turns resolve runtime actions in-line and only ever- // report `done`/`park`. The driver-owned `dispatch-*` arms exist- // solely for pre-change pinned drivers, which run their own code.- throw new Error(`Driver received unexpected turn action "${action.kind}".`);- }-- if (action.cancelled === true) {- const settled = await settleCancelledTurnStep({- parentWritable: input.driverWritable,- serializedContext: stateCursor.serializedContext,- sessionState: stateCursor.sessionState,- });- stateCursor.adoptState(settled);- input.crashCleanupState.serializedContext = stateCursor.serializedContext;- const cancelledCaller = {- caller: input.crashCleanupState.caller,- sessionId: stateCursor.sessionState.sessionId,- };- await notifyCancelledTaskCallerStep(- settled.usage === undefined- ? cancelledCaller- : { ...cancelledCaller, usage: settled.usage },- );- input.crashCleanupState.lastSessionState = stateCursor.sessionState;- }-- // Channel-created sessions may rekey their dynamic alias. Sessions- // without one remain reachable through the stable command inbox only.- if (stateCursor.sessionState.continuationToken) {- await commandInbox.rekeyContinuation(stateCursor.sessionState.continuationToken);- }-- // `settled` rides the typed park arm exclusively; `run-step` preserves- // the full StepResult so no state-key fallback exists anymore.- const settled = action.settled;- if (action.cancelled !== true && settled !== undefined) {- if (input.crashCleanupState.caller !== undefined) {- await notifyTurnCallerStep({- caller: input.crashCleanupState.caller,- lifecycle: "parked",- sessionId: stateCursor.sessionState.sessionId,- settled,- });- }- input.crashCleanupState.caller = undefined;- } else if (action.cancelled === true) {- input.crashCleanupState.caller = undefined;- }-- // An open authorization challenge must not wedge the session:- // ordinary deliveries keep starting normal turns while the challenge- // waits for its callback, and the callback surfaces through the same- // parked wait as everything else. The pending challenge survives- // intervening turns because every park re-derives- // `authorizationAttemptIds` from durable session state.- const next = await nextParkedActivity({- expectedAttemptIds: action.authorizationAttemptIds ?? [],- });- input.crashCleanupState.lastSessionState = stateCursor.sessionState;-- if (next.kind === "authorization-resume") {- action = await runTurn({- kind: "deliver",- payloads: next.payloads,- });- continue;- }-- if (next.kind === "expired") {- return {- kind: "expired",- serializedContext: stateCursor.serializedContext,- sessionState: stateCursor.sessionState,- };- }-- if (next.kind === "reset") {- return {- kind: "result",- result: await finalizeExpiredSession({- caller: input.crashCleanupState.caller,- driverWritable: input.driverWritable,- mode: input.mode,- serializedContext: stateCursor.serializedContext,- sessionState: stateCursor.sessionState,- terminalState: input.crashCleanupState,- }),- };- }-- if (next.kind === "clear" || next.kind === "compact") {- action = await runTurn({ kind: next.kind });- continue;- }-- if (next.kind === "closed") {- return {- kind: "result",- result: await finalizeExpiredSession({- caller: input.crashCleanupState.caller,- driverWritable: input.driverWritable,- mode: input.mode,- serializedContext: stateCursor.serializedContext,- sessionState: stateCursor.sessionState,- terminalState: input.crashCleanupState,- }),- };- }-- if (next.kind === "cancel-turn") {- await cancelDescendantTurnsStep({- serializedContext: stateCursor.serializedContext,- sessionState: stateCursor.sessionState,- });- const cancelled = await settleCancelledTurnStep({- parentWritable: input.driverWritable,- serializedContext: stateCursor.serializedContext,- sessionState: stateCursor.sessionState,- });- stateCursor.adoptState(cancelled);- input.crashCleanupState.serializedContext = stateCursor.serializedContext;- // Re-enter with `settled` cleared: the parked answer was already- // delivered to its caller before this wait, so the next iteration- // must not treat it as a fresh settlement.- action = { ...action, settled: undefined };- input.crashCleanupState.caller = undefined;- input.crashCleanupState.lastSessionState = stateCursor.sessionState;- continue;- }-- if (next.delivery.caller !== undefined) {- input.crashCleanupState.caller = next.delivery.caller;- }- action = await runTurn(next.delivery);- }- } finally {- await disposeSettledTurnControl?.();- await sessionTimeout?.dispose();- }-}diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.tsindex 5394e964d..4f5c55a46 100644--- a/packages/eve/src/execution/workflow-runtime.test.ts+++ b/packages/eve/src/execution/workflow-runtime.test.ts@@ -1,3 +1,4 @@+import { sessionInboxHookToken } from "#execution/session-inbox/address.js";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { context as apiContext } from "@opentelemetry/api";import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks";@@ -7,6 +8,7 @@ import {context as otelContext,trace as otelTrace,} from "#compiled/@opentelemetry/api/index.js";+import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";import type { ChannelAdapter } from "#channel/adapter.js";import { attachChannelActivityPresentation } from "#channel/activity-renderer.js";import { ActivityObserverKey, ChannelRequestIdKey, SessionTitleKey } from "#context/keys.js";@@ -16,12 +18,15 @@ import {waitForCommandHookOwner,activityCollectorWorkflowReference,sessionTimeoutWorkflowReference,+ startSessionOwnerStep,startWorkflowOnCurrentDeployment,- turnWorkflowReference,workflowEntryReference,workflowToolRunWorkflowReference,} from "#execution/workflow-runtime.js";-import { sessionCommandHookToken } from "#execution/session-command-token.js";+import {+ sessionCommandHookToken,+ sessionHandoffMarkerToken,+} from "#execution/session-inbox/address.js";import { registerInstrumentationRuntime } from "#instrumentation/runtime.js";import { AgentSpanIdGenerator } from "#tracing/agent-span-id-generator.js";import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";@@ -30,8 +35,9 @@ import { markAgentTraceContext } from "#tracing/agent-trace-context.js";import type { TraceCaptureContext } from "#shared/trace-policy.js";const getHookByTokenMock = vi.fn();-const getRawHookByTokenMock = vi.fn();-const world = { hooks: { getByToken: getRawHookByTokenMock } };+const world = {+ getDeploymentId: vi.fn(async () => "dpl_current"),+};const getRunMock = vi.fn();const getWorldMock = vi.fn();const resumeHookMock = vi.fn();@@ -53,14 +59,16 @@ vi.mock("#runtime/sessions/compiled-agent-cache.js", () => ({beforeEach(() => {cancelRunMock.mockResolvedValue(undefined);- getHookByTokenMock.mockImplementation(async (token: string) => currentSessionHook(token));+ getHookByTokenMock.mockImplementation(async (token: string) => {+ if (token.startsWith(sessionHandoffMarkerToken(""))) throw new HookNotFoundError(token);+ return currentSessionHook(token);+ });getWorldMock.mockResolvedValue(world);- getRawHookByTokenMock.mockImplementation(async (token: string) => currentSessionHook(token));+ resumeHookMock.mockImplementation(async (token: string) => currentSessionHook(token));});afterEach(() => {getHookByTokenMock.mockReset();- getRawHookByTokenMock.mockReset();getRunMock.mockReset();getWorldMock.mockReset();resumeHookMock.mockReset();@@ -80,9 +88,6 @@ describe("workflowEntryReference", () => {expect(workflowEntryReference.workflowId).toBe(`workflow//${packageInfo.name}//workflowEntry`);expect(workflowEntryReference.workflowId).not.toContain("/src/execution/");expect(workflowEntryReference.workflowId).not.toContain("@");- expect(turnWorkflowReference.workflowId).toBe(`workflow//${packageInfo.name}//turnWorkflow`);- expect(turnWorkflowReference.workflowId).not.toContain("/src/execution/");- expect(turnWorkflowReference.workflowId).not.toContain("@");expect(sessionTimeoutWorkflowReference.workflowId).toBe(`workflow//${packageInfo.name}//sessionTimeoutWorkflow`,);@@ -134,6 +139,63 @@ describe("startWorkflowOnCurrentDeployment", () => {});});+describe("session owner starts", () => {+ it("rejects non-exact deployment selectors", async () => {+ getRunMock.mockReturnValue({ getWritable: () => new WritableStream<Uint8Array>() });+ await expect(+ startSessionOwnerStep({+ activationToken: "owner-1:handoff",+ anchorRunId: "anchor-1",+ checkpoint: {} as never,+ delivery: { kind: "deliver", payloads: [] },+ targetDeploymentId: "latest",+ }),+ ).rejects.toThrow("exact deployment id");+ expect(startMock).not.toHaveBeenCalled();+ });++ it("starts a successor on the accepted deployment with the original stream", async () => {+ const sessionWritable = new WritableStream<Uint8Array>();+ getRunMock.mockReturnValue({ getWritable: () => sessionWritable });+ startMock.mockResolvedValue({ runId: "owner-2" });+ const checkpoint = {+ version: 4,+ mode: "conversation",+ serializedContext: {},+ sessionState: { continuationToken: "continuation-1", sessionId: "session-1" },+ sessionTimeoutMs: 60_000,+ } as never;+ const delivery = { kind: "deliver", payloads: [{ message: "hello" }] } as const;++ await expect(+ startSessionOwnerStep({+ activationToken: "owner-1:handoff",+ anchorRunId: "anchor-1",+ checkpoint,+ delivery,+ targetDeploymentId: "deployment-b",+ }),+ ).resolves.toBeUndefined();++ expect(getRunMock).toHaveBeenCalledWith("anchor-1");+ expect(startMock).toHaveBeenCalledWith(+ workflowEntryReference,+ [+ expect.objectContaining({+ activationToken: "owner-1:handoff",+ checkpoint,+ delivery,+ kind: "handoff",+ ownerDeploymentId: "deployment-b",+ sessionWritable,+ sessionId: "anchor-1",+ }),+ ],+ { deploymentId: "deployment-b" },+ );+ });+});+describe("createWorkflowRuntime command dispatch", () => {const NOT_FOUND_TOKEN = "test:no-such-hook";@@ -142,8 +204,8 @@ describe("createWorkflowRuntime command dispatch", () => {return createWorkflowRuntime({ compiledArtifactsSource });}- it("preserves the legacy delivery payload through a continuation alias", async () => {- resumeHookMock.mockResolvedValue({ runId: "driver-run" });+ it("preserves the current send command through a continuation alias", async () => {+ resumeHookMock.mockResolvedValue(currentSessionHook("test:token", "owner-run"));const caller = {callId: "call-1",replyTo: { kind: "hook" as const, token: "parent-turn" },@@ -161,18 +223,16 @@ describe("createWorkflowRuntime command dispatch", () => {},continuationToken: "test:token",}),- ).resolves.toEqual({ sessionId: "driver-run", status: "accepted" });+ ).resolves.toEqual({ sessionId: "owner-run", status: "accepted" });- expect(resumeHookMock).toHaveBeenCalledWith(currentSessionHook("test:token"), {+ expect(resumeHookMock).toHaveBeenCalledWith(sessionInboxHookToken("test:token"), {auth: null,caller,- kind: "deliver",+ kind: "send",payload: { message: "hello" },- payloads: [{ message: "hello" }],requestId: "req_deliver",- version: 1,});- expect(getHookByTokenMock).toHaveBeenCalledWith("test:token");+ expect(getHookByTokenMock).not.toHaveBeenCalled();});it("dispatches commands through the stable session inbox", async () => {@@ -185,9 +245,31 @@ describe("createWorkflowRuntime command dispatch", () => {}),).resolves.toEqual({ sessionId: "session-1", status: "accepted" });- expect(resumeHookMock).toHaveBeenCalledWith(sessionCommandHookToken("session-1"), {- kind: "clear",+ expect(resumeHookMock).toHaveBeenCalledWith(+ sessionInboxHookToken(sessionCommandHookToken("session-1")),+ {+ kind: "clear",+ },+ );+ expect(getHookByTokenMock).not.toHaveBeenCalled();+ });++ it("does not report an accepted command as missing when metadata hydration fails", async () => {+ const { HookNotFoundError } = await import("#compiled/@workflow/errors/index.js");+ resumeHookMock.mockResolvedValue({+ runId: "owner",+ get metadata() {+ throw new HookNotFoundError("identity-read");+ },});+ await expect(+ buildRuntime().dispatchContinuation({+ continuationToken: "alias",+ command: { kind: "send", payload: { message: "once" } },+ }),+ ).rejects.toThrow("command accepted");+ expect(resumeHookMock).toHaveBeenCalledOnce();+ expect(startMock).not.toHaveBeenCalled();expect(getHookByTokenMock).not.toHaveBeenCalled();});@@ -201,16 +283,13 @@ describe("createWorkflowRuntime command dispatch", () => {}),).resolves.toEqual({ sessionId: "session-1", status: "accepted" });- expect(resumeHookMock).toHaveBeenCalledWith(sessionCommandHookToken("session-1"), {- auth: undefined,- caller: undefined,- delivery: undefined,- kind: "send",- payload: { message: "hello" },- requestId: undefined,- taskDeliveryId: undefined,- turnPolicy: undefined,- });+ expect(resumeHookMock).toHaveBeenCalledWith(+ sessionInboxHookToken(sessionCommandHookToken("session-1")),+ {+ kind: "send",+ payload: { message: "hello" },+ },+ );expect(getHookByTokenMock).not.toHaveBeenCalled();});@@ -227,7 +306,7 @@ describe("createWorkflowRuntime command dispatch", () => {deliveryId: delivery.deliveryId,});expect(resumeHookMock).toHaveBeenCalledWith(- sessionCommandHookToken("session-1"),+ sessionInboxHookToken(sessionCommandHookToken("session-1")),expect.objectContaining({ delivery }),);});@@ -239,7 +318,7 @@ describe("createWorkflowRuntime command dispatch", () => {{ command: { kind: "reset" as const }, status: "no_active_session" },])("maps a missing $command.kind target to $status", async ({ command, status }) => {const { HookNotFoundError } = await import("#compiled/@workflow/errors/index.js");- getHookByTokenMock.mockRejectedValue(new HookNotFoundError(NOT_FOUND_TOKEN));+ resumeHookMock.mockRejectedValue(new HookNotFoundError(NOT_FOUND_TOKEN));await expect(buildRuntime().dispatchContinuation({@@ -272,10 +351,13 @@ describe("createWorkflowRuntime command dispatch", () => {sessionId: "session-1",}),).resolves.toEqual({ sessionId: "session-1", status: "accepted" });- expect(resumeHookMock).toHaveBeenCalledWith(sessionCommandHookToken("session-1"), {- kind: "cancel",- turnId: "turn-2",- });+ expect(resumeHookMock).toHaveBeenCalledWith(+ sessionInboxHookToken(sessionCommandHookToken("session-1")),+ {+ kind: "cancel",+ turnId: "turn-2",+ },+ );expect(getHookByTokenMock).not.toHaveBeenCalled();});@@ -290,7 +372,7 @@ describe("createWorkflowRuntime command dispatch", () => {];for (const error of errors) {- resumeHookMock.mockRejectedValueOnce(error);+ resumeHookMock.mockRejectedValue(error);await expect(buildRuntime().dispatchSession({command: { kind: "cancel" },@@ -314,10 +396,10 @@ describe("createWorkflowRuntime command dispatch", () => {it("waits for reset to release the stable command inbox", async () => {const { HookNotFoundError } = await import("#compiled/@workflow/errors/index.js");- resumeHookMock.mockResolvedValue({ runId: "session-1" });- getRawHookByTokenMock.mockRejectedValue(- new HookNotFoundError(sessionCommandHookToken("session-1")),- );+ resumeHookMock.mockResolvedValue(currentSessionHook("eve:token", "session-1"));+ getHookByTokenMock.mockImplementation(async (token: string) => {+ throw new HookNotFoundError(token);+ });await expect(buildRuntime().dispatchContinuation({@@ -325,19 +407,25 @@ describe("createWorkflowRuntime command dispatch", () => {continuationToken: "eve:token",}),).resolves.toEqual({ previousSessionId: "session-1", status: "reset" });- expect(resumeHookMock).toHaveBeenCalledWith(currentSessionHook("eve:token"), {+ expect(resumeHookMock).toHaveBeenCalledWith(sessionInboxHookToken("eve:token"), {kind: "reset",reason: "User requested /new",- version: 1,});- expect(getRawHookByTokenMock).toHaveBeenCalledWith(sessionCommandHookToken("session-1"));+ expect(getHookByTokenMock).toHaveBeenCalledWith(+ sessionInboxHookToken(sessionCommandHookToken("session-1")),+ );+ expect(getHookByTokenMock).toHaveBeenCalledWith(sessionInboxHookToken("eve:token"));});});-function currentSessionHook(token: string) {+function currentSessionHook(token: string, runId = "target-session") {+ const sessionId =+ token.startsWith("eve:session:") && token.endsWith(":inbox")+ ? token.slice("eve:session:".length, -":inbox".length)+ : runId;return {- metadata: { sessionInboxWireVersion: 1 },- runId: "target-session",+ metadata: { sessionId },+ runId,token,};}@@ -348,25 +436,24 @@ describe("createWorkflowRuntime#resolveContinuation", () => {}it("returns the owning session id from the hook lookup", async () => {- getRawHookByTokenMock.mockResolvedValue({ runId: "owner-session" });+ getHookByTokenMock.mockResolvedValue(currentSessionHook("test:token", "owner-session"));await expect(buildRuntime().resolveContinuation("test:token")).resolves.toEqual({sessionId: "owner-session",});- expect(getRawHookByTokenMock).toHaveBeenCalledWith("test:token");- expect(getHookByTokenMock).not.toHaveBeenCalled();+ expect(getHookByTokenMock).toHaveBeenCalledWith(sessionInboxHookToken("test:token"));});it("returns undefined for an unknown token", async () => {const { HookNotFoundError } = await import("#compiled/@workflow/errors/index.js");- getRawHookByTokenMock.mockRejectedValue(new HookNotFoundError("test:token"));+ getHookByTokenMock.mockRejectedValue(new HookNotFoundError("test:token"));await expect(buildRuntime().resolveContinuation("test:token")).resolves.toBeUndefined();});it("rethrows unexpected lookup failures", async () => {const failure = new Error("transient backing-store outage");- getRawHookByTokenMock.mockRejectedValue(failure);+ getHookByTokenMock.mockRejectedValue(failure);await expect(buildRuntime().resolveContinuation("test:token")).rejects.toBe(failure);});@@ -374,7 +461,7 @@ describe("createWorkflowRuntime#resolveContinuation", () => {describe("waitForCommandHookOwner", () => {it("resolves the winning run without hydrating hook metadata", async () => {- getRawHookByTokenMock.mockResolvedValue({+ getHookByTokenMock.mockResolvedValue({get metadata() {throw new Error("Ownership must not read encrypted metadata.");},@@ -382,15 +469,15 @@ describe("waitForCommandHookOwner", () => {});await expect(waitForCommandHookOwner("task:token")).resolves.toEqual({ runId: "winning-run" });- expect(getHookByTokenMock).not.toHaveBeenCalled();+ expect(getHookByTokenMock).toHaveBeenCalledExactlyOnceWith("task:token");});it("does not turn storage failures into missing ownership", async () => {const failure = new Error("backing store unavailable");- getRawHookByTokenMock.mockRejectedValue(failure);+ getHookByTokenMock.mockRejectedValue(failure);await expect(waitForCommandHookOwner("task:token")).rejects.toBe(failure);- expect(getRawHookByTokenMock).toHaveBeenCalledOnce();+ expect(getHookByTokenMock).toHaveBeenCalledOnce();});});@@ -433,7 +520,7 @@ describe("createWorkflowRuntime#createSession", () => {},turnAgent: createTestTurnAgent(),} as never);- getHookByTokenMock.mockResolvedValue({ runId: "driver-run" });+ getHookByTokenMock.mockResolvedValue({ runId: "owner-run" });getRunMock.mockReturnValue({getReadable: () =>new ReadableStream<Uint8Array>({@@ -448,7 +535,7 @@ describe("createWorkflowRuntime#createSession", () => {vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_current");const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;mockBundleAndRun(compiledArtifactsSource);- startMock.mockResolvedValue({ runId: "driver-run" });+ startMock.mockResolvedValue({ runId: "owner-run" });await buildRuntime(compiledArtifactsSource).createSession({adapter,@@ -461,6 +548,8 @@ describe("createWorkflowRuntime#createSession", () => {workflowEntryReference,[{+ kind: "initial",+ ownerDeploymentId: "dpl_current",input: { message: "hello" },serializedContext: expect.objectContaining({"eve.bundle": { source: compiledArtifactsSource },@@ -487,7 +576,7 @@ describe("createWorkflowRuntime#createSession", () => {it("returns without waiting for the stable command inbox", async () => {const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;mockBundleAndRun(compiledArtifactsSource);- startMock.mockResolvedValue({ runId: "driver-run" });+ startMock.mockResolvedValue({ runId: "owner-run" });await expect(buildRuntime(compiledArtifactsSource).createSession({@@ -496,7 +585,7 @@ describe("createWorkflowRuntime#createSession", () => {input: { message: "hello" },mode: "conversation",}),- ).resolves.toMatchObject({ sessionId: "driver-run" });+ ).resolves.toMatchObject({ sessionId: "owner-run" });expect(getHookByTokenMock).not.toHaveBeenCalled();});@@ -504,7 +593,7 @@ describe("createWorkflowRuntime#createSession", () => {it("returns an MCP invocation without checking continuation ownership", async () => {const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;mockBundleAndRun(compiledArtifactsSource);- startMock.mockResolvedValue({ runId: "driver-run" });+ startMock.mockResolvedValue({ runId: "owner-run" });await expect(buildRuntime(compiledArtifactsSource).createSession({@@ -518,7 +607,7 @@ describe("createWorkflowRuntime#createSession", () => {input: { message: "hello" },mode: "task",}),- ).resolves.toMatchObject({ sessionId: "driver-run" });+ ).resolves.toMatchObject({ sessionId: "owner-run" });expect(getHookByTokenMock).not.toHaveBeenCalled();});@@ -526,7 +615,7 @@ describe("createWorkflowRuntime#createSession", () => {it("passes a channel's losing-candidate delivery to the workflow", async () => {const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;mockBundleAndRun(compiledArtifactsSource);- startMock.mockResolvedValue({ runId: "driver-run" });+ startMock.mockResolvedValue({ runId: "owner-run" });const continuationConflictCommand = {auth: null,kind: "send" as const,@@ -550,7 +639,7 @@ describe("createWorkflowRuntime#createSession", () => {it("stores an explicit title alongside the trace-content policy", async () => {const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;mockBundleAndRun(compiledArtifactsSource);- startMock.mockResolvedValue({ runId: "driver-run" });+ startMock.mockResolvedValue({ runId: "owner-run" });const message = "<slack_message>\n<content>ship it</content>\n</slack_message>";await buildRuntime(compiledArtifactsSource).createSession({@@ -572,7 +661,7 @@ describe("createWorkflowRuntime#createSession", () => {it("passes the configured session timeout to the durable workflow", async () => {const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;mockBundleAndRun(compiledArtifactsSource, 86_400_000);- startMock.mockResolvedValue({ runId: "driver-run" });+ startMock.mockResolvedValue({ runId: "owner-run" });await buildRuntime(compiledArtifactsSource).createSession({adapter,@@ -594,7 +683,7 @@ describe("createWorkflowRuntime#createSession", () => {mockBundleAndRun(compiledArtifactsSource, 60_000);startMock.mockResolvedValueOnce({ runId: "collector-run" })- .mockResolvedValueOnce({ runId: "driver-run" });+ .mockResolvedValueOnce({ runId: "owner-run" });await buildRuntime(compiledArtifactsSource).createSession({adapter: activityAdapter(),@@ -628,7 +717,7 @@ describe("createWorkflowRuntime#createSession", () => {mockBundleAndRun(compiledArtifactsSource, false);startMock.mockResolvedValueOnce({ runId: "collector-run" })- .mockResolvedValueOnce({ runId: "driver-run" });+ .mockResolvedValueOnce({ runId: "owner-run" });await buildRuntime(compiledArtifactsSource).createSession({adapter: activityAdapter(),@@ -652,7 +741,7 @@ describe("createWorkflowRuntime#createSession", () => {mockBundleAndRun(compiledArtifactsSource);startMock.mockRejectedValueOnce(new Error("collector failed"))- .mockResolvedValueOnce({ runId: "driver-run" });+ .mockResolvedValueOnce({ runId: "owner-run" });await buildRuntime(compiledArtifactsSource).createSession({adapter: activityAdapter(),@@ -690,7 +779,7 @@ describe("createWorkflowRuntime#createSession", () => {mockBundleAndRun(compiledArtifactsSource);startMock.mockResolvedValueOnce({ runId: "collector-run" })- .mockResolvedValueOnce({ runId: "driver-run" });+ .mockResolvedValueOnce({ runId: "owner-run" });await expect(buildRuntime(compiledArtifactsSource).createSession({adapter: activityAdapter(),@@ -699,7 +788,7 @@ describe("createWorkflowRuntime#createSession", () => {input: { message: "hello" },mode: "conversation",}),- ).resolves.toMatchObject({ sessionId: "driver-run" });+ ).resolves.toMatchObject({ sessionId: "owner-run" });expect(getHookByTokenMock).not.toHaveBeenCalled();expect(cancelRunMock).not.toHaveBeenCalled();@@ -708,7 +797,7 @@ describe("createWorkflowRuntime#createSession", () => {it("serializes the selected dynamic subagent config for the child workflow", async () => {const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;mockBundleAndRun(compiledArtifactsSource, 86_400_000);- startMock.mockResolvedValue({ runId: "driver-run" });+ startMock.mockResolvedValue({ runId: "owner-run" });await createWorkflowRuntime({compiledArtifactsSource,@@ -742,7 +831,7 @@ describe("createWorkflowRuntime#createSession", () => {vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_current");const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;mockBundleAndRun(compiledArtifactsSource);- startMock.mockResolvedValue({ runId: "driver-run" });+ startMock.mockResolvedValue({ runId: "owner-run" });await buildRuntime(compiledArtifactsSource).createSession({adapter,@@ -756,6 +845,8 @@ describe("createWorkflowRuntime#createSession", () => {workflowEntryReference,[{+ kind: "initial",+ ownerDeploymentId: "dpl_current",input: { message: "hello" },serializedContext: expect.objectContaining({[ChannelRequestIdKey.name]: "req_run",@@ -818,6 +909,7 @@ describe("createWorkflowRuntime#createSession", () => {"$eve.trigger": "subagent","$eve.type": "subagent",},+ deploymentId: "dpl_current",});});@@ -841,7 +933,7 @@ describe("createWorkflowRuntime#createSession", () => {it("lets the Workflow world provide its current deployment when Vercel has no id", async () => {const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;mockBundleAndRun(compiledArtifactsSource);- startMock.mockResolvedValue({ runId: "driver-run" });+ startMock.mockResolvedValue({ runId: "owner-run" });await buildRuntime(compiledArtifactsSource).createSession({adapter,@@ -860,6 +952,7 @@ describe("createWorkflowRuntime#createSession", () => {"$eve.trigger": "http","$eve.type": "session",},+ deploymentId: "dpl_current",});});@@ -881,8 +974,8 @@ describe("createWorkflowRuntime#createSession", () => {}),);getRunMock.mockReturnValue({ getReadable });- startMock.mockResolvedValue({ runId: "driver-run" });- getHookByTokenMock.mockResolvedValue({ runId: "driver-run" });+ startMock.mockResolvedValue({ runId: "owner-run" });+ getHookByTokenMock.mockResolvedValue({ runId: "owner-run" });const handle = await buildRuntime(compiledArtifactsSource).createSession({adapter,@@ -899,7 +992,7 @@ describe("createWorkflowRuntime#createSession", () => {reader.releaseLock();expect(event.value).toEqual({ type: "test.event" });- expect(getRunMock).toHaveBeenCalledWith("driver-run");+ expect(getRunMock).toHaveBeenCalledWith("owner-run");expect(getReadable).toHaveBeenCalledTimes(1);});@@ -927,7 +1020,7 @@ describe("createWorkflowRuntime#createSession", () => {});const stream = await buildRuntime({} as RuntimeCompiledArtifactsSource).getEventStream(- "driver-run",+ "owner-run",);await expect(stream.getReader().read()).resolves.toEqual({@@ -968,7 +1061,7 @@ describe("createWorkflowRuntime#createSession trace seed allocation", () => {workspaceSpec: { rootEntries: [] },},} as never);- getHookByTokenMock.mockResolvedValue({ runId: "driver-run" });+ getHookByTokenMock.mockResolvedValue({ runId: "owner-run" });getRunMock.mockReturnValue({getReadable: () =>new ReadableStream<Uint8Array>({@@ -1009,7 +1102,7 @@ describe("createWorkflowRuntime#createSession trace seed allocation", () => {const tracePolicy = vi.fn(() => true);installAgentOtelRuntime(idGenerator, tracePolicy);mockBundleAndRun();- startMock.mockResolvedValue({ runId: "driver-run" });+ startMock.mockResolvedValue({ runId: "owner-run" });await buildRuntime().createSession({adapter,@@ -1058,7 +1151,7 @@ describe("createWorkflowRuntime#createSession trace seed allocation", () => {shutdown: async () => undefined,} as never);mockBundleAndRun();- startMock.mockResolvedValue({ runId: "driver-run" });+ startMock.mockResolvedValue({ runId: "owner-run" });await buildRuntime().createSession({adapter: { kind: "slack" },@@ -1074,7 +1167,7 @@ describe("createWorkflowRuntime#createSession trace seed allocation", () => {it("allocates an unsampled trace seed when the policy is unsampled", async () => {installAgentOtelRuntime(new AgentSpanIdGenerator(), () => false);mockBundleAndRun();- startMock.mockResolvedValue({ runId: "driver-run" });+ startMock.mockResolvedValue({ runId: "owner-run" });await buildRuntime().createSession({adapter,@@ -1140,7 +1233,7 @@ describe("createWorkflowRuntime#createSession trace seed allocation", () => {it("does not allocate a seed when no instrumentation runtime is installed", async () => {mockBundleAndRun();- startMock.mockResolvedValue({ runId: "driver-run" });+ startMock.mockResolvedValue({ runId: "owner-run" });await buildRuntime().createSession({adapter,@@ -1170,7 +1263,7 @@ describe("createWorkflowRuntime#createSession trace seed allocation", () => {shutdown: async () => undefined,} as never);mockBundleAndRun();- startMock.mockResolvedValue({ runId: "driver-run" });+ startMock.mockResolvedValue({ runId: "owner-run" });await buildRuntime().createSession({adapter,diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.tsindex c66de7c8a..50397e298 100644--- a/packages/eve/src/execution/workflow-runtime.ts+++ b/packages/eve/src/execution/workflow-runtime.ts@@ -12,6 +12,7 @@ import { getChannelActivityPresentation } from "#channel/activity-renderer.js";import type {CancelTurnInput,CancelTurnResult,+ DeliverHookPayload,DispatchContinuationInput,DispatchSessionInput,GetEventStreamOptions,@@ -32,7 +33,7 @@ import { resolveInstalledPackageInfo } from "#internal/application/package.js";import { createLogger, logError } from "#internal/logging.js";import {cancelRun,- getRawHookByToken,+ getHookByToken,getRun,getWorld,start,@@ -54,7 +55,11 @@ import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-import { buildRunContext } from "#execution/runtime-context.js";import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";import { parseNdjsonStream } from "#execution/ndjson-stream.js";-import type { WorkflowEntryInput } from "#execution/workflow-entry.js";+import type {+ HandoffWorkflowEntryInput,+ InitialWorkflowEntryInput,+} from "#execution/session/entry-input.js";+import type { SessionCheckpoint } from "#execution/session/handoff.js";import type { ActivityCollectorInput } from "#execution/activity-collector.js";import { createEveActivityRoutePath } from "#protocol/routes.js";import {@@ -64,8 +69,16 @@ import {import { walkCauseChain } from "#shared/errors.js";import { buildInvocationAttributes } from "#internal/invocation/metadata.js";import { isAgentTraceContext } from "#tracing/agent-trace-context.js";-import { sessionCommandHookToken } from "#execution/session-command-token.js";-import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";+import {+ sessionCommandHookToken,+ sessionInboxHookToken,+} from "#execution/session-inbox/address.js";+import {+ AcceptedSessionIdentityError,+ resolveSessionInbox,+ resumeSessionInbox,+} from "#execution/session-inbox/resume.js";+import type { SessionInboxAddress } from "#execution/session-inbox/address.js";import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";import { initializeSessionInstrumentation } from "#instrumentation/runtime.js";import {@@ -73,7 +86,6 @@ import {SESSION_TIMEOUT_WORKFLOW_NAME,TASK_RUN_WORKFLOW_NAME,WORKFLOW_TOOL_RUN_WORKFLOW_NAME,- TURN_WORKFLOW_NAME,WORKFLOW_ENTRY_NAME,} from "#execution/stable-workflow-names.js";const EVE_PACKAGE_INFO = resolveInstalledPackageInfo();@@ -88,26 +100,20 @@ interface WorkflowHookRecord {readonly runId: string;}+interface SessionInboxOwnerRecord extends WorkflowHookRecord {+ readonly sessionId: string;+}+/*** Stable workflow reference used by `start()` to locate the workflow* entrypoint registered by the Workflow DevKit builder. The id omits- * the package version stamp so the long-lived driver can rotate across+ * the package version stamp so the long-lived owner can rotate across* deployments without rewriting the registry key.*/export const workflowEntryReference = {workflowId: `workflow//${STABLE_ID_BASE}//${WORKFLOW_ENTRY_NAME}`,};-/**- * Stable workflow reference used by the driver to dispatch per-turn- * child workflow runs. The id omits the package version stamp so an- * explicitly stamped accepting deployment can resolve the workflow even- * when its eve version differs from the driver's deployment.- */-export const turnWorkflowReference = {- workflowId: `workflow//${STABLE_ID_BASE}//${TURN_WORKFLOW_NAME}`,-};-/** Stable workflow reference for session deadline timers. */export const sessionTimeoutWorkflowReference = {workflowId: `workflow//${STABLE_ID_BASE}//${SESSION_TIMEOUT_WORKFLOW_NAME}`,@@ -129,8 +135,8 @@ export const workflowToolRunWorkflowReference = {};/**- * Creates a workflow-backed runtime whose long-lived driver owns the- * event stream and dispatches each turn as a child workflow run.+ * Creates a workflow-backed runtime whose current owner executes turns and+ * whose original run retains the public event stream across owner handoffs.*/export function createWorkflowRuntime(config: {readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;@@ -203,13 +209,15 @@ export function createWorkflowRuntime(config: {const serializedContext = serializeContext(ctx);const parentLineage = readParentLineage(serializedContext);const workflowInput: {- -readonly [K in keyof WorkflowEntryInput]: WorkflowEntryInput[K];+ -readonly [K in keyof InitialWorkflowEntryInput]: InitialWorkflowEntryInput[K];} = {+ kind: "initial",input: input.input,- limits: input.limits,+ ownerDeploymentId: await resolveCurrentWorkflowDeploymentId(),serializedContext,};const taskId = input.taskId ?? input.callback?.taskId;+ if (input.limits !== undefined) workflowInput.limits = input.limits;if (taskId !== undefined) workflowInput.taskId = taskId;if (collectorRunId !== undefined) {workflowInput.activityCollectorRunId = collectorRunId;@@ -245,11 +253,17 @@ export function createWorkflowRuntime(config: {let run: Awaited<ReturnType<typeof startWorkflowOnCurrentDeployment>>;try {- run = await startWorkflowOnCurrentDeployment(workflowEntryReference, [workflowInput], {+ const startOptions: StartOptionsWithoutDeploymentId = {allowReservedAttributes: true,attributes: normalizeEveAttributes(attributes),- experimental_retention: retention,- });+ };+ if (retention !== undefined) startOptions.experimental_retention = retention;+ run = await startWorkflowOnDeployment(+ workflowEntryReference,+ [workflowInput],+ workflowInput.ownerDeploymentId,+ startOptions,+ );} catch (error) {await cancelActivityCollector(collectorRunId);logError(log, "failed to start workflow run", error, {@@ -284,7 +298,7 @@ export function createWorkflowRuntime(config: {async dispatchSession<TCommand extends SessionCommand>(input: DispatchSessionInput<TCommand>,): Promise<SessionCommandResult<TCommand>> {- return await dispatchWorkflowCommand(sessionCommandHookToken(input.sessionId), input.command);+ return await dispatchWorkflowCommand({ sessionId: input.sessionId }, input.command);},async getEventStream(@@ -311,8 +325,7 @@ export function createWorkflowRuntime(config: {continuationToken: string,): Promise<{ sessionId: string } | undefined> {try {- const hook = await getRawHookByToken(continuationToken);- return { sessionId: hook.runId };+ return await resolveSessionInbox(continuationToken);} catch (error) {if (HookNotFoundError.is(error)) {return undefined;@@ -326,6 +339,37 @@ export function createWorkflowRuntime(config: {};}+export interface SessionOwnerStartInput {+ readonly activationToken: string;+ /** Original run whose stream stays the public session stream. */+ readonly anchorRunId: string;+ readonly checkpoint: SessionCheckpoint;+ readonly delivery: DeliverHookPayload;+ readonly targetDeploymentId: string;+}++/** Starts a successor owner and binds its output to the original session stream. */+export async function startSessionOwnerStep(input: SessionOwnerStartInput): Promise<void> {+ "use step";+ const workflowInput: HandoffWorkflowEntryInput = {+ activationToken: input.activationToken,+ checkpoint: input.checkpoint,+ delivery: input.delivery,+ kind: "handoff",+ ownerDeploymentId: input.targetDeploymentId,+ sessionWritable: getRun(input.anchorRunId).getWritable<Uint8Array>(),+ sessionId: input.anchorRunId,+ };+ await startWorkflowOnDeployment(+ workflowEntryReference,+ [workflowInput],+ input.targetDeploymentId,+ input.checkpoint.retention === undefined+ ? undefined+ : { experimental_retention: input.checkpoint.retention },+ );+}+function normalizePersistedEvent(value: unknown): MessageStreamEvent {return normalizePersistedMessageStreamEvent(value as MessageStreamEventForVersion<MessageStreamVersion>,@@ -344,12 +388,13 @@ async function cancelActivityCollector(runId: string | undefined): Promise<void>}async function dispatchWorkflowCommand<TCommand extends SessionCommand>(- token: string,+ token: string | SessionInboxAddress,command: TCommand,): Promise<SessionCommandResult<TCommand>> {- let hook: WorkflowHookRecord;+ let hook: SessionInboxOwnerRecord;try {- hook = normalizeWorkflowHook(await resumeSessionInbox(token, command));+ const resumed = await resumeSessionInbox(token, command);+ hook = { runId: resumed.ownerRunId, sessionId: await resumed.sessionId };} catch (error) {if (isInactiveCommandTarget(error)) {return inactiveCommandResult(command);@@ -362,10 +407,17 @@ async function dispatchWorkflowCommand<TCommand extends SessionCommand>(}if (command.kind === "reset") {- await waitForCommandHookRelease(sessionCommandHookToken(hook.runId), hook.runId);+ const addressedToken =+ typeof token === "string" ? token : sessionCommandHookToken(token.sessionId);+ const tokens = new Set([sessionCommandHookToken(hook.sessionId), addressedToken]);+ await Promise.all(+ [...tokens].map((logicalToken) =>+ waitForHookRelease(sessionInboxHookToken(logicalToken), hook.runId),+ ),+ );}- return activeCommandResult(command, hook.runId);+ return activeCommandResult(command, hook.sessionId);}function activeCommandResult<TCommand extends SessionCommand>(@@ -403,10 +455,11 @@ export async function requestWorkflowTurnCancellation(if (input.taskId !== undefined) command.taskId = input.taskId;if (input.tasks !== undefined) command.tasks = input.tasks;if (input.turnId !== undefined) command.turnId = input.turnId;- return await dispatchWorkflowCommand(sessionCommandHookToken(input.sessionId), command);+ return await dispatchWorkflowCommand({ sessionId: input.sessionId }, command);}function isInactiveCommandTarget(error: unknown): boolean {+ if (error instanceof AcceptedSessionIdentityError) return false;if (HookNotFoundError.is(error)) return true;for (const candidate of walkCauseChain(error)) {if (@@ -429,7 +482,7 @@ export async function waitForCommandHookOwner(token: string): Promise<WorkflowHoconst deadline = Date.now() + COMMAND_HOOK_READY_TIMEOUT_MS;while (true) {try {- return normalizeWorkflowHook(await getRawHookByToken(token));+ return normalizeWorkflowHook(await getHookByToken(token));} catch (error) {if (!HookNotFoundError.is(error) || Date.now() >= deadline) throw error;await new Promise<void>((resolve) => setTimeout(resolve, 20));@@ -437,19 +490,19 @@ export async function waitForCommandHookOwner(token: string): Promise<WorkflowHo}}-async function waitForCommandHookRelease(token: string, sessionId: string): Promise<void> {+async function waitForHookRelease(token: string, ownerRunId: string): Promise<void> {const deadline = Date.now() + COMMAND_HOOK_READY_TIMEOUT_MS;while (true) {try {- const owner = normalizeWorkflowHook(await getRawHookByToken(token));- if (owner.runId !== sessionId) return;+ const owner = normalizeWorkflowHook(await getHookByToken(token));+ if (owner.runId !== ownerRunId) return;} catch (error) {if (HookNotFoundError.is(error)) return;throw error;}if (Date.now() >= deadline) {- throw new Error(`Timed out waiting for session "${sessionId}" to release its command inbox.`);+ throw new Error(`Timed out waiting for session "${ownerRunId}" to release inbox "${token}".`);}await new Promise<void>((resolve) => setTimeout(resolve, 20));}@@ -464,7 +517,7 @@ export async function startWorkflowOnCurrentDeployment<TArgs extends unknown[],return await startWorkflowOnDeployment(workflow,args,- process.env.VERCEL_DEPLOYMENT_ID?.trim() || undefined,+ await resolveCurrentWorkflowDeploymentId(),options,);}@@ -473,35 +526,30 @@ export async function startWorkflowOnCurrentDeployment<TArgs extends unknown[],* Starts on the deployment that accepted a delivery when one was stamped,* otherwise stays on the deployment executing this call.*/-export async function startWorkflowOnAcceptedDeployment<TArgs extends unknown[], TResult>(- workflow: WorkflowFunction<TArgs, TResult> | WorkflowMetadata,- args: TArgs,- acceptedDeploymentId: string | undefined,- options?: StartOptionsWithoutDeploymentId,-): Promise<Run<unknown> | Run<TResult>> {- if (acceptedDeploymentId === undefined) {- return await startWorkflowOnCurrentDeployment(workflow, args, options);- }-- return await startWorkflowOnDeployment(workflow, args, acceptedDeploymentId, options);-}async function startWorkflowOnDeployment<TArgs extends unknown[], TResult>(workflow: WorkflowFunction<TArgs, TResult> | WorkflowMetadata,args: TArgs,- deploymentId: string | undefined,+ deploymentId: string,options?: StartOptionsWithoutDeploymentId,): Promise<Run<unknown> | Run<TResult>> {return await withWorkflowStartContext(async () => {- if (deploymentId !== undefined) {- return await start(workflow, args, { ...options, deploymentId });+ if (deploymentId.length === 0 || deploymentId === "latest") {+ throw new Error("Workflow starts require an exact deployment id.");}- return options === undefined- ? await start(workflow, args)- : await start(workflow, args, options);+ return await start(workflow, args, { ...options, deploymentId });});}+async function resolveCurrentWorkflowDeploymentId(): Promise<string> {+ const deploymentId =+ process.env.VERCEL_DEPLOYMENT_ID?.trim() || (await (await getWorld()).getDeploymentId());+ if (deploymentId.length === 0 || deploymentId === "latest") {+ throw new Error("Workflow runtime could not resolve an exact deployment id.");+ }+ return deploymentId;+}+async function withWorkflowStartContext<TResult>(callback: () => Promise<TResult>) {// Agent parentage is reconstructed from Eve's serialized trace context. Only// remove the ambient span marked by an agent boundary; the marker is notdiff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.tsdeleted file mode 100644index 3efdaecbf..000000000--- a/packages/eve/src/execution/workflow-steps.ts+++ /dev/null@@ -1,685 +0,0 @@-import { buildAdapterContext } from "#channel/adapter-context.js";-import { callAdapterEventHandler, defaultDeliverResult } from "#channel/adapter.js";-import type { DeliverHookPayload } from "#channel/types.js";-import { contextStorage } from "#context/container.js";-import { dispatchStreamEventHooks } from "#context/hook-lifecycle.js";-import {- dispatchDynamicInstructionEvent,- drainDynamicInstructionUserMessages,- prepareDynamicInstructionPreamble,-} from "#context/dynamic-instruction-lifecycle.js";-import { dispatchDynamicModelEvent } from "#context/dynamic-model-lifecycle.js";-import { dispatchDynamicSkillEvent } from "#context/dynamic-skill-lifecycle.js";-import {- dispatchDynamicSubagentEvent,- refreshDynamicSessionSubagentsForRuntimeRevision,-} from "#context/dynamic-subagent-lifecycle.js";-import {- dispatchDynamicToolEvent,- rebindMissingCompiledDynamicToolCallbacks,- refreshDynamicSessionToolsForRuntimeRevision,-} from "#context/dynamic-tool-lifecycle.js";-import { dispatchMemoryLifecycleEvent } from "#context/memory-event-lifecycle.js";-import {- AuthKey,- CapabilitiesKey,- ChannelDeliveryKey,- HandleEventKey,- ModeKey,- ScheduleIdKey,- SessionDynamicSubagentRuntimeRevisionKey,- SessionDynamicToolRuntimeRevisionKey,- StaticModelReferenceKey,- TurnTaskDeliveryKey,- TurnDeliveryIdsKey,-} from "#context/keys.js";-import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";-import { deserializeContext, serializeContext } from "#context/serialize.js";-import {- emitTurnPreamble,- getHarnessEmissionState,- isHarnessBetweenTurns,- setHarnessEmissionState,-} from "#harness/emission.js";-import { bindSessionInstrumentation } from "#instrumentation/runtime.js";-import { RuntimeActionSettlementTimesKey } from "#harness/runtime-action-settlement-state.js";-import { preserveSerializedBackgroundTaskObservabilityState } from "#shared/serialized-observability-state.js";-import * as agentTraceState from "#tracing/agent-trace-context-store.js";-import { matchAuthorizationCallbacks } from "#execution/authorization-callback-match.js";-import { isTurnCancellation, throwIfTurnAborted } from "#harness/turn-cancellation.js";-import { setChannelContext } from "#execution/channel-context.js";-import { observeSessionActivity } from "#execution/session-activity-projection.js";-import { hasPendingInputBatch } from "#harness/input-requests.js";-import { activeTurnId } from "#harness/active-turn-id.js";-import { coalesceTurnInputs, type UserModelMessage } from "#harness/messages.js";-import type { HandleEventFn, HarnessSession, StepInput, StepResult } from "#harness/types.js";-import { getTurnUsageState, takeSessionUsageDelta, toUsage } from "#harness/turn-tag-state.js";-import type { DurableStepResult } from "#execution/next-driver-action.js";-import { derivePendingState } from "#execution/pending-turn-state.js";-import {- createAuthorizationCompletedEvent,- createSessionStartedEvent,- createTurnStartedEvent,- encodeMessageStreamEvent,- type UnstampedMessageStreamEvent,- stampMessageStreamEvent,-} from "#protocol/message.js";-import {- CallbackBaseUrlKey,- clearPendingAuthorization,- getPendingAuthorization,- PendingAuthorizationResultKey,-} from "#harness/authorization.js";-import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";-import { forwardTaskEventToSessionCallback } from "#execution/task-event-callback.js";-import { resolveEffectiveOutputSchema } from "#execution/effective-output-schema.js";-import { createDurableSessionState, readDurableSession } from "#execution/durable-session-store.js";-import type { TurnStepInput } from "#execution/durable-session-migrations/turn-workflow.js";-import { buildRuntimeIdentity, createExecutionNodeStep } from "#execution/node-step.js";-import {- getBackgroundTaskDelivery,- markBackgroundTaskStepInput,- resolveInitiatingTaskContext,- resolveTaskDeliveryContext,-} from "#tasks/delivery-context.js";-import { scheduledLaunchDeliveryEvent } from "#execution/scheduled-launch-delivery.js";-import {- readRetainedBackgroundToolResult,- runBackgroundStep,-} from "#execution/tasks/parent/tool-execution.js";-import { prepareWorkflowPreambleTrace } from "#execution/workflow-trace-context.js";-import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";-import { reconcileSessionContinuationToken } from "#execution/reconcile-session-continuation-token.js";-import { hydrateDurableSession, refreshSessionFromTurnAgent } from "#execution/session.js";-import { createExecutionHistoryView } from "#execution/history-view.js";-import { resolveRuntimeCompiledArtifactsVersionedCacheKey } from "#runtime/cache-key.js";-import { createWorkflowRuntime } from "#execution/workflow-runtime.js";-import { bindDynamicConnections } from "#execution/dynamic-connections.js";-import { deferMismatchedInlineTurnStep } from "#execution/accepted-delivery-deployment.js";-import { runModelCallBatch } from "#execution/model-call-batching.js";-import {- createCancelledModelCallBatchResult,- type CompletedModelCallCheckpoint,-} from "#execution/cancelled-model-call-batch.js";-import * as activityCohort from "#execution/activity-cohort.js";--const TASK_DONE_WITH_PENDING_INPUT_ERROR_MESSAGE =- "Task mode cannot complete while input requests remain pending.";--function channelDeliveryErrorCode(error: unknown): string {- if (typeof error === "object" && error !== null && "code" in error) {- const code = (error as { readonly code?: unknown }).code;- if (typeof code === "string" && code.length > 0) return code;- }- return "CHANNEL_DELIVERY_FAILED";-}--export type { TurnStepInput };--/** Runs a bounded batch of harness model steps inside one durable `"use step"` boundary. */-export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResult> {- "use step";-- const deferred = deferMismatchedInlineTurnStep(rawInput);- if (deferred !== undefined) return deferred;-- let input = rawInput;-- let durableSession = await readDurableSession(input.sessionState);- const ctx = await deserializeContext(input.serializedContext);- if (rawInput.input?.kind === "deliver") {- ctx.set(TurnTaskDeliveryKey, "none");- }- const adapter = ctx.require(ChannelKey);- const bundle = ctx.require(BundleKey);- const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);-- // Populate the callback base URL so getHookUrl() works during tool- // execution, preferring eve's active local origin over metadata fallback.- try {- const { getWorkflowMetadata } = await import("#compiled/@workflow/core/index.js");- const metadata = getWorkflowMetadata();- if (typeof metadata.url === "string") {- ctx.set(CallbackBaseUrlKey, resolveWorkflowCallbackBaseUrl(metadata.url));- }- } catch {- // Outside a workflow context (e.g. tests) — getHookUrl will return undefined.- }-- const pendingAuth = getPendingAuthorization(durableSession.state);- let completedAuths: ReturnType<typeof matchAuthorizationCallbacks>["matches"] | undefined;- if (pendingAuth && input.input?.kind === "deliver") {- const { matches, remainingPayloads } = matchAuthorizationCallbacks(- pendingAuth,- input.input.payloads,- );- input = { ...input, input: { ...input.input, payloads: remainingPayloads } };- if (matches.length > 0) {- const matchedAttemptIds = activityCohort.restoreAuthorizationActivity({- ctx,- matches,- pending: pendingAuth,- });- const authResults = matches.map((match) => match.result);- ctx.set(PendingAuthorizationResultKey, authResults);- durableSession = {- ...durableSession,- state: clearPendingAuthorization(durableSession.state, matchedAttemptIds),- };- completedAuths = matches;- if (remainingPayloads.length === 0) {- input = { ...input, input: undefined };- }- }- }-- // Apply deliver-time auth ferried via `resumeHook` (initial-turn- // input has no auth; it was seeded by buildRunContext).- if (input.input?.kind === "deliver" && input.input.auth !== undefined) {- ctx.set(AuthKey, input.input.auth ?? null);- }- const backgroundTaskDelivery = getBackgroundTaskDelivery(input.input);- const initialSession = hydrateDurableSession({- compactionOverrides: {- thresholdPercent: effectiveAgent.thresholdPercent,- },- durable: durableSession,- turnAgent: effectiveAgent.turnAgent,- });- const history = createExecutionHistoryView(initialSession);- const instrumentation = bindSessionInstrumentation({- agentName: effectiveAgent.turnAgent.id,- ctx,- rootSessionId: initialSession.rootSessionId ?? initialSession.sessionId,- sessionId: initialSession.sessionId,- });- const initialEmissionState = getHarnessEmissionState(initialSession.state);-- if (- rawInput.input?.kind === "deliver" &&- rawInput.input.payloads.some((payload) => payload.message !== undefined)- ) {- ctx.set(- TurnDeliveryIdsKey,- rawInput.input.deliveryMetadata?.map((entry) => entry.deliveryId) ?? [],- );- } else if (!initialEmissionState.sessionStarted && ctx.get(ChannelDeliveryKey) !== undefined) {- ctx.set(TurnDeliveryIdsKey, [ctx.require(ChannelDeliveryKey).deliveryId]);- }-- if (rawInput.input?.kind === "deliver") {- await contextStorage.run(ctx, () =>- instrumentation?.instrumentChannelDelivery({- agentName: bundle.turnAgent.id,- ctx,- delivery: rawInput.input as DeliverHookPayload,- rootSessionId: initialSession.rootSessionId ?? initialSession.sessionId,- sequence: initialEmissionState.sequence,- sessionId: initialSession.sessionId,- turnId: activeTurnId(initialEmissionState),- }),- );- }-- const failChannelDeliveries = async (error: unknown): Promise<void> => {- await contextStorage.run(ctx, () =>- instrumentation?.instrumentChannelDelivery({- ctx,- error,- errorCode: channelDeliveryErrorCode(error),- includeTurn: false,- outcome: "failed",- }),- );- await instrumentation?.flush();- };- const adapterCtx = buildAdapterContext(adapter, ctx);-- // Run the adapter's deliver hook for each queued payload and- // coalesce the resulting StepInput values.- let resolved: StepInput | undefined;- if (input.input?.kind === "deliver") {- const results: StepInput[] = [];- try {- for (const payload of input.input.payloads) {- const result = adapter.deliver- ? await adapter.deliver(payload, adapterCtx)- : defaultDeliverResult(payload);-- if (result !== undefined && result !== null) {- results.push(- backgroundTaskDelivery === undefined ? result : markBackgroundTaskStepInput(result),- );- }- }- } catch (error) {- await failChannelDeliveries(error);- throw error;- }- resolved = results.length === 0 ? undefined : results.reduce(coalesceTurnInputs);- } else if (input.input?.kind === "runtime-action-result") {- if (input.input.acceptedAtMsByCallId !== undefined) {- ctx.set(RuntimeActionSettlementTimesKey, input.input.acceptedAtMsByCallId);- }- resolved = { runtimeActionResults: input.input.results };- }-- let taskRootTurnId: string | undefined;- if (resolved !== undefined && backgroundTaskDelivery !== undefined) {- const taskContext = resolveTaskDeliveryContext({- state: durableSession.state,- taskDeliveryId: backgroundTaskDelivery.taskDeliveryId,- });- if (taskContext !== undefined) {- ctx.set(TurnTaskDeliveryKey, taskContext.phase);- taskRootTurnId = taskContext.rootTurnId;- resolved = {- ...resolved,- context: [...(resolved.context ?? []), taskContext.context],- };- }- }-- activityCohort.updateActivityRootForDelivery({- activeTurnId: activeTurnId(initialEmissionState),- ctx,- delivery: rawInput.input?.kind === "deliver" ? rawInput.input : undefined,- sessionState: durableSession.state,- taskRootTurnId,- });-- const taskDeliveryPhase = ctx.get(TurnTaskDeliveryKey);- if (taskDeliveryPhase === "none" || taskDeliveryPhase === "initiating") {- const taskContext = resolveInitiatingTaskContext({- state: durableSession.state,- turnId: activeTurnId(initialEmissionState),- });- if (taskContext !== undefined) {- ctx.set(TurnTaskDeliveryKey, taskContext.phase);- }- }-- if (input.input?.kind === "deliver") {- const updatedAdapter = { ...adapter, state: { ...adapterCtx.state } };- setChannelContext(ctx, updatedAdapter);- }-- if (input.input?.kind === "deliver" && resolved === undefined) {- await contextStorage.run(ctx, () =>- instrumentation?.instrumentChannelDelivery({- ctx,- includeTurn: false,- outcome: "completed",- }),- );- await instrumentation?.flush();- const rekeyed = reconcileSessionContinuationToken(ctx, initialSession);- const nextSerializedContext = serializeContext(ctx);- const nextState =- rekeyed === initialSession- ? input.sessionState- : createDurableSessionState({ session: rekeyed });-- return {- action: "park",- ...derivePendingState(rekeyed),- serializedContext: nextSerializedContext,- sessionState: nextState,- };- }-- const hookRegistry = bundle.hookRegistry;- const dynamicConnections = bindDynamicConnections(ctx, bundle.resolvedAgent);- const dynamicInstructionsResolvers = bundle.resolvedAgent.dynamicInstructionsResolvers ?? [];- const dynamicSkillResolvers = bundle.resolvedAgent.dynamicSkillResolvers ?? [];- const dynamicSubagentResolvers = bundle.subagentRegistry.dynamicResolvers ?? [];- const dynamicToolResolvers = bundle.resolvedAgent.dynamicToolResolvers ?? [];- const effectiveNode = {- ...bundle.graph.root,- turnAgent: effectiveAgent.turnAgent,- };- const runtimeIdentity = buildRuntimeIdentity(effectiveNode);- try {- const deploymentId = process.env.VERCEL_DEPLOYMENT_ID?.trim();- const dynamicRuntimeRevision = deploymentId- ? `deployment:${deploymentId}`- : await resolveRuntimeCompiledArtifactsVersionedCacheKey(bundle.compiledArtifactsSource);- const sessionStarted = initialEmissionState.sessionStarted;-- ctx.setVirtualContext(StaticModelReferenceKey, effectiveAgent.turnAgent.model ?? null);- if (!sessionStarted) {- ctx.set(SessionDynamicSubagentRuntimeRevisionKey, dynamicRuntimeRevision);- ctx.set(SessionDynamicToolRuntimeRevisionKey, dynamicRuntimeRevision);- } else {- const refreshEvent = createSessionStartedEvent({ runtime: runtimeIdentity });- await Promise.all([- refreshDynamicSessionSubagentsForRuntimeRevision({- ctx,- resolvers: dynamicSubagentResolvers,- event: refreshEvent,- messages: history.initial.messages,- runtimeRevision: dynamicRuntimeRevision,- }),- refreshDynamicSessionToolsForRuntimeRevision({- ctx,- resolvers: dynamicToolResolvers,- event: refreshEvent,- messages: history.initial.messages,- runtimeRevision: dynamicRuntimeRevision,- }),- ]);- await rebindMissingCompiledDynamicToolCallbacks({- ctx,- event: createTurnStartedEvent({- sequence: initialEmissionState.sequence,- turnId: activeTurnId(initialEmissionState),- }),- messages: history.initial.messages,- resolvers: dynamicToolResolvers,- });- }- } catch (error) {- await failChannelDeliveries(error);- throw error;- }-- const writer = input.parentWritable.getWriter();- const emit = async (event: UnstampedMessageStreamEvent) => {- const deliverableEvent = scheduledLaunchDeliveryEvent(event, {- isFirstTurn: initialEmissionState.sequence === 0,- isScheduled: ctx.get(ScheduleIdKey) !== undefined,- taskPhase: ctx.get(TurnTaskDeliveryKey),- });- if (deliverableEvent === undefined)- return {- event: stampMessageStreamEvent(event, ctx.get(TurnDeliveryIdsKey)),- suppressed: true,- };- const toEmit = await callAdapterEventHandler(adapter, deliverableEvent, adapterCtx);- setChannelContext(ctx, { ...adapter, state: { ...adapterCtx.state } });- const stamped = stampMessageStreamEvent(toEmit, ctx.get(TurnDeliveryIdsKey));- await writer.write(encodeMessageStreamEvent(stamped));- return { event: stamped, suppressed: false };- };- const handleEvent: HandleEventFn = async (event, messages): Promise<void> => {- activityCohort.updateActivityBlockers(ctx, event);- // A remote task's parent owns its blocking events.- const forwardedToTaskParent = await forwardTaskEventToSessionCallback(ctx, event);- const emitted = forwardedToTaskParent- ? { event: stampMessageStreamEvent(event, ctx.get(TurnDeliveryIdsKey)), suppressed: false }- : await emit(event);- const lifecycleMessages = await dispatchMemoryLifecycleEvent({- abortSignal: input.abortSignal,- appRoot: effectiveNode.agent?.metadata?.appRoot ?? "",- ctx,- event,- instrumentation: instrumentation?.memory,- memories: effectiveNode.agent?.memories ?? [],- messages,- nodeId: bundle.nodeId ?? "__root__",- });- void observeSessionActivity({ ctx, event: emitted.event, sessionId: initialSession.sessionId });- if (!emitted.suppressed)- await dispatchStreamEventHooks({ ctx, registry: hookRegistry, event: emitted.event });- if (emitted.event.type !== "step.started") {- await dispatchDynamicModelEvent({- ctx,- dynamicModel: effectiveAgent.turnAgent.dynamicModel,- event: emitted.event,- messages: lifecycleMessages,- scope: {- moduleMap: bundle.moduleMap,- nodeId: bundle.nodeId,- },- });- }- await dynamicConnections.dispatch(emitted.event);- await dispatchDynamicSubagentEvent({- ctx,- resolvers: dynamicSubagentResolvers,- event: emitted.event,- messages: lifecycleMessages,- });- await dispatchDynamicToolEvent({- ctx,- resolvers: dynamicToolResolvers,- event: emitted.event,- messages: lifecycleMessages,- });- await dispatchDynamicSkillEvent({- ctx,- resolvers: dynamicSkillResolvers,- event: emitted.event,- messages: lifecycleMessages,- });- await dispatchDynamicInstructionEvent({- ctx,- resolvers: dynamicInstructionsResolvers,- event: emitted.event,- messages: lifecycleMessages,- });- };-- const mode = ctx.require(ModeKey);- const modelCallsPerStep =- bundle.resolvedAgent.config?.experimental?.workflow?.modelCallsPerStep ?? 1;- const capabilities = ctx.get(CapabilitiesKey);-- const runHarnessStep = async (- lifecycleSession: HarnessSession,- stepInput: StepInput | undefined,- ): Promise<StepResult> => {- const refreshedSession = refreshSessionFromTurnAgent({- compactionOverrides: {- thresholdPercent: effectiveAgent.thresholdPercent,- },- session: lifecycleSession,- turnAgent: effectiveAgent.turnAgent,- });- const modelSession = refreshedSession;-- const step = createExecutionNodeStep({- abortSignal: input.abortSignal,- capabilities,- clearOnly: input.input?.kind === "clear",- compactOnly: input.input?.kind === "compact",- createRuntime: createWorkflowRuntime,- handleEvent,- historyProjector: history.projector,- historyView: history.prepare(modelSession),- instrumentation,- mode,- modelResolutionScope: {- moduleMap: bundle.moduleMap,- nodeId: bundle.nodeId,- },- node: effectiveNode,- });- return step(modelSession, stepInput);- };-- let completedModelCall: CompletedModelCallCheckpoint | undefined;- let stepResult: StepResult;- try {- // A signal already aborted at entry (cancellation during an in-line- // runtime-action wait) must settle before the park-resume stages run,- // or the pending batch would re-park and later re-dispatch.- throwIfTurnAborted(input.abortSignal);- stepResult = await runModelCallBatch({- initialInput: resolved,- initialSession,- modelCallsPerStep,- runStep: async ({ firstCall, session, stepInput }) => {- const result = await runBackgroundStep(ctx, session, async (enrichedSession) => {- ctx.setVirtualContext(HandleEventKey, handleEvent);- ctx.setVirtualContext(StaticModelReferenceKey, effectiveAgent.turnAgent.model ?? null);- let schemaSession = firstCall- ? resolveEffectiveOutputSchema({- agentOutputSchema: effectiveAgent.turnAgent.outputSchema,- input: resolved,- mode,- session: enrichedSession,- })- : enrichedSession;- await dynamicConnections.rehydrate(- getHarnessEmissionState(schemaSession.state),- runtimeIdentity,- isHarnessBetweenTurns(schemaSession),- );- if (firstCall && completedAuths) {- let emissionState = getHarnessEmissionState(schemaSession.state);- if (isHarnessBetweenTurns(schemaSession)) {- prepareDynamicInstructionPreamble(ctx, history.messages(schemaSession));- let instructionMessages: readonly UserModelMessage[] = [];- const traceContext = await prepareWorkflowPreambleTrace({- emissionState,- instrumentation,- });- try {- emissionState = await emitTurnPreamble(- handleEvent,- {},- emissionState,- runtimeIdentity,- traceContext,- );- } finally {- instructionMessages = drainDynamicInstructionUserMessages(ctx);- schemaSession = {- ...schemaSession,- history: [...schemaSession.history, ...instructionMessages],- };- }- schemaSession = setHarnessEmissionState(schemaSession, emissionState);- }- for (const { authorization, result } of completedAuths) {- const candidateId = pendingAuth?.challenges.find(- (challenge) => challenge.attemptId === result.attemptId,- )?.candidateId;- await handleEvent(- createAuthorizationCompletedEvent({- attemptId: result.attemptId,- authorization,- candidateId,- name: result.name,- outcome: "authorized",- sequence: emissionState.sequence,- stepIndex: emissionState.stepIndex,- turnId: emissionState.turnId,- }),- );- }- }-- return runHarnessStep(schemaSession, stepInput);- });- throwIfTurnAborted(input.abortSignal);- completedModelCall = { result, serializedContext: serializeContext(ctx) };- return result;- },- });- } catch (error) {- if (!isTurnCancellation(error) && input.abortSignal?.aborted !== true) {- await failChannelDeliveries(error);- throw error;- }- writer.releaseLock();- const retained = readRetainedBackgroundToolResult(ctx);- instrumentation?.rememberBackgroundTasks(retained?.backgroundTasks ?? []);- return createCancelledModelCallBatchResult({- beforeBatchContext: input.serializedContext,- checkpoint: completedModelCall,- ctx,- initialSession,- stepInput: resolved,- });- }-- instrumentation?.rememberBackgroundTasks(stepResult.backgroundTasks ?? []);- // Re-stamp if a handler called `session.continuation.rekey(...)` (eg. Slack auto-anchor).- const rekeyed = reconcileSessionContinuationToken(ctx, stepResult.session);- agentTraceState.pruneAgentTraceState(ctx, rekeyed.sessionId, rekeyed.state);- const nextSerializedContext = serializeContext(ctx);- stepResult = { ...stepResult, session: rekeyed };-- const nextState = createDurableSessionState({ session: stepResult.session });- const backgroundTransition =- stepResult.backgroundTasks === undefined || stepResult.backgroundTaskSession === undefined- ? {}- : {- backgroundTaskContext: preserveSerializedBackgroundTaskObservabilityState(- input.serializedContext,- nextSerializedContext,- stepResult.backgroundTasks,- ),- backgroundTaskState: createDurableSessionState({- session: stepResult.backgroundTaskSession,- }),- backgroundTasks: stepResult.backgroundTasks,- };-- if (- stepResult.next !== null &&- typeof stepResult.next === "object" &&- "done" in stepResult.next- ) {- if (mode === "task" && hasPendingInputBatch(stepResult.session.state)) {- writer.releaseLock();- throw new Error(TASK_DONE_WITH_PENDING_INPUT_ERROR_MESSAGE);- }- await writer.close();- const sessionTotals = getTurnUsageState(stepResult.session.state)?.session;- return {- action: "done",- ...backgroundTransition,- output: stepResult.next.output,- isError: stepResult.next.isError,- serializedContext: nextSerializedContext,- sessionState: nextState,- usage: sessionTotals === undefined ? undefined : toUsage(sessionTotals),- usageDelta: takeSessionUsageDelta(stepResult.session).delta,- };- }-- if (stepResult.next === null) {- writer.releaseLock();-- const pending = derivePendingState(stepResult.session);-- // `settledTurn` is the harness's explicit settlement verdict. Pending- // state may predate this turn, while newly created parks omit the verdict.- // `usage` carries only this turn's delta: the take marks the totals- // reported, so a persistent child never re-reports earlier spend.- if (stepResult.settledTurn !== undefined) {- const { delta, session: reportedSession } = takeSessionUsageDelta(stepResult.session);- return {- action: "park",- ...backgroundTransition,- ...pending,- serializedContext: nextSerializedContext,- sessionState: createDurableSessionState({ session: reportedSession }),- settled: {- output: stepResult.settledTurn.output,- isError: stepResult.settledTurn.isError,- usage: delta,- },- };- }-- return {- action: "park",- ...backgroundTransition,- ...pending,- serializedContext: nextSerializedContext,- sessionState: nextState,- };- }-- writer.releaseLock();- return {- action: "continue",- ...backgroundTransition,- serializedContext: nextSerializedContext,- sessionState: nextState,- };-}diff --git a/packages/eve/src/harness/attachment-staging.test.ts b/packages/eve/src/harness/attachment-staging.test.tsindex 58f567628..f0bbb77d6 100644--- a/packages/eve/src/harness/attachment-staging.test.ts+++ b/packages/eve/src/harness/attachment-staging.test.ts@@ -23,7 +23,7 @@ const STUB_ADAPTER_CTX: ChannelAdapterContext = {session: {id: "",auth: { current: null, initiator: null },- continuation: { token: "", rekey: () => {} },+ continuation: { token: "", alias: () => {} },},};diff --git a/packages/eve/src/harness/authorization.test.ts b/packages/eve/src/harness/authorization.test.tsindex 5ad78963f..842024a27 100644--- a/packages/eve/src/harness/authorization.test.ts+++ b/packages/eve/src/harness/authorization.test.ts@@ -26,7 +26,7 @@ describe("authorization callback URLs", () => {ctx.set(SessionIdKey, "session-1");expect(contextStorage.run(ctx, () => getHookUrl("linear", "attempt-1"))).toBe(- "https://agent.example.com/eve/v1/connections/linear/callback/attempt-1/session-1%3Aauth?x-vercel-protection-bypass=secret+value",+ "https://agent.example.com/eve/v1/connections/linear/callback/attempt-1/eve%3Ainbox%3Av1%3Aeve%3Asession%3Asession-1%3Ainbox?x-vercel-protection-bypass=secret+value",);});});diff --git a/packages/eve/src/harness/authorization.ts b/packages/eve/src/harness/authorization.tsindex 3a20eed92..f5da7148b 100644--- a/packages/eve/src/harness/authorization.ts+++ b/packages/eve/src/harness/authorization.ts@@ -1,3 +1,7 @@+import {+ sessionCommandHookToken,+ sessionInboxHookToken,+} from "#execution/session-inbox/address.js";/*** Authorization request/result API for tool execution.*@@ -187,9 +191,9 @@ export function consumeAuthorizationResult(* Builds a callback URL for external systems. `name` and `attemptId` identify* the exact challenge in the URL path.*- * By default the URL embeds the session's authorization hook token (`${sessionId}:auth`).+ * By default the URL embeds the session's stable inbox token.* A runtime with its own continuation supplies that hook through AuthorizationHookKey.- * It is independent of the continuation token, so channel re-keying mid-turn+ * It is independent of the continuation token, so channel aliasing mid-turn* does not invalidate the callback URL.** Returns `undefined` if no callback address is available.@@ -269,12 +273,12 @@ export function isPendingAuthorizationToolOutput(value: unknown): boolean {}/**- * Deterministic hook token for all authorization callbacks in a- * session. Both {@link getHookUrl} (inside tool execution) and the- * workflow body (which creates the hook upfront) use this token.+ * Physical hook token embedded in a session's authorization callback URLs.+ * The callback route resumes exactly this hook, so it is the stable inbox's+ * physical address rather than its logical session token.*/export function authHookToken(sessionId: string): string {- return `${sessionId}:auth`;+ return sessionInboxHookToken(sessionCommandHookToken(sessionId));}// ---------------------------------------------------------------------------diff --git a/packages/eve/src/harness/compaction.test.ts b/packages/eve/src/harness/compaction.test.tsindex d00cce7f2..118312ce1 100644--- a/packages/eve/src/harness/compaction.test.ts+++ b/packages/eve/src/harness/compaction.test.ts@@ -786,22 +786,6 @@ describe("compactMessages: summarization fallback", () => {expect(result.at(-1)).toEqual(task);});- it("does not replay unknown legacy provenance as the user's latest request", async () => {- const task = user("Summarize the report.");- const legacy = {- content: "A background task completed.",- kind: "legacy.unknown",- role: "user",- } as const;- const [call, resultMsg] = toolExchange({ callId: "call-1", payloadChars: 100 });- const { result } = await compact(- [user("old notes ".repeat(4_000)), task, legacy, call, resultMsg],- { recentWindowSize: 2, threshold: 2_048 },- );-- expect(result.at(-1)).toEqual(task);- });-it("makes room for the original task before keeping a large tool-result tail", async () => {const task = user("Keep these requirements. ".repeat(25));const [call, resultMsg] = toolExchange({ callId: "call-1", payloadChars: 600 });diff --git a/packages/eve/src/harness/compaction.ts b/packages/eve/src/harness/compaction.tsindex 4a0116692..fbf7cea54 100644--- a/packages/eve/src/harness/compaction.ts+++ b/packages/eve/src/harness/compaction.ts@@ -9,11 +9,7 @@ import {stubContentOutputFileParts,TRANSCRIPT_PAYLOAD_LIMIT,} from "#harness/compaction-prompt.js";-import {- createFrameworkUserMessage,- isFrameworkUserMessage,- isUserModelMessage,-} from "#harness/messages.js";+import { createFrameworkUserMessage, isFrameworkUserMessage } from "#harness/messages.js";import { estimateTokens } from "#harness/token-estimate.js";import type { RuntimeModelReference } from "#runtime/agent/bootstrap.js";import type { CompactionConfig, ToolLoopHarnessConfig } from "#harness/types.js";@@ -387,10 +383,7 @@ function findLastRealUserMessage(conversation: readonly ModelMessage[]): ModelMeif (message?.role !== "user" || typeof message.content !== "string") {continue;}- if (- isFrameworkUserMessage(message) ||- (isUserModelMessage(message) && message.kind === "legacy.unknown")- ) {+ if (isFrameworkUserMessage(message)) {continue;}return message;diff --git a/packages/eve/src/harness/emission.ts b/packages/eve/src/harness/emission.tsindex 3a08e8599..455e92f6e 100644--- a/packages/eve/src/harness/emission.ts+++ b/packages/eve/src/harness/emission.ts@@ -82,13 +82,18 @@ export async function emitTurnPreamble(runtimeIdentity?: RuntimeIdentity,traceContext?: RuntimeTraceContext,): Promise<HarnessEmissionState> {- const turnId = `turn_${state.sequence}`;+ // Steering re-enters an open turn: keep its id and step index and skip the+ // `turn.started` it already emitted.+ const steering = state.turnId !== "";+ const turnId = steering ? state.turnId : `turn_${state.sequence}`;if (!state.sessionStarted) {await emitFn(createSessionStartedEvent({ runtime: runtimeIdentity, trace: traceContext }));}- await emitFn(createTurnStartedEvent({ sequence: state.sequence, trace: traceContext, turnId }));+ if (!steering) {+ await emitFn(createTurnStartedEvent({ sequence: state.sequence, trace: traceContext, turnId }));+ }if (input.message !== undefined) {await emitFn(@@ -103,7 +108,7 @@ export async function emitTurnPreamble(return {sessionStarted: true,sequence: state.sequence,- stepIndex: 0,+ stepIndex: steering ? state.stepIndex : 0,turnId,};}diff --git a/packages/eve/src/harness/messages.test.ts b/packages/eve/src/harness/messages.test.tsindex cc1b10d03..bb9d8a055 100644--- a/packages/eve/src/harness/messages.test.ts+++ b/packages/eve/src/harness/messages.test.ts@@ -326,18 +326,6 @@ describe("createFrameworkUserMessage", () => {expect(isFrameworkUserMessage(message)).toBe(false);});- it("recognizes unknown legacy provenance without treating it as framework-authored", () => {- const message = {- content: "A retained pre-0.54 message",- kind: "legacy.unknown",- role: "user",- } as const;-- expect(isUserMessageKind(message.kind)).toBe(true);- expect(isUserModelMessage(message)).toBe(true);- expect(isFrameworkUserMessage(message)).toBe(false);- });-it("rejects unclassified user messages before history retention", () => {expect(() =>validateHarnessModelMessages([{ content: "A user message", role: "user" }]),diff --git a/packages/eve/src/harness/messages.ts b/packages/eve/src/harness/messages.tsindex cf07eac54..adc53600e 100644--- a/packages/eve/src/harness/messages.ts+++ b/packages/eve/src/harness/messages.ts@@ -21,7 +21,7 @@ export type FrameworkMessageKind =| "execution.retry";/** Semantic classification for every user-role message in model history. */-export type UserMessageKind = "user" | "legacy.unknown" | FrameworkMessageKind;+export type UserMessageKind = "user" | FrameworkMessageKind;/** A user-role message that is safe to retain in framework model history. */export type UserModelMessage = Extract<ModelMessage, { readonly role: "user" }> & {@@ -69,7 +69,7 @@ export function createFrameworkUserMessage(/** True when a value is a recognized classification for a user-role message. */export function isUserMessageKind(value: unknown): value is UserMessageKind {- return value === "user" || value === "legacy.unknown" || isFrameworkMessageKind(value);+ return value === "user" || isFrameworkMessageKind(value);}/** True when a user-role model message has the required semantic classification. */@@ -81,7 +81,7 @@ export function isUserModelMessage(message: ModelMessage): message is UserModelM/** True when a user-role message was authored by the framework. */export function isFrameworkUserMessage(message: ModelMessage): message is FrameworkUserMessage {- return isUserModelMessage(message) && isFrameworkMessageKind(message.kind);+ return isUserModelMessage(message) && message.kind !== "user";}/** Validates that every user-role message is classified before history retains it. */diff --git a/packages/eve/src/harness/proxy-input-requests.ts b/packages/eve/src/harness/proxy-input-requests.tsindex a6f3fab2b..44fd81c37 100644--- a/packages/eve/src/harness/proxy-input-requests.ts+++ b/packages/eve/src/harness/proxy-input-requests.ts@@ -5,7 +5,7 @@ import { isLoopbackHostname } from "#shared/network-address.js";import {isSessionInboxAddress,type SessionInboxAddress,-} from "#execution/wire/session-inbox-contract.js";+} from "#execution/session-inbox/address.js";const PROXY_INPUT_REQUESTS_KEY = "eve.runtime.proxyInputRequests";diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.tsindex 75030b9a1..372c59c70 100644--- a/packages/eve/src/harness/tool-loop.test.ts+++ b/packages/eve/src/harness/tool-loop.test.ts@@ -653,6 +653,12 @@ function setupMockAgentSequence(results: readonly Record<string, unknown>[]): voif (onStepEnd) await onStepEnd(result);return createMockGenerateResult(result);});+ this.stream = vi.fn().mockImplementation(async (options: { messages: unknown[] }) => {+ await invokeMockStepStart(settings, options);+ const mockResult = createMockStreamResult(result);+ if (onStepEnd) void Promise.resolve().then(() => onStepEnd(result));+ return mockResult;+ });return this;} as MockAgentConstructor);}@@ -972,6 +978,84 @@ describe("createToolLoopHarness", () => {]);});+ it("steers an open turn with a new message without repeating the turn preamble", async () => {+ const toolCall = {+ input: { query: "weather in ny" },+ toolCallId: "call-1",+ toolName: "web_search",+ type: "tool-call",+ };+ const toolResult = { ...toolCall, output: { temperature: "41 F" }, type: "tool-result" };+ setupMockAgentSequence([+ {+ finishReason: "tool-calls",+ response: {+ messages: [+ { content: [toolCall], role: "assistant" },+ { content: [toolResult], role: "tool" },+ ],+ },+ text: "",+ toolCalls: [toolCall],+ toolResults: [toolResult],+ },+ {+ finishReason: "stop",+ response: { messages: [{ content: "It is 41 F in NY.", role: "assistant" }] },+ text: "It is 41 F in NY.",+ toolCalls: [],+ toolResults: [],+ },+ ]);+ const { emit, events } = createEventCollector();+ const config = createTestConfig("conversation", emit, {+ tools: new Map([+ [+ "web_search",+ {+ description: "Search the web",+ inputSchema: jsonSchema({ type: "object" }),+ name: "web_search",+ },+ ],+ ]),+ });+ const runStep = createToolLoopHarness(config);+ const session = createTestSession({+ agent: {+ modelReference: { id: "openai/gpt-5.4" },+ system: "You are a test assistant.",+ tools: [+ { description: "Search the web", name: "web_search", inputSchema: { type: "object" } },+ ],+ },+ });++ const first = await runStep(session, { message: "What's the weather in NY?" });+ expect(typeof first.next).toBe("function");+ expect(getHarnessEmissionState(first.session.state)).toMatchObject({+ turnId: "turn_0",+ stepIndex: 1,+ });++ const second = await runStep(first.session, { message: "Use Fahrenheit." });++ expect(second.next).toBeNull();+ expect(events.filter((event) => event.type === "turn.started")).toHaveLength(1);+ expect(events.filter((event) => event.type === "message.received")).toHaveLength(2);+ expect(events.filter((event) => event.type === "turn.completed")).toHaveLength(1);+ expect(second.session.history.at(-2)).toEqual({+ content: "Use Fahrenheit.",+ kind: "user",+ role: "user",+ });+ expect(getHarnessEmissionState(second.session.state)).toMatchObject({+ sequence: 1,+ stepIndex: 0,+ turnId: "",+ });+ });+it("omits user messages with no model-visible content", async () => {setupMockAgent({finishReason: "stop",diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.tsindex 5b5c9b109..c52bf3d3e 100644--- a/packages/eve/src/harness/tool-loop.ts+++ b/packages/eve/src/harness/tool-loop.ts@@ -560,7 +560,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {sequence: emissionState.sequence,sessionStarted: emissionState.sessionStarted,traceContext: stepInstrumentation?.traceContext,- turnId: `turn_${emissionState.sequence}`,+ turnId: activeTurnId(emissionState),});};@@ -868,7 +868,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {sessionStarted: true,sequence: emissionState.sequence,stepIndex: 0,- turnId: `turn_${emissionState.sequence}`,+ turnId: activeTurnId(emissionState),});}instructionMessages = store === undefined ? [] : drainDynamicInstructionUserMessages(store);@@ -1010,7 +1010,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {sessionStarted: true,sequence: emissionState.sequence,stepIndex: 0,- turnId: `turn_${emissionState.sequence}`,+ turnId: activeTurnId(emissionState),});}instructionMessages = store === undefined ? [] : drainDynamicInstructionUserMessages(store);diff --git a/packages/eve/src/internal/application/compiled-artifacts.test.ts b/packages/eve/src/internal/application/compiled-artifacts.test.tsindex 16693195e..6a05ddb61 100644--- a/packages/eve/src/internal/application/compiled-artifacts.test.ts+++ b/packages/eve/src/internal/application/compiled-artifacts.test.ts@@ -53,6 +53,10 @@ describe("createWorkflowWorldPluginSource", () => {expect(source).toContain("/compiled/@workflow/world-vercel/index.js");expect(source).toMatch(/headers: \{ "User-Agent": "eve\/.+" \}/);+ expect(source).toContain("applyVercelWorkflowWorldDefaults(workflowWorld);");+ expect(source.indexOf("applyVercelWorkflowWorldDefaults(workflowWorld);")).toBeLessThan(+ source.indexOf("setWorld(workflowWorld);"),+ );});});diff --git a/packages/eve/src/internal/application/compiled-artifacts.ts b/packages/eve/src/internal/application/compiled-artifacts.tsindex 153c9d607..300d05dd4 100644--- a/packages/eve/src/internal/application/compiled-artifacts.ts+++ b/packages/eve/src/internal/application/compiled-artifacts.ts@@ -380,16 +380,22 @@ const workflowWorld = await workflowWorldModule.createWorld({}if (packageName === "@workflow/world-vercel") {+ const defaultsImportSpecifier = stringifyEsmImportSpecifier(+ resolvePackageSourceFilePath("src/internal/workflow/vercel-world-defaults.ts"),+ );const moduleImportSpecifier = resolvePackageCompiledFilePath(`src/compiled/${packageName}/index.js`,);const createWorldSource = `const workflowWorld = await workflowWorldModule.createWorld({headers: { "User-Agent": ${JSON.stringify(buildPackageUserAgent())} },-});`.trimStart();+});+applyVercelWorkflowWorldDefaults(workflowWorld);`.trimStart();return {moduleImportSpecifier,- extraImportLines: [],+ extraImportLines: [+ `import { applyVercelWorkflowWorldDefaults } from ${defaultsImportSpecifier};`,+ ],runtimeImports: "getWorld, setWorld",createWorldSource,};diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.tsindex 586a49919..29558098e 100644--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts@@ -28,6 +28,7 @@ import { registerInstrumentationConfig } from "#instrumentation/config.js";import { getInstrumentationRuntime } from "#instrumentation/runtime.js";import type { Runtime } from "#channel/types.js";import { readVercelProjectLink } from "#internal/vercel/project-link.js";+import { DEVELOPMENT_WORKFLOW_SECRET_ENV } from "#internal/workflow/development-world-protocol.js";import { resolveVercelOidcCurrentProject } from "#channel/auth/vercel-oidc-project.js";import type { ResolvedChannelDefinition } from "#runtime/types.js";import { isAgentTraceContext } from "#tracing/agent-trace-context.js";@@ -45,6 +46,10 @@ vi.mock("#internal/vercel/project-link.js", () => ({readVercelProjectLink: vi.fn(),}));+vi.mock("#internal/workflow/runtime.js", () => ({+ getWorld: async () => ({ getDeploymentId: async () => "dpl_test" }),+}));+const mockedResolveNitroChannelRuntimeBundle = vi.mocked(resolveNitroChannelRuntimeBundle);const mockedReadVercelProjectLink = vi.mocked(readVercelProjectLink);const runtime = {} as Runtime;@@ -380,6 +385,47 @@ describe("dispatchChannelRequest", () => {);});+ it("tags dev-worker sends with the generation that accepted them", async () => {+ vi.stubEnv(DEVELOPMENT_WORKFLOW_SECRET_ENV, "secret");+ const runtimeForTest = createRuntime({+ dispatchContinuation: vi.fn().mockResolvedValue({+ sessionId: "sess_route",+ status: "accepted",+ }),+ });++ mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({+ agentName: "test-agent",+ channels: [+ {+ handler: async (_req, args) => {+ await args.from("route-token").send("hello", { auth: null });+ return new Response("ok");+ },+ fetch: async () => new Response("ok"),+ adapter: { kind: "channel:webhook" },+ logicalPath: "agent/channels/webhook.ts",+ method: "POST",+ name: "webhook",+ sourceId: "channel-webhook",+ sourceKind: "module",+ urlPath: "/webhook",+ } satisfies ResolvedChannelDefinition,+ ],+ runtime: runtimeForTest,+ });++ await dispatchChannelRequest(+ createEvent({ waitUntil: vi.fn() }),+ "POST /webhook",+ DEVELOPMENT_ARTIFACTS_CONFIG,+ );++ expect(vi.mocked(runtimeForTest.dispatchContinuation).mock.calls[0]?.[0].command).toMatchObject(+ { delivery: { acceptedDeploymentId: "dpl_test" } },+ );+ });+it("supplies a channel-scoped reset helper", async () => {const runtimeForTest = createRuntime({dispatchContinuation: vi.fn().mockResolvedValue({diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.tsindex 3fb015a3b..f5b64b871 100644--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts@@ -27,6 +27,7 @@ import { resolveNitroChannelRuntimeBundle } from "#internal/nitro/routes/runtimeimport { readVercelProjectLink } from "#internal/vercel/project-link.js";import { withVercelOidcProjectResolver } from "#channel/auth/vercel-oidc-project.js";import { withLocalDevRequestScope } from "#runtime/local-dev-capability.js";+import { getWorld } from "#internal/workflow/runtime.js";const log = createLogger("channel.dispatch");@@ -85,7 +86,7 @@ export async function dispatchChannelRequest(span?.setAttribute("eve.channel.kind", channelKind);}- const routeArgs = buildRouteArgs(+ const routeArgs = await buildRouteArgs(event,bundle,matchedChannel.name,@@ -157,7 +158,7 @@ export async function dispatchChannelWebSocketRequest(getChannelInstrumentationKind(matchedChannel.definition) ??matchedChannel.adapter?.kind ??"channel";- const routeArgs = buildRouteArgs(+ const routeArgs = await buildRouteArgs(event,bundle,matchedChannel.name,@@ -214,14 +215,14 @@ async function withDevelopmentVercelOidcContext<T>();}-function buildRouteArgs(+async function buildRouteArgs(event: H3Event,bundle: Awaited<ReturnType<typeof resolveNitroChannelRuntimeBundle>>,channelName: string,channelKind: string,config: NitroArtifactsConfig,requestTraceContext: SpanContext | undefined,-): BuiltRouteArgs {+): Promise<BuiltRouteArgs> {const requestId = readVercelRequestId(event.req.headers);const requestIp = extractRequestIp(event, config);const backgroundTasks: Promise<unknown>[] = [];@@ -236,7 +237,7 @@ function buildRouteArgs(};const channel = bundle.channels.find((candidate) => candidate.name === channelName);const adapter = channel?.adapter ?? { kind: "channel" };- const acceptedDeploymentId = process.env.VERCEL_DEPLOYMENT_ID?.trim() || undefined;+ const acceptedDeploymentId = await resolveAcceptedDeploymentId(config);const deliverySource = {acceptedDeploymentId,channelKind,@@ -308,6 +309,28 @@ function buildRouteArgs(};}+async function resolveAcceptedDeploymentId(+ config: NitroArtifactsConfig,+): Promise<string | undefined> {+ const hosted = process.env.VERCEL_DEPLOYMENT_ID?.trim();+ if (hosted !== undefined && hosted.length > 0) return validateDeploymentId(hosted);++ // Scenario and inspection callers can invoke a development route directly,+ // outside the dev worker whose transport secret proves that its World is+ // installed. Those read-only calls keep the pre-existing unstamped shape.+ if (config.kind === "development" && process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV] === undefined) {+ return undefined;+ }+ return validateDeploymentId(await (await getWorld()).getDeploymentId());+}++function validateDeploymentId(deploymentId: string): string {+ if (deploymentId.length === 0 || deploymentId === "latest") {+ throw new Error("Channel ingress could not resolve an exact deployment id.");+ }+ return deploymentId;+}+function readVercelRequestId(headers: Headers): string | undefined {const requestId = headers.get("x-vercel-id")?.trim();return requestId === "" ? undefined : requestId;diff --git a/packages/eve/src/internal/testing/app-harness.integration.test.ts b/packages/eve/src/internal/testing/app-harness.integration.test.tsindex fae71ffda..b6e8d27d1 100644--- a/packages/eve/src/internal/testing/app-harness.integration.test.ts+++ b/packages/eve/src/internal/testing/app-harness.integration.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vitest";import { start } from "#internal/workflow/runtime.js";-import { workflowEntry } from "#execution/workflow-entry.js";+import { workflowEntry } from "#execution/session/entry.js";import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";import { getActiveRuntimeSession } from "#runtime/sessions/runtime-session.js";import { createTestRuntime } from "#internal/testing/app-harness.js";@@ -27,6 +27,8 @@ describe("AppHarness pilot", () => {const output = await runtime.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: "hello pilot harness" },serializedContext: buildSerializedContext({channelKind: "http",@@ -73,6 +75,8 @@ describe("AppHarness pilot", () => {runtimeA.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: "hello tenant-a" },serializedContext: buildSerializedContext({channelKind: "http",@@ -86,6 +90,8 @@ describe("AppHarness pilot", () => {runtimeB.run(async () => {const run = await start(workflowEntry, [{+ kind: "initial",+ ownerDeploymentId: "dpl_inline",input: { message: "hello tenant-b" },serializedContext: buildSerializedContext({channelKind: "http",diff --git a/packages/eve/src/internal/testing/durable-session-workflow.ts b/packages/eve/src/internal/testing/durable-session-workflow.tsindex 329a6eba7..414a1fb97 100644--- a/packages/eve/src/internal/testing/durable-session-workflow.ts+++ b/packages/eve/src/internal/testing/durable-session-workflow.ts@@ -101,7 +101,7 @@ export async function durableSessionReadStep(input: {}> {"use step";- const durable = await readDurableSession(input.sessionState);+ const durable = readDurableSession(input.sessionState);return {historyDepth: durable.history.length,diff --git a/packages/eve/src/internal/testing/events.test.ts b/packages/eve/src/internal/testing/events.test.tsindex fdc877a08..2090ff7cf 100644--- a/packages/eve/src/internal/testing/events.test.ts+++ b/packages/eve/src/internal/testing/events.test.ts@@ -13,7 +13,7 @@ import {** The streaming capture helper is validated end-to-end against the real* workflow in the integration tier — see- * `src/execution/workflow-entry.integration.test.ts`.+ * `src/execution/session/entry.integration.test.ts`.*/describe("containsEventSequence", () => {diff --git a/packages/eve/src/internal/testing/legacy-session-delivery-workflow.ts b/packages/eve/src/internal/testing/legacy-session-delivery-workflow.tsdeleted file mode 100644index 24fd9a75b..000000000--- a/packages/eve/src/internal/testing/legacy-session-delivery-workflow.ts+++ /dev/null@@ -1,18 +0,0 @@-import { createHook } from "#compiled/@workflow/core/index.js";--import type { DeliverHookPayload } from "#channel/types.js";--/** Models the continuation consumer shipped before SessionCommand existed. */-export async function legacySessionDeliveryWorkflow(input: {- readonly token: string;-}): Promise<string> {- "use workflow";-- const deliveries = createHook<DeliverHookPayload>({ token: input.token });- for await (const delivery of deliveries) {- if (delivery.kind !== "deliver") continue;- const message = delivery.payloads[0]?.message;- return typeof message === "string" ? message : "";- }- return "";-}diff --git a/packages/eve/src/internal/testing/legacy-session-driver-workflow.ts b/packages/eve/src/internal/testing/legacy-session-driver-workflow.tsnew file mode 100644index 000000000..48d1132b4--- /dev/null+++ b/packages/eve/src/internal/testing/legacy-session-driver-workflow.ts@@ -0,0 +1,103 @@+import { createHook, getWorkflowMetadata, getWritable } from "#compiled/@workflow/core/index.js";+import { start } from "#internal/workflow/runtime.js";+import { turnWorkflow } from "#execution/legacy-session/turn-workflow.js";+import type { DurableSession } from "#execution/durable-session-store.js";++/** Frozen driver-side protocol: it cannot see the current session inbox. */+export async function legacySessionDriverWorkflow(input: {+ readonly serializedContext: Record<string, unknown>;+ readonly alias: string;+ readonly inputVersion?: 1 | 2;+ /** `undefined` models a driver older than eve 0.45 that stamped no wire version. */+ readonly inboxVersion?: number;+ readonly committedInput?: boolean;+ readonly duplicateImport?: boolean;+ readonly sessionTimeoutMs?: number | false;+}): Promise<unknown> {+ "use workflow";+ const { workflowRunId: sessionId } = getWorkflowMetadata();+ const metadata =+ input.inboxVersion === undefined ? {} : { sessionInboxWireVersion: input.inboxVersion };+ const command = createHook<{ kind: string; payload?: unknown; payloads?: unknown[] }>({+ token: `eve:session:${sessionId}:inbox`,+ metadata,+ });+ const alias = input.alias === "" ? undefined : createHook({ token: input.alias, metadata });+ const completion = createHook<{ action: { kind: string; output: unknown } }>({+ token: `${sessionId}:turn-control:0`,+ });+ const parentWritable = getWritable<Uint8Array>();+ try {+ const delivery = await command;+ const session: DurableSession = {+ sessionId,+ continuationToken: input.alias,+ agent: { system: "previous deployment" },+ history: [+ { role: "user", kind: "user", content: "Alice selected blue for the project." },+ { role: "assistant", content: "The project color is blue." },+ ...(input.committedInput+ ? [+ {+ role: "user" as const,+ kind: "user" as const,+ content: "Alice asks to continue the blue project.",+ },+ ]+ : []),+ ],+ state: {+ "app.color": "blue",+ "eve.harness.emission": {+ sessionStarted: true,+ sequence: 7,+ stepIndex: 0,+ turnId: input.committedInput ? "turn_7" : "",+ },+ },+ };+ const sessionState = {+ version: 1,+ sessionId,+ continuationToken: input.alias,+ hasProxyInputRequests: false,+ emissionState: session.state!["eve.harness.emission"],+ snapshot: { version: 1, session },+ };+ const turnInput = {+ version: input.inputVersion ?? 2,+ mode: "conversation",+ completionToken: completion.token,+ stepInput: {+ input: { ...delivery, kind: "deliver", payloads: delivery.payloads ?? [delivery.payload] },+ parentWritable,+ sessionState,+ serializedContext: {+ ...input.serializedContext,+ "eve.sessionId": sessionId,+ "eve.continuationToken": input.alias,+ },+ },+ };+ const rawInput = input.committedInput+ ? {+ ...turnInput,+ initialStep: {+ beforeStep: turnInput.stepInput,+ result: { sessionState, serializedContext: turnInput.stepInput.serializedContext },+ },+ }+ : turnInput;+ await dispatchLegacyTurnStep(rawInput);+ if (input.duplicateImport) await dispatchLegacyTurnStep(rawInput);+ return (await completion).action;+ } finally {+ await command.dispose();+ await alias?.dispose();+ await completion.dispose();+ }+}+async function dispatchLegacyTurnStep(input: unknown): Promise<void> {+ "use step";+ await start(turnWorkflow, [input], { deploymentId: "latest" });+}diff --git a/packages/eve/src/internal/testing/mid-cohort-session-delivery-workflow.ts b/packages/eve/src/internal/testing/mid-cohort-session-delivery-workflow.tsdeleted file mode 100644index b43335a05..000000000--- a/packages/eve/src/internal/testing/mid-cohort-session-delivery-workflow.ts+++ /dev/null@@ -1,40 +0,0 @@-import { createHook, getWorkflowMetadata } from "#compiled/@workflow/core/index.js";--import type { DeliverPayload } from "#channel/types.js";-import { sessionCommandHookToken } from "#execution/session-command-token.js";--/**- * Models the parked-session consumer shipped in eve 0.30.5–0.30.8.- *- * Frozen copy of that cohort's inbox decode (`waitForNextSessionAction` +- * `commandToDelivery` at 0.30.7): every payload that is not a control kind is- * cast to a `send` command and re-wrapped by reading its `payload` field. A- * producer envelope without that field therefore delivers `undefined` and the- * message is lost. This cohort also owns the stable session inbox, which is- * the markerless capability the current producer uses to select raw `send`.- */-export async function midCohortSessionDeliveryWorkflow(input: {- readonly token: string;-}): Promise<string> {- "use workflow";-- createHook({ token: sessionCommandHookToken(getWorkflowMetadata().workflowRunId) });- const inbox = createHook<{ readonly kind: string }>({ token: input.token });- for await (const value of inbox) {- if (- value.kind === "session-timeout" ||- value.kind === "clear" ||- value.kind === "compact" ||- value.kind === "reset" ||- value.kind === "cancel"- ) {- continue;- }-- const command = value as { readonly payload?: DeliverPayload };- const payloads = [command.payload];- const message = payloads[0]?.message;- return typeof message === "string" ? message : "";- }- return "";-}diff --git a/packages/eve/src/internal/testing/session-hook-pump-workflow.ts b/packages/eve/src/internal/testing/session-hook-pump-workflow.tsnew file mode 100644index 000000000..a5bbec452--- /dev/null+++ b/packages/eve/src/internal/testing/session-hook-pump-workflow.ts@@ -0,0 +1,25 @@+import { createHook, getWorkflowMetadata } from "#compiled/@workflow/core/index.js";+import { createSessionInbox } from "#execution/session-inbox/inbox.js";+import { sessionCommandHookToken } from "#execution/session-inbox/address.js";++export async function sessionHookPumpWorkflow(input: {+ readonly aliases: readonly string[];+ readonly releaseToken: string;+}): Promise<unknown[]> {+ "use workflow";+ const inbox = createSessionInbox(getWorkflowMetadata().workflowRunId);+ using gate = createHook<void>({ token: input.releaseToken });+ try {+ await inbox.claimSessionHook(sessionCommandHookToken(getWorkflowMetadata().workflowRunId));+ for (const token of input.aliases) await inbox.claimSessionHook(token);+ await gate;+ return await recordPumpedMessages(inbox.drain());+ } finally {+ await inbox.dispose();+ }+}++async function recordPumpedMessages(messages: readonly unknown[]): Promise<unknown[]> {+ "use step";+ return [...messages];+}diff --git a/packages/eve/src/internal/testing/session-command-inbox-workflow.ts b/packages/eve/src/internal/testing/session-inbox-workflow.tssimilarity index 60%rename from packages/eve/src/internal/testing/session-command-inbox-workflow.tsrename to packages/eve/src/internal/testing/session-inbox-workflow.tsindex c71eaf015..681282895 100644--- a/packages/eve/src/internal/testing/session-command-inbox-workflow.ts+++ b/packages/eve/src/internal/testing/session-inbox-workflow.ts@@ -1,10 +1,7 @@import { getWorkflowMetadata } from "#compiled/@workflow/core/index.js";-import {- createSessionCommandInbox,- type SessionInboxPayload,-} from "#execution/session-command-inbox.js";-import { sessionCommandHookToken } from "#execution/session-command-token.js";+import { createSessionInbox, type SessionInboxPayload } from "#execution/session-inbox/inbox.js";+import { sessionCommandHookToken } from "#execution/session-inbox/address.js";export async function sessionCommandInboxWorkflow(input: {readonly messageCount?: number;@@ -13,25 +10,25 @@ export async function sessionCommandInboxWorkflow(input: {}): Promise<string[]> {"use workflow";- const inbox = createSessionCommandInbox();const { workflowRunId } = getWorkflowMetadata();+ const inbox = createSessionInbox(workflowRunId);try {- await inbox.claimStable(sessionCommandHookToken(workflowRunId));- await inbox.rekeyContinuation(input.token);+ await inbox.claimSessionHook(sessionCommandHookToken(workflowRunId));+ await inbox.claimSessionHook(input.token);const pending = inbox.next();if (input.nextToken !== undefined) {- await inbox.rekeyContinuation(input.nextToken);+ await inbox.claimSessionHook(input.nextToken);}const messages: string[] = [];- let next = await pending;+ let payload = await pending;while (true) {- inbox.consumeNext();- if (next.done || next.value.kind === "reset") return messages;- collectMessage(next.value, messages);+ if (payload === undefined) return messages;+ if (payload.kind === "reset") return messages;+ collectMessage(payload, messages);if (messages.length >= (input.messageCount ?? 2)) return messages;- next = await inbox.next();+ payload = await inbox.next();}} finally {await inbox.dispose();diff --git a/packages/eve/src/internal/testing/session-state.ts b/packages/eve/src/internal/testing/session-state.tsnew file mode 100644index 000000000..8a95d3138--- /dev/null+++ b/packages/eve/src/internal/testing/session-state.ts@@ -0,0 +1,26 @@+import {+ DURABLE_SESSION_VERSION,+ type DurableSessionState,+} from "#execution/durable-session-store.js";++/** Complete session checkpoint for tests that exercise workflow coordination. */+export function createTestSessionState(+ overrides: Partial<DurableSessionState> = {},+): DurableSessionState {+ return {+ continuationToken: overrides.continuationToken ?? "test-token",+ sessionId: overrides.sessionId ?? "test-session",+ emissionState: { sequence: 0, sessionStarted: false, stepIndex: 0, turnId: "" },+ hasProxyInputRequests: false,+ version: DURABLE_SESSION_VERSION,+ snapshot: {+ session: {+ agent: { system: "" },+ continuationToken: overrides.continuationToken ?? "test-token",+ history: [],+ sessionId: overrides.sessionId ?? "test-session",+ },+ },+ ...overrides,+ };+}diff --git a/packages/eve/src/internal/testing/task-cancel-notification-workflow.ts b/packages/eve/src/internal/testing/task-cancel-notification-workflow.tsindex aaf7f2f0c..4dd1bdde3 100644--- a/packages/eve/src/internal/testing/task-cancel-notification-workflow.ts+++ b/packages/eve/src/internal/testing/task-cancel-notification-workflow.ts@@ -1,7 +1,7 @@import { createHook, getWorkflowMetadata, sleep } from "#compiled/@workflow/core/index.js";-import { createSessionCommandInbox } from "#execution/session-command-inbox.js";-import { sessionCommandHookToken } from "#execution/session-command-token.js";+import { createSessionInbox } from "#execution/session-inbox/inbox.js";+import { sessionCommandHookToken } from "#execution/session-inbox/address.js";import { appendTaskViewStep } from "#execution/tasks/child/steps.js";import { cancelOwnedTask } from "#execution/tasks/parent/dispatch.js";import { waitForCommandHookOwner } from "#execution/workflow-runtime.js";@@ -64,14 +64,15 @@ export async function taskCancelNotificationWorkflow() {"use workflow";const { workflowRunId: sessionId } = getWorkflowMetadata();- const inbox = createSessionCommandInbox();+ const inbox = createSessionInbox(sessionId);try {- await inbox.claimStable(sessionCommandHookToken(sessionId));+ await inbox.claimSessionHook(sessionCommandHookToken(sessionId));const entry = await startSlowCancelledTaskStep({ sessionId });const cancelled = await cancelSlowTaskFromParentStep({ entry, sessionId });- const next = await inbox.next();- inbox.consumeNext();- return { ...cancelled, notification: next.value };+ const notification = await inbox.next();+ if (notification === undefined)+ throw new Error("Session inbox closed before task cancellation.");+ return { ...cancelled, notification };} finally {await inbox.dispose();}diff --git a/packages/eve/src/internal/testing/task-model-retry-workflow.ts b/packages/eve/src/internal/testing/task-model-retry-workflow.tsindex 605d3335c..0b642633f 100644--- a/packages/eve/src/internal/testing/task-model-retry-workflow.ts+++ b/packages/eve/src/internal/testing/task-model-retry-workflow.ts@@ -70,7 +70,7 @@ export async function taskModelRetryStep(input: {"use step";const { attempt } = getStepMetadata();- const durable = await readDurableSession(input.sessionState);+ const durable = readDurableSession(input.sessionState);const session = hydrateDurableSession({ durable, turnAgent: createTurnAgent() });const historyBeforeModelCall = [...session.history];const model = new MockLanguageModelV3({diff --git a/packages/eve/src/internal/testing/workflow-tool-fixtures.ts b/packages/eve/src/internal/testing/workflow-tool-fixtures.tsindex 4e1b767ba..274351cf5 100644--- a/packages/eve/src/internal/testing/workflow-tool-fixtures.ts+++ b/packages/eve/src/internal/testing/workflow-tool-fixtures.ts@@ -1,7 +1,7 @@/*** Authored workflow tool bodies for integration tests. Each exported* `"use workflow"` function stands in for a tool's `execute`: the test tier's- * bundler registers them in the driver, and the harness sees the stubs the+ * bundler registers them in the workflow owner, and the harness sees the stubs the* client transform leaves behind, exactly as it would for an application's* `agent/tools/*.ts`.*/@@ -13,7 +13,6 @@ import {} from "#compiled/@workflow/core/index.js";import type { WorkflowToolContext } from "#tools/workflow-definition.js";-import { executeWorkflowBody, type WorkflowBodyInput } from "#execution/tools/workflow/body.js";import type { TaskExec, TaskMessage } from "#tools/task.js";import {ConnectionAuthorizationFailedError,@@ -249,12 +248,3 @@ export async function askThenRaceWorkflow(const answer = await Promise.race([pending, workflowSleep("50ms")]);return { decided: answer === undefined ? "timed out" : "answered", service: input.service };}--/** Runs the actual workflow body with the capability passed by its launching turn. */-export async function workflowAuthorizationCapabilityProbe(- input: WorkflowBodyInput & { execution: "background" | "blocking" },-) {- "use workflow";-- return executeWorkflowBody(input, new AbortController().signal);-}diff --git a/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts b/packages/eve/src/internal/workflow-bundle/builder.scenario.test.tsindex 91be973a7..3ed261b6f 100644--- a/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts+++ b/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts@@ -661,7 +661,7 @@ describe("WorkflowBundleBuilder", () => {it.each([["sleep tool", "src/execution/tools/sleep-workflow.ts", "executeSleepTool"],- ["session driver", "src/execution/workflow-entry.ts", "nextTurnDelivery"],+ ["session owner", "src/execution/session/entry.ts", "nextTurnDelivery"],])("keeps the %s schemas out of the workflow driver", async (_name, sourcePath, marker) => {const tempRoot = await mkdtemp(join(tmpdir(), "eve-workflow-bundle-no-schemas-"));const outDir = join(tempRoot, "workflow-build");diff --git a/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts b/packages/eve/src/internal/workflow-bundle/workflow-builders.test.tsindex 33a6780d9..f15dc4ce5 100644--- a/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts+++ b/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts@@ -46,21 +46,23 @@ describe("applyWorkflowTransform", () => {}});- it("keeps eve workflow references stable when eve is the project root", async () => {- const filename = "src/execution/turn-workflow.ts";+ it.each([+ ["workflowEntry", "src/execution/session/entry.ts"],+ ["turnWorkflow", "src/execution/legacy-session/turn-workflow.ts"],+ ])("keeps %s stable across package versions and source moves", async (name, filename) => {const transformed = await applyWorkflowTransform(filename,- ["export async function turnWorkflow(): Promise<void> {", ' "use workflow";', "}", ""].join(- "\n",- ),+ [`export async function ${name}(): Promise<void> {`, ' "use workflow";', "}", ""].join("\n"),"workflow",resolvePackageSourceFilePath(filename),resolvePackageRoot(),);-- expect(transformed.workflowManifest.workflows?.[filename]?.turnWorkflow).toEqual({- workflowId: "workflow//eve//turnWorkflow",+ expect(transformed.workflowManifest.workflows?.[filename]?.[name]).toEqual({+ workflowId: `workflow//eve//${name}`,});+ expect(transformed.code).toContain(+ `globalThis.__private_workflows.set("workflow//eve//${name}", ${name});`,+ );});it("keeps the shared subagent tool workflow stable", async () => {@@ -299,11 +301,11 @@ describe("applyWorkflowTransform", () => {// version-stamped because they are per-deployment internal// identifiers, not cross-deployment routing keys.const transformed = await transformWorkflowDirectives({- filename: "src/execution/turn-workflow.ts",+ filename: "src/execution/workflow-entry.ts",mode: "workflow",moduleSpecifier: "[email protected]",source: [- "export async function turnWorkflow(input: { id: string }): Promise<string> {",+ "export async function workflowEntry(input: { id: string }): Promise<string> {",' "use workflow";'," return input.id;","}",@@ -315,28 +317,30 @@ describe("applyWorkflowTransform", () => {"",].join("\n"),stableModuleSpecifier: "eve",- stableWorkflowNames: new Set(["turnWorkflow"]),+ stableWorkflowNames: new Set(["workflowEntry"]),});expect(transformed.workflowManifest).toEqual({steps: {- "src/execution/turn-workflow.ts": {+ "src/execution/workflow-entry.ts": {notifyDriverStep: {stepId: "step//[email protected]//notifyDriverStep",},},},workflows: {- "src/execution/turn-workflow.ts": {- turnWorkflow: {- workflowId: "workflow//eve//turnWorkflow",+ "src/execution/workflow-entry.ts": {+ workflowEntry: {+ workflowId: "workflow//eve//workflowEntry",},},},});- expect(transformed.code).toContain('turnWorkflow.workflowId = "workflow//eve//turnWorkflow";');expect(transformed.code).toContain(- 'globalThis.__private_workflows.set("workflow//eve//turnWorkflow", turnWorkflow);',+ 'workflowEntry.workflowId = "workflow//eve//workflowEntry";',+ );+ expect(transformed.code).toContain(+ 'globalThis.__private_workflows.set("workflow//eve//workflowEntry", workflowEntry);',);});});@@ -521,10 +525,10 @@ describe("applyWorkflowTransform for authored application modules", () => {it("treats eve package sources as framework modules even under the project root", async () => {const eveRoot = resolvePackageRoot();- const filename = "src/execution/turn-workflow.ts";+ const filename = "src/execution/workflow-entry.ts";const transformed = await applyWorkflowTransform(filename,- ["export async function turnWorkflow(): Promise<void> {", ' "use workflow";', "}", ""].join(+ ["export async function workflowEntry(): Promise<void> {", ' "use workflow";', "}", ""].join("\n",),"workflow",@@ -532,14 +536,14 @@ describe("applyWorkflowTransform for authored application modules", () => {eveRoot,);- expect(transformed.workflowManifest.workflows?.[filename]?.turnWorkflow?.workflowId).toBe(- "workflow//eve//turnWorkflow",+ expect(transformed.workflowManifest.workflows?.[filename]?.workflowEntry?.workflowId).toBe(+ "workflow//eve//workflowEntry",);});it("keeps the session command inbox factory visible in workflow driver builds", async () => {const eveRoot = resolvePackageRoot();- const filename = "src/execution/session-command-inbox.ts";+ const filename = "src/execution/session-inbox/inbox.ts";const source = readFileSync(resolvePackageSourceFilePath(filename), "utf8");const transformed = await applyWorkflowTransform(filename,@@ -549,7 +553,7 @@ describe("applyWorkflowTransform for authored application modules", () => {eveRoot,);- expect(transformed.code).toContain("export function createSessionCommandInbox");+ expect(transformed.code).toContain("export function createSessionInbox");expect(transformed.code).not.toContain("subagent");expect(transformed.code).not.toContain("WORKFLOW_USE_STEP");});diff --git a/packages/eve/src/internal/workflow/development-world-client.ts b/packages/eve/src/internal/workflow/development-world-client.tsindex 46a5f8cd3..3a1c0a8f3 100644--- a/packages/eve/src/internal/workflow/development-world-client.ts+++ b/packages/eve/src/internal/workflow/development-world-client.ts@@ -9,7 +9,6 @@ import { resolvePackageSourceFilePath } from "#internal/application/package.js";import { readFile } from "node:fs/promises";import { basename, join } from "node:path";-import { turnWorkflowReference } from "#execution/workflow-runtime.js";import {decodeDevelopmentWorldJson,decodeDevelopmentWorldValue,@@ -241,8 +240,7 @@ async function resolveDeliveryGenerationId(message: unknown): Promise<string> {}const runInput = isRecord(message.runInput) ? message.runInput : undefined;if (runInput !== undefined) {- return runInput.workflowName === turnWorkflowReference.workflowId &&- typeof runInput.deploymentId === "string"+ return typeof runInput.deploymentId === "string"? runInput.deploymentId: await call<string>("resolveLatestDeploymentId");}@@ -255,13 +253,11 @@ async function resolveDeliveryGenerationId(message: unknown): Promise<string> {if (runId === undefined) {return await call<string>("resolveLatestDeploymentId");}- const run = await call<{ readonly deploymentId: string; readonly workflowName: string }>(- "runs.get",- [runId, { resolveData: "none" }],- );- return run.workflowName === turnWorkflowReference.workflowId- ? run.deploymentId- : await call<string>("resolveLatestDeploymentId");+ const run = await call<{ readonly deploymentId: string }>("runs.get", [+ runId,+ { resolveData: "none" },+ ]);+ return run.deploymentId;}async function readGenerationRuntimeAppRoot(diff --git a/packages/eve/src/internal/workflow/development-world-server.integration.test.ts b/packages/eve/src/internal/workflow/development-world-server.integration.test.tsindex b426a71de..b17efc81c 100644--- a/packages/eve/src/internal/workflow/development-world-server.integration.test.ts+++ b/packages/eve/src/internal/workflow/development-world-server.integration.test.ts@@ -3,7 +3,7 @@ import { join } from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";-import { turnWorkflowReference, workflowEntryReference } from "#execution/workflow-runtime.js";+import { workflowEntryReference } from "#execution/workflow-runtime.js";import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";import { getDevelopmentWorkflowGeneration } from "#internal/workflow/development-generation-context.js";import { deriveEveWorkflowQueuePrefix } from "#internal/workflow/queue-namespace.js";@@ -106,7 +106,7 @@ describe("parent development Workflow World", () => {}});- it("pins a turn delivery to its recorded generation", async () => {+ it("pins every workflow delivery to its recorded generation", async () => {const appRoot = await createScratchDirectory("eve-parent-workflow-world-");await seedGeneration(appRoot, "generation-a");await seedGeneration(appRoot, "generation-b");@@ -123,7 +123,7 @@ describe("parent development Workflow World", () => {deploymentId: "generation-a",executionContext: {},input: new Uint8Array(),- workflowName: turnWorkflowReference.workflowId,+ workflowName: workflowEntryReference.workflowId,},eventType: "run_created",specVersion: 6,@@ -138,8 +138,9 @@ describe("parent development Workflow World", () => {}});- it("routes the generation-neutral driver to active and rejects untrusted deliveries", async () => {+ it("honors exact run input generations and rejects untrusted deliveries", async () => {const appRoot = await createScratchDirectory("eve-parent-workflow-routing-");+ await seedGeneration(appRoot, "generation-a");await seedGeneration(appRoot, "generation-b");const world = createWorld({ activeGenerationId: () => "generation-b", appRoot });connectWorkerToWorld(world, appRoot);@@ -156,7 +157,7 @@ describe("parent development Workflow World", () => {workflowName: workflowEntryReference.workflowId,},}),- ).resolves.toBe("generation-b");+ ).resolves.toBe("generation-a");const untrusted = await createWorkerQueueHandler()(new Request("http://localhost/.well-known/workflow/v1/flow", {@@ -183,7 +184,7 @@ describe("parent development Workflow World", () => {deploymentId: "generation-a",executionContext: {},input: new Uint8Array(),- workflowName: turnWorkflowReference.workflowId,+ workflowName: workflowEntryReference.workflowId,},eventType: "run_created",specVersion: 6,@@ -228,7 +229,7 @@ describe("parent development Workflow World", () => {deploymentId: "generation-a",executionContext: {},input: new Uint8Array(),- workflowName: turnWorkflowReference.workflowId,+ workflowName: workflowEntryReference.workflowId,},eventType: "run_created",specVersion: 6,@@ -277,7 +278,7 @@ describe("parent development Workflow World", () => {deploymentId: "generation-a",executionContext: {},input: new Uint8Array(),- workflowName: turnWorkflowReference.workflowId,+ workflowName: workflowEntryReference.workflowId,},eventType: "run_created",specVersion: 6,@@ -413,7 +414,7 @@ function deliveryHeaders(input: { readonly secret?: string }): Record<string, st[DEVELOPMENT_WORKFLOW_DELIVERY_HEADER]: input.secret ?? SECRET,"x-vqs-message-attempt": "1","x-vqs-message-id": "msg_test",- "x-vqs-queue-name": `${QUEUE_PREFIX}${turnWorkflowReference.workflowId}`,+ "x-vqs-queue-name": `${QUEUE_PREFIX}${workflowEntryReference.workflowId}`,};}diff --git a/packages/eve/src/internal/workflow/development-world-server.ts b/packages/eve/src/internal/workflow/development-world-server.tsindex 9144cbd97..ff607af13 100644--- a/packages/eve/src/internal/workflow/development-world-server.ts+++ b/packages/eve/src/internal/workflow/development-world-server.ts@@ -3,7 +3,6 @@ import { basename, join } from "node:path";import type { ValidQueueName, World } from "#compiled/@workflow/world/index.js";import { createWorld } from "#compiled/@workflow/world-local/index.js";-import { turnWorkflowReference } from "#execution/workflow-runtime.js";import { deriveEveWorkflowQueuePrefix } from "#internal/workflow/queue-namespace.js";import {LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH,@@ -154,11 +153,7 @@ class LocalParentDevelopmentWorkflowWorld implements ParentDevelopmentWorkflowWo{ cause: error },);}- for (const run of page.data) {- if (run.workflowName === turnWorkflowReference.workflowId) {- generationIds.add(run.deploymentId);- }- }+ for (const run of page.data) generationIds.add(run.deploymentId);cursor = page.hasMore ? (page.cursor ?? undefined) : undefined;} while (cursor !== undefined);}diff --git a/packages/eve/src/internal/workflow/local-world-delivery-timeouts.ts b/packages/eve/src/internal/workflow/local-world-delivery-timeouts.tsindex 22e001d7f..3c62f3236 100644--- a/packages/eve/src/internal/workflow/local-world-delivery-timeouts.ts+++ b/packages/eve/src/internal/workflow/local-world-delivery-timeouts.ts@@ -7,7 +7,7 @@ const LOCAL_WORKFLOW_DELIVERY_TIMEOUT_ENV_NAMES = [* Disables world-local's delivery deadlines unless the operator supplied an* override. world-local snapshots these values when `createWorld()` constructs* its queue and supports `0` as an unbounded timeout. Without this default, a- * long inline turn can be retried while its original provider call is active.+ * long owner turn can be retried while its original provider call is active.*/export function applyLocalWorkflowWorldDeliveryTimeoutDefaults(env: Record<string, string | undefined> = process.env as Record<string, string | undefined>,diff --git a/packages/eve/src/internal/workflow/runtime.ts b/packages/eve/src/internal/workflow/runtime.tsindex b3e2e55a6..abdb46c19 100644--- a/packages/eve/src/internal/workflow/runtime.ts+++ b/packages/eve/src/internal/workflow/runtime.ts@@ -1,5 +1,4 @@import * as workflowRuntime from "#compiled/@workflow/core/runtime.js";-import type { Hook } from "#compiled/@workflow/world/index.js";export * from "#compiled/@workflow/core/runtime.js";export type {@@ -8,15 +7,9 @@ export type {WorkflowMetadata,} from "#compiled/@workflow/core/runtime/start.js";-/**- * Reads a hook without decrypting metadata or resolving an encryption key.- * Metadata is excluded from the return type; use `getHookByToken` to read it.- */-export async function getRawHookByToken(token: string): Promise<Omit<Hook, "metadata">> {- return await (await workflowRuntime.getWorld()).hooks.getByToken(token);-}-/** Installs a World across source and vendored Workflow package identities. */export function setWorld(world: unknown): void {workflowRuntime.setWorld(world as Parameters<typeof workflowRuntime.setWorld>[0]);}++export { resolveRunEncryptionKey } from "#compiled/@workflow/core/runtime/helpers.js";diff --git a/packages/eve/src/internal/workflow/vercel-world-defaults.test.ts b/packages/eve/src/internal/workflow/vercel-world-defaults.test.tsnew file mode 100644index 000000000..cb40d8c37--- /dev/null+++ b/packages/eve/src/internal/workflow/vercel-world-defaults.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from "vitest";++import { applyVercelWorkflowWorldDefaults } from "#internal/workflow/vercel-world-defaults.js";++describe("applyVercelWorkflowWorldDefaults", () => {+ it("batches event bursts without changing the world's other settings", () => {+ const streams = {};+ const world: { streams: object; streamFlushIntervalMs?: number } = { streams };+ applyVercelWorkflowWorldDefaults(world);+ expect(world).toEqual({ streams, streamFlushIntervalMs: 10 });+ expect(world.streams).toBe(streams);+ });++ it.each([0, 5, 25])("preserves an explicit %i ms window", (streamFlushIntervalMs) => {+ const world = { streamFlushIntervalMs };+ applyVercelWorkflowWorldDefaults(world);+ expect(world.streamFlushIntervalMs).toBe(streamFlushIntervalMs);+ });+});diff --git a/packages/eve/src/internal/workflow/vercel-world-defaults.ts b/packages/eve/src/internal/workflow/vercel-world-defaults.tsnew file mode 100644index 000000000..afec70685--- /dev/null+++ b/packages/eve/src/internal/workflow/vercel-world-defaults.ts@@ -0,0 +1,6 @@+/** Configure the freshly constructed built-in Vercel World before installation. */+export function applyVercelWorkflowWorldDefaults(world: { streamFlushIntervalMs?: number }): void {+ // Lifecycle events arrive across several async handlers; a short window lets+ // each burst share a network write. The SDK's explicit env override still wins.+ world.streamFlushIntervalMs ??= 10;+}diff --git a/packages/eve/src/protocol/activity.ts b/packages/eve/src/protocol/activity.tsindex eddcc3d2b..8de362f3e 100644--- a/packages/eve/src/protocol/activity.ts+++ b/packages/eve/src/protocol/activity.ts@@ -127,22 +127,7 @@ export interface ActivitySnapshotV1 {}export function parseActivityWorkIdentityV1(value: unknown): ActivityWorkIdentityV1 | undefined {- if (- !isRecord(value) ||- !hasOnlyKeys(value, [- "callId",- "id",- "kind",- "label",- "name",- "parentId",- "rootSessionId",- "rootTurnId",- "sessionId",- "turnId",- ])- )- return undefined;+ if (!isRecord(value)) return undefined;const kind = value.kind;if (!isOneOf(kind, ["root-turn", "subagent", "remote-agent", "task"] as const) ||@@ -158,6 +143,7 @@ export function parseActivityWorkIdentityV1(value: unknown): ActivityWorkIdentit)return undefined;return {+ ...value,callId: value.callId,id: value.id,kind,diff --git a/packages/eve/src/protocol/routes.ts b/packages/eve/src/protocol/routes.tsindex d85aa8138..c2afd35ea 100644--- a/packages/eve/src/protocol/routes.ts+++ b/packages/eve/src/protocol/routes.ts@@ -107,9 +107,6 @@ export function createEveDevDispatchSchedulePath(scheduleId: string): string {*/export const EVE_CONNECTION_CALLBACK_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/connections/:name/callback/:attemptId/:token`;-/** Callback shape minted by deployments before authorization attempt IDs. */-export const EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`;-/*** Stable framework-owned route pattern for terminal session callbacks.*diff --git a/packages/eve/src/public/channels/discord/discordChannel.test.ts b/packages/eve/src/public/channels/discord/discordChannel.test.tsindex 141517187..8848b5691 100644--- a/packages/eve/src/public/channels/discord/discordChannel.test.ts+++ b/packages/eve/src/public/channels/discord/discordChannel.test.ts@@ -490,7 +490,7 @@ describe("discordChannel() default event handlers", () => {);});- it("edits the original response and rekeys the session on the first post", async () => {+ it("edits the original response and aliases the session on the first post", async () => {const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ channel_id: "C01", id: "M01" }), {headers: { "content-type": "application/json" },diff --git a/packages/eve/src/public/channels/discord/discordChannel.ts b/packages/eve/src/public/channels/discord/discordChannel.tsindex e5e09badf..ddb6c9902 100644--- a/packages/eve/src/public/channels/discord/discordChannel.ts+++ b/packages/eve/src/public/channels/discord/discordChannel.ts@@ -341,7 +341,7 @@ function buildDiscordHandle(input: {state.conversationId = posted.id;state.hasMessageAnchor = true;if (state.channelId) {- input.session?.continuation?.rekey(discordContinuationToken(state.channelId, posted.id));+ input.session?.continuation?.alias(discordContinuationToken(state.channelId, posted.id));}}diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.tsindex 7bf503238..8dc93ffbb 100644--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts@@ -9,7 +9,6 @@ import type { ChannelFrom, ChannelSource } from "#channel/channel-operations.js"import { isHttpRouteDefinition } from "#channel/routes.js";import { ContextContainer, contextStorage } from "#context/container.js";import { SessionKey } from "#context/keys.js";-import { sessionInboxWire } from "#execution/wire/session-inbox-encoder.js";import {mockChannelContext,type ObservedChannelDelivery,@@ -169,7 +168,7 @@ function callCompletionHandler(/*** Accessor whose `set` writes are captured so tests can assert on- * `continuation.rekey` flowing through the SessionHandle. Returns+ * `continuation.alias` flowing through the SessionHandle. Returns* undefined for unset keys (matching the real `ContextContainer`* behavior), while seeding the current continuation token so* SessionHandle can preserve the runtime namespace.@@ -1621,7 +1620,7 @@ describe("rebuildSlackContext", () => {expect("threadId" in ctx.thread).toBe(false);});- it("auto-anchors state.threadTs and re-keys the session on the first post", async () => {+ it("auto-anchors state.threadTs and adds an alias for the session on the first post", async () => {const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ ok: true, ts: "1800000000.123456" }), {headers: { "content-type": "application/json" },@@ -1659,7 +1658,7 @@ describe("rebuildSlackContext", () => {expect((adapter.state as { threadTs: string | null }).threadTs).toBe("1800000000.123456");// The anchor moment wrote the new continuation token to context- // via `session.continuation.rekey(...)`. The workflow body picks+ // via `session.continuation.alias(...)`. The workflow body picks// this up via `reconcileSessionContinuationToken` after the step.const tokenWrites = writes.filter(([key]) => key === "eve.continuationToken");expect(tokenWrites).toEqual([["eve.continuationToken", "slack:C01:1800000000.123456"]]);@@ -1686,7 +1685,7 @@ describe("rebuildSlackContext", () => {const secondBody = parseSlackRequestBody(fetchMock.mock.calls[1]![1] as RequestInit);expect(secondBody.thread_ts).toBe("1800000000.123456");- // Once anchored, continuation.rekey does not fire again — the+ // Once anchored, continuation.alias does not fire again — the// raw token is unchanged across subsequent posts.const allTokenWrites = writes.filter(([key]) => key === "eve.continuationToken");expect(allTokenWrites).toHaveLength(1);@@ -3463,16 +3462,6 @@ describe("slackChannel() HITL interaction pipeline", () => {approvalResponderUsers: { "slack:T_ACTOR:U_APPROVER": "U_APPROVER" },},});- expect(- sessionInboxWire.encode(- { kind: "send", payload: { inputResponses: input.inputResponses } },- { version: 1 },- ),- ).toMatchObject({- kind: "deliver",- payloads: [{ inputResponses: [{ optionId: "approve", requestId: "approval_abc123" }] }],- version: 1,- });});it("opens routed freeform modals with installation-scoped credentials and metadata", async () => {diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.tsindex 4ab5fc6c0..44ce0f44b 100644--- a/packages/eve/src/public/channels/slack/slackChannel.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.ts@@ -838,7 +838,7 @@ function rebuildSlackContext(onThreadTsChanged(ts) {state.threadTs = ts;if (state.channelId) {- session.continuation?.rekey(slackContinuationToken(state.channelId, ts));+ session.continuation?.alias(slackContinuationToken(state.channelId, ts));}},});@@ -1112,7 +1112,7 @@ async function receiveOnSlack(}// Threadless proactive runs need distinct identities until their first- // Slack post supplies the real thread timestamp and re-keys the session.+ // Slack post supplies the real thread timestamp and aliases the session.const continuationThreadTs = threadTs || crypto.randomUUID();const audience =receiveTarget.audience === undefineddiff --git a/packages/eve/src/public/channels/teams/teamsChannel.ts b/packages/eve/src/public/channels/teams/teamsChannel.tsindex 18f8f4bcd..efcf8e887 100644--- a/packages/eve/src/public/channels/teams/teamsChannel.ts+++ b/packages/eve/src/public/channels/teams/teamsChannel.ts@@ -505,7 +505,7 @@ function buildTeamsHandle(input: {state.replyToActivityId = posted.id;const conversationId = state.conversationId;if (conversationId) {- input.session?.continuation?.rekey(+ input.session?.continuation?.alias(teamsContinuationToken({conversationId,replyToActivityId: posted.id,diff --git a/packages/eve/src/public/channels/telegram/telegramChannel.test.ts b/packages/eve/src/public/channels/telegram/telegramChannel.test.tsindex c490bfce5..4c2765420 100644--- a/packages/eve/src/public/channels/telegram/telegramChannel.test.ts+++ b/packages/eve/src/public/channels/telegram/telegramChannel.test.ts@@ -682,7 +682,7 @@ describe("telegramChannel() default event handlers", () => {expect(ctx.state.pendingFreeformReplies).toEqual({ "51": "call_1" });});- it("hydrates unknown private message posts without re-keying the session", async () => {+ it("hydrates unknown private message posts without aliasing the session", async () => {const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({@@ -750,7 +750,7 @@ describe("telegramChannel() default event handlers", () => {expect(ctx.state.conversationId).toBeNull();});- it("hydrates unknown group message posts and re-keys to the posted message id", async () => {+ it("hydrates unknown group message posts and adds an alias for to the posted message id", async () => {const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({@@ -818,7 +818,7 @@ describe("telegramChannel() default event handlers", () => {expect(ctx.state.conversationId).toBe("caller-selected");});- it("group message posts re-key the session to the posted message id", async () => {+ it("group message posts alias the session to the posted message id", async () => {const fetchMock = vi.fn().mockResolvedValue(diff --git a/packages/eve/src/public/channels/telegram/telegramChannel.ts b/packages/eve/src/public/channels/telegram/telegramChannel.tsindex 38ca341ad..129bdf10c 100644--- a/packages/eve/src/public/channels/telegram/telegramChannel.ts+++ b/packages/eve/src/public/channels/telegram/telegramChannel.ts@@ -380,7 +380,7 @@ function buildTelegramHandle(input: {if (!posted.id || !shouldAnchorTelegramConversation(chatType)) return;state.conversationId = posted.id;if (state.chatId) {- input.session?.continuation?.rekey(+ input.session?.continuation?.alias(telegramContinuationToken({chatId: state.chatId,conversationId: posted.id,diff --git a/packages/eve/src/public/definitions/channel.test.ts b/packages/eve/src/public/definitions/channel.test.tsindex 737614a01..2bbc84ad8 100644--- a/packages/eve/src/public/definitions/channel.test.ts+++ b/packages/eve/src/public/definitions/channel.test.ts@@ -384,7 +384,7 @@ describe("defineChannel", () => {}const captured: {- sessions: Array<{ continuation?: { rekey(token: string): void } }>;+ sessions: Array<{ continuation?: { alias(token: string): void } }>;} = {sessions: [],};@@ -401,7 +401,7 @@ describe("defineChannel", () => {const adapter = getAdapter(channel);// Stand up a minimal accessor whose `set` calls are captured so the- // session handle's continuation rekey is observable.+ // session handle's additive continuation claim is observable.const writes: Array<[string, unknown]> = [];let continuationToken = "slack:C123:";const accessor: ContextAccessor = {@@ -433,8 +433,11 @@ describe("defineChannel", () => {// The session is the one ctx.session exposes (same reference).expect(adapterCtx.session).toBe(captured.sessions[0]);- captured.sessions[0]!.continuation?.rekey("C123:T456");- expect(writes).toEqual([["eve.continuationToken", "slack:C123:T456"]]);+ captured.sessions[0]!.continuation?.alias("C123:T456");+ expect(writes).toEqual([+ ["eve.continuationHookTokens", ["slack:C123:", "slack:C123:T456"]],+ ["eve.continuationToken", "slack:C123:T456"],+ ]);});it("passes SessionContext as third arg to event handlers inside the ALS scope", async () => {diff --git a/packages/eve/src/public/definitions/channel.ts b/packages/eve/src/public/definitions/channel.tsindex cc73a879d..e31f71192 100644--- a/packages/eve/src/public/definitions/channel.ts+++ b/packages/eve/src/public/definitions/channel.ts@@ -166,7 +166,7 @@ type EventData<T extends UnstampedMessageStreamEvent["type"]> =export interface ChannelContinuationOps {readonly continuation?: {readonly token: string;- rekey(token: string): void;+ alias(token: string): void;};}@@ -361,7 +361,7 @@ function buildAdapter<TState, TCtx, TReceiveTarget, TMetadata extends Record<str? undefined: {token: session.continuation.token,- rekey: (token: string) => session.continuation?.rekey(token),+ alias: (token: string) => session.continuation?.alias(token),},};if (eventType === "session.failed") {diff --git a/packages/eve/src/public/next/index.integration.test.ts b/packages/eve/src/public/next/index.integration.test.tsindex dfd6aeec2..a3151b9bc 100644--- a/packages/eve/src/public/next/index.integration.test.ts+++ b/packages/eve/src/public/next/index.integration.test.ts@@ -50,9 +50,8 @@ describe("withEve Vercel config", () => {vi.stubEnv("NODE_ENV", "production");const config = await resolveConfig(withEve<TestConfig>({}));-await expect(config.rewrites?.()).rejects.toThrow(- `Run eve build from ${appRoot} before starting Next.js.`,+ /Run eve build from .+ before starting Next\.js\./u,);await expect(readFile(join(appRoot, ".vercel", "output", "config.json"), "utf8"),diff --git a/packages/eve/src/runtime/attributes/emit.ts b/packages/eve/src/runtime/attributes/emit.tsindex 096782995..d6d43986f 100644--- a/packages/eve/src/runtime/attributes/emit.ts+++ b/packages/eve/src/runtime/attributes/emit.ts@@ -60,8 +60,8 @@ export async function setEveAttributes(attrs: Record<string, EveAttributeValue>)}try {- // Import `@workflow/core` dynamically (matching `workflow-steps.ts`,- // `turn-workflow.ts`, etc.). A static import here would pull the+ // Import `@workflow/core` dynamically (matching `session/turn-step.ts`,+ // `session/entry.ts`, etc.). A static import here would pull the// compiled core into emit.js's static graph and defeat the dynamic// chunking those modules rely on — the build emits an// `INEFFECTIVE_DYNAMIC_IMPORT` warning and `bin-build-output` fails.diff --git a/packages/eve/src/runtime/connections/callback-route.test.ts b/packages/eve/src/runtime/connections/callback-route.test.tsindex dcd4a9f8c..ec3a169d5 100644--- a/packages/eve/src/runtime/connections/callback-route.test.ts+++ b/packages/eve/src/runtime/connections/callback-route.test.ts@@ -2,10 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import { createEveConnectionCallbackRoutePath } from "#protocol/routes.js";import type { RouteContext } from "#public/definitions/channel.js";-import {- handleConnectionCallbackRequest,- handleLegacyConnectionCallbackRequest,-} from "#execution/connections/callback-route.js";+import { handleConnectionCallbackRequest } from "#execution/connections/callback-route.js";const resumeHookMock = vi.fn();@@ -55,13 +52,13 @@ describe("handleConnectionCallbackRequest", () => {it("forwards a GET callback into resumeHook as parsed params with no request headers", async () => {resumeHookMock.mockResolvedValueOnce(undefined);- const url = `https://app.example.com${createEveConnectionCallbackRoutePath("linear", "attempt-1", "tok123")}?code=abc&state=xyz`;+ const url = `https://app.example.com${createEveConnectionCallbackRoutePath("linear", "attempt-1", "eve:inbox:v1:tok123")}?code=abc&state=xyz`;const response = await handleConnectionCallbackRequest(new Request(url, {headers: { "x-probe": "1" },method: "GET",}),- buildRouteContext({ attemptId: "attempt-1", name: "linear", token: "tok123" }),+ buildRouteContext({ attemptId: "attempt-1", name: "linear", token: "eve:inbox:v1:tok123" }),);expect(response.status).toBe(200);@@ -74,11 +71,11 @@ describe("handleConnectionCallbackRequest", () => {expect(resumeHookMock).toHaveBeenCalledTimes(1);const [token, payload] = resumeHookMock.mock.calls[0] ?? [];- expect(token).toBe("tok123");+ expect(token).toBe("eve:inbox:v1:tok123");// Exact match: only parsed params + method cross into the hook// payload. The inbound `x-probe` header (and any `Cookie`) is dropped.expect(payload).toEqual({- kind: "deliver",+ kind: "authorization-callback",payloads: [{authorizationCallback: {@@ -94,43 +91,21 @@ describe("handleConnectionCallbackRequest", () => {});});- it("keeps pre-attempt callback URLs resumable for pinned workflows", async () => {- resumeHookMock.mockResolvedValueOnce(undefined);- const response = await handleLegacyConnectionCallbackRequest(- new Request("https://app.example.com/eve/v1/connections/linear/callback/tok123?code=abc"),- buildRouteContext({ name: "linear", token: "tok123" }),- );-- expect(response.status).toBe(200);- expect(resumeHookMock).toHaveBeenCalledWith("tok123", {- kind: "deliver",- payloads: [- {- authorizationCallback: {- callback: { method: "GET", params: { code: "abc" } },- connectionName: "linear",- legacy: true,- },- },- ],- });- });-it("captures form-encoded POST bodies before resuming the hook", async () => {resumeHookMock.mockResolvedValueOnce(undefined);- const url = `https://app.example.com${createEveConnectionCallbackRoutePath("linear", "attempt-1", "tok123")}`;+ const url = `https://app.example.com${createEveConnectionCallbackRoutePath("linear", "attempt-1", "eve:inbox:v1:tok123")}`;await handleConnectionCallbackRequest(new Request(url, {body: "code=abc&state=xyz",headers: { "content-type": "application/x-www-form-urlencoded" },method: "POST",}),- buildRouteContext({ attemptId: "attempt-1", name: "linear", token: "tok123" }),+ buildRouteContext({ attemptId: "attempt-1", name: "linear", token: "eve:inbox:v1:tok123" }),);const [, payload] = resumeHookMock.mock.calls[0] ?? [];expect(payload).toEqual({- kind: "deliver",+ kind: "authorization-callback",payloads: [{authorizationCallback: {@@ -156,7 +131,7 @@ describe("handleConnectionCallbackRequest", () => {new Request(`https://app.example.com${createEveConnectionCallbackRoutePath("linear", "attempt-1", "tok")}`,),- buildRouteContext({ attemptId: "attempt-1", name: "linear", token: "tok" }),+ buildRouteContext({ attemptId: "attempt-1", name: "linear", token: "eve:inbox:v1:tok" }),);expect(response.status).toBe(404);const body = await response.json();diff --git a/packages/eve/src/runtime/prompt/compose.test.ts b/packages/eve/src/runtime/prompt/compose.test.tsindex ef13ffd97..fd855a19f 100644--- a/packages/eve/src/runtime/prompt/compose.test.ts+++ b/packages/eve/src/runtime/prompt/compose.test.ts@@ -28,6 +28,14 @@ describe("composeRuntimeBasePrompt", () => {expect(prompt).toContainEqual(expect.stringContaining("notify you"));});+ it("describes steering as updating the existing task without cancellation", () => {+ const prompt = composeRuntimeBasePrompt({ subagentsAvailable: true }).join("\n");++ expect(prompt).toContain("steers its active turn at the next safe boundary");+ expect(prompt).toContain("preserving the same taskId, child session, and pending approvals");+ expect(prompt).not.toContain("cancels its previous task");+ });+it("omits agent messaging instructions when subagents are unavailable", () => {const prompt = composeRuntimeBasePrompt({subagentsAvailable: false,diff --git a/packages/eve/src/runtime/prompt/compose.ts b/packages/eve/src/runtime/prompt/compose.tsindex defbd62e7..2406b4d1d 100644--- a/packages/eve/src/runtime/prompt/compose.ts+++ b/packages/eve/src/runtime/prompt/compose.ts@@ -12,7 +12,7 @@ const PARALLEL_ACTION_INSTRUCTION ="Tool execution\nA single tool or subagent call runs as one serial action. If you call multiple independent tools or subagents in one response, eve treats that batch as parallel work. Only batch work that is independent and does not rely on another call in the same response.";const AGENT_MESSAGING_INSTRUCTION =- "Agent messaging\nSubagent calls start durable background tasks and return immediately with a task receipt. After delegating, continue helping the user or end your turn. The task will notify you when it completes, fails, needs input, or sends an update; completion and failure notifications include the task's result. Agents you have already delegated to remain visible in the framework-authored `<agents>` conversation note. To steer delegated work, send the updated instruction to the original subagent tool with that agentId. If availability=busy, this cancels its previous task and starts a new task in the same child session, preserving its history. Forward user steering to the affected child promptly; an acknowledgement alone does not update its work. Leave unrelated background work running. If availability=available, the same call continues the idle child. Calling a subagent without agentId starts a new agent session. Use task_cancel with its taskId to stop work without sending a replacement instruction.";+ "Agent messaging\nSubagent calls start durable background tasks and return immediately with a task receipt. After delegating, continue helping the user or end your turn. The task will notify you when it completes, fails, needs input, or sends an update; completion and failure notifications include the task's result. Agents you have already delegated to remain visible in the framework-authored `<agents>` conversation note. To steer delegated work, send the updated instruction to the original subagent tool with that agentId. If availability=busy, this steers its active turn at the next safe boundary, preserving the same taskId, child session, and pending approvals. Forward user steering to the affected child promptly; an acknowledgement alone does not update its work. Leave unrelated background work running. If availability=available, the same call continues the idle child. Calling a subagent without agentId starts a new agent session. Use task_cancel with its taskId to stop work without sending a replacement instruction.";/*** Input for composing the base authored instructions prompt for onediff --git a/packages/eve/src/runtime/task-input-response-route.test.ts b/packages/eve/src/runtime/task-input-response-route.test.tsindex 20ca5bb94..c38eeb26e 100644--- a/packages/eve/src/runtime/task-input-response-route.test.ts+++ b/packages/eve/src/runtime/task-input-response-route.test.ts@@ -1,51 +1,39 @@import { beforeEach, describe, expect, it, vi } from "vitest";-import { sessionInboxWire } from "#execution/wire/session-inbox-encoder.js";import type { RouteContext } from "#public/definitions/channel.js";import { handleTaskInputResponseRequest } from "#execution/task-input-response-route.js";const resumeHookMock = vi.fn();-const getHookByTokenMock = vi.fn();const DIGEST = "0123456789abcdef0123456789abcdef";const CAPABILITY_TOKEN = `eve:task-input:${DIGEST}`;const TARGET_TOKEN = `eve:eve:op:${DIGEST}`;const TARGET_HOOK = {- metadata: { sessionInboxWireVersion: 1 },+ metadata: { sessionId: "child-session" },runId: "child-session",token: TARGET_TOKEN,};vi.mock("#compiled/@workflow/core/runtime.js", () => ({- getHookByToken: (...args: unknown[]) => getHookByTokenMock(...args),resumeHook: (...args: unknown[]) => resumeHookMock(...args),}));describe("task input response capability", () => {beforeEach(() => {- getHookByTokenMock.mockReset();- getHookByTokenMock.mockResolvedValue(TARGET_HOOK);resumeHookMock.mockReset();});it("resumes only the addressed child input batch", async () => {- resumeHookMock.mockResolvedValue(undefined);+ resumeHookMock.mockResolvedValue(TARGET_HOOK);const response = await handleTaskInputResponseRequest(request({ inputResponses: [{ optionId: "approve", requestId: "req-1" }] }),context(CAPABILITY_TOKEN),);expect(response.status).toBe(202);- expect(getHookByTokenMock).toHaveBeenCalledWith(TARGET_TOKEN);- expect(resumeHookMock).toHaveBeenCalledWith(- TARGET_HOOK,- sessionInboxWire.encode(- {- kind: "send",- payload: { inputResponses: [{ optionId: "approve", requestId: "req-1" }] },- },- { version: 1 },- ),- );+ expect(resumeHookMock).toHaveBeenCalledWith(`eve:inbox:v1:${TARGET_TOKEN}`, {+ kind: "send",+ payload: { inputResponses: [{ optionId: "approve", requestId: "req-1" }] },+ });});it("rejects messages and empty response batches", async () => {diff --git a/packages/eve/src/shared/agent-definition.ts b/packages/eve/src/shared/agent-definition.tsindex 4acb31da7..4a106a27e 100644--- a/packages/eve/src/shared/agent-definition.ts+++ b/packages/eve/src/shared/agent-definition.ts@@ -145,10 +145,11 @@ export interface PublicAgentCompactionDefinition {*/export interface AgentLimitsDefinition {/**- * Maximum lifetime of one durable session, in milliseconds.+ * Session lifetime from creation or the latest ownership handoff, in milliseconds.*- * The deadline starts when the session is created and survives process- * restarts and redeployments. If it elapses during an active turn, eve lets+ * A successful deployment handoff or legacy-session import restarts the+ * original configured duration. Process restarts and failed or skipped+ * handoffs preserve the deadline. If it elapses during an active turn, eve lets* that turn settle before completing the session normally.** `false` disables the timeout.@@ -287,7 +288,8 @@ export interface AgentWorkflowDefinition {readonly modelCallsPerStep?: number;/*** How long the agent's run data is kept after the run finishes.- * Applied to both the session run and every turn run.+ * Applied to every run that owns the session, including successors created+ * by deployment handoff.** - `"default"`: same as omission. The Workflow SDK World decides.* On Vercel this follows your team's plan.diff --git a/packages/eve/src/subagents/adapter.test.ts b/packages/eve/src/subagents/adapter.test.tsindex c1d3f2d94..1c9e86392 100644--- a/packages/eve/src/subagents/adapter.test.ts+++ b/packages/eve/src/subagents/adapter.test.ts@@ -141,10 +141,10 @@ describe("SUBAGENT_ADAPTER authorization handlers", () => {});describe("SUBAGENT_ADAPTER input.requested handler", () => {- it("advertises the driver version from durable context, even when the adapter is newer", async () => {+ it("advertises the durable public session address", async () => {resumeHookMock.mockClear();const ctx = makeContext();- ctx.ctx.set(SessionInboxKey, { sessionId: "child-session", version: 1 });+ ctx.ctx.set(SessionInboxKey, { sessionId: "child-session" });await SUBAGENT_INPUT_REQUESTED({ requests: [sampleRequest()], sequence: 0, stepIndex: 0, turnId: "turn-1" },@@ -153,7 +153,7 @@ describe("SUBAGENT_ADAPTER input.requested handler", () => {expect(resumeHookMock).toHaveBeenCalledWith("parent-token",- expect.objectContaining({ childSessionInbox: { sessionId: "child-session", version: 1 } }),+ expect.objectContaining({ childSessionInbox: { sessionId: "child-session" } }),);});diff --git a/packages/eve/src/subagents/auth-proxy.integration.test.ts b/packages/eve/src/subagents/auth-proxy.integration.test.tsindex 88d050d00..6eee52777 100644--- a/packages/eve/src/subagents/auth-proxy.integration.test.ts+++ b/packages/eve/src/subagents/auth-proxy.integration.test.ts@@ -30,7 +30,7 @@ const authorizationAdapter: ChannelAdapter<AuthorizationAdapterContext> = {kind: "authorization-proxy-test","authorization.required"(data, ctx) {ctx.state.pendingName = data.name;- ctx.session.continuation?.rekey("auth-thread");+ ctx.session.continuation?.alias("auth-thread");},"authorization.completed"(data, ctx) {delete ctx.state.pendingName;@@ -143,7 +143,7 @@ describe("subagent authorization proxy", () => {const session = createSession(parentSessionId);const { ctx } = buildContext({ adapter: authorizationAdapter, sessionId: parentSessionId });const chunks: Uint8Array[] = [];- const parentWritable = createCapturingWritable(chunks);+ const sessionWritable = createCapturingWritable(chunks);const candidateEvent: SubagentAuthorizationEvent = {data: {candidateId: "candidate-1",@@ -172,13 +172,13 @@ describe("subagent authorization proxy", () => {ctx,durableSession: projectToDurableSession(session),hookPayload: authorizationPayload(candidateEvent),- parentWritable,+ sessionWritable,});await emitProxiedSubagentEvent({ctx,durableSession: projectToDurableSession(session),hookPayload: authorizationPayload(settledEvent),- parentWritable,+ sessionWritable,});expect(decodeEvent(chunks[0]!)).toMatchObject(candidateEvent);@@ -192,7 +192,7 @@ describe("subagent authorization proxy", () => {sessionId: parentSessionId,});const chunks: Uint8Array[] = [];- const parentWritable = createCapturingWritable(chunks);+ const sessionWritable = createCapturingWritable(chunks);const requiredEvent: SubagentAuthorizationEvent = {data: {authorization: {@@ -214,7 +214,7 @@ describe("subagent authorization proxy", () => {ctx,durableSession: projectToDurableSession(session),hookPayload: authorizationPayload(requiredEvent),- parentWritable,+ sessionWritable,});expect(required.sessionState.continuationToken).toBe("http:auth-thread");@@ -237,9 +237,9 @@ describe("subagent authorization proxy", () => {};const completed = await emitProxiedSubagentEvent({ctx: rehydrateContext({ bundle, serializedContext: required.serializedContext }),- durableSession: required.sessionState.snapshot!.session,+ durableSession: required.sessionState.snapshot.session,hookPayload: authorizationPayload(completedEvent),- parentWritable,+ sessionWritable,});expect(completed.serializedContext[ChannelKey.name]).toEqual({diff --git a/packages/eve/src/subagents/event-proxy-step.ts b/packages/eve/src/subagents/event-proxy-step.tsindex 0f0b6f798..09cacf020 100644--- a/packages/eve/src/subagents/event-proxy-step.ts+++ b/packages/eve/src/subagents/event-proxy-step.ts@@ -48,13 +48,13 @@ interface ProxySubagentEventResult {export async function runProxySubagentEventStep(input: {readonly answerHook?: AnswerHookRoute;readonly hookPayload: SubagentEventHookPayload;- readonly parentWritable: WritableStream<Uint8Array>;+ readonly sessionWritable: WritableStream<Uint8Array>;readonly serializedContext: Record<string, unknown>;readonly sessionState: DurableSessionState;}): Promise<ProxySubagentEventResult> {"use step";- const durableSession = await readDurableSession(input.sessionState);+ const durableSession = readDurableSession(input.sessionState);const ctx = await deserializeContext(input.serializedContext);return emitProxiedSubagentEvent({@@ -62,20 +62,20 @@ export async function runProxySubagentEventStep(input: {ctx,durableSession,hookPayload: input.hookPayload,- parentWritable: input.parentWritable,+ sessionWritable: input.sessionWritable,});}/** Emits a task request whose proxy routes were committed by a prior step. */export async function emitRecordedTaskInputRequestStep(input: {readonly request: TaskInputRequestDelivery;- readonly parentWritable: WritableStream<Uint8Array>;+ readonly sessionWritable: WritableStream<Uint8Array>;readonly serializedContext: Record<string, unknown>;readonly sessionState: DurableSessionState;}): Promise<ProxySubagentEventResult> {"use step";- const durableSession = await readDurableSession(input.sessionState);+ const durableSession = readDurableSession(input.sessionState);const ctx = await deserializeContext(input.serializedContext);return await emitProxiedSubagentEvent({ctx,@@ -93,7 +93,7 @@ export async function emitRecordedTaskInputRequestStep(input: {kind: "subagent-input-request",subagentName: input.request.taskId,},- parentWritable: input.parentWritable,+ sessionWritable: input.sessionWritable,recordProxyInputRequests: false,});}@@ -104,7 +104,7 @@ export async function emitProxiedSubagentEvent(input: {readonly ctx: ContextContainer;readonly durableSession: DurableSession;readonly hookPayload: SubagentEventHookPayload;- readonly parentWritable: WritableStream<Uint8Array>;+ readonly sessionWritable: WritableStream<Uint8Array>;readonly recordProxyInputRequests?: boolean;}): Promise<ProxySubagentEventResult> {const { ctx } = input;@@ -119,7 +119,7 @@ export async function emitProxiedSubagentEvent(input: {turnAgent: effectiveAgent.turnAgent,});const adapterCtx = buildAdapterContext(adapter, ctx);- const writer = input.parentWritable.getWriter();+ const writer = input.sessionWritable.getWriter();let proxyEntries: ProxyInputRequestEntries | undefined;let scopedSession: HarnessSession;diff --git a/packages/eve/src/subagents/handle-dispatch.test.ts b/packages/eve/src/subagents/handle-dispatch.test.tsnew file mode 100644index 000000000..a66cf6ea6--- /dev/null+++ b/packages/eve/src/subagents/handle-dispatch.test.ts@@ -0,0 +1,121 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { createWorkflowRuntime } from "#execution/workflow-runtime.js";+import { dispatchToClaimedAgentAddress } from "./handle-dispatch.js";+import { continueRemoteAgentSession, resolveRemoteAgentForAction } from "./remote-dispatch.js";++vi.mock("#execution/workflow-runtime.js", () => ({ createWorkflowRuntime: vi.fn() }));+vi.mock("#subagents/remote-dispatch.js", async (importOriginal) => ({+ ...(await importOriginal()),+ continueRemoteAgentSession: vi.fn(),+ resolveRemoteAgentForAction: vi.fn(),+}));++describe("claimed child delivery", () => {+ const dispatchSession = vi.fn();+ const input = {+ action: {+ callId: "update-call",+ description: "Research",+ input: { message: "Use Alice's updated requirements" },+ kind: "subagent-call",+ name: "research",+ nodeId: "subagents/research",+ subagentName: "research",+ },+ auth: null,+ bundle: { compiledArtifactsSource: {} } as never,+ currentSession: {+ agent: { dynamicModel: true, system: "", tools: [] },+ compaction: { recentWindowSize: 5, threshold: 10_000 },+ continuationToken: "parent-token",+ history: [],+ sessionId: "parent",+ },+ handle: {+ address: { kind: "agent/local", sessionId: "child", continuationToken: "child-token" },+ identity: { id: "agent", name: "research", nodeId: "subagents/research" },+ operationId: "original-operation",+ callId: "original-call",+ ownerId: "original-task",+ phase: "claimed",+ },+ reply: { kind: "steer" },+ } satisfies Parameters<typeof dispatchToClaimedAgentAddress>[0];++ beforeEach(() => {+ vi.clearAllMocks();+ dispatchSession.mockResolvedValue({ status: "accepted" });+ vi.mocked(createWorkflowRuntime).mockReturnValue({ dispatchSession } as never);+ });++ it("steers without replacing the active turn's caller", async () => {+ await expect(dispatchToClaimedAgentAddress(input)).resolves.toMatchObject({ kind: "called" });+ expect(dispatchSession).toHaveBeenCalledExactlyOnceWith({+ sessionId: "child",+ command: {+ auth: null,+ caller: undefined,+ kind: "send",+ payload: { message: "Use Alice's updated requirements", outputSchema: undefined },+ },+ });+ });++ it("supplies a new caller when continuing an idle child", async () => {+ await dispatchToClaimedAgentAddress({+ ...input,+ reply: { kind: "reply", parentToken: "reply-token", taskId: "new-task" },+ });+ expect(dispatchSession).toHaveBeenCalledWith(+ expect.objectContaining({+ command: expect.objectContaining({+ caller: {+ callId: "update-call",+ replyTo: { kind: "hook", token: "reply-token" },+ subagentName: "research",+ taskId: "new-task",+ },+ }),+ }),+ );+ });++ it("reports a missing child without starting a replacement", async () => {+ dispatchSession.mockResolvedValueOnce({ status: "session_not_active" });+ await expect(dispatchToClaimedAgentAddress(input)).resolves.toMatchObject({+ kind: "error",+ deliveryPermanent: true,+ });+ expect(dispatchSession).toHaveBeenCalledTimes(1);+ });++ it("steers a remote child without replacing its callback", async () => {+ vi.mocked(resolveRemoteAgentForAction).mockReturnValue({ name: "research" } as never);+ const remoteInput = {+ ...input,+ action: { ...input.action, kind: "remote-agent-call" as const, remoteAgentName: "research" },+ bundle: { subagentRegistry: { subagentsByNodeId: new Map() } } as never,+ handle: {+ ...input.handle,+ address: {+ kind: "agent/remote" as const,+ sessionId: "remote-child",+ url: "https://child.example",+ callbackBaseUrl: "https://parent.example",+ },+ },+ };+ await expect(dispatchToClaimedAgentAddress(remoteInput)).resolves.toMatchObject({+ kind: "called",+ });+ expect(continueRemoteAgentSession).toHaveBeenCalledExactlyOnceWith({+ auth: null,+ callback: undefined,+ message: "Use Alice's updated requirements",+ outputSchema: undefined,+ remote: { name: "research", url: "https://child.example" },+ sessionId: "remote-child",+ });+ expect(dispatchSession).not.toHaveBeenCalled();+ });+});diff --git a/packages/eve/src/subagents/handle-dispatch.ts b/packages/eve/src/subagents/handle-dispatch.tsindex f1949d57f..431afdac3 100644--- a/packages/eve/src/subagents/handle-dispatch.ts+++ b/packages/eve/src/subagents/handle-dispatch.ts@@ -71,6 +71,14 @@ export type DispatchOutcome =readonly session: RuntimeSession;};+/**+ * Where the callee reports its result. A new turn replies to the caller's+ * hook; steering an active turn keeps that turn's original reply target.+ */+export type AgentReplyTarget =+ | { readonly kind: "reply"; readonly parentToken: string; readonly taskId?: string }+ | { readonly kind: "steer" };+/** Delivers a continuation after the session handle store atomically claimed it for one owner. */export async function dispatchToClaimedAgentAddress(input: {readonly activityObserver?: ActivityObserverConfig;@@ -78,23 +86,8 @@ export async function dispatchToClaimedAgentAddress(input: {readonly auth: SessionAuthContext | null;readonly bundle: CompiledBundle;readonly currentSession: RuntimeSession;- readonly parentToken: string;readonly handle: Extract<TaskOwnedAgentHandle, { phase: "claimed" }>;- readonly taskId?: string;-}): Promise<DispatchOutcome> {- return await dispatchToAgentAddress(input);-}--/** Delivers a continuation to an already-claimed local or remote agent address. */-async function dispatchToAgentAddress(input: {- readonly activityObserver?: ActivityObserverConfig;- readonly action: RuntimeAgentHandleAction;- readonly auth: SessionAuthContext | null;- readonly bundle: CompiledBundle;- readonly currentSession: RuntimeSession;- readonly parentToken: string;- readonly handle: { readonly address: AgentAddress; readonly identity: AgentIdentity };- readonly taskId?: string;+ readonly reply: AgentReplyTarget;}): Promise<DispatchOutcome> {const { action, handle } = input;const agentId = handle.identity.id;@@ -106,8 +99,7 @@ async function dispatchToAgentAddress(input: {auth: input.auth,bundle: input.bundle,identity: handle.identity,- parentToken: input.parentToken,- taskId: input.taskId,+ reply: input.reply,});if (!delivery.ok) {const { cause, permanent } = delivery.error;@@ -160,15 +152,18 @@ async function deliverToAgentAddress(input: {readonly auth: SessionAuthContext | null;readonly bundle: CompiledBundle;readonly identity: AgentIdentity;- readonly parentToken: string;- readonly taskId?: string;+ readonly reply: AgentReplyTarget;}): Promise<Result<void,{ readonly cause: unknown; readonly deliveryAmbiguous: boolean; readonly permanent: boolean }>> {- const { action, address, bundle, identity } = input;+ const { action, address, bundle, identity, reply } = input;+ const taskId =+ reply.kind === "reply"+ ? (reply.taskId ?? readTaskIdFromInboxToken(reply.parentToken))+ : undefined;if (address.kind === "agent/remote") {let resolvedRemote;@@ -187,16 +182,19 @@ async function deliverToAgentAddress(input: {await continueRemoteAgentSession({activityObserver: input.activityObserver,auth: input.auth,- callback: {- callId: action.callId,- subagentName: identity.name,- taskId: input.taskId ?? readTaskIdFromInboxToken(input.parentToken),- token: input.parentToken,- url: createWorkflowCallbackUrl(- address.callbackBaseUrl,- createEveCallbackRoutePath(input.parentToken),- ),- },+ callback:+ reply.kind === "steer"+ ? undefined+ : {+ callId: action.callId,+ subagentName: identity.name,+ taskId,+ token: reply.parentToken,+ url: createWorkflowCallbackUrl(+ address.callbackBaseUrl,+ createEveCallbackRoutePath(reply.parentToken),+ ),+ },message: readSubagentMessage(action),outputSchema: normalizeRequestedOutputSchema(action.input.outputSchema),remote: { ...resolvedRemote, url: address.url },@@ -220,13 +218,16 @@ async function deliverToAgentAddress(input: {const result = await childRuntime.dispatchSession({command: {auth: input.auth,- caller: {- activityObserver: input.activityObserver,- callId: action.callId,- replyTo: { kind: "hook", token: input.parentToken },- subagentName: identity.name,- taskId: input.taskId ?? readTaskIdFromInboxToken(input.parentToken),- },+ caller:+ reply.kind === "steer"+ ? undefined+ : {+ activityObserver: input.activityObserver,+ callId: action.callId,+ replyTo: { kind: "hook", token: reply.parentToken },+ subagentName: identity.name,+ taskId,+ },kind: "send",payload: {message: readSubagentMessage(action),diff --git a/packages/eve/src/subagents/handles/operation-id.ts b/packages/eve/src/subagents/handles/operation-id.tsindex 580225bc8..98f91119e 100644--- a/packages/eve/src/subagents/handles/operation-id.ts+++ b/packages/eve/src/subagents/handles/operation-id.ts@@ -6,7 +6,7 @@ import { createHash } from "node:crypto";* the same call produces the same operation.** Lives apart from the handle store because it needs `node:crypto`: the- * store module is bundled into the workflow driver body (which rejects+ * store module is bundled into the session owner body (which rejects* Node.js builtins), while operation ids are only ever minted inside* dispatch steps.*/diff --git a/packages/eve/src/subagents/handles/query.test.ts b/packages/eve/src/subagents/handles/query.test.tsdeleted file mode 100644index a018a9705..000000000--- a/packages/eve/src/subagents/handles/query.test.ts+++ /dev/null@@ -1,50 +0,0 @@-import { describe, expect, it } from "vitest";--import { mergeTaskOwnedAgentHandlesIntoTurnState } from "#subagents/handles/query.js";-import { AGENT_HANDLES_STATE_KEY, type AgentHandle } from "#subagents/handles/store.js";--const address = {- continuationToken: "child-token",- kind: "agent/local" as const,- sessionId: "child-session",-};-const identity = { id: "agent-1", name: "research", nodeId: "subagents/research" };-const available: AgentHandle = { address, identity, phase: "available" };-const claimed: AgentHandle = {- address,- callId: "call-1",- identity,- operationId: "operation-1",- ownerId: "workflow-run-1",- phase: "claimed",-};--describe("mergeTaskOwnedAgentHandlesIntoTurnState", () => {- it("preserves a blocking workflow run's claim when the driver did not change the handle", () => {- const baseState = {- [AGENT_HANDLES_STATE_KEY]: {- handles: [{ phase: "available", identity: { ...identity }, address: { ...address } }],- },- };-- expect(- mergeTaskOwnedAgentHandlesIntoTurnState({- baseState,- driverState: baseState,- turnState: { [AGENT_HANDLES_STATE_KEY]: { handles: [claimed] } },- }),- ).toEqual({ [AGENT_HANDLES_STATE_KEY]: { handles: [claimed] } });- });-- it("rejects conflicting owner mutations from the driver and turn", () => {- const taskClaim: AgentHandle = { ...claimed, ownerId: "task_1" };-- expect(() =>- mergeTaskOwnedAgentHandlesIntoTurnState({- baseState: { [AGENT_HANDLES_STATE_KEY]: { handles: [available] } },- driverState: { [AGENT_HANDLES_STATE_KEY]: { handles: [taskClaim] } },- turnState: { [AGENT_HANDLES_STATE_KEY]: { handles: [claimed] } },- }),- ).toThrow("changed ownership while its turn was running");- });-});diff --git a/packages/eve/src/subagents/handles/query.ts b/packages/eve/src/subagents/handles/query.tsindex 9e0dd98bf..bcb028cd6 100644--- a/packages/eve/src/subagents/handles/query.ts+++ b/packages/eve/src/subagents/handles/query.ts@@ -1,10 +1,6 @@import type { RuntimeActionResult, RuntimeSubagentChildResult } from "#shared/action-types.js";import { AGENT_HANDLES_STATE_KEY } from "#subagents/handles/state-key.js";-import type {- AgentHandle,- AgentHandleStore,- TurnOwnedAgentHandle,-} from "#subagents/handles/store.js";+import type { AgentHandle, TurnOwnedAgentHandle } from "#subagents/handles/store.js";import type { SessionStateMap } from "#harness/types.js";/** A handle with one outstanding operation and a confirmed child address. */@@ -14,8 +10,8 @@ export type RunningAgentHandle = Extract<TurnOwnedAgentHandle, { phase: "running* Schema-free read of the agent handles from session state.** Trust boundary: every source store was validated by a handle transition.- * Driver-side reads trust that invariant instead of re-validating, so the- * workflow driver bundle stays free of compiled zod.+ * Owner-side reads trust that invariant instead of re-validating, so the+ * session owner bundle stays free of compiled zod.*/function readAgentHandles(state: SessionStateMap | undefined): readonly AgentHandle[] {const raw = state?.[AGENT_HANDLES_STATE_KEY];@@ -26,75 +22,6 @@ function readAgentHandles(state: SessionStateMap | undefined): readonly AgentHanreturn Array.isArray(handles) ? (handles as readonly AgentHandle[]) : [];}-/** Preserves driver-owned task leases when a concurrent turn returns an older snapshot. */-export function mergeTaskOwnedAgentHandlesIntoTurnState(input: {- readonly baseState: SessionStateMap | undefined;- readonly driverState: SessionStateMap | undefined;- readonly turnState: SessionStateMap | undefined;-}): SessionStateMap | undefined {- const baseHandles = new Map(- readAgentHandles(input.baseState).map((handle) => [handle.identity.id, handle] as const),- );- const driverHandles = new Map(- readAgentHandles(input.driverState).map((handle) => [handle.identity.id, handle] as const),- );- const mutatedIds = new Set([...baseHandles.keys(), ...driverHandles.keys()]);- for (const id of mutatedIds) {- if (handlesEqual(baseHandles.get(id), driverHandles.get(id))) mutatedIds.delete(id);- }- if (mutatedIds.size === 0) return input.turnState;-- const merged: AgentHandle[] = [];- for (const handle of readAgentHandles(input.turnState)) {- if (!mutatedIds.has(handle.identity.id)) {- merged.push(handle);- continue;- }- const current = driverHandles.get(handle.identity.id);- const base = baseHandles.get(handle.identity.id);- if (!handlesEqual(handle, base) && !handlesEqual(handle, current)) {- throw new Error(- `Agent handle "${handle.identity.id}" changed ownership while its turn was running.`,- );- }- if (current !== undefined) merged.push(current);- mutatedIds.delete(handle.identity.id);- }- for (const id of mutatedIds) {- const current = driverHandles.get(id);- if (current !== undefined) merged.push(current);- }-- return {- ...input.turnState,- [AGENT_HANDLES_STATE_KEY]: { handles: merged } satisfies AgentHandleStore,- };-}--function handlesEqual(left: AgentHandle | undefined, right: AgentHandle | undefined): boolean {- if (left === right) return true;- if (left === undefined || right === undefined) return false;- const leftKeys = Object.keys(left);- const rightKeys = Object.keys(right);- return (- leftKeys.length === rightKeys.length &&- leftKeys.every((key) => valuesEqual(Reflect.get(left, key), Reflect.get(right, key)))- );-}--function valuesEqual(left: unknown, right: unknown): boolean {- if (left === right) return true;- if (typeof left !== "object" || left === null || typeof right !== "object" || right === null) {- return false;- }- const leftKeys = Object.keys(left);- const rightKeys = Object.keys(right);- return (- leftKeys.length === rightKeys.length &&- leftKeys.every((key) => valuesEqual(Reflect.get(left, key), Reflect.get(right, key)))- );-}-/*** Finds the running agent handle a child-produced result must settle: the* handle whose recorded operation carries the result's callId.diff --git a/packages/eve/src/subagents/handles/rebase.ts b/packages/eve/src/subagents/handles/rebase.tsdeleted file mode 100644index da4763865..000000000--- a/packages/eve/src/subagents/handles/rebase.ts+++ /dev/null@@ -1,34 +0,0 @@-import type { DurableSessionState } from "#execution/durable-session-store.js";-import type { TurnDriverAction } from "#execution/turn-control-receiver.js";-import { mergeTaskOwnedAgentHandlesIntoTurnState } from "#subagents/handles/query.js";--/** Preserves handle leases accepted by the driver against a turn's older snapshot. */-export function rebaseTaskAgentHandleMutations(- action: TurnDriverAction,- driverState: DurableSessionState,- baseState: DurableSessionState,-): TurnDriverAction {- const snapshot = action.sessionState.snapshot;- if (snapshot === undefined) {- throw new Error(- "Cannot merge task-owned agent handles into a session state without a snapshot.",- );- }- return {- ...action,- sessionState: {- ...action.sessionState,- snapshot: {- ...snapshot,- session: {- ...snapshot.session,- state: mergeTaskOwnedAgentHandlesIntoTurnState({- baseState: baseState.snapshot?.session.state,- driverState: driverState.snapshot?.session.state,- turnState: snapshot.session.state,- }),- },- },- },- };-}diff --git a/packages/eve/src/subagents/handles/state-key.ts b/packages/eve/src/subagents/handles/state-key.tsindex 62a41e006..b769570a4 100644--- a/packages/eve/src/subagents/handles/state-key.ts+++ b/packages/eve/src/subagents/handles/state-key.ts@@ -1,7 +1,7 @@/*** Session-state key for delegated agent handles.*- * Lives apart from the store so schema-free readers (the workflow driver's+ * Lives apart from the store so schema-free readers (the session owner's* handle query) can import the key without pulling the zod-backed store* module into their bundle.*/diff --git a/packages/eve/src/subagents/handles/store.test.ts b/packages/eve/src/subagents/handles/store.test.tsindex fabd14e37..450712350 100644--- a/packages/eve/src/subagents/handles/store.test.ts+++ b/packages/eve/src/subagents/handles/store.test.ts@@ -76,7 +76,6 @@ describe("getAgentHandleStore", () => {null,{ handles: "not-an-array" },{ handles: [{ phase: "starting" }] },- { extra: true, handles: [] },{handles: [{diff --git a/packages/eve/src/subagents/handles/store.ts b/packages/eve/src/subagents/handles/store.tsindex 448b11373..75b2aab02 100644--- a/packages/eve/src/subagents/handles/store.ts+++ b/packages/eve/src/subagents/handles/store.ts@@ -208,20 +208,20 @@ export type AgentHandleStoreCommandResult =const nonEmptyString = z.string().min(1);-const identitySchema = z.strictObject({+const identitySchema = z.looseObject({id: nonEmptyString,name: nonEmptyString,nodeId: nonEmptyString,});-const startOperationSchema = z.strictObject({+const startOperationSchema = z.looseObject({callId: nonEmptyString,id: nonEmptyString,kind: z.literal("start"),parentTurnId: nonEmptyString,});-const continueOperationSchema = z.strictObject({+const continueOperationSchema = z.looseObject({callId: nonEmptyString,id: nonEmptyString,kind: z.literal("continue"),@@ -230,30 +230,30 @@ const continueOperationSchema = z.strictObject({});const startTargetSchema: z.ZodType<AgentStartTarget> = z.discriminatedUnion("kind", [- z.strictObject({ continuationToken: nonEmptyString, kind: z.literal("agent/local") }),- z.strictObject({ continuationToken: nonEmptyString, kind: z.literal("agent/self") }),- z.strictObject({+ z.looseObject({ continuationToken: nonEmptyString, kind: z.literal("agent/local") }),+ z.looseObject({ continuationToken: nonEmptyString, kind: z.literal("agent/self") }),+ z.looseObject({callbackBaseUrl: z.url(),- credentialResolver: z.strictObject({ resolverId: nonEmptyString.optional() }).optional(),+ credentialResolver: z.looseObject({ resolverId: nonEmptyString.optional() }).optional(),kind: z.literal("agent/remote"),url: z.url(),}),]);const addressSchema: z.ZodType<AgentAddress> = z.discriminatedUnion("kind", [- z.strictObject({+ z.looseObject({continuationToken: nonEmptyString,kind: z.literal("agent/local"),sessionId: nonEmptyString,}),- z.strictObject({+ z.looseObject({continuationToken: nonEmptyString,kind: z.literal("agent/self"),sessionId: nonEmptyString,}),- z.strictObject({+ z.looseObject({callbackBaseUrl: z.url(),- credentialResolver: z.strictObject({ resolverId: nonEmptyString.optional() }).optional(),+ credentialResolver: z.looseObject({ resolverId: nonEmptyString.optional() }).optional(),kind: z.literal("agent/remote"),sessionId: nonEmptyString,url: z.url(),@@ -296,19 +296,19 @@ const agentHandleStoreCommandSchema: z.ZodType<AgentHandleStoreCommand> = z.disc);const turnOwnedAgentHandleSchema: z.ZodType<TurnOwnedAgentHandle> = z.discriminatedUnion("phase", [- z.strictObject({+ z.looseObject({identity: identitySchema,operation: startOperationSchema,phase: z.literal("starting"),target: startTargetSchema,}),- z.strictObject({+ z.looseObject({address: addressSchema,identity: identitySchema,operation: z.discriminatedUnion("kind", [startOperationSchema, continueOperationSchema]),phase: z.literal("running"),}),- z.strictObject({+ z.looseObject({address: addressSchema,identity: identitySchema,lastStatus: z.string().max(MAX_STATUS_LENGTH),@@ -317,14 +317,14 @@ const turnOwnedAgentHandleSchema: z.ZodType<TurnOwnedAgentHandle> = z.discrimina]);const taskOwnedAgentHandleSchema: z.ZodType<TaskOwnedAgentHandle> = z.discriminatedUnion("phase", [- z.strictObject({+ z.looseObject({callId: nonEmptyString.optional(),identity: identitySchema,operationId: nonEmptyString,phase: z.literal("reserved"),ownerId: nonEmptyString,}),- z.strictObject({+ z.looseObject({address: addressSchema,callId: nonEmptyString.optional(),identity: identitySchema,@@ -332,7 +332,7 @@ const taskOwnedAgentHandleSchema: z.ZodType<TaskOwnedAgentHandle> = z.discriminaphase: z.literal("claimed"),ownerId: nonEmptyString,}),- z.strictObject({+ z.looseObject({address: addressSchema,identity: identitySchema,phase: z.literal("available"),@@ -345,7 +345,7 @@ const agentHandleSchema: z.ZodType<AgentHandle> = z.union([]);const agentHandleStoreSchema: z.ZodType<AgentHandleStore> = z- .strictObject({+ .looseObject({handles: z.array(agentHandleSchema),}).refine(@@ -369,7 +369,7 @@ export function formatAgentStatus(output: unknown): string {* Validates one agent handle store about to be persisted, returning the* parsed value. Throws instead of writing an invalid store: transitions run* this on every write, which is the invariant that lets the schema-free- * driver-side reader (`query.ts`) trust stored values without revalidating.+ * owner-side reader (`query.ts`) trust stored values without revalidating.*/export function assertPersistableAgentHandleStore(store: AgentHandleStore): AgentHandleStore {const parsed = agentHandleStoreSchema.safeParse(store);diff --git a/packages/eve/src/subagents/hitl-proxy.test.ts b/packages/eve/src/subagents/hitl-proxy.test.tsindex 8f87de34e..25127cdb3 100644--- a/packages/eve/src/subagents/hitl-proxy.test.ts+++ b/packages/eve/src/subagents/hitl-proxy.test.ts@@ -27,7 +27,7 @@ describe("routeDeliverPayload", () => {"req-a",{childContinuationToken: "child-alias",- childSessionInbox: { sessionId: "child-a", version: 1 },+ childSessionInbox: { sessionId: "child-a" },kind: "question",},],@@ -35,7 +35,7 @@ describe("routeDeliverPayload", () => {"req-b",{childContinuationToken: "child-alias",- childSessionInbox: { sessionId: "child-b", version: 1 },+ childSessionInbox: { sessionId: "child-b" },kind: "question",},],@@ -57,12 +57,12 @@ describe("routeDeliverPayload", () => {expect(routed.forChildren).toMatchObject([{childContinuationToken: "child-alias",- childSessionInbox: { sessionId: "child-a", version: 1 },+ childSessionInbox: { sessionId: "child-a" },payload: { inputResponses: [{ requestId: "req-a", text: "A" }] },},{childContinuationToken: "child-alias",- childSessionInbox: { sessionId: "child-b", version: 1 },+ childSessionInbox: { sessionId: "child-b" },payload: { inputResponses: [{ requestId: "req-b", text: "B" }] },},]);diff --git a/packages/eve/src/subagents/hitl-proxy.ts b/packages/eve/src/subagents/hitl-proxy.tsindex 9cd3db194..3c48b9e32 100644--- a/packages/eve/src/subagents/hitl-proxy.ts+++ b/packages/eve/src/subagents/hitl-proxy.ts@@ -1,4 +1,4 @@-import type { SessionInboxAddress } from "#execution/wire/session-inbox-contract.js";+import type { SessionInboxAddress } from "#execution/session-inbox/address.js";import type { DeliverPayload, SubagentInputRequestHookPayload } from "#channel/types.js";import {emitTurnEpilogue,diff --git a/packages/eve/src/subagents/parent-notification.test.ts b/packages/eve/src/subagents/parent-notification.test.tsindex e044d4f9d..3be6096d2 100644--- a/packages/eve/src/subagents/parent-notification.test.ts+++ b/packages/eve/src/subagents/parent-notification.test.ts@@ -313,10 +313,10 @@ describe("turn caller notification", () => {},lifecycle: "terminal",sessionId: "child-session",- settled: { isError: true, output: new Error("driver crashed") },+ settled: { isError: true, output: new Error("session owner crashed") },});- const error = { code: "SUBAGENT_EXECUTION_FAILED", message: "driver crashed" };+ const error = { code: "SUBAGENT_EXECUTION_FAILED", message: "session owner crashed" };expect(resumeHookMock).toHaveBeenCalledWith("parent-turn-3", {kind: "runtime-action-result",results: [diff --git a/packages/eve/src/subagents/parent-notification.ts b/packages/eve/src/subagents/parent-notification.tsindex ba59f03f3..a185bc9ef 100644--- a/packages/eve/src/subagents/parent-notification.ts+++ b/packages/eve/src/subagents/parent-notification.ts@@ -28,7 +28,7 @@ import { readTaskIdFromInboxToken } from "#tasks/task-inbox-token.js";const log = createLogger("execution.delegated-parent-notification");/**- * Resumes the parent driver's hook with a delegated subagent result.+ * Resumes the parent owner's hook with a delegated subagent result.* No-op for root sessions.** `usage` — the completed child's session-total token spend — is@@ -76,7 +76,7 @@ export async function notifyDelegatedParentStep(input: {});}-/** Settled turn payload forwarded from the driver to the caller. */+/** Settled turn payload forwarded from the owner to the caller. */export interface SettledTurnNotification {readonly output: unknown;readonly isError?: boolean;diff --git a/packages/eve/src/subagents/parent-result.ts b/packages/eve/src/subagents/parent-result.tsindex fd9695964..01ddd2edf 100644--- a/packages/eve/src/subagents/parent-result.ts+++ b/packages/eve/src/subagents/parent-result.ts@@ -1,6 +1,6 @@/*** Pure helpers that project a delegated subagent's terminal output- * into the runtime-action result shape its parent driver expects.+ * into the runtime-action result shape its parent owner expects.* Lives in its own (non-directive) file to escape the workflow* step-proxy transform.*/diff --git a/packages/eve/src/subagents/remote-dispatch.ts b/packages/eve/src/subagents/remote-dispatch.tsindex 34e2bd536..a55e111f6 100644--- a/packages/eve/src/subagents/remote-dispatch.ts+++ b/packages/eve/src/subagents/remote-dispatch.ts@@ -219,7 +219,7 @@ export async function continueRemoteAgentSession(input: {readonly activityObserver?: ActivityObserverConfig;/** The dispatching turn's session principal, forwarded when `remote.forwardPrincipal` is set. */readonly auth: SessionAuthContext | null;- readonly callback: {+ readonly callback?: {readonly callId: string;readonly subagentName: string;readonly taskId?: string;diff --git a/packages/eve/src/subagents/start-local.ts b/packages/eve/src/subagents/start-local.tsindex ad8a0a88b..9e9e79206 100644--- a/packages/eve/src/subagents/start-local.ts+++ b/packages/eve/src/subagents/start-local.ts@@ -1,3 +1,4 @@+import { sessionInboxHookToken } from "#execution/session-inbox/address.js";import type { DispatchOutcome, RuntimeSession } from "#subagents/handle-dispatch.js";import { ContextContainer, contextStorage } from "#context/container.js";import type { LocalDevRequestProvenance } from "#context/keys.js";@@ -68,7 +69,8 @@ export async function startLocalSubagent(input: {await contextStorage.run(new ContextContainer({ localDevRequest: input.localDevRequest }), () =>childRuntime.createSession(runInput),);- childSessionId = (await waitForCommandHookOwner(childContinuationToken)).runId;+ childSessionId = (await waitForCommandHookOwner(sessionInboxHookToken(childContinuationToken)))+ .runId;} catch (error) {logError(log, "local subagent start failed", error, {callId: action.callId,diff --git a/packages/eve/src/tasks/session-index.ts b/packages/eve/src/tasks/session-index.tsindex fb6112a4a..a7845e186 100644--- a/packages/eve/src/tasks/session-index.ts+++ b/packages/eve/src/tasks/session-index.ts@@ -95,10 +95,12 @@ const sessionTaskDispatchContextSchema = z.union([]);const taskViewBaseShape = {+ // Terminal views never carry pending requests; the loose object must say so explicitly.+ inputRequests: z.never().optional(),executor: z- .strictObject({+ .looseObject({binding: z- .strictObject({+ .looseObject({data: z.record(z.string(), z.custom<JsonValue>()),kind: z.string().min(1),})@@ -108,9 +110,10 @@ const taskViewBaseShape = {metadata: taskMetadataSchema,taskId: z.string().min(1),usage: z- .strictObject({+ .looseObject({cacheReadTokens: z.number().nonnegative(),cacheWriteTokens: z.number().nonnegative(),+ costUsd: z.number().finite().nonnegative().optional(),inputTokens: z.number().nonnegative(),outputTokens: z.number().nonnegative(),})@@ -120,24 +123,32 @@ const taskViewBaseShape = {/*** Terminal views only, on purpose: the index caches a view solely as* the expired-run fallback, and the discriminated arms encode the terminal- * status/output invariants structurally (strict objects reject- * `inputRequests` and mismatched outputs).+ * status/output invariants structurally (explicit fields reject+ * `inputRequests` and mismatched outputs while preserving additive metadata).*/const taskViewSchema: z.ZodType<TaskView> = z.discriminatedUnion("status", [- z.strictObject({+ z.looseObject({...taskViewBaseShape,- lastOutput: z.strictObject({ data: z.custom<JsonValue>(), type: z.literal("result") }),+ lastOutput: z.looseObject({ data: z.custom<JsonValue>(), type: z.literal("result") }),status: z.literal("completed"),}),- z.strictObject({+ z.looseObject({...taskViewBaseShape,- lastOutput: z.strictObject({ data: z.custom<JsonValue>(), type: z.literal("error") }),+ lastOutput: z.looseObject({ data: z.custom<JsonValue>(), type: z.literal("error") }),status: z.literal("failed"),}),- z.strictObject({ ...taskViewBaseShape, status: z.literal("cancelled") }),+ z.looseObject({+ ...taskViewBaseShape,+ lastOutput: z.never().optional(),+ status: z.literal("cancelled"),+ }),]);-const storedSessionTaskIndexEntrySchema = z.strictObject({+type StoredSessionTaskIndexEntry = Omit<SessionTaskIndexEntry, "dispatchContext"> & {+ readonly dispatchContext?: SessionTaskDispatchContext;+};++const storedSessionTaskIndexEntrySchema: z.ZodType<StoredSessionTaskIndexEntry> = z.looseObject({activityWorkIdentity: z.custom<ActivityWorkIdentityV1>((value) => parseActivityWorkIdentityV1(value) !== undefined).optional(),@@ -147,7 +158,7 @@ const storedSessionTaskIndexEntrySchema = z.strictObject({cohortId: z.string().min(1).optional(),dispatchContext: sessionTaskDispatchContextSchema.optional(),executor: z- .strictObject({+ .looseObject({data: z.record(z.string(), z.custom<JsonValue>()),kind: z.string().min(1),})@@ -159,7 +170,7 @@ const storedSessionTaskIndexEntrySchema = z.strictObject({});const sessionTaskIndexSchema = z- .strictObject({+ .looseObject({tasks: z.array(storedSessionTaskIndexEntrySchema),version: z.literal(SESSION_TASKS_STATE_VERSION),})@@ -181,6 +192,7 @@ const sessionTaskIndexSchema = z);interface SessionTaskIndex {+ readonly [key: string]: unknown;readonly tasks: readonly SessionTaskIndexEntry[];readonly version: typeof SESSION_TASKS_STATE_VERSION;}@@ -194,9 +206,13 @@ interface SessionTaskIndex {export function getSessionTaskIndex(state: SessionStateMap | undefined,): readonly SessionTaskIndexEntry[] {+ return readSessionTaskIndex(state).tasks;+}++function readSessionTaskIndex(state: SessionStateMap | undefined): SessionTaskIndex {const raw = state?.[SESSION_TASKS_STATE_KEY];if (raw === undefined) {- return [];+ return { tasks: [], version: SESSION_TASKS_STATE_VERSION };}const version = typeof raw === "object" && raw !== null ? Reflect.get(raw, "version") : undefined;if (version !== SESSION_TASKS_STATE_VERSION) {@@ -210,10 +226,13 @@ export function getSessionTaskIndex(`Corrupt task index under session state key "${SESSION_TASKS_STATE_KEY}": ${parsed.error.message}`,);}- return parsed.data.tasks.map((entry): SessionTaskIndexEntry => ({- ...entry,- dispatchContext: entry.dispatchContext ?? LEGACY_TASK_AGENT_DISPATCH_CONTEXT,- }));+ return {+ ...parsed.data,+ tasks: parsed.data.tasks.map((entry): SessionTaskIndexEntry => ({+ ...entry,+ dispatchContext: entry.dispatchContext ?? LEGACY_TASK_AGENT_DISPATCH_CONTEXT,+ })),+ };}/** Caches one terminal view beside its task-run address. */@@ -224,17 +243,48 @@ export function cacheTerminalTaskView(if (!isValidTerminalView(view)) {throw new Error(`Cannot cache invalid terminal task "${view.taskId}".`);}- const entries = getSessionTaskIndex(state);+ const stored = readSessionTaskIndex(state);+ const entries = stored.tasks;const index = entries.findIndex((entry) => entry.taskId === view.taskId);if (index < 0) return state;if (!sameTaskMetadata(entries[index]!.metadata, view.metadata)) {throw new Error(`Task view metadata does not match index entry "${view.taskId}".`);}const tasks = [...entries];- tasks[index] = { ...tasks[index]!, terminalView: view };+ const previous = tasks[index]!.terminalView;+ tasks[index] = {+ ...tasks[index]!,+ terminalView: taskViewSchema.parse({+ ...previous,+ ...view,+ metadata: { ...previous?.metadata, ...view.metadata },+ lastOutput:+ view.lastOutput === undefined+ ? undefined+ : {+ ...previous?.lastOutput,+ ...view.lastOutput,+ },+ usage: view.usage === undefined ? undefined : { ...previous?.usage, ...view.usage },+ executor:+ view.executor === undefined+ ? undefined+ : {+ ...previous?.executor,+ ...view.executor,+ binding:+ view.executor.binding === undefined+ ? undefined+ : {+ ...previous?.executor?.binding,+ ...view.executor.binding,+ },+ },+ }),+ };return {...state,- [SESSION_TASKS_STATE_KEY]: { tasks, version: SESSION_TASKS_STATE_VERSION },+ [SESSION_TASKS_STATE_KEY]: { ...stored, tasks },};}@@ -270,12 +320,26 @@ export function recordSessionTask(session: HarnessSession,entry: Omit<SessionTaskIndexEntry, "cohortId">,): HarnessSession {- const tasks = [...getSessionTaskIndex(session.state)];+ const stored = readSessionTaskIndex(session.state);+ const tasks = [...stored.tasks];const index = tasks.findIndex((candidate) => candidate.taskId === entry.taskId);const previous = tasks[index];if (previous !== undefined) {tasks[index] = {+ ...previous,...entry,+ metadata: { ...previous.metadata, ...entry.metadata },+ activityWorkIdentity:+ entry.activityWorkIdentity === undefined+ ? previous.activityWorkIdentity+ : {+ ...previous.activityWorkIdentity,+ ...entry.activityWorkIdentity,+ },+ executor:+ entry.executor === undefined+ ? previous.executor+ : { ...previous.executor, ...entry.executor },cohortId: previous.cohortId,createdByStepIndex: previous.createdByStepIndex,createdByTurnId: previous.createdByTurnId,@@ -294,6 +358,7 @@ export function recordSessionTask(state: {...session.state,[SESSION_TASKS_STATE_KEY]: {+ ...stored,tasks,version: SESSION_TASKS_STATE_VERSION,} satisfies SessionTaskIndex,diff --git a/packages/eve/src/tasks/types.ts b/packages/eve/src/tasks/types.tsindex 49516de44..9995fa0ea 100644--- a/packages/eve/src/tasks/types.ts+++ b/packages/eve/src/tasks/types.ts@@ -3,7 +3,7 @@ import type {SubagentAuthorizationEventHookPayload,} from "#channel/types.js";import type { WorkflowToolAgentRequest } from "#execution/tools/workflow/messages.js";-import type { SessionInboxAddress } from "#execution/wire/session-inbox-contract.js";+import type { SessionInboxAddress } from "#execution/session-inbox/address.js";import { jsonValuesEqual, type JsonValue } from "#shared/json.js";import type { TaskExecutorBinding } from "#tools/task.js";diff --git a/packages/eve/test/scenarios/bundle-module-evaluation.scenario.test.ts b/packages/eve/test/scenarios/bundle-module-evaluation.scenario.test.tsindex 608e947b2..f67a837cc 100644--- a/packages/eve/test/scenarios/bundle-module-evaluation.scenario.test.ts+++ b/packages/eve/test/scenarios/bundle-module-evaluation.scenario.test.ts@@ -75,9 +75,9 @@ describe("eve dist single-chunk module evaluation", () => {"src/internal/workflow/builtins.ts","src/subagents/callback-step.ts","src/subagents/adapter.ts",- "src/execution/turn-workflow.ts",- "src/execution/workflow-entry.ts",- "src/execution/workflow-steps.ts",+ "src/execution/session/turn.ts",+ "src/execution/session/entry.ts",+ "src/execution/session/turn-step.ts",].map((relative) => resolvePackageSourceFilePath(relative));const entryFile = join(scratch, "entry.mjs");diff --git a/packages/eve/test/scenarios/dynamic-tool-cold-replay.scenario.test.ts b/packages/eve/test/scenarios/dynamic-tool-cold-replay.scenario.test.tsindex a26e6046c..fd377c1c9 100644--- a/packages/eve/test/scenarios/dynamic-tool-cold-replay.scenario.test.ts+++ b/packages/eve/test/scenarios/dynamic-tool-cold-replay.scenario.test.ts@@ -129,7 +129,6 @@ describe("dynamic tool cold replay", () => {async () => {const app = await scenarioApp(DYNAMIC_TOOL_COLD_REPLAY_DESCRIPTOR);const pinnedEnv = {- VERCEL_DEPLOYMENT_ID: "dynamic-tool-cold-replay",WORKFLOW_INLINE_OWNERSHIP_LEASE_SECONDS: "1",};let server = await startEveDev(app.appRoot, { env: pinnedEnv });diff --git a/packages/eve/test/scenarios/dynamic-tool-source-edit.scenario.test.ts b/packages/eve/test/scenarios/dynamic-tool-source-edit.scenario.test.tsindex 283d4ef69..c281e2ac7 100644--- a/packages/eve/test/scenarios/dynamic-tool-source-edit.scenario.test.ts+++ b/packages/eve/test/scenarios/dynamic-tool-source-edit.scenario.test.ts@@ -91,11 +91,10 @@ async function readExecuteMarker(appRoot: string, key: string): Promise<ExecuteMdescribe("dynamic tool source edits across a restart", () => {it(- "replays parked approvals against the latest code under the same tool identity",+ "keeps parked approvals on their owning generation under the same tool identity",async () => {const app = await scenarioApp(EDITABLE_DYNAMIC_DESCRIPTOR);const pinnedEnv = {- VERCEL_DEPLOYMENT_ID: "dynamic-tool-source-edit",WORKFLOW_INLINE_OWNERSHIP_LEASE_SECONDS: "1",};let server = await startEveDev(app.appRoot, { env: pinnedEnv });@@ -150,12 +149,13 @@ describe("dynamic tool source edits across a restart", () => {).result();expect(resumed.status).toBe("waiting");- // Each parked call must run its own tool — never the other one — and- // both must run the edited body from the latest code.+ // Pending approvals make the session ineligible for deployment+ // handoff. Each parked call must run its own tool — never the other+ // one — using the generation that created the approval.const alpha = await readExecuteMarker(app.appRoot, "alpha");const beta = await readExecuteMarker(app.appRoot, "beta");- expect(alpha).toMatchObject({ build: 2, key: "alpha", version: "v1" });- expect(beta).toMatchObject({ build: 2, key: "beta", version: "v1" });+ expect(alpha).toMatchObject({ build: 1, key: "alpha", version: "v1" });+ expect(beta).toMatchObject({ build: 1, key: "beta", version: "v1" });expect(alpha.pid).toBe(beta.pid);} finally {await server.stop();diff --git a/packages/eve/test/tui-client/tui-queue-steer.ts b/packages/eve/test/tui-client/tui-queue-steer.tsindex d0049b123..a152a7d6f 100644--- a/packages/eve/test/tui-client/tui-queue-steer.ts+++ b/packages/eve/test/tui-client/tui-queue-steer.ts@@ -13,10 +13,9 @@ import { theme } from "./lib/theme.ts";** 1. Start a long turn, then submit two messages while it streams —* both must land in the pinned `↑ Queue n/5` panel, not the turn.- * 2. Ctrl+C pops the oldest queued message: the panel flips to Steering,- * the running turn settles as `turn.cancelled` → `session.waiting`- * (cooperative — the session keeps its context), and the popped- * message runs as the replacement turn.+ * 2. Ctrl+C pops the oldest queued message and submits it for steering;+ * the popped message joins the running turn at its next committed+ * boundary without cancelling the model or tool work already in flight.* 3. The remaining queued message auto-drains as the following turn.* 4. The steered echo carries the `↑` provenance arrow above its bar,* the queued one below, and the runner returns to an idle prompt.@@ -65,10 +64,9 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {await screen.waitForText("Queue 2/5", 10_000);console.log(theme.muted("[tui-queue-steer] two messages queued behind the running turn"));- // Ctrl+C pops the oldest message and cooperatively cancels the running turn.+ // Admission can clear the transient Steering label before the next render.+ // The echoed message, answer, and provenance arrow prove accepted steering.input.ctrlC();- await screen.waitForText("Steering", 10_000);- console.log(theme.muted("[tui-queue-steer] steering engaged, cancelling the turn"));await waitForTwice(screen, STEER_TOKEN, 120_000, "steered turn echo + reply");console.log(theme.muted("[tui-queue-steer] steered message answered"));diff --git a/research/session-inbox-wire-schema.md b/research/session-inbox-wire-schema.mdindex f657af0f7..2ad85761a 100644--- a/research/session-inbox-wire-schema.md+++ b/research/session-inbox-wire-schema.md@@ -1,11 +1,15 @@---issue: https://github.com/vercel/eve/issues/1765-status: proposed-last_updated: "2026-09-04"+status: superseded+last_updated: "2026-09-11"---# Versioned wire schema for the session inbox+Superseded by [single-workflow sessions](./single-workflow-session-upgrades.md).+The implementation uses one inbox protocol with no negotiation or migration chain.+The proposal below records the previous deployment model, not current guidance.+## PurposePayloads resumed into session inbox hooks outlive the deployment that wrotediff --git a/research/session-network-hops.html b/research/session-network-hops.htmlnew file mode 100644index 000000000..d9e7168f3--- /dev/null+++ b/research/session-network-hops.html@@ -0,0 +1,709 @@+<!doctype html>+<html lang="en">+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>eve · Session network hops</title>+ <style>+ :root {+ color-scheme: light dark;+ font-family: ui-sans-serif, system-ui, sans-serif;+ background: #111;+ color: #eee;+ }+ body {+ max-width: 1250px;+ margin: auto;+ padding: 44px 28px;+ }+ h1 {+ font-size: 36px;+ letter-spacing: -1.5px;+ margin: 12px 0;+ }+ h2 {+ font-size: 19px;+ margin-top: 32px;+ }+ p {+ max-width: 930px;+ line-height: 1.6;+ color: #aaa;+ }+ code {+ font-family: ui-monospace, monospace;+ font-size: 12px;+ }+ header > small {+ color: #76d7ca;+ letter-spacing: 2px;+ }+ nav {+ position: sticky;+ top: 0;+ background: #111e;+ padding: 16px 0;+ display: flex;+ gap: 18px;+ align-items: center;+ flex-wrap: wrap;+ border-bottom: 1px solid #333;+ }+ select,+ button {+ background: #222;+ color: #eee;+ border: 1px solid #555;+ border-radius: 6px;+ padding: 9px;+ }+ label {+ font-size: 13px;+ }+ .cards {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 14px;+ margin: 25px 0;+ }+ .card {+ border: 1px solid #333;+ border-radius: 10px;+ padding: 20px;+ }+ .card strong {+ display: block;+ font-size: 20px;+ margin-bottom: 8px;+ }+ .card span {+ color: #aaa;+ font-size: 13px;+ }+ #chain {+ background: #192724;+ padding: 18px;+ border-radius: 8px;+ line-height: 1.9;+ font-size: 14px;+ }+ table {+ width: 100%;+ border-collapse: collapse;+ margin-top: 16px;+ font-size: 13px;+ }+ th {+ text-align: left;+ color: #aaa;+ font-weight: 500;+ }+ td,+ th {+ border-bottom: 1px solid #303030;+ padding: 15px 12px;+ vertical-align: top;+ }+ td:first-child {+ width: 27%;+ }+ td:nth-child(2) {+ width: 24%;+ color: #b5d9d3;+ }+ summary {+ cursor: pointer;+ line-height: 1.5;+ }+ details p {+ margin: 10px 0;+ font-size: 13px;+ }+ small.lane {+ display: block;+ color: #999;+ margin-top: 7px;+ }+ .response {+ color: #cbb0ff;+ }+ .background {+ color: #d8be84;+ }+ .observer {+ color: #97c3e8;+ }+ .conditional {+ color: #aaa;+ }+ footer {+ margin-top: 35px;+ border-top: 1px solid #333;+ padding-top: 16px;+ }+ li {+ color: #bbb;+ line-height: 1.7;+ }+ a {+ color: #76d7ca;+ }+ @media (max-width: 700px) {+ body {+ padding: 20px 12px;+ }+ .cards {+ grid-template-columns: 1fr;+ }+ td,+ th {+ padding: 12px 5px;+ }+ h1 {+ font-size: 29px;+ }+ }+ @media print {+ nav,+ button {+ display: none;+ }+ body {+ background: white;+ color: black;+ }+ details {+ display: block;+ }+ }+ </style>+ <header>+ <small>eve / RUNTIME AUDIT / 2026-09-11</small>+ <h1>One inbox. Resume first.</h1>+ <p>+ The path from a request to the first model call, with post-acceptance identity resolution and+ optional infrastructure shown separately. This is a source-derived map, not measured latency.+ </p>+ </header>+ <div class="cards">+ <div class="card">+ <strong>1 eve inbox + aliases</strong+ ><span+ >Also 1 SDK cancellation hook per new turn. No eager authorization, workflow-reply, or+ anchor hook.</span+ >+ </div>+ <div class="card">+ <strong>0 eve send preflights</strong+ ><span+ >The SDK still looks up the token inside resumeHook. Known-session sends never hydrate hook+ metadata.</span+ >+ </div>+ <div class="card">+ <strong>3 separate clocks</strong+ ><span+ >First model request · dispatch response · visible turn settlement. These are not+ interchangeable.</span+ >+ </div>+ </div>+ <nav>+ <label+ >Path+ <select id="mode">+ <option value="stable">Existing session ID</option>+ <option value="alias">Existing continuation alias</option>+ <option value="new">New session</option>+ <option value="handoff">Idle deployment handoff</option>+ </select></label+ >+ <label+ ><input id="extra" type="checkbox" checked /> Show response, observer, and conditional+ work</label+ ><button id="download">Download hop data</button><button id="print">Print</button>+ </nav>+ <h2>Critical dependency chain</h2>+ <div id="chain"></div>+ <p>+ Rows are logical operations, not a single serial waterfall. Startup claims are concurrent; timer+ startup overlaps the first turn. Cold replay, retained-VM execution, SDK preloads, and+ stream-key caches change the physical requests. Expand a row for its justification and source.+ </p>+ <table>+ <thead>+ <tr>+ <th>Operation</th>+ <th>Network work / durable operations</th>+ <th>Why it exists</th>+ </tr>+ </thead>+ <tbody id="rows"></tbody>+ </table>+ <h2>Identity and the remaining SDK boundary</h2>+ <p>+ <code>sessionId = anchorRunId</code> identifies the original stream-owning run.+ <code>hook.runId = ownerRunId</code> identifies the current executor. Hook metadata stores only+ <code>{ sessionId }</code>. Reading metadata is explicit and lazy, after resume acceptance. A+ random named stream still needs its owning run ID.+ </p>+ <h2>What this map does not claim</h2>+ <ul id="limits"></ul>+ <footer>+ <p id="version"></p>+ <p>+ The earlier Downloads map describes the holder architecture. This map has no child turn+ workflow or per-turn snapshot-stream round trip. Its companion JSON is the same data embedded+ here.+ </p>+ </footer>+ <script id="data" type="application/json">+ {+ "title": "eve session network hops",+ "captured": "2026-09-11",+ "baseCommit": "adb6beff622b274970d4e48b7178b7d44c11d456",+ "workingTree": true,+ "sdk": "@workflow/core 5.0.0-beta.50",+ "evidence": "Source-derived operation inventory, not a latency benchmark. World, cache, replay, payload size, and authored integrations change request counts.",+ "clocks": [+ "HTTP request to first provider request",+ "HTTP request to dispatch acceptance / returned Session identity",+ "HTTP request to visible turn settlement"+ ],+ "invariants": {+ "sessionId": "original stream-owning run ID",+ "ownerRunId": "current executor; changes on handoff",+ "metadata": "{ sessionId }, accessed only when requested after resumption",+ "startupHooks": "1 eve stable inbox + requested aliases + 1 SDK cancellation hook for the first turn"+ },+ "limitations": [+ "Alias-only delivery cannot distinguish an unowned address from a handoff gap. Atomic handoff is an upstream requirement.",+ "Rows name SDK operations, not a guaranteed count of lower-level HTTP retries or queue deliveries.",+ "Authorization, sandbox, memory, telemetry and authored hooks must be measured for a specific deployed agent."+ ],+ "rows": [+ {+ "id": "ingress",+ "title": "HTTP request + request authorization",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "critical",+ "operations": "1 HTTP request; auth-dependent I/O",+ "why": "Authenticate and authorize the resource before delivery. Auth provider/cache costs are application dependent.",+ "source": {+ "path": "packages/eve/src/channel/channel-address.ts",+ "symbol": "createChannelAddress"+ }+ },+ {+ "id": "lookup",+ "title": "SDK hook lookup",+ "modes": ["stable", "alias", "handoff"],+ "lane": "critical",+ "operations": "1 hooks.getByToken",+ "why": "resumeHook(token, command) resolves the live hook and its resume context. No eve preflight; no metadata hydration.",+ "source": {+ "path": "packages/eve/node_modules/@workflow/core/dist/runtime/resume-hook.js",+ "symbol": "async function resumeHookImpl"+ }+ },+ {+ "id": "missing",+ "title": "Try alias before creating",+ "modes": ["new"],+ "lane": "conditional",+ "operations": "0 for ID-only; 1 hooks.getByToken for an unowned alias",+ "why": "An ID-only create goes straight to start. A missing channel alias starts a candidate immediately; an ambiguous failure does not.",+ "source": {+ "path": "packages/eve/src/channel/channel-address.ts",+ "symbol": "const existing = await dispatch()"+ }+ },+ {+ "id": "key",+ "title": "Resume payload encryption",+ "modes": ["stable", "alias", "handoff"],+ "lane": "conditional",+ "operations": "0 with stored public key; key/run reads on SDK fallback",+ "why": "Current hooks carry resume context. Sealing to the public key is local; this is distinct from decrypting metadata.",+ "source": {+ "path": "packages/eve/node_modules/@workflow/core/dist/runtime/resume-hook.js",+ "symbol": "async function resolveHookEncryptionKey"+ }+ },+ {+ "id": "receive",+ "title": "Durably accept payload",+ "modes": ["stable", "alias", "handoff"],+ "lane": "critical",+ "operations": "1 hook_received event write",+ "why": "Commit the command before publishing its wake. Backend retry/dedup capabilities control transport retries.",+ "source": {+ "path": "packages/eve/node_modules/@workflow/core/dist/runtime/resume-hook.js",+ "symbol": "async function resumeHookImpl"+ }+ },+ {+ "id": "wake",+ "title": "Publish owner wake",+ "modes": ["stable", "alias", "handoff"],+ "lane": "critical",+ "operations": "1 queue publish",+ "why": "Targets the current owner on its pinned deployment; acceptance requires the durable write and publish.",+ "source": {+ "path": "packages/eve/node_modules/@workflow/core/dist/runtime/resume-hook.js",+ "symbol": "async function resumeHookImpl"+ }+ },+ {+ "id": "identity",+ "title": "Return stable identity to alias caller",+ "modes": ["alias", "handoff"],+ "lane": "response",+ "operations": "0 hook reads; lazy metadata key access as needed",+ "why": "Runs AFTER resume acceptance, concurrent with the awakened workflow. Known session addresses and forwarding-only senders do not access metadata.",+ "source": {+ "path": "packages/eve/src/execution/session-inbox/resume.ts",+ "symbol": "get sessionId()"+ }+ },+ {+ "id": "start",+ "title": "Start original session workflow",+ "modes": ["new"],+ "lane": "critical",+ "operations": "run_created + queue publish",+ "why": "One session workflow, no child turn workflow. SDK start may overlap publication and persistence.",+ "source": {+ "path": "packages/eve/src/execution/workflow-runtime.ts",+ "symbol": "async createSession"+ }+ },+ {+ "id": "activation",+ "title": "Workflow activation / event history",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "critical",+ "operations": "run lifecycle writes + history reads, capability/replay dependent",+ "why": "Queue delivery is a compute hop, not an extra producer HTTP call. Retained VM and preload paths differ from cold replay.",+ "source": {+ "path": "packages/eve/node_modules/@workflow/core/dist/runtime/suspension-handler.js",+ "symbol": "handleSuspension"+ }+ },+ {+ "id": "claims",+ "title": "Register stable inbox and initial alias",+ "modes": ["new"],+ "lane": "critical",+ "operations": "1 hook_created per address; one concurrent claim batch",+ "why": "One stable address, plus the requested alias. getConflict is a registration fence preventing duplicate first-turn execution, not hooks.getByToken.",+ "source": {+ "path": "packages/eve/src/execution/session/entry.ts",+ "symbol": "const [sessionCreation"+ }+ },+ {+ "id": "state",+ "title": "Initialize or restore session state",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "critical",+ "operations": "new: createSessionStep lifecycle; existing: inline snapshot hydration",+ "why": "New-session initialization overlaps address claiming. Current snapshots are carried in durable step results, not fetched from a per-turn snapshot stream.",+ "source": {+ "path": "packages/eve/src/execution/create-session-step.ts",+ "symbol": "async function createSessionStep"+ }+ },+ {+ "id": "handoff-check",+ "title": "Check idle handoff eligibility",+ "modes": ["handoff"],+ "lane": "critical",+ "operations": "isSessionIdleForHandoffStep lifecycle",+ "why": "Only a fresh delivery to an idle session can trigger transfer. Same-deployment and busy sessions do not run this step.",+ "source": {+ "path": "packages/eve/src/execution/session/handoff.ts",+ "symbol": "async checkpoint"+ }+ },+ {+ "id": "anchor",+ "title": "Register terminal anchor, first handoff only",+ "modes": ["handoff"],+ "lane": "critical",+ "operations": "1 hook_created on original owner's first attempt",+ "why": "Keeps the original run and its public stream alive after its execution ownership transfers.",+ "source": {+ "path": "packages/eve/src/execution/session/entry.ts",+ "symbol": "const ensureAnchor"+ }+ },+ {+ "id": "release",+ "title": "Release owned addresses and drain accepted reads",+ "modes": ["handoff"],+ "lane": "critical",+ "operations": "1 hook_disposed per address",+ "why": "If another accepted command is found, reclaim and abandon handoff. Release and claim are not atomic.",+ "source": {+ "path": "packages/eve/src/execution/session-inbox/inbox.ts",+ "symbol": "async release()"+ }+ },+ {+ "id": "successor",+ "title": "Register activation callback and start successor",+ "modes": ["handoff"],+ "lane": "critical",+ "operations": "activation hook_created + startSessionOwnerStep lifecycle + run_created + publish",+ "why": "Activation callback is registered before starting a run that can signal it. Successor receives explicit anchorRunId, snapshot, address set, and configured timeout duration. Successful activation restarts that duration.",+ "source": {+ "path": "packages/eve/src/execution/session/handoff.ts",+ "symbol": "async start"+ }+ },+ {+ "id": "reclaim",+ "title": "Validate and claim transferred addresses",+ "modes": ["handoff"],+ "lane": "critical",+ "operations": "validation step lifecycle + 1 hook_created per address, batched",+ "why": "No model work until all claims succeed. Preserves stable identity and uses the original stream writer.",+ "source": {+ "path": "packages/eve/src/execution/session/entry.ts",+ "symbol": "await validateSessionCheckpointStep"+ }+ },+ {+ "id": "ack",+ "title": "Acknowledge successor activation",+ "modes": ["handoff"],+ "lane": "critical",+ "operations": "signalSessionOwnerActivationStep + resume lookup/write/publish",+ "why": "Old owner can now exit or park as anchor. Later owners signal the anchor only at session end.",+ "source": {+ "path": "packages/eve/src/execution/session/handoff-steps.ts",+ "symbol": "signalSessionOwnerActivationStep"+ }+ },+ {+ "id": "timeout",+ "title": "Start deadline workflow concurrently",+ "modes": ["new", "handoff"],+ "lane": "background",+ "operations": "startSessionTimeoutStep + timer run_created/publish/lifecycle + durable wait scheduling",+ "why": "Default deadline infrastructure. Does not block the first model call; startup operations are joined before the session loop advances.",+ "source": {+ "path": "packages/eve/src/execution/session/entry.ts",+ "symbol": "const initialTurn"+ }+ },+ {+ "id": "abort",+ "title": "SDK cancellation hook and abort stream",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "critical",+ "operations": "1 abrt_* hook_created for the new turn; abort stream read",+ "why": "AbortSignal transport is required for cancelling active durable steps. No eve getConflict call and no steering abort.",+ "source": {+ "path": "packages/eve/node_modules/@workflow/core/dist/serialization.js",+ "symbol": "function reduceAbortWithListener"+ }+ },+ {+ "id": "step",+ "title": "Execute turnStep",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "critical",+ "operations": "step_started; step_created/queue delivery when not inline",+ "why": "SDK may execute inline or queue a step. Registration awaiters affect inline eligibility; do not equate a step call with exactly one network request.",+ "source": {+ "path": "packages/eve/node_modules/@workflow/core/dist/runtime/suspension-handler.js",+ "symbol": "const lazyInlineCorrelationIds"+ }+ },+ {+ "id": "prepare",+ "title": "Rehydrate context, deliver message, prepare model",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "critical",+ "operations": "local work + authored hooks/connections/sandbox I/O",+ "why": "No universal count: authored integrations, dynamic model selection, memory, sandbox, and tracing can add work before the provider call.",+ "source": {+ "path": "packages/eve/src/execution/session/turn-step.ts",+ "symbol": "async function turnStep"+ }+ },+ {+ "id": "writer",+ "title": "Resolve stream writer encryption/routing",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "conditional",+ "operations": "run/key reads depending on writable serialization and caches",+ "why": "Original owner uses getWritable(); a successor uses the anchor run's forwarded writable. Stream names are run-scoped.",+ "source": {+ "path": "packages/eve/node_modules/@workflow/core/dist/runtime/run.js",+ "symbol": "getWritable(options"+ }+ },+ {+ "id": "preamble",+ "title": "Publish pre-model events",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "critical",+ "operations": "stream write batches; batch count is variable",+ "why": "Lifecycle events and authored handlers can be awaited before the model call. Count actual stream batches, not individual events.",+ "source": {+ "path": "packages/eve/src/execution/session/turn-step.ts",+ "symbol": "await emitTurnPreamble"+ }+ },+ {+ "id": "model",+ "title": "MODEL REQUEST — stop time-to-model clock",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "critical",+ "operations": "1 provider request for this first call",+ "why": "Provider response latency is outside time-to-model. Subsequent tool/model cycles have their own costs.",+ "source": {+ "path": "packages/eve/src/execution/session/turn-step.ts",+ "symbol": "await runModelCallBatch"+ }+ },+ {+ "id": "settle",+ "title": "Commit results, admit steering, settle turn",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "completion",+ "operations": "step_completed + optional next step + settleTurnStep + stream batches",+ "why": "Steering uses the same turn after a committed boundary; queue waits for settlement. No child turn run or owner-release handshake per ordinary turn.",+ "source": {+ "path": "packages/eve/src/execution/session/turn.ts",+ "symbol": "async runTurn"+ }+ },+ {+ "id": "read",+ "title": "Client stream observer",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "observer",+ "operations": "stream GET + read-key resolution as needed; tail-info only when requested",+ "why": "Separate clock/branch. An already-open stream is not a new request per chunk. Reconnects target the original run.",+ "source": {+ "path": "packages/eve/src/execution/workflow-runtime.ts",+ "symbol": "async getEventStream"+ }+ },+ {+ "id": "activity",+ "title": "Optional channel activity collector",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "conditional",+ "operations": "new root collector start; hook + activity resume/write/publish batches",+ "why": "Only channels with activity renderers. Collector startup can precede session start; separate from the ordinary ID-only path.",+ "source": {+ "path": "packages/eve/src/execution/workflow-runtime.ts",+ "symbol": "let collectorRunId"+ }+ },+ {+ "id": "reset",+ "title": "Explicit reset release acknowledgement",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "conditional",+ "operations": "bounded hooks.getByToken polling after reset acceptance",+ "why": "Not an ordinary send cost. Confirms the previous owner released the stable address before reset returns.",+ "source": {+ "path": "packages/eve/src/execution/workflow-runtime.ts",+ "symbol": "async function waitForCommandHookRelease"+ }+ },+ {+ "id": "resolve",+ "title": "Explicit resolveSession()",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "conditional",+ "operations": "1 hooks.getByToken + lazy metadata hydration",+ "why": "Requested read-only identity resolution. Never used as a send preflight.",+ "source": {+ "path": "packages/eve/src/execution/workflow-runtime.ts",+ "symbol": "async resolveContinuation"+ }+ },+ {+ "id": "task-owner",+ "title": "Background task ownership resolution",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "conditional",+ "operations": "bounded hooks.getByToken polling inside durable work",+ "why": "Not the ordinary turn path. Reads runId only; no metadata hydration.",+ "source": {+ "path": "packages/eve/src/execution/workflow-runtime.ts",+ "symbol": "async function waitForCommandHookOwner"+ }+ }+ ]+ }+ </script>+ <script>+ const data = JSON.parse(document.querySelector("#data").textContent);+ const chains = {+ stable:+ "Request authorization → resumeHook: lookup → durable hook_received → queue wake → owner activation/replay → turnStep → preparation + stream events → MODEL REQUEST",+ alias:+ "Request authorization → resumeHook: lookup → durable hook_received → queue wake → owner activation/replay → turnStep → MODEL REQUEST. Parallel response branch after wake: metadata → stable session ID.",+ new: "Request authorization → [channel only: failed resume] → start owner → [session initialization ∥ stable + alias claims] → [first turn ∥ timer startup] → preparation + stream events → MODEL REQUEST",+ handoff:+ "Resume existing owner → detect idle deployment change → ensure anchor → release addresses → activation hook + successor start → validate checkpoint + batch claims → signal activation → [first turn ∥ timer startup] → MODEL REQUEST",+ };+ const make = (tag, text) => {+ const element = document.createElement(tag);+ if (text !== undefined) element.textContent = text;+ return element;+ };+ function render() {+ const mode = document.querySelector("#mode").value;+ const extra = document.querySelector("#extra").checked;+ document.querySelector("#chain").textContent = chains[mode];+ const body = document.querySelector("#rows");+ body.replaceChildren();+ for (const row of data.rows.filter(+ (row) => row.modes.includes(mode) && (extra || row.lane === "critical"),+ )) {+ const tr = make("tr");+ const title = make("td", row.title);+ const lane = make("small", row.lane);+ lane.className = "lane " + row.lane;+ title.append(lane);+ const detail = make("details");+ detail.append(make("summary", row.why));+ detail.append(make("p", row.source.path));+ detail.append(make("code", row.source.symbol));+ tr.append(title, make("td", row.operations), make("td"));+ tr.lastChild.append(detail);+ body.append(tr);+ }+ }+ for (const limit of data.limitations)+ document.querySelector("#limits").append(make("li", limit));+ document.querySelector("#version").textContent =+ data.sdk ++ " · Base " ++ data.baseCommit ++ " · Includes uncommitted implementation changes. " ++ data.evidence;+ document.querySelector("#mode").addEventListener("change", render);+ document.querySelector("#extra").addEventListener("change", render);+ document.querySelector("#print").addEventListener("click", () => window.print());+ document.querySelector("#download").addEventListener("click", () => {+ const url = URL.createObjectURL(+ new Blob([JSON.stringify(data, null, 2)], { type: "application/json" }),+ );+ const a = make("a");+ a.href = url;+ a.download = "session-network-hops.json";+ a.click();+ setTimeout(() => URL.revokeObjectURL(url), 0);+ });+ render();+ </script>+</html>diff --git a/research/session-network-hops.json b/research/session-network-hops.jsonnew file mode 100644index 000000000..41b9d0e6b--- /dev/null+++ b/research/session-network-hops.json@@ -0,0 +1,386 @@+{+ "title": "eve session network hops",+ "captured": "2026-09-11",+ "baseCommit": "adb6beff622b274970d4e48b7178b7d44c11d456",+ "workingTree": true,+ "sdk": "@workflow/core 5.0.0-beta.50",+ "evidence": "Source-derived operation inventory, not a latency benchmark. World, cache, replay, payload size, and authored integrations change request counts.",+ "clocks": [+ "HTTP request to first provider request",+ "HTTP request to dispatch acceptance / returned Session identity",+ "HTTP request to visible turn settlement"+ ],+ "invariants": {+ "sessionId": "original stream-owning run ID",+ "ownerRunId": "current executor; changes on handoff",+ "metadata": "{ sessionId }, accessed only when requested after resumption",+ "startupHooks": "1 eve stable inbox + requested aliases + 1 SDK cancellation hook for the first turn"+ },+ "limitations": [+ "Alias-only delivery cannot distinguish an unowned address from a handoff gap. Atomic handoff is an upstream requirement.",+ "Rows name SDK operations, not a guaranteed count of lower-level HTTP retries or queue deliveries.",+ "Authorization, sandbox, memory, telemetry and authored hooks must be measured for a specific deployed agent."+ ],+ "rows": [+ {+ "id": "ingress",+ "title": "HTTP request + request authorization",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "critical",+ "operations": "1 HTTP request; auth-dependent I/O",+ "why": "Authenticate and authorize the resource before delivery. Auth provider/cache costs are application dependent.",+ "source": {+ "path": "packages/eve/src/channel/channel-address.ts",+ "symbol": "createChannelAddress"+ }+ },+ {+ "id": "lookup",+ "title": "SDK hook lookup",+ "modes": ["stable", "alias", "handoff"],+ "lane": "critical",+ "operations": "1 hooks.getByToken",+ "why": "resumeHook(token, command) resolves the live hook and its resume context. No eve preflight; no metadata hydration.",+ "source": {+ "path": "packages/eve/node_modules/@workflow/core/dist/runtime/resume-hook.js",+ "symbol": "async function resumeHookImpl"+ }+ },+ {+ "id": "missing",+ "title": "Try alias before creating",+ "modes": ["new"],+ "lane": "conditional",+ "operations": "0 for ID-only; 1 hooks.getByToken for an unowned alias",+ "why": "An ID-only create goes straight to start. A missing channel alias starts a candidate immediately; an ambiguous failure does not.",+ "source": {+ "path": "packages/eve/src/channel/channel-address.ts",+ "symbol": "const existing = await dispatch()"+ }+ },+ {+ "id": "key",+ "title": "Resume payload encryption",+ "modes": ["stable", "alias", "handoff"],+ "lane": "conditional",+ "operations": "0 with stored public key; key/run reads on SDK fallback",+ "why": "Current hooks carry resume context. Sealing to the public key is local; this is distinct from decrypting metadata.",+ "source": {+ "path": "packages/eve/node_modules/@workflow/core/dist/runtime/resume-hook.js",+ "symbol": "async function resolveHookEncryptionKey"+ }+ },+ {+ "id": "receive",+ "title": "Durably accept payload",+ "modes": ["stable", "alias", "handoff"],+ "lane": "critical",+ "operations": "1 hook_received event write",+ "why": "Commit the command before publishing its wake. Backend retry/dedup capabilities control transport retries.",+ "source": {+ "path": "packages/eve/node_modules/@workflow/core/dist/runtime/resume-hook.js",+ "symbol": "async function resumeHookImpl"+ }+ },+ {+ "id": "wake",+ "title": "Publish owner wake",+ "modes": ["stable", "alias", "handoff"],+ "lane": "critical",+ "operations": "1 queue publish",+ "why": "Targets the current owner on its pinned deployment; acceptance requires the durable write and publish.",+ "source": {+ "path": "packages/eve/node_modules/@workflow/core/dist/runtime/resume-hook.js",+ "symbol": "async function resumeHookImpl"+ }+ },+ {+ "id": "identity",+ "title": "Return stable identity to alias caller",+ "modes": ["alias", "handoff"],+ "lane": "response",+ "operations": "0 hook reads; lazy metadata key access as needed",+ "why": "Runs AFTER resume acceptance, concurrent with the awakened workflow. Known session addresses and forwarding-only senders do not access metadata.",+ "source": {+ "path": "packages/eve/src/execution/session-inbox/resume.ts",+ "symbol": "get sessionId()"+ }+ },+ {+ "id": "start",+ "title": "Start original session workflow",+ "modes": ["new"],+ "lane": "critical",+ "operations": "run_created + queue publish",+ "why": "One session workflow, no child turn workflow. SDK start may overlap publication and persistence.",+ "source": {+ "path": "packages/eve/src/execution/workflow-runtime.ts",+ "symbol": "async createSession"+ }+ },+ {+ "id": "activation",+ "title": "Workflow activation / event history",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "critical",+ "operations": "run lifecycle writes + history reads, capability/replay dependent",+ "why": "Queue delivery is a compute hop, not an extra producer HTTP call. Retained VM and preload paths differ from cold replay.",+ "source": {+ "path": "packages/eve/node_modules/@workflow/core/dist/runtime/suspension-handler.js",+ "symbol": "handleSuspension"+ }+ },+ {+ "id": "claims",+ "title": "Register stable inbox and initial alias",+ "modes": ["new"],+ "lane": "critical",+ "operations": "1 hook_created per address; one concurrent claim batch",+ "why": "One stable address, plus the requested alias. getConflict is a registration fence preventing duplicate first-turn execution, not hooks.getByToken.",+ "source": {+ "path": "packages/eve/src/execution/session/entry.ts",+ "symbol": "const [sessionCreation"+ }+ },+ {+ "id": "state",+ "title": "Initialize or restore session state",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "critical",+ "operations": "new: createSessionStep lifecycle; existing: inline snapshot hydration",+ "why": "New-session initialization overlaps address claiming. Current snapshots are carried in durable step results, not fetched from a per-turn snapshot stream.",+ "source": {+ "path": "packages/eve/src/execution/create-session-step.ts",+ "symbol": "async function createSessionStep"+ }+ },+ {+ "id": "handoff-check",+ "title": "Check idle handoff eligibility",+ "modes": ["handoff"],+ "lane": "critical",+ "operations": "isSessionIdleForHandoffStep lifecycle",+ "why": "Only a fresh delivery to an idle session can trigger transfer. Same-deployment and busy sessions do not run this step.",+ "source": {+ "path": "packages/eve/src/execution/session/handoff.ts",+ "symbol": "async checkpoint"+ }+ },+ {+ "id": "anchor",+ "title": "Register terminal anchor, first handoff only",+ "modes": ["handoff"],+ "lane": "critical",+ "operations": "1 hook_created on original owner's first attempt",+ "why": "Keeps the original run and its public stream alive after its execution ownership transfers.",+ "source": {+ "path": "packages/eve/src/execution/session/entry.ts",+ "symbol": "const ensureAnchor"+ }+ },+ {+ "id": "release",+ "title": "Release owned addresses and drain accepted reads",+ "modes": ["handoff"],+ "lane": "critical",+ "operations": "1 hook_disposed per address",+ "why": "If another accepted command is found, reclaim and abandon handoff. Release and claim are not atomic.",+ "source": {+ "path": "packages/eve/src/execution/session-inbox/inbox.ts",+ "symbol": "async release()"+ }+ },+ {+ "id": "successor",+ "title": "Register activation callback and start successor",+ "modes": ["handoff"],+ "lane": "critical",+ "operations": "activation hook_created + startSessionOwnerStep lifecycle + run_created + publish",+ "why": "Activation callback is registered before starting a run that can signal it. Successor receives explicit anchorRunId, snapshot, address set, and configured timeout duration. Successful activation restarts that duration.",+ "source": {+ "path": "packages/eve/src/execution/session/handoff.ts",+ "symbol": "async start"+ }+ },+ {+ "id": "reclaim",+ "title": "Validate and claim transferred addresses",+ "modes": ["handoff"],+ "lane": "critical",+ "operations": "validation step lifecycle + 1 hook_created per address, batched",+ "why": "No model work until all claims succeed. Preserves stable identity and uses the original stream writer.",+ "source": {+ "path": "packages/eve/src/execution/session/entry.ts",+ "symbol": "await validateSessionCheckpointStep"+ }+ },+ {+ "id": "ack",+ "title": "Acknowledge successor activation",+ "modes": ["handoff"],+ "lane": "critical",+ "operations": "signalSessionOwnerActivationStep + resume lookup/write/publish",+ "why": "Old owner can now exit or park as anchor. Later owners signal the anchor only at session end.",+ "source": {+ "path": "packages/eve/src/execution/session/handoff-steps.ts",+ "symbol": "signalSessionOwnerActivationStep"+ }+ },+ {+ "id": "timeout",+ "title": "Start deadline workflow concurrently",+ "modes": ["new", "handoff"],+ "lane": "background",+ "operations": "startSessionTimeoutStep + timer run_created/publish/lifecycle + durable wait scheduling",+ "why": "Default deadline infrastructure. Does not block the first model call; startup operations are joined before the session loop advances.",+ "source": {+ "path": "packages/eve/src/execution/session/entry.ts",+ "symbol": "const initialTurn"+ }+ },+ {+ "id": "abort",+ "title": "SDK cancellation hook and abort stream",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "critical",+ "operations": "1 abrt_* hook_created for the new turn; abort stream read",+ "why": "AbortSignal transport is required for cancelling active durable steps. No eve getConflict call and no steering abort.",+ "source": {+ "path": "packages/eve/node_modules/@workflow/core/dist/serialization.js",+ "symbol": "function reduceAbortWithListener"+ }+ },+ {+ "id": "step",+ "title": "Execute turnStep",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "critical",+ "operations": "step_started; step_created/queue delivery when not inline",+ "why": "SDK may execute inline or queue a step. Registration awaiters affect inline eligibility; do not equate a step call with exactly one network request.",+ "source": {+ "path": "packages/eve/node_modules/@workflow/core/dist/runtime/suspension-handler.js",+ "symbol": "const lazyInlineCorrelationIds"+ }+ },+ {+ "id": "prepare",+ "title": "Rehydrate context, deliver message, prepare model",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "critical",+ "operations": "local work + authored hooks/connections/sandbox I/O",+ "why": "No universal count: authored integrations, dynamic model selection, memory, sandbox, and tracing can add work before the provider call.",+ "source": {+ "path": "packages/eve/src/execution/session/turn-step.ts",+ "symbol": "async function turnStep"+ }+ },+ {+ "id": "writer",+ "title": "Resolve stream writer encryption/routing",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "conditional",+ "operations": "run/key reads depending on writable serialization and caches",+ "why": "Original owner uses getWritable(); a successor uses the anchor run's forwarded writable. Stream names are run-scoped.",+ "source": {+ "path": "packages/eve/node_modules/@workflow/core/dist/runtime/run.js",+ "symbol": "getWritable(options"+ }+ },+ {+ "id": "preamble",+ "title": "Publish pre-model events",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "critical",+ "operations": "stream write batches; batch count is variable",+ "why": "Lifecycle events and authored handlers can be awaited before the model call. Count actual stream batches, not individual events.",+ "source": {+ "path": "packages/eve/src/execution/session/turn-step.ts",+ "symbol": "await emitTurnPreamble"+ }+ },+ {+ "id": "model",+ "title": "MODEL REQUEST — stop time-to-model clock",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "critical",+ "operations": "1 provider request for this first call",+ "why": "Provider response latency is outside time-to-model. Subsequent tool/model cycles have their own costs.",+ "source": {+ "path": "packages/eve/src/execution/session/turn-step.ts",+ "symbol": "await runModelCallBatch"+ }+ },+ {+ "id": "settle",+ "title": "Commit results, admit steering, settle turn",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "completion",+ "operations": "step_completed + optional next step + settleTurnStep + stream batches",+ "why": "Steering uses the same turn after a committed boundary; queue waits for settlement. No child turn run or owner-release handshake per ordinary turn.",+ "source": {+ "path": "packages/eve/src/execution/session/turn.ts",+ "symbol": "async runTurn"+ }+ },+ {+ "id": "read",+ "title": "Client stream observer",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "observer",+ "operations": "stream GET + read-key resolution as needed; tail-info only when requested",+ "why": "Separate clock/branch. An already-open stream is not a new request per chunk. Reconnects target the original run.",+ "source": {+ "path": "packages/eve/src/execution/workflow-runtime.ts",+ "symbol": "async getEventStream"+ }+ },+ {+ "id": "activity",+ "title": "Optional channel activity collector",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "conditional",+ "operations": "new root collector start; hook + activity resume/write/publish batches",+ "why": "Only channels with activity renderers. Collector startup can precede session start; separate from the ordinary ID-only path.",+ "source": {+ "path": "packages/eve/src/execution/workflow-runtime.ts",+ "symbol": "let collectorRunId"+ }+ },+ {+ "id": "reset",+ "title": "Explicit reset release acknowledgement",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "conditional",+ "operations": "bounded hooks.getByToken polling after reset acceptance",+ "why": "Not an ordinary send cost. Confirms the previous owner released the stable address before reset returns.",+ "source": {+ "path": "packages/eve/src/execution/workflow-runtime.ts",+ "symbol": "async function waitForCommandHookRelease"+ }+ },+ {+ "id": "resolve",+ "title": "Explicit resolveSession()",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "conditional",+ "operations": "1 hooks.getByToken + lazy metadata hydration",+ "why": "Requested read-only identity resolution. Never used as a send preflight.",+ "source": {+ "path": "packages/eve/src/execution/workflow-runtime.ts",+ "symbol": "async resolveContinuation"+ }+ },+ {+ "id": "task-owner",+ "title": "Background task ownership resolution",+ "modes": ["new", "stable", "alias", "handoff"],+ "lane": "conditional",+ "operations": "bounded hooks.getByToken polling inside durable work",+ "why": "Not the ordinary turn path. Reads runId only; no metadata hydration.",+ "source": {+ "path": "packages/eve/src/execution/workflow-runtime.ts",+ "symbol": "async function waitForCommandHookOwner"+ }+ }+ ]+}diff --git a/research/single-workflow-session-upgrades.md b/research/single-workflow-session-upgrades.mdnew file mode 100644index 000000000..a5b00e4a0--- /dev/null+++ b/research/single-workflow-session-upgrades.md@@ -0,0 +1,455 @@+---+issue: https://github.com/vercel/eve/issues/876+status: implemented+last_updated: "2026-09-15"+---++# Single-workflow sessions with ingress-driven upgrades++## Summary++eve runs each session as a long-lived Workflow run that pins the session's stable command hooks,+but that run does not execute conversational turns. Every turn is dispatched to a child turn+workflow on the deployment that accepted the channel request, and the two runs coordinate through a+private driver/child protocol: turn-control hooks, `NextDriverAction` transport, a driver-side+execution cursor, cross-run cancellation forwarding, and versioned turn-workflow inputs. That+topology guarantees a turn executes the same code that authenticated its request, at the cost of an+extra workflow start and several control round trips per turn. [Turn performance](./turn-performance.md)+identifies this as the largest remaining fixed cost: a benchmark-only inline prototype cut warm+p50 by 63.5%.++This proposal collapses the topology to one run. The session's owning workflow executes `turnStep`+directly and services its own inbox. Code alignment moves from every turn to the rare moment it+matters: when a delivery arrives from a different deployment and the session is idle, the owner+hands the settled session to a successor run on that exact deployment. The public session id,+stream, and `send()` / `respond()` APIs do not change, and no upgrade API, route, or channel+operation is added.++This is intentionally a deletion-heavy refactor, not an additive third execution mode. Large+swaths of the current conversational orchestration are expected to disappear: the child-turn+workflow, driver/child transport, private turn-control hooks, cross-run cancellation forwarding,+turn execution cursor, and deployment-skew input and migration layers. The implementation must not+preserve that topology behind compatibility interfaces; the deletion ledger below is a required+outcome of the design, while shared turn and harness behavior stays intact.++The tradeoff is explicit. Ordinary turns lose the cross-run overhead. The first eligible turn after+a deployment pays for the handoff, and a session with live work stays on its current deployment+until it is idle again. The first version ships with a known no-owner interval during handoff and+requests an atomic handoff primitive from Workflow in parallel.++## Former topology++```text+channel request accepted on deployment B+ -> stable session hook (owner run, started on deployment A)+ -> owner dispatches a child turn run on B (dispatch-turn-step.ts)+ -> child claims private turn-control hooks (turn-control-protocol.ts)+ -> child runs the turnStep loop, reporting NextDriverAction per step+ -> owner adopts state via TurnExecutionCursor, forwards cancel and deliveries+ -> child settles; owner disposes the control hook only after the next turn settles+```++The same-deployment path in [`inline-turn.ts`](../packages/eve/src/execution/inline-turn.ts) is a+half-step toward this proposal: it runs `turnStep` in the owner until a step needs coordination or+reaches another deployment, then falls back to the child through `requiresChildDispatch`. Both+paths must stay correct, so the fallback adds a third execution mode instead of removing one.++Everything below `turnStep` is unaffected by the topology. The harness, tool execution,+coordination handlers, and the independent durable runs for tasks, subagents, authored workflow+tools, timeout, and activity collection are identical in both designs.++## Target topology++```mermaid+flowchart LR+ Ingress["Delivery accepted on deployment B"] --> Inbox["Stable session inbox"]+ Inbox --> Owner["Owner run on A"]+ Owner -->|"same deployment, or session busy"| Owner+ Owner -->|"idle + different deployment:<br/>checkpoint, release, start"| Successor["Owner run on B"]+ Successor -->|"Run.getWritable()"| Stream["Original session stream"]+ Anchor["Original run: dormant anchor"] --> Stream+ Client["Existing session id and cursor"] --> Stream+```++One owner run executes the session:++```text+claim the stable inbox and timeout+loop:+ wait for a command+ if it is a conversational delivery from another deployment and the session is idle:+ attempt handoff; on skip or failure, continue here+ pump every claimed hook continuously into a merged inbox+ run turnStep; buffer incoming messages and respond to explicit cancellation+ admit steering against committed state, preserving the active turn+ apply coordination: task acks, workflow-tool and subagent results, input,+ authorization, cancellation rollback, caller settlement+ adopt state through the one SessionStateCursor+finalize once+```++Public identity and execution ownership become separate internal facts:++```ts+interface SessionOwnership {+ readonly sessionId: string; // stable public session identity+ readonly anchorRunId: string; // original run that owns the public stream+ readonly ownerRunId: string; // current execution run; changes on handoff+ readonly deploymentId: string; // exact deployment of the current owner+}+```++### Ownership++| State or behavior | Sole owner |+| --------------------------------------------------------------------------- | -------------------------- |+| Stable inbox, additive continuation hooks, timeout claim, terminal event | Current owner run |+| Durable session snapshot, event sequence, remaining limits | Current owner run |+| `turnStep` execution, coordination waits, cancellation rollback, settlement | Current owner run |+| Public stream lifetime | Original run (anchor) |+| Task, subagent, and authored workflow-tool bodies | Their own runs (unchanged) |+| Model history, tool projection, approvals, public action events | Harness (unchanged) |++The harness never resolves runs or hooks. Ingress never coordinates handoff; it stamps deployment+metadata and resumes the inbox.++## Upgrade semantics++The package-owned channel handler already stamps trusted `acceptedDeploymentId` on every delivery,+and `send()` / `respond()` carry it through the inbox. Today that value selects where the child+turn runs. Here it is only a signal that newer (or rolled-back) code is receiving traffic; it does+not require the accepting deployment to execute that delivery.++The owner evaluates the signal once, when it first observes a conversational delivery and before+buffering or applying it. Handoff is attempted only when both hold:++- the delivery's deployment differs from the owner's, and+- the session is idle: the triggering delivery is the only unprocessed command.++Idle excludes all of the following:++- other pending, buffered, or queued commands or deliveries, including a batched arrival;+- an active model or tool step, cancellation rollback, or caller/result settlement;+- pending human input or authorization, including waits surfaced by descendants;+- any live task, subagent, or authored workflow tool, including background work;+- pending coordination, result application, or callback processing for that work.++Unknown eligibility means skip. Session-lifetime timeout and activity collection are+infrastructure, not agent work, and do not affect eligibility.++When either condition fails, the owner processes the delivery under the existing queue/steer policy+and forgets the signal. There is no latched target, no coalescing of deployment signals, and no+re-check when a turn settles or a backlog drains. Only a later delivery that is independently+eligible can trigger an upgrade, so a continuously busy session may stay on old code indefinitely.++That rule is the core simplification. Remembering a target and pursuing it later means moving live+waits, callback ownership, and task handles between deployments, which is a cross-version+coordination protocol: the thing this proposal deletes. Deferring to the next idle delivery costs+nothing in protocol and only delays code alignment for busy sessions.++HITL responses, tool and subagent results, cancellation, reset, clear, and compact never trigger+upgrades. eve never cancels or restarts work to make a session eligible.++### Exact deployment selection++Every eve-owned Workflow start receives an exact deployment id from trusted ingress or from its+current owner. A missing id and the `"latest"` selector are rejected, and eve performs no+latest-deployment lookup, because a lookup can select a deployment other than the one that+authenticated the request. Local development supplies a trusted build-generation id in the same+role.++## Checkpoint++An eligible attempt builds a `SessionCheckpoint` from the existing durable snapshot plus settled+context and lifecycle metadata:++- private model history, raw authored state, memory, sandbox attachment;+- auth and initiator context, output schema, compaction accounting;+- event sequence, remaining limits, the complete claimed session-hook set, and original configured timeout duration.++The single triggering delivery travels alongside the checkpoint. The checkpoint never carries a+command backlog, live waits, callback ownership, or task/subagent/tool handles; the eligibility rule+guarantees none exist.++The successor rebuilds instructions, models, tools, skills, and compiled configuration from its own+bundle. Before claiming hooks, it shares the source's idle-state inspection: parse all retained+tasks (including settled entries) and handle state, and require pending-work registries to be absent+or canonically empty. Task and handle readers preserve additive metadata on updates but still+validate known fields and lifecycle rules. An unreadable checkpoint is refused before activation,+so the previous owner can recover and process the triggering delivery. Authored state stays opaque. There is no migration chain and no author-facing+state migration API, so raw `defineState` values must remain readable by the target code. The+public event stream is not a checkpoint (it omits private history and framework state), and the+design needs no per-turn snapshot store: the upgrade copies one settled snapshot when it is needed.+The checkpoint carries `anchorRunId` separately from `sessionId`, so future caller-assigned session+ids do not need to identify a Workflow run.++## Handoff++The first version releases hooks before starting the successor. This avoids a claim race between+two live owners; it does not provide atomic transfer (see [Open questions](#open-questions-and-upstream-request)).++1. Stage the checkpoint and the triggering delivery. The old run stays alive for recovery and+ starts no further turn work.+2. Dispose the session inbox hooks and account for every payload accepted up to disposal. If any+ other command arrived before release completed, abandon the upgrade, reclaim the inbox, and+ process the accepted commands there in order. A backlog is never transferred to salvage an+ upgrade.+3. After release and a final safety check, start a candidate on the triggering delivery's+ deployment with the checkpoint, the stable session identity, and the original stream. The+ checkpoint names the stable inbox and every continuation hook claimed during the session.+ The candidate validates and hydrates, then registers that exact set as one batch.+ It performs no model or tool work until it owns every hook.+4. The candidate activates and processes the triggering delivery before any later arrival.+5. Once activation is confirmed, the old owner exits, or parks as the stream anchor if it is the+ original run. Recovery after activation belongs to the successor.++On failure before activation, the old owner reclaims the hooks and processes the triggering+delivery itself, but only after confirming the candidate cannot activate and has released any+partial claims. Uncertain start or activation is resolved before retrying or recovering; two owners+never run at once.++## Stream lifetime++Workflow closes a run's streams when the run completes, so the original run must outlive every+successor for the public stream to stay open. Successors append through `Run.getWritable()` on the+original run's handle, and hook metadata carries `sessionId` separately from the hook owner's run+id.++After its first handoff the original run releases the public hooks and parks on a single terminal+hook. It performs no agent execution, command routing, or background processing. Intermediate+owners exit after handing off, so at most two runs exist per session: the anchor and the current+owner. At session end the owner runs cleanup and emits its final events, then wakes the anchor to+close the stream. Each successful handoff or legacy import restarts the original configured+timeout duration. Disabled timeouts stay disabled; failed or skipped handoffs retain the+existing deadline. The current owner ignores timeout wakes before its own deadline.++The upstream replacement is a global stream independent of any run's lifetime. Adopt it when+available and delete the anchor. Keep the anchor mechanics behind the session runtime boundary so+public identity, streaming, and cursors are unaffected either way. Global streams are follow-up+work, not a prerequisite.++## Open questions and upstream request++### The no-owner interval++The branch carries no `@workflow/core` patch. `@workflow/core` ≥ 5.0.0-beta.51+landed with [vercel/workflow#3941](https://github.com/vercel/workflow/pull/3941),+which drains released step stream writers before recording `step_completed`;+the `persists model output before settlement…` integration test in+`session/entry.integration.test.ts` covers it.++The existing [hook helpers](../packages/eve/src/execution/hook-ownership.ts)+dispose and claim in separate durable commits, so handoff steps 2–3 leave an+interval with no hook owner spanning candidate startup and hydration. eve+closes the observable consequences of that interval without an upstream+primitive:++- **Handoff markers.** Before releasing, the owner claims+ `eve:inbox:handoff:<token>` for every address in its claim set and disposes+ the markers once the transfer has either activated or been recovered. Ingress+ (`session-inbox/resume.ts`) treats "hook not found, marker present" as+ "retry within a bounded window" and "hook not found, no marker" as "no+ session". A channel therefore never starts a replacement session for an+ alias that is mid-handoff, and alias-bearing sessions hand off like+ ID-addressed ones.+- **Accepted-during-release drain.** `release()` commits `hook_disposed`+ durably before stopping the readers, and the SDK delivers every event+ accepted before that commit to the iterators first, so the payloads the+ hooks accepted but the owner never read are returned and either restored on+ the retained owner or handed to the successor.++Two guarantees hold: accepted commands are never silently dropped, and two+owners never activate. When `createHook(token, { force: true })` lands, the+successor claims with `force`; `SessionHandoff` drops the marker and release+stages and `resumeSessionInbox` drops its retry loop. Nothing else changes.++Upstream request, made in parallel and not a prerequisite for starting: an atomic,+replay-idempotent hook handoff. Inputs: expected owner, handoff id, successor, hook set, and inbox+position. Guarantees: fence the old owner, preserve every accepted payload, resolve tokens+continuously, and return the same activation result on replay across the whole multiplexed inbox,+with uncertain activation resolvable by handoff id. When available it replaces the release/start+gap inside the handoff boundary without touching ordinary execution.++## Internal boundaries++These are eve-owned internal contracts inside `execution/`, not public APIs. Each exists to absorb+a deleted path, not to wrap the Workflow SDK generally.++The owner program lives in `execution/session/`:++| Module | Responsibility |+| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| `entry.ts` | `workflowEntry`: boots an initial or handoff owner into one `SessionBoot`, then runs the program. |+| `program.ts` | The owner loop: runs turns, waits for the next input, tries handoff, finalizes once, and reports to whichever anchor holds the stream. |+| `turn.ts` | `SessionExecution.runTurn`: runs `turnStep` until the turn settles, admitting inbox traffic at committed boundaries. `ActiveTurn` owns cancellation and steering for one turn. |+| `turn-step.ts` | The `"use step"` body for one bounded batch of model calls. |+| `input-queue.ts` | The one ordered queue of admitted deliveries, controls, and authorization callbacks, plus task-delivery idempotency and cancellation facts. Decides what the next turn is and whether it may hand off. |+| `admission.ts` | Decodes one inbox payload into a queue admission; no turn policy. |+| `next-input.ts` | Waits for the next input a parked owner must act on. |+| `state-cursor.ts` | The one mutable context/state pair; claims every hook the state names before publishing a transition. |+| `hook-tokens.ts` | Derives the full hook claim set from committed state. Used by boot, every transition, handoff, and legacy import. |+| `handoff.ts`, `handoff-steps.ts` | `SessionHandoff.tryTransfer` as one transaction: markers, release, start, activate, recover. |+| `finalization.ts` | The single terminal path for done, expired, and failed sessions. |+| `event-sink.ts` | Binds adapter context, dynamic connections, and event fan-out to one step's stream writer. |+| `timeout*.ts` | The durable deadline timer, stamped with the arming owner so a successor ignores a predecessor's wake. |++`session-inbox/` is transport only: `inbox.ts` merges every claimed hook into one FIFO and pushes+interrupts to the active turn the moment they are accepted; `resume.ts` is ingress; `address.ts`+owns token namespacing. `legacy-session/` imports a pre-cutover driver's session into this program+and is the only module that knows the former wire shapes.++## Deletion ledger++The result must have fewer execution paths, not the old topology behind new interfaces.++The current inbox implementation lives in `execution/session-inbox/`: `inbox.ts`+owns the pump, `protocol.ts` normalizes commands, `address.ts` defines identity,+and `resume.ts` owns resume-first delivery and lazy identity resolution.+Session checkpoints require embedded program memory; there is no `eve.session`+stream fallback, snapshot migration registry, or duplicate snapshot version.+The state-level version only rejects incompatible handoffs. Client event-stream+versions remain separate because stored output survives deployments.++- `turn-dispatch.ts`, `dispatch-turn-step.ts`, and the inline/child split in `inline-turn.ts`.+- The old turn engine in `turn-workflow.ts`; its coordination moves into+ `SessionExecution`. The stable `turnWorkflow` name remains only as an import entrypoint.+- `turn-control-protocol.ts`, `turn-control-receiver.ts`, private turn-control hooks, cross-run+ cancellation forwarding, and deferred control-hook disposal. Local abort, rollback, and+ settlement behavior stay.+- `TurnExecutionCursor` driver reporting and `NextDriverAction` transport. The shared state cursor+ and typed step outcomes stay, minus deployment-skew transport fields.+- Turn-workflow input migrations, driver-capability branches, and inbox wire versions v0–v6 with+ their migration chains. Historical decoding and outbound encoding live only in+ `execution/legacy-session/`. Step types still needed move out of transport modules.++Transport cutover is clean: new sessions use one stable ingress envelope with required deployment+metadata, and legacy driver/child sessions enter the isolated one-time import in `execution/legacy-session/` on their next turn dispatch. The import preserves committed conversation data and interrupts pending execution; old drivers remain stream anchors until final completion. Import supports drivers from eve 0.45 onward (wire versions 1–7, turn-input versions 1–2, embedded snapshots); an older driver is reported inactive so its channel starts a fresh session. Ingress+can still be newer than a busy owner, so the owner validates that one envelope and rejects+unsupported commands instead of translating them. Nothing deleted here is replaced by wait+migration, callback rebinding, or cross-version coordination.++## Alias and steering follow-through++Channel handlers add addresses with `session.continuation.alias(rawToken)`+or `channel.continuation.alias(rawToken)`. The runtime namespaces the token,+records it in the serialized context, and claims every new address when the+step commits. The most recently selected alias is exposed as `continuation.token`;+all earlier addresses remain valid. There is no rekey API or replacement claim.+The checkpoint names the stable session inbox explicitly and carries continuation aliases separately.++Each claimed hook has one continuously running iterator reader. Readers merge+accepted payloads into one FIFO while model and tool steps run and never+pause on queue depth, so a cancel is never held behind unread input. A cancel+or reset is pushed to the active turn the moment the reader accepts it, so the+running step aborts immediately; its durable side effects apply when the+queued command is admitted at the next boundary. Authorization callbacks are+ordinary queue entries keyed by attempt; the queue resumes a challenge once+every expected attempt has reported and drops callbacks for replaced attempts.+Handoff releases the entire claim set and transfers accepted, unconsumed+payloads with the exact tokens.++`TurnRouting` admits input from the session's one queue only against committed state.+`steer` preserves completed work, turn identity, and accumulated usage.+`queue` remains pending until settlement. A different delegated caller also+waits for its own turn. Runtime results and addressed responses retain their+existing routing. Explicit cancellation uses the abort signal; steering does not.++Steering applies only while the turn is still open: `turnStep` returned+`continue` and the model wants another step. The harness emits `turn.completed`+and `session.waiting` itself inside the settling step, so a message that arrives+after the model produced its answer starts the next turn. This matches what+other harnesses do and costs no extra durable step per turn. Model-call batching+defines the checkpoint interval and therefore the steering latency.++This follows the holder attempt's continuous-reader boundary without adopting+its separate holder and turn topology or its deferred settlement. Upstream+`step-delivery-ordering.test.ts`, `step-delivery-hop-count.test.ts`, and+`delivery-barrier-coverage.test.ts` cover iterator delivery order against cached+step results and other hooks, including layered async consumers. eve additionally+tests merged alias bursts while the owner is waiting, same-turn steering,+cancellation followed by new input, and clients following settlement races.++## Unified inbox and resume-first delivery++`SessionInbox` owns the additive address set and one merged queue. Commands,+authorization callbacks, and workflow-tool messages share that transport.+Authorization eligibility is a message-routing rule, not a second hook source.+`TurnRouting` owns turn policy and cancellation, not another transport buffer.+Independent background task workflows keep their own executor inboxes.++Startup claims one stable hook plus the initial alias, if present. The SDK also+creates an `abrt_*` hook when serializing the active turn's abort signal into a+step. That hook carries explicit cancellation, never steering. The original+owner creates its terminal anchor hook only when it attempts handoff. Handoff+activation remains a separate, handoff-only acknowledgement hook. The deadline+workflow starts concurrently with the initial turn, and both operations are+settled before leaving startup. A successor starts a new deadline from activation using+the original configured duration, and the previous owner cancels its timer.++Ingress calls `resumeHook(token, command)` directly. The returned receipt carries+the owning run ID and lazy `{ sessionId }` metadata. Only alias callers asking+for a Session handle hydrate that metadata, after resumption. Known-session+requests and internal fire-and-forget senders never hydrate it. Missing metadata+is an identity error after acceptance, not permission to resend or create a run.+`getRawHookByToken` is deleted: the SDK's standard lookup is already lazy.++The only explicit hook lookups left in eve are requested alias resolution,+reset's release acknowledgement, and replay-idempotent background-task ownership+resolution. Registration barriers remain for competing claims and callbacks+that must be registered before another run can signal them. Claims within an+adoption or handoff batch run together rather than one durable barrier per alias.++The [network-hop map](./session-network-hops.html) and its+[machine-readable data](./session-network-hops.json) distinguish source-derived+operations, cache-dependent work, and model-start dependencies. They do not+claim measured latency or a fixed count for arbitrary authored integrations.++## Out of scope++- The general holder topology from [PR #3063](https://github.com/vercel/eve/pull/3063), background+ write queues, detached persistence, and per-turn snapshot storage are not ported here.+ Its continuously owned inbox readers and deferred settlement inform the session pump.+- Public upgrade or state-migration APIs: `Session.upgrade()`, a channel operation, or a route.+- A session directory and caller-assigned session ids. Separating `sessionId`, `anchorRunId`, and+ `ownerRunId` keeps that future change from depending on Workflow run identity without adding the+ directory here.+- Changes to the independent runs for tasks, subagents, workflow tools, timeout, and activity collection.++## Invariants++- The owner run and the authored agent code it executes come from the same deployment.+- Exactly one owner is activated for a session at any time.+- Accepted commands are processed in FIFO order and never dropped, including across a handoff+ attempt.+- Handoff never duplicates model or tool work.+- No Workflow start uses `"latest"` or an absent deployment id.+- No upgrade state survives a skipped attempt; there is no remembered target.+- The public session id, stream, and cursor semantics are unchanged by any number of upgrades.++## Validation++- Same-deployment turns, including coordination waits and cancellation, run on one owner with no+ child turn run or private control hooks. Assert the deleted paths are unreachable.+- An eligible A→B delivery starts one successor on B and preserves identity, connected stream and+ cursor, settled state, limits, timeout duration, and every claimed session hook. Owner and authored code+ report B. An unreadable checkpoint recovers A's ownership and processes the delivery once.+- Every unsafe category skips: parked HITL, background tasks, batched deliveries, queued commands.+ Work stays on A. Settlement and queue draining trigger nothing; only a fresh eligible delivery+ does. No remembered target or live handle crosses versions.+- Inject concurrent deliveries and replay failures at every handoff step. Verify FIFO order, no+ lost accepted commands, no duplicated model/tool work, and one activated owner. Cover+ disposal-time arrivals, partial claims, failed starts, and uncertain activation.+- During the no-owner interval, ID-addressed ingress retries within bounds and never creates a+ replacement session. With the upstream primitive, additionally assert continuous alias resolution, including+ mixed-deployment bursts and rollbacks.+- Queue, steer, cancel, clear, compact, reset, timeout, input, authorization, task, subagent, and+ workflow-tool behavior are unchanged before, during, and after an upgrade.+- With the upgraded SDK, cross-run appends and replay preserve connected readers and cursors+ locally and hosted. Repeated upgrades leave only the anchor and the current owner; intermediate+ exits do not close the stream; final cleanup closes it once.+- Missing and `"latest"` deployment selectors are rejected, and local build-generation upgrades+ work. Use integration/scenario tests for ownership and replay, plus deterministic fixture evals+ in CI for HTTP delivery and streaming.+- The paired hosted [turn-performance benchmark](./turn-performance.md) improves warm+ same-deployment one-step p50 by at least 30% and 750 ms with at most a 10% p95 regression.+ Upgrade-turn latency is reported separately and excludes background-pump work.diff --git a/scripts/guard-invariants.mjs b/scripts/guard-invariants.mjsindex 884d71c8d..22b650c3c 100644--- a/scripts/guard-invariants.mjs+++ b/scripts/guard-invariants.mjs@@ -100,16 +100,6 @@* `pnpm --filter eve build`. Turbo owns workspace dependency* ordering; nested builds race on eve's clean-and-publish dist* directory and let consumers observe a partial package.- * rule 40 — Wire schemas and version-bound encoders are immutable protocol- * data. Pure `*.vN.migration.ts` transforms are immutable data too;- * version selection, chain assembly, and realm normalization remain- * editable policy. Every data module must carry a colocated test.- * The session-inbox registry must be contiguous, name every schema- * module, and identify its highest version as current. Wire versions- * are append-only protocol history: change the contract by adding a- * version and migration, never by updating historical data and its- * snapshot together. The workflow-safe decoder must not import- * schemas or validation libraries at runtime.* rule 42 — The shared subagent workflow body is framework-authored* userspace. It must not import task, harness, or context* internals or recover private state through `Symbol.for`.@@ -124,7 +114,6 @@* `guard-invariants-baseline.json`. Counts and allowlists in that file* may only shrink (as offenders are removed) — they may never grow.*/-import { execFileSync } from "node:child_process";import { glob, readFile, readdir, lstat } from "node:fs/promises";import { createRequire } from "node:module";import { dirname, join, relative, resolve, sep } from "node:path";@@ -217,6 +206,7 @@ function isTsLike(relPath) {* rule37: Violation[];* rule42: Violation[];* rule43: Violation[];+ * rule44: Violation[];* symlinks: string[];* }} state*/@@ -248,6 +238,7 @@ async function scanRepo(state) {checkRule37(posix, content, state.rule37);checkRule42(posix, lines, state.rule42);checkRule43(posix, lines, state.rule43);+ checkRule44(posix, lines, state.rule44);}}@@ -288,7 +279,10 @@ const SUBAGENT_IMPORT_RE =/from ["'](?:#|(?:\.\.?\/)+(?:[\w-]+\/)*)(?:subagents|execution\/tools\/subagent|tools\/subagent)(?:\/|\.js|["'])/;const RULE43_GENERIC_SESSION_FILES = new Set([- "packages/eve/src/execution/session-command-inbox.ts",+ "packages/eve/src/execution/session-hook-claims.ts",+ "packages/eve/src/execution/session-inbox/inbox.ts",+ "packages/eve/src/execution/session-input-ledger.ts",+ "packages/eve/src/execution/session-input-queue.ts","packages/eve/src/execution/session-state-cursor.ts",]);@@ -311,6 +305,36 @@ function checkRule43(posix, lines, violations) {});}+// Legacy import is reachable only from workflow discovery and ingress.+const LEGACY_INGRESS_FILES = new Set([+ "packages/eve/src/execution/session-inbox/resume.ts",+ "packages/eve/src/execution/connections/callback-route.ts",+ "packages/eve/src/eve-channel/index.ts",+]);+/** @param {string} posix @param {string[]} lines @param {Violation[]} violations */+function checkRule44(posix, lines, violations) {+ if (+ posix.includes("/execution/legacy-session/") ||+ posix.includes("/internal/testing/") ||+ /\.(?:test|integration\.test|scenario\.test)\.ts$/.test(posix) ||+ LEGACY_INGRESS_FILES.has(posix)+ )+ return;+ lines.forEach((line, index) => {+ if (+ /from ["'][^"']*legacy-session\//.test(line) ||+ /import\(["'][^"']*legacy-session\//.test(line)+ )+ violations.push({+ rule: 44,+ file: posix,+ line: index + 1,+ message:+ "Legacy session import belongs at ingress; current execution must consume only normalized session state.",+ });+ });+}+// ---------- Rule 13: spread-ternary object composition ----------/** Matches `...(<expr> ? {} : { ... })` or the mirrored form. */@@ -606,273 +630,6 @@ function importSpecifier(node) {return undefined;}-// ---------- Rule 40: wire versions carry colocated contract tests ------------const WIRE_FAMILY_DIR = "packages/eve/src/execution/wire";-const SESSION_INBOX_WIRE_CONTRACT = `${WIRE_FAMILY_DIR}/session-inbox-contract.ts`;-const SESSION_INBOX_WIRE_DECODER = `${WIRE_FAMILY_DIR}/session-inbox-wire.ts`;-const VERSIONED_WIRE_HISTORY_RE = new RegExp(- `^${WIRE_FAMILY_DIR}/(?:__snapshots__/)?[a-z0-9-]+-wire\\.v\\d+(?:\\.migration)?(?:\\.test\\.ts(?:\\.snap)?|\\.ts)$`,-);-const RULE_40_ALLOWED_REWRITES = new Map([- [- `${WIRE_FAMILY_DIR}/session-inbox-wire.v1.ts`,- {- from: "5f110be5d7b488216c574a1aef9d2074d670efd2",- to: "7f5864f20e6bbb9f430c23918320ca6319c4cb14",- },- ],-]);-const PURE_MIGRATION_IMPORTS = new Map([- ["#execution/durable-session-migrations/chain.js", new Map([["VersionMigration", "type"]])],- ["#shared/guards.js", new Map([["isObject", "value"]])],-]);-const WORKFLOW_DECODER_RUNTIME_IMPORTS = new Set([- "#execution/durable-session-migrations/chain.js",- "#execution/wire/session-inbox-contract.js",- "#execution/wire/session-inbox-wire.v0.js",- "#execution/wire/session-inbox-wire.v2-migration.js",- "#execution/wire/session-inbox-wire.v2.migration.js",- "#execution/wire/session-inbox-wire.v3.migration.js",- "#execution/wire/session-inbox-wire.v4.migration.js",- "#execution/wire/session-inbox-wire.v5.migration.js",- "#shared/guards.js",-]);--function gitOutput(args) {- try {- return execFileSync("git", args, {- cwd: REPO_ROOT,- encoding: "utf8",- stdio: ["ignore", "pipe", "ignore"],- });- } catch {- return undefined;- }-}--function checkRule40ImmutableWireHistory() {- const hasBase = gitOutput(["rev-parse", "--verify", "origin/main"]) !== undefined;- const comparisons = [- { args: ["diff", "--name-status", "--", WIRE_FAMILY_DIR], state: "worktree" },- {- args: ["diff", "--cached", "--name-status", "--", WIRE_FAMILY_DIR],- state: "index",- },- ];- if (hasBase)- comparisons.push({- args: ["diff", "--name-status", "origin/main...HEAD", "--", WIRE_FAMILY_DIR],- state: "head",- });-- const changes = new Set();- for (const { args, state } of comparisons) {- for (const line of (gitOutput(args) ?? "").trim().split("\n")) {- if (line !== "") changes.add(`${state}\t${line}`);- }- }-- /** @type {Violation[]} */- const violations = [];- for (const change of changes) {- const [state, status, ...paths] = change.split("\t");- const protectedPaths = paths.filter((path) => VERSIONED_WIRE_HISTORY_RE.test(path));- if (protectedPaths.length === 0 || status === "A") continue;- if (protectedPaths.every((path) => isAllowedRule40Rewrite(path, state))) continue;- if (- hasBase &&- protectedPaths.every(- (path) => gitOutput(["cat-file", "-e", `origin/main:${path}`]) === undefined,- )- ) {- continue;- }- violations.push({- rule: 40,- file: protectedPaths.at(-1),- line: 1,- message: `shipped wire-version history is immutable (git status ${status}). Add the next wire version and migration instead of changing or deleting an existing version module, contract test, or snapshot.`,- });- }- return violations;-}--function isAllowedRule40Rewrite(path, state) {- const rewrite = RULE_40_ALLOWED_REWRITES.get(path);- if (rewrite === undefined) return false;- const baseHash = gitOutput(["rev-parse", `origin/main:${path}`])?.trim();- const currentHash =- state === "head"- ? gitOutput(["rev-parse", `HEAD:${path}`])?.trim()- : state === "index"- ? gitOutput(["rev-parse", `:${path}`])?.trim()- : gitOutput(["hash-object", path])?.trim();- return baseHash === rewrite.from && currentHash === rewrite.to;-}--function checkRule40MigrationPurity(path, source) {- const sourceFile = ts.createSourceFile(- path,- source,- ts.ScriptTarget.Latest,- true,- ts.ScriptKind.TS,- );- /** @type {Violation[]} */- const violations = [];- const visit = (node) => {- const specifier = importSpecifier(node);- if (specifier !== undefined) {- const allowed = PURE_MIGRATION_IMPORTS.get(specifier.text);- if (allowed === undefined || !hasOnlyAllowedNamedImports(node, allowed)) {- violations.push({- rule: 40,- file: path,- line: sourceFile.getLineAndCharacterOfPosition(specifier.getStart(sourceFile)).line + 1,- message: `imports "${specifier.text}". Versioned wire migrations are immutable data transforms, so they may import only the VersionMigration type or dependency-free shared guards. Move normalization and version-selection policy to the wire facade.`,- });- }- }- ts.forEachChild(node, visit);- };- visit(sourceFile);- return violations;-}--function checkRule40WorkflowDecoderImports(source) {- const sourceFile = ts.createSourceFile(- SESSION_INBOX_WIRE_DECODER,- source,- ts.ScriptTarget.Latest,- true,- ts.ScriptKind.TS,- );- /** @type {Violation[]} */- const violations = [];- const visit = (node) => {- const specifier = importSpecifier(node);- if (- specifier !== undefined &&- isRuntimeImportReference(node) &&- !WORKFLOW_DECODER_RUNTIME_IMPORTS.has(specifier.text)- ) {- violations.push({- rule: 40,- file: SESSION_INBOX_WIRE_DECODER,- line: sourceFile.getLineAndCharacterOfPosition(specifier.getStart(sourceFile)).line + 1,- message: `imports "${specifier.text}" at runtime. The session-inbox decoder is embedded with inline sources in every workflow driver; keep schema and validation dependencies in the encoder and import only the inferred wire type here.`,- });- }- ts.forEachChild(node, visit);- };- visit(sourceFile);- return violations;-}--function isRuntimeImportReference(node) {- if (ts.isImportTypeNode(node)) return false;- if (ts.isImportDeclaration(node)) {- const clause = node.importClause;- if (clause?.isTypeOnly === true) return false;- if (clause?.namedBindings !== undefined && ts.isNamedImports(clause.namedBindings)) {- return clause.namedBindings.elements.some((element) => !element.isTypeOnly);- }- return true;- }- if (ts.isExportDeclaration(node)) {- if (node.isTypeOnly) return false;- if (node.exportClause !== undefined && ts.isNamedExports(node.exportClause)) {- return node.exportClause.elements.some((element) => !element.isTypeOnly);- }- return true;- }- return true;-}--async function checkRule40WireContracts() {- const violations = checkRule40ImmutableWireHistory();- let entries;- try {- entries = await readdir(join(REPO_ROOT, WIRE_FAMILY_DIR));- } catch {- return violations;- }-- for (const name of entries) {- const match = name.match(/^([a-z0-9-]+)-wire\.v(\d+)(\.migration)?\.ts$/);- if (match === null) continue;- const [, family, version, kind = ""] = match;-- const testName = `${family}-wire.v${version}${kind}.test.ts`;- if (!entries.includes(testName)) {- violations.push({- rule: 40,- file: `${WIRE_FAMILY_DIR}/${name}`,- line: 1,- message: `wire family "${family}" version ${version} has no colocated contract test (${testName}). Pin this version's schema/encoder or migration/fixtures before shipping it.`,- });- }- if (kind === ".migration") {- const path = `${WIRE_FAMILY_DIR}/${name}`;- violations.push(- ...checkRule40MigrationPurity(path, await readFile(join(REPO_ROOT, path), "utf8")),- );- }- }-- const contractSource = await readFile(join(REPO_ROOT, SESSION_INBOX_WIRE_CONTRACT), "utf8");- const decoderSource = await readFile(join(REPO_ROOT, SESSION_INBOX_WIRE_DECODER), "utf8");- violations.push(...checkRule40WorkflowDecoderImports(decoderSource));- const registryMatch = contractSource.match(- /SESSION_INBOX_WIRE_VERSIONS\s*=\s*\[([^\]]*)\]\s*as const/,- );- const tokens = registryMatch?.[1]- .split(",")- .map((token) => token.trim())- .filter(Boolean);- if (tokens === undefined || tokens.length === 0 || tokens.some((token) => !/^\d+$/.test(token))) {- violations.push({- rule: 40,- file: SESSION_INBOX_WIRE_CONTRACT,- line: 1,- message:- "SESSION_INBOX_WIRE_VERSIONS must be an explicit numeric tuple so CI can compare the declared protocol history with shipped version modules.",- });- return violations;- }-- const line = contractSource.slice(0, registryMatch.index).split("\n").length;- const versions = tokens.map(Number);- const expectedVersions = versions.map((_, index) => index + 1);- if (JSON.stringify(versions) !== JSON.stringify(expectedVersions)) {- violations.push({- rule: 40,- file: SESSION_INBOX_WIRE_CONTRACT,- line,- message: `SESSION_INBOX_WIRE_VERSIONS must be contiguous and ascending from 1; found [${versions.join(", ")}]. Add new versions without renumbering or removing protocol history.`,- });- }-- const shippedVersions = entries- .flatMap((name) => {- const match = name.match(/^session-inbox-wire\.v(\d+)\.ts$/);- return match === null ? [] : [Number(match[1])];- })- .sort((left, right) => left - right);- const registeredModules = [0, ...versions];- if (JSON.stringify(shippedVersions) !== JSON.stringify(registeredModules)) {- violations.push({- rule: 40,- file: SESSION_INBOX_WIRE_CONTRACT,- line,- message: `session-inbox wire modules [${shippedVersions.join(", ")}] must exactly match legacy v0 plus registered versions [${registeredModules.join(", ")}].`,- });- }-- return violations;-}-// ---------- Rule 19: AsyncLocalStorage instances ----------const NEW_ALS_RE = /new\s+AsyncLocalStorage\s*[<(]/;@@ -1626,6 +1383,7 @@ async function main() {rule37: /** @type {Violation[]} */ ([]),rule42: /** @type {Violation[]} */ ([]),rule43: /** @type {Violation[]} */ ([]),+ rule44: /** @type {Violation[]} */ ([]),symlinks: /** @type {string[]} */ ([]),};@@ -1728,14 +1486,12 @@ async function main() {// Rule 38violations.push(...(await checkRule38NoNestedEveBuild()));- // Rule 40- violations.push(...(await checkRule40WireContracts()));-// Rule 42violations.push(...state.rule42);// Rule 43violations.push(...state.rule43);+ violations.push(...state.rule44);if (violations.length === 0) {process.stdout.write("[eve:guard:invariants] ok — all mechanical lints passed.\n");