Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): versioned wire schema for session inbox hook payloads (#1767)

Rui6fc904d48233
diff --git a/.changeset/wired-inbox-schema.md b/.changeset/wired-inbox-schema.md
new file mode 100644
index 000000000..1abf9e7d2
--- /dev/null
+++ b/.changeset/wired-inbox-schema.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Session inbox hook payloads are now a validated, versioned wire format following eve's existing durable-format idioms. Producers inspect the target hook's wire capability and encode the shape its pinned consumer understands, including sessions created by eve 0.30.8; readers migrate legacy shapes forward and reject unknown versions instead of reinterpreting them.
diff --git a/e2e/README.md b/e2e/README.md
index 2ece0ed7d..be80428f1 100644
--- a/e2e/README.md
+++ b/e2e/README.md
@@ -123,6 +123,14 @@ The pinned-turn assertion is a deliberate tripwire: it must be flipped when
turn dispatch gains preview latest-routing
(https://github.com/vercel/eve/issues/582).
+`agent-channels/evals/custom-channels/cross-version-session-inbox.eval.ts`
+deploys the fixture with the published `[email protected]`, holds a turn active in
+that old consumer, then redeploys the current checkout and sends a replacement
+message through the same durable session. It verifies both sides of the codec:
+the current producer must choose the old consumer's wire version, and the real
+old consumer must decode and buffer it. The eval then cancels the deliberately
+blocked turn and verifies that the old session runs the buffered follow-up.
+
The eval redeploys from inside its test body: it mutates the agent source,
runs `eve build` + `vc deploy`, and repoints a run-scoped Vercel alias at
each new deployment, polling `/eve/v1/info` until the alias serves it.
diff --git a/e2e/fixtures/agent-channels/agent/agent.ts b/e2e/fixtures/agent-channels/agent/agent.ts
index 384bb0e2a..d746d5e38 100644
--- a/e2e/fixtures/agent-channels/agent/agent.ts
+++ b/e2e/fixtures/agent-channels/agent/agent.ts
@@ -2,6 +2,19 @@ import { e2eAgentConfig } from "@eve-e2e/config";
import { defineAgent } from "eve";
export default defineAgent({
- ...e2eAgentConfig(),
+ ...e2eAgentConfig({
+ mock: ({ lastUserMessage }) =>
+ lastUserMessage?.includes("Please wait for cross-version follow-up.") === true
+ ? {
+ toolCalls: [
+ {
+ id: "wait-for-cancellation",
+ input: {},
+ name: "wait-for-cancellation",
+ },
+ ],
+ }
+ : `Mock reply: ${lastUserMessage ?? ""}`,
+ }),
reasoning: "high",
});
diff --git a/e2e/fixtures/agent-channels/agent/channels/cross-version.ts b/e2e/fixtures/agent-channels/agent/channels/cross-version.ts
new file mode 100644
index 000000000..7b32c2b7e
--- /dev/null
+++ b/e2e/fixtures/agent-channels/agent/channels/cross-version.ts
@@ -0,0 +1,59 @@
+import { defineChannel, POST, type Session } from "eve/channels";
+
+const smokeTestAuth = {
+ attributes: { source: "smoke-test" },
+ authenticator: "cross-version-webhook",
+ principalId: "smoke-test",
+ principalType: "service",
+} as const;
+
+type CrossVersionRouteContext = {
+ readonly from?: (address: string) => {
+ send(
+ message: string,
+ options: {
+ readonly auth: typeof smokeTestAuth;
+ readonly turnPolicy?: "queue" | "steer";
+ },
+ ): Promise<Session>;
+ };
+ readonly send?: (
+ message: string,
+ options: {
+ readonly auth: typeof smokeTestAuth;
+ readonly continuationToken: string;
+ },
+ ) => Promise<Session>;
+};
+
+export default defineChannel({
+ routes: [
+ POST("/cross-version-webhook", async (req, ctx) => {
+ const body = (await req.json().catch(() => ({}))) as {
+ message?: string;
+ sessionRef?: string;
+ turnPolicy?: "queue" | "steer";
+ };
+ const message = body.message ?? "Reply with the single word: hello.";
+ const address = body.sessionRef ?? crypto.randomUUID();
+ const crossVersionContext = ctx as CrossVersionRouteContext;
+
+ let session: Session;
+ if (crossVersionContext.from !== undefined) {
+ session = await crossVersionContext.from(address).send(message, {
+ auth: smokeTestAuth,
+ turnPolicy: body.turnPolicy,
+ });
+ } else if (crossVersionContext.send !== undefined) {
+ session = await crossVersionContext.send(message, {
+ auth: smokeTestAuth,
+ continuationToken: address,
+ });
+ } else {
+ throw new Error("Expected the route context to expose from() or send().");
+ }
+
+ return Response.json({ ok: true, sessionId: session.id });
+ }),
+ ],
+});
diff --git a/e2e/fixtures/agent-channels/agent/channels/webhook.ts b/e2e/fixtures/agent-channels/agent/channels/webhook.ts
index d000e7c32..908b04028 100644
--- a/e2e/fixtures/agent-channels/agent/channels/webhook.ts
+++ b/e2e/fixtures/agent-channels/agent/channels/webhook.ts
@@ -13,6 +13,7 @@ export default defineChannel({
const body = (await req.json().catch(() => ({}))) as {
message?: string;
sessionRef?: string;
+ turnPolicy?: "queue" | "steer";
};
const session = await ctx
.to(target, { sessionRef: body.sessionRef ?? crypto.randomUUID() })
@@ -23,6 +24,7 @@ export default defineChannel({
principalId: "smoke-test",
principalType: "service",
},
+ turnPolicy: body.turnPolicy,
});
return Response.json({ ok: true, sessionId: session.id });
}),
diff --git a/e2e/fixtures/agent-channels/agent/tools/wait-for-cancellation.ts b/e2e/fixtures/agent-channels/agent/tools/wait-for-cancellation.ts
new file mode 100644
index 000000000..3d03d4b0b
--- /dev/null
+++ b/e2e/fixtures/agent-channels/agent/tools/wait-for-cancellation.ts
@@ -0,0 +1,29 @@
+import { defineTool } from "eve/tools";
+import { never } from "eve/tools/approval";
+import { z } from "zod";
+
+const FALLBACK_TIMEOUT_MS = 10 * 60_000;
+
+export default defineTool({
+ description:
+ "Waits until the current turn is cancelled. Only call when the user explicitly asks you to wait for a cross-version follow-up.",
+ inputSchema: z.object({}),
+ approval: never(),
+ execute(_input, ctx) {
+ return new Promise<string>((resolve, reject) => {
+ const timer = setTimeout(() => {
+ resolve("wait-for-cancellation: fallback timeout reached without cancellation");
+ }, FALLBACK_TIMEOUT_MS);
+
+ const abort = (): void => {
+ clearTimeout(timer);
+ reject(ctx.abortSignal.reason);
+ };
+ if (ctx.abortSignal.aborted) {
+ abort();
+ return;
+ }
+ ctx.abortSignal.addEventListener("abort", abort, { once: true });
+ });
+ },
+});
diff --git a/e2e/fixtures/agent-channels/evals/custom-channels/continuation-wire.eval.ts b/e2e/fixtures/agent-channels/evals/custom-channels/continuation-wire.eval.ts
deleted file mode 100644
index 530da9530..000000000
--- a/e2e/fixtures/agent-channels/evals/custom-channels/continuation-wire.eval.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-import { existsSync, readdirSync, readFileSync } from "node:fs";
-import { join, resolve } from "node:path";
-import { zstdDecompressSync } from "node:zlib";
-
-import { defineEval } from "eve/evals";
-import { equals, satisfies } from "eve/evals/expect";
-
-import { postChannel } from "./shared";
-
-type MessageResponse = { ok: boolean; sessionId?: string };
-
-const WORKFLOW_EVENTS_DIR = resolve(".eve", ".workflow-data", "events");
-
-/**
- * A channel-address follow-up crosses the durable continuation-hook boundary,
- * and the persisted hook payload must stay on the frozen `deliver` envelope
- * with the transitional single-payload mirror (`payload` alongside
- * `payloads`) that keeps eve 0.30.3–0.30.8 parked consumers receiving
- * messages. Drop the mirror assertion together with the encoder mirror once
- * that cohort has aged out (30-day session timeout).
- *
- * The behavioral half (a same-version follow-up turn) passes even if producer
- * and consumer change the wire together — exactly how the 0.30.3 `send`
- * regression shipped. The byte-level half closes that hole: on worlds with a
- * local event log, the eval decodes the persisted `hook_received` payload and
- * fails loudly when the envelope shape drifts.
- */
-export default defineEval({
- description: "Custom channel continuation preserves the durable delivery wire protocol.",
-
- async test(t) {
- const sessionRef = crypto.randomUUID();
- const first = await postChannel<MessageResponse>(t.target, "/webhook", {
- message: "Reply with exactly: first-turn",
- sessionRef,
- });
- await t.require(
- first,
- satisfies(
- (value: MessageResponse) => value.ok === true && typeof value.sessionId === "string",
- "initial channel delivery creates a session",
- ),
- );
-
- const initialTurn = await t.target.watchTurn(first.sessionId!).result();
- initialTurn.notEvent("session.failed");
-
- const followUpTurn = t.target.watchTurn(first.sessionId!, {
- startIndex: initialTurn.events.length,
- });
- const second = await postChannel<MessageResponse>(t.target, "/webhook", {
- message: "Reply with exactly: second-turn",
- sessionRef,
- });
- await t.require(second.sessionId, equals(first.sessionId));
-
- const followUp = await followUpTurn.result();
- followUp.notEvent("session.failed");
- followUp.event("message.completed");
- followUp.messageIncludes("second-turn");
-
- // Byte-level wire pin. Only worlds persisting a local event log expose the
- // durable payload; remote worlds (Vercel, Postgres) skip this half.
- if (!existsSync(WORKFLOW_EVENTS_DIR)) {
- t.log("No local workflow event log; skipping the persisted wire-format assertion.");
- return;
- }
-
- const payloads = readSessionHookPayloads(first.sessionId!);
- if (payloads.length === 0) {
- // A stale local event log can coexist with a remote world; only assert
- // when this session's continuation actually persisted locally.
- t.log("No locally persisted hook_received for this session; skipping the wire assertion.");
- return;
- }
- for (const payload of payloads) {
- await t.require(
- payload,
- satisfies(
- (text: string) => text.includes('"deliver"') && text.includes('"payloads"'),
- "the persisted continuation payload uses the frozen `deliver` envelope",
- ),
- );
- await t.require(
- payload,
- satisfies(
- // `"payload"` never matches inside `"payloads"`: the closing quote
- // pins the exact key.
- (text: string) => /"payload"/.test(text),
- "the persisted envelope mirrors `payload` for 0.30.3–0.30.8 parked consumers",
- ),
- );
- }
- },
-});
-
-/**
- * Decoded devalue text of every session-level `hook_received` payload for one
- * run. Turn-control hooks are runtime-internal and excluded; only the channel
- * continuation hook carries the cross-deployment delivery envelope.
- */
-function readSessionHookPayloads(sessionId: string): string[] {
- const payloads: string[] = [];
- for (const name of readdirSync(WORKFLOW_EVENTS_DIR)) {
- if (!name.startsWith(`${sessionId}-`)) continue;
- const event = JSON.parse(readFileSync(join(WORKFLOW_EVENTS_DIR, name), "utf8")) as {
- eventType?: string;
- eventData?: { token?: string; payload?: { data?: string } };
- };
- if (event.eventType !== "hook_received") continue;
- const token = event.eventData?.token ?? "";
- if (token.includes(":turn-control:") || token.endsWith(":auth")) continue;
- const data = event.eventData?.payload?.data;
- if (data === undefined) continue;
- payloads.push(decodeSerializedPayload(Buffer.from(data, "base64")));
- }
- return payloads;
-}
-
-/** Undoes the workflow serde codec prefix: `zstd` wraps the `devl` bytes. */
-function decodeSerializedPayload(bytes: Buffer): string {
- const prefix = bytes.subarray(0, 4).toString("utf8");
- const body = prefix === "zstd" ? zstdDecompressSync(bytes.subarray(4)) : bytes;
- return body.toString("utf8");
-}
diff --git a/e2e/fixtures/agent-channels/evals/custom-channels/cross-channel-receive.eval.ts b/e2e/fixtures/agent-channels/evals/custom-channels/cross-channel-receive.eval.ts
index 7e746d13b..61247540b 100644
--- a/e2e/fixtures/agent-channels/evals/custom-channels/cross-channel-receive.eval.ts
+++ b/e2e/fixtures/agent-channels/evals/custom-channels/cross-channel-receive.eval.ts
@@ -1,36 +1,52 @@
import { defineEval } from "eve/evals";
-import { satisfies } from "eve/evals/expect";
+import { equals, satisfies } from "eve/evals/expect";
import { postChannel } from "./shared";
+type MessageResponse = { ok: boolean; sessionId?: string };
+
/**
- * Custom-channel eval for cross-channel `ctx.to(...).send(...)` handoff.
+ * Custom-channel eval for cross-channel `ctx.to(...).send(...)` handoff and
+ * same-address continuation.
*
* The `/webhook` route does not start a session itself; it hands the
- * message to the target channel via `ctx.to(...).send(...)` and returns the new
- * session id, which we attach to and drive to a turn boundary.
+ * message to the target channel via `ctx.to(...).send(...)`. Reusing the
+ * channel address must resume the same durable session.
*/
export default defineEval({
- description: "Custom channel smoke: cross-channel receive.",
+ description: "Custom channel smoke: cross-channel receive and continuation.",
async test(t) {
- const payload = await postChannel<{ ok: boolean; sessionId?: string }>(t.target, "/webhook", {
- message: "Reply with the single word: hello.",
+ const sessionRef = crypto.randomUUID();
+ const first = await postChannel<MessageResponse>(t.target, "/webhook", {
+ message: "Reply with exactly: first-turn",
+ sessionRef,
});
await t.require(
- payload,
+ first,
satisfies(
- (value: { ok: boolean; sessionId?: string }) =>
- value.ok === true && typeof value.sessionId === "string",
- "webhook returns a session id",
+ (value: MessageResponse) => value.ok === true && typeof value.sessionId === "string",
+ "initial channel delivery creates a session",
),
);
- const session = await t.target.attachSession(payload.sessionId!);
- session.succeeded();
- session.event("message.completed");
- session.messageIncludes("hello");
+ const initialTurn = await t.target.watchTurn(first.sessionId!).result();
+ initialTurn.succeeded();
+ initialTurn.event("message.completed");
+ initialTurn.messageIncludes("first-turn");
+
+ const followUpTurn = t.target.watchTurn(first.sessionId!, {
+ startIndex: initialTurn.events.length,
+ });
+ const second = await postChannel<MessageResponse>(t.target, "/webhook", {
+ message: "Reply with exactly: second-turn",
+ sessionRef,
+ });
+ await t.require(second.sessionId, equals(first.sessionId));
- t.succeeded();
+ const followUp = await followUpTurn.result();
+ followUp.succeeded();
+ followUp.event("message.completed");
+ followUp.messageIncludes("second-turn");
},
});
diff --git a/e2e/fixtures/agent-channels/evals/custom-channels/cross-version-session-inbox.eval.ts b/e2e/fixtures/agent-channels/evals/custom-channels/cross-version-session-inbox.eval.ts
new file mode 100644
index 000000000..d2a7fc731
--- /dev/null
+++ b/e2e/fixtures/agent-channels/evals/custom-channels/cross-version-session-inbox.eval.ts
@@ -0,0 +1,238 @@
+import { execFile } from "node:child_process";
+import { readFile, readlink, realpath, rm, symlink, writeFile } from "node:fs/promises";
+import { resolve } from "node:path";
+import { promisify } from "node:util";
+
+import { defineEval } from "eve/evals";
+import type { EveEvalContext } from "eve/evals";
+import { satisfies } from "eve/evals/expect";
+
+import { postChannel } from "./shared";
+
+const ALIAS_ENV = "EVE_E2E_REDEPLOY_ALIAS";
+const OLD_EVE_VERSION = "0.30.8";
+const ACTIVE_TURN_MESSAGE = "Please wait for cross-version follow-up.";
+const FOLLOW_UP_TOKEN = "CROSS-VERSION-WIRE-OK";
+
+const INSTRUCTIONS_PATH = resolve("agent", "instructions.md");
+const FIXTURE_EVE_LINK = resolve("node_modules", "eve");
+const CONFIG_EVE_LINK = resolve("..", "e2e-config", "node_modules", "eve");
+const OLD_EVE_PACKAGE = resolve("node_modules", "historical-eve-0-30-8");
+
+const OLD_DEPLOYMENT_MARKER = "cross-version-eve-0-30-8";
+const CURRENT_DEPLOYMENT_MARKER = "cross-version-eve-current";
+const TOOL_NAME = "wait-for-cancellation";
+
+const execFileAsync = promisify(execFile);
+const EXEC_OPTIONS = { maxBuffer: 64 * 1024 * 1024 } as const;
+
+type MessageResponse = { ok: boolean; sessionId?: string };
+
+/**
+ * Proves the complete mixed-version codec boundary through the real Workflow
+ * hook: the current producer resumes an active turn built and deployed with
+ * the published [email protected] consumer, then the old session accepts the
+ * replacement message and completes its next turn.
+ */
+export default defineEval({
+ description:
+ "Session inbox: the current producer resumes an active [email protected] consumer through the durable hook.",
+ tags: ["redeploy"],
+ timeoutMs: 20 * 60_000,
+
+ async test(t) {
+ const alias = process.env[ALIAS_ENV];
+ if (alias === undefined || alias.length === 0) {
+ t.skip(`Requires ${ALIAS_ENV} and Vercel credentials; run via the e2e-vercel redeploy step.`);
+ }
+ if (new URL(t.target.url).host !== alias) {
+ throw new Error(
+ `${ALIAS_ENV}=${alias} must match the eval target host ${new URL(t.target.url).host}; ` +
+ "redeploys repoint the alias, so the eval must run against it.",
+ );
+ }
+
+ const originalInstructions = await readFile(INSTRUCTIONS_PATH, "utf8");
+ const links = await Promise.all([
+ snapshotLink(FIXTURE_EVE_LINK),
+ snapshotLink(CONFIG_EVE_LINK),
+ ]);
+ const currentEvePackage = await realpath(FIXTURE_EVE_LINK);
+ const currentEveVersion = await readPackageVersion(currentEvePackage);
+ const oldEvePackage = await realpath(OLD_EVE_PACKAGE);
+ const oldEveVersion = await readPackageVersion(oldEvePackage);
+ if (oldEveVersion !== OLD_EVE_VERSION) {
+ throw new Error(
+ `Expected ${OLD_EVE_PACKAGE} to resolve eve@${OLD_EVE_VERSION}; got eve@${oldEveVersion}.`,
+ );
+ }
+
+ try {
+ await replaceLink(FIXTURE_EVE_LINK, oldEvePackage);
+ await replaceLink(CONFIG_EVE_LINK, oldEvePackage);
+ await writeFile(
+ INSTRUCTIONS_PATH,
+ `${originalInstructions}\nDeployment marker: ${OLD_DEPLOYMENT_MARKER}.\n`,
+ );
+ await deployToAlias(t, alias, "[email protected]");
+ await waitForAliasToServe(t, OLD_DEPLOYMENT_MARKER);
+
+ const sessionRef = crypto.randomUUID();
+ const started = await postChannel<MessageResponse>(t.target, "/cross-version-webhook", {
+ message: ACTIVE_TURN_MESSAGE,
+ sessionRef,
+ });
+ await t.require(
+ started,
+ satisfies(
+ (value: MessageResponse) => value.ok === true && typeof value.sessionId === "string",
+ "[email protected] starts the durable session",
+ ),
+ );
+ const sessionId = started.sessionId!;
+ const activeTurn = t.target.watchTurn(sessionId);
+
+ await activeTurn.waitForEvent("actions.requested", {
+ data: {
+ actions: (actions) =>
+ actions.some((action) => action.kind === "tool-call" && action.toolName === TOOL_NAME),
+ },
+ });
+
+ await restoreLinks(links);
+ await writeFile(
+ INSTRUCTIONS_PATH,
+ `${originalInstructions}\nDeployment marker: ${CURRENT_DEPLOYMENT_MARKER}.\n`,
+ );
+ await deployToAlias(t, alias, `eve@${currentEveVersion}`);
+ await waitForAliasToServe(t, CURRENT_DEPLOYMENT_MARKER);
+
+ const replacement = await postChannel<MessageResponse>(t.target, "/cross-version-webhook", {
+ message: `Reply with exactly ${FOLLOW_UP_TOKEN}.`,
+ sessionRef,
+ turnPolicy: "queue",
+ });
+ await t.require(
+ replacement,
+ satisfies(
+ (value: MessageResponse) => value.ok === true && value.sessionId === sessionId,
+ "the current producer targets the existing [email protected] session",
+ ),
+ );
+
+ // [email protected] buffers a raw `send` during an active turn but predates
+ // `turnPolicy: "steer"`. Settle the deliberately blocked turn through a
+ // separate cancellation; the queued message must then become the next
+ // turn if the old receiver decoded and retained it.
+ await t.sleep(1_000);
+ const cancellation = await activeTurn.cancel();
+ await t.require(
+ cancellation,
+ satisfies(
+ (value: { readonly sessionId?: string; readonly status: string }) =>
+ value.status === "accepted" && value.sessionId === sessionId,
+ "the current deployment cancels the active [email protected] turn",
+ ),
+ );
+
+ const cancelled = await activeTurn.result();
+ cancelled.event("turn.cancelled", { count: 1 });
+ cancelled.eventOrder([{ type: "turn.cancelled" }, { type: "session.waiting" }]);
+ cancelled.notEvent("turn.failed");
+ cancelled.notEvent("session.failed");
+
+ const followUp = await t.target
+ .watchTurn(sessionId, { startIndex: cancelled.events.length })
+ .result();
+ followUp.notEvent("turn.cancelled");
+ followUp.notEvent("turn.failed");
+ followUp.notEvent("session.failed");
+ followUp.messageIncludes(FOLLOW_UP_TOKEN);
+
+ t.succeeded();
+ } finally {
+ await restoreLinks(links);
+ await writeFile(INSTRUCTIONS_PATH, originalInstructions);
+ }
+ },
+});
+
+interface LinkSnapshot {
+ readonly path: string;
+ readonly target: string;
+}
+
+async function snapshotLink(path: string): Promise<LinkSnapshot> {
+ return { path, target: await readlink(path) };
+}
+
+async function replaceLink(path: string, target: string): Promise<void> {
+ await rm(path, { force: true });
+ await symlink(target, path);
+}
+
+async function restoreLinks(links: readonly LinkSnapshot[]): Promise<void> {
+ for (const link of links) {
+ await replaceLink(link.path, link.target);
+ }
+}
+
+async function readPackageVersion(packagePath: string): Promise<string> {
+ const manifest = JSON.parse(await readFile(resolve(packagePath, "package.json"), "utf8")) as {
+ version?: string;
+ };
+ if (manifest.version === undefined) {
+ throw new Error(`Package at ${packagePath} has no version.`);
+ }
+ return manifest.version;
+}
+
+/** Builds the fixture and repoints the run-scoped alias at the fresh deployment. */
+async function deployToAlias(t: EveEvalContext, alias: string, phase: string): Promise<void> {
+ await execFileAsync("pnpm", ["exec", "eve", "build"], {
+ ...EXEC_OPTIONS,
+ env: {
+ ...process.env,
+ VERCEL: "1",
+ VERCEL_ENV: "preview",
+ VERCEL_TARGET_ENV: "preview",
+ },
+ });
+ const tokenArgs =
+ process.env.VERCEL_TOKEN === undefined ? [] : ["--token", process.env.VERCEL_TOKEN];
+ const modelArgs =
+ process.env.EVE_E2E_MODEL === undefined
+ ? []
+ : ["--env", `EVE_E2E_MODEL=${process.env.EVE_E2E_MODEL}`];
+ const scopeArgs =
+ process.env.VERCEL_ORG_ID === undefined ? [] : ["--scope", process.env.VERCEL_ORG_ID];
+ const deploy = await execFileAsync(
+ "pnpm",
+ ["exec", "vc", "deploy", "--prebuilt", "--yes", "--target=preview", ...modelArgs, ...tokenArgs],
+ EXEC_OPTIONS,
+ );
+ const deploymentUrl = deploy.stdout.trim().split("\n").at(-1)?.trim();
+ if (deploymentUrl === undefined || !deploymentUrl.startsWith("https://")) {
+ throw new Error(`vc deploy did not print a deployment URL; got: ${deploy.stdout}`);
+ }
+ t.log(`deployed ${deploymentUrl} (${phase}); aliasing ${alias}`);
+
+ await execFileAsync(
+ "pnpm",
+ ["exec", "vc", "alias", "set", deploymentUrl, alias, ...tokenArgs, ...scopeArgs],
+ EXEC_OPTIONS,
+ );
+}
+
+/** Waits until the alias exposes the marker from the expected deployment. */
+async function waitForAliasToServe(t: EveEvalContext, marker: string): Promise<void> {
+ const deadline = Date.now() + 120_000;
+ while (Date.now() < deadline) {
+ const response = await t.target.fetch("/eve/v1/info");
+ if (response.ok && JSON.stringify(await response.json()).includes(marker)) {
+ return;
+ }
+ await t.sleep(1_000);
+ }
+ throw new Error(`Timed out waiting for the alias to serve a deployment containing ${marker}.`);
+}
diff --git a/e2e/fixtures/agent-channels/package.json b/e2e/fixtures/agent-channels/package.json
index 97c223055..827cec9e2 100644
--- a/e2e/fixtures/agent-channels/package.json
+++ b/e2e/fixtures/agent-channels/package.json
@@ -13,10 +13,12 @@
"dependencies": {
"@eve-e2e/config": "workspace:*",
"@workflow/world-postgres": "catalog:",
- "eve": "workspace:*"
+ "eve": "workspace:*",
+ "zod": "catalog:"
},
"devDependencies": {
"@types/node": "catalog:",
+ "historical-eve-0-30-8": "npm:[email protected]",
"typescript": "catalog:"
}
}
diff --git a/packages/eve/CHANGELOG.md b/packages/eve/CHANGELOG.md
index bb4caa50c..4f8e61f94 100644
--- a/packages/eve/CHANGELOG.md
+++ b/packages/eve/CHANGELOG.md
@@ -239,7 +239,7 @@
### Patch Changes
-- 2a141f0: Keep sessions resumable across eve deployment upgrades: sends now cross durable session hooks as the established `deliver` envelope (with a transitional single-payload mirror for sessions pinned to 0.30.3–0.30.8), and consumers keep accepting payloads persisted by those versions.
+- 2a141f0: Keep sessions resumable across eve deployment upgrades: sends now cross durable session hooks as the established `deliver` envelope (with a transitional single-payload mirror for sessions pinned to 0.30.5–0.30.8), and consumers keep accepting payloads persisted by those versions.
- 99982f7: Treat AI SDK `.devtools` like other generated directories: ignore it in `eve dev` watching, agent discovery, and source snapshots so generation writes do not recompile or warn.
- a497e8d: Preserve each tool executor's concrete return type through `defineTool`, so non-streaming tools no longer appear to return an async iterable. Allow `ctx.to()` to infer closed receive-target interfaces such as Slack's without requiring an index signature.
- fe9e7ef: Consume interactive authorization callback results once and keep targeted connection searches from replaying callbacks for unrelated connections.
diff --git a/packages/eve/package.json b/packages/eve/package.json
index b235d9227..7f25b8464 100644
--- a/packages/eve/package.json
+++ b/packages/eve/package.json
@@ -371,6 +371,7 @@
"eventsource-parser": "3.1.0",
"experimental-ai-sdk-code-mode": "1.0.16",
"gray-matter": "4.0.3",
+ "historical-eve-0-30-8": "npm:[email protected]",
"jose": "6.2.3",
"jsonc-parser": "3.3.1",
"just-bash": "3.1.0",
diff --git a/packages/eve/src/channel/delivery-metadata.ts b/packages/eve/src/channel/delivery-metadata.ts
index 815a90ef1..9d554fa16 100644
--- a/packages/eve/src/channel/delivery-metadata.ts
+++ b/packages/eve/src/channel/delivery-metadata.ts
@@ -11,5 +11,20 @@ export interface ChannelDeliverySource {
export function createChannelDeliveryMetadata(
source: ChannelDeliverySource,
): ChannelDeliveryMetadata {
- return { ...source, deliveryId: crypto.randomUUID() };
+ const metadata: {
+ channelKind: string;
+ channelName: string;
+ deliveryId: string;
+ requestId?: string;
+ requestTraceContext?: SessionTraceContext;
+ } = {
+ channelKind: source.channelKind,
+ channelName: source.channelName,
+ deliveryId: crypto.randomUUID(),
+ };
+ if (source.requestId !== undefined) metadata.requestId = source.requestId;
+ if (source.requestTraceContext !== undefined) {
+ metadata.requestTraceContext = source.requestTraceContext;
+ }
+ return metadata;
}
diff --git a/packages/eve/src/channel/session.test.ts b/packages/eve/src/channel/session.test.ts
index 02578fccc..d0933d84c 100644
--- a/packages/eve/src/channel/session.test.ts
+++ b/packages/eve/src/channel/session.test.ts
@@ -58,6 +58,28 @@ describe("createSession#cancel", () => {
});
describe("fixed session operations", () => {
+ it("keeps the session turn policy out of channel delivery metadata", async () => {
+ const runtime = createRuntime();
+ const session = createSession("sess_1", runtime, {
+ channelKind: "channel:slack",
+ channelName: "slack",
+ requestId: "req_1",
+ turnPolicy: "queue",
+ });
+
+ await session.send("hello", { auth: null });
+
+ const command = vi.mocked(runtime.dispatchSession).mock.calls[0]?.[0].command;
+ expect(command?.kind === "send" ? command.delivery : undefined).toMatchObject({
+ channelKind: "channel:slack",
+ channelName: "slack",
+ requestId: "req_1",
+ });
+ expect(command?.kind === "send" ? command.delivery : undefined).not.toHaveProperty(
+ "turnPolicy",
+ );
+ });
+
it("dispatches every operation through the stable session id", async () => {
const runtime = createRuntime();
const session = createAttachSessionFn(runtime, { requestId: "req_1" })("sess_1");
diff --git a/packages/eve/src/execution/parked-delivery-wait.ts b/packages/eve/src/execution/parked-delivery-wait.ts
index 27be2d275..070388f4a 100644
--- a/packages/eve/src/execution/parked-delivery-wait.ts
+++ b/packages/eve/src/execution/parked-delivery-wait.ts
@@ -1,8 +1,13 @@
import type { DeliverHookPayload, DeliverPayload } from "#channel/types.js";
import { routeDeliverToChildren } from "#execution/route-child-delivery.js";
import type { SessionCommandInbox } from "#execution/session-command-inbox.js";
-import { sendCommandToDelivery } from "#execution/session-command-wire.js";
import type { SessionStateCursor } from "#execution/session-state-cursor.js";
+import { reportDroppedWirePayloadStep } from "#execution/report-dropped-wire-payload-step.js";
+import {
+ sessionInboxWire,
+ SessionInboxWireError,
+ type DecodedSessionInbox,
+} from "#execution/wire/session-inbox-wire.js";
import { coalesceDeliveries } from "#harness/messages.js";
type NextSessionAction =
@@ -182,21 +187,35 @@ async function waitForNextSessionAction(input: {
return { delivery: null, kind: "delivery" };
}
- if (first.value.kind === "session-timeout") {
+ // Runtime-action results use the active turn's private inbox. A late value
+ // can still surface through an old session alias, where the driver has
+ // always ignored it rather than treating it as a session command.
+ if (first.value.kind === "runtime-action-result") {
+ continue;
+ }
+
+ let decoded: DecodedSessionInbox;
+ try {
+ decoded = sessionInboxWire.decode(first.value);
+ } catch (error) {
+ if (!(error instanceof SessionInboxWireError)) throw error;
+ // A lost delivery with an operator-visible signal is the designed
+ // failure; reinterpreting an unknown payload is the bug. Stay parked.
+ await reportDroppedWirePayloadStep({ detail: error.message, family: "session-inbox" });
+ continue;
+ }
+
+ if (decoded.kind === "session-timeout") {
return { kind: "expired" };
}
- if (
- first.value.kind === "clear" ||
- first.value.kind === "compact" ||
- first.value.kind === "reset"
- ) {
- return { kind: first.value.kind };
+ if (decoded.kind === "clear" || decoded.kind === "compact" || decoded.kind === "reset") {
+ return { kind: decoded.kind };
}
- if (first.value.kind === "cancel") {
- if (first.value.taskId !== undefined) {
- input.cancelledTaskIds.add(first.value.taskId);
+ if (decoded.kind === "cancel") {
+ if (decoded.taskId !== undefined) {
+ input.cancelledTaskIds.add(decoded.taskId);
const kept = input.bufferedDeliveries.filter(
(delivery) => !isCancelledTaskDelivery(delivery, input.cancelledTaskIds),
);
@@ -205,13 +224,7 @@ async function waitForNextSessionAction(input: {
continue;
}
- // Child results also arrive through this inbox, but the runtime-action
- // collector owns them. They are not channel deliveries.
- if (first.value.kind === "runtime-action-result") {
- continue;
- }
-
- const deliveryId = first.value.taskDeliveryId ?? first.value.caller?.taskId;
+ const deliveryId = decoded.taskDeliveryId ?? decoded.caller?.taskId;
if (deliveryId !== undefined && isCancelledTaskDeliveryId(deliveryId, input.cancelledTaskIds)) {
continue;
}
@@ -220,20 +233,11 @@ async function waitForNextSessionAction(input: {
input.seenTaskDeliveries.add(deliveryId);
}
- if (first.value.kind === "deliver") {
- if (input.deferDeliveries === true) {
- input.bufferedDeliveries.push(first.value);
- continue;
- }
- return { delivery: first.value, kind: "delivery" };
- }
-
- const delivery = sendCommandToDelivery(first.value);
if (input.deferDeliveries === true) {
- input.bufferedDeliveries.push(delivery);
+ input.bufferedDeliveries.push(decoded);
continue;
}
- return { delivery, kind: "delivery" };
+ return { delivery: decoded, kind: "delivery" };
}
}
diff --git a/packages/eve/src/execution/proxied-deliver-step.ts b/packages/eve/src/execution/proxied-deliver-step.ts
index 93653e64d..8cf692f7c 100644
--- a/packages/eve/src/execution/proxied-deliver-step.ts
+++ b/packages/eve/src/execution/proxied-deliver-step.ts
@@ -7,7 +7,7 @@ import {
} from "#execution/durable-session-store.js";
import { routeDeliverPayload } from "#execution/subagent-hitl-proxy.js";
import { sendTaskInboundPayload } from "#execution/tasks/parent/run-parent.js";
-import { resumeHook } from "#internal/workflow/runtime.js";
+import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";
import type { InputResponse } from "#runtime/input/types.js";
import { findSessionTaskEntry } from "#tasks/session-index.js";
import {
@@ -178,10 +178,7 @@ export async function routeProxiedDeliverStep(
deliveryMetadata: child.metadata.length === 0 ? undefined : child.metadata,
payloads: child.payloads,
};
- await resumeHook(child.childContinuationToken, {
- ...childDelivery,
- payload: coalesceDeliverPayloads(child.payloads),
- });
+ await resumeSessionInbox(child.childContinuationToken, childDelivery);
// Successfully forwarded request IDs are retired so later deliveries
// cannot route through stale entries.
durableSession = retireProxyInputRequests(durableSession, child.retireRequestIds);
diff --git a/packages/eve/src/execution/report-dropped-wire-payload-step.ts b/packages/eve/src/execution/report-dropped-wire-payload-step.ts
new file mode 100644
index 000000000..49f286fdc
--- /dev/null
+++ b/packages/eve/src/execution/report-dropped-wire-payload-step.ts
@@ -0,0 +1,21 @@
+import { createLogger } from "#internal/logging.js";
+
+const log = createLogger("execution.wire");
+
+/**
+ * Surfaces a durable payload dropped by a wire codec's decode.
+ *
+ * Workflow-context consumers cannot log directly — the logging module pulls
+ * Node builtins the workflow driver bundle must not contain — so the report
+ * crosses a step boundary. The recorded step also leaves a durable trace in
+ * the run's event log, which is the operator-visible half of the "drop
+ * loudly, never reinterpret" wire contract.
+ */
+export async function reportDroppedWirePayloadStep(input: {
+ readonly detail: string;
+ readonly family: string;
+}): Promise<void> {
+ "use step";
+
+ log.error("dropping undecodable wire payload", { detail: input.detail, family: input.family });
+}
diff --git a/packages/eve/src/execution/session-command-inbox.integration.test.ts b/packages/eve/src/execution/session-command-inbox.integration.test.ts
index fb33206d4..c4ebbb0a7 100644
--- a/packages/eve/src/execution/session-command-inbox.integration.test.ts
+++ b/packages/eve/src/execution/session-command-inbox.integration.test.ts
@@ -5,7 +5,7 @@ import { sessionCommandInboxWorkflow } from "#internal/testing/session-command-i
import { legacySessionDeliveryWorkflow } from "#internal/testing/legacy-session-delivery-workflow.js";
import { midCohortSessionDeliveryWorkflow } from "#internal/testing/mid-cohort-session-delivery-workflow.js";
import { waitForHook } from "#internal/testing/workflow-test-helpers.js";
-import { getWorld, resumeHook, start } from "#internal/workflow/runtime.js";
+import { getHookByToken, getWorld, resumeHook, start } from "#internal/workflow/runtime.js";
import { sessionCommandHookToken } from "#execution/session-command-token.js";
import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
@@ -41,7 +41,7 @@ describe("session command inbox integration", () => {
}
});
- it("resumes a 0.30.3–0.30.8 parked consumer from a current send command", async () => {
+ it("resumes a 0.30.5–0.30.8 parked consumer from a current send command", async () => {
const token = "http:session-command-inbox:mid-cohort-delivery";
const run = await start(midCohortSessionDeliveryWorkflow, [{ token }]);
@@ -72,6 +72,29 @@ describe("session command inbox integration", () => {
}
});
+ it("stamps the consumer wire version onto inbox hooks, readable pre-resume", async () => {
+ const channelToken = "http:session-command-inbox:version-stamp";
+ const run = await start(sessionCommandInboxWorkflow, [{ token: channelToken }]);
+ const stableToken = sessionCommandHookToken(run.runId);
+
+ try {
+ await Promise.all([
+ waitForHook({ runId: run.runId }, { token: stableToken }),
+ waitForHook({ runId: run.runId }, { token: channelToken }),
+ ]);
+
+ for (const token of [stableToken, channelToken]) {
+ const hook = (await getHookByToken(token)) as {
+ metadata?: { sessionInboxWireVersion?: unknown };
+ };
+ expect(hook.metadata?.sessionInboxWireVersion, `hook ${token}`).toBe(1);
+ }
+ } finally {
+ const status = await run.status;
+ if (status === "pending" || status === "running") await run.cancel();
+ }
+ });
+
it("accepts commands alternately through the stable ID and channel aliases", async () => {
const channelToken = "http:session-command-inbox:both-aliases";
const run = await start(sessionCommandInboxWorkflow, [{ token: channelToken }]);
diff --git a/packages/eve/src/execution/session-command-inbox.test.ts b/packages/eve/src/execution/session-command-inbox.test.ts
index dcf224867..e10f7fa3f 100644
--- a/packages/eve/src/execution/session-command-inbox.test.ts
+++ b/packages/eve/src/execution/session-command-inbox.test.ts
@@ -119,6 +119,10 @@ describe("createSessionCommandInbox", () => {
"A session command inbox cannot change its stable token.",
);
expect(createHookMock).toHaveBeenCalledOnce();
+ expect(createHookMock).toHaveBeenCalledWith({
+ metadata: { sessionInboxWireVersion: 1 },
+ token: "stable",
+ });
await inbox.dispose();
});
diff --git a/packages/eve/src/execution/session-command-inbox.ts b/packages/eve/src/execution/session-command-inbox.ts
index ae29c093e..fdf3f9707 100644
--- a/packages/eve/src/execution/session-command-inbox.ts
+++ b/packages/eve/src/execution/session-command-inbox.ts
@@ -7,15 +7,17 @@ import type {
SessionTimeoutHookPayload,
} from "#channel/types.js";
import { claimHookOwnership, disposeHook } from "#execution/hook-ownership.js";
+import {
+ SESSION_INBOX_WIRE_VERSION,
+ SESSION_INBOX_WIRE_VERSION_METADATA_KEY,
+} from "#execution/wire/session-inbox-contract.js";
/**
* Payloads accepted by a session driver's stable and channel aliases.
*
- * `DeliverHookPayload` is the only delivery format producers persist. The
- * `send` member of `SessionCommand` stays accepted solely for payloads
- * persisted by eve 0.30.3–0.30.8, which wrote the command shape directly;
- * sessions are bounded by the 30-day default timeout, so the decode can be
- * dropped once runs created on those versions have aged out.
+ * This union is the hook's transport typing only; consumers interpret every
+ * payload through `sessionInboxWire.decode` in `execution/wire/session-inbox-wire.ts`,
+ * which owns the versioned wire schema and its legacy-shape fallbacks.
*/
export type SessionInboxPayload =
| DeliverHookPayload
@@ -131,7 +133,16 @@ export function createSessionCommandInbox(): SessionCommandInboxHandle {
};
const createState = (token: string): SessionCommandHookState => {
- const hook = createHook<SessionInboxPayload>({ token });
+ // Stamp the consumer's wire capability so producers can select an encoder
+ // pre-resume. Hooks created before this stamp carry no wire marker:
+ // markerless means the consumer predates the capability and accepts a
+ // legacy shape.
+ const hook = createHook<SessionInboxPayload>({
+ metadata: {
+ [SESSION_INBOX_WIRE_VERSION_METADATA_KEY]: SESSION_INBOX_WIRE_VERSION,
+ },
+ token,
+ });
return {
closed: false,
enabled: false,
diff --git a/packages/eve/src/execution/session-command-wire.test.ts b/packages/eve/src/execution/session-command-wire.test.ts
deleted file mode 100644
index bee53c8ad..000000000
--- a/packages/eve/src/execution/session-command-wire.test.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { sendCommandToDelivery } from "#execution/session-command-wire.js";
-
-describe("sendCommandToDelivery", () => {
- it("emits the deliver envelope with the single-payload compat mirror", () => {
- const payload = { message: "hello" };
-
- const caller = {
- callId: "call-1",
- replyTo: { kind: "hook", token: "parent-tok" },
- subagentName: "child",
- } as const;
- const wire = sendCommandToDelivery({
- auth: null,
- caller,
- kind: "send",
- payload,
- requestId: "req-1",
- turnPolicy: "steer",
- });
-
- expect(wire).toEqual({
- auth: null,
- caller,
- kind: "deliver",
- payload,
- payloads: [payload],
- requestId: "req-1",
- turnPolicy: "steer",
- });
- // The 0.30.3–0.30.8 parked decode reads `.payload`; everything else reads
- // `payloads`. Both views must reference the same delivery.
- expect(wire.payloads[0]).toBe(wire.payload);
- });
-
- it("preserves delivery identity on the durable envelope", () => {
- const delivery = {
- channelKind: "channel:slack",
- channelName: "slack",
- deliveryId: "delivery-1",
- requestId: "request-1",
- };
-
- expect(
- sendCommandToDelivery({ delivery, kind: "send", payload: { message: "hello" } })
- .deliveryMetadata,
- ).toEqual([{ ...delivery, payloadIndex: 0 }]);
- });
-});
diff --git a/packages/eve/src/execution/session-command-wire.ts b/packages/eve/src/execution/session-command-wire.ts
deleted file mode 100644
index d90d59c29..000000000
--- a/packages/eve/src/execution/session-command-wire.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import type { DeliverHookPayload, DeliverPayload, SessionCommand } from "#channel/types.js";
-
-/**
- * The durable delivery envelope plus a transitional single-payload mirror.
- *
- * Consumers pinned to eve 0.30.3–0.30.8 cast any non-control inbox payload to
- * a `send` command and read its `payload` field, so the mirror is what keeps
- * their parked sessions receiving messages. Sessions are bounded by the
- * 30-day default timeout; once runs created on those versions have aged out,
- * drop the mirror and return plain `DeliverHookPayload`.
- */
-export interface WireDeliverHookPayload extends DeliverHookPayload {
- readonly payload: DeliverPayload;
-}
-
-/**
- * Encodes a caller-side `send` command as the durable delivery envelope.
- *
- * `DeliverHookPayload` is the only wire format persisted to session hooks.
- * Hooks outlive deployments, so every producer must emit this envelope and
- * every consumer must keep accepting it; `send` never crosses the durable
- * boundary itself.
- */
-export function sendCommandToDelivery(
- command: Extract<SessionCommand, { readonly kind: "send" }>,
-): WireDeliverHookPayload {
- return {
- auth: command.auth,
- caller: command.caller,
- deliveryMetadata:
- command.delivery === undefined ? undefined : [{ ...command.delivery, payloadIndex: 0 }],
- kind: "deliver",
- payload: command.payload,
- payloads: [command.payload],
- requestId: command.requestId,
- taskDeliveryId: command.taskDeliveryId,
- turnPolicy: command.turnPolicy,
- };
-}
diff --git a/packages/eve/src/execution/session-timeout-steps.test.ts b/packages/eve/src/execution/session-timeout-steps.test.ts
index 854d6aeb7..356fe9a85 100644
--- a/packages/eve/src/execution/session-timeout-steps.test.ts
+++ b/packages/eve/src/execution/session-timeout-steps.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
cancelSessionTimeoutStep,
@@ -9,18 +9,31 @@ import { sessionTimeoutWorkflowReference } from "#execution/workflow-runtime.js"
const cancelRunMock = vi.fn();
const getWorldMock = vi.fn();
+const getHookByTokenMock = vi.fn();
const resumeHookMock = vi.fn();
const startMock = vi.fn();
vi.mock("#compiled/@workflow/core/runtime.js", () => ({
cancelRun: (...args: unknown[]) => cancelRunMock(...args),
+ getHookByToken: (...args: unknown[]) => getHookByTokenMock(...args),
getWorld: (...args: unknown[]) => getWorldMock(...args),
resumeHook: (...args: unknown[]) => resumeHookMock(...args),
start: (...args: unknown[]) => startMock(...args),
}));
+const TIMEOUT_HOOK = {
+ metadata: { sessionInboxWireVersion: 1 },
+ runId: "session-1",
+ token: "session-1:session-timeout",
+};
+
+beforeEach(() => {
+ getHookByTokenMock.mockResolvedValue(TIMEOUT_HOOK);
+});
+
afterEach(() => {
cancelRunMock.mockReset();
+ getHookByTokenMock.mockReset();
getWorldMock.mockReset();
resumeHookMock.mockReset();
startMock.mockReset();
@@ -45,8 +58,9 @@ describe("session timeout steps", () => {
await signalSessionTimeoutStep({ token: "session-1:session-timeout" });
- expect(resumeHookMock).toHaveBeenCalledWith("session-1:session-timeout", {
+ expect(resumeHookMock).toHaveBeenCalledWith(TIMEOUT_HOOK, {
kind: "session-timeout",
+ version: 1,
});
});
diff --git a/packages/eve/src/execution/session-timeout-steps.ts b/packages/eve/src/execution/session-timeout-steps.ts
index 7ec6707a8..a923b3f5b 100644
--- a/packages/eve/src/execution/session-timeout-steps.ts
+++ b/packages/eve/src/execution/session-timeout-steps.ts
@@ -10,7 +10,8 @@ import {
sessionTimeoutWorkflowReference,
} from "#execution/workflow-runtime.js";
import type { SessionTimeoutWorkflowInput } from "#execution/session-timeout-workflow.js";
-import { cancelRun, getWorld, resumeHook } from "#internal/workflow/runtime.js";
+import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";
+import { cancelRun, getWorld } from "#internal/workflow/runtime.js";
import { walkCauseChain } from "#shared/errors.js";
/** Starts the durable timer that signals one session deadline. */
@@ -28,7 +29,7 @@ export async function signalSessionTimeoutStep(input: { readonly token: string }
"use step";
try {
- await resumeHook(input.token, { kind: "session-timeout" });
+ await resumeSessionInbox(input.token, { kind: "session-timeout" });
} catch (error) {
if (!isInactiveTimeoutTarget(error)) {
throw error;
diff --git a/packages/eve/src/execution/tasks/child/steps.ts b/packages/eve/src/execution/tasks/child/steps.ts
index 987b8dec1..080cea471 100644
--- a/packages/eve/src/execution/tasks/child/steps.ts
+++ b/packages/eve/src/execution/tasks/child/steps.ts
@@ -6,7 +6,7 @@ import type {
SubagentInputRequestHookPayload,
} from "#channel/types.js";
import { isTaskWorkflowTargetGone } from "#execution/tasks/workflow-target.js";
-import { resumeHook } from "#internal/workflow/runtime.js";
+import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";
import { createLogger } from "#internal/logging.js";
import {
isTerminalTaskStatus,
@@ -72,7 +72,7 @@ export async function wakeTaskAuthorizationParentStep(input: {
taskDeliveryId: `${input.taskId}:authorization:${input.request.event.type}:${data.turnId}:${data.stepIndex}:${data.sequence}:${taskAuthorizationRequestId(input.request.event)}`,
};
try {
- await resumeHook(input.token, command);
+ await resumeSessionInbox(input.token, command);
} catch (error) {
if (isTaskWorkflowTargetGone(error)) return;
throw error;
@@ -103,7 +103,7 @@ export async function wakeTaskParentStep(input: {
taskDeliveryId: `${input.view.taskId}:ready:${input.view.status}`,
};
try {
- await resumeHook(input.token, command);
+ await resumeSessionInbox(input.token, command);
} catch (error) {
if (isTaskWorkflowTargetGone(error)) {
log.warn("task wake target is gone; the parent session already ended", {
@@ -132,7 +132,7 @@ export async function wakeTaskUpdateParentStep(input: {
taskDeliveryId: `${input.view.taskId}:update:${input.update.childTurnId}:${input.update.childStepIndex}:${input.update.callId}`,
};
try {
- await resumeHook(input.token, command);
+ await resumeSessionInbox(input.token, command);
} catch (error) {
if (isTaskWorkflowTargetGone(error)) return;
throw error;
@@ -162,7 +162,7 @@ export async function wakeTaskInputRequestParentStep(input: {
taskDeliveryId: `${input.taskId}:input:${input.request.event.turnId}:${input.request.event.stepIndex}:${input.request.event.sequence}`,
};
try {
- await resumeHook(input.token, command);
+ await resumeSessionInbox(input.token, command);
} catch (error) {
if (isTaskWorkflowTargetGone(error)) return;
throw error;
@@ -207,7 +207,7 @@ export async function deliverTaskInputResponsesStep(input: {
if (!response.ok)
throw new Error(`Remote task input delivery failed with HTTP ${response.status}.`);
} else {
- await resumeHook(input.answer.childContinuationToken, command);
+ await resumeSessionInbox(input.answer.childContinuationToken, command);
}
return "delivered";
} catch (error) {
diff --git a/packages/eve/src/execution/turn-control-receiver.test.ts b/packages/eve/src/execution/turn-control-receiver.test.ts
index 76d4a5b3c..efa044880 100644
--- a/packages/eve/src/execution/turn-control-receiver.test.ts
+++ b/packages/eve/src/execution/turn-control-receiver.test.ts
@@ -4,6 +4,7 @@ import type { DeliverHookPayload } from "#channel/types.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
import { forwardTurnCancellationStep } from "#execution/forward-turn-cancellation-step.js";
import { forwardTurnDeliveryStep } from "#execution/forward-turn-delivery-step.js";
+import { reportDroppedWirePayloadStep } from "#execution/report-dropped-wire-payload-step.js";
import type { SessionCommandInbox, SessionInboxPayload } from "#execution/session-command-inbox.js";
import type { TurnControlPayload } from "#execution/turn-control-protocol.js";
import { TurnControlReceiver } from "#execution/turn-control-receiver.js";
@@ -22,6 +23,10 @@ vi.mock("./forward-turn-cancellation-step.js", () => ({
forwardTurnCancellationStep: vi.fn(),
}));
+vi.mock("./report-dropped-wire-payload-step.js", () => ({
+ reportDroppedWirePayloadStep: vi.fn(),
+}));
+
describe("TurnControlReceiver", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -131,12 +136,12 @@ describe("TurnControlReceiver", () => {
});
expect(action.kind).toBe("park");
+ // Decode normalizes: the wire-only mirror and `v` never reach buffers.
expect(bufferedDeliveries).toEqual([
{
auth: undefined,
caller: undefined,
kind: "deliver",
- payload: { message: "follow up" },
payloads: [{ message: "follow up" }],
requestId: undefined,
turnPolicy: undefined,
@@ -220,6 +225,31 @@ describe("TurnControlReceiver", () => {
});
});
+ it("drops an unknown wire version loudly and keeps consuming the inbox", async () => {
+ installControlHook([parkResult()], true);
+ const bufferedDeliveries: DeliverHookPayload[] = [];
+
+ const action = await runReceiver(bufferedDeliveries, {
+ commandInbox: createCommandInbox([
+ { kind: "deliver", payloads: [{ message: "from the future" }], version: 99 } as never,
+ { kind: "send", payload: { message: "still delivered" } },
+ ]),
+ });
+
+ expect(action.kind).toBe("park");
+ expect(reportDroppedWirePayloadStep).toHaveBeenCalledOnce();
+ expect(bufferedDeliveries).toEqual([
+ {
+ auth: undefined,
+ caller: undefined,
+ kind: "deliver",
+ payloads: [{ message: "still delivered" }],
+ requestId: undefined,
+ turnPolicy: undefined,
+ },
+ ]);
+ });
+
it("forwards cancel and reset through the active turn's private hook", async () => {
installControlHook([parkResult()], true);
const bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset"> = [];
diff --git a/packages/eve/src/execution/turn-control-receiver.ts b/packages/eve/src/execution/turn-control-receiver.ts
index 475a1be54..0b6c3c12a 100644
--- a/packages/eve/src/execution/turn-control-receiver.ts
+++ b/packages/eve/src/execution/turn-control-receiver.ts
@@ -1,14 +1,19 @@
import { createHook, type Hook } from "#compiled/@workflow/core/index.js";
-import type { DeliverHookPayload, SessionCommand } from "#channel/types.js";
+import type { DeliverHookPayload } from "#channel/types.js";
import { forwardTurnCancellationStep } from "#execution/forward-turn-cancellation-step.js";
import type { TurnControlPayload } from "#execution/turn-control-protocol.js";
import { forwardTurnDeliveryStep } from "#execution/forward-turn-delivery-step.js";
import { closeHookIterator, disposeHook } from "#execution/hook-ownership.js";
import type { NextDriverAction } from "#execution/next-driver-action.js";
-import type { SessionCommandInbox, SessionInboxPayload } from "#execution/session-command-inbox.js";
-import { sendCommandToDelivery } from "#execution/session-command-wire.js";
+import type { SessionCommandInbox } from "#execution/session-command-inbox.js";
import { turnCancellationHookToken } from "#execution/turn-cancellation-token.js";
+import { reportDroppedWirePayloadStep } from "#execution/report-dropped-wire-payload-step.js";
+import {
+ sessionInboxWire,
+ SessionInboxWireError,
+ type DecodedSessionInbox,
+} from "#execution/wire/session-inbox-wire.js";
import { rebuildSerializableError } from "#execution/workflow-errors.js";
type DeliveryRequest = Extract<TurnControlPayload, { readonly kind: "turn-delivery-request" }>;
@@ -79,18 +84,13 @@ export class TurnControlReceiver {
}
private async handleSessionCommand(
- command: SessionInboxPayload,
+ command: DecodedSessionInbox,
): Promise<TurnDriverAction | undefined> {
if (command.kind === "deliver") {
if (!this.acceptTaskDelivery(command)) return undefined;
await this.bufferDelivery(command);
return undefined;
}
- if (command.kind === "send") {
- if (!this.acceptTaskDelivery(command)) return undefined;
- await this.bufferDelivery(sendCommandToDelivery(command));
- return undefined;
- }
if (command.kind === "clear" || command.kind === "compact") {
this.bufferedSessionControls.push(command.kind);
return undefined;
@@ -99,9 +99,6 @@ export class TurnControlReceiver {
this.bufferedSessionControls.push("expired");
return undefined;
}
- if (command.kind === "runtime-action-result") {
- return undefined;
- }
if (command.kind === "cancel") {
if (command.taskId !== undefined) this.discardTaskDeliveries(command.taskId);
const turnId =
@@ -157,7 +154,7 @@ export class TurnControlReceiver {
}
private async nextControlOrCommand(): Promise<
- | { readonly command: SessionInboxPayload; readonly kind: "command" }
+ | { readonly command: DecodedSessionInbox; readonly kind: "command" }
| { readonly kind: "control"; readonly payload: TurnControlPayload }
> {
const winner = await Promise.race([
@@ -170,7 +167,20 @@ export class TurnControlReceiver {
throw new Error("Session command inbox closed before the active turn settled.");
}
this.commandInbox.consumeNext();
- return { command: winner.value.value, kind: "command" };
+ // Runtime-action results belong to the active turn's private inbox. A
+ // late value on a retired session alias stays ignorable, but it is not
+ // part of the versioned session-command wire family.
+ if (winner.value.value.kind === "runtime-action-result") {
+ return await this.nextControlOrCommand();
+ }
+ try {
+ return { command: sessionInboxWire.decode(winner.value.value), kind: "command" };
+ } catch (error) {
+ if (!(error instanceof SessionInboxWireError)) throw error;
+ // Drop loudly and keep servicing the turn; see sessionInboxWire.decode.
+ await reportDroppedWirePayloadStep({ detail: error.message, family: "session-inbox" });
+ return await this.nextControlOrCommand();
+ }
}
this.consumeControl();
@@ -230,26 +240,28 @@ export class TurnControlReceiver {
}
this.commandInbox.consumeNext();
- if (winner.value.value.kind === "deliver") {
- if (!this.acceptTaskDelivery(winner.value.value)) continue;
- if (deliveryHasMessage(winner.value.value)) {
- await this.bufferDelivery(winner.value.value);
- } else {
- delivery = winner.value.value;
- }
+ if (winner.value.value.kind === "runtime-action-result") {
+ continue;
+ }
+ let decoded: DecodedSessionInbox;
+ try {
+ decoded = sessionInboxWire.decode(winner.value.value);
+ } catch (error) {
+ if (!(error instanceof SessionInboxWireError)) throw error;
+ // Drop loudly and keep servicing the request; see sessionInboxWire.decode.
+ await reportDroppedWirePayloadStep({ detail: error.message, family: "session-inbox" });
continue;
}
- if (winner.value.value.kind === "send") {
- if (!this.acceptTaskDelivery(winner.value.value)) continue;
- const candidate = sendCommandToDelivery(winner.value.value);
- if (deliveryHasMessage(candidate)) {
- await this.bufferDelivery(candidate);
+ if (decoded.kind === "deliver") {
+ if (!this.acceptTaskDelivery(decoded)) continue;
+ if (deliveryHasMessage(decoded)) {
+ await this.bufferDelivery(decoded);
} else {
- delivery = candidate;
+ delivery = decoded;
}
continue;
}
- const terminal = await this.handleSessionCommand(winner.value.value);
+ const terminal = await this.handleSessionCommand(decoded);
if (terminal !== undefined) return terminal;
}
@@ -319,9 +331,7 @@ export class TurnControlReceiver {
}
}
- private acceptTaskDelivery(
- command: DeliverHookPayload | Extract<SessionCommand, { readonly kind: "send" }>,
- ): boolean {
+ private acceptTaskDelivery(command: DeliverHookPayload): boolean {
const deliveryId = command.taskDeliveryId ?? command.caller?.taskId;
if (deliveryId === undefined) return true;
if (this.originatesFromCancelledTask(deliveryId)) return false;
diff --git a/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v1.test.ts.snap b/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v1.test.ts.snap
new file mode 100644
index 000000000..696870747
--- /dev/null
+++ b/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v1.test.ts.snap
@@ -0,0 +1,3 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`session inbox wire v1 > pins the complete schema byte for byte 1`] = `"{"$schema":"https://json-schema.org/draft/2020-12/schema","oneOf":[{"additionalProperties":false,"properties":{"auth":{"anyOf":[{"additionalProperties":false,"properties":{"attributes":{"additionalProperties":{"anyOf":[{"type":"string"},{"items":{"type":"string"},"type":"array"}]},"propertyNames":{"type":"string"},"type":"object"},"authenticator":{"type":"string"},"issuer":{"type":"string"},"principalId":{"type":"string"},"principalType":{"type":"string"},"subject":{"type":"string"}},"required":["attributes","authenticator","principalId","principalType"],"type":"object"},{"type":"null"}]},"caller":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"replyTo":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"hook","type":"string"},"token":{"type":"string"}},"required":["kind","token"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"callback","type":"string"},"token":{"type":"string"},"url":{"type":"string"}},"required":["kind","token","url"],"type":"object"}]},"subagentName":{"type":"string"},"taskId":{"type":"string"}},"required":["callId","replyTo","subagentName"],"type":"object"},"deliveryMetadata":{"items":{"additionalProperties":false,"properties":{"channelKind":{"type":"string"},"channelName":{"type":"string"},"deliveryId":{"type":"string"},"payloadIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"requestId":{"type":"string"},"requestTraceContext":{"additionalProperties":false,"properties":{"spanId":{"type":"string"},"traceFlags":{"type":"number"},"traceId":{"type":"string"}},"required":["spanId","traceFlags","traceId"],"type":"object"}},"required":["channelKind","channelName","deliveryId","payloadIndex"],"type":"object"},"type":"array"},"kind":{"const":"deliver","type":"string"},"payload":{"additionalProperties":{},"properties":{"context":{"items":{"type":"string"},"type":"array"},"inputResponses":{"items":{"additionalProperties":false,"properties":{"optionId":{"type":"string"},"requestId":{"type":"string"},"text":{"type":"string"}},"required":["requestId"],"type":"object"},"type":"array"},"message":{"anyOf":[{"type":"string"},{"items":{"oneOf":[{"additionalProperties":false,"properties":{"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"text":{"type":"string"},"type":{"const":"text","type":"string"}},"required":["text","type"],"type":"object"},{"additionalProperties":false,"properties":{"image":{},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"image","type":"string"}},"required":["image","type"],"type":"object"},{"additionalProperties":false,"properties":{"data":{},"filename":{"type":"string"},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"file","type":"string"}},"required":["data","mediaType","type"],"type":"object"}]},"type":"array"}]},"outputSchema":{},"task":{"additionalProperties":false,"properties":{"authorizationEvents":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childSessionId":{"type":"string"},"event":{},"kind":{"const":"subagent-authorization-event","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"inputRequests":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childContinuationToken":{"type":"string"},"childSessionId":{"type":"string"},"event":{"additionalProperties":false,"properties":{"requests":{"items":{"additionalProperties":false,"properties":{"action":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"input":{},"kind":{"const":"tool-call","type":"string"},"toolName":{"type":"string"}},"required":["callId","input","kind","toolName"],"type":"object"},"allowFreeform":{"description":"Whether the user may answer with freeform text instead of selecting one of the provided options.","type":"boolean"},"display":{"description":"Rendering hint: the channel uses this to pick a UX treatment.","enum":["confirmation","select","text"],"type":"string"},"kind":{"description":"Framework-owned request source used to resolve, route, and render the response.","enum":["question","session-limit","tool-approval"],"type":"string"},"options":{"description":"Selectable answer options to present to the user.","items":{"additionalProperties":false,"properties":{"description":{"description":"Optional additional context for this option.","type":"string"},"id":{"description":"Stable identifier for the option.","type":"string"},"label":{"description":"User-facing label for the option.","type":"string"},"style":{"description":"Visual treatment hint for the option.","enum":["primary","danger","default"],"type":"string"}},"required":["id","label"],"type":"object"},"type":"array"},"prompt":{"description":"The prompt to present to the user.","type":"string"},"requestId":{"description":"Stable identifier for this request.","type":"string"}},"required":["action","kind","prompt","requestId"],"type":"object"},"type":"array"},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"turnId":{"type":"string"}},"required":["requests","sequence","stepIndex","turnId"],"type":"object"},"kind":{"const":"subagent-input-request","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childContinuationToken","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"views":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"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"},"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":{"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"inputRequests":{"items":{},"type":"array"},"metadata":{"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"},"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":{"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":{"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"},"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":{"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":{"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"},"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":{"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"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"},"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":{"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"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"},"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":{"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"inputRequests":{"items":{},"type":"array"},"metadata":{"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"},"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":{"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":{"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"},"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":{"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":{"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"},"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":{"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"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"},"status":{"const":"cancelled","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"}]},"type":"array"}},"type":"object"}},"type":"object"},"type":"array"},"requestId":{"type":"string"},"taskDeliveryId":{"type":"string"},"turnPolicy":{"enum":["queue","steer"],"type":"string"},"version":{"const":1,"type":"number"}},"required":["kind","payloads","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"session-timeout","type":"string"},"version":{"const":1,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"clear","type":"string"},"version":{"const":1,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"compact","type":"string"},"version":{"const":1,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"reset","type":"string"},"reason":{"type":"string"},"version":{"const":1,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"cancel","type":"string"},"taskId":{"type":"string"},"turnId":{"type":"string"},"version":{"const":1,"type":"number"}},"required":["kind","version"],"type":"object"}]}"`;
diff --git a/packages/eve/src/execution/wire/session-inbox-consumer-compatibility.test.ts b/packages/eve/src/execution/wire/session-inbox-consumer-compatibility.test.ts
new file mode 100644
index 000000000..81ff0bb43
--- /dev/null
+++ b/packages/eve/src/execution/wire/session-inbox-consumer-compatibility.test.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it } from "vitest";
+
+import { sessionInboxWire } from "#execution/wire/session-inbox-encoder.js";
+
+interface Eve0308TurnControlReceiver {
+ bufferedDeliveries: unknown[];
+ handleSessionCommand(command: unknown): Promise<unknown>;
+}
+
+interface Eve0308TurnControlReceiverConstructor {
+ readonly prototype: Eve0308TurnControlReceiver;
+}
+
+describe("session inbox consumer compatibility", () => {
+ it("loads the published eve 0.30.8 turn receiver and accepts its native send shape", async () => {
+ const receiver = await createEve0308TurnControlReceiver();
+
+ await expect(
+ receiver.handleSessionCommand({ kind: "send", payload: { message: "follow-up" } }),
+ ).resolves.toBeUndefined();
+ expect(receiver.bufferedDeliveries).toEqual([expectedDelivery]);
+ });
+
+ it("keeps current sends readable by the published eve 0.30.8 turn receiver", async () => {
+ const receiver = await createEve0308TurnControlReceiver();
+ const wire = sessionInboxWire.encode(
+ { kind: "send", payload: { message: "follow-up" } },
+ { variant: "send", version: 0 },
+ );
+
+ await expect(receiver.handleSessionCommand(wire)).resolves.toBeUndefined();
+ expect(receiver.bufferedDeliveries).toEqual([expectedDelivery]);
+ });
+
+ it("reproduces the failure when a v1 delivery is sent to the published eve 0.30.8 turn receiver", async () => {
+ const receiver = await createEve0308TurnControlReceiver();
+ const wire = sessionInboxWire.encode(
+ { kind: "send", payload: { message: "follow-up" } },
+ { version: 1 },
+ );
+
+ await expect(receiver.handleSessionCommand(wire)).rejects.toThrow(
+ /Unsupported session command:.*deliver/,
+ );
+ expect(receiver.bufferedDeliveries).toEqual([]);
+ });
+});
+
+const expectedDelivery = {
+ auth: undefined,
+ caller: undefined,
+ kind: "deliver",
+ payloads: [{ message: "follow-up" }],
+ requestId: undefined,
+};
+
+async function createEve0308TurnControlReceiver(): Promise<Eve0308TurnControlReceiver> {
+ const packageEntry = import.meta.resolve("historical-eve-0-30-8");
+ const receiverModuleUrl = new URL("./execution/turn-control-receiver.js", packageEntry);
+ const receiverModule = (await import(receiverModuleUrl.href)) as {
+ readonly TurnControlReceiver: Eve0308TurnControlReceiverConstructor;
+ };
+ // The decoder is the compatibility boundary. Bypass construction so loading
+ // the published method does not also require a live 0.30.8 Workflow world.
+ const receiver = Object.create(
+ receiverModule.TurnControlReceiver.prototype,
+ ) as Eve0308TurnControlReceiver;
+ receiver.bufferedDeliveries = [];
+ return receiver;
+}
diff --git a/packages/eve/src/execution/wire/session-inbox-contract.ts b/packages/eve/src/execution/wire/session-inbox-contract.ts
new file mode 100644
index 000000000..5b65d4ad9
--- /dev/null
+++ b/packages/eve/src/execution/wire/session-inbox-contract.ts
@@ -0,0 +1,33 @@
+/** Every explicit session-inbox wire version still supported by producers. */
+export const SESSION_INBOX_WIRE_VERSIONS = [1] as const;
+
+export type SessionInboxWireVersion = (typeof SESSION_INBOX_WIRE_VERSIONS)[number];
+
+/** Current persisted session-inbox wire version. */
+export const SESSION_INBOX_WIRE_VERSION =
+ SESSION_INBOX_WIRE_VERSIONS[SESSION_INBOX_WIRE_VERSIONS.length - 1]!;
+
+/** Hook metadata field advertising the consumer's inbox wire capability. */
+export const SESSION_INBOX_WIRE_VERSION_METADATA_KEY = "sessionInboxWireVersion";
+
+/**
+ * The consumer wire selected before a producer persists a payload.
+ *
+ * Version 0 had two incompatible unversioned shapes, so its historical
+ * variants remain explicit rather than pretending they were one protocol.
+ */
+export type SessionInboxWireTarget =
+ | { readonly variant: "deliver" | "send"; readonly version: 0 }
+ | { readonly version: SessionInboxWireVersion };
+
+export function isSessionInboxWireVersion(value: unknown): value is SessionInboxWireVersion {
+ return SESSION_INBOX_WIRE_VERSIONS.some((version) => version === value);
+}
+
+/** Raised when a session inbox value violates its versioned wire contract. */
+export class SessionInboxWireError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "SessionInboxWireError";
+ }
+}
diff --git a/packages/eve/src/execution/wire/session-inbox-encoder.ts b/packages/eve/src/execution/wire/session-inbox-encoder.ts
new file mode 100644
index 000000000..6ad30c5c7
--- /dev/null
+++ b/packages/eve/src/execution/wire/session-inbox-encoder.ts
@@ -0,0 +1,60 @@
+import type {
+ DeliverHookPayload,
+ SessionCommand,
+ SessionTimeoutHookPayload,
+} from "#channel/types.js";
+import {
+ encodeSessionCommandV1,
+ type SessionInboxWireV1,
+} from "#execution/wire/session-inbox-wire.v1.js";
+import {
+ isSessionInboxWireVersion,
+ SessionInboxWireError,
+ type SessionInboxWireTarget,
+ type SessionInboxWireVersion,
+} from "#execution/wire/session-inbox-contract.js";
+import { encodeSessionCommandV0 } from "#execution/wire/session-inbox-wire.v0.js";
+
+type SessionInboxCommand = DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload;
+
+/** Current wire type consumed after migration. */
+export type SessionInboxWire = SessionInboxWireV1;
+
+type LegacySessionInboxWireTarget = Extract<SessionInboxWireTarget, { readonly version: 0 }>;
+type VersionedSessionInboxEncoder = (command: SessionInboxCommand) => unknown;
+
+const versionedEncoders = {
+ 1: encodeSessionCommandV1,
+} 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: SessionInboxWireVersion },
+): unknown;
+function encode(
+ command: SessionInboxCommand,
+ target: LegacySessionInboxWireTarget,
+): Record<string, unknown>;
+function encode(
+ command: SessionInboxCommand,
+ target: SessionInboxWireTarget,
+): SessionInboxWireV1 | Record<string, unknown>;
+function encode(
+ command: SessionInboxCommand,
+ target: SessionInboxWireTarget,
+): SessionInboxWireV1 | Record<string, unknown> {
+ if (target.version === 0) {
+ return encodeSessionCommandV0(encodeSessionCommandV1(command), target.variant);
+ }
+ if (isSessionInboxWireVersion(target.version)) {
+ return versionedEncoders[target.version](command) as SessionInboxWireV1;
+ }
+ throw new SessionInboxWireError(
+ `Cannot encode session inbox payload for unknown wire version ${JSON.stringify((target as { version?: unknown }).version)}.`,
+ );
+}
+
+/** 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
new file mode 100644
index 000000000..6a3da7b97
--- /dev/null
+++ b/packages/eve/src/execution/wire/session-inbox-resume.test.ts
@@ -0,0 +1,103 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";
+import { sessionCommandHookToken } from "#execution/session-command-token.js";
+import { SESSION_INBOX_WIRE_VERSIONS } from "#execution/wire/session-inbox-contract.js";
+import {
+ resolveSessionInboxWireTarget,
+ resumeSessionInbox,
+} from "#execution/wire/session-inbox-resume.js";
+
+const getHookByTokenMock = vi.fn();
+const resumeHookMock = vi.fn();
+
+vi.mock("#compiled/@workflow/core/runtime.js", () => ({
+ getHookByToken: (...args: unknown[]) => getHookByTokenMock(...args),
+ resumeHook: (...args: unknown[]) => resumeHookMock(...args),
+}));
+
+afterEach(() => {
+ getHookByTokenMock.mockReset();
+ resumeHookMock.mockReset();
+});
+
+describe("session inbox target resolution", () => {
+ it.each(SESSION_INBOX_WIRE_VERSIONS)(
+ "uses wire version %i advertised by a stamped hook",
+ async (version) => {
+ const hook = sessionHook("session-1", "channel-1", {
+ sessionInboxWireVersion: version,
+ });
+
+ await expect(resolveSessionInboxWireTarget(hook)).resolves.toEqual({ version });
+ expect(getHookByTokenMock).not.toHaveBeenCalled();
+ },
+ );
+
+ it("selects raw send for a markerless stable hook", async () => {
+ const token = sessionCommandHookToken("session-1");
+
+ await expect(resolveSessionInboxWireTarget(sessionHook("session-1", token))).resolves.toEqual({
+ variant: "send",
+ version: 0,
+ });
+ expect(getHookByTokenMock).not.toHaveBeenCalled();
+ });
+
+ it("selects raw send for a markerless continuation owned by the stable-inbox cohort", async () => {
+ getHookByTokenMock.mockResolvedValue(
+ sessionHook("session-1", sessionCommandHookToken("session-1")),
+ );
+
+ await expect(
+ resolveSessionInboxWireTarget(sessionHook("session-1", "continuation-1")),
+ ).resolves.toEqual({ variant: "send", version: 0 });
+ });
+
+ it("selects deliver for a markerless continuation without a stable inbox", async () => {
+ getHookByTokenMock.mockRejectedValue(
+ new HookNotFoundError(sessionCommandHookToken("session-1")),
+ );
+
+ await expect(
+ resolveSessionInboxWireTarget(sessionHook("session-1", "continuation-1")),
+ ).resolves.toEqual({ variant: "deliver", version: 0 });
+ });
+
+ it("rejects an advertised unknown version before persistence", async () => {
+ await expect(
+ resolveSessionInboxWireTarget(
+ sessionHook("session-1", "continuation-1", { sessionInboxWireVersion: 99 }),
+ ),
+ ).rejects.toThrow(/unsupported wire version 99/);
+ expect(getHookByTokenMock).not.toHaveBeenCalled();
+ });
+});
+
+describe("resumeSessionInbox", () => {
+ it("encodes for the resolved consumer and resumes the exact inspected hook", async () => {
+ const hook = sessionHook("session-1", "continuation-1", { sessionInboxWireVersion: 1 });
+ getHookByTokenMock.mockResolvedValue(hook);
+ resumeHookMock.mockResolvedValue(hook);
+
+ await resumeSessionInbox("continuation-1", {
+ kind: "send",
+ payload: { message: "follow-up" },
+ });
+
+ expect(getHookByTokenMock).toHaveBeenCalledWith("continuation-1");
+ expect(resumeHookMock).toHaveBeenCalledWith(hook, {
+ auth: undefined,
+ caller: undefined,
+ kind: "deliver",
+ payload: { message: "follow-up" },
+ payloads: [{ message: "follow-up" }],
+ requestId: undefined,
+ version: 1,
+ });
+ });
+});
+
+function sessionHook(runId: string, token: string, metadata?: unknown) {
+ return { metadata, runId, token } as never;
+}
diff --git a/packages/eve/src/execution/wire/session-inbox-resume.ts b/packages/eve/src/execution/wire/session-inbox-resume.ts
new file mode 100644
index 000000000..2868dd7ab
--- /dev/null
+++ b/packages/eve/src/execution/wire/session-inbox-resume.ts
@@ -0,0 +1,61 @@
+import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";
+
+import type {
+ DeliverHookPayload,
+ SessionCommand,
+ SessionTimeoutHookPayload,
+} from "#channel/types.js";
+import { sessionCommandHookToken } from "#execution/session-command-token.js";
+import {
+ SESSION_INBOX_WIRE_VERSION_METADATA_KEY,
+ isSessionInboxWireVersion,
+ SessionInboxWireError,
+ type SessionInboxWireTarget,
+} from "#execution/wire/session-inbox-contract.js";
+import { sessionInboxWire } from "#execution/wire/session-inbox-encoder.js";
+import { getHookByToken, resumeHook } from "#internal/workflow/runtime.js";
+import { isObject } from "#shared/guards.js";
+
+type ResumedSessionInboxHook = Awaited<ReturnType<typeof resumeHook>>;
+
+/** Resolves the consumer contract, encodes for it, and resumes that exact hook. */
+export async function resumeSessionInbox(
+ token: string,
+ command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload,
+): Promise<ResumedSessionInboxHook> {
+ const hook = await getHookByToken(token);
+ const target = await resolveSessionInboxWireTarget(hook);
+ return await resumeHook(hook, sessionInboxWire.encode(command, target));
+}
+
+type SessionInboxHook = Awaited<ReturnType<typeof getHookByToken>>;
+
+/** Selects the encoder understood by a persisted hook's consumer deployment. */
+export async function resolveSessionInboxWireTarget(
+ hook: SessionInboxHook,
+): Promise<SessionInboxWireTarget> {
+ const metadata = isObject(hook.metadata) ? hook.metadata : undefined;
+ if (metadata !== undefined && SESSION_INBOX_WIRE_VERSION_METADATA_KEY in metadata) {
+ const version = metadata[SESSION_INBOX_WIRE_VERSION_METADATA_KEY];
+ if (isSessionInboxWireVersion(version)) return { version };
+ throw new SessionInboxWireError(
+ `Session inbox target declares unsupported wire version ${JSON.stringify(version)}.`,
+ );
+ }
+
+ const stableToken = sessionCommandHookToken(hook.runId);
+ if (hook.token === stableToken) return { variant: "send", version: 0 };
+
+ try {
+ const stableHook = await getHookByToken(stableToken);
+ if (stableHook.runId !== hook.runId) {
+ throw new SessionInboxWireError(
+ `Stable session inbox ${JSON.stringify(stableToken)} belongs to run ${JSON.stringify(stableHook.runId)}, expected ${JSON.stringify(hook.runId)}.`,
+ );
+ }
+ return { variant: "send", version: 0 };
+ } catch (error) {
+ if (HookNotFoundError.is(error)) return { variant: "deliver", version: 0 };
+ throw error;
+ }
+}
diff --git a/packages/eve/src/execution/wire/session-inbox-wire.ts b/packages/eve/src/execution/wire/session-inbox-wire.ts
new file mode 100644
index 000000000..5146a5f6a
--- /dev/null
+++ b/packages/eve/src/execution/wire/session-inbox-wire.ts
@@ -0,0 +1,105 @@
+import type {
+ DeliverHookPayload,
+ DeliverPayload,
+ SessionCommand,
+ SessionTimeoutHookPayload,
+} from "#channel/types.js";
+import {
+ runMigrationChain,
+ type VersionMigration,
+} from "#execution/durable-session-migrations/chain.js";
+import {
+ SESSION_INBOX_WIRE_VERSION,
+ SessionInboxWireError,
+} from "#execution/wire/session-inbox-contract.js";
+import type { SessionInboxWire } from "#execution/wire/session-inbox-encoder.js";
+import { sessionInboxWireV0Migration } from "#execution/wire/session-inbox-wire.v0.js";
+
+/**
+ * The session inbox wire family: every payload persisted to a session's
+ * durable inbox hooks crosses through `sessionInboxWire.encode` /
+ * `sessionInboxWire.decode`.
+ *
+ * Historic migrations live in `session-inbox-wire.vN.ts` modules; the
+ * current schema and encoder live in the current version module. This file
+ * remains the dependency-free decoder facade reached by the workflow body.
+ *
+ * See research/session-inbox-wire-schema.md and issue #1765.
+ */
+
+/** A persisted inbox payload normalized for consumption; `send` never survives decode. */
+export type DecodedSessionInbox =
+ | DeliverHookPayload
+ | SessionTimeoutHookPayload
+ | Extract<SessionCommand, { readonly kind: "cancel" | "clear" | "compact" | "reset" }>;
+
+export { SessionInboxWireError } from "#execution/wire/session-inbox-contract.js";
+
+/** Prefixes chain and schema failures alike, so messages read as one voice. */
+const WIRE_LABEL = "session inbox payload";
+
+const sessionInboxMigrations: readonly VersionMigration[] = [sessionInboxWireV0Migration];
+
+/**
+ * Decodes a persisted inbox payload or throws {@link SessionInboxWireError}.
+ *
+ * Unknown newer versions and shape mismatches both throw: a lost delivery
+ * with an operator-visible signal is the designed failure; a reinterpreted
+ * delivery is the bug this module exists to prevent.
+ */
+function decode(value: unknown): DecodedSessionInbox {
+ let migrated: unknown;
+ try {
+ migrated = runMigrationChain({
+ initialVersion: 0,
+ label: WIRE_LABEL,
+ migrations: sessionInboxMigrations,
+ targetVersion: SESSION_INBOX_WIRE_VERSION,
+ value,
+ });
+ } catch (error) {
+ throw new SessionInboxWireError(error instanceof Error ? error.message : String(error));
+ }
+
+ const wire = migrated as Partial<SessionInboxWire>;
+ if (wire.version !== SESSION_INBOX_WIRE_VERSION) {
+ throw new SessionInboxWireError(
+ `${WIRE_LABEL} declares version ${JSON.stringify(wire.version)}, expected ${SESSION_INBOX_WIRE_VERSION}.`,
+ );
+ }
+ return normalizeWire(wire as SessionInboxWire);
+}
+
+/** Workflow-safe consumer facade. */
+export const sessionInboxWire = { decode } as const;
+
+/** Strips wire-only fields (`version`, the deliver mirror) for consumption. */
+function normalizeWire(wire: SessionInboxWire): DecodedSessionInbox {
+ switch (wire.kind) {
+ case "deliver":
+ return {
+ auth: wire.auth,
+ caller: wire.caller,
+ deliveryMetadata: wire.deliveryMetadata,
+ kind: "deliver",
+ payloads: wire.payloads as readonly DeliverPayload[],
+ requestId: wire.requestId,
+ taskDeliveryId: wire.taskDeliveryId,
+ turnPolicy: wire.turnPolicy,
+ };
+ case "session-timeout":
+ return { kind: "session-timeout" };
+ case "clear":
+ return { kind: "clear" };
+ case "compact":
+ return { kind: "compact" };
+ case "reset":
+ return { kind: "reset", reason: wire.reason };
+ case "cancel":
+ return { kind: "cancel", taskId: wire.taskId, turnId: wire.turnId };
+ default:
+ throw new SessionInboxWireError(
+ `${WIRE_LABEL} has an unrecognized kind ${JSON.stringify((wire as { kind?: unknown }).kind)}.`,
+ );
+ }
+}
diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v0.test.ts b/packages/eve/src/execution/wire/session-inbox-wire.v0.test.ts
new file mode 100644
index 000000000..14e470316
--- /dev/null
+++ b/packages/eve/src/execution/wire/session-inbox-wire.v0.test.ts
@@ -0,0 +1,102 @@
+import { describe, expect, it } from "vitest";
+
+import { sessionInboxWire as sessionInboxWireEncoder } from "#execution/wire/session-inbox-encoder.js";
+import {
+ sessionInboxWire as sessionInboxWireDecoder,
+ SessionInboxWireError,
+} from "#execution/wire/session-inbox-wire.js";
+
+/** Every payload shape persisted before explicit wire versioning. */
+const FROZEN_FIXTURES: ReadonlyArray<{
+ readonly name: string;
+ readonly payload: string;
+ readonly decoded: unknown;
+}> = [
+ {
+ name: "legacy deliver envelope (≤0.30.4 producers)",
+ payload: '{"kind":"deliver","payloads":[{"message":"legacy"}]}',
+ decoded: { kind: "deliver", payloads: [{ message: "legacy" }] },
+ },
+ {
+ name: "raw send command (0.30.5–0.31.0 producers)",
+ payload:
+ '{"auth":null,"delivery":{"channelKind":"http","channelName":"web","deliveryId":"delivery-0"},"kind":"send","payload":{"message":"mid"},"requestId":"req-0","taskDeliveryId":"task-delivery-0","turnPolicy":"queue"}',
+ decoded: {
+ auth: null,
+ deliveryMetadata: [
+ {
+ channelKind: "http",
+ channelName: "web",
+ deliveryId: "delivery-0",
+ payloadIndex: 0,
+ },
+ ],
+ kind: "deliver",
+ payloads: [{ message: "mid" }],
+ requestId: "req-0",
+ taskDeliveryId: "task-delivery-0",
+ turnPolicy: "queue",
+ },
+ },
+ {
+ name: "unversioned cancel control",
+ payload: '{"kind":"cancel","turnId":"turn_1"}',
+ decoded: { kind: "cancel", turnId: "turn_1" },
+ },
+ {
+ name: "unversioned session-timeout control",
+ payload: '{"kind":"session-timeout"}',
+ decoded: { kind: "session-timeout" },
+ },
+];
+
+describe("session inbox wire v0", () => {
+ it.each(FROZEN_FIXTURES)("migrates the frozen $name fixture", ({ payload, decoded }) => {
+ expect(sessionInboxWireDecoder.decode(JSON.parse(payload))).toEqual(decoded);
+ });
+
+ it.each([
+ ["a malformed legacy deliver", { kind: "deliver", payloads: "nope" }],
+ ["a malformed legacy send", { kind: "send", payload: "nope" }],
+ ["legacy send with malformed delivery metadata", { kind: "send", payload: {}, delivery: 1 }],
+ ["a non-object payload", "deliver"],
+ ])("rejects %s instead of reinterpreting it", (_name, payload) => {
+ expect(() => sessionInboxWireDecoder.decode(payload)).toThrowError(SessionInboxWireError);
+ });
+
+ it("encodes sends for the legacy deliver cohort", () => {
+ expect(
+ sessionInboxWireEncoder.encode(
+ { auth: null, kind: "send", payload: { message: "legacy" }, requestId: "req-0" },
+ { variant: "deliver", version: 0 },
+ ),
+ ).toEqual({
+ auth: null,
+ caller: undefined,
+ deliveryMetadata: undefined,
+ kind: "deliver",
+ payloads: [{ message: "legacy" }],
+ requestId: "req-0",
+ taskDeliveryId: undefined,
+ turnPolicy: undefined,
+ });
+ });
+
+ it("encodes sends for the legacy raw-send cohort", () => {
+ expect(
+ sessionInboxWireEncoder.encode(
+ { kind: "send", payload: { message: "mid" } },
+ { variant: "send", version: 0 },
+ ),
+ ).toEqual({
+ auth: undefined,
+ caller: undefined,
+ delivery: undefined,
+ kind: "send",
+ payload: { message: "mid" },
+ requestId: undefined,
+ taskDeliveryId: undefined,
+ turnPolicy: undefined,
+ });
+ });
+});
diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v0.ts b/packages/eve/src/execution/wire/session-inbox-wire.v0.ts
new file mode 100644
index 000000000..79840dc5f
--- /dev/null
+++ b/packages/eve/src/execution/wire/session-inbox-wire.v0.ts
@@ -0,0 +1,91 @@
+import type { VersionMigration } from "#execution/durable-session-migrations/chain.js";
+import type { SessionInboxWireV1 } from "#execution/wire/session-inbox-wire.v1.js";
+import { isObject } from "#shared/guards.js";
+
+/**
+ * Version 0 is the unversioned era. Its sole shape change is the raw `send`
+ * command persisted by eve 0.30.5–0.31.0; legacy `deliver` already has the
+ * v1 discriminator and needs only the version stamp.
+ *
+ * This module is removable once runs created by that cohort have aged out
+ * under the 30-day default session timeout.
+ */
+function migrateSessionInboxWireV0(
+ prior: unknown,
+): Record<string, unknown> & { readonly version: 1 } {
+ const value = prior as Record<string, unknown>;
+ if (value.kind === "send") return migrateLegacySend(value);
+
+ if (
+ value.kind === "deliver" &&
+ !(Array.isArray(value.payloads) && value.payloads.every(isObject))
+ ) {
+ throw new Error("legacy deliver payload has no object-array payloads field.");
+ }
+
+ return { ...value, version: 1 };
+}
+
+function migrateLegacySend(
+ send: Record<string, unknown>,
+): Record<string, unknown> & { readonly version: 1 } {
+ if (!isObject(send.payload)) {
+ throw new Error("legacy send command has no object payload field.");
+ }
+ if (send.delivery !== undefined && !isObject(send.delivery)) {
+ throw new Error("legacy send command has a non-object delivery field.");
+ }
+
+ return {
+ auth: send.auth,
+ caller: send.caller,
+ deliveryMetadata:
+ send.delivery === undefined ? undefined : [{ ...send.delivery, payloadIndex: 0 }],
+ kind: "deliver",
+ payload: send.payload,
+ payloads: [send.payload],
+ requestId: send.requestId,
+ taskDeliveryId: send.taskDeliveryId,
+ turnPolicy: send.turnPolicy,
+ version: 1,
+ };
+}
+
+export const sessionInboxWireV0Migration: VersionMigration = {
+ from: 0,
+ migrate: migrateSessionInboxWireV0,
+ to: 1,
+};
+
+/** Encodes the two incompatible shapes from the unversioned wire era. */
+export function encodeSessionCommandV0(
+ wire: SessionInboxWireV1,
+ variant: "deliver" | "send",
+): Omit<SessionInboxWireV1, "version"> | Record<string, unknown> {
+ if (wire.kind !== "deliver") {
+ const { version: _version, ...legacy } = wire;
+ return legacy;
+ }
+
+ if (variant === "deliver") {
+ const { payload: _payload, version: _version, ...legacy } = wire;
+ return legacy;
+ }
+
+ const deliveryMetadata = wire.deliveryMetadata?.find((metadata) => metadata.payloadIndex === 0);
+ let delivery: Omit<NonNullable<typeof deliveryMetadata>, "payloadIndex"> | undefined;
+ if (deliveryMetadata !== undefined) {
+ const { payloadIndex: _payloadIndex, ...value } = deliveryMetadata;
+ delivery = value;
+ }
+ return {
+ auth: wire.auth,
+ caller: wire.caller,
+ delivery,
+ kind: "send",
+ payload: wire.payload,
+ requestId: wire.requestId,
+ taskDeliveryId: wire.taskDeliveryId,
+ turnPolicy: wire.turnPolicy,
+ };
+}
diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v1.test.ts b/packages/eve/src/execution/wire/session-inbox-wire.v1.test.ts
new file mode 100644
index 000000000..c2349d610
--- /dev/null
+++ b/packages/eve/src/execution/wire/session-inbox-wire.v1.test.ts
@@ -0,0 +1,210 @@
+import { describe, expect, it } from "vitest";
+import { z } from "#compiled/zod/index.js";
+
+import { sessionInboxWire as sessionInboxWireEncoder } from "#execution/wire/session-inbox-encoder.js";
+import { SESSION_INBOX_WIRE_VERSIONS } from "#execution/wire/session-inbox-contract.js";
+import {
+ sessionInboxWire as sessionInboxWireDecoder,
+ SessionInboxWireError,
+} from "#execution/wire/session-inbox-wire.js";
+import { sessionInboxWireV1Schema } from "#execution/wire/session-inbox-wire.v1.js";
+
+const FROZEN_FIXTURES = {
+ clear: '{"kind":"clear","version":1}',
+ deliver:
+ '{"auth":null,"kind":"deliver","payload":{"message":"wire"},"payloads":[{"message":"wire"}],"requestId":"req-wire","version":1}',
+} as const;
+
+describe("session inbox wire v1", () => {
+ it("accepts only its own version", () => {
+ expect(sessionInboxWireV1Schema.safeParse({ kind: "clear", version: 1 }).success).toBe(true);
+ expect(sessionInboxWireV1Schema.safeParse({ kind: "clear", version: 2 }).success).toBe(false);
+ });
+
+ it.each(SESSION_INBOX_WIRE_VERSIONS)(
+ "encodes and decodes declared wire version %i",
+ (version) => {
+ const wire = sessionInboxWireEncoder.encode(
+ { kind: "send", payload: { message: "registry" } },
+ { version },
+ );
+
+ expect(wire).toMatchObject({ version });
+ expect(sessionInboxWireDecoder.decode(wire)).toEqual({
+ auth: undefined,
+ caller: undefined,
+ kind: "deliver",
+ payloads: [{ message: "registry" }],
+ requestId: undefined,
+ });
+ },
+ );
+
+ it("pins the complete schema byte for byte", () => {
+ expect(
+ stableStringify(
+ z.toJSONSchema(sessionInboxWireV1Schema, { io: "input", unrepresentable: "any" }),
+ ),
+ ).toMatchSnapshot();
+ });
+
+ it("encodes a send as the frozen v1 delivery and round-trips", () => {
+ const wire = sessionInboxWireEncoder.encode(
+ {
+ auth: null,
+ kind: "send",
+ payload: { message: "wire" },
+ requestId: "req-wire",
+ },
+ { version: 1 },
+ );
+ expect(stableStringify(wire)).toBe(FROZEN_FIXTURES.deliver);
+ expect(sessionInboxWireDecoder.decode(JSON.parse(JSON.stringify(wire)))).toEqual({
+ auth: null,
+ caller: undefined,
+ kind: "deliver",
+ payloads: [{ message: "wire" }],
+ requestId: "req-wire",
+ });
+ });
+
+ it("preserves the current delivery, task, caller, and turn-control fields", () => {
+ const caller = {
+ callId: "call-1",
+ replyTo: {
+ kind: "callback" as const,
+ token: "callback-token",
+ url: "https://example.com/callback",
+ },
+ subagentName: "researcher",
+ taskId: "task-1",
+ };
+ const task = {
+ views: [
+ {
+ metadata: {
+ agentId: "agent-1",
+ kind: "subagent" as const,
+ mode: "local" as const,
+ name: "researcher",
+ },
+ status: "working" as const,
+ taskId: "task-1",
+ },
+ ],
+ };
+ const wire = sessionInboxWireEncoder.encode(
+ {
+ caller,
+ delivery: {
+ channelKind: "http",
+ channelName: "web",
+ deliveryId: "delivery-1",
+ requestTraceContext: { spanId: "span-1", traceFlags: 1, traceId: "trace-1" },
+ },
+ kind: "send",
+ payload: { task },
+ taskDeliveryId: "task-delivery-1",
+ turnPolicy: "queue",
+ },
+ { version: 1 },
+ );
+
+ expect(sessionInboxWireDecoder.decode(JSON.parse(JSON.stringify(wire)))).toEqual({
+ auth: undefined,
+ caller,
+ deliveryMetadata: [
+ {
+ channelKind: "http",
+ channelName: "web",
+ deliveryId: "delivery-1",
+ payloadIndex: 0,
+ requestTraceContext: { spanId: "span-1", traceFlags: 1, traceId: "trace-1" },
+ },
+ ],
+ kind: "deliver",
+ payloads: [{ task }],
+ requestId: undefined,
+ taskDeliveryId: "task-delivery-1",
+ turnPolicy: "queue",
+ });
+ expect(
+ sessionInboxWireDecoder.decode(
+ sessionInboxWireEncoder.encode({ kind: "cancel", taskId: "task-1" }, { version: 1 }),
+ ),
+ ).toEqual({ kind: "cancel", taskId: "task-1", turnId: undefined });
+ });
+
+ it("encodes controls with v1 and round-trips", () => {
+ const clear = sessionInboxWireEncoder.encode({ kind: "clear" }, { version: 1 });
+ expect(stableStringify(clear)).toBe(FROZEN_FIXTURES.clear);
+ expect(sessionInboxWireDecoder.decode(clear)).toEqual({ kind: "clear" });
+ expect(
+ sessionInboxWireDecoder.decode(
+ sessionInboxWireEncoder.encode({ kind: "session-timeout" }, { version: 1 }),
+ ),
+ ).toEqual({ kind: "session-timeout" });
+ expect(
+ sessionInboxWireDecoder.decode(
+ sessionInboxWireEncoder.encode({ kind: "cancel", turnId: "turn_9" }, { version: 1 }),
+ ),
+ ).toEqual({ kind: "cancel", turnId: "turn_9" });
+ });
+
+ it("keeps the transitional mirror equal to the delivery", () => {
+ const wire = sessionInboxWireEncoder.encode(
+ { kind: "send", payload: { message: "m" } },
+ { version: 1 },
+ );
+ expect(wire.kind).toBe("deliver");
+ if (wire.kind === "deliver") expect(wire.payloads[0]).toEqual(wire.payload);
+ });
+
+ it("does not persist undeclared command fields and preserves adapter extensions", () => {
+ const payload = { interaction: { slack: true }, message: "hi" };
+ const encoded = sessionInboxWireEncoder.encode(
+ { kind: "send", payload, stowaway: "must not persist" } as never,
+ { version: 1 },
+ );
+ expect(encoded).not.toHaveProperty("stowaway");
+ expect(encoded.kind === "deliver" && encoded.payloads[0]).toEqual(payload);
+ });
+
+ it.each([
+ ["input response", { inputResponses: [{ requestId: 7 }] }],
+ ["context", { context: ["valid", 7] }],
+ ["message part", { message: [{ text: 7, type: "text" }] }],
+ ["output schema", { outputSchema: { invalid: () => undefined } }],
+ ])("rejects a malformed eve-owned %s before persistence", (_name, payload) => {
+ expect(() =>
+ sessionInboxWireEncoder.encode({ kind: "send", payload } as never, { version: 1 }),
+ ).toThrowError(SessionInboxWireError);
+ });
+
+ it.each([
+ ["a future wire version", { kind: "deliver", payloads: [], version: 2 }],
+ ["a non-numeric version", { kind: "deliver", payloads: [], version: "1" }],
+ ["an unrecognized kind", { kind: "mystery", version: 1 }],
+ ])("rejects %s instead of reinterpreting it", (_name, payload) => {
+ expect(() => sessionInboxWireDecoder.decode(payload)).toThrowError(SessionInboxWireError);
+ });
+
+ it("reports an unknown newer version as written by a newer deployment", () => {
+ expect(() =>
+ sessionInboxWireDecoder.decode({ kind: "deliver", payloads: [], version: 99 }),
+ ).toThrowError(/newer/);
+ });
+});
+
+function stableStringify(value: unknown): string {
+ return JSON.stringify(sortKeys(value));
+}
+
+function sortKeys(value: unknown): unknown {
+ if (Array.isArray(value)) return value.map(sortKeys);
+ if (typeof value !== "object" || value === null) return value;
+ const entries = Object.entries(value as Record<string, unknown>)
+ .filter(([, entry]) => entry !== undefined)
+ .sort(([left], [right]) => left.localeCompare(right));
+ return Object.fromEntries(entries.map(([key, entry]) => [key, sortKeys(entry)]));
+}
diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v1.ts b/packages/eve/src/execution/wire/session-inbox-wire.v1.ts
new file mode 100644
index 000000000..e40f62ec4
--- /dev/null
+++ b/packages/eve/src/execution/wire/session-inbox-wire.v1.ts
@@ -0,0 +1,272 @@
+import type { DataContent } from "ai";
+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 { inputRequestSchema, inputResponseSchema } from "#runtime/input/types.js";
+import { formatValidationError } from "#runtime/validation.js";
+import { jsonObjectSchema, jsonValueSchema } from "#shared/json-schemas.js";
+import { tokenUsageSchema } from "#shared/token-usage.js";
+import type { TaskView } from "#tasks/types.js";
+
+const providerOptionsSchema = z.record(z.string(), jsonObjectSchema);
+const textPartSchema = z
+ .object({
+ providerOptions: providerOptionsSchema.optional(),
+ text: z.string(),
+ type: z.literal("text"),
+ })
+ .strict();
+const binaryDataSchema = z.custom<DataContent | URL>(
+ (value) =>
+ typeof value === "string" ||
+ value instanceof Uint8Array ||
+ value instanceof ArrayBuffer ||
+ value instanceof URL,
+ "Expected a string, URL, Uint8Array, or ArrayBuffer.",
+);
+const imagePartSchema = z
+ .object({
+ image: binaryDataSchema,
+ mediaType: z.string().optional(),
+ providerOptions: providerOptionsSchema.optional(),
+ type: z.literal("image"),
+ })
+ .strict();
+const filePartSchema = z
+ .object({
+ data: binaryDataSchema,
+ filename: z.string().optional(),
+ mediaType: z.string(),
+ providerOptions: providerOptionsSchema.optional(),
+ type: z.literal("file"),
+ })
+ .strict();
+const userContentSchema = z.union([
+ z.string(),
+ z.array(z.discriminatedUnion("type", [textPartSchema, imagePartSchema, filePartSchema])),
+]);
+
+const eventCoordinateSchema = z.number().int().nonnegative();
+const opaqueObjectSchema = z.custom<Record<string, unknown>>(
+ (value) => typeof value === "object" && value !== null && !Array.isArray(value),
+ "Expected an object.",
+);
+const subagentInputRequestHookPayloadSchema = z
+ .object({
+ callId: z.string(),
+ childContinuationToken: z.string(),
+ childSessionId: z.string(),
+ event: z
+ .object({
+ requests: z.array(inputRequestSchema),
+ sequence: eventCoordinateSchema,
+ stepIndex: eventCoordinateSchema,
+ turnId: z.string(),
+ })
+ .strict(),
+ kind: z.literal("subagent-input-request"),
+ subagentName: z.string(),
+ })
+ .strict();
+const subagentAuthorizationEventHookPayloadSchema = z
+ .object({
+ callId: z.string(),
+ childSessionId: z.string(),
+ event: opaqueObjectSchema,
+ kind: z.literal("subagent-authorization-event"),
+ subagentName: z.string(),
+ })
+ .strict();
+const taskMetadataSchema = z
+ .object({
+ agentId: z.string(),
+ kind: z.literal("subagent"),
+ mode: z.enum(["local", "remote"]),
+ name: z.string(),
+ })
+ .strict();
+const taskExecutorSchema = z
+ .object({
+ childSessionId: z.string().optional(),
+ childTurnId: z.string().optional(),
+ lifecycle: z.enum(["parked", "terminal"]).optional(),
+ })
+ .strict();
+const taskViewBase = {
+ executor: taskExecutorSchema.optional(),
+ metadata: taskMetadataSchema,
+ taskId: z.string(),
+ usage: tokenUsageSchema.optional(),
+};
+const taskViewSchema: z.ZodType<TaskView> = z.discriminatedUnion("status", [
+ z.object({ ...taskViewBase, status: z.literal("working") }).strict(),
+ z
+ .object({
+ ...taskViewBase,
+ inputRequests: z.array(jsonValueSchema),
+ status: z.literal("input_required"),
+ })
+ .strict(),
+ z
+ .object({
+ ...taskViewBase,
+ lastOutput: z.object({ data: jsonValueSchema, type: z.literal("result") }).strict(),
+ status: z.literal("completed"),
+ })
+ .strict(),
+ z
+ .object({
+ ...taskViewBase,
+ lastOutput: z.object({ data: jsonValueSchema, type: z.literal("error") }).strict(),
+ status: z.literal("failed"),
+ })
+ .strict(),
+ z.object({ ...taskViewBase, status: z.literal("cancelled") }).strict(),
+]);
+const taskPayloadSchema = z
+ .object({
+ authorizationEvents: z
+ .array(
+ z
+ .object({
+ hookPayload: subagentAuthorizationEventHookPayloadSchema,
+ taskId: z.string(),
+ })
+ .strict(),
+ )
+ .optional(),
+ inputRequests: z
+ .array(
+ z
+ .object({ hookPayload: subagentInputRequestHookPayloadSchema, taskId: z.string() })
+ .strict(),
+ )
+ .optional(),
+ views: z.array(taskViewSchema).optional(),
+ })
+ .strict();
+
+/**
+ * The complete eve-owned payload contract. Adapter fields are the explicit
+ * extension point and pass through unchanged; changing any declared field is
+ * a session-inbox wire-version change.
+ */
+const deliverPayloadSchema = z
+ .object({
+ context: z.array(z.string()).optional(),
+ inputResponses: z.array(inputResponseSchema).optional(),
+ message: userContentSchema.optional(),
+ outputSchema: jsonObjectSchema.optional(),
+ task: taskPayloadSchema.optional(),
+ })
+ .loose();
+
+const authSchema = z
+ .object({
+ attributes: z.record(z.string(), z.union([z.string(), z.array(z.string())])),
+ authenticator: z.string(),
+ issuer: z.string().optional(),
+ principalId: z.string(),
+ principalType: z.string(),
+ subject: z.string().optional(),
+ })
+ .strict();
+const callerSchema = z
+ .object({
+ callId: z.string(),
+ replyTo: z.discriminatedUnion("kind", [
+ z.object({ kind: z.literal("hook"), token: z.string() }).strict(),
+ z.object({ kind: z.literal("callback"), token: z.string(), url: z.string() }).strict(),
+ ]),
+ subagentName: z.string(),
+ taskId: z.string().optional(),
+ })
+ .strict();
+const traceContextSchema = z
+ .object({ spanId: z.string(), traceFlags: z.number(), traceId: z.string() })
+ .strict();
+const deliveryMetadataSchema = z
+ .object({
+ channelKind: z.string(),
+ channelName: z.string(),
+ deliveryId: z.string(),
+ payloadIndex: z.number().int().nonnegative(),
+ requestId: z.string().optional(),
+ requestTraceContext: traceContextSchema.optional(),
+ })
+ .strict();
+const VERSION = 1;
+const version = z.literal(VERSION);
+
+/** The complete schema for persisted session-inbox wire version 1. */
+export const sessionInboxWireV1Schema = z.discriminatedUnion("kind", [
+ z
+ .object({
+ auth: authSchema.nullable().optional(),
+ caller: callerSchema.optional(),
+ deliveryMetadata: z.array(deliveryMetadataSchema).optional(),
+ kind: z.literal("deliver"),
+ payload: deliverPayloadSchema.optional(),
+ payloads: z.array(deliverPayloadSchema),
+ requestId: z.string().optional(),
+ taskDeliveryId: z.string().optional(),
+ turnPolicy: z.enum(["queue", "steer"]).optional(),
+ version,
+ })
+ .strict(),
+ z.object({ kind: z.literal("session-timeout"), version }).strict(),
+ z.object({ kind: z.literal("clear"), version }).strict(),
+ z.object({ kind: z.literal("compact"), version }).strict(),
+ z.object({ kind: z.literal("reset"), reason: z.string().optional(), version }).strict(),
+ z
+ .object({
+ kind: z.literal("cancel"),
+ taskId: z.string().optional(),
+ turnId: z.string().optional(),
+ version,
+ })
+ .strict(),
+]);
+
+export type SessionInboxWireV1 = z.infer<typeof sessionInboxWireV1Schema>;
+
+/** Builds and validates one complete version-1 wire value. */
+export function encodeSessionCommandV1(
+ command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload,
+): SessionInboxWireV1 {
+ const wire =
+ command.kind === "send"
+ ? {
+ auth: command.auth,
+ caller: command.caller,
+ deliveryMetadata:
+ command.delivery === undefined ? undefined : [{ ...command.delivery, payloadIndex: 0 }],
+ kind: "deliver" as const,
+ payload: command.payload,
+ payloads: [command.payload],
+ requestId: command.requestId,
+ taskDeliveryId: command.taskDeliveryId,
+ turnPolicy: command.turnPolicy,
+ version: VERSION,
+ }
+ : command.kind === "deliver"
+ ? {
+ ...command,
+ payload: coalesceDeliverPayloads(command.payloads),
+ version: VERSION,
+ }
+ : { ...command, version: VERSION };
+ const parsed = sessionInboxWireV1Schema.safeParse(wire);
+ if (!parsed.success) {
+ throw new SessionInboxWireError(
+ `Produced a session inbox payload that does not match wire version ${VERSION}: ${formatValidationError(parsed.error)}`,
+ );
+ }
+ return parsed.data;
+}
diff --git a/packages/eve/src/execution/workflow-entry.test.ts b/packages/eve/src/execution/workflow-entry.test.ts
index 8ad1878fe..3a3845402 100644
--- a/packages/eve/src/execution/workflow-entry.test.ts
+++ b/packages/eve/src/execution/workflow-entry.test.ts
@@ -922,7 +922,6 @@ describe("workflowEntry", () => {
auth: undefined,
caller: undefined,
kind: "deliver",
- payload: { inputResponses: [{ optionId: "approve", requestId: "req-1" }] },
payloads: [{ inputResponses: [{ optionId: "approve", requestId: "req-1" }] }],
requestId: undefined,
},
diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.ts
index 9411fbda4..f2f857b6c 100644
--- a/packages/eve/src/execution/workflow-runtime.test.ts
+++ b/packages/eve/src/execution/workflow-runtime.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { SpanKind } from "#compiled/@opentelemetry/api/index.js";
@@ -57,6 +57,10 @@ vi.mock("#runtime/sessions/compiled-agent-cache.js", () => ({
getCompiledRuntimeAgentBundle: vi.fn(),
}));
+beforeEach(() => {
+ getHookByTokenMock.mockImplementation(async (token: string) => currentSessionHook(token));
+});
+
afterEach(() => {
getHookByTokenMock.mockReset();
getRunMock.mockReset();
@@ -121,15 +125,16 @@ describe("createWorkflowRuntime command dispatch", () => {
}),
).resolves.toEqual({ sessionId: "driver-run", status: "accepted" });
- expect(resumeHookMock).toHaveBeenCalledWith("test:token", {
+ expect(resumeHookMock).toHaveBeenCalledWith(currentSessionHook("test:token"), {
auth: null,
caller,
kind: "deliver",
payload: { message: "hello" },
payloads: [{ message: "hello" }],
requestId: "req_deliver",
+ version: 1,
});
- expect(getHookByTokenMock).not.toHaveBeenCalled();
+ expect(getHookByTokenMock).toHaveBeenCalledWith("test:token");
});
it("dispatches commands through the stable session inbox", async () => {
@@ -142,10 +147,11 @@ describe("createWorkflowRuntime command dispatch", () => {
}),
).resolves.toEqual({ sessionId: "session-1", status: "accepted" });
- expect(resumeHookMock).toHaveBeenCalledWith(sessionCommandHookToken("session-1"), {
- kind: "clear",
- });
- expect(getHookByTokenMock).not.toHaveBeenCalled();
+ expect(resumeHookMock).toHaveBeenCalledWith(
+ currentSessionHook(sessionCommandHookToken("session-1")),
+ { kind: "clear", version: 1 },
+ );
+ expect(getHookByTokenMock).toHaveBeenCalledWith(sessionCommandHookToken("session-1"));
});
it("preserves the delivery payload through the stable session inbox", async () => {
@@ -158,14 +164,18 @@ describe("createWorkflowRuntime command dispatch", () => {
}),
).resolves.toEqual({ sessionId: "session-1", status: "accepted" });
- expect(resumeHookMock).toHaveBeenCalledWith(sessionCommandHookToken("session-1"), {
- auth: undefined,
- caller: undefined,
- kind: "deliver",
- payload: { message: "hello" },
- payloads: [{ message: "hello" }],
- requestId: undefined,
- });
+ expect(resumeHookMock).toHaveBeenCalledWith(
+ currentSessionHook(sessionCommandHookToken("session-1")),
+ {
+ auth: undefined,
+ caller: undefined,
+ kind: "deliver",
+ payload: { message: "hello" },
+ payloads: [{ message: "hello" }],
+ requestId: undefined,
+ version: 1,
+ },
+ );
});
it.each([
@@ -175,7 +185,7 @@ describe("createWorkflowRuntime command dispatch", () => {
{ command: { kind: "reset" as const }, status: "no_active_session" },
])("maps a missing $command.kind target to $status", async ({ command, status }) => {
const { HookNotFoundError } = await import("#compiled/@workflow/errors/index.js");
- resumeHookMock.mockRejectedValue(new HookNotFoundError(NOT_FOUND_TOKEN));
+ getHookByTokenMock.mockRejectedValue(new HookNotFoundError(NOT_FOUND_TOKEN));
await expect(
buildRuntime().dispatchContinuation({
@@ -208,10 +218,10 @@ describe("createWorkflowRuntime command dispatch", () => {
sessionId: "session-1",
}),
).resolves.toEqual({ sessionId: "session-1", status: "accepted" });
- expect(resumeHookMock).toHaveBeenCalledWith(sessionCommandHookToken("session-1"), {
- kind: "cancel",
- turnId: "turn-2",
- });
+ expect(resumeHookMock).toHaveBeenCalledWith(
+ currentSessionHook(sessionCommandHookToken("session-1")),
+ { kind: "cancel", turnId: "turn-2", version: 1 },
+ );
});
it("maps missing and terminal targets to 'no_active_turn'", async () => {
@@ -250,9 +260,9 @@ describe("createWorkflowRuntime command dispatch", () => {
it("waits for reset to release the stable command inbox", async () => {
const { HookNotFoundError } = await import("#compiled/@workflow/errors/index.js");
resumeHookMock.mockResolvedValue({ runId: "session-1" });
- getHookByTokenMock.mockRejectedValue(
- new HookNotFoundError(sessionCommandHookToken("session-1")),
- );
+ getHookByTokenMock
+ .mockResolvedValueOnce(currentSessionHook("eve:token"))
+ .mockRejectedValue(new HookNotFoundError(sessionCommandHookToken("session-1")));
await expect(
buildRuntime().dispatchContinuation({
@@ -260,14 +270,23 @@ describe("createWorkflowRuntime command dispatch", () => {
continuationToken: "eve:token",
}),
).resolves.toEqual({ previousSessionId: "session-1", status: "reset" });
- expect(resumeHookMock).toHaveBeenCalledWith("eve:token", {
+ expect(resumeHookMock).toHaveBeenCalledWith(currentSessionHook("eve:token"), {
kind: "reset",
reason: "User requested /new",
+ version: 1,
});
expect(getHookByTokenMock).toHaveBeenCalledWith(sessionCommandHookToken("session-1"));
});
});
+function currentSessionHook(token: string) {
+ return {
+ metadata: { sessionInboxWireVersion: 1 },
+ runId: "target-session",
+ token,
+ };
+}
+
describe("createWorkflowRuntime#resolveContinuation", () => {
function buildRuntime() {
return createWorkflowRuntime({ compiledArtifactsSource: {} as RuntimeCompiledArtifactsSource });
diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.ts
index 1fd26ba32..adb74ef2e 100644
--- a/packages/eve/src/execution/workflow-runtime.ts
+++ b/packages/eve/src/execution/workflow-runtime.ts
@@ -8,7 +8,6 @@ import {
import type {
CancelTurnInput,
CancelTurnResult,
- DeliverHookPayload,
DispatchContinuationInput,
DispatchSessionInput,
GetEventStreamOptions,
@@ -31,7 +30,6 @@ import { SpanKind, trace } from "#compiled/@opentelemetry/api/index.js";
import {
getHookByToken,
getRun,
- resumeHook,
start,
type Run,
type StartOptionsWithoutDeploymentId,
@@ -51,7 +49,7 @@ import type { WorkflowEntryInput } from "#execution/workflow-entry.js";
import { walkCauseChain } from "#shared/errors.js";
import { buildInvocationAttributes } from "#internal/invocation/metadata.js";
import { sessionCommandHookToken } from "#execution/session-command-token.js";
-import { sendCommandToDelivery } from "#execution/session-command-wire.js";
+import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";
import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";
const WORKFLOW_ENTRY_NAME = "workflowEntry";
@@ -271,7 +269,7 @@ async function dispatchWorkflowCommand<TCommand extends SessionCommand>(
): Promise<SessionCommandResult<TCommand>> {
let hook: WorkflowHookRecord;
try {
- hook = normalizeWorkflowHook(await resumeHook(token, sessionHookPayload(command)));
+ hook = normalizeWorkflowHook(await resumeSessionInbox(token, command));
} catch (error) {
if (isInactiveCommandTarget(error)) {
return inactiveCommandResult(command);
@@ -290,10 +288,6 @@ async function dispatchWorkflowCommand<TCommand extends SessionCommand>(
return activeCommandResult(command, hook.runId);
}
-function sessionHookPayload(command: SessionCommand): SessionCommand | DeliverHookPayload {
- return command.kind === "send" ? sendCommandToDelivery(command) : command;
-}
-
function activeCommandResult<TCommand extends SessionCommand>(
command: TCommand,
sessionId: string,
diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.ts
index ff2ddf4cf..f41de0ed6 100644
--- a/packages/eve/src/execution/workflow-steps.test.ts
+++ b/packages/eve/src/execution/workflow-steps.test.ts
@@ -142,7 +142,7 @@ vi.mock("../runtime/sessions/compiled-agent-cache.js", () => ({
}));
vi.mock("#compiled/@workflow/core/runtime.js", () => ({
- getHookByToken: vi.fn(async () => ({ runId: "child-run" })),
+ getHookByToken: vi.fn(async (token: string) => currentSessionHook(token)),
getRun: (...args: unknown[]) => getRunMock(...args),
resumeHook: (...args: unknown[]) => resumeHookMock(...args),
start: (...args: unknown[]) => startMock(...args),
@@ -263,7 +263,7 @@ describe("routeProxiedDeliverStep", () => {
});
expect(result).toMatchObject({ kind: "continue", remainder: undefined });
- expect(resumeHookMock).toHaveBeenCalledWith("child-token", {
+ expect(resumeHookMock).toHaveBeenCalledWith(currentSessionHook("child-token"), {
auth,
caller: undefined,
kind: "deliver",
@@ -272,6 +272,7 @@ describe("routeProxiedDeliverStep", () => {
},
payloads: [{ inputResponses: [{ optionId: "approve", requestId: "request-1" }] }],
requestId: undefined,
+ version: 1,
});
});
@@ -332,7 +333,7 @@ describe("routeProxiedDeliverStep", () => {
});
expect(resumeHookMock).toHaveBeenCalledWith(
- "child-token-a",
+ currentSessionHook("child-token-a"),
expect.objectContaining({
...delivery,
deliveryMetadata: [expect.objectContaining({ deliveryId: "delivery-0", payloadIndex: 0 })],
@@ -340,7 +341,7 @@ describe("routeProxiedDeliverStep", () => {
}),
);
expect(resumeHookMock).toHaveBeenCalledWith(
- "child-token-b",
+ currentSessionHook("child-token-b"),
expect.objectContaining({
auth,
caller,
@@ -486,6 +487,14 @@ describe("routeProxiedDeliverStep", () => {
});
});
+function currentSessionHook(token: string) {
+ return {
+ metadata: { sessionInboxWireVersion: 1 },
+ runId: "child-run",
+ token,
+ };
+}
+
describe("recordTaskInputRequestStep", () => {
const hookPayload: SubagentInputRequestHookPayload = {
callId: "call-task",
diff --git a/packages/eve/src/internal/testing/mid-cohort-session-delivery-workflow.ts b/packages/eve/src/internal/testing/mid-cohort-session-delivery-workflow.ts
index eddcf6526..b43335a05 100644
--- a/packages/eve/src/internal/testing/mid-cohort-session-delivery-workflow.ts
+++ b/packages/eve/src/internal/testing/mid-cohort-session-delivery-workflow.ts
@@ -1,22 +1,24 @@
-import { createHook } from "#compiled/@workflow/core/index.js";
+import { createHook, getWorkflowMetadata } from "#compiled/@workflow/core/index.js";
import type { DeliverPayload } from "#channel/types.js";
+import { sessionCommandHookToken } from "#execution/session-command-token.js";
/**
- * Models the parked-session consumer shipped in eve 0.30.3–0.30.8.
+ * Models the parked-session consumer shipped in eve 0.30.5–0.30.8.
*
* Frozen copy of that cohort's inbox decode (`waitForNextSessionAction` +
* `commandToDelivery` at 0.30.7): every payload that is not a control kind is
* cast to a `send` command and re-wrapped by reading its `payload` field. A
* producer envelope without that field therefore delivers `undefined` and the
- * message is lost — which is exactly what the current wire encoder's
- * single-payload mirror exists to prevent.
+ * message is lost. This cohort also owns the stable session inbox, which is
+ * the markerless capability the current producer uses to select raw `send`.
*/
export async function midCohortSessionDeliveryWorkflow(input: {
readonly token: string;
}): Promise<string> {
"use workflow";
+ createHook({ token: sessionCommandHookToken(getWorkflowMetadata().workflowRunId) });
const inbox = createHook<{ readonly kind: string }>({ token: input.token });
for await (const value of inbox) {
if (
diff --git a/packages/eve/src/runtime/task-input-response-route.test.ts b/packages/eve/src/runtime/task-input-response-route.test.ts
index 90563d0e7..632b33773 100644
--- a/packages/eve/src/runtime/task-input-response-route.test.ts
+++ b/packages/eve/src/runtime/task-input-response-route.test.ts
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { sendCommandToDelivery } from "#execution/session-command-wire.js";
+import { sessionInboxWire } from "#execution/wire/session-inbox-encoder.js";
import { EVE_TASK_INPUT_ROUTE_PATTERN } from "#protocol/routes.js";
import type { RouteContext } from "#public/definitions/channel.js";
import {
@@ -9,16 +9,27 @@ import {
} from "#runtime/task-input-response-route.js";
const resumeHookMock = vi.fn();
+const getHookByTokenMock = vi.fn();
const DIGEST = "0123456789abcdef0123456789abcdef";
const CAPABILITY_TOKEN = `eve:task-input:${DIGEST}`;
const TARGET_TOKEN = `eve:eve:op:${DIGEST}`;
+const TARGET_HOOK = {
+ metadata: { sessionInboxWireVersion: 1 },
+ runId: "child-session",
+ token: TARGET_TOKEN,
+};
vi.mock("#compiled/@workflow/core/runtime.js", () => ({
- resumeHook: (token: string, payload: unknown) => resumeHookMock(token, payload),
+ getHookByToken: (...args: unknown[]) => getHookByTokenMock(...args),
+ resumeHook: (...args: unknown[]) => resumeHookMock(...args),
}));
describe("task input response capability", () => {
- beforeEach(() => resumeHookMock.mockReset());
+ beforeEach(() => {
+ getHookByTokenMock.mockReset();
+ getHookByTokenMock.mockResolvedValue(TARGET_HOOK);
+ resumeHookMock.mockReset();
+ });
it("registers one capability-scoped POST route", () => {
expect(getTaskInputResponseChannelDefinitions()).toEqual([
@@ -34,12 +45,16 @@ describe("task input response capability", () => {
);
expect(response.status).toBe(202);
+ expect(getHookByTokenMock).toHaveBeenCalledWith(TARGET_TOKEN);
expect(resumeHookMock).toHaveBeenCalledWith(
- TARGET_TOKEN,
- sendCommandToDelivery({
- kind: "send",
- payload: { inputResponses: [{ optionId: "approve", requestId: "req-1" }] },
- }),
+ TARGET_HOOK,
+ sessionInboxWire.encode(
+ {
+ kind: "send",
+ payload: { inputResponses: [{ optionId: "approve", requestId: "req-1" }] },
+ },
+ { version: 1 },
+ ),
);
});
diff --git a/packages/eve/src/runtime/task-input-response-route.ts b/packages/eve/src/runtime/task-input-response-route.ts
index a180f4bd8..c150cd039 100644
--- a/packages/eve/src/runtime/task-input-response-route.ts
+++ b/packages/eve/src/runtime/task-input-response-route.ts
@@ -1,6 +1,5 @@
-import { sendCommandToDelivery } from "#execution/session-command-wire.js";
import { readTaskInputTargetToken } from "#execution/task-input-capability.js";
-import { resumeHook } from "#internal/workflow/runtime.js";
+import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";
import { EVE_TASK_INPUT_ROUTE_PATTERN } from "#protocol/routes.js";
import type { ChannelMethod, RouteContext } from "#public/definitions/channel.js";
import type { InputResponse } from "#runtime/input/types.js";
@@ -53,9 +52,8 @@ export async function handleTaskInputResponseRequest(
}
// Child inboxes outlive deployments; cross the hook in the durable
// delivery envelope like every other session-inbox producer.
- const command = sendCommandToDelivery({ kind: "send", payload: { inputResponses } });
try {
- await resumeHook(targetToken, command);
+ await resumeSessionInbox(targetToken, { kind: "send", payload: { inputResponses } });
} catch {
return Response.json(
{ error: "Task input target is not pending.", ok: false },
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7b23ca279..eac5dcfa0 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -621,10 +621,16 @@ importers:
eve:
specifier: workspace:*
version: link:../../../packages/eve
+ zod:
+ specifier: 'catalog:'
+ version: 4.4.3
devDependencies:
'@types/node':
specifier: 'catalog:'
version: 25.9.1
+ historical-eve-0-30-8:
+ specifier: npm:[email protected]
typescript:
specifier: 'catalog:'
version: 7.0.2
@@ -1295,6 +1301,9 @@ importers:
gray-matter:
specifier: 4.0.3
version: 4.0.3
+ historical-eve-0-30-8:
+ specifier: npm:[email protected]
jose:
specifier: 6.2.3
version: 6.2.3
@@ -9880,6 +9889,26 @@ packages:
resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==}
engines: {node: '>= 0.6'}
+ resolution: {integrity: sha512-ATF9CHJQBNce7+3leWH87w6Cc7TlsNlfpGAENzmkD4d7oBpSI+P7KB3cvtGM75t+9gT+nJ0R+u7u8hF8BJdBiw==}
+ engines: {node: '>=24'}
+ hasBin: true
+ peerDependencies:
+ '@opentelemetry/api': ^1.0.0
+ ai: ^7.0.38
+ braintrust: ^3.0.0
+ just-bash: ^3.0.0
+ microsandbox: ^0.5.0
+ peerDependenciesMeta:
+ '@opentelemetry/api':
+ optional: true
+ braintrust:
+ optional: true
+ just-bash:
+ optional: true
+ microsandbox:
+ optional: true
+
resolution: {integrity: sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==}
engines: {node: '>=6'}
@@ -24934,6 +24963,106 @@ snapshots:
+ dependencies:
+ ai: 7.0.58([email protected])
+ undici: 8.9.0
+ optionalDependencies:
+ '@opentelemetry/api': 1.9.1
+ just-bash: 3.1.0([email protected])
+ microsandbox: 0.5.5
+ transitivePeerDependencies:
+ - '@azure/app-configuration'
+ - '@azure/cosmos'
+ - '@azure/data-tables'
+ - '@azure/identity'
+ - '@azure/keyvault-secrets'
+ - '@azure/storage-blob'
+ - '@capacitor/preferences'
+ - '@deno/kv'
+ - '@electric-sql/pglite'
+ - '@libsql/client'
+ - '@netlify/blobs'
+ - '@netlify/runtime'
+ - '@planetscale/database'
+ - '@upstash/redis'
+ - '@vercel/blob'
+ - '@vercel/functions'
+ - '@vercel/kv'
+ - '@vercel/queue'
+ - aws4fetch
+ - better-sqlite3
+ - chokidar
+ - dotenv
+ - drizzle-orm
+ - giget
+ - idb-keyval
+ - ioredis
+ - jiti
+ - lru-cache
+ - miniflare
+ - mongodb
+ - mysql2
+ - rollup
+ - sqlite3
+ - uploadthing
+ - vite
+ - wrangler
+ - xml2js
+ - zephyr-agent
+
+ dependencies:
+ ai: 7.0.66([email protected])
+ undici: 8.9.0
+ optionalDependencies:
+ '@opentelemetry/api': 1.9.1
+ just-bash: 3.1.0([email protected])
+ microsandbox: 0.5.5
+ transitivePeerDependencies:
+ - '@azure/app-configuration'
+ - '@azure/cosmos'
+ - '@azure/data-tables'
+ - '@azure/identity'
+ - '@azure/keyvault-secrets'
+ - '@azure/storage-blob'
+ - '@capacitor/preferences'
+ - '@deno/kv'
+ - '@electric-sql/pglite'
+ - '@libsql/client'
+ - '@netlify/blobs'
+ - '@netlify/runtime'
+ - '@planetscale/database'
+ - '@upstash/redis'
+ - '@vercel/blob'
+ - '@vercel/functions'
+ - '@vercel/kv'
+ - '@vercel/queue'
+ - aws4fetch
+ - better-sqlite3
+ - chokidar
+ - dotenv
+ - drizzle-orm
+ - giget
+ - idb-keyval
+ - ioredis
+ - jiti
+ - lru-cache
+ - miniflare
+ - mongodb
+ - mysql2
+ - rollup
+ - sqlite3
+ - uploadthing
+ - vite
+ - wrangler
+ - xml2js
+ - zephyr-agent
+
diff --git a/research/session-inbox-wire-schema.md b/research/session-inbox-wire-schema.md
new file mode 100644
index 000000000..49ab9b6ff
--- /dev/null
+++ b/research/session-inbox-wire-schema.md
@@ -0,0 +1,230 @@
+---
+issue: https://github.com/vercel/eve/issues/1765
+status: proposed
+last_updated: "2026-08-18"
+---
+
+# Versioned wire schema for the session inbox
+
+## Purpose
+
+Payloads resumed into session inbox hooks outlive the deployment that wrote
+them, but their shape is currently an emergent property of whatever TypeScript
+type flows into `resumeHook`. A shared type is not a wire contract: both sides
+recompile together while pinned deployments keep executing the old decode.
+That gap produced two silent-loss incidents from one refactor (#1586 →
+#1751): consumers on eve ≤0.30.4 require the legacy `deliver` envelope,
+while consumers on 0.30.5–0.31.0 require the raw `send` command during an
+active turn.
+
+This plan gives the session inbox a declared, versioned wire schema: one
+module owns every shape that crosses the hook, encoding and decoding are the
+only legal boundary operations, and an undecodable payload fails loudly
+instead of being reinterpreted. Other durable hook payloads
+(`turn-control`, subagent proxies, `runtime-action-result`) migrate in
+follow-ups once this pattern is proven.
+
+In this document, **must**, **should**, and **may** are normative.
+
+## Authoring API
+
+No new framework. Version walking reuses `runMigrationChain`
+(`execution/durable-session-migrations/chain.ts`), exactly as the durable
+session snapshot and turn-workflow input already do. The complete current
+wire value is defined by one zod schema in a server/step-only encoder module;
+the workflow-safe decoder imports only its inferred type. The session inbox
+is the first family; turn-control, the subagent proxies, and the auth-hook
+delivery adopt the same split in follow-ups.
+
+```ts
+// Dependency-free contract imported by encoder and decoder.
+export const SESSION_INBOX_WIRE_VERSION = 1;
+export type SessionInboxWireTarget =
+ | { version: 0; variant: "deliver" | "send" }
+ | { version: 1 };
+
+// One append-only module per shipped version:
+// execution/wire/session-inbox-wire.v1.ts (server/step only)
+const deliverPayloadSchema = z.object({
+ context: z.array(z.string()).optional(),
+ inputResponses: z.array(inputResponseSchema).optional(),
+ message: userContentSchema.optional(),
+ outputSchema: jsonObjectSchema.optional(),
+}).loose(); // explicit adapter extension point
+
+export const sessionInboxWireV1Schema = z.discriminatedUnion("kind", [
+ z.object({ kind: z.literal("deliver"), payloads: z.array(deliverPayloadSchema), ... }),
+ ...controls,
+]);
+export type SessionInboxWireV1 = z.infer<typeof sessionInboxWireV1Schema>;
+encodeSessionCommandV1(input) // build → parse complete value once → persist
+
+// execution/wire/session-inbox-wire.v0.ts (dependency-free, temporary)
+export const sessionInboxWireV0Migration: VersionMigration = { from: 0, to: 1, migrate };
+
+// Server/step-safe encoder facade selects the target consumer's version.
+sessionInboxWire.encode(input, target)
+
+// Workflow-safe decoder: execution/wire/session-inbox-wire.ts
+import type { SessionInboxWireV1 } from "./session-inbox-wire.v1.js";
+export class SessionInboxWireError extends Error { ... }
+const sessionInboxMigrations: readonly VersionMigration[] = [{ from: 0, to: 1, migrate }];
+sessionInboxWire.decode(value) // runMigrationChain (initialVersion: 0) → version/kind → trust → normalize
+```
+
+Normative rules:
+
+- **The current version has exactly one declared shape.** Changing it
+ **must** be a new version: bump the constant, add a one-step
+ `VersionMigration`, freeze the new shape. Historic versions live on as
+ executable migrations plus frozen payload fixtures (the turn-workflow
+ precedent), not as retained schemas.
+- **The complete transported value is validated once, at encode.** The
+ schema owns the envelope and every eve-owned `DeliverPayload` field,
+ composing the existing strict `inputResponseSchema` and
+ `jsonObjectSchema`; adapter-specific payload fields are the explicit open
+ extension point. The inferred schema type is the wire type, so runtime
+ validation and TypeScript cannot drift.
+- **Zod stays outside the workflow driver bundle.** Every producer is
+ server-side or a `"use step"` body; in the driver bundle those steps are
+ dependency-free stubs. The decoder imports `SessionInboxWire` with
+ `import type` and the numeric version from a dependency-free contract
+ module, so zod never enters the self-contained/base64-embedded driver.
+- **Version 0 is the unversioned era** (`initialVersion: 0`): every shape
+ the family persisted before payloads carried `version`, following the
+ field name every persisted eve structure already uses.
+- **Decode trusts a known current version because that trust is earned by
+ the single encoder.** `runMigrationChain` rejects unknown newer versions;
+ known v1 values were produced only by the schema-validating encoder. The
+ decoder checks version and kind, then normalizes away wire-only fields.
+ Legacy v0 is the temporary exception: those writers predate the encoder,
+ so its 0→1 migration defensively checks the historic `send`/`deliver`
+ fields until that cohort ages out under the 30-day timeout.
+- **Encode goes through the wire module too.** Every persisted inbox
+ payload — sends and controls alike — is built and validated against the
+ current schema before it persists, so producer drift dies at the producer
+ instead of at a pinned consumer weeks later.
+- Per family, `sessionInboxWire.encode` **must** be the only producer of
+ persisted payloads and `sessionInboxWire.decode` the only consumer-side
+ interpretation.
+
+## Version signals and their semantics
+
+Two complementary signals, each covering the other's blind side:
+
+```text
+producer ──getHookByToken──▶ hook.metadata.sessionInboxWireVersion
+ (what can they decode?)
+producer ──resumeHook──────▶ { version: N, ... } (what did I send?)
+consumer ──decode──────────▶ known version → typed payload
+ unknown version → loud failure, session stays alive
+```
+
+- **Envelope `version` (consumer-facing).** Every versioned payload carries
+ `version`. Decode of an unrecognized `version` **must not** fall through to
+ any legacy interpretation: it raises `SessionInboxWireError`, which the driver
+ surfaces through a recorded reporting step (a durable trace in the run's
+ event log plus a structured error log — the driver body cannot log
+ directly, since logging pulls Node builtins the workflow bundle rejects),
+ then keeps the session parked. A lost delivery with an operator-visible
+ signal is the designed failure; a reinterpreted delivery is the bug this
+ plan removes. A channel-visible error event **may** be added when the
+ pattern generalizes beyond the session inbox.
+- **Hook metadata stamp (producer-facing).** Consumers stamp
+ `metadata: { sessionInboxWireVersion }` at `createHook`. The producer reads
+ the capability marker and passes the resulting target to
+ `sessionInboxWire.encode`.
+- **Markerless historical classification.** Version 0 had two incompatible
+ shapes. A markerless stable session inbox, or a markerless continuation hook
+ whose run owns that stable inbox, receives raw `send`. That shape is required
+ by eve 0.30.5–0.31.0 and remains accepted by later pre-stamp stable-inbox
+ consumers. A markerless continuation without the stable inbox identifies eve
+ ≤0.30.4 and receives legacy `deliver`. This tests a concrete historical
+ capability rather than guessing from deployment or package metadata.
+- **Cost boundary.** Every producer performs one target `getHookByToken`
+ before `resumeHook`. Markerless continuation hooks require one additional
+ lookup for the stable-inbox capability. `resumeHook` receives the inspected
+ hook object, preventing the encoding decision from being applied to a
+ different hook that later reused the same token.
+
+## Compatibility and payoff timeline
+
+The producer now emits the consumer's actual contract: markerless legacy
+continuations receive unversioned `deliver`, markerless stable-inbox consumers
+receive unversioned `send` (required by eve 0.30.5–0.31.0), and stamped
+consumers receive their declared version.
+
+| Phase | Emit | Removable |
+| --------------------------------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------ |
+| Now | v0 `deliver`, v0 `send`, or v1 according to the target hook | — |
+| Pre-stamp cohorts aged out (30-day session timeout) | current version to stamped hooks | markerless classifier and both v0 encoders |
+| Pre-version payloads aged out | current version only | legacy unversioned decode paths, `SessionCommand` inbox fallback, mirror field |
+
+Each removable row already has its condition written next to the code it
+deletes; #1765 tracks the cleanups.
+
+## Enforcement
+
+Each family carries a frozen contract test with three checks, plus one
+mechanical guard in the existing CI lint job (`pnpm guard:invariants`):
+
+- **Frozen shape.** The complete current schema serializes to a byte-frozen
+ JSON Schema snapshot. Editing any envelope or eve-owned payload field
+ cannot pass this check — the only green path is bumping the version,
+ adding a migration, and freezing the new schema artifact. The wire type is
+ inferred from the same schema the encoder executes, so runtime validation
+ and TypeScript cannot drift.
+- **Backwards-compatibility fixtures.** Frozen payload JSON per shipped
+ version **must** keep decoding on the current build, with frozen expected
+ normalizations. This is the "current code still reads every payload ever
+ persisted" invariant. Fixtures pin the pre-serde object; the devalue/zstd
+ framing belongs to `@workflow` and is out of scope.
+- **Round-trip.** `encode` output is byte-frozen, declares `currentVersion`,
+ and decodes under the current schema — producers cannot drift from the
+ schema they claim to emit.
+- **Invariant guard (rule 40).** The explicit session-inbox version registry
+ must be contiguous from v1, its highest entry must equal `currentVersion`,
+ and its entries must exactly match the append-only
+ `execution/wire/session-inbox-wire.vN.ts` modules. Every wire-version module
+ must also have a colocated `*.test.ts`: v0 pins legacy fixtures and migration
+ behavior; v1 pins the complete schema and encoder. A version cannot ship as
+ unregistered or untested protocol history.
+- Enforcement is layered by what each CI job can check. Rule 40 runs in the
+ lint job and compares declared versions with shipped modules and tests.
+ TypeScript requires an encoder for every registered stamped version. The
+ required unit tier then encodes and decodes every registry entry, while each
+ version's frozen contract pins its exact shape and backwards migration.
+- Exact current-version bytes stay in the unit contract, where the encoded
+ object can be asserted without decoding workflow-owned serde. The
+ deterministic registry checks cover future stamped-version changes. The
+ agent-channels cross-version redeploy eval remains the end-to-end backstop
+ for the pre-versioning gap: it runs the current producer against an actual
+ [email protected] consumer.
+
+## Alternatives considered
+
+**Protobuf (or similar IDL codegen).** Rejected for this boundary. The byte
+serialization is owned by `@workflow`'s serde (devalue + zstd) — eve hands it
+JS objects — so protobuf would nest a second binary encoding inside a devalue
+envelope and re-implement the semantics devalue already provides. Proto's
+defining strengths (cross-language interop, compact bytes) do not apply to an
+eve↔eve-only wire, and its default evolution posture — silently tolerating
+unknown fields — is the exact failure mode this plan exists to eliminate.
+Its real benefit, an externalized schema with mechanical evolution rules, is
+what the frozen schema artifact provides without a second binary format or
+codegen toolchain.
+
+**A schema library in the workflow-safe decoder.** Tried and rejected on
+measurement: importing vendored zod there grew `weather-agent` by +1.45 MB
+and `zod/mini` by +1.63 MB because the driver bundle is self-contained,
+contains inline `sourcesContent`, and is itself base64-embedded. The final
+split keeps zod in the server/step-only encoder, where it is already bundled
+and can express the complete transported type, while the decoder imports
+only the inferred type and a dependency-free version constant.
+
+## Non-goals
+
+- Migrating the other `HookPayload` members, turn-control, or the turn inbox
+ (follow-ups adopt the same module pattern).
+- Changing the serde codec, hook APIs, or anything owned by `@workflow`.
+- Any public authoring API: this is framework-internal wire discipline.
diff --git a/scripts/guard-invariants.mjs b/scripts/guard-invariants.mjs
index 13a370dc1..2206464f1 100644
--- a/scripts/guard-invariants.mjs
+++ b/scripts/guard-invariants.mjs
@@ -92,7 +92,6 @@
* authoring roots, every historical epoch must be supported or
* dropped, every retained epoch needs a compiling fixture, and
* every public authoring value must belong to a capability.
- *
* rule 37 — The instrumentation lifecycle contract stays provider-neutral.
* `harness/instrumentation/lifecycle.ts` must not import from
* `ai`: its event payloads are eve's published shape, so deriving
@@ -102,6 +101,13 @@
* `pnpm --filter eve build`. Turbo owns workspace dependency
* ordering; nested builds race on eve's clean-and-publish dist
* directory and let consumers observe a partial package.
+ * rule 40 — Every shipped wire-version module
+ * (`src/execution/wire/*-wire.vN.ts`) must carry a colocated
+ * `*-wire.vN.test.ts`. The session-inbox registry must also be
+ * contiguous, name every module, and identify its highest version
+ * as current. Version modules are append-only protocol history;
+ * the paired test pins that version's schema/encoder or
+ * migration/fixtures so a version cannot exist as untested code.
*
* Baselines for rules with pre-existing violations live in
* `guard-invariants-baseline.json`. Counts and allowlists in that file
@@ -417,6 +423,87 @@ function importSpecifier(node) {
return undefined;
}
+// ---------- Rule 40: wire versions carry colocated contract tests ----------
+
+const WIRE_FAMILY_DIR = "packages/eve/src/execution/wire";
+const SESSION_INBOX_WIRE_CONTRACT = `${WIRE_FAMILY_DIR}/session-inbox-contract.ts`;
+
+async function checkRule40WireContracts() {
+ /** @type {Violation[]} */
+ const violations = [];
+ let entries;
+ try {
+ entries = await readdir(join(REPO_ROOT, WIRE_FAMILY_DIR));
+ } catch {
+ return violations;
+ }
+
+ for (const name of entries) {
+ const match = name.match(/^([a-z0-9-]+)-wire\.v(\d+)\.ts$/);
+ if (match === null) continue;
+ const [, family, version] = match;
+
+ const testName = `${family}-wire.v${version}.test.ts`;
+ if (!entries.includes(testName)) {
+ violations.push({
+ rule: 40,
+ file: `${WIRE_FAMILY_DIR}/${name}`,
+ line: 1,
+ message: `wire family "${family}" version ${version} has no colocated contract test (${testName}). Pin this version's schema/encoder or migration/fixtures before shipping it.`,
+ });
+ }
+ }
+
+ const contractSource = await readFile(join(REPO_ROOT, SESSION_INBOX_WIRE_CONTRACT), "utf8");
+ const registryMatch = contractSource.match(
+ /SESSION_INBOX_WIRE_VERSIONS\s*=\s*\[([^\]]*)\]\s*as const/,
+ );
+ const tokens = registryMatch?.[1]
+ .split(",")
+ .map((token) => token.trim())
+ .filter(Boolean);
+ if (tokens === undefined || tokens.length === 0 || tokens.some((token) => !/^\d+$/.test(token))) {
+ violations.push({
+ rule: 40,
+ file: SESSION_INBOX_WIRE_CONTRACT,
+ line: 1,
+ message:
+ "SESSION_INBOX_WIRE_VERSIONS must be an explicit numeric tuple so CI can compare the declared protocol history with shipped version modules.",
+ });
+ return violations;
+ }
+
+ const line = contractSource.slice(0, registryMatch.index).split("\n").length;
+ const versions = tokens.map(Number);
+ const expectedVersions = versions.map((_, index) => index + 1);
+ if (JSON.stringify(versions) !== JSON.stringify(expectedVersions)) {
+ violations.push({
+ rule: 40,
+ file: SESSION_INBOX_WIRE_CONTRACT,
+ line,
+ message: `SESSION_INBOX_WIRE_VERSIONS must be contiguous and ascending from 1; found [${versions.join(", ")}]. Add new versions without renumbering or removing protocol history.`,
+ });
+ }
+
+ const shippedVersions = entries
+ .flatMap((name) => {
+ const match = name.match(/^session-inbox-wire\.v(\d+)\.ts$/);
+ return match === null ? [] : [Number(match[1])];
+ })
+ .sort((left, right) => left - right);
+ const registeredModules = [0, ...versions];
+ if (JSON.stringify(shippedVersions) !== JSON.stringify(registeredModules)) {
+ violations.push({
+ rule: 40,
+ file: SESSION_INBOX_WIRE_CONTRACT,
+ line,
+ message: `session-inbox wire modules [${shippedVersions.join(", ")}] must exactly match legacy v0 plus registered versions [${registeredModules.join(", ")}].`,
+ });
+ }
+
+ return violations;
+}
+
// ---------- Rule 19: AsyncLocalStorage instances ----------
const NEW_ALS_RE = /new\s+AsyncLocalStorage\s*[<(]/;
@@ -1271,6 +1358,9 @@ async function main() {
// Rule 38
violations.push(...(await checkRule38NoNestedEveBuild()));
+ // Rule 40
+ violations.push(...(await checkRule40WireContracts()));
+
if (violations.length === 0) {
process.stdout.write("[eve:guard:invariants] ok — all mechanical lints passed.\n");
return;