The Open Framework for Building Agents
refactor(eve): unify durable session command routing (#1586)
Casey Gowrie70867761d793
diff --git a/.changeset/tidy-session-command-inbox.md b/.changeset/tidy-session-command-inbox.mdnew file mode 100644index 000000000..be8aaa3c9--- /dev/null+++ b/.changeset/tidy-session-command-inbox.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Route session controls and follow-up messages through one durable command inbox shared by stable session IDs and rekeyable channel addresses.diff --git a/packages/eve/src/channel/cancel.test.ts b/packages/eve/src/channel/cancel.test.tsindex 6ca006393..ae2b033de 100644--- a/packages/eve/src/channel/cancel.test.ts+++ b/packages/eve/src/channel/cancel.test.ts@@ -3,72 +3,48 @@ import { describe, expect, it, vi } from "vitest";import { createCancelFn } from "#channel/cancel.js";import type { Runtime } from "#channel/types.js";-function createRuntime(overrides?: Partial<Runtime>): Runtime {+function createRuntime(): Runtime {return {- cancelTurn: vi.fn().mockResolvedValue({ status: "accepted" }),- clearSession: vi.fn(),- compactSession: vi.fn(),- deliver: vi.fn(),+ createSession: vi.fn(),+ dispatchContinuation: vi.fn().mockResolvedValue({ status: "accepted" }),+ dispatchSession: vi.fn(),getEventStream: vi.fn(),getStreamTailIndex: vi.fn(),- resolveSession: vi.fn().mockResolvedValue({ sessionId: "sess_1" }),- run: vi.fn(),- terminateSession: vi.fn(),- ...overrides,+ resolveContinuation: vi.fn(),};}describe("createCancelFn", () => {- it("namespaces the channel-local token before resolving the session", async () => {+ it("dispatches directly through the namespaced channel address", async () => {const runtime = createRuntime();- const cancel = createCancelFn(runtime, "slack");- await cancel({ continuationToken: "C1:T1" });-- expect(runtime.resolveSession).toHaveBeenCalledWith("slack:C1:T1");+ await expect(+ createCancelFn(runtime, "slack")({ continuationToken: "C1:T1", turnId: "turn_3" }),+ ).resolves.toEqual({ status: "accepted" });+ expect(runtime.dispatchContinuation).toHaveBeenCalledWith({+ command: { kind: "cancel", turnId: "turn_3" },+ continuationToken: "slack:C1:T1",+ });+ expect(runtime.resolveContinuation).not.toHaveBeenCalled();});- it("cancels the resolved session and forwards the turn guard", async () => {+ it("passes through no_active_turn", async () => {const runtime = createRuntime();+ vi.mocked(runtime.dispatchContinuation).mockResolvedValue({ status: "no_active_turn" });- const cancel = createCancelFn(runtime, "slack");- const result = await cancel({ continuationToken: "C1:T1", turnId: "turn_3" });-- expect(result).toEqual({ status: "accepted" });- expect(runtime.cancelTurn).toHaveBeenCalledWith({ sessionId: "sess_1", turnId: "turn_3" });- });-- it("returns 'no_active_turn' for a token no session owns", async () => {- const runtime = createRuntime({ resolveSession: vi.fn().mockResolvedValue(undefined) });-- const cancel = createCancelFn(runtime, "slack");- const result = await cancel({ continuationToken: "unknown" });-- expect(result).toEqual({ status: "no_active_turn" });- expect(runtime.cancelTurn).not.toHaveBeenCalled();+ await expect(+ createCancelFn(runtime, "slack")({ continuationToken: "unknown" }),+ ).resolves.toEqual({ status: "no_active_turn" });});- it("passes through the runtime's cancellation status", async () => {- const runtime = createRuntime({- cancelTurn: vi.fn().mockResolvedValue({ status: "no_active_turn" }),- });-- const cancel = createCancelFn(runtime, "slack");-- await expect(cancel({ continuationToken: "C1:T1" })).resolves.toEqual({- status: "no_active_turn",- });- });-- it("propagates unexpected resolution failures and never starts a session", async () => {+ it("propagates dispatch failures without creating a session", async () => {const failure = new Error("transient backing-store outage");- const runtime = createRuntime({ resolveSession: vi.fn().mockRejectedValue(failure) });-- const cancel = createCancelFn(runtime, "slack");+ const runtime = createRuntime();+ vi.mocked(runtime.dispatchContinuation).mockRejectedValue(failure);- await expect(cancel({ continuationToken: "C1:T1" })).rejects.toBe(failure);- expect(runtime.cancelTurn).not.toHaveBeenCalled();- expect(runtime.run).not.toHaveBeenCalled();- expect(runtime.deliver).not.toHaveBeenCalled();+ await expect(createCancelFn(runtime, "slack")({ continuationToken: "C1:T1" })).rejects.toBe(+ failure,+ );+ expect(runtime.createSession).not.toHaveBeenCalled();});});diff --git a/packages/eve/src/channel/cancel.ts b/packages/eve/src/channel/cancel.tsindex 70a381f13..c77729250 100644--- a/packages/eve/src/channel/cancel.ts+++ b/packages/eve/src/channel/cancel.ts@@ -2,19 +2,13 @@ import type { CancelFn, CancelOptions } from "#channel/routes.js";import type { CancelTurnResult, Runtime } from "#channel/types.js";/**- * Builds the route-handler `cancel` helper for one channel. Resolves the- * channel-local continuation token to its owning session without delivering- * input, then delegates to the runtime's session-id-addressed cancellation.+ * Builds the route-handler `cancel` helper for one channel.*/export function createCancelFn(runtime: Runtime, channelName: string): CancelFn {return async (options: CancelOptions): Promise<CancelTurnResult> => {- const continuationToken = `${channelName}:${options.continuationToken}`;- const owner = await runtime.resolveSession(continuationToken);-- if (owner === undefined) {- return { status: "no_active_turn" };- }-- return await runtime.cancelTurn({ sessionId: owner.sessionId, turnId: options.turnId });+ return await runtime.dispatchContinuation({+ command: { kind: "cancel", turnId: options.turnId },+ continuationToken: `${channelName}:${options.continuationToken}`,+ });};}diff --git a/packages/eve/src/channel/clear-session.test.ts b/packages/eve/src/channel/clear-session.test.tsindex cec2971c4..be62f3608 100644--- a/packages/eve/src/channel/clear-session.test.ts+++ b/packages/eve/src/channel/clear-session.test.ts@@ -3,29 +3,23 @@ import { describe, expect, it, vi } from "vitest";import { createClearFn } from "#channel/clear-session.js";import type { Runtime } from "#channel/types.js";-function createRuntime(): Runtime {- return {- cancelTurn: vi.fn(),- clearSession: vi.fn().mockResolvedValue({ sessionId: "sess_1", status: "accepted" }),- compactSession: vi.fn(),- deliver: vi.fn(),- getEventStream: vi.fn(),- getStreamTailIndex: vi.fn(),- resolveSession: vi.fn(),- run: vi.fn(),- terminateSession: vi.fn(),- };-}-describe("createClearFn", () => {- it("namespaces the channel-local token and returns the runtime result", async () => {- const runtime = createRuntime();+ it("dispatches clear through the namespaced channel address", async () => {+ const runtime = {+ createSession: vi.fn(),+ dispatchContinuation: vi.fn().mockResolvedValue({ sessionId: "sess_1", status: "accepted" }),+ dispatchSession: vi.fn(),+ getEventStream: vi.fn(),+ getStreamTailIndex: vi.fn(),+ resolveContinuation: vi.fn(),+ } satisfies Runtime;await expect(createClearFn(runtime, "slack")({ continuationToken: "C1:T1" })).resolves.toEqual({sessionId: "sess_1",status: "accepted",});- expect(runtime.clearSession).toHaveBeenCalledWith({+ expect(runtime.dispatchContinuation).toHaveBeenCalledWith({+ command: { kind: "clear" },continuationToken: "slack:C1:T1",});});diff --git a/packages/eve/src/channel/clear-session.ts b/packages/eve/src/channel/clear-session.tsindex d8ffe7971..b7004e363 100644--- a/packages/eve/src/channel/clear-session.ts+++ b/packages/eve/src/channel/clear-session.ts@@ -4,7 +4,8 @@ import type { ClearSessionResult, Runtime } from "#channel/types.js";/** Builds a channel-scoped context-clear helper. */export function createClearFn(runtime: Runtime, channelName: string): ClearFn {return async (options: ClearOptions): Promise<ClearSessionResult> =>- await runtime.clearSession({+ await runtime.dispatchContinuation({+ command: { kind: "clear" },continuationToken: `${channelName}:${options.continuationToken}`,});}diff --git a/packages/eve/src/channel/compact-session.test.ts b/packages/eve/src/channel/compact-session.test.tsindex d9ae8a00f..b55829b4d 100644--- a/packages/eve/src/channel/compact-session.test.ts+++ b/packages/eve/src/channel/compact-session.test.ts@@ -3,28 +3,22 @@ import { describe, expect, it, vi } from "vitest";import { createCompactFn } from "#channel/compact-session.js";import type { Runtime } from "#channel/types.js";-function createRuntime(): Runtime {- return {- cancelTurn: vi.fn(),- clearSession: vi.fn(),- compactSession: vi.fn().mockResolvedValue({ sessionId: "sess_1", status: "accepted" }),- deliver: vi.fn(),- getEventStream: vi.fn(),- getStreamTailIndex: vi.fn(),- resolveSession: vi.fn(),- run: vi.fn(),- terminateSession: vi.fn(),- };-}-describe("createCompactFn", () => {- it("namespaces the channel-local token and returns the runtime result", async () => {- const runtime = createRuntime();+ it("dispatches compact through the namespaced channel address", async () => {+ const runtime = {+ createSession: vi.fn(),+ dispatchContinuation: vi.fn().mockResolvedValue({ sessionId: "sess_1", status: "accepted" }),+ dispatchSession: vi.fn(),+ getEventStream: vi.fn(),+ getStreamTailIndex: vi.fn(),+ resolveContinuation: vi.fn(),+ } satisfies Runtime;await expect(createCompactFn(runtime, "slack")({ continuationToken: "C1:T1" }),).resolves.toEqual({ sessionId: "sess_1", status: "accepted" });- expect(runtime.compactSession).toHaveBeenCalledWith({+ expect(runtime.dispatchContinuation).toHaveBeenCalledWith({+ command: { kind: "compact" },continuationToken: "slack:C1:T1",});});diff --git a/packages/eve/src/channel/compact-session.ts b/packages/eve/src/channel/compact-session.tsindex 2ab4516ae..8f31da14e 100644--- a/packages/eve/src/channel/compact-session.ts+++ b/packages/eve/src/channel/compact-session.ts@@ -4,7 +4,8 @@ import type { CompactSessionResult, Runtime } from "#channel/types.js";/** Builds a channel-scoped manual compaction helper. */export function createCompactFn(runtime: Runtime, channelName: string): CompactFn {return async (options: CompactOptions): Promise<CompactSessionResult> =>- await runtime.compactSession({+ await runtime.dispatchContinuation({+ command: { kind: "compact" },continuationToken: `${channelName}:${options.continuationToken}`,});}diff --git a/packages/eve/src/channel/cross-channel-receive.test.ts b/packages/eve/src/channel/cross-channel-receive.test.tsindex 297689e44..2f9d608c3 100644--- a/packages/eve/src/channel/cross-channel-receive.test.ts+++ b/packages/eve/src/channel/cross-channel-receive.test.ts@@ -10,15 +10,12 @@ import type { Runtime } from "#channel/types.js";function makeRuntime(): Runtime {return {- cancelTurn: vi.fn(),- clearSession: vi.fn(),- compactSession: vi.fn(),- deliver: vi.fn(),+ createSession: vi.fn(),+ dispatchContinuation: vi.fn(),+ dispatchSession: vi.fn(),getEventStream: vi.fn(),getStreamTailIndex: vi.fn(),- resolveSession: vi.fn(),- run: vi.fn(),- terminateSession: vi.fn(),+ resolveContinuation: vi.fn(),};}diff --git a/packages/eve/src/channel/reset-session.test.ts b/packages/eve/src/channel/reset-session.test.tsindex 7cc384dc1..a35134036 100644--- a/packages/eve/src/channel/reset-session.test.ts+++ b/packages/eve/src/channel/reset-session.test.ts@@ -3,40 +3,21 @@ import { describe, expect, it, vi } from "vitest";import { createResetFn } from "#channel/reset-session.js";import type { Runtime } from "#channel/types.js";-function createRuntime(overrides?: Partial<Runtime>): Runtime {+function createRuntime(): Runtime {return {- cancelTurn: vi.fn(),- clearSession: vi.fn(),- compactSession: vi.fn(),- deliver: vi.fn(),+ createSession: vi.fn(),+ dispatchContinuation: vi+ .fn()+ .mockResolvedValue({ previousSessionId: "sess_1", status: "reset" }),+ dispatchSession: vi.fn(),getEventStream: vi.fn(),getStreamTailIndex: vi.fn().mockResolvedValue(-1),- resolveSession: vi.fn().mockResolvedValue({ sessionId: "sess_1" }),- run: vi.fn(),- terminateSession: vi.fn().mockResolvedValue({ status: "terminated" }),- ...overrides,+ resolveContinuation: vi.fn(),};}describe("createResetFn", () => {- it("namespaces the channel-local token before resolving its owner", async () => {- const runtime = createRuntime();-- await createResetFn(runtime, "imessage")({ continuationToken: "direct:+1:+2" });-- expect(runtime.resolveSession).toHaveBeenCalledWith("imessage:direct:+1:+2");- });-- it("returns no_active_session without terminating when no session owns the token", async () => {- const runtime = createRuntime({ resolveSession: vi.fn().mockResolvedValue(undefined) });-- await expect(- createResetFn(runtime, "imessage")({ continuationToken: "direct:+1:+2" }),- ).resolves.toEqual({ status: "no_active_session" });- expect(runtime.terminateSession).not.toHaveBeenCalled();- });-- it("terminates the observed session id once and returns it", async () => {+ it("dispatches reset directly through the namespaced channel address", async () => {const runtime = createRuntime();await expect(@@ -47,39 +28,30 @@ describe("createResetFn", () => {continuationToken: "direct:+1:+2",reason: "User requested /new",}),- ).resolves.toEqual({ status: "reset", previousSessionId: "sess_1" });- expect(runtime.terminateSession).toHaveBeenCalledWith({- reason: "User requested /new",- sessionId: "sess_1",+ ).resolves.toEqual({ previousSessionId: "sess_1", status: "reset" });+ expect(runtime.dispatchContinuation).toHaveBeenCalledWith({+ command: { kind: "reset", reason: "User requested /new" },+ continuationToken: "imessage:direct:+1:+2",});- expect(runtime.resolveSession).toHaveBeenCalledOnce();+ expect(runtime.resolveContinuation).not.toHaveBeenCalled();});- it("treats an already-terminal observed owner as a successful reset", async () => {- const runtime = createRuntime({- terminateSession: vi.fn().mockResolvedValue({ status: "already_terminal" }),- });+ it("passes through no_active_session", async () => {+ const runtime = createRuntime();+ vi.mocked(runtime.dispatchContinuation).mockResolvedValue({ status: "no_active_session" });await expect(createResetFn(runtime, "imessage")({ continuationToken: "direct:+1:+2" }),- ).resolves.toEqual({ status: "reset", previousSessionId: "sess_1" });+ ).resolves.toEqual({ status: "no_active_session" });});- it("propagates unexpected resolution and termination failures", async () => {- const resolutionFailure = new Error("World unavailable");- const resolutionRuntime = createRuntime({- resolveSession: vi.fn().mockRejectedValue(resolutionFailure),- });- await expect(- createResetFn(resolutionRuntime, "imessage")({ continuationToken: "direct:+1:+2" }),- ).rejects.toBe(resolutionFailure);+ it("propagates dispatch failures", async () => {+ const failure = new Error("World unavailable");+ const runtime = createRuntime();+ vi.mocked(runtime.dispatchContinuation).mockRejectedValue(failure);- const terminationFailure = new Error("World unavailable");- const terminationRuntime = createRuntime({- terminateSession: vi.fn().mockRejectedValue(terminationFailure),- });await expect(- createResetFn(terminationRuntime, "imessage")({ continuationToken: "direct:+1:+2" }),- ).rejects.toBe(terminationFailure);+ createResetFn(runtime, "imessage")({ continuationToken: "direct:+1:+2" }),+ ).rejects.toBe(failure);});});diff --git a/packages/eve/src/channel/reset-session.ts b/packages/eve/src/channel/reset-session.tsindex fafb8378c..9e615e5d2 100644--- a/packages/eve/src/channel/reset-session.ts+++ b/packages/eve/src/channel/reset-session.ts@@ -2,21 +2,14 @@ import type { ResetFn, ResetOptions, ResetResult } from "#channel/routes.js";import type { Runtime } from "#channel/types.js";/**- * Builds a channel-scoped session reset helper. It resolves an owner once and- * retires that observed session id, so it can never cancel a later owner that- * claimed the same continuation token.+ * Builds a channel-scoped session reset helper.*/export function createResetFn(runtime: Runtime, channelName: string): ResetFn {return async (options: ResetOptions): Promise<ResetResult> => {const continuationToken = `${channelName}:${options.continuationToken}`;- const owner = await runtime.resolveSession(continuationToken);-- if (owner === undefined) {- return { status: "no_active_session" };- }-- await runtime.terminateSession({ reason: options.reason, sessionId: owner.sessionId });-- return { status: "reset", previousSessionId: owner.sessionId };+ return await runtime.dispatchContinuation({+ command: { kind: "reset", reason: options.reason },+ continuationToken,+ });};}diff --git a/packages/eve/src/channel/resolve-active-session.test.ts b/packages/eve/src/channel/resolve-active-session.test.tsindex b70e40123..5bd1f2d2c 100644--- a/packages/eve/src/channel/resolve-active-session.test.ts+++ b/packages/eve/src/channel/resolve-active-session.test.ts@@ -5,32 +5,29 @@ import type { Runtime } from "#channel/types.js";function runtime(): Runtime {return {- cancelTurn: vi.fn(),- clearSession: vi.fn(),- compactSession: vi.fn(),- deliver: vi.fn(),+ createSession: vi.fn(),+ dispatchContinuation: vi.fn(),+ dispatchSession: vi.fn(),getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),getStreamTailIndex: vi.fn().mockResolvedValue(-1),- resolveSession: vi.fn(),- run: vi.fn(),- terminateSession: vi.fn(),+ resolveContinuation: vi.fn(),};}describe("createResolveActiveSessionFn", () => {it("resolves a channel-local continuation using the authored channel name", async () => {const mockRuntime = runtime();- vi.mocked(mockRuntime.resolveSession).mockResolvedValue({ sessionId: "session-1" });+ vi.mocked(mockRuntime.resolveContinuation).mockResolvedValue({ sessionId: "session-1" });await expect(createResolveActiveSessionFn(mockRuntime, "support")({ continuationToken: "C1:T1" }),).resolves.toEqual({ sessionId: "session-1" });- expect(mockRuntime.resolveSession).toHaveBeenCalledWith("support:C1:T1");+ expect(mockRuntime.resolveContinuation).toHaveBeenCalledWith("support:C1:T1");});it("returns undefined for an inactive continuation", async () => {const mockRuntime = runtime();- vi.mocked(mockRuntime.resolveSession).mockResolvedValue(undefined);+ vi.mocked(mockRuntime.resolveContinuation).mockResolvedValue(undefined);await expect(createResolveActiveSessionFn(mockRuntime, "support")({ continuationToken: "C1:T1" }),diff --git a/packages/eve/src/channel/resolve-active-session.ts b/packages/eve/src/channel/resolve-active-session.tsindex c982157e6..42dce629b 100644--- a/packages/eve/src/channel/resolve-active-session.ts+++ b/packages/eve/src/channel/resolve-active-session.ts@@ -6,5 +6,6 @@ export function createResolveActiveSessionFn(runtime: Runtime,channelName: string,): ResolveActiveSessionFn {- return ({ continuationToken }) => runtime.resolveSession(`${channelName}:${continuationToken}`);+ return ({ continuationToken }) =>+ runtime.resolveContinuation(`${channelName}:${continuationToken}`);}diff --git a/packages/eve/src/channel/schedule.test.ts b/packages/eve/src/channel/schedule.test.tsindex b47abe80a..4a9d7e6ab 100644--- a/packages/eve/src/channel/schedule.test.ts+++ b/packages/eve/src/channel/schedule.test.ts@@ -10,7 +10,6 @@ import {ScheduleDispatcher,} from "#channel/schedule.js";import type { RunHandle, Runtime } from "#channel/types.js";-import { RuntimeNoActiveSessionError } from "#execution/runtime-errors.js";import { slackChannel } from "#public/channels/slack/slackChannel.js";import type { ResolvedChannelDefinition } from "#runtime/types.js";@@ -24,15 +23,12 @@ function createMockRunHandle(): RunHandle {function createMockRuntime(): Runtime {return {- cancelTurn: vi.fn(),- clearSession: vi.fn(),- compactSession: vi.fn(),- deliver: vi.fn().mockRejectedValue(new RuntimeNoActiveSessionError("schedule:token")),- resolveSession: vi.fn(),- run: vi.fn().mockResolvedValue(createMockRunHandle()),+ createSession: vi.fn().mockResolvedValue(createMockRunHandle()),+ dispatchContinuation: vi.fn().mockResolvedValue({ status: "session_not_active" }),+ dispatchSession: vi.fn(),getEventStream: vi.fn().mockResolvedValue(new ReadableStream<MessageStreamEvent>()),getStreamTailIndex: vi.fn().mockResolvedValue(-1),- terminateSession: vi.fn(),+ resolveContinuation: vi.fn(),};}@@ -63,7 +59,7 @@ function makeSlackChannelEntry(): {describe("ScheduleDispatcher", () => {describe("markdown form", () => {- it("starts a Session via runtime.run with the SCHEDULE_ADAPTER", async () => {+ it("starts a Session via runtime.createSession with the SCHEDULE_ADAPTER", async () => {const runtime = createMockRuntime();const dispatcher = new ScheduleDispatcher({ runtime, channels: [] });@@ -72,7 +68,7 @@ describe("ScheduleDispatcher", () => {markdown: "Run heartbeat task.",});- expect(runtime.run).toHaveBeenCalledWith(+ expect(runtime.createSession).toHaveBeenCalledWith(expect.objectContaining({adapter: SCHEDULE_ADAPTER,input: { message: "Run heartbeat task." },@@ -86,9 +82,9 @@ describe("ScheduleDispatcher", () => {expect(result.waitUntilTasks).toHaveLength(0);});- it("propagates runtime.run failures", async () => {+ it("propagates runtime.createSession failures", async () => {const runtime = createMockRuntime();- runtime.run = vi.fn().mockRejectedValue(new Error("boom"));+ runtime.createSession = vi.fn().mockRejectedValue(new Error("boom"));const dispatcher = new ScheduleDispatcher({ runtime, channels: [] });await expect(dispatcher.trigger({ scheduleId: "heartbeat", markdown: "x" })).rejects.toThrow(@@ -127,9 +123,9 @@ describe("ScheduleDispatcher", () => {expect(observed.hasAppAuth).toBe(true);expect(observed.hasWaitUntil).toBe(true);expect(result.sessions).toHaveLength(1);- expect(runtime.run).toHaveBeenCalledTimes(1);+ expect(runtime.createSession).toHaveBeenCalledTimes(1);- const runInput = vi.mocked(runtime.run).mock.calls[0]![0];+ const runInput = vi.mocked(runtime.createSession).mock.calls[0]![0];expect(runInput.continuationToken).toMatch(/^slack:C0123ABC:[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/,);diff --git a/packages/eve/src/channel/schedule.ts b/packages/eve/src/channel/schedule.tsindex 7fed44100..6794875e3 100644--- a/packages/eve/src/channel/schedule.ts+++ b/packages/eve/src/channel/schedule.ts@@ -106,7 +106,7 @@ export class ScheduleDispatcher {}private async runMarkdown(markdown: string): Promise<Session> {- const handle = await this.runtime.run({+ const handle = await this.runtime.createSession({adapter: SCHEDULE_ADAPTER,auth: SCHEDULE_APP_AUTH,input: { message: markdown },diff --git a/packages/eve/src/channel/send.test.ts b/packages/eve/src/channel/send.test.tsindex 7ebf80cbe..124a25084 100644--- a/packages/eve/src/channel/send.test.ts+++ b/packages/eve/src/channel/send.test.ts@@ -2,8 +2,11 @@ import { describe, expect, it, vi } from "vitest";import type { ChannelAdapter } from "#channel/adapter.js";import { createSendFn } from "#channel/send.js";-import type { RunHandle, Runtime } from "#channel/types.js";-import { RuntimeNoActiveSessionError } from "#execution/runtime-errors.js";+import type { RunHandle, Runtime, SessionSendCommandResult } from "#channel/types.js";+import {+ RuntimeNoActiveSessionError,+ RuntimeSessionOwnershipConflictError,+} from "#execution/runtime-errors.js";import type { MessageStreamEvent } from "#protocol/message.js";function createMockRunHandle(): RunHandle {@@ -14,49 +17,49 @@ function createMockRunHandle(): RunHandle {};}-function createRuntime(deliverError: unknown): Runtime {+function createRuntime(+ dispatchResult: SessionSendCommandResult = { status: "session_not_active" },+): Runtime {return {- cancelTurn: vi.fn(),- clearSession: vi.fn(),- compactSession: vi.fn(),- deliver: vi.fn().mockRejectedValue(deliverError),- resolveSession: vi.fn(),- run: vi.fn().mockResolvedValue(createMockRunHandle()),+ createSession: vi.fn().mockResolvedValue(createMockRunHandle()),+ dispatchContinuation: vi.fn().mockResolvedValue(dispatchResult),+ dispatchSession: vi.fn(),getEventStream: vi.fn().mockResolvedValue(new ReadableStream<MessageStreamEvent>()),getStreamTailIndex: vi.fn().mockResolvedValue(-1),- terminateSession: vi.fn(),+ resolveContinuation: vi.fn(),};}const ADAPTER: ChannelAdapter = { kind: "channel:test" };describe("createSendFn", () => {- it("starts a new session silently when the runtime reports no active session", async () => {- const noSession = new RuntimeNoActiveSessionError("test:token");- const runtime = createRuntime(noSession);- // info/debug → console.log; warn → console.warn. Spy on both.- const log = vi.spyOn(console, "log").mockImplementation(() => {});- const warn = vi.spyOn(console, "warn").mockImplementation(() => {});-+ it("creates a session when the channel address is unowned", async () => {+ const runtime = createRuntime();const send = createSendFn(runtime, ADAPTER, "test");- const session = await send("hello", {- auth: null,- continuationToken: "token",- });- expect(session.id).toBe("mock-session-id");- expect(runtime.deliver).toHaveBeenCalledTimes(1);- expect(runtime.run).toHaveBeenCalledTimes(1);- expect(log).not.toHaveBeenCalled();- expect(warn).not.toHaveBeenCalled();+ const session = await send("hello", { auth: null, continuationToken: "token" });- log.mockRestore();- warn.mockRestore();+ expect(session.id).toBe("mock-session-id");+ expect(runtime.dispatchContinuation).toHaveBeenCalledWith({+ command: {+ auth: null,+ caller: undefined,+ kind: "send",+ payload: {+ context: undefined,+ inputResponses: undefined,+ message: "hello",+ outputSchema: undefined,+ },+ requestId: undefined,+ },+ continuationToken: "test:token",+ });+ expect(runtime.createSession).toHaveBeenCalledOnce();});it("rethrows a typed no-active-session error when resume intent forbids fallback", async () => {- const noSession = new RuntimeNoActiveSessionError("test:token");- const runtime = createRuntime(noSession);+ const runtime = createRuntime();const send = createSendFn(runtime, ADAPTER, "test");await expect(@@ -65,86 +68,84 @@ describe("createSendFn", () => {continuationToken: "token",intent: "resume",}),- ).rejects.toBe(noSession);+ ).rejects.toEqual(new RuntimeNoActiveSessionError("test:token"));- expect(runtime.run).not.toHaveBeenCalled();+ expect(runtime.createSession).not.toHaveBeenCalled();});- it("propagates unexpected delivery failures without starting a new session", async () => {- const failure = new Error("boom");- const runtime = createRuntime(failure);-+ it("returns the existing session without creating", async () => {+ const runtime = createRuntime({ sessionId: "existing-session-id", status: "accepted" });const send = createSendFn(runtime, ADAPTER, "test");- await expect(send("hello", { auth: null, continuationToken: "token" })).rejects.toBe(failure);- expect(runtime.run).not.toHaveBeenCalled();+ await expect(send("hello", { auth: null, continuationToken: "token" })).resolves.toMatchObject({+ id: "existing-session-id",+ continuationToken: "token",+ });+ expect(runtime.createSession).not.toHaveBeenCalled();});- it("rejects inputResponses when no active session exists", async () => {- const runtime = createRuntime(new RuntimeNoActiveSessionError("test:token"));- const send = createSendFn(runtime, ADAPTER, "test");+ it("propagates unexpected dispatch failures without creating", async () => {+ const failure = new Error("boom");+ const runtime = createRuntime();+ vi.mocked(runtime.dispatchContinuation).mockRejectedValue(failure);await expect(- send(- {- inputResponses: [{ requestId: "req-1", text: "yes" }],- },+ createSendFn(+ runtime,+ ADAPTER,+ "test",+ )("hello", {+ auth: null,+ continuationToken: "token",+ }),+ ).rejects.toBe(failure);+ expect(runtime.createSession).not.toHaveBeenCalled();+ });++ it("rejects inputResponses when the channel address is unowned", async () => {+ const runtime = createRuntime();++ await expect(+ createSendFn(+ runtime,+ ADAPTER,+ "test",+ )(+ { inputResponses: [{ requestId: "req-1", text: "yes" }] },{ auth: null, continuationToken: "token" },),).rejects.toThrow(/Cannot deliver inputResponses/);- expect(runtime.run).not.toHaveBeenCalled();+ expect(runtime.createSession).not.toHaveBeenCalled();});- it("forwards context through deliver and run payloads", async () => {- const context = ["thread background"];- const deliverRuntime: Runtime = {- cancelTurn: vi.fn(),- clearSession: vi.fn(),- compactSession: vi.fn(),- deliver: vi.fn().mockResolvedValue({ sessionId: "existing-session-id" }),- resolveSession: vi.fn(),- run: vi.fn().mockResolvedValue(createMockRunHandle()),- getEventStream: vi.fn().mockResolvedValue(new ReadableStream<MessageStreamEvent>()),- getStreamTailIndex: vi.fn().mockResolvedValue(-1),- terminateSession: vi.fn(),- };-- const deliverSend = createSendFn(deliverRuntime, ADAPTER, "test");- await deliverSend({ message: "hello", context }, { auth: null, continuationToken: "token" });-- expect(deliverRuntime.deliver).toHaveBeenCalledWith({- auth: null,- continuationToken: "test:token",- payload: {- inputResponses: undefined,- message: "hello",- context,- },- });- expect(deliverRuntime.run).not.toHaveBeenCalled();-- const runRuntime = createRuntime(new RuntimeNoActiveSessionError("test:token"));- const runSend = createSendFn(runRuntime, ADAPTER, "test");- await runSend({ message: "hello", context }, { auth: null, continuationToken: "token" });+ it("re-dispatches to the winner of a concurrent first-send claim", async () => {+ const runtime = createRuntime();+ vi.mocked(runtime.createSession).mockRejectedValue(+ new RuntimeSessionOwnershipConflictError({+ continuationToken: "test:token",+ ownerSessionId: "winner",+ sessionId: "loser",+ }),+ );+ vi.mocked(runtime.dispatchContinuation)+ .mockResolvedValueOnce({ status: "session_not_active" })+ .mockResolvedValueOnce({ sessionId: "winner", status: "accepted" });- expect(vi.mocked(runRuntime.run).mock.calls[0]![0].input).toEqual({- message: "hello",- context,- });+ await expect(+ createSendFn(+ runtime,+ ADAPTER,+ "test",+ )("hello", {+ auth: null,+ continuationToken: "token",+ }),+ ).resolves.toMatchObject({ id: "winner" });+ expect(runtime.dispatchContinuation).toHaveBeenCalledTimes(2);});- it("forwards the turn caller from options onto the deliver input", async () => {- const runtime: Runtime = {- cancelTurn: vi.fn(),- clearSession: vi.fn(),- compactSession: vi.fn(),- deliver: vi.fn().mockResolvedValue({ sessionId: "existing-session-id" }),- resolveSession: vi.fn(),- run: vi.fn().mockResolvedValue(createMockRunHandle()),- getEventStream: vi.fn().mockResolvedValue(new ReadableStream<MessageStreamEvent>()),- getStreamTailIndex: vi.fn().mockResolvedValue(-1),- terminateSession: vi.fn(),- };+ it("forwards the turn caller on the session command", async () => {+ const runtime = createRuntime({ sessionId: "existing-session-id", status: "accepted" });const caller = {callId: "call-1",replyTo: { kind: "hook" as const, token: "parent-turn" },@@ -157,142 +158,93 @@ describe("createSendFn", () => {"test",)({ message: "follow up" }, { auth: null, caller, continuationToken: "token" });- expect(runtime.deliver).toHaveBeenCalledWith({- auth: null,- caller,+ expect(runtime.dispatchContinuation).toHaveBeenCalledWith({+ command: expect.objectContaining({+ caller,+ payload: expect.not.objectContaining({ caller: expect.anything() }),+ }),continuationToken: "test:token",- payload: expect.not.objectContaining({ caller: expect.anything() }),});});- it("adds channel request ids to deliver and run inputs when provided", async () => {- const deliverRuntime: Runtime = {- cancelTurn: vi.fn(),- clearSession: vi.fn(),- compactSession: vi.fn(),- deliver: vi.fn().mockResolvedValue({ sessionId: "existing-session-id" }),- resolveSession: vi.fn(),- run: vi.fn().mockResolvedValue(createMockRunHandle()),- getEventStream: vi.fn().mockResolvedValue(new ReadableStream<MessageStreamEvent>()),- getStreamTailIndex: vi.fn().mockResolvedValue(-1),- terminateSession: vi.fn(),- };-- const deliverSend = createSendFn(deliverRuntime, ADAPTER, "test", {- requestId: "req_send",- });- await deliverSend("hello", { auth: null, continuationToken: "token" });-- expect(vi.mocked(deliverRuntime.deliver).mock.calls[0]?.[0].requestId).toBe("req_send");-- const runRuntime = createRuntime(new RuntimeNoActiveSessionError("test:token"));- const runSend = createSendFn(runRuntime, ADAPTER, "test", { requestId: "req_send" });- await runSend("hello", { auth: null, continuationToken: "token" });-- expect(vi.mocked(runRuntime.run).mock.calls[0]?.[0].requestId).toBe("req_send");- });-- it("forwards outputSchema through deliver and run payloads", async () => {+ it("forwards context, output schema, and request id through dispatch and creation", async () => {+ const runtime = createRuntime();const outputSchema = {properties: { title: { type: "string" } },required: ["title"],type: "object",} as const;- const deliverRuntime: Runtime = {- cancelTurn: vi.fn(),- clearSession: vi.fn(),- compactSession: vi.fn(),- deliver: vi.fn().mockResolvedValue({ sessionId: "existing-session-id" }),- resolveSession: vi.fn(),- run: vi.fn().mockResolvedValue(createMockRunHandle()),- getEventStream: vi.fn().mockResolvedValue(new ReadableStream<MessageStreamEvent>()),- getStreamTailIndex: vi.fn().mockResolvedValue(-1),- terminateSession: vi.fn(),- };+ const send = createSendFn(runtime, ADAPTER, "test", { requestId: "req_send" });- const deliverSend = createSendFn(deliverRuntime, ADAPTER, "test");- await deliverSend(- { message: "hello", outputSchema },+ await send(+ { context: ["thread background"], message: "hello", outputSchema },{ auth: null, continuationToken: "token" },);- expect(deliverRuntime.deliver).toHaveBeenCalledWith({- auth: null,+ expect(runtime.dispatchContinuation).toHaveBeenCalledWith({+ command: expect.objectContaining({+ payload: expect.objectContaining({+ context: ["thread background"],+ message: "hello",+ outputSchema,+ }),+ requestId: "req_send",+ }),continuationToken: "test:token",- payload: {- inputResponses: undefined,- message: "hello",- modelContext: undefined,- outputSchema,- },- });-- const runRuntime = createRuntime(new RuntimeNoActiveSessionError("test:token"));- const runSend = createSendFn(runRuntime, ADAPTER, "test");- await runSend({ message: "hello", outputSchema }, { auth: null, continuationToken: "token" });-- expect(vi.mocked(runRuntime.run).mock.calls[0]![0].input).toEqual({- message: "hello",- outputSchema,});+ expect(vi.mocked(runtime.createSession).mock.calls[0]![0]).toEqual(+ expect.objectContaining({+ input: {+ context: ["thread background"],+ message: "hello",+ outputSchema,+ },+ requestId: "req_send",+ }),+ );});- it("namespaces the channel-local raw token with the channel name", async () => {- interface State {- channelId: string;- threadTs: string;- }- const runtime = createRuntime(new RuntimeNoActiveSessionError("test:token"));- const stateful: ChannelAdapter = {- kind: "channel:stateful",- state: { channelId: "C1", threadTs: "T1" },- };-- const send = createSendFn<State>(runtime, stateful, "stateful");- await send("hello", {- auth: null,- continuationToken: "C1:T1",- state: { channelId: "C1", threadTs: "T1" },- });-- expect(runtime.run).toHaveBeenCalledTimes(1);- expect(vi.mocked(runtime.run).mock.calls[0]![0].continuationToken).toBe("stateful:C1:T1");- });-- it("seeds adapter state from the send() call so the new session resumes with it", async () => {+ it("namespaces the raw token and seeds state for a new session", async () => {interface State {channelId: string;threadTs: string;}- const runtime = createRuntime(new RuntimeNoActiveSessionError("test:token"));- const stateful: ChannelAdapter = {+ const runtime = createRuntime();+ const adapter: ChannelAdapter = {kind: "channel:stateful",state: { channelId: null, threadTs: null },};- const send = createSendFn<State>(runtime, stateful, "stateful");- await send("hello", {+ await createSendFn<State>(+ runtime,+ adapter,+ "stateful",+ )("hello", {auth: null,continuationToken: "C1:T1",state: { channelId: "C1", threadTs: "T1" },});- const runInput = vi.mocked(runtime.run).mock.calls[0]![0];+ const runInput = vi.mocked(runtime.createSession).mock.calls[0]![0];+ expect(runInput.continuationToken).toBe("stateful:C1:T1");expect(runInput.adapter.state).toEqual({ channelId: "C1", threadTs: "T1" });});it("keeps an explicit workflow title separate from the model message", async () => {- const runtime = createRuntime(new RuntimeNoActiveSessionError("test:token"));- const send = createSendFn(runtime, ADAPTER, "test");- const message = "<slack_message>\n<content>ship it</content>\n</slack_message>";+ const runtime = createRuntime();+ const message = "<slack_message>ship it</slack_message>";- await send(message, {+ await createSendFn(+ runtime,+ ADAPTER,+ "test",+ )(message, {auth: null,continuationToken: "token",title: "ship it",});- const runInput = vi.mocked(runtime.run).mock.calls[0]![0];+ const runInput = vi.mocked(runtime.createSession).mock.calls[0]![0];expect(runInput.input.message).toBe(message);expect(runInput.title).toBe("ship it");});diff --git a/packages/eve/src/channel/send.ts b/packages/eve/src/channel/send.tsindex 22dcf6ce0..c4cdfcb26 100644--- a/packages/eve/src/channel/send.ts+++ b/packages/eve/src/channel/send.ts@@ -1,10 +1,13 @@import type { FilePart, UserContent } from "ai";import type { ChannelAdapter } from "#channel/adapter.js";-import type { DeliverInput, RunInput, Runtime } from "#channel/types.js";+import type { RunInput, Runtime, SessionCommand } from "#channel/types.js";import { createSession, type Session } from "#channel/session.js";import type { SendFn, SendOptions, SendPayload } from "#channel/routes.js";-import { isRuntimeNoActiveSessionError } from "#execution/runtime-errors.js";+import {+ isRuntimeSessionOwnershipConflictError,+ RuntimeNoActiveSessionError,+} from "#execution/runtime-errors.js";import { serializeUrlFilePart } from "#internal/attachments/url-refs.js";export function createSendFn<TState = undefined>(@@ -34,24 +37,27 @@ export function createSendFn<TState = undefined>(} = normalizeSendInput(input);const message = serializeUrlFilePartsInMessage(rawMessage);- try {- const deliverInput: DeliverInput = {- auth,- caller,+ const command: Extract<SessionCommand, { readonly kind: "send" }> = {+ auth,+ caller,+ kind: "send",+ payload: { inputResponses, message, context, outputSchema },+ requestId: metadata.requestId,+ };++ const dispatch = async (): Promise<Session | undefined> => {+ const result = await runtime.dispatchContinuation({+ command,continuationToken,- requestId: metadata.requestId,- payload: { inputResponses, message, context, outputSchema },- };- const { sessionId } = await runtime.deliver(deliverInput);+ });+ return result.status === "accepted"+ ? createSession(result.sessionId, rawToken, runtime)+ : undefined;+ };- return createSession(sessionId, rawToken, runtime);- } catch (error) {- // A resume-intent miss is an expected protocol outcome; the caller- // (e.g. the eve channel's continue route) decides how to surface it.- if (!isRuntimeNoActiveSessionError(error) || intent === "resume") {- throw error;- }- }+ const existing = await dispatch();+ if (existing !== undefined) return existing;+ if (intent === "resume") throw new RuntimeNoActiveSessionError(continuationToken);if (inputResponses && inputResponses.length > 0) {throw new Error(@@ -80,9 +86,15 @@ export function createSendFn<TState = undefined>(if (initiatorAuth !== undefined) {runInput.initiatorAuth = initiatorAuth;}- const handle = await runtime.run(runInput);-- return createSession(handle.sessionId, rawToken, runtime);+ try {+ const handle = await runtime.createSession(runInput);+ return createSession(handle.sessionId, rawToken, runtime);+ } catch (error) {+ if (!isRuntimeSessionOwnershipConflictError(error)) throw error;+ const winner = await dispatch();+ if (winner !== undefined) return winner;+ throw error;+ }};}diff --git a/packages/eve/src/channel/session.test.ts b/packages/eve/src/channel/session.test.tsindex 5edaa11c7..d77b6ac67 100644--- a/packages/eve/src/channel/session.test.ts+++ b/packages/eve/src/channel/session.test.ts@@ -7,15 +7,12 @@ import { AuthKey, ContinuationTokenKey, InitiatorAuthKey, SessionIdKey } from "#function createRuntime(): Runtime {return {- cancelTurn: vi.fn().mockResolvedValue({ status: "accepted" }),- clearSession: vi.fn(),- compactSession: vi.fn(),- deliver: vi.fn(),+ createSession: vi.fn(),+ dispatchContinuation: vi.fn(),+ dispatchSession: vi.fn().mockResolvedValue({ status: "accepted" }),getEventStream: vi.fn(),getStreamTailIndex: vi.fn(),- resolveSession: vi.fn(),- run: vi.fn(),- terminateSession: vi.fn(),+ resolveContinuation: vi.fn(),};}@@ -25,7 +22,10 @@ describe("createSession#cancel", () => {const session = createSession("sess_1", "C1:T1", runtime);await expect(session.cancel()).resolves.toEqual({ status: "accepted" });- expect(runtime.cancelTurn).toHaveBeenCalledWith({ sessionId: "sess_1", turnId: undefined });+ expect(runtime.dispatchSession).toHaveBeenCalledWith({+ command: { kind: "cancel", turnId: undefined },+ sessionId: "sess_1",+ });});it("forwards the turn guard", async () => {@@ -34,7 +34,10 @@ describe("createSession#cancel", () => {await session.cancel({ turnId: "turn_2" });- expect(runtime.cancelTurn).toHaveBeenCalledWith({ sessionId: "sess_1", turnId: "turn_2" });+ expect(runtime.dispatchSession).toHaveBeenCalledWith({+ command: { kind: "cancel", turnId: "turn_2" },+ sessionId: "sess_1",+ });});it("is available on sessions returned by getSession", async () => {@@ -42,7 +45,10 @@ describe("createSession#cancel", () => {const session = createGetSessionFn(runtime)("sess_2");await expect(session.cancel()).resolves.toEqual({ status: "accepted" });- expect(runtime.cancelTurn).toHaveBeenCalledWith({ sessionId: "sess_2", turnId: undefined });+ expect(runtime.dispatchSession).toHaveBeenCalledWith({+ command: { kind: "cancel", turnId: undefined },+ sessionId: "sess_2",+ });});});diff --git a/packages/eve/src/channel/session.ts b/packages/eve/src/channel/session.tsindex 6cd95fa64..d7d0f3e16 100644--- a/packages/eve/src/channel/session.ts+++ b/packages/eve/src/channel/session.ts@@ -54,7 +54,10 @@ export function createSession(id: string, continuationToken: string, runtime: Ruid,continuationToken,async cancel(options?: { turnId?: string }) {- return runtime.cancelTurn({ sessionId: id, turnId: options?.turnId });+ return runtime.dispatchSession({+ command: { kind: "cancel", turnId: options?.turnId },+ sessionId: id,+ });},async getEventStream(options?: { startIndex?: number }) {return runtime.getEventStream(id, options);diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.tsindex f6e55bd92..3b8abac3f 100644--- a/packages/eve/src/channel/types.ts+++ b/packages/eve/src/channel/types.ts@@ -176,6 +176,49 @@ export interface DeliverPayload {readonly [key: string]: unknown;}+/** One command accepted by a durable session inbox. */+export type SessionCommand =+ | {+ readonly auth?: SessionAuthContext | null;+ readonly caller?: TurnCaller;+ readonly kind: "send";+ readonly payload: DeliverPayload;+ readonly requestId?: string;+ }+ | { readonly kind: "cancel"; readonly turnId?: string }+ | { readonly kind: "compact" }+ | { readonly kind: "clear" }+ | { readonly kind: "reset"; readonly reason?: string };++export type SessionSendCommandResult =+ | { readonly status: "accepted"; readonly sessionId: string }+ | { readonly status: "session_not_active" };++export type ResetSessionCommandResult =+ | { readonly status: "reset"; readonly previousSessionId: string }+ | { readonly status: "no_active_session" };++export type SessionCommandResult<TCommand extends SessionCommand = SessionCommand> =+ TCommand extends { readonly kind: "send" }+ ? SessionSendCommandResult+ : TCommand extends { readonly kind: "cancel" }+ ? CancelTurnResult+ : TCommand extends { readonly kind: "compact" }+ ? CompactSessionResult+ : TCommand extends { readonly kind: "clear" }+ ? ClearSessionResult+ : ResetSessionCommandResult;++export interface DispatchContinuationInput<TCommand extends SessionCommand = SessionCommand> {+ readonly command: TCommand;+ readonly continuationToken: string;+}++export interface DispatchSessionInput<TCommand extends SessionCommand = SessionCommand> {+ readonly command: TCommand;+ readonly sessionId: string;+}+// ---------------------------------------------------------------------------// Hook payload// ---------------------------------------------------------------------------@@ -196,7 +239,7 @@ export interface DeliverHookPayload {readonly payloads: readonly DeliverPayload[];}-/** Internal deadline signal sent through the session's delivery hook. */+/** Internal deadline signal sent through the stable session command inbox. */export interface SessionTimeoutHookPayload {readonly kind: "session-timeout";}@@ -335,7 +378,7 @@ export interface SessionCapabilities {// ---------------------------------------------------------------------------/**- * Single input shape consumed by {@link Runtime.run} for both root runs+ * Single input shape consumed by {@link Runtime.createSession} for both root runs* (started by routes) and delegated child runs (started by the* subagent tool wrapper).*/@@ -442,8 +485,8 @@ export type RunResult =| { readonly status: "waiting" };/**- * Handle returned immediately by `runtime.run()` before the step loop- * completes.+ * Handle returned by `runtime.createSession()` once the command inbox is ready,+ * before the step loop completes.** Carries the identifiers needed for stream endpoints.*/@@ -468,31 +511,22 @@ export interface Runtime {* time), builds the seeded {@link AlsContext}, and drives the step loop to* completion.*/- run(input: RunInput): Promise<RunHandle>;-- /** Requests cancellation of a session's in-flight turn. */- cancelTurn(input: CancelTurnInput): Promise<CancelTurnResult>;-- /** Queues context compaction on the session owning a continuation token. */- compactSession(input: CompactSessionInput): Promise<CompactSessionResult>;+ createSession(input: RunInput): Promise<RunHandle>;- /** Queues a context clear on the session owning a continuation token. */- clearSession(input: ClearSessionInput): Promise<ClearSessionResult>;+ dispatchContinuation<TCommand extends SessionCommand>(+ input: DispatchContinuationInput<TCommand>,+ ): Promise<SessionCommandResult<TCommand>>;- /** Terminally retires a session and releases its non-retained continuation hooks. */- terminateSession(input: TerminateSessionInput): Promise<TerminateSessionResult>;-- /**- * Delivers a follow-up message to a parked session.- */- deliver(input: DeliverInput): Promise<{ sessionId: string }>;+ dispatchSession<TCommand extends SessionCommand>(+ input: DispatchSessionInput<TCommand>,+ ): Promise<SessionCommandResult<TCommand>>;/*** Resolves the session that currently owns a continuation token without* delivering input or starting a run. Returns `undefined` when no session* owns the token.*/- resolveSession(continuationToken: string): Promise<{ sessionId: string } | undefined>;+ resolveContinuation(continuationToken: string): Promise<{ sessionId: string } | undefined>;/*** Returns a readable stream of lifecycle events for an existing session.diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.tsindex f6828ffc4..5537adc1e 100644--- a/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts@@ -25,11 +25,10 @@ import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.jsconst mocks = vi.hoisted(() => ({createDurableSessionState: vi.fn(),- deliver: vi.fn(),deserializeContext: vi.fn(),hydrateDurableSession: vi.fn(),readDurableSession: vi.fn(),- run: vi.fn(),+ createSession: vi.fn(),startRemoteAgentSession: vi.fn(),}));@@ -49,8 +48,7 @@ vi.mock("#execution/session.js", () => ({vi.mock("#execution/workflow-runtime.js", () => ({createWorkflowRuntime: () => ({- deliver: mocks.deliver,- run: mocks.run,+ createSession: mocks.createSession,}),workflowEntryReference: { workflowId: "workflow//eve//workflowEntry" },}));@@ -84,8 +82,7 @@ const REMOTE_REGISTRY_DEFINITION = {beforeEach(() => {vi.clearAllMocks();- mocks.deliver.mockResolvedValue({ sessionId: CHILD_SESSION_ID });- mocks.run.mockResolvedValue({ sessionId: CHILD_SESSION_ID });+ mocks.createSession.mockResolvedValue({ sessionId: CHILD_SESSION_ID });mocks.startRemoteAgentSession.mockResolvedValue({continuationToken: "remote-child-token",sessionId: "remote-session-123456789012",@@ -120,7 +117,7 @@ describe("dispatchRuntimeActionsStep child starts", () => {});expect(result.results).toEqual([]);- expect(mocks.run).toHaveBeenCalledTimes(1);+ expect(mocks.createSession).toHaveBeenCalledTimes(1);expect(getAgentHandleStore(readResultSessionState(result, session))).toEqual({handles: [{@@ -153,7 +150,7 @@ describe("dispatchRuntimeActionsStep child starts", () => {definition: { description: "Research", kind: "subagent" },nodeId: "subagents/research",});- mocks.run.mockRejectedValue(new Error("runtime unavailable"));+ mocks.createSession.mockRejectedValue(new Error("runtime unavailable"));const result = await dispatchRuntimeActionsStep({parentContinuationToken: "turn-inbox",diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.tsindex 0c7206ca2..03d3b26e7 100644--- a/packages/eve/src/execution/dispatch-runtime-actions-step.ts+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.ts@@ -465,7 +465,7 @@ async function startLocalSubagent(input: {let childSessionId: string;try {- const handle = await childRuntime.run(runInput);+ const handle = await childRuntime.createSession(runInput);childSessionId = handle.sessionId;} catch (error) {logError(log, "local subagent start failed", error, {diff --git a/packages/eve/src/execution/forward-turn-cancellation-step.ts b/packages/eve/src/execution/forward-turn-cancellation-step.tsnew file mode 100644index 000000000..70255be9f--- /dev/null+++ b/packages/eve/src/execution/forward-turn-cancellation-step.ts@@ -0,0 +1,25 @@+import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";++import type { TurnCancelPayload } from "#execution/turn-cancellation-token.js";+import { resumeHook } from "#internal/workflow/runtime.js";++/** Forwards an inbox cancellation command to one private active-turn hook. */+export async function forwardTurnCancellationStep(input: {+ readonly payload: TurnCancelPayload;+ readonly token: string;+}): Promise<boolean> {+ "use step";++ for (let attempt = 0; attempt < 50; attempt += 1) {+ try {+ await resumeHook(input.token, input.payload);+ return true;+ } catch (error) {+ if (!HookNotFoundError.is(error)) throw error;+ if (attempt === 49) return false;+ await new Promise<void>((resolve) => setTimeout(resolve, 20));+ }+ }++ return false;+}diff --git a/packages/eve/src/execution/node-step.test.ts b/packages/eve/src/execution/node-step.test.tsindex 43ee0bfd9..b7471fbc8 100644--- a/packages/eve/src/execution/node-step.test.ts+++ b/packages/eve/src/execution/node-step.test.ts@@ -218,19 +218,18 @@ function createTestNode(function createNoopRuntime(): Runtime {return {- cancelTurn: vi.fn(),- clearSession: vi.fn(),- compactSession: vi.fn(),- deliver: vi.fn(),- resolveSession: vi.fn(),- run: vi.fn().mockRejectedValue(new Error("runtime.run should not be called in this test")),+ createSession: vi+ .fn()+ .mockRejectedValue(new Error("runtime.createSession should not be called in this test")),+ dispatchContinuation: vi.fn(),+ dispatchSession: vi.fn(),getEventStream: vi.fn().mockRejectedValue(new Error("runtime.getEventStream should not be called in this test")),getStreamTailIndex: vi.fn().mockRejectedValue(new Error("runtime.getStreamTailIndex should not be called in this test")),- terminateSession: vi.fn(),+ resolveContinuation: vi.fn(),};}diff --git a/packages/eve/src/execution/runtime-errors.ts b/packages/eve/src/execution/runtime-errors.tsindex 4d4e42f00..2c0d0bc3a 100644--- a/packages/eve/src/execution/runtime-errors.ts+++ b/packages/eve/src/execution/runtime-errors.ts@@ -21,3 +21,31 @@ export function isRuntimeNoActiveSessionError(): error is RuntimeNoActiveSessionError {return error instanceof RuntimeNoActiveSessionError;}++/** Signals that another session won a concurrent channel-address claim. */+export class RuntimeSessionOwnershipConflictError extends Error {+ readonly continuationToken: string;+ readonly ownerSessionId: string;+ readonly sessionId: string;++ constructor(input: {+ readonly continuationToken: string;+ readonly ownerSessionId: string;+ readonly sessionId: string;+ }) {+ super(+ `Session "${input.sessionId}" lost continuationToken "${input.continuationToken}" ` ++ `to session "${input.ownerSessionId}".`,+ );+ this.name = "RuntimeSessionOwnershipConflictError";+ this.continuationToken = input.continuationToken;+ this.ownerSessionId = input.ownerSessionId;+ this.sessionId = input.sessionId;+ }+}++export function isRuntimeSessionOwnershipConflictError(+ error: unknown,+): error is RuntimeSessionOwnershipConflictError {+ return error instanceof RuntimeSessionOwnershipConflictError;+}diff --git a/packages/eve/src/execution/session-delivery-hook.integration.test.ts b/packages/eve/src/execution/session-command-inbox.integration.test.tssimilarity index 64%rename from packages/eve/src/execution/session-delivery-hook.integration.test.tsrename to packages/eve/src/execution/session-command-inbox.integration.test.tsindex 055bc4528..55f06fab1 100644--- a/packages/eve/src/execution/session-delivery-hook.integration.test.ts+++ b/packages/eve/src/execution/session-command-inbox.integration.test.ts@@ -1,24 +1,46 @@import { describe, expect, it } from "vitest";-import { sessionDeliveryHookWorkflow } from "#internal/testing/session-delivery-hook-workflow.js";+import { sessionCommandInboxWorkflow } from "#internal/testing/session-command-inbox-workflow.js";import { waitForHook } from "#internal/testing/workflow-test-helpers.js";import { getWorld, resumeHook, start } from "#internal/workflow/runtime.js";+import { sessionCommandHookToken } from "#execution/session-command-token.js";++describe("session command inbox integration", () => {+ it("accepts commands alternately through the stable ID and channel aliases", async () => {+ const channelToken = "http:session-command-inbox:both-aliases";+ const run = await start(sessionCommandInboxWorkflow, [{ token: channelToken }]);+ const stableToken = sessionCommandHookToken(run.runId);++ try {+ await Promise.all([+ waitForHook({ runId: run.runId }, { token: stableToken }),+ waitForHook({ runId: run.runId }, { token: channelToken }),+ ]);++ await resumeHook(stableToken, { kind: "send", payload: { message: "by id" } });+ await resumeHook(channelToken, { kind: "send", payload: { message: "by channel" } });++ await expect(run.returnValue).resolves.toEqual(["by id", "by channel"]);+ } finally {+ const status = await run.status;+ if (status === "pending" || status === "running") await run.cancel();+ }+ });-describe("session delivery hook integration", () => {it.each([["old then replacement", ["old", "replacement"] as const],["replacement then old", ["replacement", "old"] as const],- ])("preserves deliveries committed %s during rekey", async (_label, order) => {+ ])("preserves sends committed %s during rekey", async (_label, order) => {const suffix = order.join("-");- const oldToken = `http:session-delivery-hook:${suffix}:old`;- const replacementToken = `http:session-delivery-hook:${suffix}:replacement`;+ const oldToken = `http:session-command-inbox:${suffix}:old`;+ const replacementToken = `http:session-command-inbox:${suffix}:replacement`;const disposal = await pauseHookDisposal(oldToken);- const run = await start(sessionDeliveryHookWorkflow, [+ const run = await start(sessionCommandInboxWorkflow, [{ nextToken: replacementToken, token: oldToken },]);try {- await withTimeout(disposal.started, "old-hook disposal");+ await withTimeout(disposal.started, "old-alias disposal");await Promise.all([waitForHook({ runId: run.runId }, { token: oldToken }),waitForHook({ runId: run.runId }, { token: replacementToken }),@@ -26,20 +48,14 @@ describe("session delivery hook integration", () => {const tokens = { old: oldToken, replacement: replacementToken };for (const owner of order) {- await resumeHook(tokens[owner], {- kind: "deliver",- payloads: [{ message: owner }],- });+ await resumeHook(tokens[owner], { kind: "send", payload: { message: owner } });}disposal.release();- await withTimeout(disposal.finished, "old-hook disposal completion");+ await withTimeout(disposal.finished, "old-alias disposal completion");await expect(- resumeHook(oldToken, {- kind: "deliver",- payloads: [{ message: "too late" }],- }),+ resumeHook(oldToken, { kind: "send", payload: { message: "too late" } }),).rejects.toMatchObject({ name: "HookNotFoundError" });await expect(run.returnValue).resolves.toEqual(order);} finally {diff --git a/packages/eve/src/execution/session-command-inbox.test.ts b/packages/eve/src/execution/session-command-inbox.test.tsnew file mode 100644index 000000000..35d739bd0--- /dev/null+++ b/packages/eve/src/execution/session-command-inbox.test.ts@@ -0,0 +1,204 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import type { SessionInboxPayload } from "#execution/session-command-inbox.js";+import { createSessionCommandInbox } from "#execution/session-command-inbox.js";++const createHookMock = vi.fn();++vi.mock("#compiled/@workflow/core/index.js", () => ({+ createHook: (...args: unknown[]) => createHookMock(...args),+}));++describe("createSessionCommandInbox", () => {+ beforeEach(() => {+ createHookMock.mockReset();+ });++ it("multiplexes the stable session inbox and continuation alias", async () => {+ installHooks(+ createMockHook({ reads: [Promise.resolve(resolved(send("by id")))], token: "stable" }),+ createMockHook({+ reads: [Promise.resolve(resolved({ kind: "clear" }))],+ token: "channel",+ }),+ );+ const inbox = createSessionCommandInbox();++ await inbox.claimStable("stable");+ await inbox.rekeyContinuation("channel");++ await expect(inbox.next()).resolves.toEqual(resolved(send("by id")));+ inbox.consumeNext();+ await expect(inbox.next()).resolves.toEqual(resolved({ kind: "clear" }));+ inbox.consumeNext();+ await inbox.dispose();+ });++ it("retains a committed read from the previous alias across rekey", async () => {+ const oldRead = createDeferred<IteratorResult<SessionInboxPayload>>();+ const replacementRead = createDeferred<IteratorResult<SessionInboxPayload>>();+ const stable = createMockHook({ token: "stable" });+ const oldAlias = createMockHook({ reads: [oldRead.promise], token: "old" });+ const replacement = createMockHook({+ reads: [replacementRead.promise],+ token: "replacement",+ });+ installHooks(stable, oldAlias, replacement);+ const inbox = createSessionCommandInbox();++ await inbox.claimStable("stable");+ await inbox.rekeyContinuation("old");+ const pending = inbox.next();+ await inbox.rekeyContinuation("replacement");++ oldRead.resolve(resolved(send("old")));+ await expect(pending).resolves.toEqual(resolved(send("old")));+ inbox.consumeNext();++ replacementRead.resolve(resolved(send("replacement")));+ await expect(inbox.next()).resolves.toEqual(resolved(send("replacement")));+ inbox.consumeNext();+ await inbox.dispose();++ expect(stable.dispose).toHaveBeenCalledOnce();+ expect(oldAlias.dispose).toHaveBeenCalledOnce();+ expect(replacement.dispose).toHaveBeenCalledOnce();+ });++ it("adds a first continuation alias to an existing stable wait", async () => {+ installHooks(+ createMockHook({ token: "stable" }),+ createMockHook({+ reads: [Promise.resolve(resolved(send("anchored")))],+ token: "channel",+ }),+ );+ const inbox = createSessionCommandInbox();++ await inbox.claimStable("stable");+ const pending = inbox.next();+ await inbox.rekeyContinuation("channel");++ await expect(pending).resolves.toEqual(resolved(send("anchored")));+ inbox.consumeNext();+ await inbox.dispose();+ });++ it("disposes a conflicting continuation candidate without releasing current ownership", async () => {+ const stable = createMockHook({ token: "stable" });+ const current = createMockHook({ token: "current" });+ const candidate = createMockHook({+ conflict: { runId: "wrun_owner" },+ token: "candidate",+ });+ installHooks(stable, current, candidate);+ const inbox = createSessionCommandInbox();++ await inbox.claimStable("stable");+ await inbox.rekeyContinuation("current");+ await expect(inbox.rekeyContinuation("candidate")).rejects.toMatchObject({+ conflictingRunId: "wrun_owner",+ name: "HookConflictError",+ token: "candidate",+ });++ expect(candidate.dispose).toHaveBeenCalledOnce();+ expect(current.dispose).not.toHaveBeenCalled();+ await inbox.dispose();+ expect(current.dispose).toHaveBeenCalledOnce();+ });++ it("never permits the stable session token to change", async () => {+ const stable = createMockHook({ token: "stable" });+ installHooks(stable);+ const inbox = createSessionCommandInbox();++ await inbox.claimStable("stable");+ await inbox.claimStable("stable");+ await expect(inbox.claimStable("different")).rejects.toThrow(+ "A session command inbox cannot change its stable token.",+ );+ expect(createHookMock).toHaveBeenCalledOnce();+ await inbox.dispose();+ });++ it("disposes active hooks without closing pending iterators", async () => {+ const stable = createMockHook({ token: "stable" });+ const alias = createMockHook({ token: "channel" });+ installHooks(stable, alias);+ const inbox = createSessionCommandInbox();++ await inbox.claimStable("stable");+ await inbox.rekeyContinuation("channel");+ void inbox.next();+ await inbox.dispose();+ await inbox.dispose();++ expect(stable.dispose).toHaveBeenCalledOnce();+ expect(alias.dispose).toHaveBeenCalledOnce();+ expect(stable.return).not.toHaveBeenCalled();+ expect(alias.return).not.toHaveBeenCalled();+ });+});++interface MockHook {+ readonly dispose: ReturnType<typeof vi.fn>;+ readonly hook: unknown;+ readonly return: ReturnType<typeof vi.fn>;+ readonly token: string;+}++function createMockHook(input: {+ readonly conflict?: { readonly runId: string } | null;+ readonly reads?: readonly Promise<IteratorResult<SessionInboxPayload>>[];+ readonly token: string;+}): MockHook {+ const reads = [...(input.reads ?? [])];+ const dispose = vi.fn();+ const iteratorReturn = vi.fn(async () => ({ done: true, value: undefined }) as const);+ const hook = Object.assign(new Promise<SessionInboxPayload>(() => {}), {+ [Symbol.asyncIterator]() {+ return {+ next: vi.fn(+ () =>+ reads.shift() ??+ new Promise<IteratorResult<SessionInboxPayload>>(() => {+ // Intentionally pending.+ }),+ ),+ return: iteratorReturn,+ };+ },+ dispose,+ getConflict: vi.fn(async () => input.conflict ?? null),+ token: input.token,+ });+ return { dispose, hook, return: iteratorReturn, token: input.token };+}++function installHooks(...hooks: readonly MockHook[]): void {+ const queue = [...hooks];+ createHookMock.mockImplementation((options: { readonly token: string }) => {+ const hook = queue.shift();+ if (hook === undefined || hook.token !== options.token) {+ throw new Error(`Unexpected hook token "${options.token}".`);+ }+ return hook.hook;+ });+}++function send(message: string): SessionInboxPayload {+ return { kind: "send", payload: { message } };+}++function resolved(value: SessionInboxPayload): IteratorResult<SessionInboxPayload> {+ return { done: false, value };+}++function createDeferred<T>(): { readonly promise: Promise<T>; resolve(value: T): void } {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((next) => {+ resolve = next;+ });+ return { promise, resolve };+}diff --git a/packages/eve/src/execution/session-command-inbox.ts b/packages/eve/src/execution/session-command-inbox.tsnew file mode 100644index 000000000..a17a0e35b--- /dev/null+++ b/packages/eve/src/execution/session-command-inbox.ts@@ -0,0 +1,209 @@+import { createHook, type Hook } from "#compiled/@workflow/core/index.js";++import type { SessionCommand, SessionTimeoutHookPayload } from "#channel/types.js";+import { claimHookOwnership, disposeHook } from "#execution/hook-ownership.js";++/** Payloads accepted by a session driver's stable and channel command aliases. */+export type SessionInboxPayload = SessionCommand | SessionTimeoutHookPayload;++interface HookRead {+ readonly order: number;+ readonly result: IteratorResult<SessionInboxPayload>;+ readonly state: SessionCommandHookState;+}++interface SessionCommandHookState {+ readonly hook: Hook<SessionInboxPayload>;+ readonly iterator: AsyncIterator<SessionInboxPayload>;+ closed: boolean;+ enabled: boolean;+ pending: boolean;+ retired: boolean;+ resolved?: HookRead;+}++/** Multiplexes one stable session hook and one rekeyable channel alias. */+export interface SessionCommandInbox {+ claimStable(token: string): Promise<void>;+ consumeNext(): void;+ next(): Promise<IteratorResult<SessionInboxPayload>>;+ rekeyContinuation(token: string): Promise<void>;+}++/** Adds workflow-entry lifecycle ownership to a session command inbox. */+export interface SessionCommandInboxHandle extends SessionCommandInbox {+ dispose(): Promise<void>;+}++/**+ * Creates the command inbox owned by one session driver.+ *+ * The stable hook is retained for the session's lifetime. Rekeying replaces+ * only the channel alias. Reads already committed to a retired alias remain in+ * the multiplexed queue and are consumed exactly once.+ */+export function createSessionCommandInbox(): SessionCommandInboxHandle {+ let stable: SessionCommandHookState | undefined;+ let continuation: SessionCommandHookState | undefined;+ const retired: SessionCommandHookState[] = [];+ const ready: HookRead[] = [];+ let nextOrder = 0;+ let offered: Promise<IteratorResult<SessionInboxPayload>> | null = null;+ let offeredRead: HookRead | undefined;+ let wake: (() => void) | undefined;++ const enqueue = (read: HookRead): void => {+ ready.push(read);+ ready.sort((left, right) => left.order - right.order);+ wake?.();+ wake = undefined;+ };++ const arm = (state: SessionCommandHookState): void => {+ if (state.closed || state.pending) return;++ state.pending = true;+ state.resolved = undefined;+ const next = state.retired+ ? Promise.resolve(state.hook).then(+ (value): IteratorResult<SessionInboxPayload> => ({ done: false, value }),+ )+ : state.iterator.next();+ void next.then(+ (result) => {+ const read: HookRead = { order: nextOrder++, result, state };+ state.resolved = read;+ if (state.enabled) enqueue(read);+ },+ () => {+ // Retired hooks reject after their committed payloads are exhausted.+ },+ );+ };++ const enable = (state: SessionCommandHookState): void => {+ state.enabled = true;+ if (state.resolved !== undefined) enqueue(state.resolved);+ };++ const createState = (token: string): SessionCommandHookState => {+ const hook = createHook<SessionInboxPayload>({ token });+ return {+ closed: false,+ enabled: false,+ hook,+ iterator: hook[Symbol.asyncIterator](),+ pending: false,+ retired: false,+ };+ };++ const states = (): readonly SessionCommandHookState[] =>+ [stable, continuation, ...retired].filter(+ (state): state is SessionCommandHookState => state !== undefined,+ );++ return {+ async claimStable(token: string): Promise<void> {+ if (stable !== undefined) {+ if (stable.hook.token === token) return;+ throw new Error("A session command inbox cannot change its stable token.");+ }++ const candidate = createState(token);+ await claimHookOwnership(candidate.hook);+ enable(candidate);+ stable = candidate;+ },++ consumeNext(): void {+ if (offeredRead === undefined) {+ throw new Error("Cannot consume a session command before it resolves.");+ }++ offeredRead.state.pending = false;+ offeredRead.state.resolved = undefined;+ if (offeredRead.result.done) offeredRead.state.closed = true;+ offeredRead = undefined;+ offered = null;+ },++ async dispose(): Promise<void> {+ const active = [continuation, stable].filter(+ (state): state is SessionCommandHookState => state !== undefined,+ );+ continuation = undefined;+ stable = undefined;+ await Promise.all(active.map(async (state) => await disposeHook(state.hook)));+ },++ next(): Promise<IteratorResult<SessionInboxPayload>> {+ if (stable === undefined) {+ throw new Error("Cannot wait for session commands before claiming the stable inbox.");+ }++ if (offered !== null) return offered;++ const current = states();+ for (const state of current) arm(state);++ if (current.every((state) => state.closed)) {+ offeredRead = {+ order: nextOrder++,+ result: { done: true, value: undefined },+ state: stable,+ };+ offered = Promise.resolve(offeredRead.result);+ return offered;+ }++ offered = (async () => {+ while (ready.length === 0) {+ await new Promise<void>((resolve) => {+ wake = resolve;+ });+ }++ const read = ready.shift()!;+ offeredRead = read;+ return read.result;+ })();+ return offered;+ },++ async rekeyContinuation(token: string): Promise<void> {+ if (!token || continuation?.hook.token === token) return;++ const candidate = createState(token);+ if (continuation === undefined) {+ await claimHookOwnership(candidate.hook);+ enable(candidate);+ continuation = candidate;+ if (offered !== null) arm(candidate);+ return;+ }++ arm(candidate);+ await claimHookOwnership(candidate.hook);+ enable(candidate);++ const previous = continuation;+ continuation = candidate;+ arm(previous);+ try {+ await disposeHook(previous.hook);+ } catch (error) {+ continuation = undefined;+ try {+ await disposeHook(candidate.hook);+ } catch {+ // The previous-alias release failure is authoritative.+ }+ throw error;+ }++ previous.retired = true;+ retired.push(previous);+ },+ };+}diff --git a/packages/eve/src/execution/session-command-token.ts b/packages/eve/src/execution/session-command-token.tsnew file mode 100644index 000000000..5f700d8b0--- /dev/null+++ b/packages/eve/src/execution/session-command-token.ts@@ -0,0 +1,6 @@+const SESSION_COMMAND_NAMESPACE = "eve:session";++/** Derives the framework-reserved stable command inbox token for a session. */+export function sessionCommandHookToken(sessionId: string): string {+ return `${SESSION_COMMAND_NAMESPACE}:${sessionId}:inbox`;+}diff --git a/packages/eve/src/execution/session-delivery-hook.test.ts b/packages/eve/src/execution/session-delivery-hook.test.tsdeleted file mode 100644index f78300019..000000000--- a/packages/eve/src/execution/session-delivery-hook.test.ts+++ /dev/null@@ -1,317 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--import type { DeliverHookPayload, HookPayload } from "#channel/types.js";-import { createSessionDeliveryHook } from "#execution/session-delivery-hook.js";--const createHookMock = vi.fn();--vi.mock("#compiled/@workflow/core/index.js", () => ({- createHook: (...args: unknown[]) => createHookMock(...args),-}));--describe("createSessionDeliveryHook", () => {- beforeEach(() => {- createHookMock.mockReset();- });-- it("retains pending reads from both hooks across rekey", async () => {- const oldRead = createDeferred<IteratorResult<HookPayload>>();- const replacementRead = createDeferred<IteratorResult<HookPayload>>();- const oldHook = createMockHook({ reads: [oldRead.promise], token: "old" });- const replacementHook = createMockHook({- reads: [replacementRead.promise],- token: "replacement",- });- installHooks(oldHook, replacementHook);- const deliveryHook = createSessionDeliveryHook([]);-- await deliveryHook.rekey("old");- const pending = deliveryHook.next();- await deliveryHook.rekey("replacement");-- oldRead.resolve(delivery("old"));- await expect(pending).resolves.toEqual(delivery("old"));- deliveryHook.consumeNext();-- replacementRead.resolve(delivery("replacement"));- await expect(deliveryHook.next()).resolves.toEqual(delivery("replacement"));- deliveryHook.consumeNext();- await deliveryHook.dispose();-- expect(oldHook.dispose).toHaveBeenCalledOnce();- expect(replacementHook.dispose).toHaveBeenCalledOnce();- });-- it("appends drained rekey deliveries after existing buffered deliveries", async () => {- const bufferedDeliveries = [deliveryPayload("existing")];- const oldHook = createMockHook({- reads: [Promise.resolve(delivery("old"))],- token: "old",- });- const replacementHook = createMockHook({- reads: [Promise.resolve(delivery("replacement"))],- token: "replacement",- });- installHooks(oldHook, replacementHook);- const deliveryHook = createSessionDeliveryHook(bufferedDeliveries);-- await deliveryHook.rekey("old");- await deliveryHook.rekey("replacement");- await deliveryHook.dispose();-- expect(bufferedDeliveries).toEqual([- deliveryPayload("existing"),- deliveryPayload("old"),- deliveryPayload("replacement"),- ]);- });-- it("latches a timeout consumed while an active turn owns delivery reads", async () => {- const hook = createMockHook({- reads: [Promise.resolve(sessionTimeout())],- token: "active",- });- installHooks(hook);- const deliveryHook = createSessionDeliveryHook([]);-- await deliveryHook.rekey("active");- await expect(deliveryHook.next()).resolves.toEqual(sessionTimeout());- deliveryHook.consumeNext();-- expect(deliveryHook.consumeSessionTimeout()).toBe(true);- expect(deliveryHook.consumeSessionTimeout()).toBe(false);- await deliveryHook.dispose();- });-- it("latches a timeout drained from a retired hook during rekey", async () => {- const oldHook = createMockHook({- reads: [Promise.resolve(sessionTimeout())],- token: "old",- });- const replacementHook = createMockHook({ token: "replacement" });- installHooks(oldHook, replacementHook);- const deliveryHook = createSessionDeliveryHook([]);-- await deliveryHook.rekey("old");- await deliveryHook.rekey("replacement");-- expect(deliveryHook.consumeSessionTimeout()).toBe(true);- await deliveryHook.dispose();- });-- it("latches compaction requests consumed while a turn owns delivery reads", async () => {- const hook = createMockHook({ reads: [Promise.resolve(compact())], token: "active" });- installHooks(hook);- const deliveryHook = createSessionDeliveryHook([]);-- await deliveryHook.rekey("active");- await expect(deliveryHook.next()).resolves.toEqual(compact());- deliveryHook.consumeNext();-- expect(deliveryHook.consumeSessionControl()).toBe("compact");- expect(deliveryHook.consumeSessionControl()).toBeUndefined();- await deliveryHook.dispose();- });-- it("latches clear requests consumed while a turn owns delivery reads", async () => {- const hook = createMockHook({ reads: [Promise.resolve(clear())], token: "active" });- installHooks(hook);- const deliveryHook = createSessionDeliveryHook([]);-- await deliveryHook.rekey("active");- await expect(deliveryHook.next()).resolves.toEqual(clear());- deliveryHook.consumeNext();-- expect(deliveryHook.consumeSessionControl()).toBe("clear");- expect(deliveryHook.consumeSessionControl()).toBeUndefined();- await deliveryHook.dispose();- });-- it("disposes a conflicting candidate without releasing the active hook", async () => {- const oldHook = createMockHook({ token: "old" });- const candidateHook = createMockHook({- conflict: { runId: "wrun_owner" },- token: "candidate",- });- installHooks(oldHook, candidateHook);- const deliveryHook = createSessionDeliveryHook([]);-- await deliveryHook.rekey("old");- await expect(deliveryHook.rekey("candidate")).rejects.toMatchObject({- name: "HookConflictError",- token: "candidate",- });-- expect(candidateHook.dispose).toHaveBeenCalledOnce();- expect(oldHook.dispose).not.toHaveBeenCalled();-- await deliveryHook.dispose();- expect(oldHook.dispose).toHaveBeenCalledOnce();- });-- it("preserves an old-hook disposal failure while cleaning the candidate", async () => {- const failure = new Error("old hook disposal failed");- const oldHook = createMockHook({- dispose: vi.fn(async () => {- throw failure;- }),- token: "old",- });- const candidateHook = createMockHook({ token: "candidate" });- installHooks(oldHook, candidateHook);- const deliveryHook = createSessionDeliveryHook([]);-- await deliveryHook.rekey("old");- await expect(deliveryHook.rekey("candidate")).rejects.toBe(failure);-- expect(oldHook.dispose).toHaveBeenCalledOnce();- expect(candidateHook.dispose).toHaveBeenCalledOnce();- });-- it("drains a committed delivery once and tolerates the retired hook re-arm rejecting", async () => {- // The old hook commits exactly one delivery before disposal (captured by- // the armed iterator read). Re-arming the retired hook awaits the exhausted- // cursor, which rejects; the delivery must surface exactly once and the- // rejection must not throw or resurrect it across later drain cycles.- const bufferedDeliveries: DeliverHookPayload[] = [];- installHooks(- createCursorHook({ committed: [deliveryPayload("old")], token: "old" }),- createCursorHook({ committed: [], token: "replacement" }),- createCursorHook({ committed: [], token: "third" }),- );- const deliveryHook = createSessionDeliveryHook(bufferedDeliveries);-- await deliveryHook.rekey("old");- await deliveryHook.rekey("replacement");- // A further rekey forces extra drain cycles that would surface a duplicate- // if a retired re-arm re-yielded the already-consumed payload.- await deliveryHook.rekey("third");- await deliveryHook.dispose();-- expect(bufferedDeliveries).toEqual([deliveryPayload("old")]);- });-- it("disposes without closing or settling a pending read", async () => {- const hook = createMockHook({ token: "active" });- installHooks(hook);- const deliveryHook = createSessionDeliveryHook([]);-- await deliveryHook.rekey("active");- void deliveryHook.next();- await deliveryHook.dispose();-- expect(hook.dispose).toHaveBeenCalledOnce();- expect(hook.return).not.toHaveBeenCalled();- });-});--interface MockHook {- readonly dispose: ReturnType<typeof vi.fn>;- readonly hook: unknown;- readonly return: ReturnType<typeof vi.fn>;- readonly token: string;-}--function createMockHook(input: {- readonly conflict?: { readonly runId: string } | null;- readonly dispose?: ReturnType<typeof vi.fn>;- readonly reads?: readonly Promise<IteratorResult<HookPayload>>[];- readonly token: string;-}): MockHook {- const reads = [...(input.reads ?? [])];- const dispose = input.dispose ?? vi.fn();- const getConflict = vi.fn(async () => input.conflict ?? null);- const next = vi.fn(- () =>- reads.shift() ??- new Promise<IteratorResult<HookPayload>>(() => {- // Intentionally pending.- }),- );- const iteratorReturn = vi.fn(async () => ({ done: true, value: undefined }) as const);- const hook = Object.assign(new Promise<HookPayload>(() => {}), {- [Symbol.asyncIterator]() {- return { next, return: iteratorReturn };- },- dispose,- getConflict,- token: input.token,- });- return { dispose, hook, return: iteratorReturn, token: input.token };-}--/**- * Builds a hook whose `await hook` and async iterator share one delivery- * cursor: each read advances a queue of committed payloads, and awaiting an- * exhausted cursor rejects with a `HookNotFoundError` — the contract the- * retired-hook re-arm in `session-delivery-hook` relies on.- */-function createCursorHook(input: {- readonly committed: readonly HookPayload[];- readonly token: string;-}): MockHook {- const queue: IteratorResult<HookPayload>[] = input.committed.map((value) => ({- done: false,- value,- }));- const pull = (): IteratorResult<HookPayload> => queue.shift() ?? { done: true, value: undefined };- const dispose = vi.fn();- const iteratorReturn = vi.fn(async () => ({ done: true, value: undefined }) as const);- const hook = {- [Symbol.asyncIterator]() {- return { next: vi.fn(async () => pull()), return: iteratorReturn };- },- dispose,- getConflict: vi.fn(async () => null),- // eslint-disable-next-line unicorn/no-thenable -- a Workflow Hook is itself a thenable- then<T>(onFulfilled: (value: HookPayload) => T, onRejected?: (reason: unknown) => T) {- const item = queue.shift();- const settled =- item === undefined- ? Promise.reject(Object.assign(new Error("hook disposed"), { name: "HookNotFoundError" }))- : Promise.resolve(item.value);- return settled.then(onFulfilled, onRejected);- },- token: input.token,- };- return { dispose, hook, return: iteratorReturn, token: input.token };-}--function installHooks(...hooks: readonly MockHook[]): void {- const queue = [...hooks];- createHookMock.mockImplementation((options: { readonly token: string }) => {- const hook = queue.shift();- if (hook === undefined || hook.token !== options.token) {- throw new Error(`Unexpected hook token "${options.token}".`);- }- return hook.hook;- });-}--function delivery(message: string): IteratorResult<HookPayload> {- return { done: false, value: deliveryPayload(message) };-}--function deliveryPayload(message: string): DeliverHookPayload {- return { kind: "deliver", payloads: [{ message }] };-}--function sessionTimeout(): IteratorResult<HookPayload> {- return { done: false, value: { kind: "session-timeout" } };-}--function compact(): IteratorResult<HookPayload> {- return { done: false, value: { kind: "compact" } };-}--function clear(): IteratorResult<HookPayload> {- return { done: false, value: { kind: "clear" } };-}--function createDeferred<T>(): { readonly promise: Promise<T>; resolve(value: T): void } {- let resolve!: (value: T) => void;- const promise = new Promise<T>((next) => {- resolve = next;- });- return { promise, resolve };-}diff --git a/packages/eve/src/execution/session-delivery-hook.ts b/packages/eve/src/execution/session-delivery-hook.tsdeleted file mode 100644index c89885237..000000000--- a/packages/eve/src/execution/session-delivery-hook.ts+++ /dev/null@@ -1,257 +0,0 @@-import { createHook, type Hook } from "#compiled/@workflow/core/index.js";--import type { DeliverHookPayload, HookPayload } from "#channel/types.js";-import { claimHookOwnership, disposeHook } from "#execution/hook-ownership.js";--interface HookRead {- readonly order: number;- readonly result: IteratorResult<HookPayload>;- readonly state: SessionDeliveryHookState;-}--interface SessionDeliveryHookState {- readonly hook: Hook<HookPayload>;- readonly iterator: AsyncIterator<HookPayload>;- closed: boolean;- enabled: boolean;- pending: boolean;- retired: boolean;- resolved?: HookRead;-}--/** Reads and rekeys the public delivery hook for one session driver. */-export interface SessionDeliveryHook {- consumeSessionControl(): "clear" | "compact" | undefined;- consumeNext(): void;- consumeSessionTimeout(): boolean;- next(): Promise<IteratorResult<HookPayload>>;- rekey(token: string): Promise<void>;-}--/** Adds workflow-entry lifecycle ownership to a session delivery hook. */-export interface SessionDeliveryHookHandle extends SessionDeliveryHook {- dispose(): Promise<void>;-}--/**- * Creates the public delivery hook used by `workflowEntry`.- *- * Retired hooks are disposed immediately, but their already-armed reads stay- * in the logical hook's delivery race. A delivery that committed before disposal can- * therefore still resolve on replay; a later delivery loses the storage race- * to `hook_disposed` and receives `HookNotFoundError` from the Workflow SDK.- */-export function createSessionDeliveryHook(- bufferedDeliveries: DeliverHookPayload[],-): SessionDeliveryHookHandle {- let active: SessionDeliveryHookState | undefined;- const retired: SessionDeliveryHookState[] = [];- const ready: HookRead[] = [];- let nextOrder = 0;- let offered: Promise<IteratorResult<HookPayload>> | null = null;- let offeredRead: HookRead | undefined;- let sessionTimedOut = false;- const pendingSessionControls = new Set<"clear" | "compact">();- let wake: (() => void) | undefined;-- const enqueue = (read: HookRead): void => {- ready.push(read);- ready.sort((left, right) => left.order - right.order);- wake?.();- wake = undefined;- };-- const arm = (state: SessionDeliveryHookState): void => {- if (state.closed || state.pending) return;-- state.pending = true;- state.resolved = undefined;- // A retired hook is disposed, so its iterator can no longer be advanced;- // awaiting the hook itself surfaces the next payload that committed to the- // token before disposal. `await hook` and the iterator share one delivery- // cursor, so a payload already drained via the iterator is never re-yielded,- // and once the committed payloads are exhausted the read rejects (swallowed- // below) instead of resolving again. Re-arming a retired hook is therefore- // safe: it cannot double-count or resurrect a delivery.- const next = state.retired- ? Promise.resolve(state.hook).then(- (value): IteratorResult<HookPayload> => ({ done: false, value }),- )- : state.iterator.next();- void next.then(- (result) => {- const read: HookRead = {- order: nextOrder++,- result,- state,- };- state.resolved = read;- if (state.enabled) enqueue(read);- },- () => {- // `claimHookOwnership` owns candidate-claim errors, and an active hook- // read cannot reject under the public delivery contract. A retired hook- // read rejects once its committed payloads are exhausted; dropping it- // here leaves the retired state quiescent (pending, never re-enqueued).- },- );- };-- const enable = (state: SessionDeliveryHookState): void => {- state.enabled = true;- if (state.resolved !== undefined) enqueue(state.resolved);- };-- const drainReady = async (): Promise<void> => {- // A caller may already be racing this read against turn control. Leave- // that promise intact: the losing race ignores it, and the next call to- // `next()` reuses it without duplicating the delivery.- if (offered !== null) return;-- await Promise.resolve();-- while (ready.length > 0) {- const read = ready.shift()!;- read.state.pending = false;- read.state.resolved = undefined;-- if (read.result.done) {- read.state.closed = true;- } else {- if (read.result.value.kind === "deliver") {- bufferedDeliveries.push(read.result.value);- } else if (read.result.value.kind === "session-timeout") {- sessionTimedOut = true;- } else if (read.result.value.kind === "clear" || read.result.value.kind === "compact") {- pendingSessionControls.add(read.result.value.kind);- }- }-- arm(read.state);- await Promise.resolve();- }- };-- return {- consumeSessionControl(): "clear" | "compact" | undefined {- for (const control of pendingSessionControls) {- pendingSessionControls.delete(control);- return control;- }- return undefined;- },-- consumeNext(): void {- if (offeredRead === undefined) {- throw new Error("Cannot consume a public delivery before it resolves.");- }-- if (!offeredRead.result.done && offeredRead.result.value.kind === "session-timeout") {- sessionTimedOut = true;- }- if (- !offeredRead.result.done &&- (offeredRead.result.value.kind === "clear" || offeredRead.result.value.kind === "compact")- ) {- pendingSessionControls.add(offeredRead.result.value.kind);- }- offeredRead.state.pending = false;- offeredRead.state.resolved = undefined;- if (offeredRead.result.done) offeredRead.state.closed = true;- offeredRead = undefined;- offered = null;- },-- consumeSessionTimeout(): boolean {- const timedOut = sessionTimedOut;- sessionTimedOut = false;- return timedOut;- },-- async dispose(): Promise<void> {- if (active !== undefined) {- await disposeHook(active.hook);- active = undefined;- }- },-- next(): Promise<IteratorResult<HookPayload>> {- if (active === undefined) {- throw new Error("Cannot wait for deliveries before a continuation token is available.");- }-- if (offered !== null) return offered;-- arm(active);- for (const state of retired) arm(state);-- if (active.closed && retired.every((state) => state.closed)) {- offeredRead = {- order: nextOrder++,- result: { done: true, value: undefined },- state: active,- };- offered = Promise.resolve(offeredRead.result);- return offered;- }-- offered = (async () => {- while (ready.length === 0) {- await new Promise<void>((resolve) => {- wake = resolve;- });- }-- const read = ready.shift()!;- offeredRead = read;- return read.result;- })();- return offered;- },-- async rekey(token: string): Promise<void> {- if (!token || active?.hook.token === token) return;-- const candidateHook = createHook<HookPayload>({ token });- const candidate: SessionDeliveryHookState = {- closed: false,- enabled: false,- hook: candidateHook,- iterator: candidateHook[Symbol.asyncIterator](),- pending: false,- retired: false,- };-- if (active === undefined) {- await claimHookOwnership(candidate.hook);- enable(candidate);- active = candidate;- return;- }-- const previous = active;- arm(previous);- arm(candidate);- await claimHookOwnership(candidate.hook);- enable(candidate);- await drainReady();-- try {- await disposeHook(previous.hook);- } catch (error) {- active = undefined;- try {- await disposeHook(candidate.hook);- } catch {- // The active hook release failure is authoritative.- }- throw error;- }-- previous.retired = true;- retired.push(previous);- active = candidate;- await drainReady();- },- };-}diff --git a/packages/eve/src/execution/session-limit-cancellation.integration.test.ts b/packages/eve/src/execution/session-limit-cancellation.integration.test.tsindex b829a427f..a5a9300c0 100644--- a/packages/eve/src/execution/session-limit-cancellation.integration.test.ts+++ b/packages/eve/src/execution/session-limit-cancellation.integration.test.ts@@ -44,10 +44,9 @@ function expectNoFailureEvents(events: readonly UnstampedMessageStreamEvent[]):}/**- * Delivers a payload to the session's delivery hook, retrying through the- * park boundary's dispose/recreate window. `waitForHook` cannot gate- * repeated deliveries on one token — it treats a hook that ever received a- * payload as consumed — so the retry is the barrier here.+ * Sends a command to the session inbox, retrying through its claim window.+ * `waitForHook` cannot gate repeated commands on one token — it treats a hook+ * that ever received a payload as consumed — so the retry is the barrier here.*/async function deliver(continuationToken: string,@@ -57,7 +56,7 @@ async function deliver(const deadline = Date.now() + timeout;while (true) {try {- await resumeHook(continuationToken, payload);+ await resumeHook(continuationToken, { auth: null, kind: "send", payload });return;} catch (error) {if (Date.now() > deadline) throw error;@@ -103,10 +102,7 @@ describe("session-limit continuation decline integration", () => {expectNoFailureEvents(firstTurn);// Turn 2 parks on the continuation prompt before any model call.- await deliver(continuationToken, {- kind: "deliver",- payloads: [{ message: "keep going please" }],- });+ await deliver(continuationToken, { message: "keep going please" });const promptTurn = await stream.nextTurn();expect(promptTurn.at(-1)?.type).toBe("session.waiting");const requestId = requestIdFromPromptTurn(promptTurn);@@ -114,8 +110,7 @@ describe("session-limit continuation decline integration", () => {// Declining settles the turn as cancelled — a user decision, not an// error, and not a session end.await deliver(continuationToken, {- kind: "deliver",- payloads: [{ inputResponses: [{ optionId: "stop", requestId }] }],+ inputResponses: [{ optionId: "stop", requestId }],});const declinedTurn = await stream.nextTurn();@@ -133,10 +128,7 @@ describe("session-limit continuation decline integration", () => {// The session stays over budget, so the next message re-raises the// prompt (fail-closed) instead of running a model call.- await deliver(continuationToken, {- kind: "deliver",- payloads: [{ message: "try again" }],- });+ await deliver(continuationToken, { message: "try again" });const repromptTurn = await stream.nextTurn();expect(repromptTurn.at(-1)?.type).toBe("session.waiting");@@ -192,8 +184,7 @@ describe("session-limit continuation decline integration", () => {// show: the turn settles as cancelled and the session stays// resumable -- same contract as the direct-decline case above.await deliver(continuationToken, {- kind: "deliver",- payloads: [{ inputResponses: [{ optionId: "stop", requestId }] }],+ inputResponses: [{ optionId: "stop", requestId }],});const declinedTurn = await stream.nextTurn();expect(declinedTurn.at(-1)?.type).toBe("session.waiting");@@ -205,10 +196,7 @@ describe("session-limit continuation decline integration", () => {// The session accepts the next message; the root is still over// budget, so it re-raises its own prompt (fail-closed) instead of// running a model call or re-dispatching the delegation.- await deliver(continuationToken, {- kind: "deliver",- payloads: [{ message: "follow up after decline" }],- });+ await deliver(continuationToken, { message: "follow up after decline" });const followUpTurn = await stream.nextTurn();expect(followUpTurn.at(-1)?.type).toBe("session.waiting");diff --git a/packages/eve/src/execution/session-reset.integration.test.ts b/packages/eve/src/execution/session-reset.integration.test.tsindex 2369f8687..4a99f0c02 100644--- a/packages/eve/src/execution/session-reset.integration.test.ts+++ b/packages/eve/src/execution/session-reset.integration.test.ts@@ -4,10 +4,10 @@ import { ContextContainer, contextStorage } from "#context/container.js";import { SessionKey } from "#context/keys.js";import { ensureSandboxAccess } from "#execution/sandbox/ensure.js";import { clearActiveSandboxHandlesForTest } from "#execution/sandbox/active-handles.js";-import { sessionDeliveryHookWorkflow } from "#internal/testing/session-delivery-hook-workflow.js";+import { sessionCommandInboxWorkflow } from "#internal/testing/session-command-inbox-workflow.js";import { waitForHook } from "#internal/testing/workflow-test-helpers.js";import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";-import { getWorld, start } from "#internal/workflow/runtime.js";+import { start } from "#internal/workflow/runtime.js";import { createWorkflowRuntime } from "#execution/workflow-runtime.js";import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";@@ -22,31 +22,28 @@ describe("session reset integration", () => {compiledArtifactsSource: {} as RuntimeCompiledArtifactsSource,});const sandboxes = createSessionSandboxHarness();- const first = await start(sessionDeliveryHookWorkflow, [- { nextToken: continuationToken, token: "http:session-reset-placeholder-1" },- ]);+ const first = await start(sessionCommandInboxWorkflow, [{ token: continuationToken }]);try {await waitForHook(first, { token: continuationToken });await expect(sandboxes.open(first.runId)).resolves.toMatchObject({ id: "sandbox-1" });await expect(- runtime.terminateSession({ reason: "User requested /new", sessionId: first.runId }),- ).resolves.toEqual({ status: "terminated" });+ runtime.dispatchContinuation({+ command: { kind: "reset", reason: "User requested /new" },+ continuationToken,+ }),+ ).resolves.toEqual({ previousSessionId: first.runId, status: "reset" });- await expect(runtime.resolveSession(continuationToken)).resolves.toBeUndefined();- await expect(getWorld().then((world) => world.runs.get(first.runId))).resolves.toMatchObject({- status: "cancelled",- });+ await expect(first.returnValue).resolves.toEqual([]);+ await expect(runtime.resolveContinuation(continuationToken)).resolves.toBeUndefined();- const second = await start(sessionDeliveryHookWorkflow, [- { nextToken: continuationToken, token: "http:session-reset-placeholder-2" },- ]);+ const second = await start(sessionCommandInboxWorkflow, [{ token: continuationToken }]);try {await expect(waitForHook(second, { token: continuationToken })).resolves.toMatchObject({runId: second.runId,});- await expect(runtime.resolveSession(continuationToken)).resolves.toEqual({+ await expect(runtime.resolveContinuation(continuationToken)).resolves.toEqual({sessionId: second.runId,});await expect(sandboxes.open(second.runId)).resolves.toMatchObject({ id: "sandbox-2" });@@ -57,7 +54,8 @@ describe("session reset integration", () => {await second.cancel();}} finally {- await first.cancel();+ const status = await first.status;+ if (status === "pending" || status === "running") await first.cancel();clearActiveSandboxHandlesForTest();}});diff --git a/packages/eve/src/execution/session-timeout-control.test.ts b/packages/eve/src/execution/session-timeout-control.test.tsindex c2bac578e..74f250e36 100644--- a/packages/eve/src/execution/session-timeout-control.test.ts+++ b/packages/eve/src/execution/session-timeout-control.test.ts@@ -16,39 +16,32 @@ afterEach(() => {});describe("createSessionTimeoutControl", () => {- it("retargets one absolute deadline when the delivery hook is rekeyed", async () => {+ it("starts one absolute deadline against the stable command inbox", async () => {const deadline = new Date("2026-02-01T00:00:00.000Z");- vi.mocked(startSessionTimeoutStep)- .mockResolvedValueOnce({ runId: "timer-old" })- .mockResolvedValueOnce({ runId: "timer-new" });- const control = createSessionTimeoutControl({ deadline });-- await control.rekey("old");- await control.rekey("old");- await control.rekey("replacement");+ vi.mocked(startSessionTimeoutStep).mockResolvedValue({ runId: "timer-run" });- expect(startSessionTimeoutStep).toHaveBeenNthCalledWith(1, {+ const control = createSessionTimeoutControl({deadline,- token: "old",+ token: "eve:session:wrun_1:inbox",});- expect(startSessionTimeoutStep).toHaveBeenNthCalledWith(2, {+ await control.start();+ await control.start();++ expect(startSessionTimeoutStep).toHaveBeenCalledOnce();+ expect(startSessionTimeoutStep).toHaveBeenCalledWith({deadline,- token: "replacement",+ token: "eve:session:wrun_1:inbox",});- expect(cancelSessionTimeoutStep).toHaveBeenCalledOnce();- expect(cancelSessionTimeoutStep).toHaveBeenCalledWith({ runId: "timer-old" });- expect(vi.mocked(cancelSessionTimeoutStep).mock.invocationCallOrder[0]).toBeLessThan(- vi.mocked(startSessionTimeoutStep).mock.invocationCallOrder[1]!,- );});it("cancels the active timer when the session settles", async () => {vi.mocked(startSessionTimeoutStep).mockResolvedValue({ runId: "timer-run" });const control = createSessionTimeoutControl({deadline: new Date("2026-02-01T00:00:00.000Z"),+ token: "eve:session:wrun_1:inbox",});- await control.rekey("active");+ await control.start();await control.dispose();await control.dispose();@@ -56,26 +49,16 @@ describe("createSessionTimeoutControl", () => {expect(cancelSessionTimeoutStep).toHaveBeenCalledWith({ runId: "timer-run" });});- it("does not start a timer without a continuation token", async () => {- const control = createSessionTimeoutControl({- deadline: new Date("2026-02-01T00:00:00.000Z"),- });-- await control.rekey("");- await control.dispose();-- expect(startSessionTimeoutStep).not.toHaveBeenCalled();- expect(cancelSessionTimeoutStep).not.toHaveBeenCalled();- });-it("propagates timer startup failures", async () => {const failure = new Error("timer startup failed");vi.mocked(startSessionTimeoutStep).mockRejectedValue(failure);+const control = createSessionTimeoutControl({deadline: new Date("2026-02-01T00:00:00.000Z"),+ token: "eve:session:wrun_1:inbox",});- await expect(control.rekey("active")).rejects.toBe(failure);+ await expect(control.start()).rejects.toBe(failure);await control.dispose();expect(cancelSessionTimeoutStep).not.toHaveBeenCalled();diff --git a/packages/eve/src/execution/session-timeout-control.ts b/packages/eve/src/execution/session-timeout-control.tsindex fc3b2784c..54445de91 100644--- a/packages/eve/src/execution/session-timeout-control.ts+++ b/packages/eve/src/execution/session-timeout-control.ts@@ -3,17 +3,18 @@ import {startSessionTimeoutStep,} from "#execution/session-timeout-steps.js";-/** Workflow-body handle that targets a durable deadline at the active delivery hook. */+/** Workflow-body handle that targets a durable deadline at the stable command inbox. */export interface SessionTimeoutControl {dispose(): Promise<void>;- rekey(token: string): Promise<void>;+ start(): Promise<void>;}-/** Creates a timer controller that preserves one absolute session deadline across hook rekeys. */+/** Creates a timer controller for one stable session command inbox. */export function createSessionTimeoutControl(input: {readonly deadline: Date;+ readonly token: string;}): SessionTimeoutControl {- let active: { readonly runId: string; readonly token: string } | undefined;+ let active: { readonly runId: string } | undefined;return {async dispose(): Promise<void> {@@ -23,18 +24,9 @@ export function createSessionTimeoutControl(input: {await cancelSessionTimeoutStep({ runId: current.runId });},- async rekey(token: string): Promise<void> {- if (!token || active?.token === token) return;-- if (active !== undefined) {- await cancelSessionTimeoutStep({ runId: active.runId });- }-- const { runId } = await startSessionTimeoutStep({- deadline: input.deadline,- token,- });- active = { runId, token };+ async start(): Promise<void> {+ if (active !== undefined) return;+ active = await startSessionTimeoutStep(input);},};}diff --git a/packages/eve/src/execution/turn-cancellation-control.test.ts b/packages/eve/src/execution/turn-cancellation-control.test.tsindex 731b53fd1..03d8bd784 100644--- a/packages/eve/src/execution/turn-cancellation-control.test.ts+++ b/packages/eve/src/execution/turn-cancellation-control.test.ts@@ -1,7 +1,7 @@import { afterEach, describe, expect, it, vi } from "vitest";import { createTurnCancellationControl } from "#execution/turn-cancellation-control.js";-import { sessionCancelHookToken } from "#execution/turn-cancellation-token.js";+import { turnCancellationHookToken } from "#execution/turn-cancellation-token.js";import { TurnCancelledError } from "#harness/turn-cancellation.js";const createHookMock = vi.fn();@@ -42,9 +42,11 @@ async function settles(promise: Promise<unknown>): Promise<boolean> {]);}-describe("sessionCancelHookToken", () => {- it("derives the stable token from the session id", () => {- expect(sessionCancelHookToken("wrun_abc")).toBe("wrun_abc:cancel");+describe("turnCancellationHookToken", () => {+ it("derives a private token from the turn control token", () => {+ expect(turnCancellationHookToken("wrun_abc:turn-control:1")).toBe(+ "wrun_abc:turn-control:1:cancel",+ );});});@@ -57,8 +59,8 @@ describe("createTurnCancellationControl", () => {installCancelHook({ conflict: { runId: "wrun_stale" } });const control = await createTurnCancellationControl({+ controlToken: "session-1",expectedTurnId: "turn_0",- sessionId: "session-1",});expect(control).toBeUndefined();@@ -68,8 +70,8 @@ describe("createTurnCancellationControl", () => {installCancelHook({ payloads: [{}] });const control = await createTurnCancellationControl({+ controlToken: "session-1",expectedTurnId: "turn_0",- sessionId: "session-1",});await expect(control!.requested).resolves.toBe("cancel");@@ -81,8 +83,8 @@ describe("createTurnCancellationControl", () => {installCancelHook({ payloads: [{ turnId: "turn_2" }] });const control = await createTurnCancellationControl({+ controlToken: "session-1",expectedTurnId: "turn_2",- sessionId: "session-1",});await expect(control!.requested).resolves.toBe("cancel");@@ -93,8 +95,8 @@ describe("createTurnCancellationControl", () => {installCancelHook({ payloads: [{ turnId: "turn_99" }, { turnId: "turn_2" }] });const control = await createTurnCancellationControl({+ controlToken: "session-1",expectedTurnId: "turn_2",- sessionId: "session-1",});await expect(control!.requested).resolves.toBe("cancel");@@ -105,8 +107,8 @@ describe("createTurnCancellationControl", () => {installCancelHook({ payloads: [{ turnId: "turn_99" }] });const control = await createTurnCancellationControl({+ controlToken: "session-1",expectedTurnId: "turn_2",- sessionId: "session-1",});expect(await settles(control!.requested)).toBe(false);@@ -139,8 +141,8 @@ describe("createTurnCancellationControl", () => {});const control = await createTurnCancellationControl({+ controlToken: "session-1",expectedTurnId: "turn_0",- sessionId: "session-1",});let releaseStep!: () => void;@@ -161,8 +163,8 @@ describe("createTurnCancellationControl", () => {const { dispose } = installCancelHook({});const control = await createTurnCancellationControl({+ controlToken: "session-1",expectedTurnId: "turn_0",- sessionId: "session-1",});await control!.dispose();diff --git a/packages/eve/src/execution/turn-cancellation-control.ts b/packages/eve/src/execution/turn-cancellation-control.tsindex 2451e821e..bbb926c38 100644--- a/packages/eve/src/execution/turn-cancellation-control.ts+++ b/packages/eve/src/execution/turn-cancellation-control.ts@@ -2,14 +2,14 @@ import { createHook } from "#compiled/@workflow/core/index.js";import { claimHookOwnership, disposeHook, isHookConflictError } from "#execution/hook-ownership.js";import {- sessionCancelHookToken,+ turnCancellationHookToken,type TurnCancelPayload,} from "#execution/turn-cancellation-token.js";import { TurnCancelledError } from "#harness/turn-cancellation.js";/*** Owns one turn's cancellation surface inside the turn workflow: the- * session-scoped cancel hook and the durable `AbortController` whose+ * turn-private cancel hook and the durable `AbortController` whose* signal is serialized into every `turnStep`. Must be created inside a* `"use workflow"` body.*/@@ -27,16 +27,16 @@ export interface TurnCancellationControl {}/**- * Creates and claims the session cancel hook for one turn workflow run.+ * Creates and claims the private cancel hook for one turn workflow run.* Returns `undefined` when the token is still claimed by a crashed prior* run — the turn then runs uncancellable rather than failing.*/export async function createTurnCancellationControl(input: {+ readonly controlToken: string;readonly expectedTurnId: string;- readonly sessionId: string;}): Promise<TurnCancellationControl | undefined> {const hook = createHook<TurnCancelPayload>({- token: sessionCancelHookToken(input.sessionId),+ token: turnCancellationHookToken(input.controlToken),});// Hook promises and iterators share one durable cursor. Create the// iterator before claiming so conflict replay is consumed bydiff --git a/packages/eve/src/execution/turn-cancellation-token.ts b/packages/eve/src/execution/turn-cancellation-token.tsindex c21fb4b08..0ebc9b2bf 100644--- a/packages/eve/src/execution/turn-cancellation-token.ts+++ b/packages/eve/src/execution/turn-cancellation-token.ts@@ -1,10 +1,10 @@-/** Derives the stable session-scoped cancellation hook token. */-export function sessionCancelHookToken(sessionId: string): string {- return `${sessionId}:cancel`;+/** Derives the private cancellation hook token for one dispatched turn. */+export function turnCancellationHookToken(controlToken: string): string {+ return `${controlToken}:cancel`;}/**- * Payload accepted by the session cancel hook. A mismatched `turnId` is a+ * Payload accepted by the private turn cancel hook. A mismatched `turnId` is a* benign no-op; omitting it targets whichever turn owns the hook.*/export interface TurnCancelPayload {diff --git a/packages/eve/src/execution/turn-cancellation.integration.test.ts b/packages/eve/src/execution/turn-cancellation.integration.test.tsindex c6dac25c1..bc134a140 100644--- a/packages/eve/src/execution/turn-cancellation.integration.test.ts+++ b/packages/eve/src/execution/turn-cancellation.integration.test.ts@@ -10,7 +10,8 @@ import {import { waitForHook } from "#internal/testing/workflow-test-helpers.js";import { ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";-import { sessionCancelHookToken } from "#execution/turn-cancellation-token.js";+import { sessionCommandHookToken } from "#execution/session-command-token.js";+import { turnCancellationHookToken } from "#execution/turn-cancellation-token.js";import { workflowEntry } from "#execution/workflow-entry.js";import { createWorkflowRuntime } from "#execution/workflow-runtime.js";import { createEveCancelTurnRoutePath } from "#protocol/routes.js";@@ -224,7 +225,11 @@ function createCancelRouteCaller(): (compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),});const agent: Agent = {- cancelTurn: (input) => runtime.cancelTurn(input),+ cancelTurn: (input) =>+ runtime.dispatchSession({+ command: { kind: "cancel", turnId: input.turnId },+ sessionId: input.sessionId,+ }),async deliver() {throw new Error("cancel route must not deliver");},@@ -308,18 +313,21 @@ describe("turn cancellation integration", () => {const stream = captureTurnEvents(run);try {- const cancelToken = sessionCancelHookToken(run.runId);- const cancelHook = await waitForHookByToken(cancelToken);+ const commandToken = sessionCommandHookToken(run.runId);+ const cancelHook = await waitForHookByToken(+ turnCancellationHookToken(`${run.runId}:turn-control:0`),+ );+ await waitForHookByToken(commandToken);await fixture.toolStarted;// A matching turn guard cancels the observed turn (the first// turn's id is `turn_0`).- await resumeHook(cancelToken, { turnId: "turn_0" });+ await resumeHook(commandToken, { kind: "cancel", turnId: "turn_0" });const cancelledTurn = await stream.nextTurn();- // A duplicate cancel after the turn settled lands on a- // consumed/disposed hook and must not disturb the session.- await resumeHook(cancelToken, {}).catch(() => undefined);+ // A duplicate cancel after the turn settled is consumed by the+ // parked driver and must not disturb the session.+ await resumeHook(commandToken, { kind: "cancel" });expect(cancelledTurn.at(-1)?.type).toBe("session.waiting");expect(@@ -341,8 +349,8 @@ describe("turn cancellation integration", () => {await waitForHook({ runId: run.runId }, { token: continuationToken });await resumeHook(continuationToken, {- kind: "deliver",- payloads: [{ message: "follow up after cancel" }],+ kind: "send",+ payload: { message: "follow up after cancel" },});const followUpTurn = await stream.nextTurn();@@ -388,7 +396,7 @@ describe("turn cancellation integration", () => {const stream = captureTurnEvents(run);try {- await waitForHookByToken(sessionCancelHookToken(run.runId));+ await waitForHookByToken(sessionCommandHookToken(run.runId));await fixture.toolStarted;const cancelled = await cancelViaRoute(run.runId);@@ -408,18 +416,15 @@ describe("turn cancellation integration", () => {expectNoFailureEvents(cancelledTurn);expect(fixture.toolAborts()).toBe(1);- // With the turn settled and its cancel hook swept from the- // world, a duplicate cancel is the benign "nothing to cancel"- // success. (Between settle and sweep a duplicate may still be- // accepted as "accepted" and land unconsumed — also benign.)- await waitForHookSweep(sessionCancelHookToken(run.runId));+ // The stable inbox remains owned while the session is parked, so a+ // duplicate cancellation is durably accepted and consumed as a no-op.const duplicate = await cancelViaRoute(run.runId);- await expectCancelResponse(duplicate, { sessionId: run.runId, status: "no_active_turn" });+ await expectCancelResponse(duplicate, { sessionId: run.runId, status: "accepted" });await waitForHook({ runId: run.runId }, { token: continuationToken });await resumeHook(continuationToken, {- kind: "deliver",- payloads: [{ message: "follow up after route cancel" }],+ kind: "send",+ payload: { message: "follow up after route cancel" },});const followUpTurn = await stream.nextTurn();@@ -454,6 +459,7 @@ describe("turn cancellation integration", () => {// A token no session owns is the benign "nothing to cancel" success// and must never start a session.await expect(cancel({ continuationToken: "no-such-thread" })).resolves.toEqual({+ reason: "HookNotFoundError",status: "no_active_turn",});@@ -491,20 +497,18 @@ describe("turn cancellation integration", () => {expectNoFailureEvents(cancelledTurn);expect(fixture.toolAborts()).toBe(1);- // Session.cancel() addresses the same session by id. With the turn- // settled and its cancel hook swept, it reports the benign status.- await waitForHookSweep(sessionCancelHookToken(run.runId));+ // Session.cancel() addresses the same parked session by its stable ID.const session = createSession(run.runId, rawToken, workflowRuntime);await expect(session.cancel()).resolves.toEqual({- reason: "HookNotFoundError",- status: "no_active_turn",+ status: "accepted",});- await waitForHook({ runId: run.runId }, { token: continuationToken });- await resumeHook(continuationToken, {- kind: "deliver",- payloads: [{ message: "follow up after helper cancel" }],- });+ await expect(+ workflowRuntime.dispatchContinuation({+ command: { kind: "send", payload: { message: "follow up after helper cancel" } },+ continuationToken,+ }),+ ).resolves.toEqual({ sessionId: run.runId, status: "accepted" });const followUpTurn = await stream.nextTurn();@@ -547,9 +551,9 @@ describe("turn cancellation integration", () => {// tool, holding the parent in `waitForRuntimeActionResults`.await fixture.toolStarted;- const cancelToken = sessionCancelHookToken(run.runId);+ const cancelToken = sessionCommandHookToken(run.runId);await waitForHookByToken(cancelToken);- await resumeHook(cancelToken, {});+ await resumeHook(cancelToken, { kind: "cancel" });const cancelledTurn = await stream.nextTurn();@@ -561,14 +565,14 @@ describe("turn cancellation integration", () => {const childSessionId = filterEventsByType(cancelledTurn, "subagent.called")[0]?.data.childSessionId;expect(childSessionId).toBeDefined();- await waitForHookSweep(sessionCancelHookToken(childSessionId ?? ""));+ await waitForHookSweep(turnCancellationHookToken(`${childSessionId ?? ""}:turn-control:0`));expect(fixture.toolAborts()).toBe(1);// The cleared pending batch must not re-dispatch on the next turn.await waitForHook({ runId: run.runId }, { token: continuationToken });await resumeHook(continuationToken, {- kind: "deliver",- payloads: [{ message: "follow up after subagent cancel" }],+ kind: "send",+ payload: { message: "follow up after subagent cancel" },});const followUpTurn = await stream.nextTurn();@@ -624,9 +628,12 @@ describe("turn cancellation integration", () => {.childSessionId;expect(childSessionId).toBeDefined();- const cancelToken = sessionCancelHookToken(run.runId);- const cancelHook = await waitForHookByToken(cancelToken);- await resumeHook(cancelToken, {});+ const cancelToken = sessionCommandHookToken(run.runId);+ await waitForHookByToken(cancelToken);+ const cancelHook = await waitForHookByToken(+ turnCancellationHookToken(`${run.runId}:turn-control:0`),+ );+ await resumeHook(cancelToken, { kind: "cancel" });// Barrier: the answer must not race the cancel — a delivery that// beats the cancel is legitimately routed to the still-live child.await waitForRunCompletion(cancelHook.runId);@@ -635,13 +642,11 @@ describe("turn cancellation integration", () => {// fabricated turn.cancelled or a second session.waiting.const world = await getWorld();const answer = {- kind: "deliver",- payloads: [- {- inputResponses: [{ requestId: requestId ?? "", text: "blue" }],- message: "answer after hitl cancel",- },- ],+ kind: "send",+ payload: {+ inputResponses: [{ requestId: requestId ?? "", text: "blue" }],+ message: "answer after hitl cancel",+ },};await waitForHook({ runId: run.runId }, { token: continuationToken });await resumeHook(continuationToken, answer);@@ -697,21 +702,21 @@ describe("turn cancellation integration", () => {const stream = captureTurnEvents(run);try {- const cancelToken = sessionCancelHookToken(run.runId);+ const cancelToken = sessionCommandHookToken(run.runId);await waitForHookByToken(cancelToken);await fixture.toolStarted;// A guard naming a turn the session has never run: the payload is// consumed as a no-op — the caller's cancel must never leak onto// a turn they did not observe.- await resumeHook(cancelToken, { turnId: "turn_99" });+ await resumeHook(cancelToken, { kind: "cancel", turnId: "turn_99" });// The turn must still be cancellable afterwards: the skip loop// re-arms the durable read rather than consuming the hook.await new Promise((resolve) => setTimeout(resolve, 250));expect(fixture.toolAborts()).toBe(0);- await resumeHook(cancelToken, { turnId: "turn_0" });+ await resumeHook(cancelToken, { kind: "cancel", turnId: "turn_0" });const cancelledTurn = await stream.nextTurn();@@ -748,14 +753,13 @@ describe("turn cancellation integration", () => {expect(firstTurn.at(-1)?.type).toBe("session.waiting");expect(filterEventsByType(firstTurn, "turn.completed")).toHaveLength(1);- // The turn workflow has settled and disposed its cancel hook; a- // late cancel either rejects (hook gone) or lands unconsumed.- await resumeHook(sessionCancelHookToken(run.runId), {}).catch(() => undefined);+ // The stable inbox accepts a late cancel and the parked driver consumes it as a no-op.+ await resumeHook(sessionCommandHookToken(run.runId), { kind: "cancel" });await waitForHook({ runId: run.runId }, { token: continuationToken });await resumeHook(continuationToken, {- kind: "deliver",- payloads: [{ message: "follow up after late cancel" }],+ kind: "send",+ payload: { message: "follow up after late cancel" },});const secondTurn = await stream.nextTurn();@@ -799,8 +803,8 @@ describe("turn cancellation integration", () => {await waitForHook({ runId: run.runId }, { token: continuationToken });await resumeHook(continuationToken, {- kind: "deliver",- payloads: [{ message: "second turn" }],+ kind: "send",+ payload: { message: "second turn" },});expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");@@ -813,7 +817,7 @@ describe("turn cancellation integration", () => {let completedTurnRuns = 0;let cancelHooks = 0;while (Date.now() < deadline) {- const cancelToken0 = sessionCancelHookToken(run.runId);+ const cancelToken0 = turnCancellationHookToken(`${run.runId}:turn-control:0`);const cancelHook0 = await world.hooks.getByToken(cancelToken0).catch(() => null);cancelHooks = cancelHook0 === null ? 0 : 1;diff --git a/packages/eve/src/execution/turn-control-protocol.test.ts b/packages/eve/src/execution/turn-control-protocol.test.tsnew file mode 100644index 000000000..ebf7c68d3--- /dev/null+++ b/packages/eve/src/execution/turn-control-protocol.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it, vi } from "vitest";++import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";+import { sendTurnControlStep } from "#execution/turn-control-protocol.js";+import { resumeHook } from "#internal/workflow/runtime.js";++vi.mock("#compiled/@workflow/core/runtime.js", () => ({+ resumeHook: vi.fn(),+}));++describe("sendTurnControlStep", () => {+ it("ignores an obsolete send after the session driver releases its hook", async () => {+ vi.mocked(resumeHook).mockRejectedValue(new HookNotFoundError("turn-control"));++ await expect(+ sendTurnControlStep({+ controlToken: "turn-control",+ payload: { kind: "turn-delivery-cancelled", requestId: "delivery-1" },+ }),+ ).resolves.toBeUndefined();+ });++ it("propagates unexpected delivery failures", async () => {+ const failure = new Error("world unavailable");+ vi.mocked(resumeHook).mockRejectedValue(failure);++ await expect(+ sendTurnControlStep({+ controlToken: "turn-control",+ payload: { kind: "turn-delivery-cancelled", requestId: "delivery-1" },+ }),+ ).rejects.toBe(failure);+ });+});diff --git a/packages/eve/src/execution/turn-control-protocol.ts b/packages/eve/src/execution/turn-control-protocol.tsindex 893b053f7..ac39d4a75 100644--- a/packages/eve/src/execution/turn-control-protocol.ts+++ b/packages/eve/src/execution/turn-control-protocol.ts@@ -1,4 +1,5 @@import type { DeliverHookPayload, HookPayload } from "#channel/types.js";+import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";import type { NextDriverAction } from "#execution/next-driver-action.js";import { resumeHook } from "#internal/workflow/runtime.js";@@ -36,5 +37,12 @@ export async function sendTurnControlStep(input: {}): Promise<void> {"use step";- await resumeHook(input.controlToken, input.payload);+ try {+ await resumeHook(input.controlToken, input.payload);+ } catch (error) {+ // Reset and timeout terminally stop the session driver while its child+ // turn may still be unwinding. A final at-least-once control send then+ // has no receiver and is already obsolete.+ if (!HookNotFoundError.is(error)) throw error;+ }}diff --git a/packages/eve/src/execution/turn-control-receiver.test.ts b/packages/eve/src/execution/turn-control-receiver.test.tsindex 25db06a22..af5b1d63e 100644--- a/packages/eve/src/execution/turn-control-receiver.test.ts+++ b/packages/eve/src/execution/turn-control-receiver.test.ts@@ -1,9 +1,10 @@import { beforeEach, describe, expect, it, vi } from "vitest";-import type { DeliverHookPayload, HookPayload } from "#channel/types.js";+import type { DeliverHookPayload } from "#channel/types.js";import type { DurableSessionState } from "#execution/durable-session-store.js";+import { forwardTurnCancellationStep } from "#execution/forward-turn-cancellation-step.js";import { forwardTurnDeliveryStep } from "#execution/forward-turn-delivery-step.js";-import type { SessionDeliveryHook } from "#execution/session-delivery-hook.js";+import type { SessionCommandInbox, SessionInboxPayload } from "#execution/session-command-inbox.js";import type { TurnControlPayload } from "#execution/turn-control-protocol.js";import { TurnControlReceiver } from "#execution/turn-control-receiver.js";@@ -17,6 +18,10 @@ vi.mock("./forward-turn-delivery-step.js", () => ({forwardTurnDeliveryStep: vi.fn(),}));+vi.mock("./forward-turn-cancellation-step.js", () => ({+ forwardTurnCancellationStep: vi.fn(),+}));+describe("TurnControlReceiver", () => {beforeEach(() => {vi.clearAllMocks();@@ -94,14 +99,71 @@ describe("TurnControlReceiver", () => {await expect(runReceiver([])).rejects.toThrow("boom");});++ it("buffers sends and context controls that arrive during a turn", async () => {+ installControlHook([parkResult()], true);+ const bufferedDeliveries: DeliverHookPayload[] = [];+ const bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset"> = [];++ const action = await runReceiver(bufferedDeliveries, {+ bufferedSessionControls,+ commandInbox: createCommandInbox([+ { kind: "send", payload: { message: "follow up" } },+ { kind: "clear" },+ { kind: "compact" },+ { kind: "session-timeout" },+ ]),+ });++ expect(action.kind).toBe("park");+ expect(bufferedDeliveries).toEqual([+ {+ auth: undefined,+ caller: undefined,+ kind: "deliver",+ payloads: [{ message: "follow up" }],+ requestId: undefined,+ },+ ]);+ expect(bufferedSessionControls).toEqual(["clear", "compact", "expired"]);+ });++ it("forwards cancel and reset through the active turn's private hook", async () => {+ installControlHook([parkResult()], true);+ const bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset"> = [];++ const action = await runReceiver([], {+ bufferedSessionControls,+ commandInbox: createCommandInbox([+ { kind: "cancel", turnId: "turn_3" },+ { kind: "reset", reason: "Start over" },+ ]),+ });++ expect(action.kind).toBe("park");+ expect(forwardTurnCancellationStep).toHaveBeenNthCalledWith(1, {+ payload: { turnId: "turn_3" },+ token: "turn-control:cancel",+ });+ expect(forwardTurnCancellationStep).toHaveBeenNthCalledWith(2, {+ payload: {},+ token: "turn-control:cancel",+ });+ expect(bufferedSessionControls).toEqual(["reset"]);+ });});function runReceiver(bufferedDeliveries: DeliverHookPayload[],+ options: {+ readonly bufferedSessionControls?: Array<"clear" | "compact" | "expired" | "reset">;+ readonly commandInbox?: SessionCommandInbox;+ } = {},): ReturnType<TurnControlReceiver["waitForAction"]> {const receiver = new TurnControlReceiver({bufferedDeliveries,- deliveryHook: createDeliveryHook(),+ bufferedSessionControls: options.bufferedSessionControls ?? [],+ commandInbox: options.commandInbox ?? createCommandInbox(),token: "turn-control",});return receiver.waitForAction().finally(() => receiver.dispose());@@ -123,18 +185,26 @@ function parkResult(): Extract<TurnControlPayload, { readonly kind: "turn-result};}-function createDeliveryHook(overrides: Partial<SessionDeliveryHook> = {}): SessionDeliveryHook {+function createCommandInbox(+ values: readonly SessionInboxPayload[] = [],+ overrides: Partial<SessionCommandInbox> = {},+): SessionCommandInbox {+ const queue = [...values];return {- consumeSessionControl: vi.fn(() => undefined),+ claimStable: vi.fn(),consumeNext: vi.fn(),- consumeSessionTimeout: vi.fn(() => false),- next: vi.fn(() => new Promise<IteratorResult<HookPayload>>(() => {})),- rekey: vi.fn(),+ next: vi.fn(() => {+ const value = queue.shift();+ return value === undefined+ ? new Promise<IteratorResult<SessionInboxPayload>>(() => {})+ : Promise.resolve({ done: false, value });+ }),+ rekeyContinuation: vi.fn(),...overrides,};}-function installControlHook(values: readonly TurnControlPayload[]): void {+function installControlHook(values: readonly TurnControlPayload[], delayed = false): void {const queue = [...values];createHookMock.mockReturnValue({token: "turn-control",@@ -142,6 +212,7 @@ function installControlHook(values: readonly TurnControlPayload[]): void {[Symbol.asyncIterator]() {return {next: async () => {+ if (delayed) await new Promise<void>((resolve) => setTimeout(resolve, 0));const value = queue.shift();return value === undefined ? { done: true, value: undefined } : { done: false, value };},diff --git a/packages/eve/src/execution/turn-control-receiver.ts b/packages/eve/src/execution/turn-control-receiver.tsindex 7c8aef2e2..053a3b9ce 100644--- a/packages/eve/src/execution/turn-control-receiver.ts+++ b/packages/eve/src/execution/turn-control-receiver.ts@@ -1,32 +1,39 @@import { createHook, type Hook } from "#compiled/@workflow/core/index.js";-import type { DeliverHookPayload } from "#channel/types.js";+import type { DeliverHookPayload, SessionCommand } from "#channel/types.js";+import { forwardTurnCancellationStep } from "#execution/forward-turn-cancellation-step.js";import type { TurnControlPayload } from "#execution/turn-control-protocol.js";import { forwardTurnDeliveryStep } from "#execution/forward-turn-delivery-step.js";import { closeHookIterator, disposeHook } from "#execution/hook-ownership.js";import type { NextDriverAction } from "#execution/next-driver-action.js";-import type { SessionDeliveryHook } from "#execution/session-delivery-hook.js";+import type { SessionCommandInbox, SessionInboxPayload } from "#execution/session-command-inbox.js";+import { turnCancellationHookToken } from "#execution/turn-cancellation-token.js";import { rebuildSerializableError } from "#execution/workflow-errors.js";type DeliveryRequest = Extract<TurnControlPayload, { readonly kind: "turn-delivery-request" }>;+export type TurnDriverAction = NextDriverAction;+/** Owns one turn's driver-side control hook and public-delivery relay state. */export class TurnControlReceiver {private readonly bufferedDeliveries: DeliverHookPayload[];+ private readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;+ private readonly commandInbox: SessionCommandInbox;private readonly control: Hook<TurnControlPayload>;private readonly controlIterator: AsyncIterator<TurnControlPayload>;- private readonly deliveryHook: SessionDeliveryHook;private pendingControl: Promise<IteratorResult<TurnControlPayload>> | null = null;constructor(input: {readonly bufferedDeliveries: DeliverHookPayload[];- readonly deliveryHook: SessionDeliveryHook;+ readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;+ readonly commandInbox: SessionCommandInbox;readonly token: string;}) {this.bufferedDeliveries = input.bufferedDeliveries;+ this.bufferedSessionControls = input.bufferedSessionControls;+ this.commandInbox = input.commandInbox;this.control = createHook<TurnControlPayload>({ token: input.token });this.controlIterator = this.control[Symbol.asyncIterator]();- this.deliveryHook = input.deliveryHook;}/** Token passed to the turn workflow so it can publish control messages. */@@ -41,11 +48,15 @@ export class TurnControlReceiver {}/** Services control messages until the active turn returns its terminal driver action. */- async waitForAction(): Promise<NextDriverAction> {+ async waitForAction(): Promise<TurnDriverAction> {while (true) {- const payload = await this.nextControl(- "Turn control hook closed before delivering a result.",- );+ const winner = await this.nextControlOrCommand();+ if (winner.kind === "command") {+ const terminal = await this.handleSessionCommand(winner.command);+ if (terminal !== undefined) return terminal;+ continue;+ }+ const payload = winner.payload;const terminal = this.readTerminalControl(payload);if (terminal !== undefined) return terminal;@@ -57,6 +68,39 @@ export class TurnControlReceiver {}}+ private async handleSessionCommand(+ command: SessionInboxPayload,+ ): Promise<TurnDriverAction | undefined> {+ if (command.kind === "send") {+ this.bufferedDeliveries.push(commandToDelivery(command));+ return undefined;+ }+ if (command.kind === "clear" || command.kind === "compact") {+ this.bufferedSessionControls.push(command.kind);+ return undefined;+ }+ if (command.kind === "session-timeout") {+ this.bufferedSessionControls.push("expired");+ return undefined;+ }+ if (command.kind === "cancel") {+ await forwardTurnCancellationStep({+ payload: command.turnId === undefined ? {} : { turnId: command.turnId },+ token: turnCancellationHookToken(this.control.token),+ });+ return undefined;+ }+ if (command.kind === "reset") {+ await forwardTurnCancellationStep({+ payload: {},+ token: turnCancellationHookToken(this.control.token),+ });+ this.bufferedSessionControls.push("reset");+ return undefined;+ }+ return unsupportedSessionCommand(command);+ }+private bufferTurnDeliveries(payload: Extract<TurnControlPayload, { readonly kind: "turn-result" }>,): void {@@ -74,23 +118,34 @@ export class TurnControlReceiver {return this.pendingControl;}- private async nextControl(- onClosed: string,- ): Promise<- Exclude<TurnControlPayload, { readonly kind: "turn-error" | "turn-continuation-token" }>+ private async nextControlOrCommand(): Promise<+ | { readonly command: SessionInboxPayload; readonly kind: "command" }+ | { readonly kind: "control"; readonly payload: TurnControlPayload }> {- while (true) {- const next = await this.getControlPromise();- this.consumeControl();- if (next.done) throw new Error(onClosed);- const payload = next.value;- if (payload.kind === "turn-error") throw rebuildSerializableError(payload.error);- if (payload.kind === "turn-continuation-token") {- await this.deliveryHook.rekey(payload.continuationToken);- continue;+ const winner = await Promise.race([+ this.getControlPromise().then((value) => ({ kind: "control" as const, value })),+ this.commandInbox.next().then((value) => ({ kind: "command" as const, value })),+ ]);++ if (winner.kind === "command") {+ if (winner.value.done) {+ throw new Error("Session command inbox closed before the active turn settled.");}- return payload;+ this.commandInbox.consumeNext();+ return { command: winner.value.value, kind: "command" };+ }++ this.consumeControl();+ if (winner.value.done) {+ throw new Error("Turn control hook closed before delivering a result.");+ }+ const payload = winner.value.value;+ if (payload.kind === "turn-error") throw rebuildSerializableError(payload.error);+ if (payload.kind === "turn-continuation-token") {+ await this.commandInbox.rekeyContinuation(payload.continuationToken);+ return await this.nextControlOrCommand();}+ return { kind: "control", payload };}private readTerminalControl(payload: TurnControlPayload): NextDriverAction | undefined {@@ -102,14 +157,14 @@ export class TurnControlReceiver {private async serviceDeliveryRequest(request: DeliveryRequest,- ): Promise<NextDriverAction | undefined> {- await this.deliveryHook.rekey(request.continuationToken);+ ): Promise<TurnDriverAction | undefined> {+ await this.commandInbox.rekeyContinuation(request.continuationToken);let delivery = this.bufferedDeliveries.shift();while (delivery === undefined) {const winner = await Promise.race([this.getControlPromise().then((value) => ({ kind: "control" as const, value })),- this.deliveryHook.next().then((value) => ({ kind: "delivery" as const, value })),+ this.commandInbox.next().then((value) => ({ kind: "command" as const, value })),]);if (winner.kind === "control") {@@ -118,7 +173,7 @@ export class TurnControlReceiver {throw new Error("Turn control hook closed during a delivery request.");}if (winner.value.value.kind === "turn-continuation-token") {- await this.deliveryHook.rekey(winner.value.value.continuationToken);+ await this.commandInbox.rekeyContinuation(winner.value.value.continuationToken);continue;}const terminal = this.readTerminalControl(winner.value.value);@@ -133,12 +188,16 @@ export class TurnControlReceiver {}if (winner.value.done) {- throw new Error("Session delivery hook closed during a turn delivery request.");+ throw new Error("Session command inbox closed during a turn delivery request.");}- this.deliveryHook.consumeNext();- if (winner.value.value.kind !== "deliver") continue;- delivery = winner.value.value;+ this.commandInbox.consumeNext();+ if (winner.value.value.kind === "send") {+ delivery = commandToDelivery(winner.value.value);+ continue;+ }+ const terminal = await this.handleSessionCommand(winner.value.value);+ if (terminal !== undefined) return terminal;}// Forwarding is provisional until the turn acknowledges it. If the inbox is@@ -169,11 +228,18 @@ export class TurnControlReceiver {private async awaitForwardedDelivery(requestId: string,outstanding: DeliverHookPayload,- ): Promise<NextDriverAction | undefined> {+ ): Promise<TurnDriverAction | undefined> {while (true) {- const payload = await this.nextControl(- "Turn control hook closed before resolving a forwarded delivery.",- );+ const winner = await this.nextControlOrCommand();+ if (winner.kind === "command") {+ const terminal = await this.handleSessionCommand(winner.command);+ if (terminal !== undefined) {+ this.bufferedDeliveries.unshift(outstanding);+ return terminal;+ }+ continue;+ }+ const payload = winner.payload;if (payload.kind === "turn-delivery-accepted") {if (payload.requestId === requestId) return undefined;@@ -194,3 +260,19 @@ export class TurnControlReceiver {}}}++function unsupportedSessionCommand(command: never): never {+ throw new Error(`Unsupported session command: ${JSON.stringify(command)}`);+}++function commandToDelivery(+ command: Extract<SessionCommand, { readonly kind: "send" }>,+): DeliverHookPayload {+ return {+ auth: command.auth,+ caller: command.caller,+ kind: "deliver",+ payloads: [command.payload],+ requestId: command.requestId,+ };+}diff --git a/packages/eve/src/execution/turn-dispatch.test.ts b/packages/eve/src/execution/turn-dispatch.test.tsindex 735b7e577..10a3373ec 100644--- a/packages/eve/src/execution/turn-dispatch.test.ts+++ b/packages/eve/src/execution/turn-dispatch.test.ts@@ -1,10 +1,10 @@import { beforeEach, describe, expect, it, vi } from "vitest";-import type { DeliverHookPayload, HookPayload } from "#channel/types.js";+import type { DeliverHookPayload } from "#channel/types.js";import type { DurableSessionState } from "#execution/durable-session-store.js";import { forwardTurnDeliveryStep } from "#execution/forward-turn-delivery-step.js";-import type { SessionDeliveryHook } from "#execution/session-delivery-hook.js";import { dispatchAndAwaitTurn } from "#execution/turn-dispatch.js";+import type { SessionCommandInbox, SessionInboxPayload } from "#execution/session-command-inbox.js";import type { TurnControlPayload } from "#execution/turn-control-protocol.js";const createHookMock = vi.fn();@@ -37,13 +37,14 @@ describe("dispatchAndAwaitTurn", () => {},]);const rekeyHook = vi.fn();- const deliveryHook = createDeliveryHook({ rekey: rekeyHook });+ const commandInbox = createCommandInbox({ rekeyContinuation: rekeyHook });await dispatchAndAwaitTurn({bufferedDeliveries: [],+ bufferedSessionControls: [],+ commandInbox,controlToken: "turn-control",delivery: { kind: "deliver", payloads: [{ message: "start" }] },- deliveryHook,mode: "conversation",parentWritable: new WritableStream<Uint8Array>(),serializedContext: {},@@ -70,13 +71,14 @@ describe("dispatchAndAwaitTurn", () => {},]);const rekeyHook = vi.fn();- const deliveryHook = createDeliveryHook({ rekey: rekeyHook });+ const commandInbox = createCommandInbox({ rekeyContinuation: rekeyHook });await dispatchAndAwaitTurn({bufferedDeliveries: [],+ bufferedSessionControls: [],+ commandInbox,controlToken: "turn-control",delivery: { kind: "deliver", payloads: [{ message: "start" }] },- deliveryHook,mode: "conversation",parentWritable: new WritableStream<Uint8Array>(),serializedContext: {},@@ -130,14 +132,15 @@ describe("dispatchAndAwaitTurn", () => {const bufferedDeliveries: DeliverHookPayload[] = [];await dispatchAndAwaitTurn({bufferedDeliveries,- controlToken: "turn-control",- delivery: { kind: "deliver", payloads: [{ message: "start" }] },- deliveryHook: createDeliveryHook({+ bufferedSessionControls: [],+ commandInbox: createCommandInbox({next: async () => ({done: false,- value: { kind: "deliver", payloads: [{ message: "later delivery" }] },+ value: { kind: "send", payload: { message: "later delivery" } },}),}),+ controlToken: "turn-control",+ delivery: { kind: "deliver", payloads: [{ message: "start" }] },mode: "conversation",parentWritable: new WritableStream<Uint8Array>(),serializedContext: {},@@ -172,9 +175,10 @@ describe("dispatchAndAwaitTurn", () => {const bufferedDeliveries: DeliverHookPayload[] = [delivery];const turn = await dispatchAndAwaitTurn({bufferedDeliveries,+ bufferedSessionControls: [],+ commandInbox: createCommandInbox(),controlToken: "turn-control",delivery: { kind: "deliver", payloads: [{ message: "start" }] },- deliveryHook: createDeliveryHook(),mode: "conversation",parentWritable: new WritableStream<Uint8Array>(),serializedContext: {},@@ -197,9 +201,10 @@ describe("dispatchAndAwaitTurn", () => {const turn = await dispatchAndAwaitTurn({bufferedDeliveries: [],+ bufferedSessionControls: [],+ commandInbox: createCommandInbox(),controlToken: "turn-control",delivery: { kind: "deliver", payloads: [{ message: "start" }] },- deliveryHook: createDeliveryHook(),mode: "conversation",parentWritable: new WritableStream<Uint8Array>(),serializedContext: {},@@ -215,13 +220,12 @@ describe("dispatchAndAwaitTurn", () => {});});-function createDeliveryHook(overrides: Partial<SessionDeliveryHook> = {}): SessionDeliveryHook {+function createCommandInbox(overrides: Partial<SessionCommandInbox> = {}): SessionCommandInbox {return {- consumeSessionControl: vi.fn(() => undefined),+ claimStable: vi.fn(),consumeNext: vi.fn(),- consumeSessionTimeout: vi.fn(() => false),- next: vi.fn(() => new Promise<IteratorResult<HookPayload>>(() => {})),- rekey: vi.fn(),+ next: vi.fn(() => new Promise<IteratorResult<SessionInboxPayload>>(() => {})),+ rekeyContinuation: vi.fn(),...overrides,};}diff --git a/packages/eve/src/execution/turn-dispatch.ts b/packages/eve/src/execution/turn-dispatch.tsindex dc69fc771..3f1c28615 100644--- a/packages/eve/src/execution/turn-dispatch.ts+++ b/packages/eve/src/execution/turn-dispatch.ts@@ -1,14 +1,14 @@import type { DeliverHookPayload, HookPayload, SessionCapabilities } from "#channel/types.js";import { TurnControlReceiver } from "#execution/turn-control-receiver.js";import type { DurableSessionState } from "#execution/durable-session-store.js";-import type { NextDriverAction } from "#execution/next-driver-action.js";-import type { SessionDeliveryHook } from "#execution/session-delivery-hook.js";+import type { SessionCommandInbox } from "#execution/session-command-inbox.js";import { dispatchTurnStep } from "#execution/workflow-steps.js";+import type { TurnDriverAction } from "#execution/turn-control-receiver.js";import type { RunMode } from "#shared/run-mode.js";/** One settled turn: its terminal driver action plus deferred hook cleanup. */export interface DispatchedTurn {- readonly action: NextDriverAction;+ readonly action: TurnDriverAction;/*** Disposes the turn's control hook. Deferred until the *next* turn* settles (or the session ends): the turn run's final control send is@@ -23,10 +23,11 @@ export interface DispatchedTurn {/** Dispatches one turn and services its private-inbox control protocol until it terminates. */export async function dispatchAndAwaitTurn(input: {readonly bufferedDeliveries: DeliverHookPayload[];+ readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;readonly capabilities?: SessionCapabilities;readonly controlToken: string;readonly delivery: HookPayload;- readonly deliveryHook: SessionDeliveryHook;+ readonly commandInbox: SessionCommandInbox;readonly mode: RunMode;readonly parentWritable: WritableStream<Uint8Array>;readonly serializedContext: Record<string, unknown>;@@ -34,7 +35,8 @@ export async function dispatchAndAwaitTurn(input: {}): Promise<DispatchedTurn> {const control = new TurnControlReceiver({bufferedDeliveries: input.bufferedDeliveries,- deliveryHook: input.deliveryHook,+ bufferedSessionControls: input.bufferedSessionControls,+ commandInbox: input.commandInbox,token: input.controlToken,});@@ -48,7 +50,6 @@ export async function dispatchAndAwaitTurn(input: {serializedContext: input.serializedContext,sessionState: input.sessionState,});-const action = await control.waitForAction();return { action, dispose: () => control.dispose() };} catch (error) {diff --git a/packages/eve/src/execution/turn-workflow.test.ts b/packages/eve/src/execution/turn-workflow.test.tsindex 22cd1140d..e1c491ed4 100644--- a/packages/eve/src/execution/turn-workflow.test.ts+++ b/packages/eve/src/execution/turn-workflow.test.ts@@ -337,9 +337,8 @@ describe("turnWorkflow", () => {serializedContext: { state: "start" },sessionState,});- // The cancel token is session-scoped so a trigger can derive it from- // the session id alone.- expect(cancelHookTokens()).toEqual(["wrun_test_123:cancel"]);+ // The command inbox forwards cancellation to this turn-private hook.+ expect(cancelHookTokens()).toEqual(["turn-token:cancel"]);// The cancelled result is a pure marker: the control payload carries// the cursor's last settled state, not the aborted step's echo.expect(resumeHookMock).toHaveBeenCalledWith("turn-token", {@@ -435,10 +434,10 @@ describe("turnWorkflow", () => {});await turnWorkflow(input);- // The token is stable across turns: the next turn's claim must never- // race this run's teardown, so disposal precedes the terminal send.+ // The next turn must never race this run's teardown, so disposal+ // precedes the terminal send.const cancelHook = createHookMock.mock.results.find(- (result) => (result.value as { token?: string }).token === "wrun_test_123:cancel",+ (result) => (result.value as { token?: string }).token === "turn-token:cancel",)?.value as { dispose: ReturnType<typeof vi.fn> };const resultCall = resumeHookMock.mock.calls.findIndex((call) => call[1]?.kind === "turn-result",diff --git a/packages/eve/src/execution/turn-workflow.ts b/packages/eve/src/execution/turn-workflow.tsindex a72af6afb..24cf9fef5 100644--- a/packages/eve/src/execution/turn-workflow.ts+++ b/packages/eve/src/execution/turn-workflow.ts@@ -49,7 +49,7 @@ export type { TurnWorkflowInput };* Runs one complete logical turn, including child-agent waits when supported.** The turn-owned path also owns turn cancellation: resuming the- * session-scoped cancel hook (`{sessionId}:cancel`) mid-turn aborts the+ * turn-private cancel hook (`{completionToken}:cancel`) mid-turn aborts the* signal serialized into every `turnStep` and settles the turn as* `turn.cancelled` → `session.waiting` — never as a failure. A late or* guard-mismatched cancel is a benign no-op.@@ -104,8 +104,8 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {canSettleCancelledTurnAsPark(input)) {cancellation = await createTurnCancellationControl({+ controlToken: input.completionToken,expectedTurnId: activeTurnId(input.stepInput.sessionState.emissionState),- sessionId: input.stepInput.sessionState.sessionId,});}diff --git a/packages/eve/src/execution/workflow-entry.integration.test.ts b/packages/eve/src/execution/workflow-entry.integration.test.tsindex 803d95c6f..e144bddd6 100644--- a/packages/eve/src/execution/workflow-entry.integration.test.ts+++ b/packages/eve/src/execution/workflow-entry.integration.test.ts@@ -206,8 +206,8 @@ describe("workflowEntry integration", () => {},);await resumeHook(continuationToken, {- kind: "deliver",- payloads: [{ message: "follow up after auth" }],+ kind: "send",+ payload: { message: "follow up after auth" },});const followupTurn = await stream.nextUntil(@@ -272,12 +272,11 @@ describe("workflowEntry integration", () => {compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),});await expect(- workflowRuntime.deliver({- auth: null,+ workflowRuntime.dispatchContinuation({+ command: { auth: null, kind: "send", payload: { message: "follow up" } },continuationToken,- payload: { message: "follow up" },}),- ).resolves.toEqual({ sessionId: run.runId });+ ).resolves.toEqual({ sessionId: run.runId, status: "accepted" });const secondTurn = await stream.nextTurn();@@ -409,7 +408,10 @@ describe("workflowEntry integration", () => {} finally {stream.dispose();if (replacementSessionId !== undefined) {- await workflowRuntime.terminateSession({ sessionId: replacementSessionId });+ await workflowRuntime.dispatchSession({+ command: { kind: "reset", reason: "Test cleanup" },+ sessionId: replacementSessionId,+ });}}});@@ -462,8 +464,8 @@ describe("workflowEntry integration", () => {);await resumeHook(continuationToken, {- kind: "deliver",- payloads: [{ message: "owner follow up" }],+ kind: "send",+ payload: { message: "owner follow up" },});const ownerFollowUp = await ownerStream.nextTurn();@@ -527,8 +529,8 @@ describe("workflowEntry integration", () => {expect(firstTurn.at(-1)?.type).toBe("session.waiting");await resumeHook(continuationToken, {- kind: "deliver",- payloads: [{ message: "follow up without structured output" }],+ kind: "send",+ payload: { message: "follow up without structured output" },});const secondTurn = await stream.nextTurn();diff --git a/packages/eve/src/execution/workflow-entry.test.ts b/packages/eve/src/execution/workflow-entry.test.tsindex d4c626884..192f4aace 100644--- a/packages/eve/src/execution/workflow-entry.test.ts+++ b/packages/eve/src/execution/workflow-entry.test.ts@@ -19,6 +19,8 @@ import { routeDeliverToChildren } from "#execution/route-child-delivery.js";import { settleCancelledTurnStep } from "#execution/settle-cancelled-turn-step.js";import { dispatchTurnStep } from "#execution/workflow-steps.js";import { emitTerminalSessionFailureStep } from "#execution/terminal-session-failure-step.js";+import type { SessionInboxPayload } from "#execution/session-command-inbox.js";+import { sessionCommandHookToken } from "#execution/session-command-token.js";vi.mock("#compiled/@workflow/core/index.js", () => ({createHook: vi.fn(),@@ -108,10 +110,10 @@ vi.mock("./session-callback-step.js", () => ({interface DeliveryHookConfig {readonly dispose?: () => void;readonly getConflict?: () => Promise<{ readonly runId: string } | null>;- readonly next?: () => Promise<IteratorResult<HookPayload>>;- readonly return?: () => Promise<IteratorResult<HookPayload>>;+ readonly next?: () => Promise<IteratorResult<SessionInboxPayload>>;+ readonly return?: () => Promise<IteratorResult<SessionInboxPayload>>;readonly token: string;- readonly values?: readonly HookPayload[];+ readonly values?: readonly SessionInboxPayload[];}interface AuthHookConfig {@@ -155,6 +157,7 @@ describe("workflowEntry", () => {expect(result).toEqual({ output: "ok" });expect(createSessionTimeoutControl).toHaveBeenCalledWith({deadline: new Date("2026-01-31T00:00:00.000Z"),+ token: sessionCommandHookToken("wrun_test_123"),});expect(createSessionStep).toHaveBeenCalledWith({compiledArtifactsSource: {},@@ -319,10 +322,11 @@ describe("workflowEntry", () => {deliveryHooks: [{dispose,+ next: () => new Promise<IteratorResult<SessionInboxPayload>>(() => {}),token: "http:test",- values: [{ kind: "session-timeout" }],},],+ stableHook: { values: [{ kind: "session-timeout" }] },turnControls: [turnResult({ action: "park", sessionState })],});@@ -336,8 +340,8 @@ describe("workflowEntry", () => {expect(createSessionTimeoutControl).toHaveBeenCalledWith({deadline: new Date("2026-01-01T00:00:01.000Z"),+ token: sessionCommandHookToken("wrun_test_123"),});- expect(timeoutControl.rekey).toHaveBeenCalledWith("http:test");expect(timeoutControl.dispose).toHaveBeenCalledOnce();expect(emitTerminalSessionFailureStep).not.toHaveBeenCalled();expect(emitTerminalSessionCompletionStep).toHaveBeenCalledWith({@@ -411,7 +415,7 @@ describe("workflowEntry", () => {expect(routeDeliverToChildren).not.toHaveBeenCalled();});- it("does not complete at the deadline until the active turn settles", async () => {+ it("completes at the deadline after the active turn settles", async () => {const sessionState = createBaseSessionState();const dispose = vi.fn();let settleTurn: ((result: IteratorResult<TurnControlPayload>) => void) | undefined;@@ -420,6 +424,7 @@ describe("workflowEntry", () => {});vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));+ let deliveredTimeout = false;vi.mocked(createHook).mockImplementation((options?: { readonly token?: string }) => {const token = options?.token ?? "";if (isTurnCompletionToken(token)) {@@ -432,11 +437,25 @@ describe("workflowEntry", () => {if (token.endsWith(":auth")) {return createMockHook({ token, values: [] }) as never;}- return createMockHook({- dispose,- token,- values: [{ kind: "session-timeout" }],- }) as never;+ return token === sessionCommandHookToken("wrun_test_123")+ ? (createMockHook({+ dispose,+ next: () => {+ if (deliveredTimeout) {+ return new Promise<IteratorResult<SessionInboxPayload>>(() => {});+ }+ deliveredTimeout = true;+ return Promise.resolve({ done: false, value: { kind: "session-timeout" } });+ },+ token,+ values: [],+ }) as never)+ : (createMockHook({+ dispose,+ next: () => new Promise<IteratorResult<SessionInboxPayload>>(() => {}),+ token,+ values: [],+ }) as never);});const result = workflowEntry({@@ -540,8 +559,8 @@ describe("workflowEntry", () => {values: [{requestId: "req_followup",- kind: "deliver",- payloads: [{ message: "follow up" }],+ kind: "send",+ payload: { message: "follow up" },},],},@@ -619,8 +638,8 @@ describe("workflowEntry", () => {token,values: [{- kind: "deliver",- payloads: [{ inputResponses: [{ optionId: "approve", requestId: "req-1" }] }],+ kind: "send",+ payload: { inputResponses: [{ optionId: "approve", requestId: "req-1" }] },},],}) as never;@@ -675,7 +694,7 @@ describe("workflowEntry", () => {}return createMockHook({token,- values: [{ kind: "deliver", payloads: [{ message: "not for the child" }] }],+ values: [{ kind: "send", payload: { message: "not for the child" } }],}) as never;});@@ -709,7 +728,7 @@ describe("workflowEntry", () => {deliveryHooks: [{token: "http:test",- values: [{ kind: "deliver", payloads: [{ message: "after cancel" }] }],+ values: [{ kind: "send", payload: { message: "after cancel" } }],},],turnControls: [@@ -898,8 +917,8 @@ describe("workflowEntry", () => {token: "slack:C01:",values: [{- kind: "deliver",- payloads: [{ message: "follow up" }],+ kind: "send",+ payload: { message: "follow up" },},],},@@ -957,8 +976,8 @@ describe("workflowEntry", () => {token: "http:test",values: [{- kind: "deliver",- payloads: [{ message: "follow up" }],+ kind: "send",+ payload: { message: "follow up" },},],},@@ -1057,6 +1076,7 @@ function turnResult(input: {function installHookMocks(input: {readonly authHook?: AuthHookConfig;readonly deliveryHooks?: readonly DeliveryHookConfig[];+ readonly stableHook?: Omit<DeliveryHookConfig, "token">;readonly symbolDispose?: () => void;readonly turnControls: readonly TurnControlPayload[];}): void {@@ -1083,6 +1103,25 @@ function installHookMocks(input: {}) as never;}+ if (token === sessionCommandHookToken("wrun_test_123")) {+ const values = [...(input.stableHook?.values ?? [])];+ return createMockHook({+ dispose: input.stableHook?.dispose,+ getConflict: input.stableHook?.getConflict,+ next:+ input.stableHook?.next ??+ (async () => {+ const value = values.shift();+ return value === undefined+ ? await new Promise<IteratorResult<SessionInboxPayload>>(() => {})+ : { done: false, value };+ }),+ return: input.stableHook?.return,+ token,+ values: [],+ }) as never;+ }+const config = deliveryHooks.shift() ?? { token, values: [] };if (config.token !== token) {throw new Error(`Expected delivery hook token "${config.token}", received "${token}".`);@@ -1103,7 +1142,7 @@ function installHookMocks(input: {function createTimeoutControl(): SessionTimeoutControl {return {dispose: vi.fn(async () => undefined),- rekey: vi.fn(async () => undefined),+ start: vi.fn(async () => undefined),};}@@ -1144,9 +1183,9 @@ function createMockHook<T>(input: {});}-function createIteratorReturn(): () => Promise<IteratorResult<HookPayload>> {+function createIteratorReturn(): () => Promise<IteratorResult<never>> {return vi.fn(- async (): Promise<IteratorResult<HookPayload>> => ({+ async (): Promise<IteratorResult<never>> => ({done: true,value: undefined,}),@@ -1159,7 +1198,10 @@ function nonTurnHookTokens(): string[] {.mock.calls.map((call) => call[0]?.token).filter((token): token is string =>- token !== undefined && !token.endsWith(":auth") && !isTurnCompletionToken(token),+ token !== undefined &&+ token !== sessionCommandHookToken("wrun_test_123") &&+ !token.endsWith(":auth") &&+ !isTurnCompletionToken(token),);}diff --git a/packages/eve/src/execution/workflow-entry.ts b/packages/eve/src/execution/workflow-entry.tsindex 9f19f8700..4dedf04ce 100644--- a/packages/eve/src/execution/workflow-entry.ts+++ b/packages/eve/src/execution/workflow-entry.ts@@ -21,6 +21,7 @@ import type { NextDriverAction } from "#execution/next-driver-action.js";import { routeDeliverToChildren } from "#execution/route-child-delivery.js";import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-step.js";import { dispatchAndAwaitTurn } from "#execution/turn-dispatch.js";+import type { TurnDriverAction } from "#execution/turn-control-receiver.js";import { normalizeSerializableError } from "#execution/workflow-errors.js";import { createSessionStep } from "#execution/create-session-step.js";import { settleCancelledTurnStep } from "#execution/settle-cancelled-turn-step.js";@@ -28,9 +29,10 @@ import { emitTerminalSessionFailureStep } from "#execution/terminal-session-failimport { fireSessionCallbackStep } from "#execution/session-callback-step.js";import { disposeHook } from "#execution/hook-ownership.js";import {- createSessionDeliveryHook,- type SessionDeliveryHook,-} from "#execution/session-delivery-hook.js";+ createSessionCommandInbox,+ type SessionCommandInbox,+} from "#execution/session-command-inbox.js";+import { sessionCommandHookToken } from "#execution/session-command-token.js";import { DEFAULT_SESSION_TIMEOUT_MS } from "#execution/session-timeout.js";import { emitTerminalSessionCompletionStep } from "#execution/terminal-session-completion-step.js";import { createSessionTimeoutControl } from "#execution/session-timeout-control.js";@@ -77,7 +79,8 @@ type NextSessionAction =readonly delivery: DeliverHookPayload | null;readonly kind: "delivery";}- | { readonly kind: "expired" };+ | { readonly kind: "expired" }+ | { readonly kind: "reset" };/*** Long-lived workflow entrypoint. Handles both root sessions and@@ -86,7 +89,7 @@ type NextSessionAction =* on a child stream and resume the parked parent with a* `subagent-result` on completion.*- * Owns the public delivery hook and the session lifecycle; each turn-owned+ * Owns the stable command inbox, its channel alias, and the session lifecycle; each turn-owned* turn resolves its own runtime actions in-line and reports back only* `done`/`park` via the closed-contract {@link NextDriverAction}. The* only session-shape flag the driver reads (besides identity) is@@ -218,11 +221,17 @@ async function runDriverLoop(input: {`${input.sessionState.sessionId}:turn-control:${String(turnDispatchIndex++)}`;const bufferedDeliveries: DeliverHookPayload[] = [];- const deliveryHook = createSessionDeliveryHook(bufferedDeliveries);+ const bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset"> = [];+ const commandInbox = createSessionCommandInbox();+ const stableCommandToken = sessionCommandHookToken(input.sessionState.sessionId);+ await commandInbox.claimStable(stableCommandToken);const sessionTimeout =input.sessionTimeoutDeadline === undefined? undefined- : createSessionTimeoutControl({ deadline: input.sessionTimeoutDeadline });+ : createSessionTimeoutControl({+ deadline: input.sessionTimeoutDeadline,+ token: stableCommandToken,+ });// Control-hook disposal is deferred one turn — see DispatchedTurn.let disposeSettledTurnControl: (() => Promise<void>) | undefined;@@ -230,13 +239,14 @@ async function runDriverLoop(input: {readonly delivery: HookPayload;readonly serializedContext: Record<string, unknown>;readonly sessionState: DurableSessionState;- }): Promise<NextDriverAction> => {+ }): Promise<TurnDriverAction> => {const turn = await dispatchAndAwaitTurn({bufferedDeliveries,+ bufferedSessionControls,capabilities: input.capabilities,+ commandInbox,controlToken: nextTurnControlToken(),delivery: args.delivery,- deliveryHook,mode: input.mode,parentWritable: input.driverWritable,serializedContext: args.serializedContext,@@ -249,11 +259,11 @@ async function runDriverLoop(input: {try {if (input.sessionState.continuationToken) {- await deliveryHook.rekey(input.sessionState.continuationToken);- await sessionTimeout?.rekey(input.sessionState.continuationToken);+ await commandInbox.rekeyContinuation(input.sessionState.continuationToken);}+ await sessionTimeout?.start();- let action: NextDriverAction = await runTurn({+ let action: TurnDriverAction = await runTurn({delivery: input.initialInput,serializedContext: input.serializedContext,sessionState: input.sessionState,@@ -290,20 +300,12 @@ async function runDriverLoop(input: {};}- if (!action.sessionState.continuationToken) {- throw new Error(- "Cannot park: no continuation token available. The channel must " +- "post the first message during the initial turn (anchoring the " +- "session) or `send()` must be called with an explicit " +- "continuationToken.",- );+ // Channel-created sessions may rekey their dynamic alias. Sessions+ // without one remain reachable through the stable command inbox only.+ if (action.sessionState.continuationToken) {+ await commandInbox.rekeyContinuation(action.sessionState.continuationToken);}- // Rekey to the parked turn's continuation token before awaiting the next- // delivery — covers both the first turn's anchor and any later rekey.- await deliveryHook.rekey(action.sessionState.continuationToken);- await sessionTimeout?.rekey(action.sessionState.continuationToken);-if (action.authorizationNames && action.authorizationNames.length > 0) {const expected = action.authorizationNames.length;const allPayloads: DeliverPayload[] = [];@@ -329,7 +331,8 @@ async function runDriverLoop(input: {const nextAction = await waitForNextSessionAction({bufferedDeliveries,- deliveryHook,+ bufferedSessionControls,+ commandInbox,});if (nextAction.kind === "expired") {@@ -339,6 +342,10 @@ async function runDriverLoop(input: {};}+ if (nextAction.kind === "reset") {+ return { kind: "result", result: { output: "" } };+ }+if (nextAction.kind === "clear" || nextAction.kind === "compact") {action = await runTurn({delivery: { kind: nextAction.kind },@@ -397,7 +404,7 @@ async function runDriverLoop(input: {} finally {await disposeSettledTurnControl?.();await sessionTimeout?.dispose();- await deliveryHook.dispose();+ await commandInbox.dispose();// Dispose without closing the iterator: a session cancelled while// awaiting authorization can leave a durable read in flight, and an// async iterator only honors `return()` after that read settles.@@ -407,13 +414,10 @@ async function runDriverLoop(input: {async function waitForNextSessionAction(input: {readonly bufferedDeliveries: DeliverHookPayload[];- readonly deliveryHook: SessionDeliveryHook;+ readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;+ readonly commandInbox: SessionCommandInbox;}): Promise<NextSessionAction> {- if (input.deliveryHook.consumeSessionTimeout()) {- return { kind: "expired" };- }-- const pendingSessionControl = input.deliveryHook.consumeSessionControl();+ const pendingSessionControl = input.bufferedSessionControls.shift();if (pendingSessionControl !== undefined) {return { kind: pendingSessionControl };}@@ -426,8 +430,8 @@ async function waitForNextSessionAction(input: {}while (true) {- const first = await input.deliveryHook.next();- input.deliveryHook.consumeNext();+ const first = await input.commandInbox.next();+ input.commandInbox.consumeNext();if (first.done) {return { delivery: null, kind: "delivery" };@@ -437,55 +441,34 @@ async function waitForNextSessionAction(input: {return { kind: "expired" };}- if (first.value.kind === "clear" || first.value.kind === "compact") {- const sessionControl = input.deliveryHook.consumeSessionControl();- if (sessionControl === undefined) {- throw new Error("Session control was consumed without being latched.");- }- return { kind: sessionControl };+ if (+ first.value.kind === "clear" ||+ first.value.kind === "compact" ||+ first.value.kind === "reset"+ ) {+ return { kind: first.value.kind };}- if (first.value.kind !== "deliver") {+ if (first.value.kind === "cancel") {continue;}- let coalesced = first.value;-- while (true) {- const ready = await takeReadyPayload(input.deliveryHook.next());-- if (ready === NO_READY_MESSAGE) {- break;- }-- if (ready.done) {- input.deliveryHook.consumeNext();- break;- }-- // Preserve a timeout queued after a delivery. The delivery committed- // first, so its active turn settles before the offered timeout is read.- if (ready.value.kind === "session-timeout") {- break;- }-- input.deliveryHook.consumeNext();-- if (ready.value.kind === "clear" || ready.value.kind === "compact") {- continue;- }-- if (ready.value.kind !== "deliver") {- continue;- }-- coalesced = coalesceDeliveries([coalesced, ready.value]);- }-- return { delivery: coalesced, kind: "delivery" };+ return { delivery: commandToDelivery(first.value), kind: "delivery" };}}+function commandToDelivery(+ command: Extract<import("#channel/types.js").SessionCommand, { readonly kind: "send" }>,+): DeliverHookPayload {+ return {+ auth: command.auth,+ caller: command.caller,+ kind: "deliver",+ payloads: [command.payload],+ requestId: command.requestId,+ };+}+async function finalizeExpiredSession(input: {readonly driverWritable: WritableStream<Uint8Array>;readonly serializedContext: Record<string, unknown>;@@ -529,10 +512,3 @@ async function finalizeDone(input: {});return { output };}--const NO_READY_MESSAGE = Symbol("no-ready-message");--async function takeReadyPayload<T>(promise: Promise<T>): Promise<T | typeof NO_READY_MESSAGE> {- await Promise.resolve();- return await Promise.race([promise, Promise.resolve(NO_READY_MESSAGE)]);-}diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.tsindex 3c021ad05..214e509e4 100644--- a/packages/eve/src/execution/workflow-runtime.test.ts+++ b/packages/eve/src/execution/workflow-runtime.test.ts@@ -10,7 +10,7 @@ import {turnWorkflowReference,workflowEntryReference,} from "#execution/workflow-runtime.js";-import { isRuntimeNoActiveSessionError } from "#execution/runtime-errors.js";+import { sessionCommandHookToken } from "#execution/session-command-token.js";import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";@@ -67,7 +67,7 @@ describe("workflowEntryReference", () => {});});-describe("createWorkflowRuntime#deliver", () => {+describe("createWorkflowRuntime command dispatch", () => {const NOT_FOUND_TOKEN = "test:no-such-hook";function buildRuntime() {@@ -75,105 +75,100 @@ describe("createWorkflowRuntime#deliver", () => {return createWorkflowRuntime({ compiledArtifactsSource });}- it("normalizes `HookNotFoundError` into `RuntimeNoActiveSessionError`", async () => {- const { HookNotFoundError } = await import("#compiled/@workflow/errors/index.js");- resumeHookMock.mockRejectedValue(new HookNotFoundError(NOT_FOUND_TOKEN));-- const runtime = buildRuntime();+ it("dispatches send commands directly through a continuation alias", async () => {+ resumeHookMock.mockResolvedValue({ runId: "driver-run" });await expect(- runtime.deliver({- auth: null,- continuationToken: NOT_FOUND_TOKEN,- payload: {},+ buildRuntime().dispatchContinuation({+ command: {+ auth: null,+ kind: "send",+ payload: { message: "hello" },+ requestId: "req_deliver",+ },+ continuationToken: "test:token",}),- ).rejects.toSatisfy(isRuntimeNoActiveSessionError);- });+ ).resolves.toEqual({ sessionId: "driver-run", status: "accepted" });- it("re-throws unexpected errors from `resumeHook`", async () => {- const failure = new Error("transient backing-store outage");- resumeHookMock.mockRejectedValue(failure);+ expect(resumeHookMock).toHaveBeenCalledWith("test:token", {+ auth: null,+ kind: "send",+ payload: { message: "hello" },+ requestId: "req_deliver",+ });+ expect(getHookByTokenMock).not.toHaveBeenCalled();+ });- const runtime = buildRuntime();+ it("dispatches commands through the stable session inbox", async () => {+ resumeHookMock.mockResolvedValue({ runId: "session-1" });await expect(- runtime.deliver({- auth: null,- continuationToken: NOT_FOUND_TOKEN,- payload: {},+ buildRuntime().dispatchSession({+ command: { kind: "clear" },+ sessionId: "session-1",}),- ).rejects.toBe(failure);+ ).resolves.toEqual({ sessionId: "session-1", status: "accepted" });++ expect(resumeHookMock).toHaveBeenCalledWith(sessionCommandHookToken("session-1"), {+ kind: "clear",+ });+ expect(getHookByTokenMock).not.toHaveBeenCalled();});- it("resumes hooks with the channel request id", async () => {- resumeHookMock.mockResolvedValue({ runId: "driver-run" });+ it.each([+ { command: { kind: "send" as const, payload: {} }, status: "session_not_active" },+ { command: { kind: "compact" as const }, status: "no_active_session" },+ { command: { kind: "clear" as const }, status: "no_active_session" },+ { command: { kind: "reset" as const }, status: "no_active_session" },+ ])("maps a missing $command.kind target to $status", async ({ command, status }) => {+ const { HookNotFoundError } = await import("#compiled/@workflow/errors/index.js");+ resumeHookMock.mockRejectedValue(new HookNotFoundError(NOT_FOUND_TOKEN));await expect(- buildRuntime().deliver({- auth: null,- continuationToken: "test:token",- payload: { message: "hello" },- requestId: "req_deliver",+ buildRuntime().dispatchContinuation({+ command,+ continuationToken: NOT_FOUND_TOKEN,}),- ).resolves.toEqual({ sessionId: "driver-run" });-- expect(resumeHookMock).toHaveBeenCalledWith("test:token", {- auth: null,- kind: "deliver",- payloads: [{ message: "hello" }],- requestId: "req_deliver",- });+ ).resolves.toEqual({ status });});- it("returns the owner from the hook resumed by the delivery", async () => {- resumeHookMock.mockResolvedValue({ runId: "owner-session" });+ it("re-throws unexpected errors from `resumeHook`", async () => {+ const failure = new Error("transient backing-store outage");+ resumeHookMock.mockRejectedValue(failure);const runtime = buildRuntime();await expect(- runtime.deliver({- auth: null,- continuationToken: "test:active-hook",- payload: { message: "hello" },+ runtime.dispatchContinuation({+ command: { kind: "compact" },+ continuationToken: NOT_FOUND_TOKEN,}),- ).resolves.toEqual({ sessionId: "owner-session" });- expect(resumeHookMock).toHaveBeenCalledOnce();- expect(resumeHookMock).toHaveBeenCalledWith("test:active-hook", {- auth: null,- kind: "deliver",- payloads: [{ message: "hello" }],- });+ ).rejects.toBe(failure);});-});--describe("createWorkflowRuntime#cancelTurn", () => {- function buildRuntime() {- return createWorkflowRuntime({ compiledArtifactsSource: {} as RuntimeCompiledArtifactsSource });- }- it("resumes the session cancel hook with an optional turn guard", async () => {- resumeHookMock.mockResolvedValue({ runId: "turn-run" });+ it("dispatches guarded cancellation through the stable inbox", async () => {+ resumeHookMock.mockResolvedValue({ runId: "session-1" });await expect(- buildRuntime().cancelTurn({ sessionId: "session-1", turnId: "turn-2" }),+ buildRuntime().dispatchSession({+ command: { kind: "cancel", turnId: "turn-2" },+ sessionId: "session-1",+ }),).resolves.toEqual({ status: "accepted" });- expect(resumeHookMock).toHaveBeenCalledWith("session-1:cancel", { turnId: "turn-2" });- });-- it("uses an empty payload for an unguarded cancel", async () => {- resumeHookMock.mockResolvedValue({ runId: "turn-run" });-- await expect(buildRuntime().cancelTurn({ sessionId: "session-1" })).resolves.toEqual({- status: "accepted",+ expect(resumeHookMock).toHaveBeenCalledWith(sessionCommandHookToken("session-1"), {+ kind: "cancel",+ turnId: "turn-2",});- expect(resumeHookMock).toHaveBeenCalledWith("session-1:cancel", {});});it("maps missing and terminal targets to 'no_active_turn' with a classified reason", async () => {const { EntityConflictError, HookNotFoundError, RunExpiredError, WorkflowRunNotFoundError } =await import("#compiled/@workflow/errors/index.js");const errors = [- { error: new HookNotFoundError("session-1:cancel"), reason: "HookNotFoundError" },+ {+ error: new HookNotFoundError(sessionCommandHookToken("session-1")),+ reason: "HookNotFoundError",+ },{ error: new WorkflowRunNotFoundError("turn-run"), reason: "WorkflowRunNotFoundError" },{ error: new RunExpiredError("turn already completed"), reason: "RunExpiredError" },{@@ -184,10 +179,12 @@ describe("createWorkflowRuntime#cancelTurn", () => {for (const { error, reason } of errors) {resumeHookMock.mockRejectedValueOnce(error);- await expect(buildRuntime().cancelTurn({ sessionId: "session-1" })).resolves.toEqual({- reason,- status: "no_active_turn",- });+ await expect(+ buildRuntime().dispatchSession({+ command: { kind: "cancel" },+ sessionId: "session-1",+ }),+ ).resolves.toEqual({ reason, status: "no_active_turn" });}});@@ -195,125 +192,36 @@ describe("createWorkflowRuntime#cancelTurn", () => {const failure = new Error("transient backing-store outage");resumeHookMock.mockRejectedValue(failure);- await expect(buildRuntime().cancelTurn({ sessionId: "session-1" })).rejects.toBe(failure);- });-});--describe("createWorkflowRuntime#compactSession", () => {- function buildRuntime() {- return createWorkflowRuntime({ compiledArtifactsSource: {} as RuntimeCompiledArtifactsSource });- }-- it("queues compaction on the continuation hook and returns its owner", async () => {- resumeHookMock.mockResolvedValue({ runId: "session-1" });-await expect(- buildRuntime().compactSession({ continuationToken: "eve:token" }),- ).resolves.toEqual({ sessionId: "session-1", status: "accepted" });- expect(resumeHookMock).toHaveBeenCalledWith("eve:token", { kind: "compact" });+ buildRuntime().dispatchSession({+ command: { kind: "cancel" },+ sessionId: "session-1",+ }),+ ).rejects.toBe(failure);});- it("reports a missing continuation hook as an inactive session", async () => {+ it("waits for reset to release the stable command inbox", async () => {const { HookNotFoundError } = await import("#compiled/@workflow/errors/index.js");- resumeHookMock.mockRejectedValue(new HookNotFoundError("eve:missing"));-- await expect(- buildRuntime().compactSession({ continuationToken: "eve:missing" }),- ).resolves.toEqual({ status: "no_active_session" });- });-- it("treats a terminal owner race as an inactive session", async () => {- const { RunExpiredError } = await import("#compiled/@workflow/errors/index.js");- resumeHookMock.mockRejectedValue(new RunExpiredError("session already completed"));-- await expect(- buildRuntime().compactSession({ continuationToken: "eve:completed" }),- ).resolves.toEqual({ status: "no_active_session" });- });-});--describe("createWorkflowRuntime#clearSession", () => {- function buildRuntime() {- return createWorkflowRuntime({ compiledArtifactsSource: {} as RuntimeCompiledArtifactsSource });- }-- it("queues a clear on the continuation hook and returns its owner", async () => {resumeHookMock.mockResolvedValue({ runId: "session-1" });-- await expect(buildRuntime().clearSession({ continuationToken: "eve:token" })).resolves.toEqual({- sessionId: "session-1",- status: "accepted",- });- expect(resumeHookMock).toHaveBeenCalledWith("eve:token", { kind: "clear" });- });-- it("reports a missing continuation hook as an inactive session", async () => {- const { HookNotFoundError } = await import("#compiled/@workflow/errors/index.js");- resumeHookMock.mockRejectedValue(new HookNotFoundError("eve:missing"));-- await expect(- buildRuntime().clearSession({ continuationToken: "eve:missing" }),- ).resolves.toEqual({ status: "no_active_session" });- });-});--describe("createWorkflowRuntime#terminateSession", () => {- function buildRuntime() {- return createWorkflowRuntime({ compiledArtifactsSource: {} as RuntimeCompiledArtifactsSource });- }-- it("cancels the whole workflow run with the supplied reason", async () => {- const world = {};- getWorldMock.mockResolvedValue(world);- cancelRunMock.mockResolvedValue(undefined);+ getHookByTokenMock.mockRejectedValue(+ new HookNotFoundError(sessionCommandHookToken("session-1")),+ );await expect(- buildRuntime().terminateSession({ reason: "User requested /new", sessionId: "session-1" }),- ).resolves.toEqual({ status: "terminated" });- expect(cancelRunMock).toHaveBeenCalledWith(world, "session-1", {- cancelReason: "User requested /new",- });- });-- it("uses a safe default terminal reason", async () => {- const world = {};- getWorldMock.mockResolvedValue(world);- cancelRunMock.mockResolvedValue(undefined);-- await buildRuntime().terminateSession({ sessionId: "session-1" });-- expect(cancelRunMock).toHaveBeenCalledWith(world, "session-1", {- cancelReason: "Session reset by channel",+ buildRuntime().dispatchContinuation({+ command: { kind: "reset", reason: "User requested /new" },+ continuationToken: "eve:token",+ }),+ ).resolves.toEqual({ previousSessionId: "session-1", status: "reset" });+ expect(resumeHookMock).toHaveBeenCalledWith("eve:token", {+ kind: "reset",+ reason: "User requested /new",});- });-- it("normalizes expected terminal races", async () => {- const { EntityConflictError, RunExpiredError, WorkflowRunNotFoundError } =- await import("#compiled/@workflow/errors/index.js");- getWorldMock.mockResolvedValue({});-- for (const cause of [- new EntityConflictError("run is terminal"),- new RunExpiredError("run is terminal"),- new WorkflowRunNotFoundError("session-1"),- ]) {- cancelRunMock.mockRejectedValueOnce(new Error("Failed to cancel run", { cause }));- await expect(buildRuntime().terminateSession({ sessionId: "session-1" })).resolves.toEqual({- status: "already_terminal",- });- }- });-- it("propagates unexpected World failures", async () => {- const failure = new Error("World unavailable");- getWorldMock.mockResolvedValue({});- cancelRunMock.mockRejectedValue(failure);-- await expect(buildRuntime().terminateSession({ sessionId: "session-1" })).rejects.toBe(failure);+ expect(getHookByTokenMock).toHaveBeenCalledWith(sessionCommandHookToken("session-1"));});});-describe("createWorkflowRuntime#resolveSession", () => {+describe("createWorkflowRuntime#resolveContinuation", () => {function buildRuntime() {return createWorkflowRuntime({ compiledArtifactsSource: {} as RuntimeCompiledArtifactsSource });}@@ -321,7 +229,7 @@ describe("createWorkflowRuntime#resolveSession", () => {it("returns the owning session id from the hook lookup", async () => {getHookByTokenMock.mockResolvedValue({ runId: "owner-session" });- await expect(buildRuntime().resolveSession("test:token")).resolves.toEqual({+ await expect(buildRuntime().resolveContinuation("test:token")).resolves.toEqual({sessionId: "owner-session",});expect(getHookByTokenMock).toHaveBeenCalledWith("test:token");@@ -331,18 +239,18 @@ describe("createWorkflowRuntime#resolveSession", () => {const { HookNotFoundError } = await import("#compiled/@workflow/errors/index.js");getHookByTokenMock.mockRejectedValue(new HookNotFoundError("test:token"));- await expect(buildRuntime().resolveSession("test:token")).resolves.toBeUndefined();+ await expect(buildRuntime().resolveContinuation("test:token")).resolves.toBeUndefined();});it("rethrows unexpected lookup failures", async () => {const failure = new Error("transient backing-store outage");getHookByTokenMock.mockRejectedValue(failure);- await expect(buildRuntime().resolveSession("test:token")).rejects.toBe(failure);+ await expect(buildRuntime().resolveContinuation("test:token")).rejects.toBe(failure);});});-describe("createWorkflowRuntime#run", () => {+describe("createWorkflowRuntime#createSession", () => {const adapter: ChannelAdapter = { kind: "http" };function buildRuntime(compiledArtifactsSource: RuntimeCompiledArtifactsSource) {@@ -361,6 +269,7 @@ describe("createWorkflowRuntime#run", () => {},},} as never);+ getHookByTokenMock.mockResolvedValue({ runId: "driver-run" });getRunMock.mockReturnValue({getReadable: () =>new ReadableStream<Uint8Array>({@@ -377,7 +286,7 @@ describe("createWorkflowRuntime#run", () => {mockBundleAndRun(compiledArtifactsSource);startMock.mockResolvedValue({ runId: "driver-run" });- await buildRuntime(compiledArtifactsSource).run({+ await buildRuntime(compiledArtifactsSource).createSession({adapter,auth: null,input: { message: "hello" },@@ -414,7 +323,7 @@ describe("createWorkflowRuntime#run", () => {startMock.mockResolvedValue({ runId: "driver-run" });const message = "<slack_message>\n<content>ship it</content>\n</slack_message>";- await buildRuntime(compiledArtifactsSource).run({+ await buildRuntime(compiledArtifactsSource).createSession({adapter,auth: null,input: { message },@@ -432,7 +341,7 @@ describe("createWorkflowRuntime#run", () => {mockBundleAndRun(compiledArtifactsSource, 86_400_000);startMock.mockResolvedValue({ runId: "driver-run" });- await buildRuntime(compiledArtifactsSource).run({+ await buildRuntime(compiledArtifactsSource).createSession({adapter,auth: null,input: { message: "hello" },@@ -459,7 +368,7 @@ describe("createWorkflowRuntime#run", () => {model: { id: "anthropic/claude-opus-4.6" },},nodeId: "subagents/researcher",- }).run({+ }).createSession({adapter,auth: null,input: { message: "research this" },@@ -485,7 +394,7 @@ describe("createWorkflowRuntime#run", () => {mockBundleAndRun(compiledArtifactsSource);startMock.mockResolvedValue({ runId: "driver-run" });- await buildRuntime(compiledArtifactsSource).run({+ await buildRuntime(compiledArtifactsSource).createSession({adapter,auth: null,input: { message: "hello" },@@ -524,11 +433,12 @@ describe("createWorkflowRuntime#run", () => {resolvedAgent: { config: {} },} as never);startMock.mockResolvedValue({ runId: "subagent-run" });+ getHookByTokenMock.mockResolvedValue({ runId: "subagent-run" });await createWorkflowRuntime({compiledArtifactsSource,nodeId: "researcher",- }).run({+ }).createSession({adapter: { kind: "subagent" },auth: null,continuationToken: "subagent:parent-session:call-1",@@ -564,7 +474,7 @@ describe("createWorkflowRuntime#run", () => {.mockRejectedValueOnce(new Error(LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE)).mockResolvedValueOnce({ runId: "driver-run" });- await buildRuntime(compiledArtifactsSource).run({+ await buildRuntime(compiledArtifactsSource).createSession({adapter,auth: null,input: { message: "hello" },@@ -606,7 +516,7 @@ describe("createWorkflowRuntime#run", () => {mockBundleAndRun(compiledArtifactsSource);startMock.mockResolvedValue({ runId: "driver-run" });- await buildRuntime(compiledArtifactsSource).run({+ await buildRuntime(compiledArtifactsSource).createSession({adapter,auth: null,input: { message: "hello" },@@ -643,8 +553,9 @@ describe("createWorkflowRuntime#run", () => {);getRunMock.mockReturnValue({ getReadable });startMock.mockResolvedValue({ runId: "driver-run" });+ getHookByTokenMock.mockResolvedValue({ runId: "driver-run" });- const handle = await buildRuntime(compiledArtifactsSource).run({+ const handle = await buildRuntime(compiledArtifactsSource).createSession({adapter,auth: null,input: { message: "hello" },diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.tsindex 019ebbf8c..392cde255 100644--- a/packages/eve/src/execution/workflow-runtime.ts+++ b/packages/eve/src/execution/workflow-runtime.ts@@ -8,18 +8,14 @@ import {import type {CancelTurnInput,CancelTurnResult,- ClearSessionInput,- ClearSessionResult,- CompactSessionInput,- CompactSessionResult,- DeliverInput,+ DispatchContinuationInput,+ DispatchSessionInput,GetEventStreamOptions,- HookPayload,RunHandle,RunInput,Runtime,- TerminateSessionInput,- TerminateSessionResult,+ SessionCommand,+ SessionCommandResult,} from "#channel/types.js";import { serializeContext } from "#context/serialize.js";import {@@ -31,10 +27,8 @@ import { resolveInstalledPackageInfo } from "#internal/application/package.js";import { isEveDevEnvironment } from "#internal/application/dev-environment.js";import { createLogger, logError } from "#internal/logging.js";import {- cancelRun,getHookByToken,getRun,- getWorld,resumeHook,start,type Run,@@ -50,19 +44,17 @@ import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-import { buildRunContext } from "#execution/runtime-context.js";import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";import { parseNdjsonStream } from "#execution/ndjson-stream.js";-import { RuntimeNoActiveSessionError } from "#execution/runtime-errors.js";+import { RuntimeSessionOwnershipConflictError } from "#execution/runtime-errors.js";import type { WorkflowEntryInput } from "#execution/workflow-entry.js";import { walkCauseChain } from "#shared/errors.js";-import {- sessionCancelHookToken,- type TurnCancelPayload,-} from "#execution/turn-cancellation-token.js";+import { sessionCommandHookToken } from "#execution/session-command-token.js";import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";const WORKFLOW_ENTRY_NAME = "workflowEntry";const TURN_WORKFLOW_NAME = "turnWorkflow";const SESSION_TIMEOUT_WORKFLOW_NAME = "sessionTimeoutWorkflow";const EVE_PACKAGE_INFO = resolveInstalledPackageInfo();+const COMMAND_HOOK_READY_TIMEOUT_MS = 30_000;export const LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE ="deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()";@@ -127,7 +119,7 @@ export function createWorkflowRuntime(config: {readonly nodeId?: string;}): Runtime {return {- async run(input: RunInput): Promise<RunHandle> {+ async createSession(input: RunInput): Promise<RunHandle> {const bundle = await getCompiledRuntimeAgentBundle({compiledArtifactsSource: config.compiledArtifactsSource,nodeId: config.nodeId,@@ -151,6 +143,7 @@ export function createWorkflowRuntime(config: {if (sessionTimeoutMs !== undefined) {workflowInput.sessionTimeoutMs = sessionTimeoutMs;}+const attributes =parentLineage.sessionId === undefined? buildSessionAttributes({@@ -179,6 +172,18 @@ export function createWorkflowRuntime(config: {throw error;}+ await waitForOwnedCommandHook(sessionCommandHookToken(run.runId), run.runId);+ if (input.continuationToken) {+ const owner = await waitForCommandHookOwner(input.continuationToken);+ if (owner.runId !== run.runId) {+ throw new RuntimeSessionOwnershipConflictError({+ continuationToken: input.continuationToken,+ ownerSessionId: owner.runId,+ sessionId: run.runId,+ });+ }+ }+let events: ReadableStream<MessageStreamEvent> | undefined;const getEvents = () => {events ??= parseNdjsonStream<MessageStreamEvent>(() => getRun(run.runId).getReadable());@@ -194,53 +199,16 @@ export function createWorkflowRuntime(config: {};},- async cancelTurn(input: CancelTurnInput): Promise<CancelTurnResult> {- return await requestWorkflowTurnCancellation(input);- },-- async compactSession(input: CompactSessionInput): Promise<CompactSessionResult> {- return await requestWorkflowSessionControl(input.continuationToken, "compact");+ async dispatchContinuation<TCommand extends SessionCommand>(+ input: DispatchContinuationInput<TCommand>,+ ): Promise<SessionCommandResult<TCommand>> {+ return await dispatchWorkflowCommand(input.continuationToken, input.command);},- async clearSession(input: ClearSessionInput): Promise<ClearSessionResult> {- return await requestWorkflowSessionControl(input.continuationToken, "clear");- },-- async terminateSession(input: TerminateSessionInput): Promise<TerminateSessionResult> {- try {- await cancelRun(await getWorld(), input.sessionId, {- cancelReason: input.reason ?? "Session reset by channel",- });- return { status: "terminated" };- } catch (error) {- if (isAlreadyTerminalSessionError(error)) {- return { status: "already_terminal" };- }- throw error;- }- },-- async deliver(input: DeliverInput): Promise<{ sessionId: string }> {- const hookPayload: Extract<HookPayload, { kind: "deliver" }> = {- auth: input.auth,- kind: "deliver",- payloads: [input.payload],- requestId: input.requestId,- };- try {- const hook = normalizeWorkflowHook(await resumeHook(input.continuationToken, hookPayload));- return { sessionId: hook.runId };- } catch (error) {- // "No hook" is the expected resume-or-start signal: normalize it to- // the eve-owned class without logging. Anything else is a real failure.- if (HookNotFoundError.is(error)) {- throw new RuntimeNoActiveSessionError(input.continuationToken);- }- logError(log, "failed to deliver to active session", error, {- continuationToken: input.continuationToken,- });- throw error;- }+ async dispatchSession<TCommand extends SessionCommand>(+ input: DispatchSessionInput<TCommand>,+ ): Promise<SessionCommandResult<TCommand>> {+ return await dispatchWorkflowCommand(sessionCommandHookToken(input.sessionId), input.command);},async getEventStream(@@ -262,7 +230,9 @@ export function createWorkflowRuntime(config: {}},- async resolveSession(continuationToken: string): Promise<{ sessionId: string } | undefined> {+ async resolveContinuation(+ continuationToken: string,+ ): Promise<{ sessionId: string } | undefined> {try {const hook = await getHookByToken(continuationToken);return { sessionId: hook.runId };@@ -279,38 +249,65 @@ export function createWorkflowRuntime(config: {};}-async function requestWorkflowSessionControl(- continuationToken: string,- kind: "clear" | "compact",-): Promise<ClearSessionResult> {+async function dispatchWorkflowCommand<TCommand extends SessionCommand>(+ token: string,+ command: TCommand,+): Promise<SessionCommandResult<TCommand>> {+ let hook: WorkflowHookRecord;try {- const hook = normalizeWorkflowHook(await resumeHook(continuationToken, { kind }));- return { sessionId: hook.runId, status: "accepted" };+ hook = normalizeWorkflowHook(await resumeHook(token, command));} catch (error) {- if (HookNotFoundError.is(error) || isAlreadyTerminalSessionError(error)) {- return { status: "no_active_session" };+ if (isInactiveCommandTarget(error)) {+ return inactiveCommandResult(command, error);}- logError(log, `failed to request session ${kind}`, error, { continuationToken });+ logError(log, "failed to dispatch session command", error, {+ command: command.kind,+ token,+ });throw error;}++ if (command.kind === "reset") {+ await waitForCommandHookRelease(sessionCommandHookToken(hook.runId), hook.runId);+ }++ return activeCommandResult(command, hook.runId);+}++function activeCommandResult<TCommand extends SessionCommand>(+ command: TCommand,+ sessionId: string,+): SessionCommandResult<TCommand> {+ const result =+ command.kind === "reset"+ ? { previousSessionId: sessionId, status: "reset" as const }+ : command.kind === "cancel"+ ? { status: "accepted" as const }+ : { sessionId, status: "accepted" as const };+ return result as SessionCommandResult<TCommand>;+}++function inactiveCommandResult<TCommand extends SessionCommand>(+ command: TCommand,+ error: unknown,+): SessionCommandResult<TCommand> {+ const result =+ command.kind === "send"+ ? { status: "session_not_active" as const }+ : command.kind === "cancel"+ ? { reason: classifyInactiveCancelTarget(error), status: "no_active_turn" as const }+ : { status: "no_active_session" as const };+ return result as SessionCommandResult<TCommand>;}-/** Requests cancellation through a session's stable workflow hook. */+/** Requests cancellation through a session's stable command inbox. */export async function requestWorkflowTurnCancellation(input: CancelTurnInput,): Promise<CancelTurnResult> {- const payload: TurnCancelPayload = input.turnId === undefined ? {} : { turnId: input.turnId };-- try {- await resumeHook(sessionCancelHookToken(input.sessionId), payload);- return { status: "accepted" };- } catch (error) {- const reason = classifyInactiveCancelTarget(error);- if (reason !== undefined) {- return { reason, status: "no_active_turn" };- }- throw error;- }+ return await dispatchWorkflowCommand(sessionCommandHookToken(input.sessionId), {+ kind: "cancel",+ turnId: input.turnId,+ });}function classifyInactiveCancelTarget(error: unknown): string | undefined {@@ -321,7 +318,8 @@ function classifyInactiveCancelTarget(error: unknown): string | undefined {return undefined;}-function isAlreadyTerminalSessionError(error: unknown): boolean {+function isInactiveCommandTarget(error: unknown): boolean {+ if (HookNotFoundError.is(error)) return true;for (const candidate of walkCauseChain(error)) {if (WorkflowRunNotFoundError.is(candidate) ||@@ -334,6 +332,47 @@ function isAlreadyTerminalSessionError(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,+ });+ }+}++async function waitForCommandHookOwner(token: string): Promise<WorkflowHookRecord> {+ const deadline = Date.now() + COMMAND_HOOK_READY_TIMEOUT_MS;+ while (true) {+ try {+ return normalizeWorkflowHook(await getHookByToken(token));+ } catch (error) {+ if (!HookNotFoundError.is(error) || Date.now() >= deadline) throw error;+ await new Promise<void>((resolve) => setTimeout(resolve, 20));+ }+ }+}++async function waitForCommandHookRelease(token: string, sessionId: string): Promise<void> {+ const deadline = Date.now() + COMMAND_HOOK_READY_TIMEOUT_MS;+ while (true) {+ try {+ const owner = normalizeWorkflowHook(await getHookByToken(token));+ if (owner.runId !== sessionId) return;+ } catch (error) {+ if (HookNotFoundError.is(error)) return;+ throw error;+ }++ if (Date.now() >= deadline) {+ throw new Error(`Timed out waiting for session "${sessionId}" to release its command inbox.`);+ }+ await new Promise<void>((resolve) => setTimeout(resolve, 20));+ }+}+/*** Starts a workflow on the latest deployment when latest routing applies,* while preserving local/dev worlds that do not implement latest routing.diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.tsindex 24a7e021e..1d5211aa4 100644--- a/packages/eve/src/execution/workflow-steps.test.ts+++ b/packages/eve/src/execution/workflow-steps.test.ts@@ -20,6 +20,7 @@ import { setPendingRuntimeActionBatch } from "#harness/runtime-actions.js";import { getAgentHandleStore } from "#harness/handles/store.js";import { requestTurnSleep } from "#harness/turn-sleep.js";import { getPendingAuthorization, setPendingAuthorization } from "#harness/authorization.js";+import { upsertProxyInputRequests } from "#harness/proxy-input-requests.js";import type { HarnessSession, StepResult } from "#harness/types.js";import { createEmptyHookRegistry } from "#runtime/hooks/registry.js";import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";@@ -39,6 +40,7 @@ import { runProxySubagentEventStep } from "#execution/subagent-event-proxy-step.import { emitTerminalSessionFailureStep } from "#execution/terminal-session-failure-step.js";import {dispatchTurnStep,+ routeProxiedDeliverStep,resolveEffectiveOutputSchema,turnStep,} from "#execution/workflow-steps.js";@@ -94,6 +96,7 @@ function createStubSessionState(overrides: Partial<DurableSessionState> = {}): Dconst DEFAULT_WORKFLOW_STREAM_NAMESPACE = "__default__";const getRunMock = vi.fn();+const resumeHookMock = vi.fn();const startMock = vi.fn();const workflowWritesByNamespace = new Map<string, unknown[]>();@@ -123,8 +126,9 @@ vi.mock("../runtime/sessions/compiled-agent-cache.js", () => ({}));vi.mock("#compiled/@workflow/core/runtime.js", () => ({+ getHookByToken: vi.fn(async () => ({ runId: "child-run" })),getRun: (...args: unknown[]) => getRunMock(...args),- resumeHook: vi.fn(),+ resumeHook: (...args: unknown[]) => resumeHookMock(...args),start: (...args: unknown[]) => startMock(...args),}));@@ -193,6 +197,7 @@ function createSerializedContext(): Record<string, unknown> {afterEach(() => {getRunMock.mockReset();+ resumeHookMock.mockReset();startMock.mockReset();workflowWritesByNamespace.clear();vi.unstubAllGlobals();@@ -200,6 +205,49 @@ afterEach(() => {vi.restoreAllMocks();});+describe("routeProxiedDeliverStep", () => {+ it("forwards descendant input responses as session send commands", async () => {+ const auth = {+ attributes: {},+ authenticator: "test",+ principalId: "user-1",+ principalType: "user",+ };+ const session = upsertProxyInputRequests({+ entries: [["request-1", { childContinuationToken: "child-token", kind: "tool-approval" }]],+ forChildContinuationToken: "child-token",+ session: createStubSession({+ continuationToken: "parent-token",+ sessionId: "parent-session",+ }),+ });+ installSessionStoreMocks([session]);++ await expect(+ routeProxiedDeliverStep({+ auth,+ parentWritable: createTestWritable(),+ payload: {+ inputResponses: [{ optionId: "approve", requestId: "request-1" }],+ },+ sessionState: createStubSessionState({+ continuationToken: "parent-token",+ hasProxyInputRequests: true,+ sessionId: "parent-session",+ }),+ }),+ ).resolves.toEqual({ kind: "continue", remainder: undefined });++ expect(resumeHookMock).toHaveBeenCalledWith("child-token", {+ auth,+ kind: "send",+ payload: {+ inputResponses: [{ optionId: "approve", requestId: "request-1" }],+ },+ });+ });+});+describe("dispatchTurnStep", () => {function createTurnInput(): Parameters<typeof dispatchTurnStep>[0] {const parentWritable = createTestWritable();diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.tsindex 0d0d38a71..644fd2ae3 100644--- a/packages/eve/src/execution/workflow-steps.ts+++ b/packages/eve/src/execution/workflow-steps.ts@@ -1,6 +1,6 @@import { buildAdapterContext } from "#channel/adapter-context.js";import { callAdapterEventHandler, defaultDeliverResult } from "#channel/adapter.js";-import type { DeliverPayload, SessionAuthContext } from "#channel/types.js";+import type { DeliverPayload, SessionAuthContext, SessionCommand } from "#channel/types.js";import { dispatchStreamEventHooks } from "#context/hook-lifecycle.js";import { dispatchDynamicInstructionEvent } from "#context/dynamic-instruction-lifecycle.js";import { dispatchDynamicModelEvent } from "#context/dynamic-model-lifecycle.js";@@ -602,11 +602,12 @@ export async function routeProxiedDeliverStep(input: {});for (const forChild of routed.forChildren) {- await resumeHook(forChild.childContinuationToken, {+ const command = {auth: input.auth,- kind: "deliver",- payloads: [forChild.payload],- });+ kind: "send",+ payload: forChild.payload,+ } satisfies SessionCommand;+ await resumeHook(forChild.childContinuationToken, command);}return routed.parentAction ?? { kind: "continue", remainder: routed.forSelf };diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.tsindex 94195d3ad..2a64b5e93 100644--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts@@ -54,6 +54,18 @@ const DEVELOPMENT_ARTIFACTS_CONFIG = {moduleMapLoaderPath: "/eve/src/internal/authored-module-map-loader.ts",} as const;+function createRuntime(overrides: Partial<Runtime> = {}): Runtime {+ return {+ createSession: vi.fn(),+ dispatchContinuation: vi.fn(),+ dispatchSession: vi.fn(),+ getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),+ getStreamTailIndex: vi.fn().mockResolvedValue(-1),+ resolveContinuation: vi.fn(),+ ...overrides,+ };+}+function createDeferred<T>() {let resolve!: (value: T | PromiseLike<T>) => void;let reject!: (reason?: unknown) => void;@@ -263,17 +275,12 @@ describe("dispatchChannelRequest", () => {});it("tags route sends with Vercel's request id", async () => {- const runtimeForTest: Runtime = {- cancelTurn: vi.fn(),- clearSession: vi.fn(),- compactSession: vi.fn(),- deliver: vi.fn().mockResolvedValue({ sessionId: "sess_route" }),- resolveSession: vi.fn(),- getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),- getStreamTailIndex: vi.fn().mockResolvedValue(-1),- run: vi.fn(),- terminateSession: vi.fn(),- };+ const runtimeForTest = createRuntime({+ dispatchContinuation: vi.fn().mockResolvedValue({+ sessionId: "sess_route",+ status: "accepted",+ }),+ });mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({channels: [@@ -308,23 +315,18 @@ describe("dispatchChannelRequest", () => {);expect(response.status).toBe(200);- expect(vi.mocked(runtimeForTest.deliver).mock.calls[0]?.[0].requestId).toBe(- "iad1::abc123-1710000000000-deadbeef",+ expect(vi.mocked(runtimeForTest.dispatchContinuation).mock.calls[0]?.[0].command).toMatchObject(+ { requestId: "iad1::abc123-1710000000000-deadbeef" },);});it("supplies a channel-scoped reset helper", async () => {- const runtimeForTest: Runtime = {- cancelTurn: vi.fn(),- clearSession: vi.fn(),- compactSession: vi.fn(),- deliver: vi.fn(),- getEventStream: vi.fn(),- getStreamTailIndex: vi.fn(),- resolveSession: vi.fn().mockResolvedValue({ sessionId: "sess_previous" }),- run: vi.fn(),- terminateSession: vi.fn().mockResolvedValue({ status: "terminated" }),- };+ const runtimeForTest = createRuntime({+ dispatchContinuation: vi.fn().mockResolvedValue({+ previousSessionId: "sess_previous",+ status: "reset",+ }),+ });mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({channels: [@@ -358,27 +360,18 @@ describe("dispatchChannelRequest", () => {previousSessionId: "sess_previous",status: "reset",});- expect(runtimeForTest.resolveSession).toHaveBeenCalledWith(- "imessage:direct:+15551234567:+15557654321",- );- expect(runtimeForTest.terminateSession).toHaveBeenCalledWith({- reason: "User requested /new",- sessionId: "sess_previous",+ expect(runtimeForTest.dispatchContinuation).toHaveBeenCalledWith({+ command: { kind: "reset", reason: "User requested /new" },+ continuationToken: "imessage:direct:+15551234567:+15557654321",});});it("supplies a channel-scoped clear helper", async () => {- const runtimeForTest: Runtime = {- cancelTurn: vi.fn(),- clearSession: vi.fn().mockResolvedValue({ sessionId: "sess_active", status: "accepted" }),- compactSession: vi.fn(),- deliver: vi.fn(),- getEventStream: vi.fn(),- getStreamTailIndex: vi.fn(),- resolveSession: vi.fn(),- run: vi.fn(),- terminateSession: vi.fn(),- };+ const runtimeForTest = createRuntime({+ dispatchContinuation: vi+ .fn()+ .mockResolvedValue({ sessionId: "sess_active", status: "accepted" }),+ });mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({channels: [@@ -409,23 +402,19 @@ describe("dispatchChannelRequest", () => {sessionId: "sess_active",status: "accepted",});- expect(runtimeForTest.clearSession).toHaveBeenCalledWith({+ expect(runtimeForTest.dispatchContinuation).toHaveBeenCalledWith({+ command: { kind: "clear" },continuationToken: "imessage:direct:+15551234567:+15557654321",});});it("does not invent a channel request id when Vercel did not send one", async () => {- const runtimeForTest: Runtime = {- cancelTurn: vi.fn(),- clearSession: vi.fn(),- compactSession: vi.fn(),- deliver: vi.fn().mockResolvedValue({ sessionId: "sess_route" }),- resolveSession: vi.fn(),- getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),- getStreamTailIndex: vi.fn().mockResolvedValue(-1),- run: vi.fn(),- terminateSession: vi.fn(),- };+ const runtimeForTest = createRuntime({+ dispatchContinuation: vi.fn().mockResolvedValue({+ sessionId: "sess_route",+ status: "accepted",+ }),+ });mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({channels: [@@ -457,25 +446,24 @@ describe("dispatchChannelRequest", () => {);expect(response.status).toBe(200);- expect(vi.mocked(runtimeForTest.deliver).mock.calls[0]?.[0].requestId).toBeUndefined();+ expect(+ vi.mocked(runtimeForTest.dispatchContinuation).mock.calls[0]?.[0].command,+ ).toHaveProperty("requestId", undefined);});it("does not mutate route-owned run and deliver inputs", async () => {- const runtimeForTest: Runtime = {- cancelTurn: vi.fn().mockResolvedValue({ status: "accepted" }),- clearSession: vi.fn(),- compactSession: vi.fn(),- deliver: vi.fn().mockResolvedValue({ sessionId: "sess_deliver" }),- resolveSession: vi.fn(),- getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),- getStreamTailIndex: vi.fn().mockResolvedValue(-1),- run: vi.fn().mockResolvedValue({+ const runtimeForTest = createRuntime({+ createSession: vi.fn().mockResolvedValue({continuationToken: "route-token",events: new ReadableStream(),sessionId: "sess_run",}),- terminateSession: vi.fn(),- };+ dispatchContinuation: vi.fn().mockResolvedValue({+ sessionId: "sess_deliver",+ status: "accepted",+ }),+ dispatchSession: vi.fn().mockResolvedValue({ status: "accepted" }),+ });const deliverInput = Object.freeze({auth: null,continuationToken: "route-token",@@ -522,12 +510,17 @@ describe("dispatchChannelRequest", () => {);expect(response.status).toBe(200);- const deliveredInput = vi.mocked(runtimeForTest.deliver).mock.calls[0]?.[0];- const startedInput = vi.mocked(runtimeForTest.run).mock.calls[0]?.[0];- expect(runtimeForTest.cancelTurn).toHaveBeenCalledWith(cancelInput);+ const deliveredInput = vi.mocked(runtimeForTest.dispatchContinuation).mock.calls[0]?.[0];+ const startedInput = vi.mocked(runtimeForTest.createSession).mock.calls[0]?.[0];+ expect(runtimeForTest.dispatchSession).toHaveBeenCalledWith({+ command: { kind: "cancel", turnId: "turn_1" },+ sessionId: "sess_run",+ });expect(deliveredInput).not.toBe(deliverInput);expect(startedInput).not.toBe(runInput);- expect(deliveredInput?.requestId).toBe("iad1::abc123-1710000000000-deadbeef");+ expect(deliveredInput?.command).toMatchObject({+ requestId: "iad1::abc123-1710000000000-deadbeef",+ });expect(startedInput?.requestId).toBe("iad1::abc123-1710000000000-deadbeef");expect(deliverInput).not.toHaveProperty("requestId");expect(runInput).not.toHaveProperty("requestId");diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.tsindex a061c2133..abbc571b4 100644--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts@@ -15,6 +15,7 @@ import { createSendFn } from "#channel/send.js";import { createResolveActiveSessionFn } from "#channel/resolve-active-session.js";import { createGetSessionFn } from "#channel/session.js";import { createLogger, logError } from "#internal/logging.js";+import { RuntimeNoActiveSessionError } from "#execution/runtime-errors.js";import { readTrustedDevelopmentClientAddress } from "#internal/nitro/dev-client-address.js";import { DEVELOPMENT_WORKFLOW_SECRET_ENV } from "#internal/workflow/development-world-protocol.js";import {@@ -258,18 +259,33 @@ function buildRouteArgs(function createRouteAgent(runtime: Runtime, requestId: string | undefined): Agent {return {async cancelTurn(input) {- return await runtime.cancelTurn(input);+ return await runtime.dispatchSession({+ command: { kind: "cancel", turnId: input.turnId },+ sessionId: input.sessionId,+ });},async deliver(input) {const deliverInput: DeliverInput = { ...input, requestId }; // Avoid mutating a frozen caller input.- return await runtime.deliver(deliverInput);+ const result = await runtime.dispatchContinuation({+ command: {+ auth: deliverInput.auth,+ kind: "send",+ payload: deliverInput.payload,+ requestId: deliverInput.requestId,+ },+ continuationToken: deliverInput.continuationToken,+ });+ if (result.status === "session_not_active") {+ throw new RuntimeNoActiveSessionError(deliverInput.continuationToken);+ }+ return { sessionId: result.sessionId };},async getEventStream(sessionId, options) {return await runtime.getEventStream(sessionId, options);},async run(input) {const runInput: RunInput = { ...input, requestId }; // Avoid mutating a frozen caller input.- return await runtime.run(runInput);+ return await runtime.createSession(runInput);},};}diff --git a/packages/eve/src/internal/testing/session-command-inbox-workflow.ts b/packages/eve/src/internal/testing/session-command-inbox-workflow.tsnew file mode 100644index 000000000..2e7591929--- /dev/null+++ b/packages/eve/src/internal/testing/session-command-inbox-workflow.ts@@ -0,0 +1,45 @@+import { getWorkflowMetadata } from "#compiled/@workflow/core/index.js";++import {+ createSessionCommandInbox,+ type SessionInboxPayload,+} from "#execution/session-command-inbox.js";+import { sessionCommandHookToken } from "#execution/session-command-token.js";++export async function sessionCommandInboxWorkflow(input: {+ readonly messageCount?: number;+ readonly nextToken?: string;+ readonly token: string;+}): Promise<string[]> {+ "use workflow";++ const inbox = createSessionCommandInbox();+ const { workflowRunId } = getWorkflowMetadata();++ try {+ await inbox.claimStable(sessionCommandHookToken(workflowRunId));+ await inbox.rekeyContinuation(input.token);+ const pending = inbox.next();+ if (input.nextToken !== undefined) {+ await inbox.rekeyContinuation(input.nextToken);+ }++ const messages: string[] = [];+ let next = await pending;+ while (true) {+ inbox.consumeNext();+ if (next.done || next.value.kind === "reset") return messages;+ collectMessage(next.value, messages);+ if (messages.length >= (input.messageCount ?? 2)) return messages;+ next = await inbox.next();+ }+ } finally {+ await inbox.dispose();+ }+}++function collectMessage(command: SessionInboxPayload, messages: string[]): void {+ if (command.kind === "send" && typeof command.payload.message === "string") {+ messages.push(command.payload.message);+ }+}diff --git a/packages/eve/src/internal/testing/session-delivery-hook-workflow.ts b/packages/eve/src/internal/testing/session-delivery-hook-workflow.tsdeleted file mode 100644index 7808b3990..000000000--- a/packages/eve/src/internal/testing/session-delivery-hook-workflow.ts+++ /dev/null@@ -1,55 +0,0 @@-import type { DeliverHookPayload, HookPayload } from "#channel/types.js";-import {- createSessionDeliveryHook,- type SessionDeliveryHook,-} from "#execution/session-delivery-hook.js";--export async function sessionDeliveryHookWorkflow(input: {- readonly nextToken: string;- readonly token: string;-}): Promise<string[]> {- "use workflow";-- const bufferedDeliveries: DeliverHookPayload[] = [];- const deliveryHook = createSessionDeliveryHook(bufferedDeliveries);-- try {- await deliveryHook.rekey(input.token);- const pendingDelivery = deliveryHook.next();- await deliveryHook.rekey(input.nextToken);-- const messages: string[] = [];- collectMessages(await pendingDelivery, deliveryHook, messages);-- while (messages.length < 2) {- const buffered = bufferedDeliveries.shift();- if (buffered !== undefined) {- appendMessages(buffered, messages);- continue;- }-- collectMessages(await deliveryHook.next(), deliveryHook, messages);- }-- return messages;- } finally {- await deliveryHook.dispose();- }-}--function collectMessages(- result: IteratorResult<HookPayload>,- deliveryHook: SessionDeliveryHook,- messages: string[],-): void {- deliveryHook.consumeNext();- if (!result.done && result.value.kind === "deliver") {- appendMessages(result.value, messages);- }-}--function appendMessages(delivery: DeliverHookPayload, messages: string[]): void {- for (const payload of delivery.payloads) {- if (typeof payload.message === "string") messages.push(payload.message);- }-}diff --git a/packages/eve/test/scenarios/cross-channel-receive.scenario.test.ts b/packages/eve/test/scenarios/cross-channel-receive.scenario.test.tsindex 5fa5ac906..be7f3c4f2 100644--- a/packages/eve/test/scenarios/cross-channel-receive.scenario.test.ts+++ b/packages/eve/test/scenarios/cross-channel-receive.scenario.test.ts@@ -7,9 +7,8 @@ import {createCrossChannelReceiveFn,toCrossChannelTargets,} from "../../src/channel/cross-channel-receive.js";-import type { Runtime } from "../../src/channel/types.js";+import type { Runtime, SessionCommand, SessionCommandResult } from "../../src/channel/types.js";import { compileAgent } from "../../src/compiler/compile-agent.js";-import { RuntimeNoActiveSessionError } from "../../src/execution/runtime-errors.js";import { createDiskRuntimeCompiledArtifactsSource } from "../../src/runtime/compiled-artifacts-source.js";import { getCompiledRuntimeAgentBundle } from "../../src/runtime/sessions/compiled-agent-cache.js";import {@@ -80,19 +79,7 @@ interface CapturedRun {function createCapturingRuntime(captured: CapturedRun[]): Runtime {return {- async cancelTurn() {- throw new Error("cancelTurn should not be called in this scenario");- },- async clearSession() {- throw new Error("clearSession should not be called in this scenario");- },- async compactSession() {- throw new Error("compactSession should not be called in this scenario");- },- async resolveSession() {- throw new Error("resolveSession should not be called in this scenario");- },- async run(input) {+ async createSession(input) {captured.push({adapter: input.adapter,continuationToken: input.continuationToken,@@ -105,8 +92,13 @@ function createCapturingRuntime(captured: CapturedRun[]): Runtime {sessionId: "sess_scenario",};},- async deliver(input) {- throw new RuntimeNoActiveSessionError(input.continuationToken);+ async dispatchContinuation<TCommand extends SessionCommand>(): Promise<+ SessionCommandResult<TCommand>+ > {+ return { status: "session_not_active" } as SessionCommandResult<TCommand>;+ },+ async dispatchSession() {+ throw new Error("dispatchSession should not be called in this scenario");},async getEventStream() {return new ReadableStream();@@ -114,8 +106,8 @@ function createCapturingRuntime(captured: CapturedRun[]): Runtime {async getStreamTailIndex() {return -1;},- async terminateSession() {- throw new Error("terminateSession should not be called in this scenario");+ async resolveContinuation() {+ throw new Error("resolveContinuation should not be called in this scenario");},};}diff --git a/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts b/packages/eve/test/scenarios/schedule-trigger.scenario.test.tsindex 9ee9071ed..b105bdaeb 100644--- a/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts+++ b/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts@@ -57,19 +57,7 @@ interface CapturedRun {function createCapturingRuntime(captured: CapturedRun[]): Runtime {return {- async cancelTurn() {- throw new Error("cancelTurn should not be called in this scenario");- },- async clearSession() {- throw new Error("clearSession should not be called in this scenario");- },- async compactSession() {- throw new Error("compactSession should not be called in this scenario");- },- async resolveSession() {- throw new Error("resolveSession should not be called in this scenario");- },- async run(input) {+ async createSession(input) {captured.push({adapter: input.adapter,input: input.input as { message: string },@@ -82,8 +70,11 @@ function createCapturingRuntime(captured: CapturedRun[]): Runtime {};return handle;},- async deliver() {- throw new Error("deliver should not be called in this scenario");+ async dispatchContinuation() {+ throw new Error("dispatchContinuation should not be called in this scenario");+ },+ async dispatchSession() {+ throw new Error("dispatchSession should not be called in this scenario");},async getEventStream() {return new ReadableStream<MessageStreamEvent>();@@ -91,8 +82,8 @@ function createCapturingRuntime(captured: CapturedRun[]): Runtime {async getStreamTailIndex() {return -1;},- async terminateSession() {- throw new Error("terminateSession should not be called in this scenario");+ async resolveContinuation() {+ throw new Error("resolveContinuation should not be called in this scenario");},};}