Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): turn performance - remove workflow round trips (#2836)

Andrew Barbae219a6a71d2b
diff --git a/.changeset/inline-same-deployment-turns.md b/.changeset/inline-same-deployment-turns.md
new file mode 100644
index 000000000..889eda7e2
--- /dev/null
+++ b/.changeset/inline-same-deployment-turns.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+Reduce channel turn latency by using optimized session resumes, routing work to the deployment that accepted it, and running ordinary same-deployment turns without a child-workflow handshake. Turns that need sleep, background work, runtime actions, or cross-deployment execution continue in the existing child workflow without repeating completed steps.
diff --git a/packages/eve/src/channel/delivery-metadata.ts b/packages/eve/src/channel/delivery-metadata.ts
index 9d554fa16..5e66819dc 100644
--- a/packages/eve/src/channel/delivery-metadata.ts
+++ b/packages/eve/src/channel/delivery-metadata.ts
@@ -1,6 +1,7 @@
import type { ChannelDeliveryMetadata, SessionTraceContext } from "#channel/types.js";
export interface ChannelDeliverySource {
+ readonly acceptedDeploymentId?: string;
readonly channelKind: string;
readonly channelName: string;
readonly requestId?: string;
@@ -12,6 +13,7 @@ export function createChannelDeliveryMetadata(
source: ChannelDeliverySource,
): ChannelDeliveryMetadata {
const metadata: {
+ acceptedDeploymentId?: string;
channelKind: string;
channelName: string;
deliveryId: string;
@@ -22,6 +24,9 @@ export function createChannelDeliveryMetadata(
channelName: source.channelName,
deliveryId: crypto.randomUUID(),
};
+ if (source.acceptedDeploymentId !== undefined) {
+ metadata.acceptedDeploymentId = source.acceptedDeploymentId;
+ }
if (source.requestId !== undefined) metadata.requestId = source.requestId;
if (source.requestTraceContext !== undefined) {
metadata.requestTraceContext = source.requestTraceContext;
diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.ts
index fc75fca24..80ef1d95e 100644
--- a/packages/eve/src/channel/types.ts
+++ b/packages/eve/src/channel/types.ts
@@ -97,6 +97,7 @@ export interface SessionTraceContext {
/** Framework-owned identity for one inbound channel operation. */
export interface ChannelDeliveryMetadata {
+ readonly acceptedDeploymentId?: string;
readonly channelKind: string;
readonly channelName: string;
readonly deliveryId: string;
diff --git a/packages/eve/src/execution/accepted-delivery-deployment.ts b/packages/eve/src/execution/accepted-delivery-deployment.ts
new file mode 100644
index 000000000..a21085ac3
--- /dev/null
+++ b/packages/eve/src/execution/accepted-delivery-deployment.ts
@@ -0,0 +1,31 @@
+import type { HookPayload } from "#channel/types.js";
+import type { TurnStepInput } from "#execution/durable-session-migrations/turn-workflow.js";
+import type { DurableStepResult } from "#execution/next-driver-action.js";
+
+/** Returns one trusted accepting deployment only when every delivery agrees. */
+export function readAcceptedDeploymentId(input: HookPayload): string | undefined {
+ if (input.kind !== "deliver" || input.deliveryMetadata?.length === 0) return undefined;
+ const acceptedDeploymentId = input.deliveryMetadata?.[0]?.acceptedDeploymentId;
+ if (acceptedDeploymentId === undefined || acceptedDeploymentId.length === 0) return undefined;
+ return input.deliveryMetadata?.every(
+ (metadata) => metadata.acceptedDeploymentId === acceptedDeploymentId,
+ )
+ ? acceptedDeploymentId
+ : undefined;
+}
+
+/** Defers a speculative inline step before mutation when it reached another deployment. */
+export function deferMismatchedInlineTurnStep(input: TurnStepInput): DurableStepResult | undefined {
+ if (
+ input.acceptedDeploymentId === undefined ||
+ process.env.VERCEL_DEPLOYMENT_ID?.trim() === input.acceptedDeploymentId
+ ) {
+ return undefined;
+ }
+ return {
+ action: "continue",
+ requiresChildDispatch: true,
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
+ };
+}
diff --git a/packages/eve/src/execution/dispatch-turn-step.ts b/packages/eve/src/execution/dispatch-turn-step.ts
index 9297d2adc..520386436 100644
--- a/packages/eve/src/execution/dispatch-turn-step.ts
+++ b/packages/eve/src/execution/dispatch-turn-step.ts
@@ -2,8 +2,12 @@ import {
createTurnWorkflowInput,
type TurnWorkflowDispatchInput,
} from "#execution/durable-session-migrations/turn-workflow.js";
+import { readAcceptedDeploymentId } from "#execution/accepted-delivery-deployment.js";
import { buildTurnAttributes, readRootSessionId } from "#execution/eve-workflow-attributes.js";
-import { startWorkflowPreferLatest, turnWorkflowReference } from "#execution/workflow-runtime.js";
+import {
+ startWorkflowPreferAcceptedDeployment,
+ turnWorkflowReference,
+} from "#execution/workflow-runtime.js";
import { normalizeEveAttributes } from "#runtime/attributes/normalize.js";
/** Starts a per-turn child workflow for the current driver session. */
@@ -12,9 +16,10 @@ export async function dispatchTurnStep(
): Promise<{ readonly runId: string }> {
"use step";
- const run = await startWorkflowPreferLatest(
+ const run = await startWorkflowPreferAcceptedDeployment(
turnWorkflowReference,
[createTurnWorkflowInput(input)],
+ readAcceptedDeploymentId(input.delivery),
{
allowReservedAttributes: true,
attributes: normalizeEveAttributes(
diff --git a/packages/eve/src/execution/durable-session-migrations/turn-workflow-v1-to-v2.ts b/packages/eve/src/execution/durable-session-migrations/turn-workflow-v1-to-v2.ts
new file mode 100644
index 000000000..e7a89c3b4
--- /dev/null
+++ b/packages/eve/src/execution/durable-session-migrations/turn-workflow-v1-to-v2.ts
@@ -0,0 +1,9 @@
+import type { VersionMigration } from "./chain.js";
+
+export const turnWorkflowInputV1ToV2: VersionMigration = {
+ from: 1,
+ migrate(prior) {
+ return { ...(prior as Record<string, unknown>), version: 2 };
+ },
+ to: 2,
+};
diff --git a/packages/eve/src/execution/durable-session-migrations/turn-workflow.test.ts b/packages/eve/src/execution/durable-session-migrations/turn-workflow.test.ts
index 23f73b004..7968a0ba7 100644
--- a/packages/eve/src/execution/durable-session-migrations/turn-workflow.test.ts
+++ b/packages/eve/src/execution/durable-session-migrations/turn-workflow.test.ts
@@ -62,6 +62,27 @@ describe("turn workflow wire migrations", () => {
});
});
+ it("migrates frozen v1 child inputs into the current continuation shape", () => {
+ const input = {
+ capabilities: undefined,
+ completionToken: "turn-token",
+ driverCapabilities: { cancelledTurnSettle: true as const, turnInbox: true as const },
+ mode: "conversation" as const,
+ stepInput: {
+ input: createDelivery(),
+ parentWritable: new WritableStream<Uint8Array>(),
+ serializedContext: { state: "v1" },
+ sessionState: createSessionState(),
+ },
+ version: 1 as const,
+ };
+
+ expect(migrateTurnWorkflowInput(input)).toEqual({
+ ...input,
+ version: TURN_WORKFLOW_INPUT_VERSION,
+ });
+ });
+
it("migrates pre-version (unversioned) workflow input into the current shape", () => {
const delivery = createDelivery();
const parentWritable = new WritableStream<Uint8Array>();
diff --git a/packages/eve/src/execution/durable-session-migrations/turn-workflow.ts b/packages/eve/src/execution/durable-session-migrations/turn-workflow.ts
index d8119e5a2..562ad914e 100644
--- a/packages/eve/src/execution/durable-session-migrations/turn-workflow.ts
+++ b/packages/eve/src/execution/durable-session-migrations/turn-workflow.ts
@@ -18,11 +18,14 @@ import type {
import type { DurableSessionState } from "#execution/durable-session-store.js";
import type { RuntimeActionResult } from "#shared/action-types.js";
import type { RunMode } from "#shared/run-mode.js";
+import type { DurableStepResult } from "#execution/next-driver-action.js";
+import type { TurnCancelPayload } from "#execution/turn-cancellation-token.js";
import { runMigrationChain, type VersionMigration } from "./chain.js";
import { turnWorkflowInputV0ToV1 } from "./turn-workflow-v0-to-v1.js";
+import { turnWorkflowInputV1ToV2 } from "./turn-workflow-v1-to-v2.js";
-export const TURN_WORKFLOW_INPUT_VERSION = 1;
+export const TURN_WORKFLOW_INPUT_VERSION = 2;
/** Trusted runtime-action results collected by the parent turn driver. */
interface RuntimeActionResultStepInput {
@@ -38,14 +41,15 @@ export type TurnStepPayload =
export interface TurnStepInput {
/** Cancellation signal forwarded into the turn step. */
readonly abortSignal?: AbortSignal;
+ /** Executes only on this Vercel deployment; mismatches defer before mutation. */
+ readonly acceptedDeploymentId?: string;
readonly input: TurnStepPayload | undefined;
readonly parentWritable: WritableStream<Uint8Array>;
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
}
-export interface TurnWorkflowInput {
- readonly version: typeof TURN_WORKFLOW_INPUT_VERSION;
+interface TurnWorkflowInputBase {
readonly capabilities: SessionCapabilities | undefined;
readonly completionToken: string;
/**
@@ -60,23 +64,53 @@ export interface TurnWorkflowInput {
readonly stepInput: TurnStepInput;
}
+/** A step completed inline before the turn needed its child workflow. */
+export interface InitialTurnStep {
+ readonly beforeStep: {
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+ };
+ readonly result: DurableStepResult;
+}
+
+export type TurnWorkflowInput = TurnWorkflowInputBase &
+ (
+ | {
+ readonly initialCancellation?: undefined;
+ readonly initialStep?: undefined;
+ readonly version: 1;
+ }
+ | {
+ readonly initialCancellation?: TurnCancelPayload;
+ readonly initialStep?: InitialTurnStep;
+ readonly version: typeof TURN_WORKFLOW_INPUT_VERSION;
+ }
+ );
+
export interface TurnWorkflowDispatchInput {
readonly capabilities: SessionCapabilities | undefined;
readonly completionToken: string;
readonly delivery: HookPayload;
readonly mode: RunMode;
+ readonly initialStep?: InitialTurnStep;
+ readonly initialCancellation?: TurnCancelPayload;
readonly parentWritable: WritableStream<Uint8Array>;
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
}
-const turnWorkflowInputMigrations: readonly VersionMigration[] = [turnWorkflowInputV0ToV1];
+const turnWorkflowInputMigrations: readonly VersionMigration[] = [
+ turnWorkflowInputV0ToV1,
+ turnWorkflowInputV1ToV2,
+];
export function createTurnWorkflowInput(input: TurnWorkflowDispatchInput): TurnWorkflowInput {
return {
capabilities: input.capabilities,
completionToken: input.completionToken,
driverCapabilities: { cancelledTurnSettle: true, turnInbox: true },
+ initialCancellation: input.initialCancellation,
+ initialStep: input.initialStep,
mode: input.mode,
stepInput: {
input: input.delivery,
diff --git a/packages/eve/src/execution/inline-turn.ts b/packages/eve/src/execution/inline-turn.ts
new file mode 100644
index 000000000..f00a8190e
--- /dev/null
+++ b/packages/eve/src/execution/inline-turn.ts
@@ -0,0 +1,285 @@
+import type { DeliverHookPayload, HookPayload, SessionCapabilities } from "#channel/types.js";
+import { readAcceptedDeploymentId } from "#execution/accepted-delivery-deployment.js";
+import type {
+ InitialTurnStep,
+ TurnStepPayload,
+} from "#execution/durable-session-migrations/turn-workflow.js";
+import type { DurableSessionState } from "#execution/durable-session-store.js";
+import type { DurableStepResult, NextDriverAction } from "#execution/next-driver-action.js";
+import { reportDroppedWirePayloadStep } from "#execution/report-dropped-wire-payload-step.js";
+import type { SessionCommandInbox, SessionInboxPayload } from "#execution/session-command-inbox.js";
+import { SessionStateCursor } from "#execution/session-state-cursor.js";
+import type { TurnCancelPayload } from "#execution/turn-cancellation-token.js";
+import {
+ sessionInboxWire,
+ SessionInboxWireError,
+ type DecodedSessionInbox,
+} from "#execution/wire/session-inbox-wire.js";
+import { turnStep } from "#execution/workflow-steps.js";
+import { activeTurnId } from "#harness/active-turn-id.js";
+import { TurnCancelledError } from "#harness/turn-cancellation.js";
+import type { RunMode } from "#shared/run-mode.js";
+
+export type InlineTurnOutcome =
+ | {
+ readonly initialCancellation?: TurnCancelPayload;
+ readonly initialStep?: InitialTurnStep;
+ readonly kind: "child";
+ }
+ | { readonly action: NextDriverAction; readonly kind: "result" };
+
+/** Runs ordinary same-deployment turn steps inline and hands complex work to the child path. */
+export async function runInlineTurn(input: {
+ readonly bufferedDeliveries: DeliverHookPayload[];
+ readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;
+ readonly cancelledTaskIds?: Set<string>;
+ readonly capabilities?: SessionCapabilities;
+ readonly commandInbox: SessionCommandInbox;
+ readonly delivery: HookPayload;
+ readonly mode: RunMode;
+ readonly parentWritable: WritableStream<Uint8Array>;
+ readonly seenTaskDeliveries?: Set<string>;
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+}): Promise<InlineTurnOutcome> {
+ const acceptedDeploymentId = readAcceptedDeploymentId(input.delivery);
+ if (acceptedDeploymentId === undefined) return { kind: "child" };
+
+ const control = new InlineTurnControl({
+ bufferedDeliveries: input.bufferedDeliveries,
+ bufferedSessionControls: input.bufferedSessionControls,
+ cancelledTaskIds: input.cancelledTaskIds,
+ commandInbox: input.commandInbox,
+ expectedTurnId: activeTurnId(input.sessionState.emissionState),
+ seenTaskDeliveries: input.seenTaskDeliveries,
+ });
+ const cursor = new SessionStateCursor({
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
+ });
+ let nextStepInput: TurnStepPayload | undefined = input.delivery;
+
+ while (true) {
+ const beforeStep = {
+ serializedContext: cursor.serializedContext,
+ sessionState: cursor.sessionState,
+ };
+ const result = await control.waitForStep(
+ turnStep({
+ abortSignal: control.signal,
+ acceptedDeploymentId,
+ input: nextStepInput,
+ parentWritable: input.parentWritable,
+ serializedContext: cursor.serializedContext,
+ sessionState: cursor.sessionState,
+ }),
+ );
+
+ if (result.requiresChildDispatch === true) {
+ return childOutcome(control);
+ }
+
+ const initialStep = { beforeStep, result } satisfies InitialTurnStep;
+ if (
+ control.initialCancellation !== undefined ||
+ result.action === "cancelled" ||
+ result.sleepDurationMs !== undefined ||
+ (result.backgroundTasks?.length ?? 0) > 0
+ ) {
+ return childOutcome(control, initialStep);
+ }
+
+ if (result.action === "done") {
+ return {
+ action: {
+ isError: result.isError,
+ kind: "done",
+ output: result.output ?? "",
+ serializedContext: result.serializedContext,
+ sessionState: result.sessionState,
+ usage: result.usage,
+ usageDelta: result.usageDelta,
+ },
+ kind: "result",
+ };
+ }
+
+ if (
+ result.action === "dispatch-workflow-runtime-actions" ||
+ (result.action === "park" && result.pendingRuntimeActionKeys !== undefined)
+ ) {
+ return childOutcome(control, initialStep);
+ }
+
+ if (result.action === "park") {
+ const canPark =
+ result.hasPendingAuthorization ||
+ (result.hasPendingInputBatch && input.capabilities?.requestInput === true) ||
+ input.mode === "conversation";
+ if (!canPark) return childOutcome(control, initialStep);
+ return {
+ action: {
+ authorizationAttemptIds: result.authorizationAttemptIds,
+ authorizationNames: result.authorizationNames,
+ kind: "park",
+ serializedContext: result.serializedContext,
+ sessionState: result.sessionState,
+ settled: result.settled,
+ },
+ kind: "result",
+ };
+ }
+
+ const previousContinuationToken = cursor.sessionState.continuationToken;
+ cursor.adoptState(result);
+ if (
+ cursor.sessionState.continuationToken !== "" &&
+ cursor.sessionState.continuationToken !== previousContinuationToken
+ ) {
+ await input.commandInbox.rekeyContinuation(cursor.sessionState.continuationToken);
+ }
+ nextStepInput = undefined;
+ }
+}
+
+function childOutcome(
+ control: InlineTurnControl,
+ initialStep?: InitialTurnStep,
+): Extract<InlineTurnOutcome, { readonly kind: "child" }> {
+ return {
+ initialCancellation: control.initialCancellation,
+ initialStep,
+ kind: "child",
+ };
+}
+
+class InlineTurnControl {
+ private readonly bufferedDeliveries: DeliverHookPayload[];
+ private readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;
+ private readonly cancelledTaskIds: Set<string>;
+ private readonly commandInbox: SessionCommandInbox;
+ private readonly controller = new AbortController();
+ private readonly expectedTurnId: string;
+ private readonly seenTaskDeliveries: Set<string>;
+ private cancellation: TurnCancelPayload | undefined;
+
+ constructor(input: {
+ readonly bufferedDeliveries: DeliverHookPayload[];
+ readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;
+ readonly cancelledTaskIds?: Set<string>;
+ readonly commandInbox: SessionCommandInbox;
+ readonly expectedTurnId: string;
+ readonly seenTaskDeliveries?: Set<string>;
+ }) {
+ this.bufferedDeliveries = input.bufferedDeliveries;
+ this.bufferedSessionControls = input.bufferedSessionControls;
+ this.cancelledTaskIds = input.cancelledTaskIds ?? new Set();
+ this.commandInbox = input.commandInbox;
+ this.expectedTurnId = input.expectedTurnId;
+ this.seenTaskDeliveries = input.seenTaskDeliveries ?? new Set();
+ }
+
+ get initialCancellation(): TurnCancelPayload | undefined {
+ return this.cancellation;
+ }
+
+ get signal(): AbortSignal {
+ return this.controller.signal;
+ }
+
+ async waitForStep(step: Promise<DurableStepResult>): Promise<DurableStepResult> {
+ const settled = step.then((result) => ({ kind: "step" as const, result }));
+ while (true) {
+ const winner = await Promise.race([
+ settled,
+ this.commandInbox.next().then((result) => ({ kind: "command" as const, result })),
+ ]);
+ if (winner.kind === "step") return winner.result;
+ if (winner.result.done) {
+ throw new Error("Session command inbox closed before the inline turn step settled.");
+ }
+ this.commandInbox.consumeNext();
+ await this.handle(winner.result.value);
+ }
+ }
+
+ private abort(payload: TurnCancelPayload): void {
+ if (this.controller.signal.aborted) return;
+ this.cancellation = payload;
+ this.controller.abort(new TurnCancelledError());
+ }
+
+ private acceptTaskDelivery(command: DeliverHookPayload): boolean {
+ const deliveryId = command.taskDeliveryId ?? command.caller?.taskId;
+ if (deliveryId === undefined) return true;
+ if (this.originatesFromCancelledTask(deliveryId)) return false;
+ if (this.seenTaskDeliveries.has(deliveryId)) return false;
+ this.seenTaskDeliveries.add(deliveryId);
+ return true;
+ }
+
+ private async handle(value: SessionInboxPayload): Promise<void> {
+ if (value.kind === "runtime-action-result") return;
+ let command: DecodedSessionInbox;
+ try {
+ command = sessionInboxWire.decode(value);
+ } catch (error) {
+ if (!(error instanceof SessionInboxWireError)) throw error;
+ await reportDroppedWirePayloadStep({ detail: error.message, family: "session-inbox" });
+ return;
+ }
+
+ if (command.kind === "deliver") {
+ if (!this.acceptTaskDelivery(command)) return;
+ this.bufferedDeliveries.push(command);
+ if (command.turnPolicy === "steer" && deliveryHasMessage(command)) this.abort({});
+ return;
+ }
+ if (command.kind === "clear" || command.kind === "compact") {
+ this.bufferedSessionControls.push(command.kind);
+ return;
+ }
+ if (command.kind === "session-timeout") {
+ this.bufferedSessionControls.push("expired");
+ return;
+ }
+ if (command.kind === "reset") {
+ this.bufferedSessionControls.push("reset");
+ this.abort({});
+ return;
+ }
+ if (command.kind === "cancel") {
+ if (command.taskId !== undefined) this.discardTaskDeliveries(command.taskId);
+ const turnId =
+ command.taskId !== undefined &&
+ command.turnId !== undefined &&
+ command.turnId !== this.expectedTurnId
+ ? undefined
+ : command.turnId;
+ if (turnId === undefined || turnId === this.expectedTurnId) {
+ this.abort(turnId === undefined ? {} : { turnId });
+ }
+ }
+ }
+
+ private discardTaskDeliveries(taskId: string): void {
+ this.cancelledTaskIds.add(taskId);
+ const kept = this.bufferedDeliveries.filter((delivery) => !this.shouldDiscard(delivery));
+ this.bufferedDeliveries.splice(0, this.bufferedDeliveries.length, ...kept);
+ }
+
+ private originatesFromCancelledTask(deliveryId: string): boolean {
+ return [...this.cancelledTaskIds].some(
+ (taskId) => deliveryId === taskId || deliveryId.startsWith(`${taskId}:`),
+ );
+ }
+
+ private shouldDiscard(delivery: DeliverHookPayload): boolean {
+ const deliveryId = delivery.taskDeliveryId ?? delivery.caller?.taskId;
+ return deliveryId !== undefined && this.originatesFromCancelledTask(deliveryId);
+ }
+}
+
+function deliveryHasMessage(delivery: DeliverHookPayload): boolean {
+ return delivery.payloads.some((payload) => payload.message !== undefined);
+}
diff --git a/packages/eve/src/execution/next-driver-action.ts b/packages/eve/src/execution/next-driver-action.ts
index f776c7070..5b339a3dc 100644
--- a/packages/eve/src/execution/next-driver-action.ts
+++ b/packages/eve/src/execution/next-driver-action.ts
@@ -18,6 +18,8 @@ import type { TokenUsage } from "#shared/token-usage.js";
interface DurableStepResultFields {
readonly backgroundTaskState?: DurableSessionState;
readonly backgroundTasks?: StepResult["backgroundTasks"];
+ /** The guarded inline step deferred before mutating state. */
+ readonly requiresChildDispatch?: true;
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
}
diff --git a/packages/eve/src/execution/session-command-token.ts b/packages/eve/src/execution/session-command-token.ts
index d915075f2..73122b9b6 100644
--- a/packages/eve/src/execution/session-command-token.ts
+++ b/packages/eve/src/execution/session-command-token.ts
@@ -5,6 +5,14 @@ export function isReservedSessionCommandToken(token: string): boolean {
return token.startsWith(`${SESSION_COMMAND_NAMESPACE}:`);
}
+/** Returns whether a token is the stable command inbox for one workflow run. */
+export function isSessionCommandHookToken(token: string): boolean {
+ const prefix = `${SESSION_COMMAND_NAMESPACE}:`;
+ const suffix = ":inbox";
+ if (!token.startsWith(prefix) || !token.endsWith(suffix)) return false;
+ return !token.slice(prefix.length, -suffix.length).includes(":");
+}
+
/** Derives the framework-reserved stable command inbox token for a session. */
export function sessionCommandHookToken(sessionId: string): string {
return `${SESSION_COMMAND_NAMESPACE}:${sessionId}:inbox`;
diff --git a/packages/eve/src/execution/turn-cancellation-control.test.ts b/packages/eve/src/execution/turn-cancellation-control.test.ts
index 03d8bd784..3cd48c7d8 100644
--- a/packages/eve/src/execution/turn-cancellation-control.test.ts
+++ b/packages/eve/src/execution/turn-cancellation-control.test.ts
@@ -91,6 +91,20 @@ describe("createTurnCancellationControl", () => {
expect(control!.signal.aborted).toBe(true);
});
+ it("starts aborted when inline execution already consumed cancellation", async () => {
+ installCancelHook({ payloads: [] });
+
+ const control = await createTurnCancellationControl({
+ controlToken: "session-1",
+ expectedTurnId: "turn_2",
+ initialPayload: { turnId: "turn_2" },
+ });
+
+ await expect(control!.requested).resolves.toBe("cancel");
+ expect(control!.signal.aborted).toBe(true);
+ expect(control!.signal.reason).toBeInstanceOf(TurnCancelledError);
+ });
+
it("consumes a stale turn guard as a no-op and honors the next matching cancel", async () => {
installCancelHook({ payloads: [{ turnId: "turn_99" }, { turnId: "turn_2" }] });
diff --git a/packages/eve/src/execution/turn-cancellation-control.ts b/packages/eve/src/execution/turn-cancellation-control.ts
index bbb926c38..7b55768db 100644
--- a/packages/eve/src/execution/turn-cancellation-control.ts
+++ b/packages/eve/src/execution/turn-cancellation-control.ts
@@ -34,6 +34,7 @@ export interface TurnCancellationControl {
export async function createTurnCancellationControl(input: {
readonly controlToken: string;
readonly expectedTurnId: string;
+ readonly initialPayload?: TurnCancelPayload;
}): Promise<TurnCancellationControl | undefined> {
const hook = createHook<TurnCancelPayload>({
token: turnCancellationHookToken(input.controlToken),
@@ -55,9 +56,14 @@ export async function createTurnCancellationControl(input: {
// `.then` — so the signal is already flipped when a same-drain
// continuation (the turn loop's settle check) reads it; one microtask
// later and an ordinary completion swallows the cancel.
- const requested = consumeMatchingCancel(iterator, input.expectedTurnId, () => {
- controller.abort(new TurnCancelledError());
- }).then(() => "cancel" as const);
+ const abort = () => controller.abort(new TurnCancelledError());
+ const initiallyCancelled =
+ input.initialPayload !== undefined &&
+ matchesActiveTurn(input.initialPayload, input.expectedTurnId);
+ if (initiallyCancelled) abort();
+ const requested = initiallyCancelled
+ ? Promise.resolve("cancel" as const)
+ : consumeMatchingCancel(iterator, input.expectedTurnId, abort).then(() => "cancel" as const);
let disposed = false;
return {
diff --git a/packages/eve/src/execution/turn-dispatch.test.ts b/packages/eve/src/execution/turn-dispatch.test.ts
index fd745a040..c82fe7c19 100644
--- a/packages/eve/src/execution/turn-dispatch.test.ts
+++ b/packages/eve/src/execution/turn-dispatch.test.ts
@@ -2,10 +2,12 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import type { DeliverHookPayload } from "#channel/types.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
+import { dispatchTurnStep } from "#execution/dispatch-turn-step.js";
import { forwardTurnDeliveryStep } from "#execution/forward-turn-delivery-step.js";
import { dispatchAndAwaitTurn } from "#execution/turn-dispatch.js";
import type { SessionCommandInbox, SessionInboxPayload } from "#execution/session-command-inbox.js";
import type { TurnControlPayload } from "#execution/turn-control-protocol.js";
+import { turnStep } from "#execution/workflow-steps.js";
const createHookMock = vi.fn();
@@ -21,6 +23,10 @@ vi.mock("./forward-turn-delivery-step.js", () => ({
forwardTurnDeliveryStep: vi.fn(),
}));
+vi.mock("./workflow-steps.js", () => ({
+ turnStep: vi.fn(),
+}));
+
describe("dispatchAndAwaitTurn", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -226,6 +232,194 @@ describe("dispatchAndAwaitTurn", () => {
await turn.dispose();
expect(hook.dispose).toHaveBeenCalledOnce();
});
+
+ it("settles an ordinary same-deployment turn without a child workflow", async () => {
+ const state = createState("http:test");
+ vi.mocked(turnStep).mockResolvedValueOnce({
+ action: "park",
+ hasPendingAuthorization: false,
+ hasPendingInputBatch: false,
+ serializedContext: { state: "settled" },
+ sessionState: state,
+ settled: { output: "ok" },
+ });
+
+ const turn = await dispatchAndAwaitTurn({
+ bufferedDeliveries: [],
+ bufferedSessionControls: [],
+ commandInbox: createCommandInbox(),
+ controlToken: "turn-control",
+ delivery: createAcceptedDelivery(),
+ mode: "conversation",
+ parentWritable: new WritableStream<Uint8Array>(),
+ serializedContext: { state: "start" },
+ sessionState: state,
+ });
+
+ expect(turn.action).toMatchObject({ kind: "park", settled: { output: "ok" } });
+ expect(turnStep).toHaveBeenCalledWith(
+ expect.objectContaining({ acceptedDeploymentId: "dpl_current" }),
+ );
+ expect(dispatchTurnStep).not.toHaveBeenCalled();
+ expect(createHookMock).not.toHaveBeenCalled();
+ });
+
+ it("keeps ordinary tool-loop continuations inline", async () => {
+ const firstState = createState("http:test:rekeyed");
+ const finalState = createState("http:test:rekeyed");
+ vi.mocked(turnStep)
+ .mockResolvedValueOnce({
+ action: "continue",
+ serializedContext: { state: "continued" },
+ sessionState: firstState,
+ })
+ .mockResolvedValueOnce({
+ action: "done",
+ output: "complete",
+ serializedContext: { state: "done" },
+ sessionState: finalState,
+ });
+ const commandInbox = createCommandInbox();
+
+ const turn = await dispatchAndAwaitTurn({
+ bufferedDeliveries: [],
+ bufferedSessionControls: [],
+ commandInbox,
+ controlToken: "turn-control",
+ delivery: createAcceptedDelivery(),
+ mode: "conversation",
+ parentWritable: new WritableStream<Uint8Array>(),
+ serializedContext: { state: "start" },
+ sessionState: createState("http:test"),
+ });
+
+ expect(turn.action).toMatchObject({ kind: "done", output: "complete" });
+ expect(vi.mocked(turnStep).mock.calls[1]?.[0].input).toBeUndefined();
+ expect(commandInbox.rekeyContinuation).toHaveBeenCalledWith("http:test:rekeyed");
+ expect(dispatchTurnStep).not.toHaveBeenCalled();
+ });
+
+ it("hands an already-completed complex step to the child workflow", async () => {
+ const state = createState("http:test");
+ const result = {
+ action: "park" as const,
+ hasPendingAuthorization: false,
+ hasPendingInputBatch: false,
+ pendingRuntimeActionKeys: ["subagent-call:delegate:call-1"],
+ serializedContext: { state: "pending" },
+ sessionState: state,
+ };
+ vi.mocked(turnStep).mockResolvedValueOnce(result);
+ installControlHook([
+ {
+ action: { kind: "park", serializedContext: result.serializedContext, sessionState: state },
+ kind: "turn-result",
+ },
+ ]);
+
+ await dispatchAndAwaitTurn({
+ bufferedDeliveries: [],
+ bufferedSessionControls: [],
+ commandInbox: createCommandInbox(),
+ controlToken: "turn-control",
+ delivery: createAcceptedDelivery(),
+ mode: "conversation",
+ parentWritable: new WritableStream<Uint8Array>(),
+ serializedContext: { state: "start" },
+ sessionState: state,
+ });
+
+ expect(dispatchTurnStep).toHaveBeenCalledWith(
+ expect.objectContaining({
+ initialStep: {
+ beforeStep: expect.objectContaining({ serializedContext: { state: "start" } }),
+ result,
+ },
+ }),
+ );
+ });
+
+ it("defers a guarded deployment mismatch without consuming the delivery", async () => {
+ const state = createState("http:test");
+ vi.mocked(turnStep).mockResolvedValueOnce({
+ action: "continue",
+ requiresChildDispatch: true,
+ serializedContext: { state: "start" },
+ sessionState: state,
+ });
+ installControlHook([
+ {
+ action: { kind: "park", serializedContext: {}, sessionState: state },
+ kind: "turn-result",
+ },
+ ]);
+
+ await dispatchAndAwaitTurn({
+ bufferedDeliveries: [],
+ bufferedSessionControls: [],
+ commandInbox: createCommandInbox(),
+ controlToken: "turn-control",
+ delivery: createAcceptedDelivery(),
+ mode: "conversation",
+ parentWritable: new WritableStream<Uint8Array>(),
+ serializedContext: { state: "start" },
+ sessionState: state,
+ });
+
+ expect(dispatchTurnStep).toHaveBeenCalledWith(
+ expect.objectContaining({ initialStep: undefined }),
+ );
+ });
+
+ it("carries inline cancellation into the continued child turn", async () => {
+ const state = createState("http:test");
+ vi.mocked(turnStep).mockImplementationOnce(async (input) => {
+ await vi.waitFor(() => expect(input.abortSignal?.aborted).toBe(true));
+ return {
+ action: "cancelled",
+ serializedContext: { state: "cancelled" },
+ sessionState: state,
+ };
+ });
+ let delivered = false;
+ const commandInbox = createCommandInbox({
+ next: vi.fn(async () => {
+ if (!delivered) {
+ delivered = true;
+ return { done: false as const, value: { kind: "cancel" as const } };
+ }
+ return await new Promise<IteratorResult<SessionInboxPayload>>(() => {});
+ }),
+ });
+ installControlHook([
+ {
+ action: { cancelled: true, kind: "park", serializedContext: {}, sessionState: state },
+ kind: "turn-result",
+ },
+ ]);
+
+ await dispatchAndAwaitTurn({
+ bufferedDeliveries: [],
+ bufferedSessionControls: [],
+ commandInbox,
+ controlToken: "turn-control",
+ delivery: createAcceptedDelivery(),
+ mode: "conversation",
+ parentWritable: new WritableStream<Uint8Array>(),
+ serializedContext: { state: "start" },
+ sessionState: state,
+ });
+
+ expect(dispatchTurnStep).toHaveBeenCalledWith(
+ expect.objectContaining({
+ initialCancellation: {},
+ initialStep: expect.objectContaining({
+ result: expect.objectContaining({ action: "cancelled" }),
+ }),
+ }),
+ );
+ expect(commandInbox.consumeNext).toHaveBeenCalledOnce();
+ });
});
function createCommandInbox(overrides: Partial<SessionCommandInbox> = {}): SessionCommandInbox {
@@ -276,3 +470,19 @@ function createState(continuationToken: string): DurableSessionState {
version: 1,
};
}
+
+function createAcceptedDelivery(): DeliverHookPayload {
+ return {
+ deliveryMetadata: [
+ {
+ acceptedDeploymentId: "dpl_current",
+ channelKind: "channel:test",
+ channelName: "test",
+ deliveryId: "delivery-1",
+ payloadIndex: 0,
+ },
+ ],
+ kind: "deliver",
+ payloads: [{ message: "start" }],
+ };
+}
diff --git a/packages/eve/src/execution/turn-dispatch.ts b/packages/eve/src/execution/turn-dispatch.ts
index 545dcc3e8..efba94ad8 100644
--- a/packages/eve/src/execution/turn-dispatch.ts
+++ b/packages/eve/src/execution/turn-dispatch.ts
@@ -2,7 +2,13 @@ import type { DeliverHookPayload, HookPayload, SessionCapabilities } from "#chan
import { dispatchTurnStep } from "#execution/dispatch-turn-step.js";
import { TurnControlReceiver } from "#execution/turn-control-receiver.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
+import type {
+ InitialTurnStep,
+ TurnWorkflowDispatchInput,
+} from "#execution/durable-session-migrations/turn-workflow.js";
+import { runInlineTurn } from "#execution/inline-turn.js";
import type { SessionCommandInbox } from "#execution/session-command-inbox.js";
+import type { TurnCancelPayload } from "#execution/turn-cancellation-token.js";
import type { TurnDriverAction } from "#execution/turn-control-receiver.js";
import type { RunMode } from "#shared/run-mode.js";
import { activeTurnId } from "#harness/active-turn-id.js";
@@ -22,7 +28,7 @@ export interface DispatchedTurn {
}
/** Dispatches one turn and services its private-inbox control protocol until it terminates. */
-export async function dispatchAndAwaitTurn(input: {
+interface TurnDispatchInput {
readonly bufferedDeliveries: DeliverHookPayload[];
readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;
readonly capabilities?: SessionCapabilities;
@@ -35,7 +41,26 @@ export async function dispatchAndAwaitTurn(input: {
readonly serializedContext: Record<string, unknown>;
readonly seenTaskDeliveries?: Set<string>;
readonly sessionState: DurableSessionState;
-}): Promise<DispatchedTurn> {
+}
+
+export async function dispatchAndAwaitTurn(input: TurnDispatchInput): Promise<DispatchedTurn> {
+ const inline = await runInlineTurn(input);
+ if (inline.kind === "result") {
+ return { action: inline.action, async dispose() {} };
+ }
+ return await dispatchAndAwaitChildTurn({
+ ...input,
+ initialCancellation: inline.initialCancellation,
+ initialStep: inline.initialStep,
+ });
+}
+
+async function dispatchAndAwaitChildTurn(
+ input: TurnDispatchInput & {
+ readonly initialCancellation?: TurnCancelPayload;
+ readonly initialStep?: InitialTurnStep;
+ },
+): Promise<DispatchedTurn> {
const control = new TurnControlReceiver({
bufferedDeliveries: input.bufferedDeliveries,
bufferedSessionControls: input.bufferedSessionControls,
@@ -51,11 +76,13 @@ export async function dispatchAndAwaitTurn(input: {
capabilities: input.capabilities,
completionToken: control.token,
delivery: input.delivery,
+ initialCancellation: input.initialCancellation,
+ initialStep: input.initialStep,
mode: input.mode,
parentWritable: input.parentWritable,
serializedContext: input.serializedContext,
sessionState: input.sessionState,
- });
+ } satisfies TurnWorkflowDispatchInput);
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.ts
index 3e08c66dd..9172d9db8 100644
--- a/packages/eve/src/execution/turn-workflow.test.ts
+++ b/packages/eve/src/execution/turn-workflow.test.ts
@@ -116,6 +116,85 @@ describe("turnWorkflow", () => {
expect(createOwnerHookMock).not.toHaveBeenCalled();
});
+ it("continues from an inline step result without executing it twice", async () => {
+ const initialState = createSessionState();
+ const finalState = createSessionState({ continuationToken: "http:continued" });
+ installInbox([]);
+ const { input } = createInput({
+ driverCapabilities: { cancelledTurnSettle: true, turnInbox: true },
+ sessionState: initialState,
+ });
+
+ await turnWorkflow({
+ ...input,
+ initialStep: {
+ beforeStep: {
+ serializedContext: input.stepInput.serializedContext,
+ sessionState: initialState,
+ },
+ result: {
+ action: "done",
+ output: "already complete",
+ serializedContext: { state: "done" },
+ sessionState: finalState,
+ },
+ },
+ });
+
+ expect(turnStep).not.toHaveBeenCalled();
+ expect(resumeHookMock).toHaveBeenCalledWith(
+ "turn-token",
+ expect.objectContaining({
+ action: expect.objectContaining({ kind: "done", output: "already complete" }),
+ kind: "turn-result",
+ }),
+ );
+ });
+
+ it("keeps earlier inline state when cancellation wins over a completed step", async () => {
+ const initialState = createSessionState({ continuationToken: "http:initial" });
+ const beforeStepState = createSessionState({ continuationToken: "http:inline-checkpoint" });
+ const completedState = createSessionState({ continuationToken: "http:completed" });
+ installInbox([]);
+ const { input } = createInput({
+ driverCapabilities: { cancelledTurnSettle: true, turnInbox: true },
+ sessionState: initialState,
+ });
+
+ await turnWorkflow({
+ ...input,
+ initialCancellation: {},
+ initialStep: {
+ beforeStep: {
+ serializedContext: { state: "inline-checkpoint" },
+ sessionState: beforeStepState,
+ },
+ result: {
+ action: "done",
+ output: "must not complete",
+ serializedContext: { state: "done" },
+ sessionState: completedState,
+ },
+ },
+ });
+
+ expect(cancelDescendantTurnsStep).toHaveBeenCalledWith({
+ serializedContext: { state: "inline-checkpoint" },
+ sessionState: beforeStepState,
+ });
+ expect(resumeHookMock).toHaveBeenCalledWith(
+ "turn-token",
+ expect.objectContaining({
+ action: expect.objectContaining({
+ cancelled: true,
+ kind: "park",
+ sessionState: beforeStepState,
+ }),
+ kind: "turn-result",
+ }),
+ );
+ });
+
it("migrates a pre-version (unversioned) input and runs the first turn step", async () => {
const sessionState = createSessionState();
const parentWritable = new WritableStream<Uint8Array>();
diff --git a/packages/eve/src/execution/turn-workflow.ts b/packages/eve/src/execution/turn-workflow.ts
index 33108b5a3..da97c4132 100644
--- a/packages/eve/src/execution/turn-workflow.ts
+++ b/packages/eve/src/execution/turn-workflow.ts
@@ -81,11 +81,13 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {
// Hook promises and iterators share one durable cursor. Create the iterator before
// claiming so conflict replay is consumed by getConflict(), not a later iterator read.
const inboxReader = createChannelReader("inbox", inbox);
+ let initialStep = input.initialStep;
const cursor = new TurnExecutionCursor({
controlToken: input.completionToken,
parentWritable: input.stepInput.parentWritable,
- serializedContext: input.stepInput.serializedContext,
- sessionState: input.stepInput.sessionState,
+ serializedContext:
+ initialStep?.beforeStep.serializedContext ?? input.stepInput.serializedContext,
+ sessionState: initialStep?.beforeStep.sessionState ?? input.stepInput.sessionState,
});
// Delivery request ids stay unique across every wait in this turn. A forwarded
// delivery left unconsumed when one wait resolves would otherwise reuse a later
@@ -113,16 +115,20 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {
if (input.driverCapabilities?.cancelledTurnSettle === true) {
cancellation = await createTurnCancellationControl({
controlToken: input.completionToken,
- expectedTurnId: activeTurnId(input.stepInput.sessionState.emissionState),
+ expectedTurnId: activeTurnId(cursor.sessionState.emissionState),
+ initialPayload: input.initialCancellation,
});
}
while (true) {
- const beforeStep = {
+ const beforeStep = initialStep?.beforeStep ?? {
serializedContext: cursor.serializedContext,
sessionState: cursor.sessionState,
};
- const result = await turnStep(cursor.createStepInput(nextStepInput, cancellation?.signal));
+ const result =
+ initialStep?.result ??
+ (await turnStep(cursor.createStepInput(nextStepInput, cancellation?.signal)));
+ initialStep = undefined;
const pendingActionKeys =
result.action === "dispatch-workflow-runtime-actions" || result.action === "park"
? result.pendingRuntimeActionKeys
diff --git a/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v3.test.ts.snap b/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v3.test.ts.snap
new file mode 100644
index 000000000..31a68197b
--- /dev/null
+++ b/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v3.test.ts.snap
@@ -0,0 +1,3 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`session inbox wire v3 > pins the complete schema byte for byte 1`] = `"{"$schema":"https://json-schema.org/draft/2020-12/schema","oneOf":[{"additionalProperties":false,"properties":{"auth":{"anyOf":[{"additionalProperties":false,"properties":{"attributes":{"additionalProperties":{"anyOf":[{"type":"string"},{"items":{"type":"string"},"type":"array"}]},"propertyNames":{"type":"string"},"type":"object"},"authenticator":{"type":"string"},"issuer":{"type":"string"},"principalId":{"type":"string"},"principalType":{"type":"string"},"subject":{"type":"string"}},"required":["attributes","authenticator","principalId","principalType"],"type":"object"},{"type":"null"}]},"caller":{"additionalProperties":false,"properties":{"activityObserver":{"additionalProperties":false,"properties":{"sink":{"additionalProperties":false,"properties":{"url":{"type":"string"},"version":{"const":1,"type":"number"}},"required":["url","version"],"type":"object"},"workIdentity":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"id":{"type":"string"},"kind":{"enum":["root-turn","subagent","remote-agent","task"],"type":"string"},"name":{"type":"string"},"parentId":{"type":"string"},"rootSessionId":{"type":"string"},"rootTurnId":{"type":"string"},"sessionId":{"type":"string"},"turnId":{"type":"string"}},"required":["id","kind","rootSessionId","rootTurnId"],"type":"object"}},"required":["sink"],"type":"object"},"callId":{"type":"string"},"replyTo":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"hook","type":"string"},"token":{"type":"string"}},"required":["kind","token"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"callback","type":"string"},"token":{"type":"string"},"url":{"type":"string"}},"required":["kind","token","url"],"type":"object"}]},"subagentName":{"type":"string"},"taskId":{"type":"string"}},"required":["callId","replyTo","subagentName"],"type":"object"},"deliveryMetadata":{"items":{"additionalProperties":false,"properties":{"acceptedDeploymentId":{"type":"string"},"channelKind":{"type":"string"},"channelName":{"type":"string"},"deliveryId":{"type":"string"},"payloadIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"requestId":{"type":"string"},"requestTraceContext":{"additionalProperties":false,"properties":{"spanId":{"type":"string"},"traceFlags":{"type":"number"},"traceId":{"type":"string"}},"required":["spanId","traceFlags","traceId"],"type":"object"}},"required":["channelKind","channelName","deliveryId","payloadIndex"],"type":"object"},"type":"array"},"kind":{"const":"deliver","type":"string"},"payload":{"additionalProperties":{},"properties":{"context":{"items":{"type":"string"},"type":"array"},"inputResponses":{"items":{"additionalProperties":false,"properties":{"optionId":{"type":"string"},"requestId":{"type":"string"},"text":{"type":"string"}},"required":["requestId"],"type":"object"},"type":"array"},"message":{"anyOf":[{"type":"string"},{"items":{"oneOf":[{"additionalProperties":false,"properties":{"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"text":{"type":"string"},"type":{"const":"text","type":"string"}},"required":["text","type"],"type":"object"},{"additionalProperties":false,"properties":{"image":{},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"image","type":"string"}},"required":["image","type"],"type":"object"},{"additionalProperties":false,"properties":{"data":{},"filename":{"type":"string"},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"file","type":"string"}},"required":["data","mediaType","type"],"type":"object"}]},"type":"array"}]},"outputSchema":{},"task":{"additionalProperties":false,"properties":{"authorizationEvents":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childSessionId":{"type":"string"},"event":{},"kind":{"const":"subagent-authorization-event","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"inputRequests":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childContinuationToken":{"type":"string"},"childSessionId":{"type":"string"},"event":{"additionalProperties":false,"properties":{"requests":{"items":{"additionalProperties":false,"properties":{"action":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"input":{},"kind":{"const":"tool-call","type":"string"},"toolName":{"type":"string"}},"required":["callId","input","kind","toolName"],"type":"object"},"allowFreeform":{"description":"Whether the user may answer with freeform text instead of selecting one of the provided options.","type":"boolean"},"display":{"description":"Rendering hint: the channel uses this to pick a UX treatment.","enum":["confirmation","select","text"],"type":"string"},"kind":{"description":"Framework-owned request source used to resolve, route, and render the response.","enum":["question","session-limit","tool-approval"],"type":"string"},"options":{"description":"Selectable answer options to present to the user.","items":{"additionalProperties":false,"properties":{"description":{"description":"Optional additional context for this option.","type":"string"},"id":{"description":"Stable identifier for the option.","type":"string"},"label":{"description":"User-facing label for the option.","type":"string"},"style":{"description":"Visual treatment hint for the option.","enum":["primary","danger","default"],"type":"string"}},"required":["id","label"],"type":"object"},"type":"array"},"prompt":{"description":"The prompt to present to the user.","type":"string"},"requestId":{"description":"Stable identifier for this request.","type":"string"}},"required":["action","kind","prompt","requestId"],"type":"object"},"type":"array"},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"turnId":{"type":"string"}},"required":["requests","sequence","stepIndex","turnId"],"type":"object"},"kind":{"const":"subagent-input-request","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childContinuationToken","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"views":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"working","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"inputRequests":{"items":{},"type":"array"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"input_required","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","inputRequests","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"result","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"completed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"error","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"failed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"cancelled","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"}]},"type":"array"}},"type":"object"}},"type":"object"},"payloads":{"items":{"additionalProperties":{},"properties":{"context":{"items":{"type":"string"},"type":"array"},"inputResponses":{"items":{"additionalProperties":false,"properties":{"optionId":{"type":"string"},"requestId":{"type":"string"},"text":{"type":"string"}},"required":["requestId"],"type":"object"},"type":"array"},"message":{"anyOf":[{"type":"string"},{"items":{"oneOf":[{"additionalProperties":false,"properties":{"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"text":{"type":"string"},"type":{"const":"text","type":"string"}},"required":["text","type"],"type":"object"},{"additionalProperties":false,"properties":{"image":{},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"image","type":"string"}},"required":["image","type"],"type":"object"},{"additionalProperties":false,"properties":{"data":{},"filename":{"type":"string"},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"file","type":"string"}},"required":["data","mediaType","type"],"type":"object"}]},"type":"array"}]},"outputSchema":{},"task":{"additionalProperties":false,"properties":{"authorizationEvents":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childSessionId":{"type":"string"},"event":{},"kind":{"const":"subagent-authorization-event","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"inputRequests":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childContinuationToken":{"type":"string"},"childSessionId":{"type":"string"},"event":{"additionalProperties":false,"properties":{"requests":{"items":{"additionalProperties":false,"properties":{"action":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"input":{},"kind":{"const":"tool-call","type":"string"},"toolName":{"type":"string"}},"required":["callId","input","kind","toolName"],"type":"object"},"allowFreeform":{"description":"Whether the user may answer with freeform text instead of selecting one of the provided options.","type":"boolean"},"display":{"description":"Rendering hint: the channel uses this to pick a UX treatment.","enum":["confirmation","select","text"],"type":"string"},"kind":{"description":"Framework-owned request source used to resolve, route, and render the response.","enum":["question","session-limit","tool-approval"],"type":"string"},"options":{"description":"Selectable answer options to present to the user.","items":{"additionalProperties":false,"properties":{"description":{"description":"Optional additional context for this option.","type":"string"},"id":{"description":"Stable identifier for the option.","type":"string"},"label":{"description":"User-facing label for the option.","type":"string"},"style":{"description":"Visual treatment hint for the option.","enum":["primary","danger","default"],"type":"string"}},"required":["id","label"],"type":"object"},"type":"array"},"prompt":{"description":"The prompt to present to the user.","type":"string"},"requestId":{"description":"Stable identifier for this request.","type":"string"}},"required":["action","kind","prompt","requestId"],"type":"object"},"type":"array"},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"turnId":{"type":"string"}},"required":["requests","sequence","stepIndex","turnId"],"type":"object"},"kind":{"const":"subagent-input-request","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childContinuationToken","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"views":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"working","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"inputRequests":{"items":{},"type":"array"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"input_required","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","inputRequests","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"result","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"completed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"error","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"failed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"cancelled","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"}]},"type":"array"}},"type":"object"}},"type":"object"},"type":"array"},"requestId":{"type":"string"},"taskDeliveryId":{"type":"string"},"turnPolicy":{"enum":["queue","steer"],"type":"string"},"version":{"const":3,"type":"number"}},"required":["kind","payload","payloads","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"session-timeout","type":"string"},"version":{"const":3,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"clear","type":"string"},"version":{"const":3,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"compact","type":"string"},"version":{"const":3,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"reset","type":"string"},"reason":{"type":"string"},"version":{"const":3,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"cancel","type":"string"},"taskId":{"type":"string"},"turnId":{"type":"string"},"version":{"const":3,"type":"number"}},"required":["kind","version"],"type":"object"}]}"`;
diff --git a/packages/eve/src/execution/wire/session-inbox-contract.ts b/packages/eve/src/execution/wire/session-inbox-contract.ts
index c8b1e0212..a570b9645 100644
--- a/packages/eve/src/execution/wire/session-inbox-contract.ts
+++ b/packages/eve/src/execution/wire/session-inbox-contract.ts
@@ -1,5 +1,5 @@
/** Every explicit session-inbox wire version still supported by producers. */
-export const SESSION_INBOX_WIRE_VERSIONS = [1, 2] as const;
+export const SESSION_INBOX_WIRE_VERSIONS = [1, 2, 3] as const;
export type SessionInboxWireVersion = (typeof SESSION_INBOX_WIRE_VERSIONS)[number];
diff --git a/packages/eve/src/execution/wire/session-inbox-encoder.ts b/packages/eve/src/execution/wire/session-inbox-encoder.ts
index 405c3ecff..0c1aac606 100644
--- a/packages/eve/src/execution/wire/session-inbox-encoder.ts
+++ b/packages/eve/src/execution/wire/session-inbox-encoder.ts
@@ -11,6 +11,10 @@ import {
encodeSessionCommandV2,
type SessionInboxWireV2,
} from "#execution/wire/session-inbox-wire.v2.js";
+import {
+ encodeSessionCommandV3,
+ type SessionInboxWireV3,
+} from "#execution/wire/session-inbox-wire.v3.js";
import {
isSessionInboxWireVersion,
SessionInboxWireError,
@@ -22,19 +26,21 @@ import { encodeSessionCommandV0 } from "#execution/wire/session-inbox-wire.v0.js
type SessionInboxCommand = DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload;
/** Current wire type consumed after migration. */
-export type SessionInboxWire = SessionInboxWireV2;
+export type SessionInboxWire = SessionInboxWireV3;
type LegacySessionInboxWireTarget = Extract<SessionInboxWireTarget, { readonly version: 0 }>;
type VersionedSessionInboxEncoder = (command: SessionInboxCommand) => unknown;
const versionedEncoders = {
- 1: encodeSessionCommandV1,
- 2: encodeSessionCommandV2,
+ 1: (command: SessionInboxCommand) => encodeSessionCommandV1(withoutAcceptedDeployment(command)),
+ 2: (command: SessionInboxCommand) => encodeSessionCommandV2(withoutAcceptedDeployment(command)),
+ 3: encodeSessionCommandV3,
} satisfies Record<SessionInboxWireVersion, VersionedSessionInboxEncoder>;
/** Encodes a command for the selected session-inbox consumer. */
function encode(command: SessionInboxCommand, target: { readonly version: 1 }): SessionInboxWireV1;
function encode(command: SessionInboxCommand, target: { readonly version: 2 }): SessionInboxWireV2;
+function encode(command: SessionInboxCommand, target: { readonly version: 3 }): SessionInboxWireV3;
function encode(
command: SessionInboxCommand,
target: { readonly version: SessionInboxWireVersion },
@@ -46,21 +52,64 @@ function encode(
function encode(
command: SessionInboxCommand,
target: SessionInboxWireTarget,
-): SessionInboxWireV1 | SessionInboxWireV2 | Record<string, unknown>;
+): SessionInboxWireV1 | SessionInboxWireV2 | SessionInboxWireV3 | Record<string, unknown>;
function encode(
command: SessionInboxCommand,
target: SessionInboxWireTarget,
-): SessionInboxWireV1 | SessionInboxWireV2 | Record<string, unknown> {
+): SessionInboxWireV1 | SessionInboxWireV2 | SessionInboxWireV3 | Record<string, unknown> {
if (target.version === 0) {
- return encodeSessionCommandV0(encodeSessionCommandV1(command), target.variant);
+ const legacy = encodeSessionCommandV0(
+ encodeSessionCommandV1(withoutAcceptedDeployment(command)),
+ target.variant,
+ );
+ const legacyRecord = legacy as Record<string, unknown>;
+ const delivery = legacyRecord.delivery;
+ const acceptedDeploymentId = readAcceptedDeploymentId(command);
+ if (
+ target.variant !== "send" ||
+ acceptedDeploymentId === undefined ||
+ legacyRecord.kind !== "send" ||
+ typeof delivery !== "object" ||
+ delivery === null
+ ) {
+ return legacy;
+ }
+ return {
+ ...legacy,
+ delivery: { ...(delivery as Record<string, unknown>), acceptedDeploymentId },
+ };
}
if (isSessionInboxWireVersion(target.version)) {
- return versionedEncoders[target.version](command) as SessionInboxWireV1 | SessionInboxWireV2;
+ return versionedEncoders[target.version](command) as
+ | SessionInboxWireV1
+ | SessionInboxWireV2
+ | SessionInboxWireV3;
}
throw new SessionInboxWireError(
`Cannot encode session inbox payload for unknown wire version ${JSON.stringify((target as { version?: unknown }).version)}.`,
);
}
+function withoutAcceptedDeployment(command: SessionInboxCommand): SessionInboxCommand {
+ if (command.kind === "send" && command.delivery?.acceptedDeploymentId !== undefined) {
+ const { acceptedDeploymentId: _acceptedDeploymentId, ...delivery } = command.delivery;
+ return { ...command, delivery };
+ }
+ if (command.kind !== "deliver" || command.deliveryMetadata === undefined) return command;
+ return {
+ ...command,
+ deliveryMetadata: command.deliveryMetadata.map((metadata) => {
+ const { acceptedDeploymentId: _acceptedDeploymentId, ...legacy } = metadata;
+ return legacy;
+ }),
+ };
+}
+
+function readAcceptedDeploymentId(command: SessionInboxCommand): string | undefined {
+ if (command.kind === "send") return command.delivery?.acceptedDeploymentId;
+ if (command.kind !== "deliver") return undefined;
+ return command.deliveryMetadata?.find((metadata) => metadata.payloadIndex === 0)
+ ?.acceptedDeploymentId;
+}
/** Server/step-safe producer facade. */
export const sessionInboxWire = { encode } as const;
diff --git a/packages/eve/src/execution/wire/session-inbox-resume.test.ts b/packages/eve/src/execution/wire/session-inbox-resume.test.ts
index 6a3da7b97..144cc71a0 100644
--- a/packages/eve/src/execution/wire/session-inbox-resume.test.ts
+++ b/packages/eve/src/execution/wire/session-inbox-resume.test.ts
@@ -75,7 +75,63 @@ describe("session inbox target resolution", () => {
});
describe("resumeSessionInbox", () => {
- it("encodes for the resolved consumer and resumes the exact inspected hook", async () => {
+ it("resumes a compatible stable inbox by token without inspecting metadata", async () => {
+ const token = sessionCommandHookToken("session-1");
+ const hook = sessionHook("session-1", token, { sessionInboxWireVersion: 2 });
+ resumeHookMock.mockResolvedValue(hook);
+
+ await resumeSessionInbox(token, {
+ kind: "send",
+ payload: { message: "follow-up" },
+ });
+
+ expect(getHookByTokenMock).not.toHaveBeenCalled();
+ expect(resumeHookMock).toHaveBeenCalledWith(token, {
+ auth: undefined,
+ caller: undefined,
+ delivery: undefined,
+ kind: "send",
+ payload: { message: "follow-up" },
+ requestId: undefined,
+ taskDeliveryId: undefined,
+ turnPolicy: undefined,
+ });
+ });
+
+ it("strips an undefined activity observer from the stable fast path", async () => {
+ const token = sessionCommandHookToken("session-1");
+ const hook = sessionHook("session-1", token, { sessionInboxWireVersion: 2 });
+ resumeHookMock.mockResolvedValue(hook);
+
+ await resumeSessionInbox(token, {
+ caller: {
+ activityObserver: undefined,
+ callId: "call-1",
+ replyTo: { kind: "hook", token: "reply-1" },
+ subagentName: "researcher",
+ },
+ kind: "send",
+ payload: { message: "follow-up" },
+ });
+
+ expect(getHookByTokenMock).not.toHaveBeenCalled();
+ expect(resumeHookMock).toHaveBeenCalledWith(token, {
+ auth: undefined,
+ caller: {
+ callId: "call-1",
+ replyTo: { kind: "hook", token: "reply-1" },
+ subagentName: "researcher",
+ },
+ delivery: undefined,
+ kind: "send",
+ payload: { message: "follow-up" },
+ requestId: undefined,
+ taskDeliveryId: undefined,
+ turnPolicy: undefined,
+ });
+ });
+
+ it("encodes continuation delivery for the resolved consumer and resumes that hook", async () => {
const hook = sessionHook("session-1", "continuation-1", { sessionInboxWireVersion: 1 });
getHookByTokenMock.mockResolvedValue(hook);
resumeHookMock.mockResolvedValue(hook);
@@ -96,6 +152,48 @@ describe("resumeSessionInbox", () => {
version: 1,
});
});
+
+ it("inspects reserved session aliases outside the stable inbox", async () => {
+ const token = "eve:session:session-1:session-timeout";
+ const hook = sessionHook("session-1", token, { sessionInboxWireVersion: 1 });
+ getHookByTokenMock.mockResolvedValue(hook);
+ resumeHookMock.mockResolvedValue(hook);
+
+ await resumeSessionInbox(token, { kind: "session-timeout" });
+
+ expect(getHookByTokenMock).toHaveBeenCalledWith(token);
+ expect(resumeHookMock).toHaveBeenCalledWith(hook, {
+ kind: "session-timeout",
+ version: 1,
+ });
+ });
+
+ it("retains metadata negotiation when a stable delivery needs the current caller wire", async () => {
+ const token = sessionCommandHookToken("session-1");
+ const hook = sessionHook("session-1", token, { sessionInboxWireVersion: 2 });
+ getHookByTokenMock.mockResolvedValue(hook);
+ resumeHookMock.mockResolvedValue(hook);
+
+ await resumeSessionInbox(token, {
+ caller: {
+ activityObserver: { sink: { url: "https://example.com/activity", version: 1 } },
+ callId: "call-1",
+ replyTo: { kind: "hook", token: "reply-1" },
+ subagentName: "researcher",
+ },
+ kind: "send",
+ payload: { message: "follow-up" },
+ });
+
+ expect(getHookByTokenMock).toHaveBeenCalledWith(token);
+ expect(resumeHookMock).toHaveBeenCalledWith(
+ hook,
+ expect.objectContaining({
+ caller: expect.objectContaining({ activityObserver: expect.any(Object) }),
+ version: 2,
+ }),
+ );
+ });
});
function sessionHook(runId: string, token: string, metadata?: unknown) {
diff --git a/packages/eve/src/execution/wire/session-inbox-resume.ts b/packages/eve/src/execution/wire/session-inbox-resume.ts
index 2868dd7ab..8589a5e7d 100644
--- a/packages/eve/src/execution/wire/session-inbox-resume.ts
+++ b/packages/eve/src/execution/wire/session-inbox-resume.ts
@@ -5,7 +5,10 @@ import type {
SessionCommand,
SessionTimeoutHookPayload,
} from "#channel/types.js";
-import { sessionCommandHookToken } from "#execution/session-command-token.js";
+import {
+ isSessionCommandHookToken,
+ sessionCommandHookToken,
+} from "#execution/session-command-token.js";
import {
SESSION_INBOX_WIRE_VERSION_METADATA_KEY,
isSessionInboxWireVersion,
@@ -23,11 +26,26 @@ export async function resumeSessionInbox(
token: string,
command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload,
): Promise<ResumedSessionInboxHook> {
+ if (isStableInboxFastPathCompatible(token, command)) {
+ return await resumeHook(
+ token,
+ sessionInboxWire.encode(command, { variant: "send", version: 0 }),
+ );
+ }
+
const hook = await getHookByToken(token);
const target = await resolveSessionInboxWireTarget(hook);
return await resumeHook(hook, sessionInboxWire.encode(command, target));
}
+function isStableInboxFastPathCompatible(
+ token: string,
+ command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload,
+): boolean {
+ if (!isSessionCommandHookToken(token)) return false;
+ return !("caller" in command && command.caller?.activityObserver !== undefined);
+}
+
type SessionInboxHook = Awaited<ReturnType<typeof getHookByToken>>;
/** Selects the encoder understood by a persisted hook's consumer deployment. */
diff --git a/packages/eve/src/execution/wire/session-inbox-wire.ts b/packages/eve/src/execution/wire/session-inbox-wire.ts
index 9818a4710..4a129c6af 100644
--- a/packages/eve/src/execution/wire/session-inbox-wire.ts
+++ b/packages/eve/src/execution/wire/session-inbox-wire.ts
@@ -16,6 +16,7 @@ import type { SessionInboxWire } from "#execution/wire/session-inbox-encoder.js"
import { sessionInboxWireV0Migration } from "#execution/wire/session-inbox-wire.v0.js";
import { normalizeSessionInboxWireV2 } from "#execution/wire/session-inbox-wire.v2-migration.js";
import { sessionInboxWireV1Migration } from "#execution/wire/session-inbox-wire.v2.migration.js";
+import { sessionInboxWireV2Migration } from "#execution/wire/session-inbox-wire.v3.migration.js";
/**
* The session inbox wire family: every payload persisted to a session's
@@ -43,6 +44,7 @@ const WIRE_LABEL = "session inbox payload";
const sessionInboxMigrations: readonly VersionMigration[] = [
sessionInboxWireV0Migration,
sessionInboxWireV1Migration,
+ sessionInboxWireV2Migration,
];
/**
@@ -81,8 +83,15 @@ function decode(value: unknown): DecodedSessionInbox {
`${WIRE_LABEL} declares version ${JSON.stringify(wire.version)}, expected ${SESSION_INBOX_WIRE_VERSION}.`,
);
}
- if (declaredVersion === 2 && wire.kind === "deliver" && !("payload" in wire)) {
- throw new SessionInboxWireError(`${WIRE_LABEL} does not match wire version 2.`);
+ if (
+ typeof declaredVersion === "number" &&
+ declaredVersion >= 2 &&
+ wire.kind === "deliver" &&
+ !("payload" in wire)
+ ) {
+ throw new SessionInboxWireError(
+ `${WIRE_LABEL} does not match wire version ${declaredVersion}.`,
+ );
}
return normalizeWire(wire as SessionInboxWire);
}
diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v3.migration.test.ts b/packages/eve/src/execution/wire/session-inbox-wire.v3.migration.test.ts
new file mode 100644
index 000000000..daea1932a
--- /dev/null
+++ b/packages/eve/src/execution/wire/session-inbox-wire.v3.migration.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from "vitest";
+
+import { sessionInboxWireV2Migration } from "#execution/wire/session-inbox-wire.v3.migration.js";
+
+describe("session inbox wire v3 migration", () => {
+ it("stamps controls with version 3", () => {
+ expect(sessionInboxWireV2Migration.migrate({ kind: "clear", version: 2 })).toEqual({
+ kind: "clear",
+ version: 3,
+ });
+ });
+
+ it("preserves v2 deliveries without inventing deployment provenance", () => {
+ expect(
+ sessionInboxWireV2Migration.migrate({
+ kind: "deliver",
+ payload: { message: "legacy" },
+ payloads: [{ message: "legacy" }],
+ version: 2,
+ }),
+ ).toEqual({
+ kind: "deliver",
+ payload: { message: "legacy" },
+ payloads: [{ message: "legacy" }],
+ version: 3,
+ });
+ });
+});
diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v3.migration.ts b/packages/eve/src/execution/wire/session-inbox-wire.v3.migration.ts
new file mode 100644
index 000000000..f0817a52e
--- /dev/null
+++ b/packages/eve/src/execution/wire/session-inbox-wire.v3.migration.ts
@@ -0,0 +1,10 @@
+import type { VersionMigration } from "#execution/durable-session-migrations/chain.js";
+
+/** Pure shape migration from the immutable v2 wire contract to v3. */
+export const sessionInboxWireV2Migration: VersionMigration = {
+ from: 2,
+ migrate(prior) {
+ return { ...(prior as Record<string, unknown>), version: 3 };
+ },
+ to: 3,
+};
diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v3.test.ts b/packages/eve/src/execution/wire/session-inbox-wire.v3.test.ts
new file mode 100644
index 000000000..a8888c696
--- /dev/null
+++ b/packages/eve/src/execution/wire/session-inbox-wire.v3.test.ts
@@ -0,0 +1,108 @@
+import { describe, expect, it } from "vitest";
+import { z } from "#compiled/zod/index.js";
+
+import { sessionInboxWire as sessionInboxWireEncoder } from "#execution/wire/session-inbox-encoder.js";
+import { sessionInboxWire as sessionInboxWireDecoder } from "#execution/wire/session-inbox-wire.js";
+import { sessionInboxWireV0Migration } from "#execution/wire/session-inbox-wire.v0.js";
+import { normalizeSessionInboxWireV2 } from "#execution/wire/session-inbox-wire.v2-migration.js";
+import { sessionInboxWireV1Migration } from "#execution/wire/session-inbox-wire.v2.migration.js";
+import { sessionInboxWireV3Schema } from "#execution/wire/session-inbox-wire.v3.js";
+
+const delivery = {
+ acceptedDeploymentId: "dpl_current",
+ channelKind: "channel:webhook",
+ channelName: "webhook",
+ deliveryId: "delivery-1",
+};
+
+describe("session inbox wire v3", () => {
+ it("round-trips accepted deployment provenance", () => {
+ const wire = sessionInboxWireEncoder.encode(
+ { delivery, kind: "send", payload: { message: "hello" } },
+ { version: 3 },
+ );
+
+ expect(wire).toMatchObject({
+ deliveryMetadata: [{ ...delivery, payloadIndex: 0 }],
+ version: 3,
+ });
+ expect(sessionInboxWireDecoder.decode(JSON.parse(JSON.stringify(wire)))).toMatchObject({
+ deliveryMetadata: [{ ...delivery, payloadIndex: 0 }],
+ kind: "deliver",
+ });
+ });
+
+ it("omits deployment provenance for older versioned consumers", () => {
+ expect(
+ sessionInboxWireEncoder.encode(
+ { delivery, kind: "send", payload: { message: "hello" } },
+ { version: 2 },
+ ),
+ ).not.toHaveProperty("deliveryMetadata.0.acceptedDeploymentId");
+ });
+
+ it("carries deployment provenance through the stable raw-send fast path", () => {
+ const wire = sessionInboxWireEncoder.encode(
+ { delivery, kind: "send", payload: { message: "hello" } },
+ { variant: "send", version: 0 },
+ );
+
+ expect(wire).toMatchObject({ delivery, kind: "send" });
+ expect(sessionInboxWireDecoder.decode(JSON.parse(JSON.stringify(wire)))).toMatchObject({
+ deliveryMetadata: [{ ...delivery, payloadIndex: 0 }],
+ });
+ });
+
+ it("keeps stable raw sends readable by previous v2 consumers", () => {
+ const wire = sessionInboxWireEncoder.encode(
+ { delivery, kind: "send", payload: { message: "hello" } },
+ { variant: "send", version: 0 },
+ );
+ const v1 = sessionInboxWireV0Migration.migrate(normalizeSessionInboxWireV2(wire));
+ const v2 = normalizeSessionInboxWireV2(sessionInboxWireV1Migration.migrate(v1));
+
+ expect(v2).toMatchObject({
+ deliveryMetadata: [{ ...delivery, payloadIndex: 0 }],
+ kind: "deliver",
+ payloads: [{ message: "hello" }],
+ version: 2,
+ });
+ });
+
+ it("migrates frozen v2 deliveries without inventing provenance", () => {
+ expect(
+ sessionInboxWireDecoder.decode({
+ kind: "deliver",
+ payload: { message: "legacy" },
+ payloads: [{ message: "legacy" }],
+ version: 2,
+ }),
+ ).toEqual({
+ auth: undefined,
+ caller: undefined,
+ deliveryMetadata: undefined,
+ kind: "deliver",
+ payloads: [{ message: "legacy" }],
+ requestId: undefined,
+ taskDeliveryId: undefined,
+ turnPolicy: undefined,
+ });
+ });
+
+ it("pins the complete schema byte for byte", () => {
+ expect(
+ stableStringify(
+ z.toJSONSchema(sessionInboxWireV3Schema, { io: "input", unrepresentable: "any" }),
+ ),
+ ).toMatchSnapshot();
+ });
+});
+
+function stableStringify(value: unknown): string {
+ return JSON.stringify(value, (_key, item) => {
+ if (item === null || typeof item !== "object" || Array.isArray(item)) return item;
+ return Object.fromEntries(
+ Object.entries(item).sort(([left], [right]) => left.localeCompare(right)),
+ );
+ });
+}
diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v3.ts b/packages/eve/src/execution/wire/session-inbox-wire.v3.ts
new file mode 100644
index 000000000..6f81e72fa
--- /dev/null
+++ b/packages/eve/src/execution/wire/session-inbox-wire.v3.ts
@@ -0,0 +1,73 @@
+import { z } from "#compiled/zod/index.js";
+
+import type {
+ DeliverHookPayload,
+ SessionCommand,
+ SessionTimeoutHookPayload,
+} from "#channel/types.js";
+import { coalesceDeliverPayloads } from "#execution/deliver-payloads.js";
+import { SessionInboxWireError } from "#execution/wire/session-inbox-contract.js";
+import { normalizeSessionInboxWireV2 } from "#execution/wire/session-inbox-wire.v2-migration.js";
+import { sessionInboxWireV2Schema } from "#execution/wire/session-inbox-wire.v2.js";
+import { formatValidationError } from "#runtime/validation.js";
+
+const v2 = sessionInboxWireV2Schema.options;
+const v2Deliver = v2[0];
+const v2DeliveryMetadata = v2Deliver.shape.deliveryMetadata.unwrap().element;
+const version = z.literal(3);
+
+/** Version 3 adds the trusted deployment that accepted each channel delivery. */
+export const sessionInboxWireV3Schema = z.discriminatedUnion("kind", [
+ v2Deliver.extend({
+ deliveryMetadata: z
+ .array(v2DeliveryMetadata.extend({ acceptedDeploymentId: z.string().optional() }))
+ .optional(),
+ version,
+ }),
+ v2[1].extend({ version }),
+ v2[2].extend({ version }),
+ v2[3].extend({ version }),
+ v2[4].extend({ version }),
+ v2[5].extend({ version }),
+]);
+
+export type SessionInboxWireV3 = z.infer<typeof sessionInboxWireV3Schema>;
+
+export function parseSessionInboxWireV3(value: unknown) {
+ return sessionInboxWireV3Schema.safeParse(normalizeSessionInboxWireV2(value));
+}
+
+/** Builds and validates one complete version-3 wire value. */
+export function encodeSessionCommandV3(
+ command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload,
+): SessionInboxWireV3 {
+ const wire =
+ command.kind === "send"
+ ? {
+ auth: command.auth,
+ caller: command.caller,
+ deliveryMetadata:
+ command.delivery === undefined ? undefined : [{ ...command.delivery, payloadIndex: 0 }],
+ kind: "deliver" as const,
+ payload: command.payload,
+ payloads: [command.payload],
+ requestId: command.requestId,
+ taskDeliveryId: command.taskDeliveryId,
+ turnPolicy: command.turnPolicy,
+ version: 3 as const,
+ }
+ : command.kind === "deliver"
+ ? {
+ ...command,
+ payload: coalesceDeliverPayloads(command.payloads),
+ version: 3 as const,
+ }
+ : { ...command, version: 3 as const };
+ const parsed = parseSessionInboxWireV3(wire);
+ if (!parsed.success) {
+ throw new SessionInboxWireError(
+ `Produced a session inbox payload that does not match wire version 3: ${formatValidationError(parsed.error)}`,
+ );
+ }
+ return parsed.data;
+}
diff --git a/packages/eve/src/execution/workflow-entry.integration.test.ts b/packages/eve/src/execution/workflow-entry.integration.test.ts
index 0098cf6bf..ebae01607 100644
--- a/packages/eve/src/execution/workflow-entry.integration.test.ts
+++ b/packages/eve/src/execution/workflow-entry.integration.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { getWorld, resumeHook, start } from "#internal/workflow/runtime.js";
import { hydrateWorkflowArguments } from "@workflow/core/serialization";
@@ -30,6 +30,7 @@ import { toInputSchema } from "#tools/schema.js";
import { defineHook } from "#public/definitions/hook.js";
function buildSerializedContext(overrides: {
+ acceptedDeploymentId?: string;
audience?: "public" | "private" | "unknown";
auth?: Record<string, unknown>;
channelKind: string;
@@ -59,6 +60,14 @@ function buildSerializedContext(overrides: {
"eve.channel": channel,
"eve.mode": overrides.mode,
};
+ if (overrides.acceptedDeploymentId !== undefined) {
+ context["eve.channelDelivery"] = {
+ acceptedDeploymentId: overrides.acceptedDeploymentId,
+ channelKind: overrides.channelKind,
+ channelName: "test",
+ deliveryId: "delivery-initial",
+ };
+ }
if (overrides.continuationToken !== undefined) {
context["eve.continuationToken"] = overrides.continuationToken;
}
@@ -68,6 +77,10 @@ function buildSerializedContext(overrides: {
return context;
}
+afterEach(() => {
+ vi.unstubAllEnvs();
+});
+
interface WeatherAuthRuntime {
completeCalls(): number;
completedPrincipals(): readonly ConnectionPrincipal[];
@@ -683,6 +696,7 @@ describe("workflowEntry integration", () => {
});
it("parks in conversation mode and resumes via runtime delivery", async () => {
+ vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_inline");
const runtime = await createTestRuntime({ agent: { name: "workflow-entry-conversation" } });
const continuationToken = "http:workflow-entry-conversation";
@@ -691,6 +705,7 @@ describe("workflowEntry integration", () => {
{
input: { message: "hello there" },
serializedContext: buildSerializedContext({
+ acceptedDeploymentId: "dpl_inline",
channelKind: "http",
continuationToken,
mode: "conversation",
@@ -729,7 +744,17 @@ describe("workflowEntry integration", () => {
});
await expect(
workflowRuntime.dispatchContinuation({
- command: { auth: null, kind: "send", payload: { message: "follow up" } },
+ command: {
+ auth: null,
+ delivery: {
+ acceptedDeploymentId: "dpl_inline",
+ channelKind: "http",
+ channelName: "test",
+ deliveryId: "delivery-followup",
+ },
+ kind: "send",
+ payload: { message: "follow up" },
+ },
continuationToken,
}),
).resolves.toEqual({ sessionId: run.runId, status: "accepted" });
@@ -753,6 +778,9 @@ describe("workflowEntry integration", () => {
await expect(run.returnValue).resolves.toEqual({ output: "" });
completed = true;
expect(await listCallerStepNames(run.runId)).toEqual([]);
+ const stepNames = await listStepNames(run.runId);
+ expect(stepNames.filter((name) => name === "turnStep")).toHaveLength(2);
+ expect(stepNames).not.toContain("dispatchTurnStep");
} finally {
stream.dispose();
if (!completed) await run.cancel();
@@ -1327,16 +1355,17 @@ const CALLER_STEP_NAMES = new Set([
]);
async function listCallerStepNames(runId: string): Promise<string[]> {
+ return (await listStepNames(runId)).filter((name) => CALLER_STEP_NAMES.has(name)).sort();
+}
+
+async function listStepNames(runId: string): Promise<string[]> {
const world = await getWorld();
const steps = await world.steps.list({
pagination: { limit: 1_000 },
resolveData: "none",
runId,
});
- return steps.data
- .map((step) => step.stepName.split("//").at(-1) ?? "")
- .filter((name) => CALLER_STEP_NAMES.has(name))
- .sort();
+ return steps.data.map((step) => step.stepName.split("//").at(-1) ?? "");
}
interface CapturedEventStream {
diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.ts
index 762aa1b46..6292ac650 100644
--- a/packages/eve/src/execution/workflow-runtime.test.ts
+++ b/packages/eve/src/execution/workflow-runtime.test.ts
@@ -177,11 +177,10 @@ describe("createWorkflowRuntime command dispatch", () => {
}),
).resolves.toEqual({ sessionId: "session-1", status: "accepted" });
- expect(resumeHookMock).toHaveBeenCalledWith(
- currentSessionHook(sessionCommandHookToken("session-1")),
- { kind: "clear", version: 1 },
- );
- expect(getHookByTokenMock).toHaveBeenCalledWith(sessionCommandHookToken("session-1"));
+ expect(resumeHookMock).toHaveBeenCalledWith(sessionCommandHookToken("session-1"), {
+ kind: "clear",
+ });
+ expect(getHookByTokenMock).not.toHaveBeenCalled();
});
it("preserves the delivery payload through the stable session inbox", async () => {
@@ -194,18 +193,17 @@ describe("createWorkflowRuntime command dispatch", () => {
}),
).resolves.toEqual({ sessionId: "session-1", status: "accepted" });
- expect(resumeHookMock).toHaveBeenCalledWith(
- currentSessionHook(sessionCommandHookToken("session-1")),
- {
- auth: undefined,
- caller: undefined,
- kind: "deliver",
- payload: { message: "hello" },
- payloads: [{ message: "hello" }],
- requestId: undefined,
- version: 1,
- },
- );
+ expect(resumeHookMock).toHaveBeenCalledWith(sessionCommandHookToken("session-1"), {
+ auth: undefined,
+ caller: undefined,
+ delivery: undefined,
+ kind: "send",
+ payload: { message: "hello" },
+ requestId: undefined,
+ taskDeliveryId: undefined,
+ turnPolicy: undefined,
+ });
+ expect(getHookByTokenMock).not.toHaveBeenCalled();
});
it.each([
@@ -248,10 +246,11 @@ describe("createWorkflowRuntime command dispatch", () => {
sessionId: "session-1",
}),
).resolves.toEqual({ sessionId: "session-1", status: "accepted" });
- expect(resumeHookMock).toHaveBeenCalledWith(
- currentSessionHook(sessionCommandHookToken("session-1")),
- { kind: "cancel", turnId: "turn-2", version: 1 },
- );
+ expect(resumeHookMock).toHaveBeenCalledWith(sessionCommandHookToken("session-1"), {
+ kind: "cancel",
+ turnId: "turn-2",
+ });
+ expect(getHookByTokenMock).not.toHaveBeenCalled();
});
it("maps missing and terminal targets to 'no_active_turn'", async () => {
diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.ts
index feead2ebe..a283cd15c 100644
--- a/packages/eve/src/execution/workflow-runtime.ts
+++ b/packages/eve/src/execution/workflow-runtime.ts
@@ -450,14 +450,7 @@ export async function startWorkflowPreferLatest<TArgs extends unknown[], TResult
args: TArgs,
options?: StartOptionsWithoutDeploymentId,
): Promise<Run<unknown> | Run<TResult>> {
- // Agent parentage is reconstructed from Eve's serialized trace context. Only
- // remove the ambient span marked by an agent boundary; the marker is not
- // propagated into Workflow runs, so Workflow-to-Workflow traces stay intact.
- const activeContext = context.active();
- const workflowContext = isAgentTraceContext(activeContext)
- ? trace.deleteSpan(activeContext)
- : activeContext;
- return await context.with(workflowContext, async () => {
+ return await withWorkflowStartContext(async () => {
if (!shouldRouteToLatestDeployment()) {
return options === undefined
? await start(workflow, args)
@@ -478,6 +471,41 @@ export async function startWorkflowPreferLatest<TArgs extends unknown[], TResult
});
}
+/**
+ * Starts on the deployment that accepted a delivery when this step is running
+ * there, otherwise preserves latest-deployment routing.
+ */
+export async function startWorkflowPreferAcceptedDeployment<TArgs extends unknown[], TResult>(
+ workflow: WorkflowFunction<TArgs, TResult> | WorkflowMetadata,
+ args: TArgs,
+ acceptedDeploymentId: string | undefined,
+ options?: StartOptionsWithoutDeploymentId,
+): Promise<Run<unknown> | Run<TResult>> {
+ const currentDeploymentId = process.env.VERCEL_DEPLOYMENT_ID?.trim();
+ if (
+ acceptedDeploymentId === undefined ||
+ currentDeploymentId === undefined ||
+ acceptedDeploymentId !== currentDeploymentId
+ ) {
+ return await startWorkflowPreferLatest(workflow, args, options);
+ }
+
+ return await withWorkflowStartContext(
+ async () => await start(workflow, args, { ...options, deploymentId: acceptedDeploymentId }),
+ );
+}
+
+async function withWorkflowStartContext<TResult>(callback: () => Promise<TResult>) {
+ // Agent parentage is reconstructed from Eve's serialized trace context. Only
+ // remove the ambient span marked by an agent boundary; the marker is not
+ // propagated into Workflow runs, so Workflow-to-Workflow traces stay intact.
+ const activeContext = context.active();
+ const workflowContext = isAgentTraceContext(activeContext)
+ ? trace.deleteSpan(activeContext)
+ : activeContext;
+ return await context.with(workflowContext, callback);
+}
+
/**
* Local development resolves "latest" to the active promoted generation.
* Vercel resolves it only for production deployments; previews and CLI
diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.ts
index 75b7cfe43..7e0fc3c59 100644
--- a/packages/eve/src/execution/workflow-steps.test.ts
+++ b/packages/eve/src/execution/workflow-steps.test.ts
@@ -709,6 +709,73 @@ describe("dispatchTurnStep", () => {
);
});
+ it("starts on the accepted deployment when the dispatch step runs there", async () => {
+ vi.stubEnv("VERCEL_ENV", "production");
+ vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_current");
+ const baseInput = createTurnInput();
+ const input = {
+ ...baseInput,
+ delivery: {
+ ...baseInput.delivery,
+ deliveryMetadata: [
+ {
+ acceptedDeploymentId: "dpl_current",
+ channelKind: "channel:webhook",
+ channelName: "webhook",
+ deliveryId: "delivery-1",
+ payloadIndex: 0,
+ },
+ ],
+ },
+ };
+ startMock.mockResolvedValue({ runId: "turn-run" });
+
+ await expect(dispatchTurnStep(input)).resolves.toEqual({ runId: "turn-run" });
+
+ expect(startMock).toHaveBeenCalledWith(
+ turnWorkflowReference,
+ [createTurnWorkflowInput(input)],
+ expect.objectContaining({ deploymentId: "dpl_current" }),
+ );
+ });
+
+ it("keeps latest routing for mixed accepted deployments", async () => {
+ vi.stubEnv("VERCEL_ENV", "production");
+ vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_current");
+ const baseInput = createTurnInput();
+ const input = {
+ ...baseInput,
+ delivery: {
+ ...baseInput.delivery,
+ deliveryMetadata: [
+ {
+ acceptedDeploymentId: "dpl_current",
+ channelKind: "channel:webhook",
+ channelName: "webhook",
+ deliveryId: "delivery-1",
+ payloadIndex: 0,
+ },
+ {
+ acceptedDeploymentId: "dpl_other",
+ channelKind: "channel:webhook",
+ channelName: "webhook",
+ deliveryId: "delivery-2",
+ payloadIndex: 1,
+ },
+ ],
+ },
+ };
+ startMock.mockResolvedValue({ runId: "turn-run" });
+
+ await expect(dispatchTurnStep(input)).resolves.toEqual({ runId: "turn-run" });
+
+ expect(startMock).toHaveBeenCalledWith(
+ turnWorkflowReference,
+ [createTurnWorkflowInput(input)],
+ expect.objectContaining({ deploymentId: "latest" }),
+ );
+ });
+
it("starts turn workflows on the latest promoted generation in local development", async () => {
vi.stubEnv("EVE_DEV", "1");
const input = createTurnInput();
@@ -1433,6 +1500,29 @@ describe("dispatchRuntimeActionsStep", () => {
});
describe("turnStep", () => {
+ it("defers before mutation when an inline step reaches another deployment", async () => {
+ vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_driver");
+ const sessionState = createStubSessionState();
+ const durableReadsBefore = vi.mocked(readDurableSession).mock.calls.length;
+
+ await expect(
+ turnStep({
+ acceptedDeploymentId: "dpl_ingress",
+ input: { kind: "deliver", payloads: [{ message: "hello" }] },
+ parentWritable: createTestWritable(),
+ serializedContext: { state: "untouched" },
+ sessionState,
+ }),
+ ).resolves.toEqual({
+ action: "continue",
+ requiresChildDispatch: true,
+ serializedContext: { state: "untouched" },
+ sessionState,
+ });
+
+ expect(vi.mocked(readDurableSession).mock.calls).toHaveLength(durableReadsBefore);
+ });
+
it("prepares resumed-session history before dynamic runtime refresh", async () => {
const hidden = { content: "HIDE_FROM_RUNTIME_REFRESH", role: "user" as const };
mockIdentityHistoryViewProjector.mockImplementation(({ messages }) =>
diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.ts
index 7d294775f..d1458cd50 100644
--- a/packages/eve/src/execution/workflow-steps.ts
+++ b/packages/eve/src/execution/workflow-steps.ts
@@ -104,6 +104,7 @@ import { resolveRuntimeCompiledArtifactsVersionedCacheKey } from "#runtime/cache
import { createWorkflowRuntime } from "#execution/workflow-runtime.js";
import { bindDynamicConnections } from "#execution/dynamic-connections.js";
import { preserveCancelledTurnMessage } from "#execution/cancelled-turn-message.js";
+import { deferMismatchedInlineTurnStep } from "#execution/accepted-delivery-deployment.js";
const TASK_DONE_WITH_PENDING_INPUT_ERROR_MESSAGE =
"Task mode cannot complete while input requests remain pending.";
@@ -122,6 +123,9 @@ export type { TurnStepInput };
export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResult> {
"use step";
+ const deferred = deferMismatchedInlineTurnStep(rawInput);
+ if (deferred !== undefined) return deferred;
+
let input = rawInput;
let durableSession = await readDurableSession(input.sessionState);
diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts
index a8effb8bd..8d5017580 100644
--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts
+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts
@@ -55,6 +55,10 @@ const DEVELOPMENT_ARTIFACTS_CONFIG = {
moduleMapLoaderPath: "/eve/src/internal/authored-module-map-loader.ts",
} as const;
+afterEach(() => {
+ vi.unstubAllEnvs();
+});
+
function createRuntime(overrides: Partial<Runtime> = {}): Runtime {
return {
createSession: vi.fn(),
@@ -339,6 +343,43 @@ describe("dispatchChannelRequest", () => {
);
});
+ it("tags route sends with the Vercel deployment that accepted them", async () => {
+ vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_current");
+ const runtimeForTest = createRuntime({
+ dispatchContinuation: vi.fn().mockResolvedValue({
+ sessionId: "sess_route",
+ status: "accepted",
+ }),
+ });
+
+ mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
+ agentName: "test-agent",
+ channels: [
+ {
+ handler: async (_req, args) => {
+ await args.from("route-token").send("hello", { auth: null });
+ return new Response("ok");
+ },
+ fetch: async () => new Response("ok"),
+ adapter: { kind: "channel:webhook" },
+ logicalPath: "agent/channels/webhook.ts",
+ method: "POST",
+ name: "webhook",
+ sourceId: "channel-webhook",
+ sourceKind: "module",
+ urlPath: "/webhook",
+ } satisfies ResolvedChannelDefinition,
+ ],
+ runtime: runtimeForTest,
+ });
+
+ await dispatchChannelRequest(createEvent({ waitUntil: vi.fn() }), "POST /webhook", {} as never);
+
+ expect(vi.mocked(runtimeForTest.dispatchContinuation).mock.calls[0]?.[0].command).toMatchObject(
+ { delivery: { acceptedDeploymentId: "dpl_current" } },
+ );
+ });
+
it("supplies a channel-scoped reset helper", async () => {
const runtimeForTest = createRuntime({
dispatchContinuation: vi.fn().mockResolvedValue({
diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts
index f4d45a184..712f4b74f 100644
--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts
+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts
@@ -229,7 +229,9 @@ function buildRouteArgs(
const channel = bundle.channels.find((candidate) => candidate.name === channelName);
const adapter = channel?.adapter ?? { kind: "channel" };
const requestSpanContext = requestSpan?.spanContext();
+ const acceptedDeploymentId = process.env.VERCEL_DEPLOYMENT_ID?.trim() || undefined;
const deliverySource = {
+ acceptedDeploymentId,
channelKind,
channelName,
requestId,