The Open Framework for Building Agents
fix(eve): session startup - return early and retry follow-ups (#2843)
Andrew Barba9ed9d29a892c
diff --git a/.changeset/quick-hooks-smile.md b/.changeset/quick-hooks-smile.mdnew file mode 100644index 000000000..54d5ad8ea--- /dev/null+++ b/.changeset/quick-hooks-smile.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Reduce new-session startup latency by returning the session ID as soon as Workflow accepts the run instead of waiting for its command inbox. Hook claims and session initialization also start together so the first turn can begin sooner, and `session.send()` retries the brief inbox-readiness gap three times with exponential backoff.diff --git a/docs/channels/eve.mdx b/docs/channels/eve.mdxindex e1c336dcf..a94c05dfc 100644--- a/docs/channels/eve.mdx+++ b/docs/channels/eve.mdx@@ -47,6 +47,10 @@ curl -X POST https://<deployment>/eve/v1/session \# {"ok":true,"sessionId":"wrun_A","status":"accepted"}```+The `202` response means Workflow accepted the durable run. The command inbox may still be+starting, so an immediate follow-up or control request can report that the session is not active.+The event-stream client retries the brief window before the new run becomes readable.+Authenticated callers that may retry a create request can pass their own `operationId` forcreate-once semantics. The same operation under the same authenticated principal returns theactive session it already created instead of dispatching the input again. The first accepted@@ -72,7 +76,7 @@ curl -X POST https://<deployment>/eve/v1/session/wrun_A \Follow-up messages use `turnPolicy: "steer"` by default. If a turn is active, eve buffers the message before cooperatively cancelling that turn, then starts the follow-up as a replacement turn with a new turn ID. Set `turnPolicy: "queue"` on `eveChannel(...)` when follow-ups should wait for active turns to finish. `inputResponses` never steer.-Sending a message to an unknown or terminal session ID returns `409` with+Sending a message to an unknown, terminal, or not-yet-active session ID returns `409` with`{"code":"session_not_active","error":"The session is no longer active.","ok":false}`.TypeScript clients expose the stable code as `ClientError.code`. The route nevercreates or follows a replacement session.diff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.mdindex 0249b6457..d2089f304 100644--- a/docs/concepts/sessions-runs-and-streaming.md+++ b/docs/concepts/sessions-runs-and-streaming.md@@ -32,8 +32,10 @@ curl -X POST http://127.0.0.1:2000/eve/v1/session \-d '{"message":"Summarize the latest forecast."}'```-eve responds right away with the durable `sessionId` in the JSON body and-`x-eve-session-id` header.+eve responds with `202` and the durable `sessionId` in the JSON body and+`x-eve-session-id` header as soon as Workflow accepts the run. The command inbox can still be+starting at that point. An immediate follow-up can return `409 session_not_active`; wait for+`session.waiting` before sending the next message.## Stream a sessiondiff --git a/docs/guides/client/messages.mdx b/docs/guides/client/messages.mdxindex 5cc804ec7..9e826108f 100644--- a/docs/guides/client/messages.mdx+++ b/docs/guides/client/messages.mdx@@ -36,6 +36,12 @@ console.log(result.status, result.message);When the stream includes `session.failed`, the turn returns `status: "failed"` rather than throwing. Transport and route errors throw `ClientError`.+`session.send()` retries `409 session_not_active` three times when a durable run has been accepted+but its command inbox is still starting. The retries wait 250 ms, 500 ms, and 1 second. Other+errors, `session.respond()`, control methods, and raw HTTP requests do not use this retry. An unknown+session still throws `ClientError` immediately, while a terminal session throws after the final+attempt. The client never creates a replacement session.+## Send a full turn payloadPass the full payload to `create()` for the first turn or `send()` for a follow-up:diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.tsindex 8c757e625..fc75fca24 100644--- a/packages/eve/src/channel/types.ts+++ b/packages/eve/src/channel/types.ts@@ -548,8 +548,8 @@ export type RunResult =| { readonly status: "waiting" };/**- * Handle returned by `runtime.createSession()` once the command inbox is ready,- * before the step loop completes.+ * Handle returned by `runtime.createSession()` once the durable run is accepted,+ * before its command inbox or step loop necessarily starts.** Carries the identifiers needed for stream endpoints.*/diff --git a/packages/eve/src/client/open-stream.ts b/packages/eve/src/client/open-stream.tsindex 54d30edff..96ce7bee5 100644--- a/packages/eve/src/client/open-stream.ts+++ b/packages/eve/src/client/open-stream.ts@@ -303,7 +303,7 @@ function parseTailIndexHeader(headers: Headers): number | undefined {return Number.isSafeInteger(parsed) ? parsed : undefined;}-async function sleep(ms: number, signal?: AbortSignal): Promise<void> {+export async function sleep(ms: number, signal?: AbortSignal): Promise<void> {if (signal?.aborted) {return;}diff --git a/packages/eve/src/client/session.test.ts b/packages/eve/src/client/session.test.tsindex b607591df..01957420e 100644--- a/packages/eve/src/client/session.test.ts+++ b/packages/eve/src/client/session.test.ts@@ -56,6 +56,17 @@ function createAcceptedResponse() {);}+function createSessionNotActiveResponse() {+ return Response.json(+ {+ code: "session_not_active",+ error: "The session is no longer active.",+ ok: false,+ },+ { status: 409 },+ );+}+function createStreamResponse(events: readonly unknown[]) {const encoder = new TextEncoder();return new Response(@@ -257,20 +268,65 @@ describe("ClientSession", () => {await expect(session.cancel()).rejects.toThrow("Cancel route returned an invalid response");});- it("exposes a typed session_not_active conflict", async () => {- vi.spyOn(globalThis, "fetch").mockResolvedValue(- Response.json(- {- code: "session_not_active",- error: "The session is no longer active.",- ok: false,- },- { status: 409 },- ),+ it("retries session_not_active with exponential backoff", async () => {+ let headerResolution = 0;+ const observedHeaders: string[] = [];+ const fetchMock = vi.spyOn(globalThis, "fetch").mockImplementation(async (_request, init) => {+ observedHeaders.push(new Headers(init?.headers).get("x-attempt") ?? "");+ return fetchMock.mock.calls.length <= 3+ ? createSessionNotActiveResponse()+ : createAcceptedResponse();+ });+ const session = createSession(+ { sessionId: "session_1", streamIndex: 0 },+ {+ resolveHeaders: async () => new Headers({ "x-attempt": String((headerResolution += 1)) }),+ },);++ vi.useFakeTimers();+ try {+ const sent = session.send("ready soon");+ await vi.advanceTimersByTimeAsync(0);+ expect(fetchMock).toHaveBeenCalledTimes(1);++ await vi.advanceTimersByTimeAsync(249);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(1);+ expect(fetchMock).toHaveBeenCalledTimes(2);++ await vi.advanceTimersByTimeAsync(499);+ expect(fetchMock).toHaveBeenCalledTimes(2);+ await vi.advanceTimersByTimeAsync(1);+ expect(fetchMock).toHaveBeenCalledTimes(3);++ await vi.advanceTimersByTimeAsync(999);+ expect(fetchMock).toHaveBeenCalledTimes(3);+ await vi.advanceTimersByTimeAsync(1);+ await expect(sent).resolves.toMatchObject({ sessionId: "session_1" });+ } finally {+ vi.useRealTimers();+ }++ expect(fetchMock).toHaveBeenCalledTimes(4);+ expect(observedHeaders).toEqual(["1", "2", "3", "4"]);+ });++ it("exposes the typed session_not_active conflict after three retries", async () => {+ const fetchMock = vi+ .spyOn(globalThis, "fetch")+ .mockImplementation(async () => createSessionNotActiveResponse());const session = createSession({ sessionId: "session_1", streamIndex: 0 });- const error = await session.send("too late").catch((cause: unknown) => cause);+ vi.useFakeTimers();+ let error: unknown;+ try {+ const sent = session.send("too late").catch((cause: unknown) => cause);+ await vi.runAllTimersAsync();+ error = await sent;+ } finally {+ vi.useRealTimers();+ }expect(error).toBeInstanceOf(ClientError);expect(error).toMatchObject({@@ -278,6 +334,58 @@ describe("ClientSession", () => {message: "The session is no longer active.",status: 409,});+ expect(fetchMock).toHaveBeenCalledTimes(4);+ });++ it("does not retry another conflict from send", async () => {+ const fetchMock = vi+ .spyOn(globalThis, "fetch")+ .mockResolvedValue(+ Response.json(+ { code: "another_conflict", error: "The request conflicts.", ok: false },+ { status: 409 },+ ),+ );+ const session = createSession({ sessionId: "session_1", streamIndex: 0 });++ await expect(session.send("conflict")).rejects.toMatchObject({+ code: "another_conflict",+ status: 409,+ });+ expect(fetchMock).toHaveBeenCalledOnce();+ });++ it("does not retry session_not_active from respond", async () => {+ const fetchMock = vi+ .spyOn(globalThis, "fetch")+ .mockImplementation(async () => createSessionNotActiveResponse());+ const session = createSession({ sessionId: "session_1", streamIndex: 0 });++ await expect(+ session.respond([{ requestId: "approval_1", optionId: "approve" }]),+ ).rejects.toMatchObject({ code: "session_not_active", status: 409 });+ expect(fetchMock).toHaveBeenCalledOnce();+ });++ it("stops session_not_active backoff when send is aborted", async () => {+ const fetchMock = vi+ .spyOn(globalThis, "fetch")+ .mockImplementation(async () => createSessionNotActiveResponse());+ const session = createSession({ sessionId: "session_1", streamIndex: 0 });+ const controller = new AbortController();++ vi.useFakeTimers();+ try {+ const sent = session.send("stop", { signal: controller.signal });+ const assertion = expect(sent).rejects.toMatchObject({ name: "AbortError" });+ await vi.advanceTimersByTimeAsync(0);+ controller.abort(new DOMException("Aborted", "AbortError"));+ await assertion;+ } finally {+ vi.useRealTimers();+ }++ expect(fetchMock).toHaveBeenCalledOnce();});it("queues a context clear without clearing the local session cursor", async () => {diff --git a/packages/eve/src/client/session.ts b/packages/eve/src/client/session.tsindex e1a2b43fc..bd3e02b0f 100644--- a/packages/eve/src/client/session.ts+++ b/packages/eve/src/client/session.ts@@ -3,7 +3,7 @@ import { EVE_SESSION_ID_HEADER, isCurrentTurnBoundaryEvent } from "#protocol/mesimport { EVE_SESSION_ROUTE_PATH, createEveSessionRoutePath } from "#protocol/routes.js";import { ClientError } from "#client/client-error.js";import { MessageResponse } from "#client/message-response.js";-import { followStreamIterable } from "#client/open-stream.js";+import { followStreamIterable, sleep } from "#client/open-stream.js";import {cancelClientSession,clearClientSession,@@ -28,6 +28,9 @@ import type {StreamOptions,} from "#client/types.js";+const SESSION_SEND_RETRY_COUNT = 3;+const SESSION_SEND_RETRY_BASE_DELAY_MS = 250;+/*** Internal interface that a {@link ClientSession} uses to access client-level* configuration without depending on the full {@link Client} class.@@ -94,7 +97,7 @@ export class ClientSession {message: SendTurnInput<TOutput>["message"],options: SendTurnOptions<TOutput> = {},): Promise<MessageResponse<TOutput>> {- return await this.#send({ ...options, message });+ return await this.#send({ ...options, message }, true);}/** Answers pending input requests on this exact session ID. */@@ -105,19 +108,18 @@ export class ClientSession {if (inputResponses.length === 0) {throw new Error("ClientSession.respond() requires at least one input response.");}- return await this.#send({ ...options, inputResponses });+ return await this.#send({ ...options, inputResponses }, false);}async #send<TOutput = unknown>(input: SendTurnPayload<TOutput>,+ retrySessionNotActive: boolean,): Promise<MessageResponse<TOutput>> {const initialStreamIndex = this.#state.streamIndex;- const response = await postTurn(- this.#context,- createEveSessionRoutePath(this.#state.sessionId),- input,- false,- );+ const path = createEveSessionRoutePath(this.#state.sessionId);+ const response = retrySessionNotActive+ ? await postSessionSend(this.#context, path, input)+ : await postTurn(this.#context, path, input, false);const responseSessionId = await readSessionId(response, this.#state.sessionId);if (responseSessionId !== this.#state.sessionId) {throw new Error("Message route returned a different session id.");@@ -257,6 +259,31 @@ export class ClientSession {}}+async function postSessionSend(+ context: ClientSessionContext,+ path: string,+ input: SendTurnPayload,+): Promise<Response> {+ let retryDelayMs = SESSION_SEND_RETRY_BASE_DELAY_MS;+ for (let retry = 0; ; retry += 1) {+ try {+ return await postTurn(context, path, input, false);+ } catch (error) {+ if (!isSessionNotActive(error) || retry >= SESSION_SEND_RETRY_COUNT) throw error;+ }++ await sleep(retryDelayMs, input.signal);+ input.signal?.throwIfAborted();+ retryDelayMs *= 2;+ }+}++function isSessionNotActive(error: unknown): error is ClientError {+ return (+ error instanceof ClientError && error.status === 409 && error.code === "session_not_active"+ );+}+function shouldKeepActiveTurnAlive(policy: StreamOptions["streamReconnectPolicy"]): boolean {if (policy && "reconnect" in policy) {return false;diff --git a/packages/eve/src/execution/workflow-entry.test.ts b/packages/eve/src/execution/workflow-entry.test.tsindex 54f38e62e..a395fe24d 100644--- a/packages/eve/src/execution/workflow-entry.test.ts+++ b/packages/eve/src/execution/workflow-entry.test.ts@@ -150,6 +150,7 @@ interface DeliveryHookConfig {interface AuthHookConfig {readonly dispose?: () => void;+ readonly getConflict?: () => Promise<{ readonly runId: string } | null>;readonly return?: () => Promise<IteratorResult<HookPayload>>;}@@ -225,6 +226,41 @@ describe("workflowEntry", () => {});});+ it("claims command hooks while session creation is still pending", async () => {+ const sessionState = createBaseSessionState();+ let resolveSessionCreation:+ | ((result: ReturnType<typeof createSessionStepResultForMock>) => void)+ | undefined;+ vi.mocked(createSessionStep).mockReturnValueOnce(+ new Promise((resolve) => {+ resolveSessionCreation = resolve;+ }),+ );+ const stableGetConflict = vi.fn(async () => null);+ const authorizationGetConflict = vi.fn(async () => null);+ const continuationGetConflict = vi.fn(async () => null);+ installHookMocks({+ authHook: { getConflict: authorizationGetConflict },+ deliveryHooks: [{ getConflict: continuationGetConflict, token: "http:test" }],+ stableHook: { getConflict: stableGetConflict },+ turnControls: [turnResult({ action: "done", output: "ok", sessionState })],+ });++ const result = workflowEntry({+ input: { message: "hello there" },+ serializedContext: createSerializedContext(),+ });++ expect(createSessionStep).toHaveBeenCalledOnce();+ expect(stableGetConflict).toHaveBeenCalledOnce();+ expect(authorizationGetConflict).toHaveBeenCalledOnce();+ expect(continuationGetConflict).toHaveBeenCalledOnce();+ expect(dispatchTurnStep).not.toHaveBeenCalled();++ resolveSessionCreation?.(createSessionStepResultForMock(sessionState));+ await expect(result).resolves.toEqual({ output: "ok" });+ });+it("omits caller resolution, binding, and settlement steps for a root turn", async () => {const sessionState = createBaseSessionState();vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));@@ -772,6 +808,15 @@ describe("workflowEntry", () => {// serialized context or the delegated parent's call parks forever.vi.mocked(createSessionStep).mockRejectedValueOnce(new Error("session creation failed"));vi.mocked(resolveInitialTurnCallerStep).mockResolvedValueOnce(caller);+ const stableDispose = vi.fn();+ const authorizationDispose = vi.fn();+ const continuationDispose = vi.fn();+ installHookMocks({+ authHook: { dispose: authorizationDispose },+ deliveryHooks: [{ dispose: continuationDispose, token: "http:test" }],+ stableHook: { dispose: stableDispose },+ turnControls: [],+ });const serializedContext = createSerializedContext({"eve.channel": {kind: "subagent",@@ -803,6 +848,9 @@ describe("workflowEntry", () => {});// No snapshot was ever received, so there are no children to terminate.expect(terminateChildSessionsStep).not.toHaveBeenCalled();+ expect(stableDispose).toHaveBeenCalledOnce();+ expect(authorizationDispose).toHaveBeenCalledOnce();+ expect(continuationDispose).toHaveBeenCalledOnce();});it("does not resolve or notify a caller when a root turn crashes", async () => {@@ -1826,6 +1874,7 @@ function installHookMocks(input: {if (token.endsWith(":auth")) {return createMockHook({dispose: input.authHook?.dispose,+ getConflict: input.authHook?.getConflict,return: input.authHook?.return,token,values: [],diff --git a/packages/eve/src/execution/workflow-entry.ts b/packages/eve/src/execution/workflow-entry.tsindex 1d72d04d6..44837a259 100644--- a/packages/eve/src/execution/workflow-entry.ts+++ b/packages/eve/src/execution/workflow-entry.ts@@ -34,7 +34,10 @@ import { emitTerminalSessionFailureStep } from "#execution/terminal-session-failimport { finalizeTerminalSession } from "#execution/finalize-terminal-session.js";import { fireSessionCallbackStep } from "#execution/session-callback-step.js";import { isHookConflictError } from "#execution/hook-ownership.js";-import { createSessionCommandInbox } from "#execution/session-command-inbox.js";+import {+ createSessionCommandInbox,+ type SessionCommandInbox,+} from "#execution/session-command-inbox.js";import { activeTurnId } from "#harness/active-turn-id.js";import { sessionCommandHookToken } from "#execution/session-command-token.js";import { DEFAULT_SESSION_TIMEOUT_MS } from "#execution/session-timeout.js";@@ -178,65 +181,101 @@ export async function workflowEntry(input: WorkflowEntryInput): Promise<Workflow| DynamicSubagentAgentConfig| undefined;- const { state: sessionState } = await createSessionStep({- compiledArtifactsSource: serializedBundle.source,- continuationToken,- dynamicSubagentAgentConfig,- inheritedLimits: input.limits,- nodeId: serializedBundle.nodeId,- outputSchema: input.input.outputSchema,- rootSessionId: rootSessionIdFromParent,- sessionId,- subagentDepth,- taskOwned: isTaskOwnedSerializedContext(input.serializedContext),- });- crashCleanupState.lastSessionState = sessionState;- if (!hasGuaranteedRootLineage(input.serializedContext)) {- crashCleanupState.caller = await resolveInitialTurnCallerStep({+ const commandInbox = createSessionCommandInbox();+ const stableCommandToken = sessionCommandHookToken(sessionId);+ // getHookUrl() builds authorization callback URLs with this token. It is+ // inlined because the durable workflow body cannot import the harness.+ const authorizationHookToken = `${sessionId}:auth`;+ let sessionState: DurableSessionState;+ let outcome: DriverLoopOutcome;+ try {+ // Hook ownership is independent of session hydration. Start every+ // readiness claim immediately so Workflow can persist them while the+ // session bundle is loading, then join every sibling before cleanup.+ const [sessionCreation, stableClaim, authorizationClaim, continuationClaim] =+ await Promise.allSettled([+ createSessionStep({+ compiledArtifactsSource: serializedBundle.source,+ continuationToken,+ dynamicSubagentAgentConfig,+ inheritedLimits: input.limits,+ nodeId: serializedBundle.nodeId,+ outputSchema: input.input.outputSchema,+ rootSessionId: rootSessionIdFromParent,+ sessionId,+ subagentDepth,+ taskOwned: isTaskOwnedSerializedContext(input.serializedContext),+ }),+ commandInbox.claimStable(stableCommandToken),+ commandInbox.claimAuthorization(authorizationHookToken),+ commandInbox.rekeyContinuation(continuationToken),+ ]);++ if (sessionCreation.status === "rejected") throw sessionCreation.reason;+ if (stableClaim.status === "rejected") throw stableClaim.reason;+ if (authorizationClaim.status === "rejected") throw authorizationClaim.reason;+ if (continuationClaim.status === "rejected") {+ // A concurrent create can start two candidate runs before either+ // publishes the shared continuation alias. The runtime adopts the+ // alias owner; the losing candidate exits before its first turn.+ if (isHookConflictError(continuationClaim.reason)) return { output: "" };+ throw continuationClaim.reason;+ }++ sessionState = sessionCreation.value.state;+ crashCleanupState.lastSessionState = sessionState;+ if (!hasGuaranteedRootLineage(input.serializedContext)) {+ crashCleanupState.caller = await resolveInitialTurnCallerStep({+ serializedContext: input.serializedContext,+ });+ }+ crashCleanupState.callerResolved = true;++ outcome = await runDriverLoop({+ capabilities,+ commandInbox,+ driverWritable,+ initialInput: {+ deliveryMetadata:+ input.serializedContext["eve.channelDelivery"] === undefined+ ? undefined+ : [+ {+ ...(input.serializedContext["eve.channelDelivery"] as NonNullable<+ RunInput["delivery"]+ >),+ payloadIndex: 0,+ },+ ],+ kind: "deliver",+ payloads: [+ attachClientContext(+ {+ message: input.input.message,+ context: input.input.context,+ outputSchema: input.input.outputSchema,+ },+ readClientContext(input.input),+ ),+ ],+ requestId: readChannelRequestId(input.serializedContext),+ },+ crashCleanupState,+ mode,serializedContext: input.serializedContext,+ sessionState,+ sessionTimeoutDeadline:+ input.sessionTimeoutMs === false+ ? undefined+ : new Date(+ workflowStartedAt.getTime() ++ (input.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS),+ ),+ stableCommandToken,});+ } finally {+ await commandInbox.dispose();}- crashCleanupState.callerResolved = true;-- const outcome = await runDriverLoop({- capabilities,- driverWritable,- initialInput: {- deliveryMetadata:- input.serializedContext["eve.channelDelivery"] === undefined- ? undefined- : [- {- ...(input.serializedContext["eve.channelDelivery"] as NonNullable<- RunInput["delivery"]- >),- payloadIndex: 0,- },- ],- kind: "deliver",- payloads: [- attachClientContext(- {- message: input.input.message,- context: input.input.context,- outputSchema: input.input.outputSchema,- },- readClientContext(input.input),- ),- ],- requestId: readChannelRequestId(input.serializedContext),- },- crashCleanupState,- mode,- serializedContext: input.serializedContext,- sessionState,- sessionTimeoutDeadline:- input.sessionTimeoutMs === false- ? undefined- : new Date(- workflowStartedAt.getTime() + (input.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS),- ),- });if (outcome.kind === "result") {return outcome.result;}@@ -337,6 +376,7 @@ function hasGuaranteedRootLineage(serializedContext: Record<string, unknown>): basync function runDriverLoop(input: {readonly capabilities?: SessionCapabilities;+ readonly commandInbox: SessionCommandInbox;readonly driverWritable: WritableStream<Uint8Array>;readonly initialInput: HookPayload;readonly crashCleanupState: CrashCleanupState;@@ -344,7 +384,9 @@ async function runDriverLoop(input: {readonly serializedContext: Record<string, unknown>;readonly sessionState: DurableSessionState;readonly sessionTimeoutDeadline?: Date;+ readonly stableCommandToken: string;}): Promise<DriverLoopOutcome> {+ const commandInbox = input.commandInbox;// One payload per exact authorization attempt accumulates across// intervening turns. Replaced attempts are pruned at each park.const collectedAuthPayloads = new Map<string, DeliverPayload>();@@ -424,21 +466,12 @@ async function runDriverLoop(input: {const bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset"> = [];const cancelledTaskIds = new Set<string>();const seenTaskDeliveries = new Set<string>();- const commandInbox = createSessionCommandInbox();- const stableCommandToken = sessionCommandHookToken(input.sessionState.sessionId);- await commandInbox.claimStable(stableCommandToken);- // Per-session authorization-callback hook. Claimed before any turns so it- // exists when authorization.required events trigger OAuth callbacks;- // getHookUrl() builds callback URLs with this token (see authHookToken —- // inlined here because the workflow driver body cannot import the- // harness module).- await commandInbox.claimAuthorization(`${input.sessionState.sessionId}:auth`);const sessionTimeout =input.sessionTimeoutDeadline === undefined? undefined: createSessionTimeoutControl({deadline: input.sessionTimeoutDeadline,- token: stableCommandToken,+ token: input.stableCommandToken,});// Durable state accumulated across turns and the parked waits between@@ -496,18 +529,6 @@ async function runDriverLoop(input: {};try {- if (input.sessionState.continuationToken) {- try {- await commandInbox.rekeyContinuation(input.sessionState.continuationToken);- } catch (error) {- // A concurrent create can start two candidate runs before either- // publishes the shared continuation alias. The runtime adopts the- // alias owner; the losing candidate must exit before its first turn- // instead of emitting a second session failure for the same create.- if (!isHookConflictError(error)) throw error;- return { kind: "result", result: { output: "" } };- }- }await sessionTimeout?.start();let action: TurnDriverAction = await runTurn(input.initialInput);@@ -656,6 +677,5 @@ async function runDriverLoop(input: {} finally {await disposeSettledTurnControl?.();await sessionTimeout?.dispose();- await commandInbox.dispose();}}diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.tsindex cde919e79..762aa1b46 100644--- a/packages/eve/src/execution/workflow-runtime.test.ts+++ b/packages/eve/src/execution/workflow-runtime.test.ts@@ -436,6 +436,43 @@ describe("createWorkflowRuntime#createSession", () => {);});+ it("returns without waiting for the stable command inbox", async () => {+ const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;+ mockBundleAndRun(compiledArtifactsSource);+ startMock.mockResolvedValue({ runId: "driver-run" });++ await expect(+ buildRuntime(compiledArtifactsSource).createSession({+ adapter,+ auth: null,+ input: { message: "hello" },+ mode: "conversation",+ }),+ ).resolves.toMatchObject({ sessionId: "driver-run" });++ expect(getHookByTokenMock).not.toHaveBeenCalled();+ });++ it("waits only for continuation ownership when a token is supplied", async () => {+ const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;+ mockBundleAndRun(compiledArtifactsSource);+ startMock.mockResolvedValue({ runId: "driver-run" });+ getHookByTokenMock.mockResolvedValue({ runId: "driver-run" });++ await expect(+ buildRuntime(compiledArtifactsSource).createSession({+ adapter,+ auth: null,+ continuationToken: "slack:thread",+ input: { message: "hello" },+ mode: "conversation",+ }),+ ).resolves.toMatchObject({ sessionId: "driver-run" });++ expect(getHookByTokenMock).toHaveBeenCalledOnce();+ expect(getHookByTokenMock).toHaveBeenCalledWith("slack:thread");+ });+it("stores an explicit title alongside the trace-content policy", async () => {const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;mockBundleAndRun(compiledArtifactsSource);diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.tsindex 7053d40be..feead2ebe 100644--- a/packages/eve/src/execution/workflow-runtime.ts+++ b/packages/eve/src/execution/workflow-runtime.ts@@ -244,8 +244,8 @@ export function createWorkflowRuntime(config: {throw error;}- try {- if (input.continuationToken) {+ if (input.continuationToken) {+ try {const owner = await waitForCommandHookOwner(input.continuationToken);if (owner.runId !== run.runId) {throw new RuntimeSessionOwnershipConflictError({@@ -254,11 +254,10 @@ export function createWorkflowRuntime(config: {sessionId: run.runId,});}+ } catch (error) {+ await cancelActivityCollector(collectorRunId);+ throw error;}- await waitForOwnedCommandHook(sessionCommandHookToken(run.runId), run.runId);- } catch (error) {- await cancelActivityCollector(collectorRunId);- throw error;}let events: ReadableStream<MessageStreamEvent> | undefined;@@ -412,17 +411,6 @@ function isInactiveCommandTarget(error: unknown): boolean {return false;}-async function waitForOwnedCommandHook(token: string, sessionId: string): Promise<void> {- const owner = await waitForCommandHookOwner(token);- if (owner.runId !== sessionId) {- throw new RuntimeSessionOwnershipConflictError({- continuationToken: token,- ownerSessionId: owner.runId,- sessionId,- });- }-}-export async function waitForCommandHookOwner(token: string): Promise<WorkflowHookRecord> {const deadline = Date.now() + COMMAND_HOOK_READY_TIMEOUT_MS;while (true) {