The Open Framework for Building Agents
feat(eve): hand off sessions atomically with forced hook claims (#5035)
Andrew Barba54d63fd0be82
diff --git a/.changeset/atomic-session-handoff.md b/.changeset/atomic-session-handoff.mdnew file mode 100644index 000000000..b6a7f01b6--- /dev/null+++ b/.changeset/atomic-session-handoff.md@@ -0,0 +1,5 @@+---+"eve": patch+---++A session keeps accepting messages during a deployment or compaction handoff, so the first message after a handoff reaches the model sooner and messages sent mid-handoff no longer retry or return `409 session_not_ready`; messages already waiting when a compaction finishes now run before the session moves. Sessions started on an earlier eve release still move to this release: their first move uses the previous handoff, and every move after it uses the new one. On Workflow worlds without hook force-claim support, sessions no longer move between runs, so their run history keeps growing for as long as the session lives.diff --git a/docs/concepts/execution-model-and-durability.mdx b/docs/concepts/execution-model-and-durability.mdxindex 70c3cded6..b5b965537 100644--- a/docs/concepts/execution-model-and-durability.mdx+++ b/docs/concepts/execution-model-and-durability.mdx@@ -27,7 +27,11 @@ When a Vercel production deployment changes, a new delivery to an idle session hBefore taking ownership, the target deployment upgrades the checkpoint when an older eve release wrote it, then checks that no pending work remains. A deployment accepts checkpoints from eve 0.66.0 and later, so upgrading eve does not leave long-lived sessions, such as a Slack thread, on their old deployment. An older release cannot read a newer checkpoint: after a rollback, a session that already moved to the newer deployment stays there. Extension state saved before eve 0.69 moves to its mount when exactly one mount of that extension package defines that state. State that the target deployment no longer defines, such as a removed `defineState` key, is dropped, and the target deployment's runtime logs show a `dropping unknown context key during deserialization` warning. When two or more mounts of one extension package define that state, eve cannot choose an owner, and the session stays on its current deployment. Idle subagent sessions that eve 0.66–0.68 kept for later reuse are stopped after the handoff. Authored session state remains opaque to this validation.-If the target deployment rejects the session, the previous owner keeps it and processes the triggering delivery. When the target deployment cannot read the checkpoint, its Vercel runtime logs show a `session handoff refused` warning with the checkpoint version and the reason. Owners on this release or later also write a `session handoff failed` warning to their own runtime logs, with the target deployment and the reason.+Messages that arrive while a handoff is in progress are accepted right away and are not lost. The new owner processes them after the triggering delivery, in the order they arrived, whichever run accepted them.++The previous owner forwards the messages it accepted as soon as the new owner has taken over the session. Until they arrive, the new owner holds back everything it receives itself, including replies to tool runs and subagents that its first turn started, and processes it afterwards. A cancel still stops the new owner's running turn as soon as it arrives. If either run ends before the handoff settles, the other stops waiting for it.++If the target deployment rejects the session, the previous owner keeps it and processes the triggering delivery, followed by any messages that arrived during the attempt. When the target deployment cannot read the checkpoint, its Vercel runtime logs show a `session handoff refused` warning with the checkpoint version and the reason. Owners on this release or later also write a `session handoff failed` warning to their own runtime logs, with the target deployment and the reason.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.@@ -35,7 +39,9 @@ eve does not move live work between deployments. A session with a running turn,Every workflow run records each step it executes, so a session that ran on one run for weeks would carry its whole history in that run. To bound this, eve moves a session to a fresh run on its current deployment after [compaction](./default-harness#compaction) rewrites the conversation history. This applies to automatic compaction during a turn and to a client or channel compaction request.-The move happens once the turn settles and nothing else is waiting: no queued messages, running tasks or subagents, or pending human input. The new run receives the compacted history and settled state, then waits for the next message. If a single message reaches an otherwise idle session before the move completes, eve moves the session with that message, and the message's turn runs on the new run. If work is still pending, eve tries again after a later turn settles. The session keeps its ID, event stream, continuation addresses, and deadline; compaction never extends [`sessionTimeoutMs`](../agent-config#runtime-limits). If the new run cannot take ownership, the current run keeps the session, writes a `session handoff failed` warning to its runtime logs, and tries again later.+The move happens once the turn settles and nothing else is waiting: no queued messages, running tasks or subagents, or pending human input. The new run receives the compacted history and settled state, then waits for the next message. A message that is already waiting when the turn settles runs on the current run first, and the session moves at the next point where nothing is waiting. A message that arrives after the move starts is accepted right away and runs once, on the new run. If work is still pending, eve tries again after a later turn settles. The session keeps its ID, event stream, continuation addresses, and deadline; compaction never extends [`sessionTimeoutMs`](../agent-config#runtime-limits). If the new run cannot take ownership, the current run keeps the session, writes a `session handoff failed` warning to its runtime logs, and tries again later.++Both kinds of handoff need a Workflow world that can move a session's addresses from one run to another without releasing them, and can keep a released address reserved for a while (the `hookForceClaim` and `hookRetention` capabilities). Vercel Workflow, the local world, and `@workflow/world-postgres` 5.0.4 and later provide both. On a world without them, sessions never move between runs: deployment and compaction handoffs are skipped, and a session's run history grows for as long as the session lives. The first skipped attempt writes a `session handoff unavailable` warning to the runtime logs.### Stranded sessions@@ -253,11 +259,14 @@ the returned handle. That identity lookup does not block workflow resumption.ID-addressed delivery already knows the session ID and needs no hook metadatalookup. 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.+A handoff never leaves the session's addresses without an owner. The previous+owner keeps every address until the new run takes all of them over, so a+delivery during a handoff is accepted immediately and is never reported as an+inactive session. An owner still running an earlier eve release gives up its+addresses briefly during a handoff and leaves a short-lived marker for each+one; a delivery that lands in that interval retries until the successor+claims the address. Either way, a channel never starts a replacement session+for an address that is changing owners.When a session is waiting, a delivery through its ID or any claimed channel address wakes it and starts the next turn. Message sends default to `turnPolicy: "steer"`. Before assistant output begins, the session owner signals pending model generation to stop, then applies the correction within the same turn and with the same turn ID. This includes model requests that perform provider-managed search before answering; interrupted search work may run again. Reasoning and search progress do not count as assistant output.diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/compact-session-handoff.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/compact-session-handoff.eval.tsindex 215bb2b10..0d81bea5d 100644--- a/e2e/fixtures/agent-cancellation/evals/cancellation/compact-session-handoff.eval.ts+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/compact-session-handoff.eval.ts@@ -18,7 +18,9 @@ function expectCompaction(compacted: EveEvalTurn): void {* Each compaction moves the idle session to a fresh workflow run on the same* deployment. The session keeps its ID, event stream, and conversation, so* later messages still stream normally and a fact from before both- * compactions is still known.+ * compactions is still known. Bob's reply is sent the moment the first+ * compaction reports `session.waiting`, while the session is moving, and must+ * still run exactly once.*/export default defineEval({description: "Continue a session and its conversation across repeated compactions.",@@ -39,6 +41,7 @@ export default defineEval({);update.expectOk();update.notEvent("session.failed");+ update.event("turn.started", { count: 1 });update.messageIncludes(/STATUS-AFTER-COMPACTION-OK/);expectCompaction(await session.compact());@@ -50,6 +53,12 @@ export default defineEval({recall.notEvent("session.failed");recall.messageIncludes(/ORCHID-42/);+ // One unbroken stream across both moves: it never restarted or ended.+ session.event("session.started", { count: 1 });+ session.notEvent("session.failed");+ session.notEvent("session.completed");+ session.event("turn.started", { count: 3 });+t.succeeded();},});diff --git a/packages/eve/src/execution/hook-ownership.ts b/packages/eve/src/execution/hook-ownership.tsindex f48efec8c..e57fb76a5 100644--- a/packages/eve/src/execution/hook-ownership.ts+++ b/packages/eve/src/execution/hook-ownership.ts@@ -40,6 +40,24 @@ export function isHookConflictError(error: unknown): error is {);}+/**+ * Another run took the hook's token with `experimental_force`. Matched by name:+ * `HookForceClaimedError.is` lives in a module the workflow bundle cannot load.+ */+export function isHookForceClaimedError(error: unknown): error is {+ readonly claimedByRunId: string;+ readonly name: "HookForceClaimedError";+} {+ return (+ typeof error === "object" &&+ error !== null &&+ "name" in error &&+ error.name === "HookForceClaimedError" &&+ "claimedByRunId" in error &&+ typeof error.claimedByRunId === "string"+ );+}+function createHookConflictError(token: string,conflictingRunId: string,diff --git a/packages/eve/src/execution/session-inbox/address.ts b/packages/eve/src/execution/session-inbox/address.tsindex 85905765c..6317d7800 100644--- a/packages/eve/src/execution/session-inbox/address.ts+++ b/packages/eve/src/execution/session-inbox/address.ts@@ -53,7 +53,10 @@ export function logicalSessionInboxToken(token: string): string | undefined {: undefined;}-/** Marker a releasing owner leaves so ingress can tell "handoff in progress" from "no session". */+/**+ * Marker an owner older than handoff version 3 leaves while it releases its+ * hooks, 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/end-stranded-session.ts b/packages/eve/src/execution/session-inbox/end-stranded-session.tsindex 7e175d90d..0e6430165 100644--- a/packages/eve/src/execution/session-inbox/end-stranded-session.ts+++ b/packages/eve/src/execution/session-inbox/end-stranded-session.ts@@ -65,7 +65,7 @@ export async function endStrandedSession(await cancelRuns(world, [ownerRunId, sessionId], "Session ended: its deployment was retired");await waitForSessionHooksRelease([sessionCommandHookToken(sessionId), logicalSessionToken(address), ...ownedTokens],- ownerRunId,+ { ownerRunId, sessionId },);log.warn("Reset stranded session", {currentEveVersion: resolveInstalledPackageInfo().version,diff --git a/packages/eve/src/execution/session-inbox/hook-release.ts b/packages/eve/src/execution/session-inbox/hook-release.tsindex e1c634d64..9f0363797 100644--- a/packages/eve/src/execution/session-inbox/hook-release.ts+++ b/packages/eve/src/execution/session-inbox/hook-release.ts@@ -1,29 +1,54 @@import { sessionInboxHookToken } from "#execution/session-inbox/address.js";import { findSessionHookHolder } from "#execution/session-inbox/owner.js";+import { requireSessionId } from "#execution/session-inbox/resume.js";/** Longest ingress waits for a session hook to change hands. */export const SESSION_HOOK_HANDOVER_TIMEOUT_MS = 30_000;-/** Waits until none of the logical session addresses belongs to `ownerRunId` any more. */+/**+ * Waits until no run serving `session` holds any of the logical addresses. A+ * handoff successor serves the same session, so only the session's end (or+ * an unrelated run claiming the address afterwards) satisfies the wait.+ */export async function waitForSessionHooksRelease(logicalTokens: Iterable<string>,- ownerRunId: string,+ session: { readonly ownerRunId: string; readonly sessionId: string },): Promise<void> {await Promise.all([...new Set(logicalTokens)].map((token) =>- waitForHookRelease(sessionInboxHookToken(token), ownerRunId),+ waitForHookRelease(sessionInboxHookToken(token), session),),);}-async function waitForHookRelease(token: string, ownerRunId: string): Promise<void> {+async function waitForHookRelease(+ token: string,+ session: { readonly ownerRunId: string; readonly sessionId: string },+): Promise<void> {const deadline = Date.now() + SESSION_HOOK_HANDOVER_TIMEOUT_MS;while (true) {- if ((await findSessionHookHolder(token))?.runId !== ownerRunId) return;+ if (!(await servesSession(token, session))) return;if (Date.now() >= deadline) {- throw new Error(`Timed out waiting for session "${ownerRunId}" to release inbox "${token}".`);+ throw new Error(+ `Timed out waiting for session "${session.sessionId}" to release inbox "${token}".`,+ );}await new Promise<void>((resolve) => setTimeout(resolve, 20));}}++async function servesSession(+ token: string,+ session: { readonly ownerRunId: string; readonly sessionId: string },+): Promise<boolean> {+ const holder = await findSessionHookHolder(token);+ if (holder === undefined) return false;+ try {+ if (holder.hook !== undefined)+ return requireSessionId(await holder.hook.metadata) === session.sessionId;+ } catch {+ // Unreadable metadata says nothing about the holder; fall through to its id.+ }+ return holder.runId === session.ownerRunId;+}diff --git a/packages/eve/src/execution/session-inbox/inbox.integration.test.ts b/packages/eve/src/execution/session-inbox/inbox.integration.test.tsindex b09c6cb41..94003214a 100644--- a/packages/eve/src/execution/session-inbox/inbox.integration.test.ts+++ b/packages/eve/src/execution/session-inbox/inbox.integration.test.ts@@ -1,9 +1,14 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";-import { sessionCommandInboxWorkflow } from "#internal/testing/session-inbox-workflow.js";+import {+ releasingSessionOwnerWorkflow,+ sessionCommandInboxWorkflow,+ sessionInboxForceClaimWorkflow,+ sessionInboxTakeoverWorkflow,+} from "#internal/testing/session-inbox-workflow.js";import { sessionHookPumpWorkflow } from "#internal/testing/session-hook-pump-workflow.js";import { waitForHook, startSessionOwner } from "#internal/testing/workflow-test-helpers.js";-import { getHookByToken, resumeHook, start } from "#internal/workflow/runtime.js";+import { getHookByToken, getWorld, resumeHook, start } from "#internal/workflow/runtime.js";import { sessionCommandHookToken } from "#execution/session-inbox/address.js";import {SESSION_INBOX_SESSION_ID_METADATA_KEY,@@ -52,4 +57,71 @@ describe("session command inbox integration", () => {if (status === "pending" || status === "running") await run.cancel();}});++ it("keeps payloads accepted before a forced takeover and can take the address back", async () => {+ const token = "http:session-inbox:takeover";+ const physicalToken = sessionInboxHookToken(token);+ const owner = await start(sessionInboxTakeoverWorkflow, [{ token }]);+ const runs: { cancel(): Promise<unknown>; status: Promise<string> }[] = [owner];+ try {+ await waitForHook(owner, { token: physicalToken });+ const before = [send("one"), send("two")];+ for (const payload of before) await resumeHook(physicalToken, payload);++ const claimer = await start(sessionInboxForceClaimWorkflow, [{ token }]);+ runs.push(claimer);+ // The claimer returns once the original owner has taken the address back.+ await claimer.returnValue;+ await resumeHook(physicalToken, send("three"));++ await expect(owner.returnValue).resolves.toEqual({+ afterReclaim: send("three"),+ beforeTakeover: before,+ });+ } finally {+ for (const run of runs) if ((await run.status) === "running") await run.cancel();+ }+ });++ it("returns a payload accepted just before the release commits", async () => {+ const alias = "http:session-inbox:release";+ const owner = await start(releasingSessionOwnerWorkflow, [+ { aliases: [alias], release: "session-inbox:release" },+ ]);+ const aliasToken = sessionInboxHookToken(alias);+ const world = await getWorld();+ const createEvent = world.events.create.bind(world.events);+ let sent = false;+ // Alice's message lands while the owner is disposing the address.+ const spy = vi.spyOn(world.events, "create").mockImplementation(async (...args) => {+ const [runId, event] = args;+ if (+ !sent &&+ runId === owner.runId &&+ event.eventType === "hook_disposed" &&+ event.eventData?.token === aliasToken+ ) {+ sent = true;+ await resumeHook(aliasToken, send("Alice writes as the owner lets go."));+ }+ return await createEvent(...args);+ });+ try {+ await waitForHook(owner, { token: aliasToken });+ await resumeHook("session-inbox:release", undefined);+ await vi.waitFor(() => expect(sent).toBe(true));+ await resumeHook(`${owner.runId}:handoff`, { kind: "active" });+ await expect(owner.returnValue).resolves.toEqual({+ activation: { kind: "active" },+ released: [send("Alice writes as the owner lets go.")],+ });+ } finally {+ spy.mockRestore();+ if ((await owner.status) === "running") await owner.cancel();+ }+ });});++function send(message: string) {+ return { kind: "send", payload: { message } } as const;+}diff --git a/packages/eve/src/execution/session-inbox/inbox.test.ts b/packages/eve/src/execution/session-inbox/inbox.test.tsindex 9bc6f4089..e0a63f311 100644--- a/packages/eve/src/execution/session-inbox/inbox.test.ts+++ b/packages/eve/src/execution/session-inbox/inbox.test.ts@@ -304,6 +304,202 @@ describe("createSessionInbox", () => {await inbox.dispose();});+ it("holds every payload behind the handover while interrupts still fire", async () => {+ const handover = createDeferred<IteratorResult<SessionInboxPayload>>();+ installHooks(+ createMockHook({+ reads: [+ Promise.resolve(resolved(send("direct"))),+ Promise.resolve(resolved(runtimeResult)),+ Promise.resolve(resolved(cancel)),+ ],+ token: "stable",+ }),+ createMockHook({+ reads: [handover.promise, Promise.resolve(resolved(finalPart("owner-a:1", 1)))],+ token: "channel",+ }),+ );+ const inbox = createSessionInbox("session-1");+ const delivered = vi.fn();+ inbox.onDelivery(delivered);+ const interrupted = nextInterrupt(inbox);+ const arrived = inbox.whenArrival();+ await inbox.claimSessionHooks(["stable", "channel"], { handover: "owner-a:1" });++ await expect(interrupted).resolves.toEqual(cancel);+ // Arrivals count even while nothing is readable.+ await arrived;+ expect(inbox.awaitingHandover).toBe(true);+ expect(inbox.drain()).toEqual([]);+ expect(inbox.hasPending()).toBe(false);+ expect(delivered).not.toHaveBeenCalled();++ const next = inbox.next();+ handover.resolve(resolved(part("owner-a:1", 0, send("accepted by a"))));+ await expect(next).resolves.toEqual(send("accepted by a"));+ expect(inbox.awaitingHandover).toBe(false);+ expect(inbox.drain()).toEqual([send("direct"), runtimeResult, cancel]);+ expect(delivered.mock.calls).toEqual([[send("accepted by a")], [send("direct")]]);+ await inbox.dispose();+ });++ it("opens on a handover that is the first payload its hook delivers and drops other attempts'", async () => {+ installHooks(+ createMockHook({+ reads: [+ Promise.resolve(resolved(part("owner-a:0", 0, send("stale")))),+ Promise.resolve(resolved(finalPart("owner-a:0", 1))),+ Promise.resolve(resolved(part("owner-a:1", 0, send("accepted by a")))),+ Promise.resolve(resolved(finalPart("owner-a:1", 1))),+ Promise.resolve(resolved(send("direct"))),+ ],+ token: "stable",+ }),+ );+ const inbox = createSessionInbox("session-1");+ await inbox.claimSessionHooks(["stable"], { handover: "owner-a:1" });++ await expect(readResult(inbox)).resolves.toEqual(resolved(send("accepted by a")));+ await expect(readResult(inbox)).resolves.toEqual(resolved(send("direct")));+ expect(inbox.hasPending()).toBe(false);+ await inbox.dispose();+ });++ it("applies handover parts in index order, once each, and opens only after every part", async () => {+ const first = createDeferred<IteratorResult<SessionInboxPayload>>();+ installHooks(+ createMockHook({+ reads: [+ Promise.resolve(resolved(send("direct"))),+ Promise.resolve(resolved(part("owner-a:1", 1, send("b")))),+ // A retried send step repeats its index.+ Promise.resolve(resolved(part("owner-a:1", 1, send("b")))),+ Promise.resolve(resolved(finalPart("owner-a:1", 2))),+ Promise.resolve(resolved(cancel)),+ first.promise,+ ],+ token: "stable",+ }),+ );+ const inbox = createSessionInbox("session-1");+ const pumped = nextInterrupt(inbox);+ await inbox.claimSessionHooks(["stable"], { handover: "owner-a:1" });+ await pumped;+ // The final part has arrived, but part 0 has not.+ expect(inbox.awaitingHandover).toBe(true);+ expect(inbox.drain()).toEqual([]);++ first.resolve(resolved(part("owner-a:1", 0, send("a"))));++ await vi.waitFor(() => expect(inbox.awaitingHandover).toBe(false));+ expect(inbox.drain()).toEqual([send("a"), send("b"), send("direct"), cancel]);+ await inbox.dispose();+ });++ it("stops waiting for an abandoned handover, ignoring other attempts", async () => {+ installHooks(+ createMockHook({+ reads: [Promise.resolve(resolved(send("direct"))), Promise.resolve(resolved(cancel))],+ token: "stable",+ }),+ );+ const inbox = createSessionInbox("session-1");+ const pumped = nextInterrupt(inbox);+ await inbox.claimSessionHooks(["stable"], { handover: "owner-a:1" });+ await pumped;+ const settled = inbox.whenHandoverSettled();++ inbox.abandonHandover("owner-a:0");+ expect(inbox.awaitingHandover).toBe(true);+ inbox.abandonHandover("owner-a:1");++ await settled;+ expect(inbox.drain()).toEqual([send("direct"), cancel]);+ await inbox.dispose();+ });++ it("takes back a held address on a fresh hook and places the handover after what it had queued", async () => {+ const replaced = createDeferred<IteratorResult<SessionInboxPayload>>();+ const handover = createDeferred<IteratorResult<SessionInboxPayload>>();+ installHooks(+ createMockHook({+ reads: [Promise.resolve(resolved(send("queued before"))), replaced.promise],+ token: "stable",+ }),+ createMockHook({+ reads: [+ Promise.resolve(resolved(send("after"))),+ handover.promise,+ Promise.resolve(resolved(finalPart("owner-a:1", 1))),+ ],+ token: "stable",+ }),+ );+ const inbox = createSessionInbox("session-1");+ await inbox.claimSessionHook("stable");+ await vi.waitFor(() => expect(inbox.hasPending()).toBe(true));++ await inbox.claimSessionHooks(["stable"], { force: true, handover: "owner-a:1" });+ replaced.reject(forceClaimed("owner-1"));+ handover.resolve(resolved(part("owner-a:1", 0, send("accepted by b"))));++ await vi.waitFor(() => expect(inbox.awaitingHandover).toBe(false));+ expect(inbox.claimedTokens).toEqual(["stable"]);+ expect(inbox.drain()).toEqual([send("queued before"), send("accepted by b"), send("after")]);+ await inbox.dispose();+ });++ it.each([+ {+ name: "every hook taken: resolves, and the gate no longer hides what was queued",+ reads: [forceClaimed("owner-b"), forceClaimed("owner-b")],+ takenOver: "resolved",+ },+ {+ name: "one hook taken: stays pending",+ reads: [forceClaimed("owner-b"), undefined],+ takenOver: "pending",+ },+ {+ name: "a reader failure: rejects as a failure, not a takeover",+ reads: [new Error("reader failed"), undefined],+ takenOver: "rejected",+ },+ ] as const)("reports a takeover once $name", async ({ reads, takenOver }) => {+ const outcomes = reads.map(() => createDeferred<IteratorResult<SessionInboxPayload>>());+ installHooks(+ createMockHook({+ reads: [Promise.resolve(resolved(send("accepted before"))), outcomes[0]!.promise],+ token: "stable",+ }),+ createMockHook({ reads: [outcomes[1]!.promise], token: "channel" }),+ );+ const inbox = createSessionInbox("session-1");+ await inbox.claimSessionHooks(["stable", "channel"], { handover: "owner-a:1" });+ const settled = inbox.whenTakenOver().then(+ () => "resolved",+ (error: unknown) => (error instanceof Error ? error.message : "rejected"),+ );+ reads.forEach((error, index) => {+ if (error !== undefined) outcomes[index]!.reject(error);+ });++ if (takenOver === "pending") {+ await vi.waitFor(() => expect(inbox.claimedTokens).toEqual(["channel"]));+ expect(inbox.takenOver).toBe(false);+ await inbox.dispose();+ await expect(settled).resolves.toBe("The session inbox was released before a takeover.");+ return;+ }+ await expect(settled).resolves.toBe(takenOver === "rejected" ? "reader failed" : takenOver);+ if (takenOver === "resolved") {+ expect(inbox.takenOver).toBe(true);+ expect(inbox.drain()).toEqual([send("accepted before")]);+ }+ await inbox.dispose();+ });+it("keeps every continuation alias active after later claims", async () => {const oldRead = createDeferred<IteratorResult<SessionInboxPayload>>();const replacementRead = createDeferred<IteratorResult<SessionInboxPayload>>();@@ -522,6 +718,24 @@ function installHooks(...hooks: readonly MockHook[]): void {});}+const cancel: SessionInboxPayload = { kind: "cancel" };+const runtimeResult: SessionInboxPayload = { kind: "runtime-action-result", results: [] };++function part(attemptKey: string, index: number, ...payloads: SessionInboxPayload[]) {+ return { attemptKey, index, kind: "handover", payloads } as SessionInboxPayload;+}++function finalPart(attemptKey: string, index: number): SessionInboxPayload {+ return { attemptKey, final: true, index, kind: "handover", payloads: [] };+}++function forceClaimed(claimedByRunId: string): Error {+ return Object.assign(new Error("Hook token was force-claimed."), {+ claimedByRunId,+ name: "HookForceClaimedError",+ });+}+function send(message: string): SessionInboxPayload {return { kind: "send", payload: { message } };}diff --git a/packages/eve/src/execution/session-inbox/inbox.ts b/packages/eve/src/execution/session-inbox/inbox.tsindex 19afa8f1e..72e8eddd4 100644--- a/packages/eve/src/execution/session-inbox/inbox.ts+++ b/packages/eve/src/execution/session-inbox/inbox.ts@@ -3,7 +3,11 @@ import { createHook, getWorkflowMetadata, type Hook } from "#compiled/@workflow/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 {+ claimHookOwnership,+ disposeHook,+ isHookForceClaimedError,+} from "#execution/hook-ownership.js";import type {WorkflowToolRunMessage,WorkflowToolRunMessageBatch,@@ -22,8 +26,25 @@ export interface SessionFailurePayload {readonly error: string;}+/**+ * One part of the previous owner's accepted-but-unread payloads after a+ * handoff. The runtime sends these commands; channel request bodies cannot+ * supply them.+ */+export interface SessionHandoverPayload {+ readonly kind: "handover";+ /** The handoff attempt this answers; see {@link SessionHookBatchClaimOptions.handover}. */+ readonly attemptKey: string;+ /** Parts apply in index order; a retried send repeats its index. */+ readonly index: number;+ /** The last part; reads resume once every part before it has been applied. */+ readonly final?: true;+ readonly payloads: readonly Exclude<SessionInboxPayload, SessionHandoverPayload>[];+}+export type SessionInboxPayload =| SessionFailurePayload+ | SessionHandoverPayload| HookPayload| SessionCommand| WorkflowToolRunMessage@@ -35,13 +56,19 @@ interface Source {registered?: Promise<void>;stopping: boolean;closed: boolean;+ /** A forced claim by this inbox took the token over from this source. */+ replaced: boolean;}+/**+ * While a handover is awaited (see {@link SessionHookBatchClaimOptions.handover}),+ * reads expose nothing; interrupt handlers still fire on arrival.+ */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.+ * `undefined` once no hook can deliver any more (released or taken over).+ * 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. */@@ -60,21 +87,67 @@ export interface SessionInboxReader {* consumer still processes it in order.*/onInterrupt(handler: (payload: SessionInboxPayload) => void): () => void;- /** Observes deliveries without consuming them; replays unread deliveries on subscription. */+ /**+ * Observes readable deliveries without consuming them; replays unread+ * deliveries on subscription and when a handover arrives, so handlers must+ * be idempotent.+ */onDelivery(handler: (payload: SessionInboxPayload) => void): () => void;/** Requeues payloads a successor handed back, ahead of everything pumped since. */restore(payloads: readonly SessionInboxPayload[]): void;}+export interface SessionHookClaimOptions {+ /**+ * Take the address over from the run that holds it instead of conflicting.+ * Still rejects with `HookConflictError` when the holder's runtime cannot be+ * taken from; throws `FatalError` when the World does not support it. A+ * token this inbox already holds is claimed again on a fresh hook.+ */+ readonly force?: boolean;+}++export interface SessionHookBatchClaimOptions extends SessionHookClaimOptions {+ /**+ * Expect a `handover` for this attempt key. Before any hook is created,+ * reads stop exposing anything; as its parts arrive on any hook, their+ * payloads take their place after what was queued at this call and ahead of+ * everything accepted since. Reads resume after the final part.+ */+ readonly handover?: string;+}+export interface SessionInboxOwnership {/** Logical tokens currently claimed, in claim order. */readonly claimedTokens: readonly string[];- claimSessionHook(token: string): Promise<void>;+ claimSessionHook(token: string, options?: SessionHookClaimOptions): Promise<void>;/** Registers every token as one batch; all claims settle before the first failure propagates. */- claimSessionHooks(tokens: readonly string[]): Promise<void>;+ claimSessionHooks(+ tokens: readonly string[],+ options?: SessionHookBatchClaimOptions,+ ): Promise<void>;}export interface SessionInbox extends SessionInboxReader, SessionInboxOwnership {}export interface SessionInboxHandle extends SessionInbox {+ /** A handover is expected and has not arrived; the session must not move again until it does. */+ readonly awaitingHandover: boolean;+ /** Resolves once no handover is awaited: it arrived, was abandoned, or the inbox closed. */+ whenHandoverSettled(): Promise<void>;+ /** Stops waiting for `attemptKey`'s handover, which can no longer arrive; queued payloads become readable. */+ abandonHandover(attemptKey: string): void;+ /** Resolves the first time a read waits on an awaited handover. */+ whenBlockedOnHandover(): Promise<void>;+ /** Resolves when the next payload arrives on any hook, readable or not. */+ whenArrival(): Promise<void>;+ /** Another run force-claimed every hook this inbox held. */+ readonly takenOver: boolean;+ /**+ * Resolves once another run has force-claimed every hook this inbox held.+ * Every payload delivered before the takeover is queued by then. Rejects if+ * a reader fails, if the inbox is released or disposed first, or once+ * `signal` aborts.+ */+ whenTakenOver(signal?: AbortSignal): Promise<void>;dispose(): Promise<void>;/** Disposes every hook and returns each payload the hooks accepted but the owner never read. */release(): Promise<SessionInboxPayload[]>;@@ -89,6 +162,10 @@ export function isInterrupt(value: SessionInboxPayload): boolean {);}+function isDelivery(value: SessionInboxPayload): boolean {+ return value.kind === "send" || value.kind === "deliver";+}+/*** 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@@ -103,6 +180,22 @@ export function createSessionInbox(sessionId: string): SessionInboxHandle {const interruptHandlers = new Set<(payload: SessionInboxPayload) => void>();const deliveryHandlers = new Set<(payload: SessionInboxPayload) => void>();let failure: { error: unknown } | undefined;+ /**+ * `index` is where the next part's payloads go in `queue`; `parts` holds+ * parts that arrived ahead of `nextPart`.+ */+ let handover:+ | {+ readonly attemptKey: string;+ index: number;+ nextPart: number;+ readonly parts: Map<number, SessionHandoverPayload>;+ }+ | undefined;+ const blockedWaiters = new Set<() => void>();+ const arrivalWaiters = new Set<() => void>();+ let takenOver = false;+ let stopped = false;const notify = (): void => {for (const resolve of waiters) resolve();@@ -110,6 +203,58 @@ export function createSessionInbox(sessionId: string): SessionInboxHandle {};const wait = (): Promise<void> => new Promise((resolve) => waiters.add(resolve));const closed = (): boolean => sources.every((source) => source.closed || source.stopping);+ // With no source left the handover can never arrive, so what is queued stays readable.+ const gated = (): boolean => handover !== undefined && sources.length > 0;+ const hasReadable = (): boolean => !gated() && queue.length > 0;+ const throwIfFailed = (): void => {+ if (failure !== undefined) throw failure.error;+ };+ const observe = (+ handlers: ReadonlySet<(payload: SessionInboxPayload) => void>,+ payloads: readonly SessionInboxPayload[],+ accepts: (payload: SessionInboxPayload) => boolean,+ ): void => {+ for (const payload of payloads)+ if (accepts(payload)) for (const handler of handlers) handler(payload);+ };++ const openHandover = (): void => {+ handover = undefined;+ // Deliveries held back while the handover was awaited were never observed.+ observe(deliveryHandlers, queue, isDelivery);+ notify();+ };+ const blockedOnHandover = (): void => {+ if (!gated()) return;+ for (const resolve of blockedWaiters) resolve();+ blockedWaiters.clear();+ };++ const acceptHandover = (part: SessionHandoverPayload): void => {+ // A retried send step repeats its own key and index, so any other key+ // belongs to an attempt this inbox is no longer waiting for.+ const current = handover;+ if (current === undefined || part.attemptKey !== current.attemptKey) return;+ if (part.index < current.nextPart || current.parts.has(part.index)) return;+ current.parts.set(part.index, part);+ const restored: SessionInboxPayload[] = [];+ while (true) {+ const next = current.parts.get(current.nextPart);+ if (next === undefined) break;+ if (next.final === true) {+ observe(interruptHandlers, restored, isInterrupt);+ openHandover();+ return;+ }+ current.parts.delete(current.nextPart);+ current.nextPart += 1;+ queue.splice(current.index, 0, ...next.payloads);+ current.index += next.payloads.length;+ restored.push(...next.payloads);+ }+ observe(interruptHandlers, restored, isInterrupt);+ notify();+ };// 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`.@@ -120,20 +265,35 @@ export function createSessionInbox(sessionId: string): SessionInboxHandle {const result = await iterator.next();if (result.done) break;const payload = result.value;+ for (const resolve of arrivalWaiters) resolve();+ arrivalWaiters.clear();if (payload.kind === "workflow-batch") {// A run's messages carry no deliveries or interrupts.queue.push(...payload.messages);notify();continue;}+ if (payload.kind === "handover") {+ acceptHandover(payload);+ continue;+ }queue.push(payload);- if (payload.kind === "send" || payload.kind === "deliver")- for (const handler of deliveryHandlers) handler(payload);- if (isInterrupt(payload)) for (const handler of interruptHandlers) handler(payload);+ if (!gated()) observe(deliveryHandlers, [payload], isDelivery);+ observe(interruptHandlers, [payload], isInterrupt);notify();}} catch (error) {- if (!source.stopping) failure = { error };+ // A replaced source's payloads accepted before the replacement are+ // already queued; its fresh hook carries on.+ if (source.stopping || source.replaced) return;+ // The SDK delivers every payload accepted before a takeover first, so+ // the queue already holds them; the address now belongs to another run.+ if (isHookForceClaimedError(error)) {+ sources.splice(sources.indexOf(source), 1);+ takenOver = true;+ } else {+ failure = { error };+ }} finally {source.closed = true;notify();@@ -142,6 +302,9 @@ export function createSessionInbox(sessionId: string): SessionInboxHandle {const stop = async (): Promise<SessionInboxPayload[]> => {const released = sources.splice(0);+ handover = undefined;+ takenOver = false;+ stopped = true;for (const source of released) source.stopping = true;notify();await Promise.all(released.map(({ hook }) => disposeHook(hook)));@@ -150,29 +313,52 @@ export function createSessionInbox(sessionId: string): SessionInboxHandle {return accepted;};- const claimSessionHook = async (token: string): Promise<void> => {+ const claimSessionHook = async (+ token: string,+ options: SessionHookClaimOptions = {},+ ): Promise<void> => {if (!token) throw new Error("A session alias requires a nonempty continuation token.");+ const force = options.force === true;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.");+ if (existing !== undefined && !force) return await existing.registered;+ if (existing === undefined && sources.length >= 256)+ throw new Error("A session may claim at most 256 addresses.");const source: Source = {token,hook: createHook<SessionInboxPayload | WorkflowToolRunMessageBatch>({token: sessionInboxHookToken(token),metadata: { sessionId },+ ...(force && { experimental_force: true }),}),stopping: false,closed: false,+ replaced: false,};// Reserve the slot before awaiting registration: parallel claims retain// deterministic order and duplicate calls cannot create another hook.- sources.push(source);+ if (existing === undefined) {+ sources.push(source);+ } else {+ // Workflow lets a run take a token from its own earlier hook. This also+ // reclaims a token whose takeover the old pump has not observed yet.+ existing.replaced = true;+ sources.splice(sources.indexOf(existing), 1, source);+ }+ stopped = false;try {source.registered = claimHookOwnership(source.hook);await source.registered;+ // A takeover this run has reclaimed from no longer counts toward the next one.+ takenOver = false;void pump(source);} catch (error) {- sources.splice(sources.indexOf(source), 1);+ if (existing === undefined || existing.closed) {+ // A replaced source whose pump already returned can never deliver again.+ sources.splice(sources.indexOf(source), 1);+ } else {+ existing.replaced = false;+ sources.splice(sources.indexOf(source), 1, existing);+ }throw error;}};@@ -181,28 +367,67 @@ export function createSessionInbox(sessionId: string): SessionInboxHandle {get claimedTokens() {return sources.map(({ token }) => token);},+ get awaitingHandover() {+ return handover !== undefined;+ },+ async whenHandoverSettled() {+ while (handover !== undefined) await wait();+ },+ abandonHandover(attemptKey) {+ if (handover?.attemptKey === attemptKey) openHandover();+ },+ whenBlockedOnHandover() {+ return new Promise((resolve) => blockedWaiters.add(resolve));+ },+ whenArrival() {+ return new Promise((resolve) => arrivalWaiters.add(resolve));+ },+ get takenOver() {+ return takenOver && sources.length === 0;+ },claimSessionHook,- async claimSessionHooks(tokens) {- const outcomes = await Promise.allSettled([...new Set(tokens)].map(claimSessionHook));+ async claimSessionHooks(tokens, options = {}) {+ if (options.handover !== undefined)+ handover = {+ attemptKey: options.handover,+ index: queue.length,+ nextPart: 0,+ parts: new Map(),+ };+ const outcomes = await Promise.allSettled(+ [...new Set(tokens)].map((token) => claimSessionHook(token, options)),+ );for (const outcome of outcomes) if (outcome.status === "rejected") throw outcome.reason;},+ async whenTakenOver(signal) {+ // Wakes the loop now rather than at the next arrival, so no waiter lingers.+ signal?.addEventListener("abort", notify, { once: true });+ while (sources.length > 0 || !takenOver) {+ throwIfFailed();+ if (stopped) throw new Error("The session inbox was released before a takeover.");+ if (signal?.aborted === true) throw signal.reason;+ await wait();+ }+ },async next() {while (true) {- if (failure !== undefined) throw failure.error;- if (queue.length > 0) return queue.shift();+ throwIfFailed();+ if (hasReadable()) return queue.shift();if (closed()) return undefined;+ blockedOnHandover();await wait();}},drain() {- if (failure !== undefined) throw failure.error;- return queue.splice(0);+ throwIfFailed();+ return gated() ? [] : queue.splice(0);},takeLeading<T extends SessionInboxPayload>(accepts: (payload: SessionInboxPayload) => payload is T,): T[] {- if (failure !== undefined) throw failure.error;+ throwIfFailed();const taken: T[] = [];+ if (gated()) return taken;for (let next = queue[0]; next !== undefined && accepts(next); next = queue[0]) {taken.push(next);queue.shift();@@ -210,11 +435,14 @@ export function createSessionInbox(sessionId: string): SessionInboxHandle {return taken;},hasPending() {- if (failure !== undefined) throw failure.error;- return queue.length > 0;+ throwIfFailed();+ return hasReadable();},async whenPending() {- while (failure === undefined && queue.length === 0 && !closed()) await wait();+ while (failure === undefined && !hasReadable() && !closed()) {+ blockedOnHandover();+ await wait();+ }},onInterrupt(handler) {interruptHandlers.add(handler);@@ -222,8 +450,7 @@ export function createSessionInbox(sessionId: string): SessionInboxHandle {},onDelivery(handler) {deliveryHandlers.add(handler);- for (const payload of queue)- if (payload.kind === "send" || payload.kind === "deliver") handler(payload);+ if (!gated()) for (const payload of queue) if (isDelivery(payload)) handler(payload);return () => deliveryHandlers.delete(handler);},restore(payloads) {@@ -232,6 +459,7 @@ export function createSessionInbox(sessionId: string): SessionInboxHandle {// Restored payloads were accepted before anything the reclaimed pumps// have enqueued since, so they must precede the current queue.queue.unshift(...payloads);+ if (handover !== undefined) handover.index += payloads.length;notify();},async dispose() {diff --git a/packages/eve/src/execution/session-inbox/resume.ts b/packages/eve/src/execution/session-inbox/resume.tsindex 7103abd37..28c69d237 100644--- a/packages/eve/src/execution/session-inbox/resume.ts+++ b/packages/eve/src/execution/session-inbox/resume.ts@@ -37,9 +37,10 @@ export interface ResumedSessionInboxHook {}/**- * 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+ * Resumes the current owner with the current command shape. Owners on+ * handoff version 3 never leave an address unowned. An older owner releases+ * its hooks before its successor claims them and leaves a marker for that+ * interval, so delivery retries instead of* reporting the session gone and letting a channel start a replacement.* The retry window bounds this request, not the handoff: a marker that* outlives it throws {@link SessionHandoffPendingError}.diff --git a/packages/eve/src/execution/session/entry-handoff-lifetime.integration.test.ts b/packages/eve/src/execution/session/entry-handoff-lifetime.integration.test.tsindex af9349786..1320add6f 100644--- a/packages/eve/src/execution/session/entry-handoff-lifetime.integration.test.ts+++ b/packages/eve/src/execution/session/entry-handoff-lifetime.integration.test.ts@@ -6,7 +6,10 @@ import { hydrateStepReturnValue, hydrateWorkflowArguments } from "@workflow/coreimport { captureTurnEvents } from "#internal/testing/events.js";import { createTestRuntime } from "#internal/testing/app-harness.js";import { captureConsoleOutput, workflowSdkNotice } from "#internal/testing/log-records.js";-import { waitForParkedTurnStep } from "#internal/testing/session-test-helpers.js";+import {+ readTurnStepStates,+ waitForParkedTurnStep,+} from "#internal/testing/session-test-helpers.js";import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";import { workflowEntry } from "#execution/session/entry.js";import {@@ -354,6 +357,107 @@ describe("workflowEntry integration", () => {// Successors start on the test's synthetic deployment, not the local world's.expect(output.unexpected(workflowSdkNotice.unpinnedDelivery)).toEqual([]);});++ it("runs a reply that races the eager transfer once, on the successor", async () => {+ const runtime = await createTestRuntime({+ agent: { name: "workflow-entry-compaction-race" },+ });++ await runtime.run(async () => {+ const world = await getWorld();+ const anchor = await startSessionOwner(workflowEntry, [+ {+ kind: "initial",+ sessionTimeoutMs: false,+ ownerDeploymentId: "dpl_a",+ input: { message: "Alice starts a long planning session." },+ serializedContext: buildSerializedContext({+ acceptedDeploymentId: "dpl_a",+ channelKind: "http",+ }),+ },+ ]);+ const stream = captureTurnEvents(anchor);+ const workflowRuntime = createWorkflowRuntime({+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),+ });+ const inboxToken = sessionInboxHookToken(sessionCommandHookToken(anchor.runId));+ const reply = "Bob replies just as the session moves.";+ let replied = false;+ const createEvent = world.events.create.bind(world.events);+ // Bob's reply reaches the owner once it has started moving the session.+ vi.spyOn(world.events, "create").mockImplementation(async (...args) => {+ const [runId, event] = args;+ const stepName = (event.eventData as { stepName?: string } | undefined)?.stepName;+ if (+ !replied &&+ runId === anchor.runId &&+ event.eventType === "step_started" &&+ stepName?.endsWith("//startSuccessorStep") === true+ ) {+ replied = true;+ await resumeHook(inboxToken, {+ kind: "send",+ payload: { message: reply },+ turnPolicy: "queue",+ });+ }+ return createEvent(...args);+ });+ try {+ expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");+ await waitForParkedTurnStep(anchor.runId);++ await workflowRuntime.dispatchSession({+ command: { kind: "compact" },+ sessionId: anchor.runId,+ });+ expect((await stream.nextTurn()).map((event) => event.type)).toContain(+ "compaction.completed",+ );+ const replyTurn = await stream.nextTurn();+ expect(+ replyTurn.some(+ (event) =>+ event.type === "message.completed" && event.data.message?.includes(reply) === true,+ ),+ ).toBe(true);+ expect(replied).toBe(true);++ let successor: Awaited<ReturnType<typeof waitForCommandHookOwner>> | undefined;+ await vi.waitFor(async () => {+ successor = await waitForCommandHookOwner(inboxToken);+ expect(successor.runId).not.toBe(anchor.runId);+ });+ await waitForParkedTurnStep(successor!.runId);+ // The longest saved history is the one that accumulated every turn.+ const history = (await readTurnStepStates(successor!.runId))+ .map((state) => state.history)+ .reduce(+ (longest, entries) => (entries.length > longest.length ? entries : longest),+ [],+ );+ expect(+ history.filter(+ (entry) => entry.role === "user" && JSON.stringify(entry.content).includes(reply),+ ),+ ).toHaveLength(1);+ const startSteps = (await world.steps.list({ runId: anchor.runId })).data.filter((step) =>+ step.stepName.endsWith("//startSuccessorStep"),+ );+ expect(startSteps).toHaveLength(1);+ // The owner's only turns are the opening one and the compaction.+ expect(+ (await world.steps.list({ runId: anchor.runId })).data.filter((step) =>+ step.stepName.endsWith("//turnStep"),+ ),+ ).toHaveLength(2);+ } finally {+ stream.dispose();+ await anchor.cancel();+ }+ });+ });});});diff --git a/packages/eve/src/execution/session/entry-handoff.integration.test.ts b/packages/eve/src/execution/session/entry-handoff.integration.test.tsindex 8d00cb715..20972f81a 100644--- a/packages/eve/src/execution/session/entry-handoff.integration.test.ts+++ b/packages/eve/src/execution/session/entry-handoff.integration.test.ts@@ -1,8 +1,12 @@-import { startSessionOwner } from "#internal/testing/workflow-test-helpers.js";+import { startSessionOwner, waitForHook } from "#internal/testing/workflow-test-helpers.js";+import {+ parkedAnchorWorkflow,+ releasingSessionOwnerWorkflow,+} from "#internal/testing/session-inbox-workflow.js";import type { HandoffWorkflowEntryInput } from "#execution/session/entry-input.js";-import type { RunCreatedEventRequest } from "@workflow/world";+import type { AnyEventRequest, RunCreatedEventRequest } from "@workflow/world";import { assert, describe, expect, it, vi } from "vitest";-import { getWorld, resumeHook } from "#internal/workflow/runtime.js";+import { getRun, getWorld, resumeHook, start } from "#internal/workflow/runtime.js";import { dehydrateWorkflowArguments, hydrateWorkflowArguments } from "@workflow/core/serialization";import { captureTurnEvents } from "#internal/testing/events.js";import { createTestRuntime } from "#internal/testing/app-harness.js";@@ -14,6 +18,7 @@ import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-aimport { workflowEntry } from "#execution/session/entry.js";import { SESSION_CHECKPOINT_VERSION } from "#execution/session/handoff.js";import {+ isSessionInboxHookToken,sessionCommandHookToken,sessionInboxHookToken,} from "#execution/session-inbox/address.js";@@ -26,304 +31,167 @@ const HANDOFF_LOG = "[eve:execution.handoff]";describe("workflowEntry integration", () => {describe("deployment handoff", () => {- it("recovers the original owner when target rejects nested state", async () => {- const output = captureConsoleOutput();- const runtime = await createTestRuntime({ agent: { name: "handoff-validation" } });+ it("processes what the owner accepted during the move on the successor, after the trigger", async () => {+ const runtime = await createTestRuntime({ agent: { name: "handoff-accepted-during-move" } });await runtime.run(async () => {- const anchor = await startSessionOwner(workflowEntry, [- {- kind: "initial",- ownerDeploymentId: "dpl_a",- sessionTimeoutMs: false,- input: { message: "Alice opens a research session." },- serializedContext: buildSerializedContext({- acceptedDeploymentId: "dpl_a",- channelKind: "http",- }),+ const { anchor, stream, workflowRuntime } = await openSession();+ const inbox = stableInbox(anchor.runId);+ // Alice's messages reach the owner while it is starting the successor.+ const world = await instrumentWorld({+ async beforeEvent(_runId, event) {+ if (!isCandidateCreated(event)) return;+ for (let index = 0; index < 3; index++)+ await resumeHook(inbox, aliceSends(`Alice sends input ${index} during the move.`));},- ]);- 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 [- HandoffWorkflowEntryInput,- ];- expect(args[0].kind).toBe("handoff");- candidateId = runId;- const session = args[0].checkpoint.sessionState.snapshot.session;- Object.assign(session, {- // Input the source still holds is pending work the target refuses.- state: {- ...session.state,- "eve.harness.turnState": {- grants: [],- queued: { message: "Alice asks for a summary." },- suspended: [],- },- },- });-- 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();+ expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");await waitForParkedTurnStep(anchor.runId);- await workflowRuntime.dispatchSession({- command: handoffFollowUp(- "dpl_b",- "Bob requests the next research step.",- "validation-trigger",- ),- sessionId: anchor.runId,- });++ await expect(+ workflowRuntime.dispatchSession({+ command: handoffFollowUp("dpl_b", "Bob requests the next step.", "trigger"),+ sessionId: anchor.runId,+ }),+ ).resolves.toMatchObject({ sessionId: anchor.runId, status: "accepted" });++ const successor = await waitForNewOwner(anchor.runId, anchor.runId);+ const history = await waitForUserMessages(successor.runId, "Alice sends input 2");+ const positions = [+ "Bob requests the next step.",+ ...[0, 1, 2].map((index) => `Alice sends input ${index} during the move.`),+ ].map((message) => positionOf(history, message));+ expect(positions.every((position) => position >= 0)).toBe(true);+ expect(positions).toEqual([...positions].sort((a, b) => a - b));+ // The trigger ran once, on the successor: the owner kept its single opening turn.+ expect(await readTurnStepStates(anchor.runId)).toHaveLength(1);+ } finally {+ world.restore();+ stream.dispose();+ await anchor.cancel();+ }+ });+ });++ // Deliveries racing the forced claim can be lost in @workflow/world-local+ // until https://github.com/vercel/workflow/pull/4924 ships; re-enable then.+ it.skip("answers alias deliveries with accepted at every step of the move", async () => {+ const output = captureConsoleOutput();+ const runtime = await createTestRuntime({ agent: { name: "handoff-alias-every-step" } });+ const continuationToken = "http:handoff-alias-every-step";+ await runtime.run(async () => {+ const { anchor, stream, workflowRuntime } = await openSession({ continuationToken });+ const deliveries: { message: string; result: Promise<unknown> }[] = [];+ let moving = false;+ // Deliveries race the move: none waits for the one before to be accepted.+ const world = await instrumentWorld({+ beforeEvent(runId, event) {+ if (isCandidateCreated(event)) moving = true;+ if (!moving) return;+ const onCandidate = runId !== anchor.runId;+ if (onCandidate && event.eventType === "step_started") {+ const stepName = (event.eventData as { stepName?: string }).stepName ?? "";+ if (stepName.endsWith("//turnStep")) moving = false;+ }+ const durable =+ event.eventType === "hook_created" ||+ event.eventType === "hook_disposed" ||+ event.eventType === "step_started" ||+ event.eventType === "step_completed";+ if (!durable) return;+ const message = `Alice writes at move step ${deliveries.length}.`;+ const result = workflowRuntime.dispatchContinuation({+ command: handoffFollowUp("dpl_b", message, `step-${deliveries.length}`),+ continuationToken,+ });+ deliveries.push({ message, result });+ },+ });+ try {expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");- assert(candidateId !== undefined);- 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([]);- await vi.waitFor(- async () => {- 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);- // The waiting event is streamed before the step's return value is persisted.- expect(turns.every((step) => step.output !== undefined)).toBe(true);- },- { timeout: 5000 },- );- const histories = (await readTurnStepStates(anchor.runId)).map((state) => state.history);- const deliveries = histories.map((history) =>- history.filter(- (message) =>- message.role === "user" &&- JSON.stringify(message.content).includes("Bob requests the next research step."),- ),+ await waitForParkedTurnStep(anchor.runId);++ await expect(+ workflowRuntime.dispatchContinuation({+ command: handoffFollowUp("dpl_b", "Bob requests the next step.", "trigger"),+ continuationToken,+ }),+ ).resolves.toMatchObject({ sessionId: anchor.runId, status: "accepted" });++ const successor = await waitForNewOwner(anchor.runId, anchor.runId);+ // The move ends when the successor starts its first turn.+ await vi.waitFor(() => expect(moving).toBe(false), { timeout: 10_000 });+ expect(deliveries.length).toBeGreaterThan(3);+ for (const { result } of deliveries) {+ await expect(result).resolves.toEqual({+ deliveryId: expect.any(String),+ sessionId: anchor.runId,+ status: "accepted",+ });+ }+ const history = await waitForUserMessages(+ successor.runId,+ ...deliveries.map(({ message }) => message),);- expect(deliveries.map((messages) => messages.length).sort()).toEqual([0, 1]);- } finally {- created.mockRestore();- queued.mockRestore();- await workflowRuntime.dispatchSession({- command: { kind: "reset", reason: "validation test" },+ for (const { message } of deliveries) expect(countOf(history, message), message).toBe(1);+ await expect(+ waitForCommandHookOwner(sessionInboxHookToken(continuationToken)),+ ).resolves.toMatchObject({ runId: successor.runId });+ await expect(workflowRuntime.resolveContinuation(continuationToken)).resolves.toEqual({sessionId: anchor.runId,});- await anchor.returnValue;+ } finally {+ world.restore();stream.dispose();+ await anchor.cancel();}});- expect(output.lines).toContainEqual(- expect.stringContaining(workflowSdkNotice.unpinnedDelivery),- );- expect(output.lines).toContainEqual(expect.stringContaining(workflowSdkNotice.maxRetries));- expect(output.lines).toContainEqual(- expect.stringContaining(`${HANDOFF_LOG} session handoff failed`),- );- expect(- output.unexpected(- workflowSdkNotice.unpinnedDelivery,- workflowSdkNotice.maxRetries,- HANDOFF_LOG,- ),- ).toEqual([]);+ expect(output.unexpected(workflowSdkNotice.unpinnedDelivery)).toEqual([]);});it("stops attempting a deployment that cannot read the checkpoint version", async () => {const output = captureConsoleOutput();const runtime = await createTestRuntime({ agent: { name: "handoff-checkpoint-version" } });await runtime.run(async () => {- const anchor = await startSessionOwner(workflowEntry, [- {- kind: "initial",- ownerDeploymentId: "dpl_a",- sessionTimeoutMs: false,- input: { message: "Alice opens a research session." },- serializedContext: buildSerializedContext({- acceptedDeploymentId: "dpl_a",- channelKind: "http",- }),+ const { anchor, stream, workflowRuntime } = await openSession();+ // As after a rollback: the successor's build cannot read what this owner wrote.+ const world = await instrumentWorld({+ rewriteCandidate(input) {+ Object.assign(input.checkpoint, { version: SESSION_CHECKPOINT_VERSION + 1 });+ return input;},- ]);- const stream = captureTurnEvents(anchor);- const world = await getWorld();- const workflowRuntime = createWorkflowRuntime({- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),- });- const rewritten = new Map<string, Promise<unknown>>();- const candidateIds = new Set<string>();- // Rewrites only the candidate checkpoint version to one a newer eve build- // wrote, as after a rollback. Owner and candidate both run this build, so- // the test covers successor validation and memoization on a current owner.- const newerCheckpointInput = (runId: string, encoded: unknown): Promise<unknown> => {- let pending = rewritten.get(runId);- if (pending === undefined) {- pending = (async () => {- const args = (await hydrateWorkflowArguments(encoded, runId, undefined)) as [- HandoffWorkflowEntryInput,- ];- expect(args[0].kind).toBe("handoff");- candidateIds.add(runId);- Object.assign(args[0].checkpoint, { version: SESSION_CHECKPOINT_VERSION + 1 });-- 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 newerCheckpointInput(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 newerCheckpointInput(- message.runId,- message.runInput.input,- );- }- return queue(...args);});- const handoffMarkerClaims = async (): Promise<number> => {- const events = await world.events.list({- pagination: { limit: 1000 },- resolveData: "all",- runId: anchor.runId,- });- return events.data.filter(- (event) =>- event.eventType === "hook_created" &&- event.eventData.token.startsWith("eve:inbox:handoff:"),- ).length;- };try {await stream.nextTurn();await waitForParkedTurnStep(anchor.runId);-- await workflowRuntime.dispatchSession({- command: handoffFollowUp("dpl_b", "Bob requests the first research step.", "version-1"),- sessionId: anchor.runId,- });- expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");- await waitForParkedTurnStep(anchor.runId, 2);- expect(candidateIds.size).toBe(1);- const markersAfterAttempt = await handoffMarkerClaims();- expect(markersAfterAttempt).toBeGreaterThan(0);-- await workflowRuntime.dispatchSession({- command: handoffFollowUp(- "dpl_b",- "Bob requests the second research step.",- "version-2",- ),- sessionId: anchor.runId,- });- expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");- await waitForParkedTurnStep(anchor.runId, 3);- // The remembered target is skipped before any candidate or marker exists.- expect(candidateIds.size).toBe(1);- expect(await handoffMarkerClaims()).toBe(markersAfterAttempt);-- const [candidateId] = candidateIds;- const candidateEvents = await world.events.list({- pagination: { limit: 1000 },- resolveData: "none",- runId: candidateId!,- });+ const claimsBefore = await countSessionHookClaims(anchor.runId);+ for (const [index, message] of [+ "Bob requests the first research step.",+ "Bob requests the second research step.",+ ].entries()) {+ await workflowRuntime.dispatchSession({+ command: handoffFollowUp("dpl_b", message, `version-${index}`),+ sessionId: anchor.runId,+ });+ expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");+ await waitForParkedTurnStep(anchor.runId, index + 2);+ }+ // The remembered target is skipped before any candidate exists.+ expect(world.candidates.size).toBe(1);+ const [candidateId] = world.candidates.keys();+ const candidateEvents = await world.events(candidateId!);// An unreadable version is an answer, not a fault: validation runs once.expect(- candidateEvents.data.filter(+ candidateEvents.filter((event) => event.eventType === "step_failed" || event.eventType === "step_retrying",),).toEqual([]);-- expect(- (- await waitForCommandHookOwner(- sessionInboxHookToken(sessionCommandHookToken(anchor.runId)),- )- ).runId,- ).toBe(anchor.runId);- await vi.waitFor(- async () => {- // Recorded steps are not returned in turn order; the settled- // history is the one that accumulated every turn.- const settled = (await readTurnStepStates(anchor.runId))- .map((state) => state.history)- .reduce<readonly unknown[]>(- (longest, history) => (history.length > longest.length ? history : longest),- [],- ) as readonly { role: string; content: unknown }[];- const delivered = (message: string) =>- settled.filter(- (entry) =>- entry.role === "user" && JSON.stringify(entry.content).includes(message),- );- expect(delivered("Bob requests the first research step.")).toHaveLength(1);- expect(delivered("Bob requests the second research step.")).toHaveLength(1);- },- { timeout: 5000 },+ expect((await waitForCommandHookOwner(stableInbox(anchor.runId))).runId).toBe(+ anchor.runId,);+ // The candidate never held a session address, so the owner reclaimed nothing.+ expect(await listSessionHookTokens(candidateId!)).toEqual([]);+ expect(await countSessionHookClaims(anchor.runId)).toBe(claimsBefore);// A different deployment is unproven, so it earns a fresh attempt.await workflowRuntime.dispatchSession({@@ -331,396 +199,585 @@ describe("workflowEntry integration", () => {sessionId: anchor.runId,});await stream.nextTurn();- const successor = await waitForCommandHookOwner(- sessionInboxHookToken(sessionCommandHookToken(anchor.runId)),- );- expect(successor.runId).not.toBe(anchor.runId);+ await waitForNewOwner(anchor.runId, anchor.runId);} finally {- created.mockRestore();- queued.mockRestore();+ world.restore();stream.dispose();await anchor.cancel();}});- expect(output.lines).toContainEqual(- expect.stringContaining(workflowSdkNotice.unpinnedDelivery),- );// Both sides explain the refusal once: the successor names the version it// cannot read and the owner names the target it keeps the session from.- expect(- output.lines.filter((line) => line.startsWith(`${HANDOFF_LOG} session handoff refused`)),- ).toHaveLength(1);+ for (const prefix of ["session handoff refused", "session handoff failed"]) {+ expect(+ output.lines.filter((line) => line.startsWith(`${HANDOFF_LOG} ${prefix}`)),+ ).toHaveLength(1);+ }+ expect(output.unexpected(workflowSdkNotice.unpinnedDelivery, HANDOFF_LOG)).toEqual([]);+ });++ it("remembers a successor that claims ordinarily as unable to take over", async () => {+ const output = captureConsoleOutput();+ const runtime = await createTestRuntime({ agent: { name: "handoff-older-successor" } });+ await runtime.run(async () => {+ const { anchor, stream, workflowRuntime } = await openSession();+ // A build older than this protocol reads the input as a released source's.+ const world = await instrumentWorld({+ rewriteCandidate({ attemptKey: _attemptKey, hookTokens: _hookTokens, ...input }) {+ return { ...input, handoffVersion: 2 };+ },+ });+ try {+ await stream.nextTurn();+ await waitForParkedTurnStep(anchor.runId);+ const messages = ["Bob requests the first step.", "Bob requests the second step."];+ for (const [index, message] of messages.entries()) {+ await workflowRuntime.dispatchSession({+ command: handoffFollowUp("dpl_b", message, `older-${index}`),+ sessionId: anchor.runId,+ });+ expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");+ await waitForParkedTurnStep(anchor.runId, index + 2);+ }+ expect(world.candidates.size).toBe(1);+ expect((await waitForCommandHookOwner(stableInbox(anchor.runId))).runId).toBe(+ anchor.runId,+ );+ const history = await waitForUserMessages(anchor.runId, messages[1]!);+ for (const message of messages) expect(countOf(history, message)).toBe(1);+ } finally {+ world.restore();+ stream.dispose();+ await anchor.cancel();+ }+ });expect(output.lines.filter((line) => line.startsWith(`${HANDOFF_LOG} session handoff failed`)),).toHaveLength(1);- // No validation retry: the SDK never reports an exhausted step.expect(output.unexpected(workflowSdkNotice.unpinnedDelivery, HANDOFF_LOG)).toEqual([]);});- it("continues an eve 0.66 checkpoint on a current successor and stops its idle children", async () => {+ it("takes the session back from a successor that fails partway through its claims", async () => {const output = captureConsoleOutput();- const runtime = await createTestRuntime({ agent: { name: "handoff-eve-066-owner" } });+ const runtime = await createTestRuntime({ agent: { name: "handoff-partial-claims" } });+ const continuationToken = "http:handoff-partial-claims";await runtime.run(async () => {- const anchor = await startSessionOwner(workflowEntry, [- {- kind: "initial",- ownerDeploymentId: "dpl_a",- sessionTimeoutMs: false,- input: { message: "Alice opens a research session." },- serializedContext: buildSerializedContext({- acceptedDeploymentId: "dpl_a",- channelKind: "http",- }),+ const { anchor, stream, workflowRuntime } = await openSession({ continuationToken });+ const inbox = stableInbox(anchor.runId);+ const world = await instrumentWorld({+ // The successor takes the stable inbox, then fails to claim the next address.+ rewriteCandidate(input) {+ return { ...input, hookTokens: [sessionCommandHookToken(anchor.runId), ""] };+ },+ // Alice writes while the failing successor holds the stable inbox.+ async beforeEvent(runId, event) {+ if (runId === anchor.runId || event.eventType !== "step_started") return;+ const { stepName } = event.eventData as { stepName?: string };+ if (stepName?.endsWith("//signalSessionOwnerActivationStep") !== true) return;+ await resumeHook(inbox, aliceSends("Alice writes while the move fails."));},- ]);- const stream = captureTurnEvents(anchor);- const world = await getWorld();- const workflowRuntime = createWorkflowRuntime({- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),- });- const rewritten = new Map<string, Promise<unknown>>();- // The owner runs this build; only the candidate input changes to what an- // eve 0.66 owner sends, so the successor must upgrade the checkpoint.- const eve066Input = (runId: string, encoded: unknown): Promise<unknown> => {- let pending = rewritten.get(runId);- if (pending === undefined) {- pending = (async () => {- const args = (await hydrateWorkflowArguments(encoded, runId, undefined)) as [unknown];- args[0] = toEve066HandoffInput(args[0] as HandoffWorkflowEntryInput);- 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 eve066Input(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 eve066Input(message.runId, message.runInput.input);- }- return queue(...args);});try {- await stream.nextTurn();+ expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");await waitForParkedTurnStep(anchor.runId);await workflowRuntime.dispatchSession({- command: handoffFollowUp("dpl_b", "Bob requests the next research step.", "eve-066"),+ command: handoffFollowUp("dpl_b", "Bob requests the next step.", "trigger"),sessionId: anchor.runId,});- expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");- const successor = await waitForCommandHookOwner(- sessionInboxHookToken(sessionCommandHookToken(anchor.runId)),+ const history = await waitForUserMessages(+ anchor.runId,+ "Alice writes while the move fails.",);- expect(rewritten.has(successor.runId)).toBe(true);- const successorSteps = await world.steps.list({ runId: successor.runId });- expect(- successorSteps.data.some((step) =>- step.stepName.endsWith("//stopUntrackedChildSessionsStep"),- ),- ).toBe(true);- await vi.waitFor(- async () => {- const [state] = await readTurnStepStates(successor.runId);- const userMessages = (state?.history ?? [])- .filter((message) => message.role === "user")- .map((message) => JSON.stringify(message.content));- // The successor's turn continues the history the old owner carried.- expect(userMessages).toEqual([- expect.stringContaining("Alice opens a research session."),- expect.stringContaining("Bob requests the next research step."),- ]);- },- { timeout: 5000 },+ expect(positionOf(history, "Bob requests the next step.")).toBeGreaterThanOrEqual(0);+ expect(positionOf(history, "Bob requests the next step.")).toBeLessThan(+ positionOf(history, "Alice writes while the move fails."),+ );+ for (const token of [inbox, sessionInboxHookToken(continuationToken)]) {+ expect((await waitForCommandHookOwner(token)).runId).toBe(anchor.runId);+ }+ const [candidateId] = world.candidates.keys();+ const backend = await getWorld();+ await vi.waitFor(async () =>+ expect((await backend.runs.get(candidateId!)).status).toBe("completed"),);} finally {- created.mockRestore();- queued.mockRestore();+ world.restore();stream.dispose();await anchor.cancel();}});- expect(output.unexpected(workflowSdkNotice.unpinnedDelivery)).toEqual([]);+ expect(output.unexpected(workflowSdkNotice.unpinnedDelivery, HANDOFF_LOG)).toEqual([]);});- it("retains a message accepted just before durable hook disposal", async () => {- const runtime = await createTestRuntime({ agent: { name: "workflow-entry-handoff" } });-+ it("fences a duplicate candidate out with its attempt lease", async () => {+ const runtime = await createTestRuntime({ agent: { name: "handoff-duplicate" } });await runtime.run(async () => {- const anchor = await startSessionOwner(workflowEntry, [- {- kind: "initial",- ownerDeploymentId: "dpl_a",- input: { message: "hello from a" },- serializedContext: buildSerializedContext({- acceptedDeploymentId: "dpl_a",- channelKind: "http",- }),- },- ]);- 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.` },- turnPolicy: "queue",- });- }- }- return await createEvent(...args);- });+ const { anchor, stream, workflowRuntime } = await openSession();+ const world = await instrumentWorld({});try {expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");await waitForParkedTurnStep(anchor.runId);-- await expect(- workflowRuntime.dispatchSession({- command: handoffFollowUp("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: handoffFollowUp("dpl_b", "Bob sends a later sentinel.", "sentinel"),+ command: handoffFollowUp("dpl_b", "Bob requests the next step.", "trigger"),sessionId: anchor.runId,});await stream.nextTurn();- let saved: string | undefined;- await vi.waitFor(- async () => {- for (const state of await readTurnStepStates(owner.runId)) {- const history = JSON.stringify(state.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"),+ const successor = await waitForNewOwner(anchor.runId, anchor.runId);+ const original = world.candidates.get(successor.runId);+ assert(original !== undefined);++ // A start step retried after its run was created starts the same attempt again.+ const duplicate = await start(+ workflowEntry,+ [{ ...original, sessionWritable: getRun(anchor.runId).getWritable<Uint8Array>() }],+ { deploymentId: "dpl_b" },);- expect(saved!.indexOf("Alice sends input 1")).toBeLessThan(- saved!.indexOf("Alice sends input 2"),+ await expect(duplicate.returnValue).resolves.toEqual({ output: "" });+ const backend = await getWorld();+ expect((await backend.hooks.list({ runId: duplicate.runId })).data).toEqual([]);+ expect((await backend.steps.list({ runId: duplicate.runId })).data).toEqual([]);+ expect((await waitForCommandHookOwner(stableInbox(anchor.runId))).runId).toBe(+ successor.runId,);} finally {- spy.mockRestore();+ world.restore();stream.dispose();- if ((await anchor.status) === "running") await anchor.cancel();+ await anchor.cancel();}});});+ });- it("hands off an alias-addressed session and keeps the alias resolving through the gap", async () => {- const output = captureConsoleOutput();- const runtime = await createTestRuntime({ agent: { name: "workflow-entry-handoff-alias" } });- const continuationToken = "http:workflow-entry-handoff-alias";-+ describe("late candidate", () => {+ it("shuts out a candidate that boots after its owner kept the session", async () => {+ const runtime = await createTestRuntime({ agent: { name: "handoff-late-candidate" } });await runtime.run(async () => {- const anchor = await startSessionOwner(workflowEntry, [- {- kind: "initial",- ownerDeploymentId: "dpl_a",- input: { message: "hello from a" },- serializedContext: buildSerializedContext({- acceptedDeploymentId: "dpl_a",- channelKind: "http",- continuationToken,- }),- },- ]);- 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 createBatch = world.events.createBatch;- world.events.createBatch = 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: handoffFollowUp("dpl_b", "Alice writes during the gap.", "delivery-gap"),- continuationToken,- });- }- return created;- });+ const { anchor, stream, workflowRuntime } = await openSession();+ const trigger = "Bob requests the next step.";+ const world = await instrumentWorld({ failCandidateStart: true });try {expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");await waitForParkedTurnStep(anchor.runId);-- await expect(- workflowRuntime.dispatchContinuation({- command: handoffFollowUp("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({+ await workflowRuntime.dispatchSession({+ command: handoffFollowUp("dpl_b", trigger, "trigger"),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)),+ // The start step created the candidate and failed; the owner won the+ // attempt's lease and ran the trigger itself.+ const history = await waitForUserMessages(anchor.runId, trigger);+ expect(countOf(history, trigger)).toBe(1);+ const created = [...world.candidates.values()].find((input) => input.kind === "handoff");+ assert(created !== undefined);+ world.restore();++ const late = await start(+ workflowEntry,+ [{ ...created, sessionWritable: getRun(anchor.runId).getWritable<Uint8Array>() }],+ { deploymentId: "dpl_b" },);- 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:"),+ await expect(late.returnValue).resolves.toEqual({ output: "" });+ const backend = await getWorld();+ expect((await backend.hooks.list({ runId: late.runId })).data).toEqual([]);+ expect((await backend.steps.list({ runId: late.runId })).data).toEqual([]);+ expect((await waitForCommandHookOwner(stableInbox(anchor.runId))).runId).toBe(+ anchor.runId,);- expect(markers).toEqual([]);- // Only one session exists for this alias.- await expect(workflowRuntime.resolveContinuation(continuationToken)).resolves.toEqual({- sessionId: anchor.runId,- });} finally {- spy.mockRestore();- world.events.createBatch = createBatch;+ world.restore();stream.dispose();await anchor.cancel();}});- expect(output.lines).toContainEqual(- expect.stringContaining(workflowSdkNotice.unpinnedDelivery),- );- expect(output.unexpected(workflowSdkNotice.unpinnedDelivery)).toEqual([]);});+ });- it("keeps the session on the current owner when it is not idle", async () => {- const runtime = await createTestRuntime({ agent: { name: "workflow-entry-handoff-busy" } });-+ describe("source gone before the successor claims", () => {+ it("claims nothing when its source ended before the successor prepared", async () => {+ const runtime = await createTestRuntime({ agent: { name: "handoff-source-gone" } });await runtime.run(async () => {- const run = await startSessionOwner(workflowEntry, [- {- kind: "initial",- ownerDeploymentId: "dpl_a",- input: { message: "hello from a" },- serializedContext: buildSerializedContext({- acceptedDeploymentId: "dpl_a",- channelKind: "http",- }),+ const { anchor, stream, workflowRuntime } = await openSession();+ let candidateRunId: string | undefined;+ // Alice's session is cancelled while its successor is still booting.+ const world = await instrumentWorld({+ async beforeEvent(runId, event) {+ if (+ runId === anchor.runId ||+ event.eventType !== "hook_created" ||+ !String(event.eventData.token).startsWith("eve:handoff:lease:")+ )+ return;+ candidateRunId = runId;+ await anchor.cancel();},- ]);- const stream = captureTurnEvents(run);- const workflowRuntime = createWorkflowRuntime({- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),});try {expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");+ await waitForParkedTurnStep(anchor.runId);+ await workflowRuntime.dispatchSession({+ command: handoffFollowUp("dpl_b", "Bob requests the next step.", "trigger"),+ sessionId: anchor.runId,+ });- // 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: handoffFollowUp("dpl_b", "first burst", "delivery-1"),- sessionId: run.runId,- }),- workflowRuntime.dispatchSession({- command: handoffFollowUp("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);+ await vi.waitFor(() => expect(candidateRunId).toBeDefined(), { timeout: 10_000 });+ await expect(getRun(candidateRunId!).returnValue).resolves.toEqual({ output: "" });+ expect(await countSessionHookClaims(candidateRunId!)).toBe(0);+ expect(await readTurnStepStates(candidateRunId!)).toEqual([]);} finally {+ world.restore();stream.dispose();- await run.cancel();}});});});++ // Every live session takes this path on the first deploy of this protocol:+ // its owner runs an older build, which releases its addresses before it+ // starts the successor and waits for `active`.+ describe("handoff from an owner that released its addresses", () => {+ const trigger = "Bob requests the next research step.";++ it.each([undefined, 2] as const)(+ "claims every address, tells the owner, and runs the trigger once (handoffVersion %s)",+ async (handoffVersion) => {+ const runtime = await createTestRuntime({+ agent: { name: `handoff-released-v${String(handoffVersion ?? 1)}` },+ });+ await runtime.run(async () => {+ const move = await handOffFromReleasedOwner(trigger, (input) => ({+ ...input,+ ...(handoffVersion !== undefined && { handoffVersion }),+ }));+ try {+ await expect(move.source.returnValue).resolves.toEqual({+ activation: { kind: "active" },+ released: [],+ });+ for (const token of move.addresses) {+ await expect(+ waitForCommandHookOwner(sessionInboxHookToken(token)),+ ).resolves.toMatchObject({ runId: move.successor.runId });+ }+ const history = await waitForUserMessages(move.successor.runId, trigger);+ expect(countOf(history, trigger)).toBe(1);+ } finally {+ await move.cleanup();+ }+ });+ },+ );++ it("continues an eve 0.66 checkpoint and stops its idle children", async () => {+ const output = captureConsoleOutput();+ const runtime = await createTestRuntime({ agent: { name: "handoff-eve-066-owner" } });+ await runtime.run(async () => {+ const move = await handOffFromReleasedOwner(trigger, toEve066Checkpoint);+ try {+ await expect(move.source.returnValue).resolves.toMatchObject({+ activation: { kind: "active" },+ });+ const successorSteps = await (+ await getWorld()+ ).steps.list({ runId: move.successor.runId });+ expect(+ successorSteps.data.some((step) =>+ step.stepName.endsWith("//stopUntrackedChildSessionsStep"),+ ),+ ).toBe(true);+ // The successor's turn continues the history the old owner carried.+ const history = await waitForUserMessages(move.successor.runId, trigger);+ expect(history).toEqual([+ expect.stringContaining("Alice opens a research session."),+ expect.stringContaining(trigger),+ ]);+ } finally {+ await move.cleanup();+ }+ });+ expect(output.unexpected(workflowSdkNotice.unpinnedDelivery, HANDOFF_LOG)).toEqual([]);+ });+ });});-/** The handoff input an eve 0.66 owner sends, per a captured checkpoint version 8. */+/**+ * Hands a real checkpoint to a current successor the way an older owner did:+ * the owner releases its addresses first and the start input carries none of+ * this protocol's fields.+ */+async function handOffFromReleasedOwner(+ trigger: string,+ shape: (input: HandoffWorkflowEntryInput) => unknown,+) {+ const checkpoint = await captureCheckpoint();+ const alias = "http:handoff-released-owner";+ const source = await start(releasingSessionOwnerWorkflow, [+ { aliases: [alias], release: `release:${alias}` },+ ]);+ const sessionId = source.runId;+ await waitForHook(source, { token: sessionInboxHookToken(alias) });+ // Stands in for the original run, which owned the session's stream.+ const streamHost = await start(parkedAnchorWorkflow, [{ token: `stream:${sessionId}` }]);+ await resumeHook(`release:${alias}`, undefined);+ await vi.waitFor(async () => expect(await listSessionHookTokens(sessionId)).toEqual([]));++ const {+ attemptKey: _attemptKey,+ handoffVersion: _handoffVersion,+ hookTokens: _hookTokens,+ sourceRunId: _sourceRunId,+ ...released+ } = {+ ...checkpoint,+ activationToken: `${sessionId}:handoff`,+ checkpoint: rebindCheckpoint(checkpoint.checkpoint, sessionId, alias),+ delivery: { kind: "deliver" as const, payloads: [{ message: trigger }] },+ reason: undefined,+ sessionId,+ sessionWritable: getRun(streamHost.runId).getWritable<Uint8Array>(),+ };+ const successor = await start(+ workflowEntry,+ [shape(released as HandoffWorkflowEntryInput) as HandoffWorkflowEntryInput],+ { deploymentId: "dpl_b" },+ );+ return {+ addresses: [sessionCommandHookToken(sessionId), alias],+ source,+ successor,+ async cleanup() {+ for (const run of [successor, streamHost, source])+ if ((await run.status) === "running") await run.cancel();+ },+ };+}++/** A settled checkpoint of a real session, as its owner sends it to a successor. */+async function captureCheckpoint(): Promise<HandoffWorkflowEntryInput> {+ const { anchor, stream, workflowRuntime } = await openSession();+ // The candidate refuses, so the session stays where it is.+ const world = await instrumentWorld({+ rewriteCandidate(input) {+ Object.assign(input.checkpoint, { version: SESSION_CHECKPOINT_VERSION + 1 });+ return input;+ },+ });+ try {+ await stream.nextTurn();+ await waitForParkedTurnStep(anchor.runId);+ await workflowRuntime.dispatchSession({+ command: handoffFollowUp("dpl_b", "Alice asks for a checkpoint.", "capture"),+ sessionId: anchor.runId,+ });+ await stream.nextTurn();+ const [captured] = world.candidates.values();+ assert(captured !== undefined);+ return captured;+ } finally {+ world.restore();+ stream.dispose();+ await anchor.cancel();+ }+}++function rebindCheckpoint(+ checkpoint: HandoffWorkflowEntryInput["checkpoint"],+ sessionId: string,+ continuationToken: string,+): HandoffWorkflowEntryInput["checkpoint"] {+ const { serializedContext, sessionState } = checkpoint;+ return {+ ...checkpoint,+ serializedContext: { ...serializedContext, "eve.continuationToken": continuationToken },+ sessionState: {+ ...sessionState,+ continuationToken,+ sessionId,+ snapshot: {+ session: { ...sessionState.snapshot.session, continuationToken, sessionId },+ },+ },+ };+}++async function openSession(options: { readonly continuationToken?: string } = {}) {+ const anchor = await startSessionOwner(workflowEntry, [+ {+ kind: "initial",+ ownerDeploymentId: "dpl_a",+ sessionTimeoutMs: false,+ input: { message: "Alice opens a research session." },+ serializedContext: buildSerializedContext({+ acceptedDeploymentId: "dpl_a",+ channelKind: "http",+ continuationToken: options.continuationToken,+ }),+ },+ ]);+ return {+ anchor,+ stream: captureTurnEvents(anchor),+ workflowRuntime: createWorkflowRuntime({+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),+ }),+ };+}++function stableInbox(sessionId: string): string {+ return sessionInboxHookToken(sessionCommandHookToken(sessionId));+}++function aliceSends(message: string) {+ return { kind: "send" as const, payload: { message }, turnPolicy: "queue" as const };+}++function isCandidateCreated(event: AnyEventRequest): boolean {+ return (+ event.eventType === "run_created" &&+ (event as RunCreatedEventRequest).eventData.deploymentId === "dpl_b"+ );+}++/**+ * Observes every event before it is written (batching off, so none bypass it)+ * and captures, and optionally rewrites, each candidate started on `dpl_b`.+ */+async function instrumentWorld(options: {+ readonly beforeEvent?: (runId: string, event: AnyEventRequest) => Promise<void> | void;+ /** Fails each candidate's start after its run is created, before it is queued. */+ readonly failCandidateStart?: boolean;+ readonly rewriteCandidate?: (input: HandoffWorkflowEntryInput) => unknown;+}) {+ const world = await getWorld();+ const candidates = new Map<string, HandoffWorkflowEntryInput>();+ const encoded = new Map<string, Promise<unknown>>();+ const rewrite = (runId: string, input: unknown): Promise<unknown> => {+ let pending = encoded.get(runId);+ if (pending === undefined) {+ pending = (async () => {+ const args = (await hydrateWorkflowArguments(input, runId, undefined)) as [+ HandoffWorkflowEntryInput,+ ];+ candidates.set(runId, structuredClone({ ...args[0], sessionWritable: undefined }) as never);+ if (options.rewriteCandidate === undefined) return input;+ const rewritten = [options.rewriteCandidate(args[0])];+ const operations: Promise<void>[] = [];+ const result = await dehydrateWorkflowArguments(rewritten, runId, undefined, operations);+ await Promise.all(operations);+ return result;+ })();+ encoded.set(runId, pending);+ }+ return pending;+ };+ const createBatch = world.events.createBatch;+ world.events.createBatch = undefined;+ 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 AnyEventRequest;+ await options.beforeEvent?.(runId, event);+ if (isCandidateCreated(event)) {+ const data = (event as RunCreatedEventRequest).eventData;+ data.input = await rewrite(runId, data.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") {+ if (options.failCandidateStart === true)+ throw Object.assign(new Error("The queue is unavailable."), { name: "FatalError" });+ message.runInput.input = await rewrite(message.runId, message.runInput.input);+ }+ return queue(...args);+ });+ return {+ candidates,+ async events(runId: string) {+ const listed = await world.events.list({+ pagination: { limit: 1000 },+ resolveData: "none",+ runId,+ });+ return listed.data;+ },+ restore() {+ created.mockRestore();+ queued.mockRestore();+ world.events.createBatch = createBatch;+ },+ };+}++async function listSessionHookTokens(runId: string): Promise<string[]> {+ const hooks = await (await getWorld()).hooks.list({ runId });+ return hooks.data.map((hook) => hook.token).filter(isSessionInboxHookToken);+}++async function countSessionHookClaims(runId: string): Promise<number> {+ const events = await (+ await getWorld()+ ).events.list({+ pagination: { limit: 1000 },+ resolveData: "all",+ runId,+ });+ return events.data.filter(+ (event) => event.eventType === "hook_created" && isSessionInboxHookToken(event.eventData.token),+ ).length;+}++/** The user messages of a run's longest saved history, once it contains every one of `messages`. */+async function waitForUserMessages(runId: string, ...messages: string[]): Promise<string[]> {+ let saved: string[] = [];+ await vi.waitFor(+ async () => {+ // Recorded steps are not returned in turn order; the settled history is+ // the one that accumulated every turn.+ saved = (await readTurnStepStates(runId))+ .map((state) =>+ state.history+ .filter((entry) => entry.role === "user")+ .map((entry) => JSON.stringify(entry.content)),+ )+ .reduce((longest, history) => (history.length > longest.length ? history : longest), []);+ for (const message of messages)+ expect(+ saved.some((entry) => entry.includes(message)),+ message,+ ).toBe(true);+ },+ { timeout: 10_000 },+ );+ return saved;+}++function positionOf(messages: readonly string[], message: string): number {+ return messages.findIndex((entry) => entry.includes(message));+}++function countOf(messages: readonly string[], message: string): number {+ return messages.filter((entry) => entry.includes(message)).length;+}++/** Waits until a run other than `previousOwnerRunId` owns the session's stable inbox. */+async function waitForNewOwner(sessionId: string, previousOwnerRunId: string) {+ let owner: Awaited<ReturnType<typeof waitForCommandHookOwner>> | undefined;+ await vi.waitFor(+ async () => {+ owner = await waitForCommandHookOwner(stableInbox(sessionId));+ expect(owner.runId).not.toBe(previousOwnerRunId);+ },+ { timeout: 10_000 },+ );+ return owner!;+}+/** The idle session's lifecycle as an eve 0.66 owner kept it: an emission position. */function eve066LifecycleState(state: Record<string, unknown> | undefined) {const projection = storedProjection(state);@@ -740,8 +797,9 @@ function eve066LifecycleState(state: Record<string, unknown> | undefined) {};}-function toEve066HandoffInput(input: HandoffWorkflowEntryInput): unknown {- const { checkpoint, handoffVersion: _handoffVersion, ...fields } = input;+/** The checkpoint an eve 0.66 owner wrote (checkpoint version 8). */+function toEve066Checkpoint(input: HandoffWorkflowEntryInput): unknown {+ const { checkpoint, ...fields } = input;const { history, serializedContext, sessionState, ...checkpointFields } = checkpoint;const { "eve.stateLayout": _stateLayout, ...context } = serializedContext;return {diff --git a/packages/eve/src/execution/session/entry-input.ts b/packages/eve/src/execution/session/entry-input.tsindex bf3939dec..ed7b0656d 100644--- a/packages/eve/src/execution/session/entry-input.ts+++ b/packages/eve/src/execution/session/entry-input.ts@@ -3,8 +3,12 @@ import type { DeliverHookPayload, RunInput, SessionCommand } from "#channel/typeimport type { SessionCheckpoint } from "#execution/session/handoff.js";import type { AgentWorkflowRetentionDefinition } from "#shared/agent-definition.js";-/** Version 2 marks source runs whose Workflow SDK supports forced hook claims. */-export const SESSION_HANDOFF_VERSION = 2;+/**+ * Version 3 sources keep their hooks while the successor starts: it takes+ * them over with forced claims and the source hands over what it accepted+ * meanwhile. Earlier sources released their hooks before starting it.+ */+export const SESSION_HANDOFF_VERSION = 3;/*** Serializable workflow-entry input. All runtime state travels via@@ -37,8 +41,9 @@ export type SessionHandoffStart =*/readonly reason: "compaction";/**- * The lone delivery that arrived before the owner could move, processed- * first. Without one, the successor parks until the next input arrives.+ * Only sources older than version 3 send one: the lone delivery that+ * arrived before they could move, processed first. Without one, the+ * successor parks until the next input arrives.*/readonly delivery?: DeliverHookPayload;/** Compaction does not extend the session's lifetime. */@@ -48,9 +53,18 @@ export type SessionHandoffStart =/** A successor owner started by a previous owner during a handoff. */export type HandoffWorkflowEntryInput = SessionHandoffStart & {readonly activationToken: string;+ /**+ * Version 3: names this attempt, so a duplicate candidate fences itself out+ * and the source's handover reaches the successor that expects it.+ */+ readonly attemptKey?: string;readonly checkpoint: SessionCheckpoint;- /** Omitted by version 1 sources, whose hooks cannot safely be force-claimed. */+ /** Omitted by version 1 sources. */readonly handoffVersion?: number;+ /** Version 3: the source's logical hook set, which the successor takes over. */+ readonly hookTokens?: readonly string[];+ /** Version 3: the source run, whose handover the successor waits for while it lives. */+ readonly sourceRunId?: string;readonly kind: "handoff";readonly ownerDeploymentId: string;readonly sessionWritable: WritableStream<Uint8Array>;diff --git a/packages/eve/src/execution/session/entry.ts b/packages/eve/src/execution/session/entry.tsindex cc0e1bd66..e942ded07 100644--- a/packages/eve/src/execution/session/entry.ts+++ b/packages/eve/src/execution/session/entry.ts@@ -1,6 +1,6 @@import { readSerializedSessionSchedule } from "#context/session-schedule.js";import { failSession, runPreparedSession, type SessionBoot } from "#execution/session/program.js";-import { getWorkflowMetadata, getWritable } from "#compiled/@workflow/core/index.js";+import { createHook, 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";@@ -8,8 +8,12 @@ import type { DurableCompiledArtifactsSource } from "#runtime/durable-compiled-aimport { 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 { claimHookOwnership, isHookConflictError } from "#execution/hook-ownership.js";+import {+ createSessionInbox,+ type SessionInboxHandle,+ type SessionInboxPayload,+} 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 {@@ -26,13 +30,18 @@ import {sessionCommandHookToken,} from "#execution/session-inbox/address.js";import {- recordSessionOwnerStep,+ prepareSuccessorStep,signalSessionOwnerActivationStep,stopUntrackedChildSessionsStep,- validateSessionCheckpointStep,} from "#execution/session/handoff-steps.js";import { migrateSessionCheckpoint } from "#execution/session/checkpoint-migrations.js";-import type { SessionCheckpoint } from "#execution/session/handoff.js";+import {+ HANDOFF_LEASE_RETENTION,+ handoffLeaseToken,+ sendSessionHandover,+ type SessionCheckpoint,+} from "#execution/session/handoff.js";+import { abandonHandoverIfRunEnds, watchRunEnd } from "#execution/session/run-watch.js";import type {HandoffWorkflowEntryInput,InitialWorkflowEntryInput,@@ -61,7 +70,9 @@ export async function workflowEntry(input: WorkflowEntryInput): Promise<Workflowconst boot =input.kind === "initial"? await bootInitialOwner(input, getWorkflowMetadata().workflowRunId)- : await bootHandoffOwner(input);+ : (input.handoffVersion ?? 0) >= 3+ ? await bootForcedHandoffOwner(input)+ : await bootReleasedHandoffOwner(input);if (boot === undefined) return { output: "" };const result = await runPreparedSession(boot.session, boot.inbox);return { output: result.output };@@ -243,45 +254,184 @@ export async function bootInitialOwner(}}-/** Validates, claims the exact hook set, then tells the previous owner it may exit. */-async function bootHandoffOwner(+/** A successor that may continue the session, before it owns any of its hooks. */+interface PreparedSuccessor {+ readonly checkpoint: SessionCheckpoint;+ readonly childRunIdsToStop: readonly string[];+ readonly serializedContext: Record<string, unknown>;+}++/** Migrates and validates the checkpoint; tells the source and returns `undefined` when it is unreadable here. */+async function prepareSuccessor(input: HandoffWorkflowEntryInput,-): Promise<BootOutcome | undefined> {+ source?: { readonly runId: string; readonly hookTokens: readonly string[] },+): Promise<PreparedSuccessor | undefined> {const { sessionId } = input;+ // The previous owner may run an older eve build; read its checkpoint in this build's shape.+ const migration = migrateSessionCheckpoint(input.checkpoint);+ const validation = await prepareSuccessorStep({+ handoffVersion: input.handoffVersion,+ migration,+ sessionId,+ ...(source !== undefined && { source }),+ });+ if (migration.kind === "incompatible" || validation.kind === "incompatible") {+ await signalSessionOwnerActivationStep({+ activation: {+ kind: "incompatible",+ payloads: [],+ reason: "checkpoint-version",+ runId: getWorkflowMetadata().workflowRunId,+ },+ token: input.activationToken,+ });+ return undefined;+ }+ if (validation.kind === "source-gone") {+ // A source that ended no longer listens; a live one keeps the session.+ const error = new Error("The session's previous owner no longer holds all of its addresses.");+ await signalFailedActivation(input, error, { payloads: [] });+ return undefined;+ }+ const { checkpoint, childRunIdsToStop } = migration;+ return {+ checkpoint,+ childRunIdsToStop,+ serializedContext: stampSessionIdentity(checkpoint.serializedContext, sessionId),+ };+}++async function signalFailedActivation(+ input: HandoffWorkflowEntryInput,+ error: unknown,+ failure: { readonly claimedHooks?: boolean; readonly payloads: readonly SessionInboxPayload[] },+): Promise<void> {+ await signalSessionOwnerActivationStep({+ activation: {+ error: normalizeSerializableError(error),+ kind: "failed",+ runId: getWorkflowMetadata().workflowRunId,+ ...failure,+ },+ token: input.activationToken,+ });+}++/**+ * Version 3: the source still holds every hook. Fences duplicate candidates,+ * prepares, then force-claims the source's hook set and runs right away; the+ * source's handover is placed ahead of everything this run accepts itself.+ */+async function bootForcedHandoffOwner(+ input: HandoffWorkflowEntryInput,+): Promise<BootOutcome | undefined> {+ const { attemptKey, hookTokens, sessionId, sourceRunId } = input;+ if (attemptKey === undefined || hookTokens === undefined || sourceRunId === undefined) {+ const error = new Error(+ "Session handoff version 3 input is missing attemptKey, hookTokens, or sourceRunId.",+ );+ await signalFailedActivation(input, error, { payloads: [] });+ return undefined;+ }+ try {+ // A start step retried after its run was created leaves a duplicate+ // candidate, and an owner whose start step failed takes the lease itself.+ // Only one run claims it; the token stays reserved past that run's end.+ const lease = createHook<never>({+ experimental_minRetention: HANDOFF_LEASE_RETENTION,+ token: handoffLeaseToken(attemptKey),+ });+ await claimHookOwnership(lease);+ } catch (error) {+ if (isHookConflictError(error)) return undefined;+ await signalFailedActivation(input, error, { payloads: [] });+ return undefined;+ }+ let prepared: PreparedSuccessor | undefined;+ try {+ prepared = await prepareSuccessor(input, { hookTokens, runId: sourceRunId });+ } catch (error) {+ await signalFailedActivation(input, error, { payloads: [] });+ return undefined;+ }+ if (prepared === undefined) return undefined;const inbox = createSessionInbox(sessionId);- let checkpoint: SessionCheckpoint;- let childRunIdsToStop: readonly string[];- let serializedContext: Record<string, unknown>;try {- // The previous owner may run an older eve build; read its checkpoint in this build's shape.- const migration = migrateSessionCheckpoint(input.checkpoint);- const validation = await validateSessionCheckpointStep({ migration, sessionId });- if (migration.kind === "incompatible" || validation.kind === "incompatible") {- const payloads = await inbox.release();- await signalSessionOwnerActivationStep({- activation: { kind: "incompatible", payloads, reason: "checkpoint-version" },- token: input.activationToken,- });- return undefined;- }- ({ checkpoint, childRunIdsToStop } = migration);- serializedContext = stampSessionIdentity(checkpoint.serializedContext, sessionId);- await recordSessionOwnerStep({ sessionId });+ await inbox.claimSessionHooks(hookTokens, { force: true, handover: attemptKey });+ } catch (error) {+ const claimedHooks = inbox.claimedTokens.length > 0;+ await signalFailedActivation(input, error, { claimedHooks, payloads: [] });+ if (claimedHooks) await handBack(inbox, { attemptKey, sessionId, sourceRunId });+ await inbox.dispose();+ return undefined;+ }+ abandonHandoverIfRunEnds(inbox, { attemptKey, sourceRunId });+ return await startSuccessor(input, inbox, prepared);+}++/**+ * Waits for the source to take its hooks back, then returns what this run+ * accepted meanwhile as the handover. A source that ended takes nothing back.+ */+async function handBack(+ inbox: SessionInboxHandle,+ input: { readonly attemptKey: string; readonly sessionId: string; readonly sourceRunId: string },+): Promise<void> {+ const watch = watchRunEnd(input.sourceRunId);+ const settled = new AbortController();+ try {+ const outcome = await Promise.race([+ inbox.whenTakenOver(settled.signal).then(() => "taken-back" as const),+ watch.ended.then(() => "source-ended" as const),+ ]);+ if (outcome === "source-ended") return;+ } finally {+ watch.stop();+ settled.abort();+ }+ await sendSessionHandover({+ attemptKey: input.attemptKey,+ payloads: inbox.drain(),+ sessionId: input.sessionId,+ });+}++/**+ * A source older than version 3 already released its hooks: claim them+ * ordinarily and tell the source it may exit.+ */+async function bootReleasedHandoffOwner(+ input: HandoffWorkflowEntryInput,+): Promise<BootOutcome | undefined> {+ const inbox = createSessionInbox(input.sessionId);+ let prepared: PreparedSuccessor | undefined;+ try {+ prepared = await prepareSuccessor(input);+ if (prepared === undefined) return undefined;await inbox.claimSessionHooks(- sessionHookTokens({ serializedContext, sessionState: checkpoint.sessionState }),+ sessionHookTokens({+ serializedContext: prepared.serializedContext,+ sessionState: prepared.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,- });+ await signalFailedActivation(input, error, { payloads: await inbox.release() });return undefined;}+ return await startSuccessor(input, inbox, prepared);+}++async function startSuccessor(+ input: HandoffWorkflowEntryInput,+ inbox: SessionInboxHandle,+ prepared: PreparedSuccessor,+): Promise<BootOutcome> {+ const { sessionId } = input;+ const { checkpoint, childRunIdsToStop, serializedContext } = prepared;if (childRunIdsToStop.length > 0) {await stopUntrackedChildSessionsStep({ runIds: childRunIdsToStop, sessionId });}diff --git a/packages/eve/src/execution/session/handoff-steps.test.ts b/packages/eve/src/execution/session/handoff-steps.test.tsindex 83efe9017..f724a59b2 100644--- a/packages/eve/src/execution/session/handoff-steps.test.ts+++ b/packages/eve/src/execution/session/handoff-steps.test.ts@@ -1,18 +1,34 @@import { createTestSessionState } from "#internal/testing/session-state.js";import { beforeEach, describe, expect, it, vi } from "vitest";-import { WorkflowRunNotFoundError } from "#compiled/@workflow/errors/index.js";+import { HookNotFoundError, WorkflowRunNotFoundError } from "#compiled/@workflow/errors/index.js";import { IncompatibleStateLayoutError } from "#context/serialize.js";import { SESSION_CHECKPOINT_VERSION, type SessionCheckpoint } from "#execution/session/handoff.js";import {+ prepareSuccessorStep,+ signalSessionOwnerActivationStep,+ startSuccessorStep,stopUntrackedChildSessionsStep,- validateSessionCheckpointStep,+ type SuccessorStartInput,} from "#execution/session/handoff-steps.js";+import { positionState } from "#internal/testing/session-machine.js";+import { captureLogRecords } from "#internal/testing/log-records.js";import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";+import { sessionInboxHookToken } from "#execution/session-inbox/address.js";const deserializeContextMock = vi.fn();const readDurableSessionMock = vi.fn();const cancelRunMock = vi.fn();+const setAttributesMock = vi.fn();+const getWorldMock = vi.fn(async () => ({}));+const getRunMock = vi.fn();+const resumeHookMock = vi.fn();+const getHookByTokenMock = vi.fn();+const startWorkflowOnDeploymentMock = vi.fn();++vi.mock("#compiled/@workflow/core/index.js", () => ({+ setAttributes: (...args: unknown[]) => setAttributesMock(...args),+}));vi.mock("#context/serialize.js", async (importOriginal) => ({...(await importOriginal()),@@ -25,15 +41,24 @@ vi.mock("#execution/durable-session-store.js", async (importOriginal) => ({vi.mock("#internal/workflow/runtime.js", async (importOriginal) => ({...(await importOriginal()),cancelRun: (...args: unknown[]) => cancelRunMock(...args),- getWorld: async () => ({}),+ getRun: (...args: unknown[]) => getRunMock(...args),+ getHookByToken: (...args: unknown[]) => getHookByTokenMock(...args),+ getWorld: () => getWorldMock(),+ resumeHook: (...args: unknown[]) => resumeHookMock(...args),}));+vi.mock("#execution/workflow-runtime.js", async (importOriginal) => ({+ ...(await importOriginal()),+ startWorkflowOnDeployment: (...args: unknown[]) => startWorkflowOnDeploymentMock(...args),+}));++const SOURCE_TOKENS = ["eve:session:session-1", "channel:alias"];-describe("validateSessionCheckpointStep", () => {+describe("prepareSuccessorStep", () => {beforeEach(() => {vi.clearAllMocks();});- it("hydrates the target bundle and durable state for a complete hook set", async () => {+ it("hydrates the target bundle and durable state, then records this owner", async () => {const require = vi.fn();deserializeContextMock.mockResolvedValue({ require });readDurableSessionMock.mockReturnValue({});@@ -43,6 +68,38 @@ describe("validateSessionCheckpointStep", () => {expect(require).toHaveBeenCalledWith(BundleKey);expect(readDurableSessionMock).toHaveBeenCalledWith(checkpoint.sessionState);+ expect(setAttributesMock).toHaveBeenCalledWith(+ expect.objectContaining({ "$eve.session": "session-1" }),+ { allowReservedAttributes: true },+ );+ });++ it.each([+ ["every address is still the source's", ["run-a", "run-a"], "valid"],+ ["another run now holds an alias", ["run-a", "run-other"], "source-gone"],+ ["an address is no longer held", ["run-a", undefined], "source-gone"],+ ] as const)("checks the source still holds its addresses: %s", async (_name, holders, kind) => {+ deserializeContextMock.mockResolvedValue({ require: vi.fn() });+ readDurableSessionMock.mockReturnValue({});+ getHookByTokenMock.mockImplementation(async (token: string) => {+ const runId = holders[token.includes("channel:alias") ? 1 : 0];+ if (runId === undefined) throw new HookNotFoundError(token);+ return { runId };+ });++ await expect(+ prepareSuccessorStep({+ handoffVersion: 3,+ migration: { kind: "current", checkpoint: createCheckpoint(), childRunIdsToStop: [] },+ sessionId: "session-1",+ source: { hookTokens: SOURCE_TOKENS, runId: "run-a" },+ }),+ ).resolves.toEqual({ kind });+ expect(getHookByTokenMock.mock.calls.map(([token]) => token)).toEqual(+ SOURCE_TOKENS.map(sessionInboxHookToken),+ );+ // Ingress reads the recorded owner version, so only a successor that will claim records it.+ expect(setAttributesMock).toHaveBeenCalledTimes(kind === "valid" ? 1 : 0);});it("ignores a sandbox record saved before the provider redesign", async () => {@@ -84,12 +141,14 @@ describe("validateSessionCheckpointStep", () => {const detail = "checkpoint version 7 is outside the supported range";await expect(- validateSessionCheckpointStep({+ prepareSuccessorStep({+ handoffVersion: 3,migration: { kind: "incompatible", detail },sessionId: "session-1",}),).resolves.toEqual({ kind: "incompatible", reason: "checkpoint-version" });expect(deserializeContextMock).not.toHaveBeenCalled();+ expect(setAttributesMock).not.toHaveBeenCalled();expect(warn).toHaveBeenCalledWith(expect.stringContaining("cannot read the checkpoint"),expect.objectContaining({ detail, sessionId: "session-1" }),@@ -122,6 +181,102 @@ describe("validateSessionCheckpointStep", () => {);});+describe("startSuccessorStep", () => {+ const forcingWorld = { capabilities: { hookForceClaim: true, hookRetention: { active: true } } };++ beforeEach(() => {+ vi.clearAllMocks();+ getWorldMock.mockResolvedValue(forcingWorld);+ readDurableSessionMock.mockReturnValue({ state: undefined });+ });++ it.each([+ ["force-claim", { hookRetention: { active: true } }],+ ["hook retention", { hookForceClaim: true }],+ ])("starts nothing on a World without %s support", async (_name, capabilities) => {+ getWorldMock.mockResolvedValue({ capabilities });+ const records = captureLogRecords();+ await expect(startSuccessorStep(startInput())).resolves.toEqual({ kind: "unsupported" });+ expect(startWorkflowOnDeploymentMock).not.toHaveBeenCalled();+ expect(records.records).toContainEqual(+ expect.objectContaining({ message: expect.stringContaining("cannot force-claim hooks") }),+ );+ });++ it("starts nothing when the checkpoint still holds work", async () => {+ readDurableSessionMock.mockReturnValue({+ state: positionState({ sequence: 1, turnId: "turn_0" }),+ });+ await expect(startSuccessorStep(startInput())).resolves.toEqual({ kind: "not-idle" });+ expect(startWorkflowOnDeploymentMock).not.toHaveBeenCalled();+ });++ it.each([undefined, 0, "default"] as const)(+ "starts a version 3 successor on the original stream with retention=%s",+ async (retention) => {+ const sessionWritable = new WritableStream<Uint8Array>();+ getRunMock.mockReturnValue({ getWritable: () => sessionWritable });+ startWorkflowOnDeploymentMock.mockResolvedValue({ runId: "owner-2" });+ const input = startInput();+ const checkpoint = { ...input.checkpoint, retention };++ await expect(startSuccessorStep({ ...input, checkpoint })).resolves.toEqual({+ kind: "started",+ runId: "owner-2",+ });++ expect(getRunMock).toHaveBeenCalledWith("anchor-1");+ expect(startWorkflowOnDeploymentMock).toHaveBeenCalledWith(+ expect.objectContaining({ workflowId: expect.stringContaining("workflowEntry") }),+ [+ {+ activationToken: "owner-1:handoff:0",+ attemptKey: "owner-1:0",+ checkpoint,+ delivery: input.delivery,+ handoffVersion: 3,+ hookTokens: input.hookTokens,+ kind: "handoff",+ ownerDeploymentId: "deployment-b",+ sessionWritable,+ sessionId: "anchor-1",+ sourceRunId: "owner-1",+ },+ ],+ "deployment-b",+ retention === undefined ? undefined : { experimental_retention: retention },+ );+ },+ );++ function startInput(): SuccessorStartInput & {+ readonly delivery: { readonly kind: "deliver"; readonly payloads: { message: string }[] };+ } {+ return {+ activationToken: "owner-1:handoff:0",+ anchorRunId: "anchor-1",+ attemptKey: "owner-1:0",+ checkpoint: createCheckpoint(),+ delivery: { kind: "deliver", payloads: [{ message: "hello" }] },+ hookTokens: ["eve:session:anchor-1:inbox", "http:alias"],+ sourceRunId: "owner-1",+ targetDeploymentId: "deployment-b",+ };+ }+});++describe("signalSessionOwnerActivationStep", () => {+ it("treats an owner that already settled the attempt as told", async () => {+ resumeHookMock.mockRejectedValue(new HookNotFoundError("owner-1:handoff:0"));+ await expect(+ signalSessionOwnerActivationStep({+ activation: { kind: "active" },+ token: "owner-1:handoff:0",+ }),+ ).resolves.toBeUndefined();+ });+});+describe("stopUntrackedChildSessionsStep", () => {it("stops every child except the session itself and tolerates finished runs", async () => {cancelRunMock.mockReset();@@ -142,7 +297,8 @@ describe("stopUntrackedChildSessionsStep", () => {});function validate(checkpoint: SessionCheckpoint) {- return validateSessionCheckpointStep({+ return prepareSuccessorStep({+ handoffVersion: 3,migration: { kind: "current", checkpoint, childRunIdsToStop: [] },sessionId: "session-1",});diff --git a/packages/eve/src/execution/session/handoff-steps.ts b/packages/eve/src/execution/session/handoff-steps.tsindex 4a1b58d26..f69552c68 100644--- a/packages/eve/src/execution/session/handoff-steps.ts+++ b/packages/eve/src/execution/session/handoff-steps.ts@@ -4,18 +4,37 @@ import { getBlockingWorkflowToolRuns } from "#harness/workflow-tool-runs.js";import { holdsHitlRequests } from "#harness/hitl/index.js";import {EntityConflictError,+ HookNotFoundError,RunExpiredError,WorkflowRunNotFoundError,} from "#compiled/@workflow/errors/index.js";+import type { SessionHandoverPayload } from "#execution/session-inbox/inbox.js";+import { findSessionHookHolder } from "#execution/session-inbox/owner.js";+import { mapWithConcurrency } from "#shared/map-with-concurrency.js";+import {+ sessionCommandHookToken,+ sessionInboxHookToken,+} from "#execution/session-inbox/address.js";import { deserializeContext, IncompatibleStateLayoutError } from "#context/serialize.js";import type { SessionCheckpointMigration } from "#execution/session/checkpoint-migrations.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 { createLogger, logError } from "#internal/logging.js";-import { cancelRun, getWorld, resumeHook } from "#internal/workflow/runtime.js";+import { cancelRun, getRun, getWorld, resumeHook } from "#internal/workflow/runtime.js";+import {+ hasRunEnded,+ startWorkflowOnDeployment,+ workflowEntryReference,+} from "#execution/workflow-runtime.js";+import {+ SESSION_HANDOFF_VERSION,+ type HandoffWorkflowEntryInput,+ type SessionHandoffStart,+} from "#execution/session/entry-input.js";import { resolveInstalledPackageInfo } from "#internal/application/package.js";import {EVE_SESSION_ATTRIBUTE,@@ -58,28 +77,91 @@ export function isSessionStateIdleForHandoff(input: {);}-/** Reads durable work using the source deployment's handoff contract. */-export async function isSessionIdleForHandoffStep(input: {- readonly sessionState: DurableSessionState;-}): Promise<boolean> {+export type SuccessorStartInput = SessionHandoffStart & {+ readonly activationToken: string;+ /** Original run whose stream stays the public session stream. */+ readonly anchorRunId: string;+ readonly attemptKey: string;+ readonly checkpoint: SessionCheckpoint;+ readonly hookTokens: readonly string[];+ /** The owner starting the successor, which hands over what it accepts meanwhile. */+ readonly sourceRunId: string;+ readonly targetDeploymentId: string;+};++export type SuccessorStart =+ | { readonly kind: "not-idle" }+ | { readonly kind: "unsupported" }+ | { readonly kind: "started"; readonly runId: string };++/**+ * Starts a successor owner bound to the original session stream, unless this+ * deployment's code finds work in the checkpoint that cannot move yet, or the+ * World cannot move session addresses between runs without releasing them.+ */+export async function startSuccessorStep(input: SuccessorStartInput): Promise<SuccessorStart> {+ "use step";+ const { activationToken, anchorRunId, checkpoint, targetDeploymentId, ...start } = input;+ const { capabilities } = await getWorld();+ // Forced claims move the addresses; the attempt lease must outlive its candidate.+ if (capabilities?.hookForceClaim !== true || capabilities.hookRetention?.active !== true) {+ log.warn("session handoff unavailable: the Workflow world cannot force-claim hooks", {+ sessionId: anchorRunId,+ });+ return { kind: "unsupported" };+ }+ if (!isSessionStateIdleForHandoff(checkpoint)) return { kind: "not-idle" };+ const workflowInput: HandoffWorkflowEntryInput = {+ ...start,+ activationToken,+ checkpoint,+ handoffVersion: SESSION_HANDOFF_VERSION,+ kind: "handoff",+ ownerDeploymentId: targetDeploymentId,+ sessionWritable: getRun(anchorRunId).getWritable<Uint8Array>(),+ sessionId: anchorRunId,+ };+ // The successor is stamped with this eve version at start, because the+ // queue guard runs before it boots. Single-build Worlds share this version;+ // deployment-affine Worlds bypass the guard and the successor records its+ // own version at boot.+ const run = await startWorkflowOnDeployment(+ workflowEntryReference,+ [workflowInput],+ targetDeploymentId,+ checkpoint.retention === undefined+ ? undefined+ : { experimental_retention: checkpoint.retention },+ );+ return { kind: "started", runId: run.runId };+}++/** Whether `runId` has ended; a run not readable yet has not. */+export async function hasRunEndedStep(input: { readonly runId: string }): Promise<boolean> {"use step";- return isSessionStateIdleForHandoff(input);+ return await hasRunEnded(input.runId);}export type SessionCheckpointValidation =| { readonly kind: "valid" }- | { readonly kind: "incompatible"; readonly reason: "checkpoint-version" };+ | { readonly kind: "incompatible"; readonly reason: "checkpoint-version" }+ /** The source no longer holds every address it handed over, so none may be taken. */+ | { readonly kind: "source-gone" };/**- * Validates an upgraded checkpoint and resolves the target deployment's- * compiled bundle.+ * Validates an upgraded checkpoint, resolves the target deployment's compiled+ * bundle, and records this owner's identity before it claims any hook.** A checkpoint this deployment cannot read is a settled answer, not a fault,* so it returns rather than throws: retrying the step can never change it.*/-export async function validateSessionCheckpointStep(input: {+export async function prepareSuccessorStep(input: {+ /** Absent for version 1 sources, which predate the field. */+ readonly handoffVersion: number | undefined;readonly migration: SessionCheckpointMigration;readonly sessionId: string;+ /** Version 3: the run that still holds the session and the addresses it hands over. */+ readonly source?: { readonly runId: string; readonly hookTokens: readonly string[] };}): Promise<SessionCheckpointValidation> {"use step";const { migration } = input;@@ -134,9 +216,38 @@ export async function validateSessionCheckpointStep(input: {if (!isSessionStateIdleForHandoff(checkpoint)) {throw new Error("Session checkpoint contains pending work and cannot be handed off.");}+ if (input.source !== undefined && !(await holdsEveryAddress(input.source))) {+ return { kind: "source-gone" };+ }+ await recordSessionOwner(input.sessionId);+ // Owners on releases before version 3 release their addresses first. This+ // line shows when none remain, which is when that compatibility can go.+ if ((input.handoffVersion ?? 1) < SESSION_HANDOFF_VERSION) {+ log.info("session moved from an owner that releases its addresses first", {+ handoffVersion: input.handoffVersion ?? 1,+ sessionId: input.sessionId,+ });+ }return { kind: "valid" };}+/**+ * Whether `source.runId` still holds every address. A delayed successor whose+ * source has ended could otherwise force-claim a channel alias that a new+ * session reuses. The source can still end between this check and the claims+ * that follow, but that window is one step rather than a queue delay.+ */+async function holdsEveryAddress(source: {+ readonly runId: string;+ readonly hookTokens: readonly string[];+}): Promise<boolean> {+ // A session may hold up to 256 addresses.+ const holders = await mapWithConcurrency(source.hookTokens, 16, (token) =>+ findSessionHookHolder(sessionInboxHookToken(token)),+ );+ return holders.every((holder) => holder?.runId === source.runId);+}+/*** Stops idle subagent sessions an older owner kept resumable, after this owner* activates. Best effort: a child that cannot be stopped ends at its own timeout.@@ -184,19 +295,23 @@ export async function reportSessionHandoffRetainedStep(input: {}/**- * Records the identity of an owner that this deployment's code did not start- * (a handoff successor or a legacy importer) before it claims any hook:- * ingress reads `$eve.version` to decide whether the owner can run, so a- * missing value would strand a healthy session. The value comes from this- * step's code, not the previous owner's. Unlike observability attributes, a- * failed write fails the boot.+ * Records the identity of a legacy importer before it claims any hook;+ * handoff successors do the same inside `prepareSuccessorStep`. Ingress reads+ * `$eve.version` to decide whether the owner can run, so a missing value would+ * strand a healthy session. The value comes from this step's code, not the+ * previous owner's. Unlike observability attributes, a failed write fails the+ * boot.*/export async function recordSessionOwnerStep(input: { readonly sessionId: string }): Promise<void> {"use step";+ await recordSessionOwner(input.sessionId);+}++async function recordSessionOwner(sessionId: string): Promise<void> {const { setAttributes } = await import("#compiled/@workflow/core/index.js");await setAttributes({- [EVE_SESSION_ATTRIBUTE]: input.sessionId,+ [EVE_SESSION_ATTRIBUTE]: sessionId,[EVE_VERSION_ATTRIBUTE]: resolveInstalledPackageInfo().version,},{ allowReservedAttributes: true },@@ -208,7 +323,60 @@ export async function signalSessionOwnerActivationStep(input: {readonly token: string;}): Promise<void> {"use step";- await resumeHook(input.token, input.activation);+ try {+ await resumeHook(input.token, input.activation);+ } catch (error) {+ // The owner already settled the attempt and disposed the hook.+ if (!HookNotFoundError.is(error)) throw error;+ }+}++/** Makes a takeover with no attempt open visible: every forced claim belongs to one. */+export async function reportSessionTakenOverOutsideAttemptStep(input: {+ readonly sessionId: string;+}): Promise<void> {+ "use step";+ log.error("session taken over with no handoff attempt open; this run leaves without finalizing", {+ sessionId: input.sessionId,+ });+}++/**+ * Makes a move whose handover part keeps failing visible; the owner keeps+ * retrying, because dropping the part would lose an accepted message.+ */+export async function reportHandoverPartStuckStep(input: {+ readonly attemptKey: string;+ readonly error: string | undefined;+ readonly failures: number;+ readonly index: number;+ readonly sessionId: string;+}): Promise<void> {+ "use step";+ log.warn("session handover part keeps failing; the previous owner keeps retrying", input);+}++/**+ * Sends one handover part through the stable session address, which reaches+ * whichever run owns the session. A part that keeps failing fails the step,+ * for the caller to retry until it is delivered.+ */+export async function sendSessionHandoverPartStep(input: {+ readonly part: Omit<SessionHandoverPayload, "kind">;+ readonly sessionId: string;+}): Promise<"delivered" | "session-ended"> {+ "use step";+ try {+ await resumeHook(sessionInboxHookToken(sessionCommandHookToken(input.sessionId)), {+ ...input.part,+ kind: "handover",+ } satisfies SessionHandoverPayload);+ return "delivered";+ } catch (error) {+ // The session has ended, so nothing waits for these payloads.+ if (HookNotFoundError.is(error)) return "session-ended";+ throw error;+ }}export async function signalSessionAnchorStep(input: {diff --git a/packages/eve/src/execution/session/handoff.test.ts b/packages/eve/src/execution/session/handoff.test.tsindex cfe922588..9c149c620 100644--- a/packages/eve/src/execution/session/handoff.test.ts+++ b/packages/eve/src/execution/session/handoff.test.ts@@ -1,4 +1,4 @@-import { afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { DeliverHookPayload } from "#channel/types.js";import type { DurableSessionState } from "#execution/durable-session-store.js";@@ -10,36 +10,73 @@ import {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 reportSessionHandoffRetainedStepMock = vi.fn();-const startSessionOwnerStepMock = vi.fn();+const sendSessionHandoverPartStepMock = vi.fn();+const reportHandoverPartStuckStepMock = vi.fn();+const startSuccessorStepMock = vi.fn();const createHookMock = vi.fn();+const sleepMock = vi.fn();++const abandonHandoverIfRunEndsMock = vi.fn();+/** Resolving it ends the watched candidate run. */+let candidateEnded = Promise.withResolvers<void>();+/** Resolvers for the inbox's pending arrival waits; resolving one delivers a payload. */+const arrivals: (() => void)[] = [];+/** The workflow clock, in milliseconds since the attempt began. */+let now = 0;+const watchedRuns: string[] = [];+const endedRuns = new Set<string>();vi.mock("#execution/session/handoff-steps.js", () => ({- isSessionIdleForHandoffStep: (...args: unknown[]) => isSessionIdleForHandoffStepMock(...args),+ hasRunEndedStep: async (input: { runId: string }) => endedRuns.has(input.runId),+ reportHandoverPartStuckStep: (...args: unknown[]) => reportHandoverPartStuckStepMock(...args),reportSessionHandoffRetainedStep: (...args: unknown[]) =>reportSessionHandoffRetainedStepMock(...args),+ sendSessionHandoverPartStep: (...args: unknown[]) => sendSessionHandoverPartStepMock(...args),+ startSuccessorStep: (...args: unknown[]) => startSuccessorStepMock(...args),}));-vi.mock("#execution/workflow-runtime.js", () => ({- startSessionOwnerStep: (...args: unknown[]) => startSessionOwnerStepMock(...args),+vi.mock("#execution/session/run-watch.js", () => ({+ abandonHandoverIfRunEnds: (...args: unknown[]) => abandonHandoverIfRunEndsMock(...args),+ watchRunEnd: (runId: string) => {+ watchedRuns.push(runId);+ return { ended: candidateEnded.promise, stop: () => {} };+ },}));vi.mock("#compiled/@workflow/core/index.js", () => ({createHook: (...args: unknown[]) => createHookMock(...args),getWorkflowMetadata: () => ({ workflowRunId: "owner-1" }),+ sleep: (...args: unknown[]) => sleepMock(...args),}));+beforeEach(() => {+ sendSessionHandoverPartStepMock.mockResolvedValue("delivered");+ sleepMock.mockResolvedValue(undefined);+ vi.spyOn(Date, "now").mockImplementation(() => now);+});+afterEach(() => {vi.resetAllMocks();- isSessionIdleForHandoffStepMock.mockResolvedValue(true);+ candidateEnded = Promise.withResolvers<void>();+ arrivals.length = 0;+ now = 0;+ vi.restoreAllMocks();+ watchedRuns.length = 0;+ endedRuns.clear();});-const STABLE = "eve:session:session-1:inbox";+const STARTED = { kind: "started", runId: "candidate-1" } as const;++const TOKENS = ["eve:session:session-1:inbox", "channel:current"];describe("SessionHandoff", () => {- it("transfers one eligible conversational trigger with a structural checkpoint", async () => {- const handoff = createHandoff(createInbox());- installActivation({ kind: "active" });- startSessionOwnerStepMock.mockResolvedValue(undefined);+ it("hands over what it accepted once the successor takes over every hook", async () => {+ const accepted: SessionInboxPayload[] = [+ { kind: "send", payload: { message: "Bob writes during the move." } },+ ];+ const inbox = createInbox({ takenOver: true, unread: accepted });+ const handoff = createHandoff(inbox);+ installActivation();+ startSuccessorStepMock.mockResolvedValue(STARTED);const trigger = selection("deployment-b");const history = [{ content: "Alice asks for the status.", kind: "user" as const, role: "user" as const },@@ -48,17 +85,28 @@ describe("SessionHandoff", () => {await expect(handoff.tryTransfer(trigger, { ...state(), history })).resolves.toEqual({kind: "transferred",});- expect(startSessionOwnerStepMock).toHaveBeenCalledWith({- activationToken: "owner-1:handoff",+ expect(startSuccessorStepMock).toHaveBeenCalledWith({+ activationToken: "owner-1:handoff:0",anchorRunId: "session-1",+ attemptKey: "owner-1:0",checkpoint: expect.objectContaining({history,sessionTimeoutMs: 60_000,version: SESSION_CHECKPOINT_VERSION,}),delivery: trigger.delivery,+ hookTokens: TOKENS,+ sourceRunId: "owner-1",targetDeploymentId: "deployment-b",});+ expect(sendSessionHandoverPartStepMock.mock.calls.map(([call]) => call)).toEqual([+ { part: { attemptKey: "owner-1:0", index: 0, payloads: accepted }, sessionId: "session-1" },+ {+ part: { attemptKey: "owner-1:0", final: true, index: 1, payloads: [] },+ sessionId: "session-1",+ },+ ]);+ expect(inbox.claimSessionHooks).not.toHaveBeenCalled();await expect(handoff.awaitAnchoredResult()).resolves.toEqual({ output: "done" });});@@ -66,222 +114,358 @@ describe("SessionHandoff", () => {["same-deployment", "deployment-a"],["missing-deployment", "latest"],] as const)("retains ownership for %s", async (reason, deployment) => {- installActivation({ kind: "active" });+ installActivation();const handoff = createHandoff(createInbox());await expect(handoff.tryTransfer(selection(deployment), state())).resolves.toEqual({kind: "retained",reason,});- expect(startSessionOwnerStepMock).not.toHaveBeenCalled();+ expect(startSuccessorStepMock).not.toHaveBeenCalled();});- it("moves a compacted session to this deployment with the delivery that arrived first", async () => {- installActivation({ kind: "active" });- startSessionOwnerStepMock.mockResolvedValue(undefined);+ it("moves a compacted session to a parked successor on this deployment", async () => {+ installActivation();+ startSuccessorStepMock.mockResolvedValue(STARTED);const sessionTimeoutDeadline = new Date("2026-11-01T00:00:00.000Z");- const trigger = selection("deployment-a");await expect(- createHandoff(createInbox()).tryTransfer(trigger, state(), {- compaction: { sessionTimeoutDeadline },- }),- ).resolves.toEqual({ kind: "transferred" });- expect(startSessionOwnerStepMock).toHaveBeenCalledWith(- expect.objectContaining({- delivery: trigger.delivery,- reason: "compaction",+ createHandoff(createInbox({ takenOver: true })).tryCompactionTransfer(state(), {sessionTimeoutDeadline,- targetDeploymentId: "deployment-a",- }),- );- });-- it("moves a compacted session to a newer deployment as a deployment handoff", async () => {- installActivation({ kind: "active" });- startSessionOwnerStepMock.mockResolvedValue(undefined);-- await expect(- createHandoff(createInbox()).tryTransfer(selection("deployment-b"), state(), {- compaction: { sessionTimeoutDeadline: new Date("2026-11-01T00:00:00.000Z") },}),).resolves.toEqual({ kind: "transferred" });- const [start] = startSessionOwnerStepMock.mock.calls[0] as [Record<string, unknown>];- expect(start).toMatchObject({ targetDeploymentId: "deployment-b" });- expect(start).not.toHaveProperty("reason");+ const [start] = startSuccessorStepMock.mock.calls[0] as [Record<string, unknown>];+ expect(start).toMatchObject({+ reason: "compaction",+ sessionTimeoutDeadline,+ targetDeploymentId: "deployment-a",+ });+ expect(start).not.toHaveProperty("delivery");});- it("retains ownership when the selection was not a lone fresh conversational delivery", async () => {- installActivation({ kind: "active" });- const inbox = createInbox();+ it.each([+ ["the selection was not a lone fresh delivery", { handoffEligible: false }, {}],+ ["a previous attempt's handover has not arrived", {}, { awaitingHandover: true }],+ ] as const)("stays busy when %s", async (_name, selected, inboxState) => {+ installActivation();await expect(- createHandoff(inbox).tryTransfer(- { ...selection("deployment-b"), handoffEligible: false },+ createHandoff(createInbox(inboxState)).tryTransfer(+ { ...selection("deployment-b"), ...selected },state(),),).resolves.toEqual({ kind: "retained", reason: "busy" });- expect(inbox.release).not.toHaveBeenCalled();+ expect(startSuccessorStepMock).not.toHaveBeenCalled();});- it("retains ownership when durable state still holds work", async () => {- installActivation({ kind: "active" });- isSessionIdleForHandoffStepMock.mockResolvedValue(false);+ it("retains ownership without a handover when the start step finds work", async () => {+ installActivation();+ startSuccessorStepMock.mockResolvedValue({ kind: "not-idle" });const inbox = createInbox();await expect(createHandoff(inbox).tryTransfer(selection("deployment-b"), state()),).resolves.toEqual({ kind: "retained", reason: "not-idle" });- expect(inbox.release).not.toHaveBeenCalled();+ expect(sendSessionHandoverPartStepMock).not.toHaveBeenCalled();+ expect(created.find((hook) => hook.token === "owner-1:handoff:0")?.dispose).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"] },+ it("still hands over once the successor took over when the start step failed after creating it", async () => {+ const inbox = createInbox({ takenOver: true });+ installActivation();+ leaseHolder = "candidate-1";+ startSuccessorStepMock.mockRejectedValue(new Error("start response lost"));++ await expect(+ createHandoff(inbox).tryTransfer(selection("deployment-b"), state()),+ ).resolves.toEqual({ kind: "transferred" });+ expect(sendSessionHandoverPartStepMock).toHaveBeenCalledOnce();+ });++ it("retains the session when it wins the lease of an attempt whose start step failed", async () => {+ const inbox = createInbox({ takenOver: true });+ installActivation();+ startSuccessorStepMock.mockRejectedValue(new Error("deployment unreachable"));++ await expect(+ createHandoff(inbox).tryTransfer(selection("deployment-b"), state()),+ ).resolves.toEqual({ kind: "retained", reason: "activation-failed" });+ expect(created.map((hook) => hook.token)).toContain("eve:handoff:lease:owner-1:0");+ expect(sendSessionHandoverPartStepMock).not.toHaveBeenCalled();+ });++ it("fences at the deadline once one early message waits, and watches a live lease holder", async () => {+ let pending = false;+ const inbox = createInbox({ hasPending: () => pending });+ const deadline = Promise.withResolvers<void>();+ sleepMock.mockReturnValueOnce(deadline.promise);+ installActivation();+ leaseHolder = "candidate-1";+ startSuccessorStepMock.mockResolvedValue(STARTED);+ const outcome = createHandoff(inbox).tryTransfer(selection("deployment-b"), state());++ // Nothing waits, so no timer runs.+ await vi.waitFor(() => expect(arrivals).toHaveLength(1));+ expect(sleepMock).not.toHaveBeenCalled();+ now = 60_000;+ pending = true;+ arrivals.shift()!();+ await vi.waitFor(() => expect(sleepMock).toHaveBeenCalledWith(4 * 60_000));+ expect(created.map((hook) => hook.token)).not.toContain("eve:handoff:lease:owner-1:0");++ // No further input arrives; the deadline alone fences the attempt.+ deadline.resolve();+ await vi.waitFor(() => expect(watchedRuns).toEqual(["candidate-1"]));+ expect(reportSessionHandoffRetainedStepMock).not.toHaveBeenCalled();+ endedRuns.add("candidate-1");+ candidateEnded.resolve();++ await expect(outcome).resolves.toEqual({ kind: "retained", reason: "activation-failed" });+ // It may hold addresses this run's pumps have not seen it take yet.+ expect(inbox.claimSessionHooks).toHaveBeenCalledWith(TOKENS, { force: true });+ });++ it("counts input accepted during the start step and wins the lease from a candidate that never boots", async () => {+ const inbox = createInbox({ hasPending: () => true });+ installActivation();+ startSuccessorStepMock.mockImplementation(async () => {+ now = 30_000;+ return STARTED;});await expect(- createHandoff(inbox).tryTransfer(selection("deployment-b"), aliased),- ).resolves.toEqual({- kind: "transferred",+ createHandoff(inbox).tryTransfer(selection("deployment-b"), state()),+ ).resolves.toEqual({ kind: "retained", reason: "activation-failed" });+ expect(sleepMock).toHaveBeenCalledWith(5 * 60_000 - 30_000);+ const lease = created.find((hook) => hook.token === "eve:handoff:lease:owner-1:0");+ // Disposing it would free the token for a candidate that boots late.+ expect(lease?.dispose).not.toHaveBeenCalled();+ expect(watchedRuns).toEqual([]);+ expect(inbox.claimSessionHooks).not.toHaveBeenCalled();+ });++ it("keeps waiting for the lease winner when a duplicate candidate reports a failure", async () => {+ const takeover = Promise.withResolvers<void>();+ const inbox = createInbox({ whenTakenOver: takeover.promise });+ installActivation({+ error: new Error("lost the race to prepare"),+ kind: "failed",+ payloads: [],+ runId: "candidate-2",});- 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();- }+ // The start step ran twice: it returned the duplicate, and the first run holds the lease.+ leaseHolder = "candidate-1";+ startSuccessorStepMock.mockResolvedValue({ kind: "started", runId: "candidate-2" });+ const outcome = createHandoff(inbox).tryTransfer(selection("deployment-b"), state());++ await vi.waitFor(() => expect(watchedRuns).toEqual(["candidate-1"]));+ expect(reportSessionHandoffRetainedStepMock).not.toHaveBeenCalled();+ expect(inbox.claimSessionHooks).not.toHaveBeenCalled();+ expect(sleepMock).not.toHaveBeenCalled();+ takeover.resolve();++ await expect(outcome).resolves.toEqual({ kind: "transferred" });});- it("keeps ownership and restores accepted payloads when activation fails", async () => {+ it("retains on the verdict of the candidate that holds the lease", async () => {+ installActivation({+ error: new Error("could not read state"),+ kind: "failed",+ payloads: [],+ runId: "candidate-1",+ });+ leaseHolder = "candidate-1";+ startSuccessorStepMock.mockResolvedValue(STARTED);+const inbox = createInbox();- const payloads: SessionInboxPayload[] = [- { kind: "send", payload: { message: "Alice sends the first input." } },- { kind: "send", payload: { message: "Bob sends the second input." } },+ await expect(+ createHandoff(inbox).tryTransfer(selection("deployment-b"), state()),+ ).resolves.toEqual({ kind: "retained", reason: "activation-failed" });+ expect(watchedRuns).toEqual([]);+ // It reported holding no address.+ expect(inbox.claimSessionHooks).not.toHaveBeenCalled();+ });++ it("retries every handover part until it is delivered, in order", async () => {+ const accepted: SessionInboxPayload[] = [+ { kind: "send", payload: { message: "Bob's first note." } },+ { kind: "send", payload: { message: "Bob's second note." } },];- installActivation({ error: new Error("bundle mismatch"), kind: "failed", payloads });- startSessionOwnerStepMock.mockResolvedValue(undefined);+ installActivation();+ startSuccessorStepMock.mockResolvedValue(STARTED);+ sendSessionHandoverPartStepMock+ .mockRejectedValueOnce(new Error("store unavailable"))+ .mockRejectedValueOnce(new Error("store unavailable"))+ .mockResolvedValueOnce("delivered")+ .mockResolvedValueOnce("delivered")+ .mockRejectedValueOnce(new Error("store unavailable"))+ .mockResolvedValueOnce("delivered");await expect(- createHandoff(inbox).tryTransfer(+ createHandoff(createInbox({ takenOver: true, unread: accepted })).tryTransfer(selection("deployment-b"),- state({ continuationToken: "channel:current" }),+ state(),),- ).resolves.toEqual({ kind: "retained", reason: "activation-failed" });- expect(inbox.claimSessionHooks).toHaveBeenCalledWith([STABLE, "channel:current"]);- expect(inbox.restore).toHaveBeenCalledWith(payloads);+ ).resolves.toEqual({ kind: "transferred" });+ expect(sendSessionHandoverPartStepMock.mock.calls.map(([call]) => call.part.index)).toEqual([+ 0, 0, 0, 1, 2, 2,+ ]);+ expect(sleepMock.mock.calls).toEqual([[1000], [2000], [1000]]);+ });++ it("reports a part that keeps failing once, and keeps retrying it", async () => {+ installActivation();+ startSuccessorStepMock.mockResolvedValue(STARTED);+ reportHandoverPartStuckStepMock.mockResolvedValue(undefined);+ for (let failure = 0; failure < 6; failure++)+ sendSessionHandoverPartStepMock.mockRejectedValueOnce(new Error("store unavailable"));+ sendSessionHandoverPartStepMock.mockResolvedValue("delivered");++ await expect(+ createHandoff(createInbox({ takenOver: true })).tryTransfer(+ selection("deployment-b"),+ state(),+ ),+ ).resolves.toEqual({ kind: "transferred" });+ expect(sendSessionHandoverPartStepMock).toHaveBeenCalledTimes(7);+ expect(reportHandoverPartStuckStepMock.mock.calls).toEqual([+ [+ {+ attemptKey: "owner-1:0",+ error: "store unavailable",+ failures: 5,+ index: 0,+ sessionId: "session-1",+ },+ ],+ ]);+ });++ it("stops sending once the session has ended", async () => {+ installActivation();+ startSuccessorStepMock.mockResolvedValue(STARTED);+ sendSessionHandoverPartStepMock.mockResolvedValue("session-ended");+ const unread: SessionInboxPayload[] = [+ { kind: "send", payload: { message: "Bob's note." } },+ { kind: "send", payload: { message: "Bob's follow-up." } },+ ];++ await expect(+ createHandoff(createInbox({ takenOver: true, unread })).tryTransfer(+ selection("deployment-b"),+ state(),+ ),+ ).resolves.toEqual({ kind: "transferred" });+ expect(sendSessionHandoverPartStepMock).toHaveBeenCalledOnce();});it("remembers every incompatible target for the rest of the owner run", async () => {const inbox = createInbox();- const payloads: SessionInboxPayload[] = [- { kind: "send", payload: { message: "Alice sends a follow-up." } },- ];- installActivationSequence(- { kind: "incompatible", payloads, reason: "checkpoint-version" },- { kind: "incompatible", payloads, reason: "checkpoint-version" },+ installActivation(+ { kind: "incompatible", payloads: [], reason: "checkpoint-version" },+ // A successor older than this protocol cannot take over from an owner that keeps its hooks.+ {+ error: { message: "Hook token is already in use", name: "HookConflictError" },+ kind: "failed",+ payloads: [],+ },);- startSessionOwnerStepMock.mockResolvedValue(undefined);+ startSuccessorStepMock.mockResolvedValue(STARTED);const handoff = createHandoff(inbox);await expect(handoff.tryTransfer(selection("deployment-b"), state())).resolves.toEqual({kind: "retained",reason: "checkpoint-incompatible",});- expect(inbox.restore).toHaveBeenCalledWith(payloads);-await expect(handoff.tryTransfer(selection("deployment-b"), state())).resolves.toEqual({kind: "retained",reason: "known-incompatible",});- expect(startSessionOwnerStepMock).toHaveBeenCalledTimes(1);- expect(inbox.release).toHaveBeenCalledTimes(1);-await expect(handoff.tryTransfer(selection("deployment-c"), state())).resolves.toEqual({kind: "retained",- reason: "checkpoint-incompatible",+ reason: "activation-failed",});- expect(startSessionOwnerStepMock).toHaveBeenCalledTimes(2);-- await expect(handoff.tryTransfer(selection("deployment-b"), state())).resolves.toEqual({+ await expect(handoff.tryTransfer(selection("deployment-c"), state())).resolves.toEqual({kind: "retained",reason: "known-incompatible",});- expect(startSessionOwnerStepMock).toHaveBeenCalledTimes(2);- // Each refusing deployment is reported once; remembered skips stay quiet.- expect(reportSessionHandoffRetainedStepMock.mock.calls).toEqual(- ["deployment-b", "deployment-c"].map((targetDeploymentId) => [- {- error: undefined,- reason: "checkpoint-incompatible",- sessionId: "session-1",- sourceDeploymentId: "deployment-a",- targetDeploymentId,- },- ]),- );+ expect(startSuccessorStepMock.mock.calls.map(([start]) => start.attemptKey)).toEqual([+ "owner-1:0",+ "owner-1:1",+ ]);+ expect(inbox.claimSessionHooks).not.toHaveBeenCalled();+ expect(reportSessionHandoffRetainedStepMock.mock.calls.map(([report]) => report)).toEqual([+ expect.objectContaining({+ reason: "checkpoint-incompatible",+ targetDeploymentId: "deployment-b",+ }),+ expect.objectContaining({ reason: "activation-failed", targetDeploymentId: "deployment-c" }),+ ]);});- it("attempts handoff on every turn when the owner only sees a generic activation failure", async () => {- installActivation({ error: new Error("unsupported checkpoint"), kind: "failed", payloads: [] });- startSessionOwnerStepMock.mockResolvedValue(undefined);+ it("stops attempting for the owner's lifetime on a World that cannot force-claim hooks", async () => {+ installActivation();+ startSuccessorStepMock.mockResolvedValue({ kind: "unsupported" });const handoff = createHandoff(createInbox());await expect(handoff.tryTransfer(selection("deployment-b"), state())).resolves.toEqual({kind: "retained",- reason: "activation-failed",- });- await expect(handoff.tryTransfer(selection("deployment-b"), state())).resolves.toEqual({- kind: "retained",- reason: "activation-failed",+ reason: "unsupported-world",});- expect(startSessionOwnerStepMock).toHaveBeenCalledTimes(2);- expect(reportSessionHandoffRetainedStepMock).toHaveBeenCalledWith(- expect.objectContaining({ error: "unsupported checkpoint", reason: "activation-failed" }),- );+ await expect(+ handoff.tryCompactionTransfer(state(), { sessionTimeoutDeadline: undefined }),+ ).resolves.toEqual({ kind: "retained", reason: "unsupported-world" });+ expect(startSuccessorStepMock).toHaveBeenCalledTimes(1);+ expect(reportSessionHandoffRetainedStepMock).not.toHaveBeenCalled();});- 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 });+ it("attempts again on every turn after a generic activation failure", async () => {+ const failure = {+ error: new Error("unsupported checkpoint"),+ kind: "failed",+ payloads: [],+ } as const;+ installActivation(failure, failure);+ startSuccessorStepMock.mockResolvedValue(STARTED);+ const handoff = createHandoff(createInbox());- 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);+ for (let attempt = 0; attempt < 2; attempt++) {+ await expect(handoff.tryTransfer(selection("deployment-b"), state())).resolves.toEqual({+ kind: "retained",+ reason: "activation-failed",+ });+ }+ expect(startSuccessorStepMock).toHaveBeenCalledTimes(2);+ expect(reportSessionHandoffRetainedStepMock).toHaveBeenCalledWith(+ expect.objectContaining({ error: "unsupported checkpoint", reason: "activation-failed" }),+ );});});const created: { token: string; dispose: ReturnType<typeof vi.fn> }[] = [];-function createdHooks() {- return created;-}--function installActivation(activation: SessionOwnerActivation): void {- installActivationSequence(activation);-}--function installActivationSequence(...activations: SessionOwnerActivation[]): void {+/** The run already holding the attempt lease, if any. */+let leaseHolder: string | undefined;++/**+ * Like a real hook, each await of an activation hook takes the next verdict;+ * once they run out it never answers.+ */+function installActivation(...verdicts: SessionOwnerActivation[]): void {created.length = 0;- let index = 0;+ leaseHolder = undefined;+ const remaining = [...verdicts];createHookMock.mockImplementation((options: { token: string }) => {- const resolved = options.token.endsWith(":anchor")- ? { output: "done" }- : (activations[Math.min(index++, activations.length - 1)] ?? activations.at(-1)!);- const hook = Object.assign(Promise.resolve(resolved), {+ const isLease = options.token.startsWith("eve:handoff:lease:");+ const next = (): Promise<unknown> => {+ if (options.token.endsWith(":anchor")) return Promise.resolve({ output: "done" });+ const verdict = isLease ? undefined : remaining.shift();+ return verdict === undefined ? new Promise(() => {}) : Promise.resolve(verdict);+ };+ const conflict = isLease ? leaseHolder : undefined;+ const hook = {+ // oxlint-disable-next-line unicorn/no-thenable -- Workflow hooks are awaited for each payload.+ then: (...handlers: Parameters<Promise<unknown>["then"]>) => next().then(...handlers),dispose: vi.fn(),- getConflict: vi.fn(async () => null),+ getConflict: vi.fn(async () => (conflict === undefined ? null : { runId: conflict })),token: options.token,- });+ };created.push(hook);return hook;});@@ -315,17 +499,12 @@ function selection(acceptedDeploymentId: string): TurnSelection {};}-function state(- input: {- readonly continuationToken?: string;- readonly serializedContext?: Record<string, unknown>;- } = {},-) {+function state() {return {history: [],- serializedContext: input.serializedContext ?? {},+ serializedContext: {},sessionState: {- continuationToken: input.continuationToken ?? "",+ continuationToken: "channel:current",sessionId: "session-1",} as DurableSessionState,};@@ -341,20 +520,37 @@ function createHandoff(inbox: SessionInboxHandle): SessionHandoff {});}-function createInbox(input: { released?: SessionInboxPayload[] } = {}): SessionInboxHandle {+function createInbox(+ input: {+ readonly awaitingHandover?: boolean;+ readonly takenOver?: boolean;+ readonly unread?: SessionInboxPayload[];+ readonly whenTakenOver?: Promise<void>;+ readonly hasPending?: () => boolean;+ } = {},+): SessionInboxHandle {return {+ abandonHandover: vi.fn(),+ awaitingHandover: input.awaitingHandover ?? false,+ takenOver: false,+ whenHandoverSettled: () => new Promise<void>(() => {}),claimSessionHook: vi.fn(async () => {}),claimSessionHooks: vi.fn(async () => {}),- claimedTokens: [],+ claimedTokens: TOKENS,takeLeading: () => [],dispose: vi.fn(async () => {}),- drain: vi.fn(() => []),- hasPending: vi.fn(() => false),+ drain: vi.fn(() => input.unread ?? []),+ hasPending: vi.fn(input.hasPending ?? (() => false)),whenPending: () => new Promise<void>(() => {}),+ whenArrival: () => new Promise<void>((resolve) => arrivals.push(resolve)),+ whenBlockedOnHandover: () => new Promise<void>(() => {}),+ whenTakenOver: () =>+ input.whenTakenOver ??+ (input.takenOver === true ? Promise.resolve() : new Promise<void>(() => {})),next: vi.fn(),onDelivery: vi.fn(() => () => {}),onInterrupt: vi.fn(() => () => {}),- release: vi.fn(async () => input.released ?? []),+ release: vi.fn(async () => []),restore: vi.fn(),};}diff --git a/packages/eve/src/execution/session/handoff.ts b/packages/eve/src/execution/session/handoff.tsindex 25b17d95e..42fbc99e1 100644--- a/packages/eve/src/execution/session/handoff.ts+++ b/packages/eve/src/execution/session/handoff.ts@@ -1,20 +1,35 @@-import { createHook, getWorkflowMetadata, type Hook } from "#compiled/@workflow/core/index.js";+import {+ createHook,+ getWorkflowMetadata,+ sleep,+ type Hook,+} from "#compiled/@workflow/core/index.js";-import type { DeliverHookPayload, SessionCapabilities } from "#channel/types.js";+import type { SessionCapabilities } from "#channel/types.js";import { readAcceptedDeploymentId } from "#execution/session/accepted-deployment.js";import type { DurableSessionState } from "#execution/durable-session-store.js";import type { HarnessModelMessage } from "#harness/messages.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 { claimHookOwnership, disposeHook, isHookConflictError } from "#execution/hook-ownership.js";+import type {+ SessionHandoverPayload,+ SessionInboxHandle,+ SessionInboxPayload,+} from "#execution/session-inbox/inbox.js";import type { TurnSelection } from "#execution/session/input-queue.js";import type { SessionHandoffStart, WorkflowEntryResult } from "#execution/session/entry-input.js";-import { startSessionOwnerStep } from "#execution/workflow-runtime.js";-import { sessionHandoffMarkerToken } from "#execution/session-inbox/address.js";import {- isSessionIdleForHandoffStep,+ hasRunEndedStep,+ reportHandoverPartStuckStep,reportSessionHandoffRetainedStep,+ reportSessionTakenOverOutsideAttemptStep,+ sendSessionHandoverPartStep,+ startSuccessorStep,} from "#execution/session/handoff-steps.js";+import {+ abandonHandoverIfRunEnds,+ watchRunEnd,+ type RunWatch,+} from "#execution/session/run-watch.js";import type { AgentWorkflowRetentionDefinition } from "#shared/agent-definition.js";import { isObject } from "#shared/guards.js";@@ -46,12 +61,21 @@ export type SessionOwnerActivation =// failure, so this variant carries `payloads` in the same shape.readonly kind: "incompatible";readonly reason: "checkpoint-version";+ /** Version 3: the successor run that gave this verdict. */+ readonly runId?: string;/** Commands accepted by partial successor claims before it rejected the checkpoint. */readonly payloads: readonly SessionInboxPayload[];}| {readonly kind: "failed";+ /**+ * Version 3: the successor took some of the session's hooks before it+ * failed. The owner takes them back and waits for their handover.+ */+ readonly claimedHooks?: boolean;readonly error: unknown;+ /** Version 3: the successor run that gave this verdict. */+ readonly runId?: string;/** Commands accepted by partial successor claims before startup failed. */readonly payloads: readonly SessionInboxPayload[];};@@ -71,6 +95,17 @@ export function sessionAnchorToken(sessionId: string): string {return `${sessionId}:anchor`;}+/** Only one run per attempt can hold this; a successor that loses it exits untouched. */+export function handoffLeaseToken(attemptKey: string): string {+ return `eve:handoff:lease:${attemptKey}`;+}++/**+ * Measured from the lease's creation and far beyond any queue delay, so a+ * duplicate candidate that boots late still finds the token taken.+ */+export const HANDOFF_LEASE_RETENTION = "7d";+type SessionTransferOutcome =| { readonly kind: "transferred" }| { readonly kind: "retained"; readonly reason: SessionRetainedReason };@@ -80,10 +115,10 @@ type SessionRetainedReason =| "missing-deployment"| "not-idle"| "busy"- | "accepted-during-release"| "activation-failed"| "checkpoint-incompatible"- | "known-incompatible";+ | "known-incompatible"+ | "unsupported-world";/** A compaction handoff the owner owes; the successor keeps this deadline. */export interface CompactionHandoff {@@ -95,49 +130,131 @@ type SessionTransferState = Pick<"history" | "serializedContext" | "sessionState">;+type AttemptSettlement =+ | { readonly kind: "taken-over" }+ | { readonly kind: "candidate-ended" }+ | { readonly kind: "arrival" }+ | { readonly kind: "deadline" }+ | { readonly kind: "verdict"; readonly verdict: SessionOwnerActivation };++/** Who holds an attempt's lease once the owner has tried to claim it. */+type AttemptFence =+ /** The owner: no candidate can take over any more. */+ | { readonly kind: "won" }+ /** A candidate that gave its verdict or has ended. */+ | { readonly kind: "done"; readonly runId: string }+ /** A live candidate that may still take over. */+ | { readonly kind: "live"; readonly runId: string };++/** The successor run that gave a verdict, if the outcome is one. */+function verdictRunId(settled: AttemptSettlement): string | undefined {+ return settled.kind === "verdict" && settled.verdict.kind !== "active"+ ? settled.verdict.runId+ : undefined;+}++/**+ * How long a candidate may stay silent, once input is waiting, before the+ * owner fences the attempt. The timer starts only when input is pending: an+ * open wait turns off Workflow's inline step delta, and a stuck attempt only+ * matters once input is waiting for it.+ */+const HANDOFF_BOOT_DEADLINE_MS = 5 * 60_000;++/**+ * Sends `payloads` as handover parts, one payload per part: each was accepted+ * on its own, so no part exceeds what the World already took. Every part is+ * retried with backoff until it is delivered or the session has ended: the+ * receiver reads nothing until the final part lands, and dropping a part+ * would lose a message the session accepted.+ */+export async function sendSessionHandover(input: {+ readonly attemptKey: string;+ readonly payloads: readonly SessionInboxPayload[];+ readonly sessionId: string;+}): Promise<void> {+ const { attemptKey, sessionId } = input;+ // A handover is consumed on arrival and never queued, so none is ever drained.+ const payloads = input.payloads.filter(+ (payload): payload is SessionHandoverPayload["payloads"][number] => payload.kind !== "handover",+ );+ for (const [index, payload] of payloads.entries()) {+ const sent = await sendHandoverPart({ attemptKey, index, payloads: [payload] }, sessionId);+ if (sent === "session-ended") return;+ }+ await sendHandoverPart(+ { attemptKey, final: true, index: payloads.length, payloads: [] },+ sessionId,+ );+}++async function sendHandoverPart(+ part: Omit<SessionHandoverPayload, "kind">,+ sessionId: string,+): Promise<"delivered" | "session-ended"> {+ for (let failures = 1, delaySeconds = 1; ; failures++) {+ try {+ return await sendSessionHandoverPartStep({ part, sessionId });+ } catch (error) {+ if (failures === HANDOVER_PART_FAILURES_BEFORE_REPORT) {+ await reportHandoverPartStuckStep({+ attemptKey: part.attemptKey,+ error: isObject(error) && typeof error.message === "string" ? error.message : undefined,+ failures,+ index: part.index,+ sessionId,+ }).catch(() => {});+ }+ await sleep(delaySeconds * 1000);+ delaySeconds = Math.min(delaySeconds * 2, 60);+ }+ }+}++/** Each failure is a send step that already exhausted its own retries. */+const HANDOVER_PART_FAILURES_BEFORE_REPORT = 5;++type RetainedAttempt = {+ readonly error?: unknown;+ readonly reason: "activation-failed" | "checkpoint-incompatible";+};+/*** The sole boundary for moving an idle session to a successor run: on another* exact deployment when newer code accepts a delivery, or on this deployment* after compaction so no single run's event log grows with the session.* Constructed once per owner; each `try*` method attempts one transfer.- * When the upstream atomic hook-handoff primitive lands, only this class changes.*- * Skipping known-incompatible targets requires this owner run to execute the- * `incompatible` activation branch below. Owners still on an older eve build- * treat that signal as a generic failure and attempt handoff on every turn;- * they still benefit from successors returning incompatibility without step- * retries.+ * The owner never releases its hooks. The successor force-claims every one of+ * them, and the takeover itself is the success signal: the owner then hands+ * over whatever it accepted meanwhile and exits. Until the attempt settles+ * the owner runs no turn.*/export class SessionHandoff {private readonly input: SessionHandoffInput;private anchor: Hook<WorkflowEntryResult> | undefined;/** Deployments that rejected this session's checkpoint during this owner run. */private readonly incompatibleTargetDeploymentIds = new Set<string>();+ /** Counts this run's attempts; replay repeats the same sequence. */+ private attempts = 0;+ /** The World cannot force-claim hooks, so no attempt can ever succeed. */+ private worldUnsupported = false;constructor(input: SessionHandoffInput) {this.input = input;}/**- * Attempts to move the session to the selected delivery's deployment. When a- * compaction handoff is due and that deployment is this one or unknown, the- * session moves to a fresh run here instead. The outcome states whether the- * successor activated or this owner retained the session. Candidate failures- * recover locally rather than escaping.+ * Attempts to move the session to the selected delivery's deployment. The+ * outcome states whether the successor took over or this owner retained the+ * session. Candidate failures recover locally rather than escaping.*/async tryTransfer(selection: TurnSelection,state: SessionTransferState,- options: { readonly compaction?: CompactionHandoff } = {},): Promise<SessionTransferOutcome> {const { delivery } = selection;const targetDeploymentId = readAcceptedDeploymentId(delivery);- const sameDeployment =- targetDeploymentId === undefined || targetDeploymentId === this.input.deploymentId;- if (sameDeployment && options.compaction !== undefined) {- if (!selection.handoffEligible) return { kind: "retained", reason: "busy" };- return await this.tryCompactionTransfer(state, { ...options.compaction, delivery });- }if (targetDeploymentId === undefined) return { kind: "retained", reason: "missing-deployment" };if (targetDeploymentId === this.input.deploymentId)return { kind: "retained", reason: "same-deployment" };@@ -149,13 +266,12 @@ export class SessionHandoff {/*** Attempts to move a session that compacted to a fresh run on this- * deployment. Without a delivery the caller guarantees no input is waiting,- * and the successor parks until the next one arrives. The successor keeps- * the session's deadline.+ * deployment. The caller guarantees no input is waiting; the successor+ * parks until the next one arrives and keeps the session's deadline.*/async tryCompactionTransfer(state: SessionTransferState,- compaction: CompactionHandoff & { readonly delivery?: DeliverHookPayload },+ compaction: CompactionHandoff,): Promise<SessionTransferOutcome> {const { deploymentId } = this.input;if (this.incompatibleTargetDeploymentIds.has(deploymentId))@@ -169,55 +285,227 @@ export class SessionHandoff {start: SessionHandoffStart,): Promise<SessionTransferOutcome> {const { inbox } = this.input;- if (!(await isSessionIdleForHandoffStep({ sessionState: state.sessionState })))- 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)));- let retained: {- readonly error?: unknown;- readonly reason: "activation-failed" | "checkpoint-incompatible";- };+ if (this.worldUnsupported) return { kind: "retained", reason: "unsupported-world" };+ // The previous attempt's payloads have not come back yet.+ if (inbox.awaitingHandover) return { kind: "retained", reason: "busy" };+ const ownerRunId = getWorkflowMetadata().workflowRunId;+ const attempt = this.attempts++;+ const attemptKey = `${ownerRunId}:${String(attempt)}`;+ const hookTokens = inbox.claimedTokens;+ // Both tokens are unique to this run, so neither awaits its registration:+ // they commit with the start step below, which can then run inline.+ const activation = createHook<SessionOwnerActivation>({+ token: `${ownerRunId}:handoff:${String(attempt)}`,+ });+ this.ensureAnchor();+ const attemptEnded = new AbortController();+ // Workflow's clock is replay-stable.+ const startedAt = Date.now();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[] = [];+ let candidateRunId: string;try {- const activation = await this.startAndActivate(checkpoint, start, targetDeploymentId);- if (activation.kind === "active") return { kind: "transferred" };- acceptedByFailedCandidate = activation.payloads;- if (activation.kind === "incompatible") {- this.incompatibleTargetDeploymentIds.add(targetDeploymentId);- retained = { reason: "checkpoint-incompatible" };- } else {- retained = { error: activation.error, reason: "activation-failed" };+ const started = await startSuccessorStep({+ ...start,+ activationToken: activation.token,+ anchorRunId: this.input.sessionId,+ attemptKey,+ checkpoint: { ...this.input.checkpoint, ...state, version: SESSION_CHECKPOINT_VERSION },+ hookTokens,+ sourceRunId: ownerRunId,+ targetDeploymentId,+ });+ if (started.kind === "not-idle") return { kind: "retained", reason: "not-idle" };+ if (started.kind === "unsupported") {+ this.worldUnsupported = true;+ return { kind: "retained", reason: "unsupported-world" };}+ candidateRunId = started.runId;} catch (error) {- // The current owner remains authoritative until activation.- retained = { error, reason: "activation-failed" };+ // `start()` can create the run and still fail.+ const fence = await this.fenceAttempt(attemptKey);+ if (fence.kind !== "live") {+ if (fence.kind === "done") await this.holdEveryToken(hookTokens);+ await this.reportRetained("activation-failed", targetDeploymentId, error);+ return { kind: "retained", reason: "activation-failed" };+ }+ candidateRunId = fence.runId;+ }+ const takenOver = inbox+ .whenTakenOver(attemptEnded.signal)+ .then((): AttemptSettlement => ({ kind: "taken-over" }));+ // Watching a candidate costs a wait every few seconds, so it starts only+ // once the deadline has fenced the attempt and a live candidate remains.+ let watch: RunWatch | undefined;+ let deadline: Promise<AttemptSettlement> | undefined;+ while (true) {+ if (watch === undefined && deadline === undefined && inbox.hasPending()) {+ const remaining = startedAt + HANDOFF_BOOT_DEADLINE_MS - Date.now();+ deadline = sleep(Math.max(0, remaining)).then(() => ({ kind: "deadline" }));+ }+ let settled: AttemptSettlement;+ try {+ settled = await Promise.race<AttemptSettlement>([+ takenOver,+ activation.then((verdict) => ({ kind: "verdict", verdict })),+ watch !== undefined+ ? watch.ended.then(() => ({ kind: "candidate-ended" }))+ : (deadline ?? inbox.whenArrival().then(() => ({ kind: "arrival" }))),+ ]);+ } finally {+ watch?.stop();+ }+ if (settled.kind === "taken-over") return await this.handOver(attemptKey);+ // Input is now waiting, so the next pass starts the deadline.+ if (settled.kind === "arrival") continue;+ // A duplicate candidate from a retried start step may have given this+ // outcome while the lease winner can still take over.+ // A candidate silent past the deadline may still be booting.+ const gaveUpRunId =+ settled.kind === "candidate-ended" ? candidateRunId : verdictRunId(settled);+ const fence = await this.fenceAttempt(attemptKey, gaveUpRunId);+ if (fence.kind === "live") {+ candidateRunId = fence.runId;+ watch = watchRunEnd(candidateRunId);+ continue;+ }+ // Only a lease holder can have claimed addresses. One that gave a+ // verdict reports what it holds; any other may hold some.+ if (fence.kind === "done" && fence.runId !== verdictRunId(settled))+ await this.holdEveryToken(hookTokens);+ const retained =+ settled.kind === "verdict"+ ? await this.recover(settled.verdict, {+ attemptKey,+ candidateRunId,+ hookTokens,+ targetDeploymentId,+ })+ : this.recoverFromSilentCandidate(settled.kind);+ await this.reportRetained(retained.reason, targetDeploymentId, retained.error);+ return { kind: "retained", reason: retained.reason };}- await this.recover(tokens, acceptedByFailedCandidate);} finally {- await Promise.all(markers.map((marker) => disposeHook(marker)));+ attemptEnded.abort();+ await disposeHook(activation);}- await this.reportRetained(retained.reason, targetDeploymentId, retained.error);- return { kind: "retained", reason: retained.reason };+ }++ /**+ * The session was taken over while no attempt was open. This run leaves as+ * after a transfer, without finalizing the stream the new owner now writes.+ */+ async adoptTakeover(): Promise<{ readonly kind: "transferred" }> {+ // Every forced claim happens inside an attempt, so this is a bug; report+ // it, but still leave the stream to whichever run took it.+ await reportSessionTakenOverOutsideAttemptStep({ sessionId: this.input.sessionId });+ // Attempts normally create the anchor; with none open, the original run+ // creates it now so it still parks for the final owner's result.+ this.ensureAnchor();+ return { kind: "transferred" };+ }++ /**+ * Claims the attempt's lease. `gaveUpRunId` is the candidate whose outcome+ * the owner is acting on: holding the lease, it can no longer take over.+ */+ private async fenceAttempt(attemptKey: string, gaveUpRunId?: string): Promise<AttemptFence> {+ const lease = createHook<never>({+ experimental_minRetention: HANDOFF_LEASE_RETENTION,+ token: handoffLeaseToken(attemptKey),+ });+ try {+ await claimHookOwnership(lease);+ } catch (error) {+ if (!isHookConflictError(error) || typeof error.conflictingRunId !== "string") throw error;+ const runId = error.conflictingRunId;+ if (runId === gaveUpRunId || (await hasRunEndedStep({ runId })))+ return { kind: "done", runId };+ return { kind: "live", runId };+ }+ // Held for the rest of this run, like the successor's lease: disposing it+ // would free the token at once for a late candidate. Retention keeps it+ // reserved after the run ends.+ return { kind: "won" };+ }++ /** Forwards what this run accepted but never read to the run that took the session over. */+ private async handOver(attemptKey: string): Promise<{ readonly kind: "transferred" }> {+ await sendSessionHandover({+ attemptKey,+ payloads: this.input.inbox.drain(),+ sessionId: this.input.sessionId,+ });+ return { kind: "transferred" };+ }++ /**+ * Takes back every address a candidate that gave up may hold. Forced claims+ * replace this run's own hooks, so this holds whether or not a pump has+ * observed the candidate's claim yet.+ */+ private async holdEveryToken(hookTokens: readonly string[]): Promise<void> {+ await this.input.inbox.claimSessionHooks(hookTokens, { force: true });+ }++ private recoverFromSilentCandidate(kind: "candidate-ended" | "deadline"): RetainedAttempt {+ const message =+ kind === "deadline"+ ? `The successor run did not report within ${String(HANDOFF_BOOT_DEADLINE_MS / 60_000)} minutes.`+ : "The successor run ended before the handoff settled.";+ return { error: new Error(message), reason: "activation-failed" };+ }++ /** Keeps the session after a candidate's verdict, taking back any hook it claimed. */+ private async recover(+ verdict: SessionOwnerActivation,+ attempt: {+ readonly attemptKey: string;+ readonly candidateRunId: string;+ readonly hookTokens: readonly string[];+ readonly targetDeploymentId: string;+ },+ ): Promise<RetainedAttempt> {+ const { inbox } = this.input;+ switch (verdict.kind) {+ case "active":+ // Only a successor that claims ordinarily signals `active`, and it+ // cannot while this owner holds the hooks.+ return {+ error: new Error("Successor reported active without a takeover."),+ reason: "activation-failed",+ };+ case "incompatible":+ this.incompatibleTargetDeploymentIds.add(attempt.targetDeploymentId);+ if (verdict.payloads.length > 0) inbox.restore(verdict.payloads);+ return { reason: "checkpoint-incompatible" };+ case "failed":+ if (verdict.claimedHooks === true) {+ // If this throws, the session fails here; the successor stops+ // waiting to be taken back once this run ends.+ await inbox.claimSessionHooks(attempt.hookTokens, {+ force: true,+ handover: attempt.attemptKey,+ });+ abandonHandoverIfRunEnds(inbox, {+ attemptKey: attempt.attemptKey,+ sourceRunId: verdict.runId ?? attempt.candidateRunId,+ });+ } else if (isHookConflictError(verdict.error)) {+ // A successor older than this protocol claims ordinarily and so can+ // never take over from an owner that keeps its hooks.+ this.incompatibleTargetDeploymentIds.add(attempt.targetDeploymentId);+ }+ if (verdict.payloads.length > 0) inbox.restore(verdict.payloads);+ return { error: verdict.error, reason: "activation-failed" };+ }+ }++ private ensureAnchor(): 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),+ });}/** After a transfer, the original run parks until the final owner reports the session result. */@@ -237,39 +525,6 @@ export class SessionHandoff {await disposeHook(anchor);}- /** Starts the candidate and waits for it to activate or fail. */- private async startAndActivate(- checkpoint: SessionCheckpoint,- start: SessionHandoffStart,- targetDeploymentId: string,- ): Promise<SessionOwnerActivation> {- const activation = createHook<SessionOwnerActivation>({- token: `${getWorkflowMetadata().workflowRunId}:handoff`,- });- await claimHookOwnership(activation);- try {- await startSessionOwnerStep({- ...start,- activationToken: activation.token,- anchorRunId: this.input.sessionId,- checkpoint,- 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 reportRetained(reason: "activation-failed" | "checkpoint-incompatible",targetDeploymentId: string,@@ -285,13 +540,4 @@ export class SessionHandoff {targetDeploymentId,});}-- 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/program.ts b/packages/eve/src/execution/session/program.tsindex 50bbe1b53..e937270ac 100644--- a/packages/eve/src/execution/session/program.ts+++ b/packages/eve/src/execution/session/program.ts@@ -279,8 +279,9 @@ async function runSessionLoop(: undefined;/*** Hands a session that compacted to a fresh run on this deployment while- * nothing is waiting. When input arrives first, the next lone delivery- * carries the handoff instead; see `runDeliveredTurn`.+ * nothing is waiting. Input that is already waiting runs here first, and+ * the session moves at the next quiet boundary; input that arrives once the+ * move has started runs on the successor.*/const tryCompactionHandoff = async (): Promise<SessionLoopOutcome | undefined> => {const compaction = dueCompactionHandoff();@@ -291,9 +292,7 @@ async function runSessionLoop(const runDeliveredTurn = async (next: Extract<NextTurnInstruction, { kind: "turn" }>,): Promise<SessionActionResult> => {- const transfer = await handoff.tryTransfer(next, transferState(), {- compaction: dueCompactionHandoff(),- });+ const transfer = await handoff.tryTransfer(next, transferState());if (transfer.kind === "transferred") return transfer;if (next.delivery.caller !== undefined) progress.caller = next.delivery.caller;return { action: await runTurn({ delivery: next.delivery }), kind: "action" };@@ -309,9 +308,12 @@ async function runSessionLoop(while (true) {const next = await nextParkedActivity();switch (next.kind) {+ case "closed":+ // Taken over outside an attempt: the new owner now writes the stream.+ if (inbox.takenOver) return await handoff.adoptTakeover();+ return { kind: "terminal", outcome: { kind: "expired" } };case "expired":case "reset":- case "closed":return { kind: "terminal", outcome: { kind: "expired" } };case "clear":case "compact":@@ -380,9 +382,12 @@ async function runSessionLoop(const next = await nextParkedActivity();switch (next.kind) {+ case "closed":+ // Taken over outside an attempt: the new owner now writes the stream.+ if (inbox.takenOver) return await handoff.adoptTakeover();+ return { kind: "terminal", outcome: { kind: "expired" } };case "expired":case "reset":- case "closed":return { kind: "terminal", outcome: { kind: "expired" } };case "clear":case "compact":diff --git a/packages/eve/src/execution/session/run-watch.test.ts b/packages/eve/src/execution/session/run-watch.test.tsnew file mode 100644index 000000000..1718a9c25--- /dev/null+++ b/packages/eve/src/execution/session/run-watch.test.ts@@ -0,0 +1,61 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import { watchRunEnd } from "#execution/session/run-watch.js";++const sleeps: (() => void)[] = [];+const hasRunEndedStepMock = vi.fn();++vi.mock("#compiled/@workflow/core/index.js", () => ({+ sleep: () => new Promise<void>((resolve) => sleeps.push(resolve)),+}));+vi.mock("#execution/session/handoff-steps.js", () => ({+ hasRunEndedStep: (...args: unknown[]) => hasRunEndedStepMock(...args),+}));++afterEach(() => {+ sleeps.length = 0;+ vi.resetAllMocks();+});++describe("watchRunEnd", () => {+ it("checks after each interval and resolves once the run has ended", async () => {+ hasRunEndedStepMock.mockResolvedValueOnce(false).mockResolvedValueOnce(true);+ const watch = watchRunEnd("run-b");++ await vi.waitFor(() => expect(sleeps).toHaveLength(1));+ sleeps[0]!();+ await vi.waitFor(() => expect(sleeps).toHaveLength(2));+ sleeps[1]!();++ await expect(watch.ended).resolves.toBeUndefined();+ expect(hasRunEndedStepMock).toHaveBeenCalledTimes(2);+ expect(hasRunEndedStepMock).toHaveBeenCalledWith({ runId: "run-b" });+ });++ it("keeps watching after a status check fails", async () => {+ hasRunEndedStepMock+ .mockRejectedValueOnce(new Error("world unavailable"))+ .mockResolvedValueOnce(true);+ const watch = watchRunEnd("run-b");++ await vi.waitFor(() => expect(sleeps).toHaveLength(1));+ sleeps[0]!();+ await vi.waitFor(() => expect(sleeps).toHaveLength(2));+ sleeps[1]!();++ await expect(watch.ended).resolves.toBeUndefined();+ expect(hasRunEndedStepMock).toHaveBeenCalledTimes(2);+ });++ it("checks nothing more once stopped", async () => {+ const watch = watchRunEnd("run-b");+ await vi.waitFor(() => expect(sleeps).toHaveLength(1));++ watch.stop();+ sleeps[0]!();+ await Promise.resolve();++ expect(hasRunEndedStepMock).not.toHaveBeenCalled();+ expect(sleeps).toHaveLength(1);+ });+});diff --git a/packages/eve/src/execution/session/run-watch.ts b/packages/eve/src/execution/session/run-watch.tsnew file mode 100644index 000000000..a658af9ee--- /dev/null+++ b/packages/eve/src/execution/session/run-watch.ts@@ -0,0 +1,56 @@+import { sleep } from "#compiled/@workflow/core/index.js";++import { hasRunEndedStep } from "#execution/session/handoff-steps.js";+import type { SessionInboxHandle } from "#execution/session-inbox/inbox.js";++/** Long enough that a handoff settling normally never pays for a check. */+const RUN_WATCH_INTERVAL = "10s";++export interface RunWatch {+ /** Resolves once the run has ended; never settles once stopped. */+ readonly ended: Promise<void>;+ stop(): void;+}++/**+ * Watches a counterpart run so a wait on it has a way out when that run is+ * gone. Durable sleeps between checks keep it deterministic under replay;+ * `stop()` ends it before its next check.+ */+export function watchRunEnd(runId: string): RunWatch {+ let stopped = false;+ const ended = (async () => {+ while (!stopped) {+ await sleep(RUN_WATCH_INTERVAL);+ if (stopped) break;+ // A check that fails says nothing about the run; try again later.+ const ended = await hasRunEndedStep({ runId }).catch(() => false);+ if (ended && !stopped) return;+ }+ return await new Promise<never>(() => {});+ })();+ return {+ ended,+ stop() {+ stopped = true;+ },+ };+}++/**+ * Opens the inbox's handover gate with nothing restored if `sourceRunId` ends+ * before its handover arrives: an ended run can never send it. The watch+ * starts only once a read waits on the gate, so a handover that arrives+ * before it is needed costs nothing.+ */+export function abandonHandoverIfRunEnds(+ inbox: SessionInboxHandle,+ handover: { readonly attemptKey: string; readonly sourceRunId: string },+): void {+ void inbox.whenBlockedOnHandover().then(() => {+ if (!inbox.awaitingHandover) return;+ const watch = watchRunEnd(handover.sourceRunId);+ void inbox.whenHandoverSettled().then(() => watch.stop());+ void watch.ended.then(() => inbox.abandonHandover(handover.attemptKey));+ });+}diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.tsindex f6556e092..ec7164a06 100644--- a/packages/eve/src/execution/workflow-runtime.test.ts+++ b/packages/eve/src/execution/workflow-runtime.test.ts@@ -17,7 +17,7 @@ import {waitForCommandHookOwner,waitForSessionInbox,sessionTimeoutWorkflowReference,- startSessionOwnerStep,+ startWorkflowOnDeployment,startWorkflowOnCurrentDeployment,workflowEntryReference,workflowToolRunWorkflowReference,@@ -140,70 +140,13 @@ describe("startWorkflowOnCurrentDeployment", () => {});});-describe("session owner starts", () => {+describe("deployment 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: { serializedContext: {} } as never,- delivery: { kind: "deliver", payloads: [] },- targetDeploymentId: "latest",- }),- ).rejects.toThrow("exact deployment id");+ await expect(startWorkflowOnDeployment(workflowEntryReference, [], "latest")).rejects.toThrow(+ "exact deployment id",+ );expect(startMock).not.toHaveBeenCalled();});-- it.each([undefined, 0, "default"] as const)(- "starts a successor with the original stream and retention=%s",- async (retention) => {- const sessionWritable = new WritableStream<Uint8Array>();- getRunMock.mockReturnValue({ getWritable: () => sessionWritable });- startMock.mockResolvedValue({ runId: "owner-2" });- const checkpoint = {- version: 10,- serializedContext: {},- sessionState: { continuationToken: "continuation-1", sessionId: "session-1" },- sessionTimeoutMs: 60_000,- retention,- } 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,- handoffVersion: 2,- kind: "handoff",- ownerDeploymentId: "deployment-b",- sessionWritable,- sessionId: "anchor-1",- }),- ],- expect.objectContaining({- deploymentId: "deployment-b",- allowReservedAttributes: true,- attributes: { "$eve.version": resolveInstalledPackageInfo().version },- }),- );- expect(startMock.mock.calls[0]?.[2].experimental_retention).toBe(retention);- },- );});describe("createWorkflowRuntime command dispatch", () => {diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.tsindex 5a3a36eb2..1023dce86 100644--- a/packages/eve/src/execution/workflow-runtime.ts+++ b/packages/eve/src/execution/workflow-runtime.ts@@ -49,13 +49,7 @@ import {readSessionEventStream,readSessionStreamTailIndex,} from "#execution/session-event-stream.js";-import {- SESSION_HANDOFF_VERSION,- type HandoffWorkflowEntryInput,- type InitialWorkflowEntryInput,- type SessionHandoffStart,-} from "#execution/session/entry-input.js";-import type { SessionCheckpoint } from "#execution/session/handoff.js";+import type { InitialWorkflowEntryInput } from "#execution/session/entry-input.js";import { walkCauseChain } from "#shared/errors.js";import { buildInvocationAttributes } from "#internal/invocation/metadata.js";import { isAgentTraceContext } from "#tracing/eve/agent-trace-context.js";@@ -311,42 +305,6 @@ export function createWorkflowRuntime(config: {};}-export type SessionOwnerStartInput = SessionHandoffStart & {- readonly activationToken: string;- /** Original run whose stream stays the public session stream. */- readonly anchorRunId: string;- readonly checkpoint: SessionCheckpoint;- 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 { activationToken, anchorRunId, checkpoint, targetDeploymentId, ...start } = input;- const workflowInput: HandoffWorkflowEntryInput = {- ...start,- activationToken,- checkpoint,- handoffVersion: SESSION_HANDOFF_VERSION,- kind: "handoff",- ownerDeploymentId: targetDeploymentId,- sessionWritable: getRun(anchorRunId).getWritable<Uint8Array>(),- sessionId: anchorRunId,- };- // The successor is stamped with this eve version at start, because the- // queue guard runs before it boots. Single-build Worlds share this version;- // deployment-affine Worlds bypass the guard and the successor records its- // own version at boot.- await startWorkflowOnDeployment(- workflowEntryReference,- [workflowInput],- targetDeploymentId,- checkpoint.retention === undefined- ? undefined- : { experimental_retention: checkpoint.retention },- );-}-async function dispatchWorkflowCommand<TCommand extends SessionCommand>(token: string | SessionInboxAddress,command: TCommand,@@ -383,7 +341,7 @@ async function dispatchWorkflowCommand<TCommand extends SessionCommand>(if (command.kind === "reset") {await waitForSessionHooksRelease([sessionCommandHookToken(hook.sessionId), logicalSessionToken(token)],- hook.runId,+ { ownerRunId: hook.runId, sessionId: hook.sessionId },);}@@ -593,7 +551,7 @@ export async function startWorkflowOnCurrentDeployment<TArgs extends unknown[],* version that started it: ingress and the stranded replay guard read it to* decide whether this build can still execute the run.*/-async function startWorkflowOnDeployment<TArgs extends unknown[], TResult>(+export async function startWorkflowOnDeployment<TArgs extends unknown[], TResult>(workflow: WorkflowFunction<TArgs, TResult> | WorkflowMetadata,args: TArgs,deploymentId: string,diff --git a/packages/eve/src/internal/testing/session-inbox-workflow.ts b/packages/eve/src/internal/testing/session-inbox-workflow.tsindex 569204f7a..dd71ffbab 100644--- a/packages/eve/src/internal/testing/session-inbox-workflow.ts+++ b/packages/eve/src/internal/testing/session-inbox-workflow.ts@@ -1,6 +1,6 @@import { createHook, getWorkflowMetadata } from "#compiled/@workflow/core/index.js";-import { createSessionInbox } from "#execution/session-inbox/inbox.js";+import { createSessionInbox, type SessionInboxPayload } from "#execution/session-inbox/inbox.js";import { sessionCommandHookToken } from "#execution/session-inbox/address.js";export async function sessionCommandInboxWorkflow(input: {@@ -32,3 +32,66 @@ export async function parkedAnchorWorkflow(input: { readonly token: string }): Pusing gate = createHook<void>({ token: input.token });await gate;}++/**+ * Holds `token` until another run force-claims it, reads what arrived before+ * the takeover, then takes the token back and returns the next payload.+ */+export async function sessionInboxTakeoverWorkflow(input: { readonly token: string }): Promise<{+ readonly beforeTakeover: readonly SessionInboxPayload[];+ readonly afterReclaim: SessionInboxPayload | undefined;+}> {+ "use workflow";++ const inbox = createSessionInbox(getWorkflowMetadata().workflowRunId);+ try {+ await inbox.claimSessionHook(input.token);+ await inbox.whenTakenOver();+ const beforeTakeover: SessionInboxPayload[] = [];+ for (let payload = await inbox.next(); payload !== undefined; payload = await inbox.next())+ beforeTakeover.push(payload);+ await inbox.claimSessionHook(input.token, { force: true });+ return { afterReclaim: await inbox.next(), beforeTakeover };+ } finally {+ await inbox.dispose();+ }+}++/** Force-claims `token` and returns once another run takes it back. */+export async function sessionInboxForceClaimWorkflow(input: {+ readonly token: string;+}): Promise<void> {+ "use workflow";++ const inbox = createSessionInbox(getWorkflowMetadata().workflowRunId);+ try {+ await inbox.claimSessionHook(input.token, { force: true });+ await inbox.whenTakenOver();+ } finally {+ await inbox.dispose();+ }+}++/**+ * A session owner from before handoff version 3: on `release` it releases its+ * addresses, then waits for its successor's activation signal.+ */+export async function releasingSessionOwnerWorkflow(input: {+ readonly aliases: readonly string[];+ readonly release: string;+}): Promise<{ readonly activation: unknown; readonly released: readonly SessionInboxPayload[] }> {+ "use workflow";++ const sessionId = getWorkflowMetadata().workflowRunId;+ const inbox = createSessionInbox(sessionId);+ using release = createHook<void>({ token: input.release });+ using activation = createHook<unknown>({ token: `${sessionId}:handoff` });+ try {+ await inbox.claimSessionHooks([sessionCommandHookToken(sessionId), ...input.aliases]);+ await release;+ const released = await inbox.release();+ return { activation: await activation, released };+ } finally {+ await inbox.dispose();+ }+}diff --git a/packages/eve/src/internal/workflow/development-world-client.ts b/packages/eve/src/internal/workflow/development-world-client.tsindex ee79001a2..1cd8ad6ca 100644--- a/packages/eve/src/internal/workflow/development-world-client.ts+++ b/packages/eve/src/internal/workflow/development-world-client.ts@@ -102,6 +102,9 @@ export function createDevelopmentWorkflowWorld(): World {const forwarded = buildForwardedOperations();const world = {specVersion: 8 as SpecVersion,+ // Every operation runs on the dev parent's local world, which supports+ // both; session handoffs across reloads depend on them.+ capabilities: { hookForceClaim: true, hookRetention: { active: true } },async getDeploymentId() {// Inside a pinned delivery, steps and child runs must record the// delivery's generation — not whatever is active — so replay after adiff --git a/research/atomic-session-handoff.md b/research/atomic-session-handoff.mdnew file mode 100644index 000000000..690ba062c--- /dev/null+++ b/research/atomic-session-handoff.md@@ -0,0 +1,401 @@+---+issue: TBD+status: in-progress+last_updated: "2026-10-19"+---++# Atomic session handoff++## Summary++A session handoff moves an idle session to a successor workflow run, either on the deployment+that accepted a new delivery or on the same deployment after compaction. Customers see the first+message after a handoff take 9 seconds or more. The cause is structural: the current protocol+releases every session hook before it starts the successor, so it pays for a release/claim+handshake and covers the resulting no-owner interval with markers, an ingress retry loop, and an+activation round trip. That puts about 10 serial durable operations in front of the user's+message, where an ordinary turn has one.++Workflow now ships the atomic primitive the original handoff design was waiting for:+`createHook({ token, experimental_force: true })`. Both first-party Worlds declare+`hookForceClaim: true` (`@workflow/world-vercel` 5.2.0 and `@workflow/world-local` 5.1.0), and+current runs are stamped at the spec version that understands a takeover (8). This plan replaces+the release-based handoff with a force-claim protocol (handoff version 3):++- The current owner never releases its hooks. It starts the successor and keeps serving its inbox.+- The successor validates, force-claims the whole hook set in one batch, and runs the triggering+ delivery right away.+- The old owner sees the takeover and forwards whatever it accepted but never read. The successor+ processes those messages before anything it received directly.++The critical path goes from about 10 durable operations to 4. No address is ever without a live+owner, so ingress never retries, a channel never gets `session_not_ready` because of a handoff,+and a compaction handoff can no longer be abandoned by a racing reply.++There is no public API change. Observable changes:++- Lower latency for the first message after a deployment or compaction handoff.+- Compaction handoffs never ride on a message.+- Rolling back to an eve build older than this protocol leaves existing sessions on the newer+ owner, as a checkpoint version bump already does.++This plan replaces the release-based handoff and compaction trigger from the single-workflow+session design ([#876](https://github.com/vercel/eve/issues/876)). The rest of that design is+unchanged: one owner runs turns, the original run anchors the stream, checkpoints carry settled+state, and handoff targets the exact accepting deployment.++## Where the time goes today++Measured with `world-local` (integration tier, same machine). Times are from `hook_received` on+the old owner A:++| ms | Run | Durable operation |+| ------- | --- | --------------------------------------------------------------- |+| 46–88 | A | `isSessionIdleForHandoffStep` (pure check, run as a step) |+| 91 | A | anchor hook created, `getConflict` awaited |+| 98 | A | handoff marker hooks created, awaited after the anchor |+| 103–147 | A | `releaseSessionHooksStep`; the no-owner interval starts |+| 150 | A | activation hook created, awaited |+| 155–207 | A | `startSessionOwnerStep` (cross-deployment probe, `run_created`) |+| 247–287 | B | `validateSessionCheckpointStep` (bundle load on a cold process) |+| 290–331 | B | `recordSessionOwnerStep` |+| 335 | B | session hooks claimed; the no-owner interval ends |+| 339–384 | B | `signalSessionOwnerActivationStep`, awaited before the turn |+| 394 | B | `turnStep` starts |++An ordinary turn reaches `turnStep` 57 ms after `hook_received`, with the abort hooks as its only+durable operation. On Vercel each row costs at least one network write plus a replay, and a step+that cannot run inline costs a queue hop. The successor's first process on a new deployment also+starts cold.++Two costs fall outside the table:++- **Cross-deployment capability probe.** `start()` probes the target deployment before every+ cross-deployment start (`CROSS_DEPLOYMENT_CAPABILITY_PROBE_TIMEOUT_MS = 10_000`). The result is+ cached per process for 10 minutes, so the first handoff from each old-deployment process pays a+ round trip that invokes the new deployment. eve cannot skip the probe; see+ [Upstream follow-ups](#upstream-follow-ups).+- **Compaction double handoff.** The eager compaction transfer starts after `session.waiting`. A+ reply accepted before the release commits makes the owner abandon the attempt, reclaim its+ hooks, and then carry a second full handoff on that reply (`runDeliveredTurn` passes+ `dueCompactionHandoff()`). That first message pays for roughly two handoffs. A reply that lands+ in the no-owner interval instead polls in ingress for up to 5 seconds+ (`HANDOFF_RETRY_WINDOW_MS`) and then gets a 409 `session_not_ready`.++## The primitive++From `@workflow/core` 5.2 and `@workflow/world` spec version 8, a forced hook creation:++- always ends with the claimer owning the token. Concurrent claimers converge on one owner.+- disposes the previous owner's hook and wakes that run. The previous owner's payload awaiters+ reject with `HookForceClaimedError`, which carries `claimedByRunId`.+- keeps every payload delivered before the takeover with the previous owner. Its iterator drains+ those payloads first and only then rejects. The takeover is ordered after them.+- redirects every later `resumeHook(token)` to the new owner, including resumes already in flight+ that hit the old owner. Each redirect is the same logical resume with the same dedup id.+- is refused with an ordinary `HookConflictError` (`forceRefusedReason: 'victim-spec-version'`)+ when the holder is a running victim stamped below spec version 8.++`start()` cannot take a caller-chosen run id or an idempotency key, so a start step retried after+`run_created` can create two candidates. With forced claims, both would win in turn. The protocol+fences this itself.++## Protocol (handoff version 3)++```text+A: current owner B: successor (target deployment)+──────────────── ────────────────────────────────+eligible delivery dequeued+startSuccessorStep ──────────────────────▶ boot+ (idle check + start, one step) claim attempt lease (ordinary claim)+keeps owning and pumping its inbox; prepareSuccessorStep: migrate, validate,+runs no turn while the attempt is open record $eve.version, warm the bundle+ force-claim the full hook set (one batch)+pumps drain, then HookForceClaimedError ◀─ ownership moves+ first turnStep(delivery) ← model work+handover(leftovers) ─────────────────────▶ inbox gate opens; leftovers go first+exits, or parks as the stream anchor+```++### Owner (A)++1. **No separate hook barrier.** The attempt's outcome hook (`<runId>:handoff:<attempt>`) and, on+ the original run's first attempt, the stream anchor are created in the same suspension as the+ start step, without awaiting `getConflict`. Their tokens are unique, the suspension commits+ them before the step runs, and the step can still run inline.+2. **One step to start.** `startSuccessorStep` runs the idle check with the source's code and, if+ the session is idle, starts the candidate. The step returns `not-idle`, `started` with the+ candidate's run id, or `unsupported` when the World does not declare both `hookForceClaim` and+ active `hookRetention` (see [Compatibility](#compatibility)). The candidate input carries the+ checkpoint, the triggering delivery, `handoffVersion: 3`, A's exact logical hook set+ (`hookTokens`), A's run id (`sourceRunId`), and an attempt key (`<A runId>:<attempt index>`)+ that is deterministic under replay. `start()` can create the run and still fail, so a failed+ start step is not proof that no candidate exists, and a retried start step can leave a+ duplicate; A therefore fences the attempt (below) before any retained outcome.+3. **Keep serving.** A keeps every hook and keeps queueing arrivals. It runs no turn until the+ attempt settles.+4. **Settle on exactly one outcome:**++| What A observes | Outcome | A's action |+| ----------------------------------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| Every session hook force-claimed by the same run | transferred | Drain the queue and send it as `handover` parts, then exit (or park as the anchor). |+| `incompatible` verdict, no hook taken | retained | Remember the deployment as incompatible, then run the delivery here. |+| `failed` verdict, no hook taken | retained | Run the delivery here; retry at the next eligible delivery. |+| `failed` verdict with `claimedHooks: true` | retained | Force-reclaim the full hook set with the gate armed and run the delivery at once; the candidate's `handover` lands behind it, which keeps FIFO because the trigger precedes anything the candidate accepted. |+| `failed` with `HookConflictError` (successor older than v3) | retained | Treat as `known-incompatible` for that deployment. |+| The candidate run ended with neither takeover nor verdict | retained | Force-reclaim the full hook set (forced claims replace A's own hooks, so pump timing does not matter), then run the delivery. |+| Input waits through the boot deadline (5 min), no verdict | retained | Fence; if no live candidate holds the lease, run the delivery (reclaiming the full set if a lease holder ended). |++The takeover itself is the success signal. Because A waits for every one of its pumps to close,+the leftovers it forwards are complete. The handover goes through the stable address, which+reaches whoever owns it, so A does not check which run took its hooks. A forced reclaim of a+token A still holds replaces A's own hook with a fresh one (Workflow lets a run take a token from+its own earlier hook), so the reclaim is correct even if a takeover has not reached A's pump yet.+While a handover is awaited A attempts no new transfer. The `failed` verdict carries+`claimedHooks` so A knows whether to reclaim, and v3 verdicts carry the successor's `runId`;+`SessionOwnerActivation` otherwise keeps its shape.++**Fence before retaining.** Every retained outcome after a candidate may exist (failed start+step, any verdict, the candidate ending, the boot deadline) first passes `fenceAttempt`: A+ordinary-claims the attempt's lease and holds it for the rest of its run, like a successor:+`dispose()` would free the token at once for a late candidate, and retention covers the time after+the run ends. Winning it shuts every candidate out. A conflict naming the+run that gave the outcome, or a run that has ended, means that candidate gave up. A conflict+naming a different live run (the lease winner, when the outcome came from a duplicate) sends A+back to waiting, now watching that run. The healthy path never fences. Only a lease holder can+have claimed addresses: one that gave a verdict reports what it holds, and A force-reclaims the+full set from any other that gave up.++**Handover parts.** A sends leftovers one payload per part, each carrying the attempt key and+an index, then a final part with the next index. Each payload was accepted on its own, so no+part exceeds a limit the original did not. The gate applies parts in index order at the armed+position, ignores repeated indexes (a retried send step repeats its index), and opens once the+final part and every part before it have been applied. Every part, data and final alike, is+retried with durable backoff until delivered or the session has ended (`HookNotFound`), so no+accepted message is dropped and a takeover always ends with a final part.++**Counterpart watch.** No wait on the other run is unbounded once that run is gone. A shared+helper sleeps durably (10 s) between checks of the run's status, keeps looping when a check+fails, and stops as soon as the awaited event happens. An open wait due within the invocation's+inline window (2, 5, or 10 minutes by function deadline, plus 30 s skew) turns off Workflow's+inline step delta, so no watch runs on the healthy path:++- A awaiting the takeover or verdict records the attempt's start, before the start step, on the+ replay-stable workflow clock. A stuck attempt only matters once input is waiting, and all input,+ including the session timeout command, arrives through the inbox, so A sets no timer while the+ inbox is empty; it races the next arrival instead. Once input is pending, A races one durable+ sleep for the time left until 5 minutes after the start. Reaching it fences the attempt; if a+ live candidate still holds the lease, A watches that run.+- A gated after a `claimedHooks` failure, and B gated awaiting A's handover, start watching only+ when a read (`next`, `whenPending`) actually blocks on the gate. If the counterpart has ended,+ the gate opens with nothing restored.+- B's failure path, waiting for A to take its hooks back, also stops if A ends.++**Never finalize after takeover.** A run that no longer owns the session must not finalize the+shared stream. Once A observes the takeover it only sends handover parts, which do not fail, and+exits as transferred; the original run still parks on its anchor. A takeover observed outside any+attempt cannot happen, since every forced claim belongs to one; if it does, A logs an error from a+step and leaves the same way rather than treating it as the inbox closing. If A's forced reclaim itself fails, A's session fails as any owner failure would,+and B, watching A, stops waiting and exits without writing to the stream.++### Successor (B)++1. **Fence duplicates.** B's first durable operation is an ordinary claim of+ `eve:handoff:lease:<attempt key>` with `experimental_minRetention: "7d"`. Relative retention+ starts when the hook is created; seven days is far beyond any queue delay and within the+ Postgres World's default 30-day cap. A duplicate from a retried start step, or a candidate whose+ owner already took the lease after a failed start step, conflicts and exits without touching+ session hooks or signaling. A `v3` input missing `attemptKey`, `hookTokens`, or `sourceRunId`+ is malformed and signals `failed` rather than taking the released path.+2. **Prepare in one step.** `prepareSuccessorStep` migrates the checkpoint, validates it,+ confirms A (`sourceRunId`) still holds every token in `hookTokens`, and records `$eve.version`.+ Recording must precede any claim, because ingress reads it. If validation fails, signal+ `incompatible` or `failed` and exit. If A no longer holds an address (A was cancelled or failed+ while B was queued, and a new session may reuse a channel alias), B claims nothing, signals+ `failed` (a no-op once A is gone), and exits. The source can still end between this check and+ the claims; that window is one step rather than a queue delay. Nothing was claimed, so A has+ nothing to recover.+3. **Force-claim A's hook set** (`hookTokens`) in one batch, arming the gate before any hook+ exists so a handover that is a hook's first payload is never dropped. B claims exactly A's set:+ forcing a token A never held could take it from an unrelated run, and A reclaims only its own+ set on failure. B's state cursor claims any other token it derives, ordinarily, at its first+ transition. No model or tool work happens until every claim settles. If any claim fails,+ signal `failed` (with `claimedHooks` when B holds any) and keep the pumps open until A+ reclaims, or until A ends. Then drain and send the leftovers back as a `handover`. Recovery is the same+ mechanism in the other direction.+4. **Run the triggering delivery immediately.** The inbox starts gated. Interrupt handlers+ (`cancel`, `reset`, timeout) still fire on arrival, but reads (`next`, `drain`, `takeLeading`,+ `hasPending`) expose nothing until A's `handover` for this attempt arrives. It is then placed+ where the gate was armed (the head, on a fresh successor), ahead of every direct arrival, so+ FIFO holds across the move. The gate holds every payload kind, so replies to B's own work+ (workflow-run messages, `runtime-action-result`) and accepted cancels are processed once the+ handover arrives; a cancel's interrupt still aborts B's running turn on arrival. The wait is+ bounded by A's side alone (its pumps close, then one step per leftover plus the final part), so+ it cannot deadlock on B; if A ends first, the counterpart watch opens the gate with nothing+ restored. Once no hook+ remains the gate can never open, so it is ignored and leftovers stay drainable.+5. **Session timeout.** Unchanged: a deployment handoff renews the deadline, a compaction handoff+ keeps it, and the timer starts concurrently with the first turn.++`handover` is a runtime-only inbox payload, like `session-failure`. A sends it through the stable+session address, so the SDK's redirect delivers it to B. Channel request bodies cannot construct+it.++### Invariants++1. **One executing owner.** A runs no turn from `startSuccessorStep` until the attempt settles. B+ does no model or tool work until it owns every hook in the set.+2. **Continuous ownership.** Every address always has a live owner. Ingress never sees+ `HookNotFound` for a live session because of a handoff.+3. **FIFO, no loss.** Every payload accepted by A is processed before any payload accepted by B+ (the SDK orders the takeover after A's buffered deliveries, and B's gate holds everything it+ accepts until A's handover is in place). In-flight resumes redirect. Leftovers always travel in+ a `handover`, in either direction.+4. **No duplicated work.** The triggering delivery runs exactly once: on B if every claim+ succeeded, otherwise on A. Duplicate candidates lose the lease before they claim anything.+5. **Eligibility is unchanged.** Only a lone, callerless delivery to an idle session triggers a+ deployment handoff (`handoffEligible`). Messages arriving after A decides ride the handover;+ they never block or abandon the move. A backlog that already exists when A decides still+ keeps the session where it is.++## Compaction handoff++The latch and eligibility stay the same: after a compacting turn, with no delegated caller and no+working tasks. The trigger changes:++- The owner transfers only from the eager path, at the first boundary where nothing is queued.+ Deliveries no longer carry a compaction transfer. A message already waiting at that boundary+ runs on the current owner with no handoff cost, and the next quiet boundary moves the session.+- A message that arrives once the eager transfer has started is not a race any more. Whichever+ owner accepts it, it is processed on the successor after the handover, without a second+ attempt. Its added latency is bounded by the rest of one transfer.+- Starvation is no worse than today. The delivery-carried path also required a lone delivery, so+ a client that always queues during turns already deferred the move.++## Ingress++Owners using v3 never leave an address unowned, so `resumeSessionInbox` takes its normal path on+every handoff. The marker read path (`waitWhileHandoffInProgress`), `SessionHandoffPendingError`,+and the handoff-driven 409 `session_not_ready` stay only for owners still running a v2 build,+whose own handoff to a v3 deployment still releases first (see+[Compatibility](#compatibility)). That path is reached only after a `HookNotFound`, so it costs+nothing on a delivery. The `session_not_ready` reply for a session whose initial run has not+claimed its inbox yet is unrelated and stays.++## Compatibility++| Source → successor | Behavior |+| -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| v3 → v3 | Force-claim protocol. |+| v2 → v3 (first move after this ships) | The source has already released and holds markers. B claims ordinarily, with no lease and no gate because no handover will come, and signals `active` in the v2 shape the source awaits. |+| v1/unversioned → v3 | Same as v2. |+| v3 → successor on a build older than v3 (rollback) | The older successor's ordinary claim conflicts, so it signals `failed`. A remembers the deployment as incompatible and keeps the session, matching the documented rollback behavior for newer checkpoints. |+| Legacy driver import | Unchanged. Its ordinary claim conflict still means "another importer won". |+| Stranded reset, `reset` release wait | Wait until no run serving the same session (by the holder's hook metadata) holds the address, so a takeover mid-reset does not end the wait while the session lives on. |+| World without `hookForceClaim` | `startSuccessorStep` starts nothing and returns `unsupported`; A stops attempting for its lifetime (`unsupported-world`). Sessions never move between runs, so their event logs grow with the session. |++`SESSION_HANDOFF_VERSION` becomes 3. `SESSION_CHECKPOINT_VERSION` does not change, because the+state shape is untouched. `SessionOwnerActivation` keeps its shape; v3 sources rely on the+takeover instead of `active`.++## Expected critical path++| Path | Today | v3 |+| --------------------------- | --------------------------------------------------------------------- | -------------------------------------------------------- |+| Deployment handoff, on A | idle step, anchor, markers, release step, activation hook, start step | `startSuccessorStep` |+| Deployment handoff, on B | validate step, record step, claim, signal step | lease, prepare step, force-claim |+| Durable operations in total | 10 | 4 |+| Delivery during the move | polls up to 5 s, then 409 | accepted at once; runs after the handover |+| Compaction, racing reply | abandon, reclaim, then a second full handoff | runs on the current owner, or after one bounded transfer |++The lease and the force-claim batch are single-hook or batched creations that Workflow 5.2+continues in-process, so each costs writes rather than a queue hop. The cross-deployment probe+and the successor's cold start remain. Both run before B's first step, and the probe warms the+target deployment.++## Rollout++1. **Baseline.** Not done yet. Add a handoff scenario to the `agent-workflow-stress` fixture that reports+ time-to-first-model-request after a compaction handoff through `EVE_WORKFLOW_STRESS_METRIC`.+ Record the hosted p50 and p95 on `main` before changing the protocol. Cross-deployment handoff+ cannot run in CI (one deployment), so measure it once by hand on two preview deployments.+2. **Inbox primitives.** `claimSessionHooks(tokens, { force, handover })`; pumps that treat+ `HookForceClaimedError` as a takeover rather than a failure, and `whenTakenOver()` once every+ hook is taken; the read gate and `handover` restore. Integration tests at the inbox boundary.+3. **Protocol v3.** `SessionHandoff`, `startSuccessorStep`, successor boot (lease, prepare,+ force-claim, gate), boot-time outcome and anchor hooks, the new compaction trigger, and v2+ successor compatibility. Delete markers and the release step from the owner side. Update+ [execution model and durability](../docs/concepts/execution-model-and-durability.mdx) (the+ compaction paragraph and handoff failure behavior). Add a `patch` changeset.+4. **Retire v2 compatibility, on evidence rather than a date.** Every session that is live when+ this ships is owned by a run on an earlier release, and it can reach current code only through+ a released handoff. The successor logs `session moved from an owner that releases its+addresses first` each time it accepts one. Once production logs show none for a sustained+ period, a later release may delete the ingress marker path, `SessionHandoffPendingError`,+ `bootReleasedHandoffOwner`, and the marker token, as a deliberate breaking change in its+ changeset. Sessions with disabled timeouts (`sessionTimeoutMs: false`) can stay on an earlier+ owner indefinitely, so a fixed window would strand them. Track this in a follow-up issue+ opened alongside step 3 (not opened yet).++## Validation++Integration tier (`entry-handoff*.integration.test.ts`, rewritten around observable outcomes):++- deployment handoff runs the delivery on B, and the stream shows one `turn.started` for it.+- a delivery accepted by A after the start step is processed on B after the trigger, in order.+- a delivery sent to an alias at every point of the move resolves to the same session with+ `accepted`, and no `session_not_ready` is returned.+- B rejecting the checkpoint leaves A as owner with no reclaim, and A runs the delivery.+- B failing after partial claims: A reclaims everything, B's leftovers come back, and order holds.+- a duplicate candidate exits on the lease, with no hook changes and no turn.+- a v2-shaped source hands off to a v3 successor; a v3 source's attempt against a successor older+ than v3 is retained once and then skipped.+- compaction: a reply racing the eager transfer runs once, on the successor, with no second+ transfer attempt.++The local critical-path probe used for the baseline table (an integration test that timestamps+`world.events.create` and `world.queue`) is run once before and after to confirm the operation+count. It is not committed as a test.++E2E: extend `agent-cancellation/evals/cancellation/compact-session-handoff.eval.ts` with a reply+sent immediately after `session.waiting`, asserting one reply turn and an unbroken stream.++## Open questions++- **Lease overlap.** Claiming the lease in the same suspension as the prepare step removes one+ operation, but a `getConflict` awaiter disables inline execution for steps in that suspension.+ Measure both orders on hosted before choosing.+- **A handover part that never delivers.** Every part is retried until delivered or the session+ ends. A part that fails permanently therefore keeps the move retrying, and B gated, rather than+ dropping a message the session accepted. A only stops when the session has ended.+- **Watch cost.** No path creates a wait until something is actually blocked or waiting: input+ pending behind an open attempt (one sleep until the boot deadline), a gated read, or a candidate+ still live past the deadline. A watch then costs a wait plus a step every 10 s. A candidate that+ never boots holds the session's pending input for up to the boot deadline; whether to also+ cancel such a candidate is deferred. When a message races the move, the deadline sleep cannot+ be cancelled: after a retain it turns off Workflow's inline step delta for up to the boot+ deadline and wakes the run once with nothing to do (a parked original run also gets one extra+ replay).+- **Retirement signal.** The released-path log shows sessions that moved, not sessions that are+ still waiting on an earlier owner for their next message. Before retiring, decide whether the+ log's silence is enough, or whether to count remaining owners by `$eve.version` in the World.++## Upstream follow-ups++- `@workflow/world-local` 5.1 writes a force-claimed victim's `hook_disposed` without the+ victim's per-hook lock that `hook_received` takes. A resume that passed the disposal check just+ before the claim commits can append after the disposal row, where it is neither redirected nor+ delivered (the same class as vercel/workflow#2781, for a run's own disposal). Reported as+ [vercel/workflow#4923](https://github.com/vercel/workflow/issues/4923) and fixed in+ [vercel/workflow#4924](https://github.com/vercel/workflow/pull/4924). eve does not patch it:+ until it upgrades to a `@workflow/world-local` release with that fix, a delivery racing a+ forced claim on the local world can be lost, and the alias-delivery integration test that races+ the claim is skipped. `eve dev` runs on the local world, so a delivery racing a handoff after a+ dev reload is exposed to the same race until that upgrade. Upgrade and re-enable that test once+ the fix ships.+ `@workflow/world-postgres` 5.0.4 serializes the same pair with row locks in one transaction and+ is not affected.+- Let a cross-deployment `start()` skip or prefetch the capability probe when the caller already+ holds a fresh attestation, for example one stamped by ingress on the accepting deployment.+- A global stream independent of any run would let the original run stop parking as the anchor.+ This request predates this plan and is still open.diff --git a/research/session-inbox-wire-schema.md b/research/session-inbox-wire-schema.mdindex 2ad85761a..49aa1aaf8 100644--- a/research/session-inbox-wire-schema.md+++ b/research/session-inbox-wire-schema.md@@ -6,7 +6,8 @@ last_updated: "2026-09-11"# Versioned wire schema for the session inbox-Superseded by [single-workflow sessions](./single-workflow-session-upgrades.md).+Superseded by single-workflow sessions ([#876](https://github.com/vercel/eve/issues/876)), whose+handoff is now described in [atomic session handoff](./atomic-session-handoff.md).The implementation uses one inbox protocol with no negotiation or migration chain.The proposal below records the previous deployment model, not current guidance.diff --git a/research/single-workflow-session-upgrades.md b/research/single-workflow-session-upgrades.mddeleted file mode 100644index cab98fb99..000000000--- a/research/single-workflow-session-upgrades.md+++ /dev/null@@ -1,494 +0,0 @@-----issue: https://github.com/vercel/eve/issues/876-status: implemented-last_updated: "2026-10-02"------# 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, active subagent turn or lease, 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 active task or subagent leases between deployments, which is a-cross-version coordination protocol: the thing this proposal deletes. Idle subagent handles are-not leases: a `parked` conversation handle or `available` task-owned handle retains only the stable-address of an independently owned child session, so those handles move with settled session state.-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. Compaction does trigger a-same-deployment handoff; see [Compaction handoff](#compaction-handoff).--### 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, active subagent leases, or live task/tool-ownership; the eligibility rule guarantees none exist. It may carry `parked` conversation handles-or `available` task-owned handles, which retain only the stable address of an independently owned-child session. The child session itself does not move with its parent: a later continuation carries-a caller and is therefore not handoff-eligible, so the child keeps executing on the deployment that-owns it.--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, require every retained handle to be `parked` or-`available`, 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.--## Compaction handoff--Workflow replay reads every step output of a run, so one owner that serves a session for its whole-life accumulates an unbounded event log. Compaction is the natural reset point: it rewrites history-to a summary plus a recent window, and it is already a slow, infrequent operation.--When any step of a turn (automatic or an explicit `compact` control) reports `compacted`, the owner-latches a handoff. At the next idle boundary after the turn settles, it moves the session to a-successor on its own deployment through the same `SessionHandoff` transaction:--- Eligibility adds to the shared idle check: no queued or buffered input, no unsettled delegated- caller, and no working tasks. The latch holds until a transfer succeeds; like deployment- handoffs, a failed successor is retried at the next opportunity, and an incompatible one is- remembered.-- The successor input carries `reason: "compaction"`. From the eager path it carries no delivery,- so the successor claims the hook set, activates, and parks instead of running a turn.-- A client that replies the moment `session.waiting` arrives races that eager attempt, which- then abandons the transfer and restores the message. While the latch holds, a lone- handoff-eligible delivery therefore carries the transfer itself, exactly like a deployment- signal: the successor runs that delivery first. A delivery accepted by another deployment- takes the ordinary deployment handoff instead.-- The successor keeps the existing deadline. Compaction is a storage concern and never extends the- session lifetime, unlike a deployment handoff.--The anchor's log stops growing at the first handoff, and each later owner's log spans at most the-turns between two compactions.--## 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, active subagent turns or leases,- batched deliveries, and queued commands. Work stays on A. Settlement and queue draining trigger- nothing; only a fresh eligible delivery does. No remembered target or active handle crosses- versions.-- `parked` conversation handles and `available` task-owned handles cross with settled state. The- successor can resume them by stable child address, while the child continues on the deployment- that owns it.-- 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/research/stranded-session-revival.md b/research/stranded-session-revival.mdindex 50687ec09..ad541f26a 100644--- a/research/stranded-session-revival.md+++ b/research/stranded-session-revival.md@@ -11,7 +11,7 @@ last_updated: "2026-10-05"A session is **stranded** when the code that started its Workflow run is no longer available toexecute it. A Workflow run can only be replayed by the exact code that started it, and eve's stepids include the eve version, so after any eve upgrade older runs can't be replayed. On Vercel this-is rare: old deployments keep running, and sessions [hand off](./single-workflow-session-upgrades.md)+is rare: old deployments keep running, and sessions [hand off](./atomic-session-handoff.md)to the new one. On self-hosted Worlds, every eve upgrade strands every parked session (#2866,#3022).