Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

refactor(eve): turns - own subagent waits inside the active turn (#320)

Andrew Barbaf1abdfd69285
diff --git a/.changeset/dry-hooks-agree.md b/.changeset/dry-hooks-agree.md
new file mode 100644
index 000000000..607f3bf3a
--- /dev/null
+++ b/.changeset/dry-hooks-agree.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Deduplicate repeated durable turn dispatches through turn-inbox ownership so a duplicate child workflow no longer fails the active session.
diff --git a/.changeset/quiet-turns-wait.md b/.changeset/quiet-turns-wait.md
new file mode 100644
index 000000000..cee4b5390
--- /dev/null
+++ b/.changeset/quiet-turns-wait.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Keep each logical turn active while local or remote subagents run, including while proxying child input requests, so child completion resumes the same turn instead of starting a replacement turn.
diff --git a/docs/connections/overview.mdx b/docs/connections/overview.mdx
index a5d78ca3c..6c276c5d0 100644
--- a/docs/connections/overview.mdx
+++ b/docs/connections/overview.mdx
@@ -32,11 +32,11 @@ eve resolves and caches connection tokens per step; they never land in conversat
A connection credential can belong to the agent or to the person using it. This choice is separate from route auth, but user-scoped connection auth depends on route auth: eve can only resolve a user token when the active session has `ctx.session.auth.current?.principalType === "user"`.
-| Credential owner | Use when | Auth shape |
-| ---------------- | --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| App | The agent should use one shared service, bot, installation, or app credential. | `auth: { getToken }` defaults to `principalType: "app"`, or use `connect({ connector: "linear/myagent", principalType: "app" })` with Vercel Connect. |
-| User | Each end-user should authorize and use their own third-party account. | `connect("linear/myagent")`, `connect({ connector: "linear/myagent", principalType: "user" })`, or `auth: { principalType: "user", getToken }`. |
-| User from a job | Background work should use the same user's OAuth grant that started the work. | Start or resume the session through a channel whose route auth resolved that user, or pass an explicit user auth context when dispatching through a channel. |
+| Credential owner | Use when | Auth shape |
+| ---------------- | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| App | The agent should use one shared service, bot, installation, or app credential. | `auth: { getToken }` defaults to `principalType: "app"`, or use `connect({ connector: "linear/myagent", principalType: "app" })` with Vercel Connect. |
+| User | Each end-user should authorize and use their own third-party account. | `connect("linear/myagent")`, `connect({ connector: "linear/myagent", principalType: "user" })`, or `auth: { principalType: "user", getToken }`. |
+| User from a job | Background work should use the same user's OAuth grant that started the work. | Start or resume the session through a channel whose route auth resolved that user, or pass an explicit user auth context when dispatching through a channel. |
`principalType: "user"` does not mean "ask any human later." It means "key this credential to the authenticated user already attached to the eve session." If the run was started by a schedule, a same-project runtime token, `localDev()`, or another internal runtime path without an end-user principal, a user-scoped connection fails with `reason: "principal_required"` instead of starting OAuth. In that case, either authenticate the inbound channel as a user or configure the connection as app-scoped.
@@ -157,12 +157,12 @@ App-scoped Connect auth is non-interactive. eve asks Vercel Connect for an app t
### Troubleshooting Vercel Connect auth
-| Symptom | What it means | Fix |
-| -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
-| `reason: "principal_required"` | A user-scoped connection ran without an authenticated user on the active session. | Return `principalType: "user"` from the channel's route auth, or change the connection to `principalType: "app"` if it should be shared. |
-| `authorization.required` appears but no UI | eve parked the turn for OAuth, but the channel or frontend is not rendering the challenge. | Render the challenge from the stream event and continue the same session after the callback. |
-| OAuth works locally but fails after deploy | The project may not be linked to the Connect client, or the deployed runtime may not have the expected Vercel OIDC/project scope. | Run Connect setup from the consuming project directory, link the project, deploy again, and verify the connector UID in `connect("...")`. |
-| A scheduled or internal run needs user OAuth | Schedules and runtime callers do not automatically carry an end-user principal. | Dispatch through a user-authenticated channel when work is user-owned, or use app-scoped auth for agent-owned background work. |
+| Symptom | What it means | Fix |
+| -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
+| `reason: "principal_required"` | A user-scoped connection ran without an authenticated user on the active session. | Return `principalType: "user"` from the channel's route auth, or change the connection to `principalType: "app"` if it should be shared. |
+| `authorization.required` appears but no UI | eve parked the turn for OAuth, but the channel or frontend is not rendering the challenge. | Render the challenge from the stream event and continue the same session after the callback. |
+| OAuth works locally but fails after deploy | The project may not be linked to the Connect client, or the deployed runtime may not have the expected Vercel OIDC/project scope. | Run Connect setup from the consuming project directory, link the project, deploy again, and verify the connector UID in `connect("...")`. |
+| A scheduled or internal run needs user OAuth | Schedules and runtime callers do not automatically carry an end-user principal. | Dispatch through a user-authenticated channel when work is user-owned, or use app-scoped auth for agent-owned background work. |
## Self-hosted interactive OAuth
diff --git a/e2e/README.md b/e2e/README.md
index b5b629be4..56a621c3e 100644
--- a/e2e/README.md
+++ b/e2e/README.md
@@ -13,8 +13,9 @@ pnpm exec eve eval --strict
```
Every retained e2e eval is deterministic and self-contained. Coverage that
-needs external services, injected env, or provider credentials is intentionally
-not part of this suite.
+needs external services or injected env is intentionally not part of this
+suite. Most fixtures use the shared model-provider credentials; dedicated
+runtime stress fixtures may use an authored deterministic model instead.
Each retained fixture package also exposes the same command as:
@@ -58,9 +59,12 @@ npx eve eval --strict --url "$DEPLOYMENT_URL"
Do not set `VERCEL_TEAM_ID` at build: sandbox template keys must derive
identically at build and runtime, and Vercel has no team variable at runtime.
-Both local and deployed evals run the fixture agents and judges against real
+Most local and deployed evals run the fixture agents and judges against real
models (`openai/gpt-5.5`), so the environment must provide the corresponding
-model-provider credentials.
+model-provider credentials. `agent-workflow-stress` uses an authored AI SDK
+mock model so its 100-turn runs stay fast and deterministic. Its concurrent and
+sequential evals cover high-volume session execution and repeated session
+resumption respectively.
## Fixtures
diff --git a/e2e/fixtures/agent-workflow-stress/.gitignore b/e2e/fixtures/agent-workflow-stress/.gitignore
new file mode 100644
index 000000000..4301967e4
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-stress/.gitignore
@@ -0,0 +1,11 @@
+node_modules
+.env*
+.eve
+.vercel
+.workflow-data
+.next
+.output
+.nitro
+dist
+.DS_Store
+*.tsbuildinfo
diff --git a/e2e/fixtures/agent-workflow-stress/.vercelignore b/e2e/fixtures/agent-workflow-stress/.vercelignore
new file mode 100644
index 000000000..27188ef27
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-stress/.vercelignore
@@ -0,0 +1,7 @@
+.env*.local
+node_modules
+.eve
+.next
+.output
+.nitro
+dist
diff --git a/e2e/fixtures/agent-workflow-stress/agent/agent.ts b/e2e/fixtures/agent-workflow-stress/agent/agent.ts
new file mode 100644
index 000000000..ce1d11121
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-stress/agent/agent.ts
@@ -0,0 +1,92 @@
+import { defineAgent } from "eve";
+import { MockLanguageModelV3 } from "ai/test";
+
+type GenerateOptions = Parameters<MockLanguageModelV3["doGenerate"]>[0];
+type GenerateResult = Awaited<ReturnType<MockLanguageModelV3["doGenerate"]>>;
+type StreamResult = Awaited<ReturnType<MockLanguageModelV3["doStream"]>>;
+
+const RESPONSE_TIMESTAMP = new Date("2026-06-26T00:00:00.000Z");
+
+const model = new MockLanguageModelV3({
+ provider: "eve-stress",
+ modelId: "workflow-turns",
+ doGenerate: async (options) => createGenerateResult(options),
+ doStream: async (options) => createStreamResult(createGenerateResult(options)),
+});
+
+export default defineAgent({
+ model,
+ modelContextWindowTokens: 1_000_000,
+});
+
+function createGenerateResult(options: GenerateOptions): GenerateResult {
+ const userMessages = options.prompt.filter((message) => message.role === "user");
+ const latestMessage = userMessages.at(-1);
+ const latestText = latestMessage === undefined ? "" : contentText(latestMessage.content);
+ const text = `stress-ack:${userMessages.length}:${latestText}`;
+ const inputTokens = estimateTokens(
+ options.prompt.map((message) => contentText(message.content)).join(" "),
+ );
+ const outputTokens = estimateTokens(text);
+
+ return {
+ content: [{ text, type: "text" }],
+ finishReason: { raw: undefined, unified: "stop" },
+ response: {
+ id: `stress-response-${userMessages.length}`,
+ modelId: model.modelId,
+ timestamp: RESPONSE_TIMESTAMP,
+ },
+ usage: {
+ inputTokens: {
+ cacheRead: 0,
+ cacheWrite: 0,
+ noCache: inputTokens,
+ total: inputTokens,
+ },
+ outputTokens: {
+ reasoning: 0,
+ text: outputTokens,
+ total: outputTokens,
+ },
+ },
+ warnings: [],
+ };
+}
+
+function createStreamResult(result: GenerateResult): StreamResult {
+ const text = result.content.find((part) => part.type === "text")?.text ?? "";
+
+ return {
+ stream: new ReadableStream({
+ start(controller) {
+ controller.enqueue({ type: "stream-start", warnings: result.warnings });
+ controller.enqueue({ ...result.response, type: "response-metadata" });
+ controller.enqueue({ id: "stress-text", type: "text-start" });
+ controller.enqueue({ delta: text, id: "stress-text", type: "text-delta" });
+ controller.enqueue({ id: "stress-text", type: "text-end" });
+ controller.enqueue({
+ finishReason: result.finishReason,
+ type: "finish",
+ usage: result.usage,
+ });
+ controller.close();
+ },
+ }),
+ };
+}
+
+function contentText(content: GenerateOptions["prompt"][number]["content"]): string {
+ if (typeof content === "string") {
+ return content;
+ }
+
+ return content
+ .flatMap((part) => (part.type === "text" ? [part.text] : []))
+ .join("")
+ .trim();
+}
+
+function estimateTokens(value: string): number {
+ return Math.max(1, Math.ceil(value.length / 4));
+}
diff --git a/e2e/fixtures/agent-workflow-stress/agent/instructions.md b/e2e/fixtures/agent-workflow-stress/agent/instructions.md
new file mode 100644
index 000000000..d6f3831d5
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-stress/agent/instructions.md
@@ -0,0 +1 @@
+You are a deterministic stress-test agent.
diff --git a/e2e/fixtures/agent-workflow-stress/evals/concurrent-workflow-turns.eval.ts b/e2e/fixtures/agent-workflow-stress/evals/concurrent-workflow-turns.eval.ts
new file mode 100644
index 000000000..a46566b96
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-stress/evals/concurrent-workflow-turns.eval.ts
@@ -0,0 +1,42 @@
+import { defineEval } from "eve/evals";
+import { equals } from "eve/evals/expect";
+
+const SESSION_COUNT = 50;
+const TURNS_PER_SESSION = 2;
+const TURN_COUNT = SESSION_COUNT * TURNS_PER_SESSION;
+
+export default defineEval({
+ description: "Workflow stress: 50 durable sessions complete 100 total turns.",
+ tags: ["stress", "workflow", "concurrent"],
+
+ async test(t) {
+ const sessions = Array.from({ length: SESSION_COUNT }, () => t.newSession());
+ const firstTurns = await Promise.all(
+ sessions.map((session, index) => session.send(markerFor(index, 1))),
+ );
+ const secondTurns = await Promise.all(
+ sessions.map((session, index) => session.send(markerFor(index, 2))),
+ );
+
+ for (let index = 0; index < SESSION_COUNT; index += 1) {
+ const first = firstTurns[index]!.expectOk();
+ const second = secondTurns[index]!.expectOk();
+
+ await t.require(first.message, equals(`stress-ack:1:${markerFor(index, 1)}`));
+ await t.require(second.message, equals(`stress-ack:2:${markerFor(index, 2)}`));
+ await t.require(second.sessionId, equals(first.sessionId));
+ }
+
+ await t.require(new Set(firstTurns.map((turn) => turn.sessionId)).size, equals(SESSION_COUNT));
+
+ t.succeeded();
+ t.event("session.started", { count: SESSION_COUNT });
+ t.event("turn.started", { count: TURN_COUNT });
+ t.event("turn.completed", { count: TURN_COUNT });
+ t.notEvent("turn.failed");
+ },
+});
+
+function markerFor(sessionIndex: number, turnNumber: number): string {
+ return `stress-session-${String(sessionIndex + 1).padStart(2, "0")}-turn-${turnNumber}`;
+}
diff --git a/e2e/fixtures/agent-workflow-stress/evals/evals.config.ts b/e2e/fixtures/agent-workflow-stress/evals/evals.config.ts
new file mode 100644
index 000000000..18709137f
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-stress/evals/evals.config.ts
@@ -0,0 +1,6 @@
+import { defineEvalConfig } from "eve/evals";
+
+export default defineEvalConfig({
+ maxConcurrency: 1,
+ timeoutMs: 600_000,
+});
diff --git a/e2e/fixtures/agent-workflow-stress/evals/sequential-workflow-turns.eval.ts b/e2e/fixtures/agent-workflow-stress/evals/sequential-workflow-turns.eval.ts
new file mode 100644
index 000000000..825899f47
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-stress/evals/sequential-workflow-turns.eval.ts
@@ -0,0 +1,28 @@
+import { defineEval } from "eve/evals";
+import { equals } from "eve/evals/expect";
+
+const TURN_COUNT = 100;
+
+export default defineEval({
+ description: "Workflow stress: one durable session completes 100 sequential turns.",
+ tags: ["stress", "workflow", "sequential"],
+
+ async test(t) {
+ let sessionId: string | undefined;
+
+ for (let turnNumber = 1; turnNumber <= TURN_COUNT; turnNumber += 1) {
+ const marker = `sequential-turn-${String(turnNumber).padStart(3, "0")}`;
+ const turn = (await t.send(marker)).expectOk();
+
+ sessionId ??= turn.sessionId;
+ await t.require(turn.sessionId, equals(sessionId));
+ await t.require(turn.message, equals(`stress-ack:${turnNumber}:${marker}`));
+ }
+
+ t.succeeded();
+ t.event("session.started", { count: 1 });
+ t.event("turn.started", { count: TURN_COUNT });
+ t.event("turn.completed", { count: TURN_COUNT });
+ t.notEvent("turn.failed");
+ },
+});
diff --git a/e2e/fixtures/agent-workflow-stress/package.json b/e2e/fixtures/agent-workflow-stress/package.json
new file mode 100644
index 000000000..5469ecc86
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-stress/package.json
@@ -0,0 +1,24 @@
+{
+ "name": "agent-workflow-stress",
+ "version": "0.0.0",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "build": "eve build",
+ "dev": "eve dev",
+ "start": "eve start",
+ "typecheck": "eve build && tsc",
+ "test:e2e": "eve eval --strict"
+ },
+ "dependencies": {
+ "@opentelemetry/core": "2.6.1",
+ "@opentelemetry/sdk-trace-base": "2.6.1",
+ "@vercel/otel": "2.1.2",
+ "ai": "catalog:",
+ "eve": "workspace:*"
+ },
+ "devDependencies": {
+ "@types/node": "catalog:",
+ "typescript": "catalog:"
+ }
+}
diff --git a/e2e/fixtures/agent-workflow-stress/tsconfig.json b/e2e/fixtures/agent-workflow-stress/tsconfig.json
new file mode 100644
index 000000000..66f5b1ea5
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-stress/tsconfig.json
@@ -0,0 +1,17 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "outDir": "dist",
+ "rootDir": ".",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "declaration": true,
+ "noEmit": true,
+ "types": ["node"]
+ },
+ "include": ["agent/**/*.ts", "evals/**/*.ts", ".eve/**/*.d.ts"]
+}
diff --git a/packages/eve/src/execution/deliver-payloads.ts b/packages/eve/src/execution/deliver-payloads.ts
new file mode 100644
index 000000000..123e38092
--- /dev/null
+++ b/packages/eve/src/execution/deliver-payloads.ts
@@ -0,0 +1,25 @@
+import type { DeliverPayload } from "#channel/types.js";
+import type { InputResponse } from "#runtime/input/types.js";
+
+/** Coalesces channel payloads while preserving every structured input response. */
+export function coalesceDeliverPayloads(payloads: readonly DeliverPayload[]): DeliverPayload {
+ if (payloads.length === 0) return {};
+ if (payloads.length === 1) return payloads[0] ?? {};
+
+ const merged: Record<string, unknown> = {};
+ const inputResponses: InputResponse[] = [];
+
+ for (const payload of payloads) {
+ for (const [key, value] of Object.entries(payload)) {
+ if (key !== "inputResponses" && value !== undefined) {
+ merged[key] = value;
+ }
+ }
+ if (payload.inputResponses !== undefined) {
+ inputResponses.push(...payload.inputResponses);
+ }
+ }
+
+ if (inputResponses.length > 0) merged.inputResponses = inputResponses;
+ return merged as DeliverPayload;
+}
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.ts
index 9a7141d15..117037be6 100644
--- a/packages/eve/src/execution/dispatch-runtime-actions-step.ts
+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.ts
@@ -49,6 +49,8 @@ const log = createLogger("execution.dispatch-runtime-actions");
export async function dispatchRuntimeActionsStep(input: {
readonly callbackBaseUrl?: string;
+ /** Internal hook that receives child completion and HITL payloads. */
+ readonly parentContinuationToken?: string;
readonly parentWritable: WritableStream<Uint8Array>;
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
@@ -106,6 +108,7 @@ export async function dispatchRuntimeActionsStep(input: {
capabilities,
channelMetadata,
initiatorAuth,
+ parentContinuationToken: input.parentContinuationToken,
session,
});
const handle = await childRuntime.run(runInput);
@@ -131,6 +134,7 @@ export async function dispatchRuntimeActionsStep(input: {
childSessionId = await startRemoteAgentSession({
action,
callbackBaseUrl: input.callbackBaseUrl,
+ callbackToken: input.parentContinuationToken,
remote: resolvedRemote,
session,
});
diff --git a/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts
index 829b90a6b..19197118b 100644
--- a/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts
+++ b/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts
@@ -15,6 +15,7 @@ import type { RuntimeSubagentResultActionResult } from "#runtime/actions/types.j
/** Dispatches the child-agent action currently blocking a dynamic workflow. */
export async function dispatchWorkflowRuntimeActionsStep(input: {
readonly callbackBaseUrl?: string;
+ readonly parentContinuationToken?: string;
readonly parentWritable: WritableStream<Uint8Array>;
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
@@ -50,6 +51,7 @@ export async function dispatchWorkflowRuntimeActionsStep(input: {
return dispatchRuntimeActionsStep({
callbackBaseUrl: input.callbackBaseUrl,
+ parentContinuationToken: input.parentContinuationToken,
parentWritable: input.parentWritable,
serializedContext: input.serializedContext,
sessionState: createDurableSessionState({ session: sessionWithBatch }),
diff --git a/packages/eve/src/execution/durable-session-migrations/turn-workflow.test.ts b/packages/eve/src/execution/durable-session-migrations/turn-workflow.test.ts
index 7d8feda93..b8e248e62 100644
--- a/packages/eve/src/execution/durable-session-migrations/turn-workflow.test.ts
+++ b/packages/eve/src/execution/durable-session-migrations/turn-workflow.test.ts
@@ -18,6 +18,7 @@ describe("turn workflow wire migrations", () => {
const input = {
capabilities: undefined,
completionToken: "turn-token",
+ driverCapabilities: { turnInbox: true },
mode: "conversation",
stepInput: {
input: createDelivery(),
@@ -49,6 +50,7 @@ describe("turn workflow wire migrations", () => {
).toEqual({
capabilities: undefined,
completionToken: "turn-token",
+ driverCapabilities: { turnInbox: true },
mode: "conversation",
stepInput: {
input: delivery,
diff --git a/packages/eve/src/execution/durable-session-migrations/turn-workflow.ts b/packages/eve/src/execution/durable-session-migrations/turn-workflow.ts
index 59891d18b..347724582 100644
--- a/packages/eve/src/execution/durable-session-migrations/turn-workflow.ts
+++ b/packages/eve/src/execution/durable-session-migrations/turn-workflow.ts
@@ -30,6 +30,13 @@ export interface TurnWorkflowInput {
readonly version: typeof TURN_WORKFLOW_INPUT_VERSION;
readonly capabilities: SessionCapabilities | undefined;
readonly completionToken: string;
+ /**
+ * Additive driver feature negotiation. Older pinned drivers omit this,
+ * which keeps runtime-action orchestration on the legacy entry-owned path.
+ */
+ readonly driverCapabilities?: {
+ readonly turnInbox?: true;
+ };
readonly mode: RunMode;
readonly stepInput: TurnStepInput;
}
@@ -50,6 +57,7 @@ export function createTurnWorkflowInput(input: TurnWorkflowDispatchInput): TurnW
return {
capabilities: input.capabilities,
completionToken: input.completionToken,
+ driverCapabilities: { turnInbox: true },
mode: input.mode,
stepInput: {
input: input.delivery,
diff --git a/packages/eve/src/execution/forward-turn-delivery-step.ts b/packages/eve/src/execution/forward-turn-delivery-step.ts
new file mode 100644
index 000000000..fa668f69c
--- /dev/null
+++ b/packages/eve/src/execution/forward-turn-delivery-step.ts
@@ -0,0 +1,12 @@
+import type { TurnInboxPayload } from "#execution/turn-control-protocol.js";
+import { resumeHook } from "#internal/workflow/runtime.js";
+
+/** Forwards one accepted public delivery to the private inbox of its requesting turn. */
+export async function forwardTurnDeliveryStep(input: {
+ readonly inboxToken: string;
+ readonly payload: TurnInboxPayload;
+}): Promise<void> {
+ "use step";
+
+ await resumeHook(input.inboxToken, input.payload);
+}
diff --git a/packages/eve/src/execution/hook-ownership.ts b/packages/eve/src/execution/hook-ownership.ts
index 089cc0fee..890aa852c 100644
--- a/packages/eve/src/execution/hook-ownership.ts
+++ b/packages/eve/src/execution/hook-ownership.ts
@@ -56,10 +56,18 @@ function normalizeHookClaimError(error: unknown, token: string): unknown {
);
}
-function isHookConflictError(
- error: unknown,
-): error is Error & { readonly conflictingRunId?: unknown; readonly token?: unknown } {
- return error instanceof Error && error.name === "HookConflictError";
+/** Recognizes hook conflicts across current and legacy Workflow World implementations. */
+export function isHookConflictError(error: unknown): error is {
+ readonly conflictingRunId?: unknown;
+ readonly name: "HookConflictError";
+ readonly token?: unknown;
+} {
+ return (
+ typeof error === "object" &&
+ error !== null &&
+ "name" in error &&
+ error.name === "HookConflictError"
+ );
}
function createHookConflictError(
diff --git a/packages/eve/src/execution/remote-agent-dispatch.test.ts b/packages/eve/src/execution/remote-agent-dispatch.test.ts
index 99941061f..9cf507cd3 100644
--- a/packages/eve/src/execution/remote-agent-dispatch.test.ts
+++ b/packages/eve/src/execution/remote-agent-dispatch.test.ts
@@ -104,6 +104,36 @@ describe("startRemoteAgentSession", () => {
expect(body.mode).toBe("task");
});
+ it("targets an active turn inbox when a callback token is supplied", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValue(
+ new Response(JSON.stringify({ sessionId: "remote-session" }), { status: 202 }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ await startRemoteAgentSession({
+ action: createAction(),
+ callbackBaseUrl: "https://caller.example.com",
+ callbackToken: "turn-inbox",
+ remote: createRemoteAgent(),
+ session: {
+ agent: { modelReference: { id: "mock/test" }, system: "", tools: [] },
+ compaction: { recentWindowSize: 10, threshold: 100000 },
+ continuationToken: "eve:parent-token",
+ history: [],
+ sessionId: "parent-session",
+ },
+ });
+
+ expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string).callback).toEqual({
+ callId: "call-remote",
+ subagentName: "research",
+ token: "turn-inbox",
+ url: "https://caller.example.com/eve/v1/callback/turn-inbox",
+ });
+ });
+
it("adds the Vercel automation bypass secret to callback URLs", async () => {
vi.stubEnv("VERCEL_AUTOMATION_BYPASS_SECRET", "remote callback secret");
const fetchMock = vi
diff --git a/packages/eve/src/execution/remote-agent-dispatch.ts b/packages/eve/src/execution/remote-agent-dispatch.ts
index 5291b3c69..0e8401ea6 100644
--- a/packages/eve/src/execution/remote-agent-dispatch.ts
+++ b/packages/eve/src/execution/remote-agent-dispatch.ts
@@ -10,10 +10,11 @@ import type { ResolvedRuntimeRemoteAgentNode } from "#runtime/types.js";
export async function startRemoteAgentSession(input: {
readonly action: RuntimeRemoteAgentCallActionRequest;
readonly callbackBaseUrl: string | undefined;
+ readonly callbackToken?: string;
readonly remote: ResolvedRuntimeRemoteAgentNode;
readonly session: HarnessSession;
}): Promise<string> {
- const callbackToken = input.session.continuationToken;
+ const callbackToken = input.callbackToken ?? input.session.continuationToken;
if (!callbackToken) {
throw new Error("Cannot dispatch remote agent without a parent continuation token.");
}
diff --git a/packages/eve/src/execution/route-child-delivery.ts b/packages/eve/src/execution/route-child-delivery.ts
new file mode 100644
index 000000000..5fef594ed
--- /dev/null
+++ b/packages/eve/src/execution/route-child-delivery.ts
@@ -0,0 +1,32 @@
+import type { DeliverPayload, SessionAuthContext } from "#channel/types.js";
+import { coalesceDeliverPayloads } from "#execution/deliver-payloads.js";
+import type { DurableSessionState } from "#execution/durable-session-store.js";
+import { routeProxiedDeliverStep } from "#execution/workflow-steps.js";
+
+/**
+ * Coalesces inbound deliver payloads and routes any descendant-bound input
+ * responses down to the owning child, returning the parent-local remainder
+ * (or `undefined` when the whole payload routed away).
+ *
+ * Short-circuits via `hasProxyInputRequests` so the common no-active-descendant
+ * path skips a durable step boundary. Lives in its own non-step module so both
+ * the driver and the active turn can share it (a `"use step"` module cannot
+ * re-export plain helpers into a workflow body).
+ */
+export async function routeDeliverToChildren(input: {
+ readonly auth?: SessionAuthContext | null;
+ readonly parentWritable: WritableStream<Uint8Array>;
+ readonly payloads: readonly DeliverPayload[];
+ readonly sessionState: DurableSessionState;
+}): Promise<DeliverPayload | undefined> {
+ const payload = coalesceDeliverPayloads(input.payloads);
+ if (!input.sessionState.hasProxyInputRequests) return payload;
+
+ const routed = await routeProxiedDeliverStep({
+ auth: input.auth,
+ parentWritable: input.parentWritable,
+ payload,
+ sessionState: input.sessionState,
+ });
+ return routed.remainder;
+}
diff --git a/packages/eve/src/execution/session-delivery-hook.integration.test.ts b/packages/eve/src/execution/session-delivery-hook.integration.test.ts
new file mode 100644
index 000000000..055bc4528
--- /dev/null
+++ b/packages/eve/src/execution/session-delivery-hook.integration.test.ts
@@ -0,0 +1,118 @@
+import { describe, expect, it } from "vitest";
+
+import { sessionDeliveryHookWorkflow } from "#internal/testing/session-delivery-hook-workflow.js";
+import { waitForHook } from "#internal/testing/workflow-test-helpers.js";
+import { getWorld, resumeHook, start } from "#internal/workflow/runtime.js";
+
+describe("session delivery hook integration", () => {
+ it.each([
+ ["old then replacement", ["old", "replacement"] as const],
+ ["replacement then old", ["replacement", "old"] as const],
+ ])("preserves deliveries committed %s during rekey", async (_label, order) => {
+ const suffix = order.join("-");
+ const oldToken = `http:session-delivery-hook:${suffix}:old`;
+ const replacementToken = `http:session-delivery-hook:${suffix}:replacement`;
+ const disposal = await pauseHookDisposal(oldToken);
+ const run = await start(sessionDeliveryHookWorkflow, [
+ { nextToken: replacementToken, token: oldToken },
+ ]);
+
+ try {
+ await withTimeout(disposal.started, "old-hook disposal");
+ await Promise.all([
+ waitForHook({ runId: run.runId }, { token: oldToken }),
+ waitForHook({ runId: run.runId }, { token: replacementToken }),
+ ]);
+
+ const tokens = { old: oldToken, replacement: replacementToken };
+ for (const owner of order) {
+ await resumeHook(tokens[owner], {
+ kind: "deliver",
+ payloads: [{ message: owner }],
+ });
+ }
+
+ disposal.release();
+ await withTimeout(disposal.finished, "old-hook disposal completion");
+
+ await expect(
+ resumeHook(oldToken, {
+ kind: "deliver",
+ payloads: [{ message: "too late" }],
+ }),
+ ).rejects.toMatchObject({ name: "HookNotFoundError" });
+ await expect(run.returnValue).resolves.toEqual(order);
+ } finally {
+ disposal.release();
+ disposal.restore();
+ const status = await run.status;
+ if (status === "pending" || status === "running") await run.cancel();
+ }
+ });
+});
+
+async function pauseHookDisposal(token: string): Promise<{
+ readonly finished: Promise<void>;
+ readonly started: Promise<void>;
+ release(): void;
+ restore(): void;
+}> {
+ const world = await getWorld();
+ const events = world.events as {
+ create(...args: unknown[]): Promise<unknown>;
+ };
+ const originalCreate = events.create.bind(events);
+ const started = createDeferred();
+ const release = createDeferred();
+ const finished = createDeferred();
+
+ events.create = async (...args: unknown[]): Promise<unknown> => {
+ const event = args[1] as { readonly correlationId?: string; readonly eventType?: string };
+ if (event.eventType === "hook_disposed" && event.correlationId !== undefined) {
+ const hook = await world.hooks.get(event.correlationId);
+ if (hook.token === token) {
+ started.resolve();
+ await release.promise;
+ try {
+ return await originalCreate(...args);
+ } finally {
+ finished.resolve();
+ }
+ }
+ }
+ return await originalCreate(...args);
+ };
+
+ return {
+ finished: finished.promise,
+ release: release.resolve,
+ restore() {
+ events.create = originalCreate;
+ },
+ started: started.promise,
+ };
+}
+
+function createDeferred(): { readonly promise: Promise<void>; resolve(): void } {
+ let resolve!: () => void;
+ const promise = new Promise<void>((next) => {
+ resolve = next;
+ });
+ return { promise, resolve };
+}
+
+async function withTimeout<T>(promise: Promise<T>, label: string): Promise<T> {
+ let timeout: ReturnType<typeof setTimeout> | undefined;
+ try {
+ return await Promise.race([
+ promise,
+ new Promise<never>((_resolve, reject) => {
+ timeout = setTimeout(() => {
+ reject(new Error(`Timed out waiting for ${label}.`));
+ }, 10_000);
+ }),
+ ]);
+ } finally {
+ if (timeout !== undefined) clearTimeout(timeout);
+ }
+}
diff --git a/packages/eve/src/execution/session-delivery-hook.test.ts b/packages/eve/src/execution/session-delivery-hook.test.ts
new file mode 100644
index 000000000..d3337c139
--- /dev/null
+++ b/packages/eve/src/execution/session-delivery-hook.test.ts
@@ -0,0 +1,244 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { DeliverHookPayload, HookPayload } from "#channel/types.js";
+import { createSessionDeliveryHook } from "#execution/session-delivery-hook.js";
+
+const createHookMock = vi.fn();
+
+vi.mock("#compiled/@workflow/core/index.js", () => ({
+ createHook: (...args: unknown[]) => createHookMock(...args),
+}));
+
+describe("createSessionDeliveryHook", () => {
+ beforeEach(() => {
+ createHookMock.mockReset();
+ });
+
+ it("retains pending reads from both hooks across rekey", async () => {
+ const oldRead = createDeferred<IteratorResult<HookPayload>>();
+ const replacementRead = createDeferred<IteratorResult<HookPayload>>();
+ const oldHook = createMockHook({ reads: [oldRead.promise], token: "old" });
+ const replacementHook = createMockHook({
+ reads: [replacementRead.promise],
+ token: "replacement",
+ });
+ installHooks(oldHook, replacementHook);
+ const deliveryHook = createSessionDeliveryHook([]);
+
+ await deliveryHook.rekey("old");
+ const pending = deliveryHook.next();
+ await deliveryHook.rekey("replacement");
+
+ oldRead.resolve(delivery("old"));
+ await expect(pending).resolves.toEqual(delivery("old"));
+ deliveryHook.consumeNext();
+
+ replacementRead.resolve(delivery("replacement"));
+ await expect(deliveryHook.next()).resolves.toEqual(delivery("replacement"));
+ deliveryHook.consumeNext();
+ await deliveryHook.dispose();
+
+ expect(oldHook.dispose).toHaveBeenCalledOnce();
+ expect(replacementHook.dispose).toHaveBeenCalledOnce();
+ });
+
+ it("appends drained rekey deliveries after existing buffered deliveries", async () => {
+ const bufferedDeliveries = [deliveryPayload("existing")];
+ const oldHook = createMockHook({
+ reads: [Promise.resolve(delivery("old"))],
+ token: "old",
+ });
+ const replacementHook = createMockHook({
+ reads: [Promise.resolve(delivery("replacement"))],
+ token: "replacement",
+ });
+ installHooks(oldHook, replacementHook);
+ const deliveryHook = createSessionDeliveryHook(bufferedDeliveries);
+
+ await deliveryHook.rekey("old");
+ await deliveryHook.rekey("replacement");
+ await deliveryHook.dispose();
+
+ expect(bufferedDeliveries).toEqual([
+ deliveryPayload("existing"),
+ deliveryPayload("old"),
+ deliveryPayload("replacement"),
+ ]);
+ });
+
+ it("disposes a conflicting candidate without releasing the active hook", async () => {
+ const oldHook = createMockHook({ token: "old" });
+ const candidateHook = createMockHook({
+ conflict: { runId: "wrun_owner" },
+ token: "candidate",
+ });
+ installHooks(oldHook, candidateHook);
+ const deliveryHook = createSessionDeliveryHook([]);
+
+ await deliveryHook.rekey("old");
+ await expect(deliveryHook.rekey("candidate")).rejects.toMatchObject({
+ name: "HookConflictError",
+ token: "candidate",
+ });
+
+ expect(candidateHook.dispose).toHaveBeenCalledOnce();
+ expect(oldHook.dispose).not.toHaveBeenCalled();
+
+ await deliveryHook.dispose();
+ expect(oldHook.dispose).toHaveBeenCalledOnce();
+ });
+
+ it("preserves an old-hook disposal failure while cleaning the candidate", async () => {
+ const failure = new Error("old hook disposal failed");
+ const oldHook = createMockHook({
+ dispose: vi.fn(async () => {
+ throw failure;
+ }),
+ token: "old",
+ });
+ const candidateHook = createMockHook({ token: "candidate" });
+ installHooks(oldHook, candidateHook);
+ const deliveryHook = createSessionDeliveryHook([]);
+
+ await deliveryHook.rekey("old");
+ await expect(deliveryHook.rekey("candidate")).rejects.toBe(failure);
+
+ expect(oldHook.dispose).toHaveBeenCalledOnce();
+ expect(candidateHook.dispose).toHaveBeenCalledOnce();
+ });
+
+ it("drains a committed delivery once and tolerates the retired hook re-arm rejecting", async () => {
+ // The old hook commits exactly one delivery before disposal (captured by
+ // the armed iterator read). Re-arming the retired hook awaits the exhausted
+ // cursor, which rejects; the delivery must surface exactly once and the
+ // rejection must not throw or resurrect it across later drain cycles.
+ const bufferedDeliveries: DeliverHookPayload[] = [];
+ installHooks(
+ createCursorHook({ committed: [deliveryPayload("old")], token: "old" }),
+ createCursorHook({ committed: [], token: "replacement" }),
+ createCursorHook({ committed: [], token: "third" }),
+ );
+ const deliveryHook = createSessionDeliveryHook(bufferedDeliveries);
+
+ await deliveryHook.rekey("old");
+ await deliveryHook.rekey("replacement");
+ // A further rekey forces extra drain cycles that would surface a duplicate
+ // if a retired re-arm re-yielded the already-consumed payload.
+ await deliveryHook.rekey("third");
+ await deliveryHook.dispose();
+
+ expect(bufferedDeliveries).toEqual([deliveryPayload("old")]);
+ });
+
+ it("disposes without closing or settling a pending read", async () => {
+ const hook = createMockHook({ token: "active" });
+ installHooks(hook);
+ const deliveryHook = createSessionDeliveryHook([]);
+
+ await deliveryHook.rekey("active");
+ void deliveryHook.next();
+ await deliveryHook.dispose();
+
+ expect(hook.dispose).toHaveBeenCalledOnce();
+ expect(hook.return).not.toHaveBeenCalled();
+ });
+});
+
+interface MockHook {
+ readonly dispose: ReturnType<typeof vi.fn>;
+ readonly hook: unknown;
+ readonly return: ReturnType<typeof vi.fn>;
+ readonly token: string;
+}
+
+function createMockHook(input: {
+ readonly conflict?: { readonly runId: string } | null;
+ readonly dispose?: ReturnType<typeof vi.fn>;
+ readonly reads?: readonly Promise<IteratorResult<HookPayload>>[];
+ readonly token: string;
+}): MockHook {
+ const reads = [...(input.reads ?? [])];
+ const dispose = input.dispose ?? vi.fn();
+ const getConflict = vi.fn(async () => input.conflict ?? null);
+ const next = vi.fn(
+ () =>
+ reads.shift() ??
+ new Promise<IteratorResult<HookPayload>>(() => {
+ // Intentionally pending.
+ }),
+ );
+ const iteratorReturn = vi.fn(async () => ({ done: true, value: undefined }) as const);
+ const hook = Object.assign(new Promise<HookPayload>(() => {}), {
+ [Symbol.asyncIterator]() {
+ return { next, return: iteratorReturn };
+ },
+ dispose,
+ getConflict,
+ token: input.token,
+ });
+ return { dispose, hook, return: iteratorReturn, token: input.token };
+}
+
+/**
+ * Builds a hook whose `await hook` and async iterator share one delivery
+ * cursor: each read advances a queue of committed payloads, and awaiting an
+ * exhausted cursor rejects with a `HookNotFoundError` — the contract the
+ * retired-hook re-arm in `session-delivery-hook` relies on.
+ */
+function createCursorHook(input: {
+ readonly committed: readonly HookPayload[];
+ readonly token: string;
+}): MockHook {
+ const queue: IteratorResult<HookPayload>[] = input.committed.map((value) => ({
+ done: false,
+ value,
+ }));
+ const pull = (): IteratorResult<HookPayload> => queue.shift() ?? { done: true, value: undefined };
+ const dispose = vi.fn();
+ const iteratorReturn = vi.fn(async () => ({ done: true, value: undefined }) as const);
+ const hook = {
+ [Symbol.asyncIterator]() {
+ return { next: vi.fn(async () => pull()), return: iteratorReturn };
+ },
+ dispose,
+ getConflict: vi.fn(async () => null),
+ // eslint-disable-next-line unicorn/no-thenable -- a Workflow Hook is itself a thenable
+ then<T>(onFulfilled: (value: HookPayload) => T, onRejected?: (reason: unknown) => T) {
+ const item = queue.shift();
+ const settled =
+ item === undefined
+ ? Promise.reject(Object.assign(new Error("hook disposed"), { name: "HookNotFoundError" }))
+ : Promise.resolve(item.value);
+ return settled.then(onFulfilled, onRejected);
+ },
+ token: input.token,
+ };
+ return { dispose, hook, return: iteratorReturn, token: input.token };
+}
+
+function installHooks(...hooks: readonly MockHook[]): void {
+ const queue = [...hooks];
+ createHookMock.mockImplementation((options: { readonly token: string }) => {
+ const hook = queue.shift();
+ if (hook === undefined || hook.token !== options.token) {
+ throw new Error(`Unexpected hook token "${options.token}".`);
+ }
+ return hook.hook;
+ });
+}
+
+function delivery(message: string): IteratorResult<HookPayload> {
+ return { done: false, value: deliveryPayload(message) };
+}
+
+function deliveryPayload(message: string): DeliverHookPayload {
+ return { kind: "deliver", payloads: [{ message }] };
+}
+
+function createDeferred<T>(): { readonly promise: Promise<T>; resolve(value: T): void } {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((next) => {
+ resolve = next;
+ });
+ return { promise, resolve };
+}
diff --git a/packages/eve/src/execution/session-delivery-hook.ts b/packages/eve/src/execution/session-delivery-hook.ts
new file mode 100644
index 000000000..6af0d2970
--- /dev/null
+++ b/packages/eve/src/execution/session-delivery-hook.ts
@@ -0,0 +1,224 @@
+import { createHook, type Hook } from "#compiled/@workflow/core/index.js";
+
+import type { DeliverHookPayload, HookPayload } from "#channel/types.js";
+import { claimHookOwnership, disposeHook } from "#execution/hook-ownership.js";
+
+interface HookRead {
+ readonly order: number;
+ readonly result: IteratorResult<HookPayload>;
+ readonly state: SessionDeliveryHookState;
+}
+
+interface SessionDeliveryHookState {
+ readonly hook: Hook<HookPayload>;
+ readonly iterator: AsyncIterator<HookPayload>;
+ closed: boolean;
+ enabled: boolean;
+ pending: boolean;
+ retired: boolean;
+ resolved?: HookRead;
+}
+
+/** Reads and rekeys the public delivery hook for one session driver. */
+export interface SessionDeliveryHook {
+ consumeNext(): void;
+ next(): Promise<IteratorResult<HookPayload>>;
+ rekey(token: string): Promise<void>;
+}
+
+/** Adds workflow-entry lifecycle ownership to a session delivery hook. */
+export interface SessionDeliveryHookHandle extends SessionDeliveryHook {
+ dispose(): Promise<void>;
+}
+
+/**
+ * Creates the public delivery hook used by `workflowEntry`.
+ *
+ * Retired hooks are disposed immediately, but their already-armed reads stay
+ * in the logical hook's delivery race. A delivery that committed before disposal can
+ * therefore still resolve on replay; a later delivery loses the storage race
+ * to `hook_disposed` and receives `HookNotFoundError` from the Workflow SDK.
+ */
+export function createSessionDeliveryHook(
+ bufferedDeliveries: DeliverHookPayload[],
+): SessionDeliveryHookHandle {
+ let active: SessionDeliveryHookState | undefined;
+ const retired: SessionDeliveryHookState[] = [];
+ const ready: HookRead[] = [];
+ let nextOrder = 0;
+ let offered: Promise<IteratorResult<HookPayload>> | null = null;
+ let offeredRead: HookRead | undefined;
+ let wake: (() => void) | undefined;
+
+ const enqueue = (read: HookRead): void => {
+ ready.push(read);
+ ready.sort((left, right) => left.order - right.order);
+ wake?.();
+ wake = undefined;
+ };
+
+ const arm = (state: SessionDeliveryHookState): void => {
+ if (state.closed || state.pending) return;
+
+ state.pending = true;
+ state.resolved = undefined;
+ // A retired hook is disposed, so its iterator can no longer be advanced;
+ // awaiting the hook itself surfaces the next payload that committed to the
+ // token before disposal. `await hook` and the iterator share one delivery
+ // cursor, so a payload already drained via the iterator is never re-yielded,
+ // and once the committed payloads are exhausted the read rejects (swallowed
+ // below) instead of resolving again. Re-arming a retired hook is therefore
+ // safe: it cannot double-count or resurrect a delivery.
+ const next = state.retired
+ ? Promise.resolve(state.hook).then(
+ (value): IteratorResult<HookPayload> => ({ done: false, value }),
+ )
+ : state.iterator.next();
+ void next.then(
+ (result) => {
+ const read: HookRead = {
+ order: nextOrder++,
+ result,
+ state,
+ };
+ state.resolved = read;
+ if (state.enabled) enqueue(read);
+ },
+ () => {
+ // `claimHookOwnership` owns candidate-claim errors, and an active hook
+ // read cannot reject under the public delivery contract. A retired hook
+ // read rejects once its committed payloads are exhausted; dropping it
+ // here leaves the retired state quiescent (pending, never re-enqueued).
+ },
+ );
+ };
+
+ const enable = (state: SessionDeliveryHookState): void => {
+ state.enabled = true;
+ if (state.resolved !== undefined) enqueue(state.resolved);
+ };
+
+ const drainReady = async (): Promise<void> => {
+ // A caller may already be racing this read against turn control. Leave
+ // that promise intact: the losing race ignores it, and the next call to
+ // `next()` reuses it without duplicating the delivery.
+ if (offered !== null) return;
+
+ await Promise.resolve();
+
+ while (ready.length > 0) {
+ const read = ready.shift()!;
+ read.state.pending = false;
+ read.state.resolved = undefined;
+
+ if (read.result.done) {
+ read.state.closed = true;
+ } else if (read.result.value.kind === "deliver") {
+ bufferedDeliveries.push(read.result.value);
+ }
+
+ arm(read.state);
+ await Promise.resolve();
+ }
+ };
+
+ return {
+ consumeNext(): void {
+ if (offeredRead === undefined) {
+ throw new Error("Cannot consume a public delivery before it resolves.");
+ }
+
+ offeredRead.state.pending = false;
+ offeredRead.state.resolved = undefined;
+ if (offeredRead.result.done) offeredRead.state.closed = true;
+ offeredRead = undefined;
+ offered = null;
+ },
+
+ async dispose(): Promise<void> {
+ if (active !== undefined) {
+ await disposeHook(active.hook);
+ active = undefined;
+ }
+ },
+
+ next(): Promise<IteratorResult<HookPayload>> {
+ if (active === undefined) {
+ throw new Error("Cannot wait for deliveries before a continuation token is available.");
+ }
+
+ if (offered !== null) return offered;
+
+ arm(active);
+ for (const state of retired) arm(state);
+
+ if (active.closed && retired.every((state) => state.closed)) {
+ offeredRead = {
+ order: nextOrder++,
+ result: { done: true, value: undefined },
+ state: active,
+ };
+ offered = Promise.resolve(offeredRead.result);
+ return offered;
+ }
+
+ offered = (async () => {
+ while (ready.length === 0) {
+ await new Promise<void>((resolve) => {
+ wake = resolve;
+ });
+ }
+
+ const read = ready.shift()!;
+ offeredRead = read;
+ return read.result;
+ })();
+ return offered;
+ },
+
+ async rekey(token: string): Promise<void> {
+ if (!token || active?.hook.token === token) return;
+
+ const candidateHook = createHook<HookPayload>({ token });
+ const candidate: SessionDeliveryHookState = {
+ closed: false,
+ enabled: false,
+ hook: candidateHook,
+ iterator: candidateHook[Symbol.asyncIterator](),
+ pending: false,
+ retired: false,
+ };
+
+ if (active === undefined) {
+ await claimHookOwnership(candidate.hook);
+ enable(candidate);
+ active = candidate;
+ return;
+ }
+
+ const previous = active;
+ arm(previous);
+ arm(candidate);
+ await claimHookOwnership(candidate.hook);
+ enable(candidate);
+ await drainReady();
+
+ try {
+ await disposeHook(previous.hook);
+ } catch (error) {
+ active = undefined;
+ try {
+ await disposeHook(candidate.hook);
+ } catch {
+ // The active hook release failure is authoritative.
+ }
+ throw error;
+ }
+
+ previous.retired = true;
+ retired.push(previous);
+ active = candidate;
+ await drainReady();
+ },
+ };
+}
diff --git a/packages/eve/src/execution/subagent-tool.test.ts b/packages/eve/src/execution/subagent-tool.test.ts
index 98ef795b9..6c35c206f 100644
--- a/packages/eve/src/execution/subagent-tool.test.ts
+++ b/packages/eve/src/execution/subagent-tool.test.ts
@@ -83,6 +83,21 @@ describe("buildSubagentRunInput", () => {
expect(childContinuationToken).toMatch(/^subagent:parent-session:call-1$/);
});
+ it("routes parent notifications to an active turn inbox when supplied", () => {
+ const { runInput } = buildSubagentRunInput({
+ action: makeAction(),
+ auth: null,
+ batchEvent: { sequence: 0, turnId: "turn-0" },
+ initiatorAuth: null,
+ parentContinuationToken: "turn-inbox",
+ session: makeSession(),
+ });
+
+ expect(runInput.adapter.state).toMatchObject({
+ parentContinuationToken: "turn-inbox",
+ });
+ });
+
it("forwards channelMetadata to the child run input", () => {
const projection = {
kind: "channel:slack",
diff --git a/packages/eve/src/execution/subagent-tool.ts b/packages/eve/src/execution/subagent-tool.ts
index 8ec5367e6..a5ef0f50c 100644
--- a/packages/eve/src/execution/subagent-tool.ts
+++ b/packages/eve/src/execution/subagent-tool.ts
@@ -46,6 +46,8 @@ export function buildSubagentRunInput(input: {
readonly capabilities?: SessionCapabilities;
readonly channelMetadata?: ChannelInstrumentationProjection;
readonly initiatorAuth: SessionAuthContext | null;
+ /** Hook token owned by the workflow currently waiting for this child. */
+ readonly parentContinuationToken?: string;
readonly session: HarnessSession;
}): SubagentRunInputBuild {
const { action, auth, batchEvent, capabilities, channelMetadata, initiatorAuth, session } = input;
@@ -68,7 +70,7 @@ export function buildSubagentRunInput(input: {
kind: SUBAGENT_ADAPTER_KIND,
state: {
callId: action.callId,
- parentContinuationToken: session.continuationToken,
+ parentContinuationToken: input.parentContinuationToken ?? session.continuationToken,
parentSessionId: session.sessionId,
subagentName: action.subagentName,
...(action.subagentName === "agent" && session.sandboxState
diff --git a/packages/eve/src/execution/turn-control-protocol.ts b/packages/eve/src/execution/turn-control-protocol.ts
new file mode 100644
index 000000000..893b053f7
--- /dev/null
+++ b/packages/eve/src/execution/turn-control-protocol.ts
@@ -0,0 +1,40 @@
+import type { DeliverHookPayload, HookPayload } from "#channel/types.js";
+import type { NextDriverAction } from "#execution/next-driver-action.js";
+import { resumeHook } from "#internal/workflow/runtime.js";
+
+/** Payloads delivered to the private inbox owned by one active turn. */
+export type TurnInboxPayload =
+ | Exclude<HookPayload, DeliverHookPayload>
+ | {
+ readonly delivery: DeliverHookPayload;
+ readonly kind: "driver-delivery";
+ readonly requestId: string;
+ };
+
+/** Control payloads emitted from an active turn to its session driver. */
+export type TurnControlPayload =
+ | {
+ readonly action: NextDriverAction;
+ readonly bufferedDeliveries?: readonly DeliverHookPayload[];
+ readonly kind: "turn-result";
+ }
+ | { readonly kind: "turn-error"; readonly error: unknown }
+ | { readonly continuationToken: string; readonly kind: "turn-continuation-token" }
+ | {
+ readonly continuationToken: string;
+ readonly inboxToken: string;
+ readonly kind: "turn-delivery-request";
+ readonly requestId: string;
+ }
+ | { readonly kind: "turn-delivery-accepted"; readonly requestId: string }
+ | { readonly kind: "turn-delivery-cancelled"; readonly requestId: string };
+
+/** Sends one lifecycle payload to the session driver's control hook. */
+export async function sendTurnControlStep(input: {
+ readonly controlToken: string;
+ readonly payload: TurnControlPayload;
+}): Promise<void> {
+ "use step";
+
+ await resumeHook(input.controlToken, input.payload);
+}
diff --git a/packages/eve/src/execution/turn-control-receiver.test.ts b/packages/eve/src/execution/turn-control-receiver.test.ts
new file mode 100644
index 000000000..3e587039f
--- /dev/null
+++ b/packages/eve/src/execution/turn-control-receiver.test.ts
@@ -0,0 +1,160 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { DeliverHookPayload, HookPayload } from "#channel/types.js";
+import type { DurableSessionState } from "#execution/durable-session-store.js";
+import { forwardTurnDeliveryStep } from "#execution/forward-turn-delivery-step.js";
+import type { SessionDeliveryHook } from "#execution/session-delivery-hook.js";
+import type { TurnControlPayload } from "#execution/turn-control-protocol.js";
+import { TurnControlReceiver } from "#execution/turn-control-receiver.js";
+
+const createHookMock = vi.fn();
+
+vi.mock("#compiled/@workflow/core/index.js", () => ({
+ createHook: (...args: unknown[]) => createHookMock(...args),
+}));
+
+vi.mock("./forward-turn-delivery-step.js", () => ({
+ forwardTurnDeliveryStep: vi.fn(),
+}));
+
+describe("TurnControlReceiver", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ createHookMock.mockReset();
+ });
+
+ it("forwards a buffered delivery and consumes it once the turn accepts", async () => {
+ const delivery: DeliverHookPayload = { kind: "deliver", payloads: [{ message: "hello" }] };
+ installControlHook([
+ deliveryRequest("req-1"),
+ { kind: "turn-delivery-accepted", requestId: "req-1" },
+ parkResult(),
+ ]);
+ const bufferedDeliveries: DeliverHookPayload[] = [delivery];
+
+ const action = await runReceiver(bufferedDeliveries);
+
+ expect(forwardTurnDeliveryStep).toHaveBeenCalledWith({
+ inboxToken: "turn-inbox",
+ payload: { delivery, kind: "driver-delivery", requestId: "req-1" },
+ });
+ expect(action.kind).toBe("park");
+ expect(bufferedDeliveries).toEqual([]);
+ });
+
+ it("re-buffers the outstanding delivery when the turn cancels its request", async () => {
+ const delivery: DeliverHookPayload = { kind: "deliver", payloads: [{ message: "hello" }] };
+ installControlHook([
+ deliveryRequest("req-1"),
+ { kind: "turn-delivery-cancelled", requestId: "req-1" },
+ parkResult(),
+ ]);
+ const bufferedDeliveries: DeliverHookPayload[] = [delivery];
+
+ const action = await runReceiver(bufferedDeliveries);
+
+ expect(forwardTurnDeliveryStep).toHaveBeenCalledOnce();
+ expect(action.kind).toBe("park");
+ expect(bufferedDeliveries).toEqual([delivery]);
+ });
+
+ it("re-buffers an unresolved forwarded delivery when the turn terminates", async () => {
+ const delivery: DeliverHookPayload = { kind: "deliver", payloads: [{ message: "hello" }] };
+ installControlHook([
+ deliveryRequest("req-1"),
+ {
+ action: { kind: "done", output: "bye", serializedContext: {}, sessionState: createState() },
+ kind: "turn-result",
+ },
+ ]);
+ const bufferedDeliveries: DeliverHookPayload[] = [delivery];
+
+ const action = await runReceiver(bufferedDeliveries);
+
+ expect(action).toMatchObject({ kind: "done", output: "bye" });
+ expect(bufferedDeliveries).toEqual([delivery]);
+ });
+
+ it("hands the turn's remainders back ahead of existing buffered deliveries", async () => {
+ const earlier: DeliverHookPayload = { kind: "deliver", payloads: [{ message: "earlier" }] };
+ const handBack: DeliverHookPayload = { kind: "deliver", payloads: [{ message: "from-turn" }] };
+ installControlHook([{ ...parkResult(), bufferedDeliveries: [handBack] }]);
+ const bufferedDeliveries: DeliverHookPayload[] = [earlier];
+
+ await runReceiver(bufferedDeliveries);
+
+ expect(bufferedDeliveries.map((item) => item.payloads[0]?.message)).toEqual([
+ "from-turn",
+ "earlier",
+ ]);
+ });
+
+ it("rethrows a rebuilt error when the turn reports a failure", async () => {
+ installControlHook([{ error: { message: "boom", name: "TurnError" }, kind: "turn-error" }]);
+
+ await expect(runReceiver([])).rejects.toThrow("boom");
+ });
+});
+
+function runReceiver(
+ bufferedDeliveries: DeliverHookPayload[],
+): ReturnType<TurnControlReceiver["waitForAction"]> {
+ const receiver = new TurnControlReceiver({
+ bufferedDeliveries,
+ deliveryHook: createDeliveryHook(),
+ token: "turn-control",
+ });
+ return receiver.waitForAction().finally(() => receiver.dispose());
+}
+
+function deliveryRequest(requestId: string): TurnControlPayload {
+ return {
+ continuationToken: "http:test",
+ inboxToken: "turn-inbox",
+ kind: "turn-delivery-request",
+ requestId,
+ };
+}
+
+function parkResult(): Extract<TurnControlPayload, { readonly kind: "turn-result" }> {
+ return {
+ action: { kind: "park", serializedContext: {}, sessionState: createState() },
+ kind: "turn-result",
+ };
+}
+
+function createDeliveryHook(overrides: Partial<SessionDeliveryHook> = {}): SessionDeliveryHook {
+ return {
+ consumeNext: vi.fn(),
+ next: vi.fn(() => new Promise<IteratorResult<HookPayload>>(() => {})),
+ rekey: vi.fn(),
+ ...overrides,
+ };
+}
+
+function installControlHook(values: readonly TurnControlPayload[]): void {
+ const queue = [...values];
+ createHookMock.mockReturnValue({
+ token: "turn-control",
+ dispose: vi.fn(),
+ [Symbol.asyncIterator]() {
+ return {
+ next: async () => {
+ const value = queue.shift();
+ return value === undefined ? { done: true, value: undefined } : { done: false, value };
+ },
+ return: vi.fn(async () => ({ done: true, value: undefined })),
+ };
+ },
+ });
+}
+
+function createState(): DurableSessionState {
+ return {
+ continuationToken: "http:test",
+ emissionState: { sequence: 0, sessionStarted: false, stepIndex: 0, turnId: "" },
+ hasProxyInputRequests: false,
+ sessionId: "session",
+ version: 1,
+ };
+}
diff --git a/packages/eve/src/execution/turn-control-receiver.ts b/packages/eve/src/execution/turn-control-receiver.ts
new file mode 100644
index 000000000..7c8aef2e2
--- /dev/null
+++ b/packages/eve/src/execution/turn-control-receiver.ts
@@ -0,0 +1,196 @@
+import { createHook, type Hook } from "#compiled/@workflow/core/index.js";
+
+import type { DeliverHookPayload } from "#channel/types.js";
+import type { TurnControlPayload } from "#execution/turn-control-protocol.js";
+import { forwardTurnDeliveryStep } from "#execution/forward-turn-delivery-step.js";
+import { closeHookIterator, disposeHook } from "#execution/hook-ownership.js";
+import type { NextDriverAction } from "#execution/next-driver-action.js";
+import type { SessionDeliveryHook } from "#execution/session-delivery-hook.js";
+import { rebuildSerializableError } from "#execution/workflow-errors.js";
+
+type DeliveryRequest = Extract<TurnControlPayload, { readonly kind: "turn-delivery-request" }>;
+
+/** Owns one turn's driver-side control hook and public-delivery relay state. */
+export class TurnControlReceiver {
+ private readonly bufferedDeliveries: DeliverHookPayload[];
+ private readonly control: Hook<TurnControlPayload>;
+ private readonly controlIterator: AsyncIterator<TurnControlPayload>;
+ private readonly deliveryHook: SessionDeliveryHook;
+ private pendingControl: Promise<IteratorResult<TurnControlPayload>> | null = null;
+
+ constructor(input: {
+ readonly bufferedDeliveries: DeliverHookPayload[];
+ readonly deliveryHook: SessionDeliveryHook;
+ readonly token: string;
+ }) {
+ this.bufferedDeliveries = input.bufferedDeliveries;
+ this.control = createHook<TurnControlPayload>({ token: input.token });
+ this.controlIterator = this.control[Symbol.asyncIterator]();
+ this.deliveryHook = input.deliveryHook;
+ }
+
+ /** Token passed to the turn workflow so it can publish control messages. */
+ get token(): string {
+ return this.control.token;
+ }
+
+ /** Releases the turn control hook and its iterator. */
+ async dispose(): Promise<void> {
+ await closeHookIterator(this.controlIterator);
+ await disposeHook(this.control);
+ }
+
+ /** Services control messages until the active turn returns its terminal driver action. */
+ async waitForAction(): Promise<NextDriverAction> {
+ while (true) {
+ const payload = await this.nextControl(
+ "Turn control hook closed before delivering a result.",
+ );
+
+ const terminal = this.readTerminalControl(payload);
+ if (terminal !== undefined) return terminal;
+
+ if (payload.kind === "turn-delivery-request") {
+ const resolved = await this.serviceDeliveryRequest(payload);
+ if (resolved !== undefined) return resolved;
+ }
+ }
+ }
+
+ private bufferTurnDeliveries(
+ payload: Extract<TurnControlPayload, { readonly kind: "turn-result" }>,
+ ): void {
+ if (payload.bufferedDeliveries !== undefined) {
+ this.bufferedDeliveries.unshift(...payload.bufferedDeliveries);
+ }
+ }
+
+ private consumeControl(): void {
+ this.pendingControl = null;
+ }
+
+ private getControlPromise(): Promise<IteratorResult<TurnControlPayload>> {
+ this.pendingControl ??= this.controlIterator.next();
+ return this.pendingControl;
+ }
+
+ private async nextControl(
+ onClosed: string,
+ ): Promise<
+ Exclude<TurnControlPayload, { readonly kind: "turn-error" | "turn-continuation-token" }>
+ > {
+ while (true) {
+ const next = await this.getControlPromise();
+ this.consumeControl();
+ if (next.done) throw new Error(onClosed);
+ const payload = next.value;
+ if (payload.kind === "turn-error") throw rebuildSerializableError(payload.error);
+ if (payload.kind === "turn-continuation-token") {
+ await this.deliveryHook.rekey(payload.continuationToken);
+ continue;
+ }
+ return payload;
+ }
+ }
+
+ private readTerminalControl(payload: TurnControlPayload): NextDriverAction | undefined {
+ if (payload.kind === "turn-error") throw rebuildSerializableError(payload.error);
+ if (payload.kind !== "turn-result") return undefined;
+ this.bufferTurnDeliveries(payload);
+ return payload.action;
+ }
+
+ private async serviceDeliveryRequest(
+ request: DeliveryRequest,
+ ): Promise<NextDriverAction | undefined> {
+ await this.deliveryHook.rekey(request.continuationToken);
+
+ let delivery = this.bufferedDeliveries.shift();
+ while (delivery === undefined) {
+ const winner = await Promise.race([
+ this.getControlPromise().then((value) => ({ kind: "control" as const, value })),
+ this.deliveryHook.next().then((value) => ({ kind: "delivery" as const, value })),
+ ]);
+
+ if (winner.kind === "control") {
+ this.consumeControl();
+ if (winner.value.done) {
+ throw new Error("Turn control hook closed during a delivery request.");
+ }
+ if (winner.value.value.kind === "turn-continuation-token") {
+ await this.deliveryHook.rekey(winner.value.value.continuationToken);
+ continue;
+ }
+ const terminal = this.readTerminalControl(winner.value.value);
+ if (terminal !== undefined) return terminal;
+ if (
+ winner.value.value.kind === "turn-delivery-cancelled" &&
+ winner.value.value.requestId === request.requestId
+ ) {
+ return undefined;
+ }
+ continue;
+ }
+
+ if (winner.value.done) {
+ throw new Error("Session delivery hook closed during a turn delivery request.");
+ }
+
+ this.deliveryHook.consumeNext();
+ if (winner.value.value.kind !== "deliver") continue;
+ delivery = winner.value.value;
+ }
+
+ // Forwarding is provisional until the turn acknowledges it. If the inbox is
+ // already gone (the turn ended or was replaced), the turn's terminal or
+ // cancellation still re-buffers the delivery for the next parent turn.
+ try {
+ await forwardTurnDeliveryStep({
+ inboxToken: request.inboxToken,
+ payload: {
+ delivery,
+ kind: "driver-delivery",
+ requestId: request.requestId,
+ },
+ });
+ } catch (error) {
+ if (!(error instanceof Error && error.name === "HookNotFoundError")) throw error;
+ }
+
+ return await this.awaitForwardedDelivery(request.requestId, delivery);
+ }
+
+ /**
+ * Waits for the active turn to resolve a forwarded delivery. The turn either
+ * accepts it (consumed) or releases it on cancellation or termination, in
+ * which case the delivery returns to the buffer ahead of the turn's own
+ * remainders so the next parent turn still observes it in arrival order.
+ */
+ private async awaitForwardedDelivery(
+ requestId: string,
+ outstanding: DeliverHookPayload,
+ ): Promise<NextDriverAction | undefined> {
+ while (true) {
+ const payload = await this.nextControl(
+ "Turn control hook closed before resolving a forwarded delivery.",
+ );
+
+ if (payload.kind === "turn-delivery-accepted") {
+ if (payload.requestId === requestId) return undefined;
+ continue;
+ }
+
+ if (payload.kind === "turn-delivery-cancelled" && payload.requestId === requestId) {
+ this.bufferedDeliveries.unshift(outstanding);
+ return undefined;
+ }
+
+ if (payload.kind === "turn-result") {
+ this.bufferedDeliveries.unshift(outstanding);
+ }
+
+ const terminal = this.readTerminalControl(payload);
+ if (terminal !== undefined) return terminal;
+ }
+ }
+}
diff --git a/packages/eve/src/execution/turn-dispatch.test.ts b/packages/eve/src/execution/turn-dispatch.test.ts
new file mode 100644
index 000000000..45c6bea15
--- /dev/null
+++ b/packages/eve/src/execution/turn-dispatch.test.ts
@@ -0,0 +1,230 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { DeliverHookPayload, HookPayload } from "#channel/types.js";
+import type { DurableSessionState } from "#execution/durable-session-store.js";
+import { forwardTurnDeliveryStep } from "#execution/forward-turn-delivery-step.js";
+import type { SessionDeliveryHook } from "#execution/session-delivery-hook.js";
+import { dispatchAndAwaitTurn } from "#execution/turn-dispatch.js";
+import type { TurnControlPayload } from "#execution/turn-control-protocol.js";
+
+const createHookMock = vi.fn();
+
+vi.mock("#compiled/@workflow/core/index.js", () => ({
+ createHook: (...args: unknown[]) => createHookMock(...args),
+}));
+
+vi.mock("./workflow-steps.js", () => ({
+ dispatchTurnStep: vi.fn(async () => ({ runId: "turn-run" })),
+}));
+
+vi.mock("./forward-turn-delivery-step.js", () => ({
+ forwardTurnDeliveryStep: vi.fn(),
+}));
+
+describe("dispatchAndAwaitTurn", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ createHookMock.mockReset();
+ });
+
+ it("rekeys the public hook when the active turn changes its continuation token", async () => {
+ const state = createState("slack:C1:T1");
+ installControlHook([
+ { continuationToken: "slack:C1:T1", kind: "turn-continuation-token" },
+ {
+ action: { kind: "park", serializedContext: {}, sessionState: state },
+ kind: "turn-result",
+ },
+ ]);
+ const rekeyHook = vi.fn();
+ const deliveryHook = createDeliveryHook({ rekey: rekeyHook });
+
+ await dispatchAndAwaitTurn({
+ bufferedDeliveries: [],
+ controlToken: "turn-control",
+ delivery: { kind: "deliver", payloads: [{ message: "start" }] },
+ deliveryHook,
+ mode: "conversation",
+ parentWritable: new WritableStream<Uint8Array>(),
+ serializedContext: {},
+ sessionState: createState("slack:C1:"),
+ });
+
+ expect(rekeyHook).toHaveBeenCalledWith("slack:C1:T1");
+ });
+
+ it("rekeys while a turn delivery request is already waiting", async () => {
+ const state = createState("slack:C1:T1");
+ installControlHook([
+ {
+ continuationToken: "slack:C1:",
+ inboxToken: "turn-inbox",
+ kind: "turn-delivery-request",
+ requestId: "request-1",
+ },
+ { continuationToken: "slack:C1:T1", kind: "turn-continuation-token" },
+ { kind: "turn-delivery-cancelled", requestId: "request-1" },
+ {
+ action: { kind: "park", serializedContext: {}, sessionState: state },
+ kind: "turn-result",
+ },
+ ]);
+ const rekeyHook = vi.fn();
+ const deliveryHook = createDeliveryHook({ rekey: rekeyHook });
+
+ await dispatchAndAwaitTurn({
+ bufferedDeliveries: [],
+ controlToken: "turn-control",
+ delivery: { kind: "deliver", payloads: [{ message: "start" }] },
+ deliveryHook,
+ mode: "conversation",
+ parentWritable: new WritableStream<Uint8Array>(),
+ serializedContext: {},
+ sessionState: createState("slack:C1:"),
+ });
+
+ expect(rekeyHook).toHaveBeenCalledWith("slack:C1:T1");
+ });
+
+ it("keeps earlier turn remainders ahead of later cancelled deliveries", async () => {
+ const state = createState("http:test");
+ let releaseCancellation: (() => void) | undefined;
+ const forwarded = new Promise<void>((resolve) => {
+ releaseCancellation = resolve;
+ });
+ vi.mocked(forwardTurnDeliveryStep).mockImplementation(async () => releaseCancellation?.());
+
+ let controlIndex = 0;
+ createHookMock.mockReturnValue(
+ createMockHook(async () => {
+ controlIndex += 1;
+ if (controlIndex === 1) {
+ return {
+ done: false,
+ value: {
+ continuationToken: "http:test",
+ inboxToken: "turn-inbox",
+ kind: "turn-delivery-request",
+ requestId: "request-1",
+ },
+ };
+ }
+ if (controlIndex === 2) {
+ await forwarded;
+ return {
+ done: false,
+ value: { kind: "turn-delivery-cancelled", requestId: "request-1" },
+ };
+ }
+ return {
+ done: false,
+ value: {
+ action: { kind: "park", serializedContext: {}, sessionState: state },
+ bufferedDeliveries: [{ kind: "deliver", payloads: [{ message: "earlier remainder" }] }],
+ kind: "turn-result",
+ },
+ };
+ }),
+ );
+
+ const bufferedDeliveries: DeliverHookPayload[] = [];
+ await dispatchAndAwaitTurn({
+ bufferedDeliveries,
+ controlToken: "turn-control",
+ delivery: { kind: "deliver", payloads: [{ message: "start" }] },
+ deliveryHook: createDeliveryHook({
+ next: async () => ({
+ done: false,
+ value: { kind: "deliver", payloads: [{ message: "later delivery" }] },
+ }),
+ }),
+ mode: "conversation",
+ parentWritable: new WritableStream<Uint8Array>(),
+ serializedContext: {},
+ sessionState: state,
+ });
+
+ expect(bufferedDeliveries.map((item) => item.payloads[0]?.message)).toEqual([
+ "earlier remainder",
+ "later delivery",
+ ]);
+ });
+
+ it("re-buffers a forwarded delivery when the turn inbox is already gone", async () => {
+ const state = createState("http:test");
+ const delivery: DeliverHookPayload = { kind: "deliver", payloads: [{ message: "relayed" }] };
+ vi.mocked(forwardTurnDeliveryStep).mockRejectedValue(
+ Object.assign(new Error("inbox gone"), { name: "HookNotFoundError" }),
+ );
+ installControlHook([
+ {
+ continuationToken: "http:test",
+ inboxToken: "turn-inbox",
+ kind: "turn-delivery-request",
+ requestId: "request-1",
+ },
+ {
+ action: { kind: "park", serializedContext: {}, sessionState: state },
+ kind: "turn-result",
+ },
+ ]);
+
+ const bufferedDeliveries: DeliverHookPayload[] = [delivery];
+ const action = await dispatchAndAwaitTurn({
+ bufferedDeliveries,
+ controlToken: "turn-control",
+ delivery: { kind: "deliver", payloads: [{ message: "start" }] },
+ deliveryHook: createDeliveryHook(),
+ mode: "conversation",
+ parentWritable: new WritableStream<Uint8Array>(),
+ serializedContext: {},
+ sessionState: state,
+ });
+
+ expect(forwardTurnDeliveryStep).toHaveBeenCalledOnce();
+ expect(action.kind).toBe("park");
+ expect(bufferedDeliveries).toEqual([delivery]);
+ });
+});
+
+function createDeliveryHook(overrides: Partial<SessionDeliveryHook> = {}): SessionDeliveryHook {
+ return {
+ consumeNext: vi.fn(),
+ next: vi.fn(() => new Promise<IteratorResult<HookPayload>>(() => {})),
+ rekey: vi.fn(),
+ ...overrides,
+ };
+}
+
+function installControlHook(values: readonly TurnControlPayload[]): void {
+ const queue = [...values];
+ createHookMock.mockReturnValue(
+ createMockHook(async () => {
+ const value = queue.shift();
+ return value === undefined ? { done: true, value: undefined } : { done: false, value };
+ }),
+ );
+}
+
+function createMockHook(next: () => Promise<IteratorResult<TurnControlPayload>>): unknown {
+ return {
+ token: "turn-control",
+ dispose: vi.fn(),
+ [Symbol.asyncIterator]() {
+ return {
+ next,
+ return: vi.fn(async () => ({ done: true, value: undefined })),
+ };
+ },
+ };
+}
+
+function createState(continuationToken: string): DurableSessionState {
+ return {
+ continuationToken,
+ emissionState: { sequence: 0, sessionStarted: false, stepIndex: 0, turnId: "" },
+ hasProxyInputRequests: false,
+ sessionId: "session",
+ version: 1,
+ };
+}
diff --git a/packages/eve/src/execution/turn-dispatch.ts b/packages/eve/src/execution/turn-dispatch.ts
new file mode 100644
index 000000000..b2aa35d59
--- /dev/null
+++ b/packages/eve/src/execution/turn-dispatch.ts
@@ -0,0 +1,42 @@
+import type { DeliverHookPayload, HookPayload, SessionCapabilities } from "#channel/types.js";
+import { TurnControlReceiver } from "#execution/turn-control-receiver.js";
+import type { DurableSessionState } from "#execution/durable-session-store.js";
+import type { NextDriverAction } from "#execution/next-driver-action.js";
+import type { SessionDeliveryHook } from "#execution/session-delivery-hook.js";
+import { dispatchTurnStep } from "#execution/workflow-steps.js";
+import type { RunMode } from "#shared/run-mode.js";
+
+/** Dispatches one turn and services its private-inbox control protocol until it terminates. */
+export async function dispatchAndAwaitTurn(input: {
+ readonly bufferedDeliveries: DeliverHookPayload[];
+ readonly capabilities?: SessionCapabilities;
+ readonly controlToken: string;
+ readonly delivery: HookPayload;
+ readonly deliveryHook: SessionDeliveryHook;
+ readonly mode: RunMode;
+ readonly parentWritable: WritableStream<Uint8Array>;
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+}): Promise<NextDriverAction> {
+ const control = new TurnControlReceiver({
+ bufferedDeliveries: input.bufferedDeliveries,
+ deliveryHook: input.deliveryHook,
+ token: input.controlToken,
+ });
+
+ try {
+ await dispatchTurnStep({
+ capabilities: input.capabilities,
+ completionToken: control.token,
+ delivery: input.delivery,
+ mode: input.mode,
+ parentWritable: input.parentWritable,
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
+ });
+
+ return await control.waitForAction();
+ } finally {
+ await control.dispose();
+ }
+}
diff --git a/packages/eve/src/execution/turn-execution-cursor.test.ts b/packages/eve/src/execution/turn-execution-cursor.test.ts
new file mode 100644
index 000000000..04a815bf5
--- /dev/null
+++ b/packages/eve/src/execution/turn-execution-cursor.test.ts
@@ -0,0 +1,85 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { sendTurnControlStep } from "#execution/turn-control-protocol.js";
+import type { DurableSessionState } from "#execution/durable-session-store.js";
+import { TurnExecutionCursor } from "#execution/turn-execution-cursor.js";
+
+vi.mock("./turn-control-protocol.js", () => ({
+ sendTurnControlStep: vi.fn(),
+}));
+
+describe("TurnExecutionCursor", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("adopts transitions and reports each continuation token once", async () => {
+ const parentWritable = new WritableStream<Uint8Array>();
+ const cursor = new TurnExecutionCursor({
+ controlToken: "turn-control",
+ parentWritable,
+ serializedContext: { revision: 1 },
+ sessionState: createState("slack:C1:"),
+ });
+ const anchoredState = createState("slack:C1:T1");
+
+ await cursor.adopt({ serializedContext: { revision: 2 }, sessionState: anchoredState });
+ await cursor.adopt({ sessionState: anchoredState });
+
+ expect(sendTurnControlStep).toHaveBeenCalledOnce();
+ expect(sendTurnControlStep).toHaveBeenCalledWith({
+ controlToken: "turn-control",
+ payload: {
+ continuationToken: "slack:C1:T1",
+ kind: "turn-continuation-token",
+ },
+ });
+ expect(cursor.createStepInput(undefined)).toEqual({
+ input: undefined,
+ parentWritable,
+ serializedContext: { revision: 2 },
+ sessionState: anchoredState,
+ });
+ });
+
+ it("publishes a terminal transition without a redundant token update", async () => {
+ const cursor = new TurnExecutionCursor({
+ controlToken: "turn-control",
+ parentWritable: new WritableStream<Uint8Array>(),
+ serializedContext: { revision: 1 },
+ sessionState: createState("slack:C1:"),
+ });
+ const finalState = createState("slack:C1:T1");
+
+ await cursor.finish(
+ { serializedContext: { revision: 2 }, sessionState: finalState },
+ { kind: "done", output: "ok" },
+ [{ kind: "deliver", payloads: [{ message: "queued" }] }],
+ );
+
+ expect(sendTurnControlStep).toHaveBeenCalledOnce();
+ expect(sendTurnControlStep).toHaveBeenCalledWith({
+ controlToken: "turn-control",
+ payload: {
+ action: {
+ kind: "done",
+ output: "ok",
+ serializedContext: { revision: 2 },
+ sessionState: finalState,
+ },
+ bufferedDeliveries: [{ kind: "deliver", payloads: [{ message: "queued" }] }],
+ kind: "turn-result",
+ },
+ });
+ });
+});
+
+function createState(continuationToken: string): DurableSessionState {
+ return {
+ continuationToken,
+ emissionState: { sequence: 0, sessionStarted: false, stepIndex: 0, turnId: "" },
+ hasProxyInputRequests: false,
+ sessionId: "session",
+ version: 1,
+ };
+}
diff --git a/packages/eve/src/execution/turn-execution-cursor.ts b/packages/eve/src/execution/turn-execution-cursor.ts
new file mode 100644
index 000000000..32724c70f
--- /dev/null
+++ b/packages/eve/src/execution/turn-execution-cursor.ts
@@ -0,0 +1,107 @@
+import type { DeliverHookPayload, HookPayload } from "#channel/types.js";
+import type { TurnControlPayload } from "#execution/turn-control-protocol.js";
+import { sendTurnControlStep } from "#execution/turn-control-protocol.js";
+import type { DurableSessionState } from "#execution/durable-session-store.js";
+import type { TurnStepInput } from "#execution/durable-session-migrations/turn-workflow.js";
+
+interface TurnTransition {
+ readonly serializedContext?: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+}
+
+type TurnTerminalAction =
+ | {
+ readonly isError?: boolean;
+ readonly kind: "done";
+ readonly output: unknown;
+ }
+ | {
+ readonly authorizationNames?: readonly string[];
+ readonly kind: "park";
+ };
+
+/** Owns the mutable durable state cursor for one active turn workflow. */
+export class TurnExecutionCursor {
+ readonly controlToken: string;
+ readonly parentWritable: WritableStream<Uint8Array>;
+
+ private currentSerializedContext: Record<string, unknown>;
+ private currentSessionState: DurableSessionState;
+ private lastReportedContinuationToken: string;
+
+ constructor(input: {
+ readonly controlToken: string;
+ readonly parentWritable: WritableStream<Uint8Array>;
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+ }) {
+ this.controlToken = input.controlToken;
+ this.currentSerializedContext = input.serializedContext;
+ this.currentSessionState = input.sessionState;
+ this.lastReportedContinuationToken = input.sessionState.continuationToken;
+ this.parentWritable = input.parentWritable;
+ }
+
+ /** Latest serialized runtime context adopted by the active turn. */
+ get serializedContext(): Record<string, unknown> {
+ return this.currentSerializedContext;
+ }
+
+ /** Latest durable session state adopted by the active turn. */
+ get sessionState(): DurableSessionState {
+ return this.currentSessionState;
+ }
+
+ /** Adopts a state transition and reports any continuation-token change once. */
+ async adopt(transition: TurnTransition): Promise<void> {
+ this.setState(transition);
+
+ const nextToken = transition.sessionState.continuationToken;
+ if (nextToken === "" || nextToken === this.lastReportedContinuationToken) return;
+
+ this.lastReportedContinuationToken = nextToken;
+ await this.send({ continuationToken: nextToken, kind: "turn-continuation-token" });
+ }
+
+ /** Builds the next atomic turn-step input from the cursor's current state. */
+ createStepInput(input: HookPayload | undefined): TurnStepInput {
+ return {
+ input,
+ parentWritable: this.parentWritable,
+ serializedContext: this.currentSerializedContext,
+ sessionState: this.currentSessionState,
+ };
+ }
+
+ /**
+ * Adopts a terminal turn transition and publishes it as the turn result.
+ * The result already carries the final session state, so no separate
+ * continuation-token update is sent.
+ */
+ async finish(
+ transition: TurnTransition,
+ action: TurnTerminalAction,
+ bufferedDeliveries: readonly DeliverHookPayload[],
+ ): Promise<void> {
+ this.setState(transition);
+ await this.send({
+ action: {
+ ...action,
+ serializedContext: this.currentSerializedContext,
+ sessionState: this.currentSessionState,
+ },
+ bufferedDeliveries: bufferedDeliveries.length === 0 ? undefined : [...bufferedDeliveries],
+ kind: "turn-result",
+ });
+ }
+
+ /** Sends one control payload to the session driver. */
+ async send(payload: TurnControlPayload): Promise<void> {
+ await sendTurnControlStep({ controlToken: this.controlToken, payload });
+ }
+
+ private setState(transition: TurnTransition): void {
+ this.currentSerializedContext = transition.serializedContext ?? this.currentSerializedContext;
+ this.currentSessionState = transition.sessionState;
+ }
+}
diff --git a/packages/eve/src/execution/turn-workflow.test.ts b/packages/eve/src/execution/turn-workflow.test.ts
index e901230a4..14611b872 100644
--- a/packages/eve/src/execution/turn-workflow.test.ts
+++ b/packages/eve/src/execution/turn-workflow.test.ts
@@ -1,28 +1,55 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import type { HookPayload } from "#channel/types.js";
+import { dispatchRuntimeActionsStep } from "#execution/dispatch-runtime-actions-step.js";
+import { dispatchWorkflowRuntimeActionsStep } from "#execution/dispatch-workflow-runtime-actions-step.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
import { turnWorkflow } from "#execution/turn-workflow.js";
import {
TURN_WORKFLOW_INPUT_VERSION,
type TurnWorkflowInput,
} from "#execution/durable-session-migrations/turn-workflow.js";
-import { turnStep } from "#execution/workflow-steps.js";
+import { routeDeliverToChildren } from "#execution/route-child-delivery.js";
+import { runProxyInputRequestStep, turnStep } from "#execution/workflow-steps.js";
const resumeHookMock = vi.fn();
+const createHookMock = vi.fn();
+
+vi.mock("#compiled/@workflow/core/index.js", () => ({
+ createHook: (...args: unknown[]) => createHookMock(...args),
+ getWorkflowMetadata: vi.fn(() => ({ url: "https://eve.example.com" })),
+}));
vi.mock("#compiled/@workflow/core/runtime.js", () => ({
resumeHook: (...args: unknown[]) => resumeHookMock(...args),
}));
+vi.mock("./route-child-delivery.js", () => ({
+ routeDeliverToChildren: vi.fn(),
+}));
+
vi.mock("./workflow-steps.js", () => ({
+ runProxyInputRequestStep: vi.fn(),
turnStep: vi.fn(),
}));
+vi.mock("./dispatch-runtime-actions-step.js", () => ({
+ dispatchRuntimeActionsStep: vi.fn(),
+}));
+
+vi.mock("./dispatch-workflow-runtime-actions-step.js", () => ({
+ dispatchWorkflowRuntimeActionsStep: vi.fn(),
+}));
+
+vi.mock("./workflow-callback-url.js", () => ({
+ resolveWorkflowCallbackBaseUrl: vi.fn((metadataUrl: string) => metadataUrl),
+}));
+
describe("turnWorkflow", () => {
afterEach(() => {
vi.clearAllMocks();
resumeHookMock.mockReset();
+ createHookMock.mockReset();
});
it("notifies the driver when a turn completes", async () => {
@@ -220,8 +247,421 @@ describe("turnWorkflow", () => {
kind: "turn-error",
});
});
+
+ it("deduplicates concurrent turn workflows through inbox ownership", async () => {
+ const sessionState = createSessionState();
+ const ownerInbox = createInboxMock([]);
+ const duplicateInbox = createInboxMock([], {
+ conflict: { runId: "wrun_owner" },
+ });
+ createHookMock.mockReturnValueOnce(ownerInbox.hook).mockReturnValueOnce(duplicateInbox.hook);
+ vi.mocked(turnStep).mockResolvedValueOnce({
+ action: "done",
+ output: "ok",
+ serializedContext: { state: "done" },
+ sessionState,
+ });
+
+ const { input } = createInput({
+ driverCapabilities: { turnInbox: true },
+ sessionState,
+ });
+ await Promise.all([turnWorkflow(input), turnWorkflow(input)]);
+
+ expect(turnStep).toHaveBeenCalledOnce();
+ expect(
+ resumeHookMock.mock.calls.filter((call) => call[1]?.kind === "turn-result"),
+ ).toHaveLength(1);
+ expect(resumeHookMock.mock.calls.filter((call) => call[1]?.kind === "turn-error")).toEqual([]);
+ expect(ownerInbox.dispose).toHaveBeenCalledOnce();
+ expect(duplicateInbox.dispose).toHaveBeenCalledOnce();
+ expect(ownerInbox.createIterator).toHaveBeenCalledOnce();
+ expect(duplicateInbox.createIterator).toHaveBeenCalledOnce();
+ });
+
+ it("deduplicates a cross-realm inbox conflict rejection", async () => {
+ const inbox = installInbox([], {
+ claimError: {
+ conflictingRunId: "wrun_owner",
+ name: "HookConflictError",
+ token: "turn-token:inbox",
+ },
+ });
+ const { input } = createInput({ driverCapabilities: { turnInbox: true } });
+
+ await turnWorkflow(input);
+
+ expect(turnStep).not.toHaveBeenCalled();
+ expect(resumeHookMock).not.toHaveBeenCalled();
+ expect(inbox.dispose).toHaveBeenCalledOnce();
+ expect(inbox.createIterator).toHaveBeenCalledOnce();
+ });
+
+ it("reports non-conflict inbox claim failures to the driver", async () => {
+ const failure = new Error("hook storage unavailable");
+ const inbox = installInbox([], { claimError: failure });
+ const { input } = createInput({ driverCapabilities: { turnInbox: true } });
+
+ await expect(turnWorkflow(input)).rejects.toBe(failure);
+
+ expect(turnStep).not.toHaveBeenCalled();
+ expect(resumeHookMock).toHaveBeenCalledTimes(1);
+ expect(resumeHookMock.mock.calls[0]?.[0]).toBe("turn-token");
+ expect(resumeHookMock.mock.calls[0]?.[1]).toMatchObject({ kind: "turn-error" });
+ expect(inbox.dispose).toHaveBeenCalledOnce();
+ expect(inbox.createIterator).toHaveBeenCalledOnce();
+ });
+
+ it("keeps a local subagent result inside one turn workflow", async () => {
+ const initialState = createSessionState({ continuationToken: "slack:C1:" });
+ const pendingState = createSessionState({ continuationToken: "slack:C1:T1" });
+ const completedState = createSessionState({ continuationToken: "slack:C1:T1" });
+ installInbox([
+ {
+ kind: "runtime-action-result",
+ results: [
+ {
+ callId: "call-1",
+ kind: "subagent-result",
+ output: "child output",
+ subagentName: "delegate",
+ },
+ ],
+ },
+ ]);
+ vi.mocked(dispatchRuntimeActionsStep).mockResolvedValue({
+ results: [],
+ sessionState: pendingState,
+ });
+ vi.mocked(turnStep)
+ .mockResolvedValueOnce({
+ action: "park",
+ hasPendingAuthorization: false,
+ hasPendingInputBatch: false,
+ pendingRuntimeActionKeys: ["subagent-call:delegate:call-1"],
+ serializedContext: { state: "pending" },
+ sessionState: pendingState,
+ })
+ .mockResolvedValueOnce({
+ action: "done",
+ output: "parent output",
+ serializedContext: { state: "done" },
+ sessionState: completedState,
+ });
+
+ const { input, parentWritable } = createInput({
+ driverCapabilities: { turnInbox: true },
+ mode: "task",
+ sessionState: initialState,
+ });
+ await turnWorkflow(input);
+
+ expect(resumeHookMock).toHaveBeenCalledWith("turn-token", {
+ continuationToken: "slack:C1:T1",
+ kind: "turn-continuation-token",
+ });
+ expect(resumeHookMock.mock.invocationCallOrder[0]).toBeLessThan(
+ vi.mocked(dispatchRuntimeActionsStep).mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
+ );
+ expect(dispatchRuntimeActionsStep).toHaveBeenCalledWith({
+ callbackBaseUrl: "https://eve.example.com",
+ parentContinuationToken: "turn-token:inbox",
+ parentWritable,
+ serializedContext: { state: "pending" },
+ sessionState: pendingState,
+ });
+ expect(vi.mocked(turnStep).mock.calls[1]?.[0]).toMatchObject({
+ input: {
+ kind: "runtime-action-result",
+ results: [expect.objectContaining({ callId: "call-1", output: "child output" })],
+ },
+ });
+ expect(resumeHookMock.mock.calls.filter((call) => call[1]?.kind === "turn-result")).toEqual([
+ [
+ "turn-token",
+ expect.objectContaining({
+ action: expect.objectContaining({ kind: "done", output: "parent output" }),
+ }),
+ ],
+ ]);
+ expect(resumeHookMock).not.toHaveBeenCalledWith(
+ "turn-token",
+ expect.objectContaining({
+ action: expect.objectContaining({ kind: "dispatch-runtime-actions" }),
+ }),
+ );
+ });
+
+ it("keeps dynamic-workflow child dispatch and immediate remote failures in the same turn", async () => {
+ const pendingState = createSessionState();
+ const completedState = createSessionState();
+ installInbox([]);
+ vi.mocked(dispatchWorkflowRuntimeActionsStep).mockResolvedValue({
+ results: [
+ {
+ callId: "call-1",
+ isError: true,
+ kind: "subagent-result",
+ output: { code: "REMOTE_AGENT_START_FAILED", message: "remote unavailable" },
+ subagentName: "research",
+ },
+ ],
+ sessionState: pendingState,
+ });
+ vi.mocked(turnStep)
+ .mockResolvedValueOnce({
+ action: "dispatch-workflow-runtime-actions",
+ pendingRuntimeActionKeys: ["subagent-call:research:call-1"],
+ serializedContext: { state: "pending" },
+ sessionState: pendingState,
+ })
+ .mockResolvedValueOnce({
+ action: "done",
+ output: "handled failure",
+ serializedContext: { state: "done" },
+ sessionState: completedState,
+ });
+
+ const { input, parentWritable } = createInput({
+ driverCapabilities: { turnInbox: true },
+ mode: "task",
+ sessionState: pendingState,
+ });
+ await turnWorkflow(input);
+
+ expect(dispatchWorkflowRuntimeActionsStep).toHaveBeenCalledWith({
+ callbackBaseUrl: "https://eve.example.com",
+ parentContinuationToken: "turn-token:inbox",
+ parentWritable,
+ serializedContext: { state: "pending" },
+ sessionState: pendingState,
+ });
+ expect(vi.mocked(turnStep).mock.calls[1]?.[0].input).toEqual({
+ kind: "runtime-action-result",
+ results: [expect.objectContaining({ callId: "call-1", isError: true })],
+ });
+ expect(
+ resumeHookMock.mock.calls.filter((call) => call[1]?.kind === "turn-result"),
+ ).toHaveLength(1);
+ });
+
+ it("proxies child HITL and pulls the response through the active turn", async () => {
+ const pendingState = createSessionState();
+ const proxyState = createSessionState({ hasProxyInputRequests: true });
+ const completedState = createSessionState();
+ const requestId = "turn-token:inbox:delivery:0";
+ installInbox([
+ {
+ callId: "call-1",
+ childContinuationToken: "subagent:parent:call-1",
+ childSessionId: "child-session",
+ event: { requests: [], sequence: 0, stepIndex: 0, turnId: "turn_0" },
+ kind: "subagent-input-request",
+ subagentName: "delegate",
+ },
+ {
+ delivery: {
+ kind: "deliver",
+ payloads: [{ inputResponses: [{ optionId: "approve", requestId: "approval-1" }] }],
+ },
+ kind: "driver-delivery",
+ requestId,
+ },
+ {
+ kind: "runtime-action-result",
+ results: [
+ {
+ callId: "call-1",
+ kind: "subagent-result",
+ output: "approved child output",
+ subagentName: "delegate",
+ },
+ ],
+ },
+ ]);
+ vi.mocked(dispatchRuntimeActionsStep).mockResolvedValue({
+ results: [],
+ sessionState: pendingState,
+ });
+ vi.mocked(runProxyInputRequestStep).mockResolvedValue({
+ serializedContext: { state: "proxied" },
+ sessionState: proxyState,
+ });
+ vi.mocked(routeDeliverToChildren).mockResolvedValue(undefined);
+ vi.mocked(turnStep)
+ .mockResolvedValueOnce({
+ action: "park",
+ hasPendingAuthorization: false,
+ hasPendingInputBatch: false,
+ pendingRuntimeActionKeys: ["subagent-call:delegate:call-1"],
+ serializedContext: { state: "pending" },
+ sessionState: pendingState,
+ })
+ .mockResolvedValueOnce({
+ action: "done",
+ output: "done",
+ serializedContext: { state: "done" },
+ sessionState: completedState,
+ });
+
+ const { input } = createInput({
+ driverCapabilities: { turnInbox: true },
+ mode: "task",
+ sessionState: pendingState,
+ });
+ await turnWorkflow(input);
+
+ expect(runProxyInputRequestStep).toHaveBeenCalledOnce();
+ expect(resumeHookMock).toHaveBeenCalledWith("turn-token", {
+ continuationToken: "http:test",
+ inboxToken: "turn-token:inbox",
+ kind: "turn-delivery-request",
+ requestId,
+ });
+ expect(resumeHookMock).toHaveBeenCalledWith("turn-token", {
+ kind: "turn-delivery-accepted",
+ requestId,
+ });
+ expect(routeDeliverToChildren).toHaveBeenCalledWith(
+ expect.objectContaining({
+ payloads: [{ inputResponses: [{ optionId: "approve", requestId: "approval-1" }] }],
+ sessionState: proxyState,
+ }),
+ );
+ });
+
+ it("mints a unique delivery request id per wait so a stale forward is not re-accepted", async () => {
+ const pendingState = createSessionState({ hasProxyInputRequests: true });
+ const completedState = createSessionState();
+ // The first wait resolves on its child result while a delivery forwarded for
+ // request `:delivery:0` is still queued behind it. The second wait must mint
+ // a fresh id so that stale forward is dropped, not mistaken for its response.
+ installInbox([
+ {
+ kind: "runtime-action-result",
+ results: [
+ { callId: "call-1", kind: "subagent-result", output: "first", subagentName: "delegate" },
+ ],
+ },
+ {
+ delivery: {
+ kind: "deliver",
+ payloads: [{ inputResponses: [{ optionId: "approve", requestId: "approval-1" }] }],
+ },
+ kind: "driver-delivery",
+ requestId: "turn-token:inbox:delivery:0",
+ },
+ {
+ kind: "runtime-action-result",
+ results: [
+ {
+ callId: "call-2",
+ kind: "subagent-result",
+ output: "second",
+ subagentName: "delegate",
+ },
+ ],
+ },
+ ]);
+ vi.mocked(dispatchRuntimeActionsStep).mockResolvedValue({
+ results: [],
+ sessionState: pendingState,
+ });
+ vi.mocked(routeDeliverToChildren).mockResolvedValue(undefined);
+ vi.mocked(turnStep)
+ .mockResolvedValueOnce({
+ action: "park",
+ hasPendingAuthorization: false,
+ hasPendingInputBatch: false,
+ pendingRuntimeActionKeys: ["subagent-call:delegate:call-1"],
+ serializedContext: { state: "batch-1" },
+ sessionState: pendingState,
+ })
+ .mockResolvedValueOnce({
+ action: "park",
+ hasPendingAuthorization: false,
+ hasPendingInputBatch: false,
+ pendingRuntimeActionKeys: ["subagent-call:delegate:call-2"],
+ serializedContext: { state: "batch-2" },
+ sessionState: pendingState,
+ })
+ .mockResolvedValueOnce({
+ action: "done",
+ output: "done",
+ serializedContext: { state: "done" },
+ sessionState: completedState,
+ });
+
+ const { input } = createInput({
+ driverCapabilities: { turnInbox: true },
+ mode: "task",
+ sessionState: pendingState,
+ });
+ await turnWorkflow(input);
+
+ const deliveryRequestIds = resumeHookMock.mock.calls
+ .filter((call) => call[1]?.kind === "turn-delivery-request")
+ .map((call) => call[1]?.requestId);
+ expect(deliveryRequestIds).toEqual([
+ "turn-token:inbox:delivery:0",
+ "turn-token:inbox:delivery:1",
+ ]);
+ expect(resumeHookMock).not.toHaveBeenCalledWith(
+ "turn-token",
+ expect.objectContaining({ kind: "turn-delivery-accepted" }),
+ );
+ expect(routeDeliverToChildren).not.toHaveBeenCalled();
+ });
});
+interface InboxMock {
+ readonly createIterator: ReturnType<typeof vi.fn>;
+ readonly dispose: ReturnType<typeof vi.fn>;
+ readonly hook: unknown;
+}
+
+function installInbox(
+ values: readonly unknown[],
+ options: {
+ readonly claimError?: unknown;
+ readonly conflict?: { readonly runId: string } | null;
+ } = {},
+): InboxMock {
+ const inbox = createInboxMock(values, options);
+ createHookMock.mockReturnValue(inbox.hook);
+ return inbox;
+}
+
+function createInboxMock(
+ values: readonly unknown[],
+ options: {
+ readonly claimError?: unknown;
+ readonly conflict?: { readonly runId: string } | null;
+ } = {},
+): InboxMock {
+ const queue = [...values];
+ const dispose = vi.fn();
+ const createIterator = vi.fn(() => ({
+ next: vi.fn(async () => {
+ const value = queue.shift();
+ return value === undefined ? { done: true, value: undefined } : { done: false, value };
+ }),
+ return: vi.fn(async () => ({ done: true, value: undefined })),
+ }));
+ const hook = {
+ token: "turn-token:inbox",
+ getConflict: vi.fn(async () => {
+ if (options.claimError !== undefined) throw options.claimError;
+ return options.conflict ?? null;
+ }),
+ dispose,
+ [Symbol.asyncIterator](): AsyncIterator<unknown> {
+ return createIterator();
+ },
+ };
+ return { createIterator, dispose, hook };
+}
+
function createInput(
overrides: Partial<Omit<TurnWorkflowInput, "stepInput" | "version">> & {
readonly sessionState?: DurableSessionState;
diff --git a/packages/eve/src/execution/turn-workflow.ts b/packages/eve/src/execution/turn-workflow.ts
index 52ec16ae1..83e4e2bbd 100644
--- a/packages/eve/src/execution/turn-workflow.ts
+++ b/packages/eve/src/execution/turn-workflow.ts
@@ -1,39 +1,236 @@
-import type { NextDriverAction } from "#execution/next-driver-action.js";
-import { normalizeSerializableError } from "#execution/workflow-errors.js";
+import { createHook, getWorkflowMetadata } from "#compiled/@workflow/core/index.js";
+
+import type { DeliverHookPayload } from "#channel/types.js";
+import { sendTurnControlStep, type TurnInboxPayload } from "#execution/turn-control-protocol.js";
+import { dispatchRuntimeActionsStep } from "#execution/dispatch-runtime-actions-step.js";
+import { dispatchWorkflowRuntimeActionsStep } from "#execution/dispatch-workflow-runtime-actions-step.js";
import {
migrateTurnWorkflowInput,
type TurnStepInput,
type TurnWorkflowInput,
} from "#execution/durable-session-migrations/turn-workflow.js";
-import { turnStep } from "#execution/workflow-steps.js";
-import { resumeHook } from "#internal/workflow/runtime.js";
+import {
+ claimHookOwnership,
+ closeHookIterator,
+ disposeHook,
+ isHookConflictError,
+} from "#execution/hook-ownership.js";
+import type { NextDriverAction } from "#execution/next-driver-action.js";
+import { routeDeliverToChildren } from "#execution/route-child-delivery.js";
+import { TurnExecutionCursor } from "#execution/turn-execution-cursor.js";
+import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";
+import { normalizeSerializableError } from "#execution/workflow-errors.js";
+import { runProxyInputRequestStep, turnStep } from "#execution/workflow-steps.js";
+import { resolveRuntimeActionResultsForKeys } from "#harness/runtime-actions.js";
+import type { RuntimeActionResult } from "#runtime/actions/types.js";
const TASK_MODE_WAIT_ERROR_MESSAGE = "Task mode cannot wait for follow-up input (`next: null`).";
-/**
- * Hook payload the turn child workflow delivers to the parent driver
- * on completion. `turn-result` wraps a {@link NextDriverAction} the
- * driver dispatches on; `turn-error` carries a normalized error the
- * driver rethrows.
- */
-export type TurnCompletionPayload =
- | { readonly kind: "turn-result"; readonly action: NextDriverAction }
- | { readonly kind: "turn-error"; readonly error: unknown };
-
export type { TurnWorkflowInput };
-/**
- * Short-lived workflow that owns one runtime turn for the driver.
- *
- * `parentWritable` is threaded in from the driver run so event writes
- * land on the driver's stream. Resolves the turn into a
- * {@link NextDriverAction} and reports it back through
- * {@link notifyDriverStep}.
- */
+/** Runs one complete logical turn, including child-agent waits when supported. */
export async function turnWorkflow(rawInput: unknown): Promise<void> {
"use workflow";
const input = migrateTurnWorkflowInput(rawInput);
+
+ if (input.driverCapabilities?.turnInbox !== true) {
+ return runLegacyTurnWorkflow(input);
+ }
+
+ return runTurnOwnedWorkflow(input);
+}
+
+async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {
+ const inbox = createHook<TurnInboxPayload>({ token: `${input.completionToken}:inbox` });
+ // Hook promises and iterators share one durable cursor. Create the iterator before
+ // claiming so conflict replay is consumed by getConflict(), not a later iterator read.
+ const iterator = inbox[Symbol.asyncIterator]();
+ const cursor = new TurnExecutionCursor({
+ controlToken: input.completionToken,
+ parentWritable: input.stepInput.parentWritable,
+ serializedContext: input.stepInput.serializedContext,
+ sessionState: input.stepInput.sessionState,
+ });
+ // Delivery request ids stay unique across every wait in this turn. A forwarded
+ // delivery left unconsumed when one wait resolves would otherwise reuse a later
+ // wait's id and be mis-accepted as that wait's response.
+ let deliveryRequestSeq = 0;
+ const nextDeliveryRequestId = (): string =>
+ `${inbox.token}:delivery:${String(deliveryRequestSeq++)}`;
+ const bufferedDeliveries: DeliverHookPayload[] = [];
+ let nextStepInput = input.stepInput.input;
+ let ownsInbox = false;
+
+ try {
+ try {
+ await claimHookOwnership(inbox);
+ ownsInbox = true;
+ } catch (error) {
+ if (isHookConflictError(error)) return;
+ throw error;
+ }
+
+ while (true) {
+ const result = await turnStep(cursor.createStepInput(nextStepInput));
+
+ if (result.action === "done") {
+ await cursor.finish(
+ result,
+ { kind: "done", output: result.output ?? "", isError: result.isError },
+ bufferedDeliveries,
+ );
+ return;
+ }
+
+ // A pending runtime-action batch (model-driven `park` or dynamic-workflow
+ // interrupt) is resolved in-line so the turn stays alive across the wait;
+ // the two arms differ only in their dispatch path.
+ const pendingActionKeys =
+ result.action === "dispatch-workflow-runtime-actions" || result.action === "park"
+ ? result.pendingRuntimeActionKeys
+ : undefined;
+
+ if (pendingActionKeys !== undefined) {
+ await cursor.adopt(result);
+ const dispatch =
+ result.action === "dispatch-workflow-runtime-actions"
+ ? dispatchWorkflowRuntimeActionsStep
+ : dispatchRuntimeActionsStep;
+ const dispatchResult = await dispatch({
+ callbackBaseUrl: resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url),
+ parentContinuationToken: inbox.token,
+ parentWritable: cursor.parentWritable,
+ serializedContext: cursor.serializedContext,
+ sessionState: cursor.sessionState,
+ });
+ await cursor.adopt(dispatchResult);
+
+ const results = await waitForRuntimeActionResults({
+ bufferedDeliveries,
+ cursor,
+ inboxToken: inbox.token,
+ initialResults: dispatchResult.results,
+ iterator,
+ nextDeliveryRequestId,
+ pendingActionKeys,
+ });
+ nextStepInput = { kind: "runtime-action-result", results };
+ continue;
+ }
+
+ if (result.action === "park") {
+ const canPark =
+ result.hasPendingAuthorization ||
+ (result.hasPendingInputBatch && input.capabilities?.requestInput === true) ||
+ input.mode === "conversation";
+
+ if (!canPark) throw new Error(TASK_MODE_WAIT_ERROR_MESSAGE);
+
+ await cursor.finish(
+ result,
+ {
+ authorizationNames: result.authorizationNames,
+ kind: "park",
+ },
+ bufferedDeliveries,
+ );
+ return;
+ }
+
+ await cursor.adopt(result);
+ nextStepInput = undefined;
+ }
+ } catch (error) {
+ await cursor.send({ error: normalizeSerializableError(error), kind: "turn-error" });
+ throw error;
+ } finally {
+ await closeHookIterator(iterator);
+ if (ownsInbox) await disposeHook(inbox);
+ }
+}
+
+async function waitForRuntimeActionResults(input: {
+ readonly bufferedDeliveries: DeliverHookPayload[];
+ readonly cursor: TurnExecutionCursor;
+ readonly inboxToken: string;
+ readonly initialResults: readonly RuntimeActionResult[];
+ readonly iterator: AsyncIterator<TurnInboxPayload>;
+ readonly nextDeliveryRequestId: () => string;
+ readonly pendingActionKeys: readonly string[];
+}): Promise<readonly RuntimeActionResult[]> {
+ let pendingDeliveryRequest: string | undefined;
+ const results: RuntimeActionResult[] = [...input.initialResults];
+
+ while (true) {
+ const ready = resolveRuntimeActionResultsForKeys({
+ pendingKeys: input.pendingActionKeys,
+ results,
+ });
+ if (ready !== undefined) {
+ if (pendingDeliveryRequest !== undefined) {
+ // The entry may already be racing public input against this wait.
+ // Cancellation keeps that input available for the next parent turn.
+ await input.cursor.send({
+ kind: "turn-delivery-cancelled",
+ requestId: pendingDeliveryRequest,
+ });
+ }
+ return ready;
+ }
+
+ if (input.cursor.sessionState.hasProxyInputRequests && pendingDeliveryRequest === undefined) {
+ pendingDeliveryRequest = input.nextDeliveryRequestId();
+ await input.cursor.send({
+ continuationToken: input.cursor.sessionState.continuationToken,
+ inboxToken: input.inboxToken,
+ kind: "turn-delivery-request",
+ requestId: pendingDeliveryRequest,
+ });
+ }
+
+ const next = await input.iterator.next();
+ if (next.done) throw new Error("Turn inbox closed before runtime actions completed.");
+
+ const value = next.value;
+ if (value.kind === "runtime-action-result") {
+ results.push(...value.results);
+ continue;
+ }
+
+ if (value.kind === "subagent-input-request") {
+ const proxyResult = await runProxyInputRequestStep({
+ hookPayload: value,
+ parentWritable: input.cursor.parentWritable,
+ serializedContext: input.cursor.serializedContext,
+ sessionState: input.cursor.sessionState,
+ });
+ await input.cursor.adopt(proxyResult);
+ continue;
+ }
+
+ // Only `driver-delivery` reaches the inbox for public input: children
+ // resume it with results/HITL, and the driver relays public deliveries
+ // through the request handshake. A stale, non-matching request id means
+ // the turn already resolved and the driver re-buffered the delivery.
+ if (value.kind === "driver-delivery" && value.requestId === pendingDeliveryRequest) {
+ await input.cursor.send({ kind: "turn-delivery-accepted", requestId: value.requestId });
+ pendingDeliveryRequest = undefined;
+
+ const remainder = await routeDeliverToChildren({
+ auth: value.delivery.auth,
+ parentWritable: input.cursor.parentWritable,
+ payloads: value.delivery.payloads,
+ sessionState: input.cursor.sessionState,
+ });
+ if (remainder !== undefined) {
+ input.bufferedDeliveries.push({ ...value.delivery, payloads: [remainder] });
+ }
+ }
+ }
+}
+
+async function runLegacyTurnWorkflow(input: TurnWorkflowInput): Promise<void> {
let currentStepInput: TurnStepInput = input.stepInput;
try {
@@ -41,8 +238,8 @@ export async function turnWorkflow(rawInput: unknown): Promise<void> {
const result = await turnStep(currentStepInput);
if (result.action === "done") {
- await notifyDriverStep({
- completionToken: input.completionToken,
+ await sendTurnControlStep({
+ controlToken: input.completionToken,
payload: {
action: {
kind: "done",
@@ -58,8 +255,8 @@ export async function turnWorkflow(rawInput: unknown): Promise<void> {
}
if (result.action === "dispatch-workflow-runtime-actions") {
- await notifyDriverStep({
- completionToken: input.completionToken,
+ await sendTurnControlStep({
+ controlToken: input.completionToken,
payload: {
action: {
kind: "dispatch-workflow-runtime-actions",
@@ -81,9 +278,7 @@ export async function turnWorkflow(rawInput: unknown): Promise<void> {
(result.hasPendingInputBatch && input.capabilities?.requestInput === true) ||
input.mode === "conversation";
- if (!canPark) {
- throw new Error(TASK_MODE_WAIT_ERROR_MESSAGE);
- }
+ if (!canPark) throw new Error(TASK_MODE_WAIT_ERROR_MESSAGE);
const action: NextDriverAction =
pendingActionKeys !== undefined
@@ -100,8 +295,8 @@ export async function turnWorkflow(rawInput: unknown): Promise<void> {
authorizationNames: result.authorizationNames,
};
- await notifyDriverStep({
- completionToken: input.completionToken,
+ await sendTurnControlStep({
+ controlToken: input.completionToken,
payload: { action, kind: "turn-result" },
});
return;
@@ -115,23 +310,10 @@ export async function turnWorkflow(rawInput: unknown): Promise<void> {
};
}
} catch (error) {
- await notifyDriverStep({
- completionToken: input.completionToken,
- payload: {
- error: normalizeSerializableError(error),
- kind: "turn-error",
- },
+ await sendTurnControlStep({
+ controlToken: input.completionToken,
+ payload: { error: normalizeSerializableError(error), kind: "turn-error" },
});
throw error;
}
}
-
-/** Resumes the driver's one-shot completion hook with the turn result. */
-export async function notifyDriverStep(input: {
- readonly completionToken: string;
- readonly payload: TurnCompletionPayload;
-}): Promise<void> {
- "use step";
-
- await resumeHook(input.completionToken, input.payload);
-}
diff --git a/packages/eve/src/execution/workflow-entry.test.ts b/packages/eve/src/execution/workflow-entry.test.ts
index e62773750..2536ac709 100644
--- a/packages/eve/src/execution/workflow-entry.test.ts
+++ b/packages/eve/src/execution/workflow-entry.test.ts
@@ -1,20 +1,15 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createHook } from "#compiled/@workflow/core/index.js";
+import { resumeHook } from "#internal/workflow/runtime.js";
import type { HookPayload } from "#channel/types.js";
import { ChannelRequestIdKey } from "#context/keys.js";
-import { getRuntimeActionRequestKey } from "#runtime/actions/keys.js";
-import type { RuntimeSubagentResultActionResult } from "#runtime/actions/types.js";
import { createSessionStep } from "#execution/create-session-step.js";
-import { dispatchRuntimeActionsStep } from "#execution/dispatch-runtime-actions-step.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
-import type { TurnCompletionPayload } from "#execution/turn-workflow.js";
+import type { TurnControlPayload } from "#execution/turn-control-protocol.js";
import { workflowEntry } from "#execution/workflow-entry.js";
-import {
- dispatchTurnStep,
- routeProxiedDeliverStep,
- runProxyInputRequestStep,
-} from "#execution/workflow-steps.js";
+import { routeDeliverToChildren } from "#execution/route-child-delivery.js";
+import { dispatchTurnStep } from "#execution/workflow-steps.js";
vi.mock("#compiled/@workflow/core/index.js", () => ({
createHook: vi.fn(),
@@ -45,27 +40,13 @@ vi.mock("./create-session-step.js", () => ({
),
}));
-vi.mock("./dispatch-runtime-actions-step.js", () => ({
- dispatchRuntimeActionsStep: vi
- .fn()
- .mockImplementation(async ({ sessionState }: { sessionState: DurableSessionState }) => ({
- results: [],
- sessionState,
- })),
+vi.mock("./route-child-delivery.js", () => ({
+ routeDeliverToChildren: vi.fn().mockImplementation(async ({ payloads }) => payloads[0]),
}));
vi.mock("./workflow-steps.js", () => ({
dispatchTurnStep: vi.fn().mockImplementation(async () => ({ runId: "turn-run" })),
emitTerminalSessionFailureStep: vi.fn().mockResolvedValue(undefined),
- routeProxiedDeliverStep: vi
- .fn()
- .mockImplementation(async ({ payload }) => ({ remainder: payload })),
- runProxyInputRequestStep: vi
- .fn()
- .mockImplementation(async ({ serializedContext, sessionState }) => ({
- serializedContext,
- sessionState,
- })),
}));
function createSessionStateForMock(
@@ -92,7 +73,7 @@ vi.mock("./session-callback-step.js", () => ({
fireSessionCallbackStep: vi.fn().mockResolvedValue(undefined),
}));
-interface ParkHookConfig {
+interface DeliveryHookConfig {
readonly dispose?: () => void;
readonly getConflict?: () => Promise<{ readonly runId: string } | null>;
readonly return?: () => Promise<IteratorResult<HookPayload>>;
@@ -116,8 +97,8 @@ describe("workflowEntry", () => {
const getConflict = vi.fn(async () => null);
vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));
installHookMocks({
- parkHooks: [{ getConflict, token: "http:test" }],
- turnCompletions: [
+ deliveryHooks: [{ getConflict, token: "http:test" }],
+ turnControls: [
turnResult({
action: "done",
output: "ok",
@@ -160,19 +141,19 @@ describe("workflowEntry", () => {
);
});
- it("fails a conflicting park hook before dispatching the first turn", async () => {
+ it("fails a conflicting delivery hook before dispatching the first turn", async () => {
const sessionState = createBaseSessionState();
const dispose = vi.fn();
vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));
installHookMocks({
- parkHooks: [
+ deliveryHooks: [
{
dispose,
getConflict: vi.fn(async () => ({ runId: "wrun_owner" })),
token: "http:test",
},
],
- turnCompletions: [],
+ turnControls: [],
});
await expect(
@@ -199,7 +180,7 @@ describe("workflowEntry", () => {
});
vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));
installHookMocks({
- parkHooks: [
+ deliveryHooks: [
{
dispose,
getConflict: vi.fn(async () => {
@@ -208,7 +189,7 @@ describe("workflowEntry", () => {
token: "http:test",
},
],
- turnCompletions: [],
+ turnControls: [],
});
await expect(
@@ -231,7 +212,7 @@ describe("workflowEntry", () => {
const sessionState = createBaseSessionState();
vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));
installHookMocks({
- turnCompletions: [turnResult({ action: "done", output: "ok", sessionState })],
+ turnControls: [turnResult({ action: "done", output: "ok", sessionState })],
});
await workflowEntry({
@@ -252,7 +233,7 @@ describe("workflowEntry", () => {
const sessionState = createBaseSessionState();
vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));
installHookMocks({
- parkHooks: [
+ deliveryHooks: [
{
token: "http:test",
values: [
@@ -264,7 +245,7 @@ describe("workflowEntry", () => {
],
},
],
- turnCompletions: [
+ turnControls: [
turnResult({ action: "park", sessionState }),
turnResult({ action: "done", output: "ok", sessionState }),
],
@@ -283,406 +264,141 @@ describe("workflowEntry", () => {
});
});
- it("buffers follow-up user input until a pending subagent batch resolves", async () => {
- const baseSessionState = createBaseSessionState();
- const pendingSessionState = createPendingSubagentSessionState("forecast_delegate");
- const resumedSessionState: DurableSessionState = {
- ...baseSessionState,
- };
+ it("supplies a requested public delivery to the active turn inbox", async () => {
+ const sessionState = createBaseSessionState();
+ vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));
- vi.mocked(createSessionStep).mockResolvedValue(
- createSessionStepResultForMock(baseSessionState),
- );
- installHookMocks({
- parkHooks: [
- {
- token: "http:test",
- values: [
- {
- kind: "deliver",
- payloads: [{ message: "follow up while child runs" }],
- },
- {
- kind: "runtime-action-result",
- results: [
- {
- callId: "call-1",
- kind: "subagent-result",
- output: "delegated output",
- subagentName: "forecast_delegate",
+ let acceptForward: (() => void) | undefined;
+ const forwarded = new Promise<void>((resolve) => {
+ acceptForward = resolve;
+ });
+ vi.mocked(resumeHook).mockImplementation(async (token) => {
+ if (token === "turn-inbox") acceptForward?.();
+ return { runId: "turn-run" } as never;
+ });
+
+ let completionIndex = 0;
+ vi.mocked(createHook).mockImplementation((options?: { readonly token?: string }) => {
+ const token = options?.token ?? "";
+ if (isTurnCompletionToken(token)) {
+ return createMockHook<TurnControlPayload>({
+ next: async () => {
+ completionIndex += 1;
+ if (completionIndex === 1) {
+ return {
+ done: false,
+ value: {
+ continuationToken: "http:test",
+ inboxToken: "turn-inbox",
+ kind: "turn-delivery-request",
+ requestId: "delivery-1",
},
- ],
- },
- ],
- },
- ],
- turnCompletions: [
- turnResult({
- action: "dispatch-runtime-actions",
- pendingActionKeys: subagentPendingActionKeys("forecast_delegate"),
- sessionState: pendingSessionState,
- }),
- turnResult({ action: "park", sessionState: resumedSessionState }),
- turnResult({
- action: "done",
- output: "after follow-up",
- sessionState: resumedSessionState,
- }),
- ],
- });
-
- const result = await workflowEntry({
- input: { message: "hello there" },
- serializedContext: createSerializedContext(),
- });
-
- expect(result).toEqual({ output: "after follow-up" });
- expect(turnCompletionTokens()).toEqual([
- "wrun_test_123:turn-completion:0",
- "wrun_test_123:turn-completion:1",
- "wrun_test_123:turn-completion:2",
- ]);
- const parentWritable = vi.mocked(dispatchTurnStep).mock.calls[0]?.[0].parentWritable;
- expect(dispatchRuntimeActionsStep).toHaveBeenCalledWith({
- callbackBaseUrl: "https://eve.example.com",
- parentWritable,
- serializedContext: expect.objectContaining({
- "eve.sessionId": "wrun_test_123",
- }),
- sessionState: pendingSessionState,
- });
- expect(vi.mocked(dispatchTurnStep).mock.calls[1]?.[0].delivery).toEqual({
- kind: "runtime-action-result",
- results: [
- {
- callId: "call-1",
- kind: "subagent-result",
- output: "delegated output",
- subagentName: "forecast_delegate",
- },
- ],
- });
- expect(vi.mocked(dispatchTurnStep).mock.calls[2]?.[0].delivery).toEqual({
- kind: "deliver",
- payloads: [{ message: "follow up while child runs" }],
- });
- });
-
- it("feeds immediate remote dispatch failures back into the parent turn", async () => {
- const baseSessionState = createBaseSessionState();
- const pendingSessionState = createPendingRemoteAgentSessionState("research");
- const resumedSessionState: DurableSessionState = {
- ...baseSessionState,
- };
- const failedResult = {
- callId: "call-1",
- isError: true,
- kind: "subagent-result",
- output: {
- code: "REMOTE_AGENT_START_FAILED",
- message: "remote unavailable",
- },
- subagentName: "research",
- } satisfies RuntimeSubagentResultActionResult;
-
- vi.mocked(createSessionStep).mockResolvedValue(
- createSessionStepResultForMock(baseSessionState),
- );
- vi.mocked(dispatchRuntimeActionsStep).mockResolvedValueOnce({
- results: [failedResult],
- sessionState: pendingSessionState,
- });
- installHookMocks({
- parkHooks: [
- {
- token: "http:test",
+ };
+ }
+ if (completionIndex === 2) {
+ await forwarded;
+ return {
+ done: false,
+ value: { kind: "turn-delivery-accepted", requestId: "delivery-1" },
+ };
+ }
+ return {
+ done: false,
+ value: turnResult({ action: "done", output: "finished", sessionState }),
+ };
+ },
+ token,
values: [],
- },
- ],
- turnCompletions: [
- turnResult({
- action: "dispatch-runtime-actions",
- pendingActionKeys: remoteAgentPendingActionKeys("research"),
- sessionState: pendingSessionState,
- }),
- turnResult({
- action: "done",
- output: "handled failure",
- sessionState: resumedSessionState,
- }),
- ],
+ }) as never;
+ }
+ if (token.endsWith(":auth")) {
+ return createMockHook({ token, values: [] }) as never;
+ }
+ return createMockHook({
+ token,
+ values: [
+ {
+ kind: "deliver",
+ payloads: [{ inputResponses: [{ optionId: "approve", requestId: "req-1" }] }],
+ },
+ ],
+ }) as never;
});
const result = await workflowEntry({
- input: { message: "hello there" },
+ input: { message: "delegate" },
serializedContext: createSerializedContext(),
});
- expect(result).toEqual({ output: "handled failure" });
- expect(vi.mocked(dispatchTurnStep).mock.calls[1]?.[0].delivery).toEqual({
- kind: "runtime-action-result",
- results: [failedResult],
- });
- });
-
- it("proxies a subagent input request through the parent writable while waiting for subagent results", async () => {
- const baseSessionState = createBaseSessionState();
- const pendingSessionState = createPendingSubagentSessionState("linear");
- const resumedSessionState: DurableSessionState = {
- ...baseSessionState,
- };
-
- vi.mocked(createSessionStep).mockResolvedValue(
- createSessionStepResultForMock(baseSessionState),
- );
- installHookMocks({
- parkHooks: [
- {
- token: "http:test",
- values: [
- createSubagentInputRequest(),
- {
- kind: "runtime-action-result",
- results: [
- {
- callId: "call-1",
- kind: "subagent-result",
- output: "child done",
- subagentName: "linear",
- },
- ],
- },
- ],
- },
- ],
- turnCompletions: [
- turnResult({
- action: "dispatch-runtime-actions",
- pendingActionKeys: subagentPendingActionKeys("linear"),
- sessionState: pendingSessionState,
- }),
- turnResult({ action: "done", output: "all done", sessionState: resumedSessionState }),
- ],
- });
-
- const result = await workflowEntry({
- input: { message: "hi" },
- serializedContext: createSerializedContext({
- "eve.capabilities": { requestInput: true },
- }),
- });
-
- expect(result).toEqual({ output: "all done" });
- expect(runProxyInputRequestStep).toHaveBeenCalledTimes(1);
- const parentWritable = vi.mocked(dispatchTurnStep).mock.calls[0]?.[0].parentWritable;
- const proxyCall = vi.mocked(runProxyInputRequestStep).mock.calls[0]?.[0];
- expect(proxyCall?.parentWritable).toBe(parentWritable);
- expect(proxyCall?.hookPayload.callId).toBe("call-1");
- expect(proxyCall?.hookPayload.childContinuationToken).toBe("subagent:wrun_test_123:call-1");
- expect(proxyCall?.hookPayload.event.requests[0]?.requestId).toBe("req-1");
- expect(vi.mocked(dispatchTurnStep).mock.calls[1]?.[0].delivery).toEqual({
- kind: "runtime-action-result",
- results: [
- {
- callId: "call-1",
- kind: "subagent-result",
- output: "child done",
- subagentName: "linear",
- },
- ],
- });
- expect(routeProxiedDeliverStep).not.toHaveBeenCalled();
- });
-
- it("rekeys the active hook when proxied subagent input anchors the parent session", async () => {
- const baseSessionState = createBaseSessionState({ continuationToken: "slack:C01:" });
- const pendingSessionState = createPendingSubagentSessionState("linear", {
- continuationToken: "slack:C01:",
- });
- const anchoredSessionState: DurableSessionState = {
- ...pendingSessionState,
- continuationToken: "slack:C01:1800000000.123456",
- };
- const resumedSessionState: DurableSessionState = {
- ...baseSessionState,
- continuationToken: "slack:C01:1800000000.123456",
- };
-
- vi.mocked(createSessionStep).mockResolvedValue(
- createSessionStepResultForMock(baseSessionState),
- );
- vi.mocked(runProxyInputRequestStep).mockResolvedValueOnce({
- serializedContext: {
- "eve.continuationToken": "slack:C01:1800000000.123456",
- "eve.sessionId": "wrun_test_123",
+ expect(result).toEqual({ output: "finished" });
+ expect(dispatchTurnStep).toHaveBeenCalledTimes(1);
+ expect(resumeHook).toHaveBeenCalledWith("turn-inbox", {
+ delivery: {
+ kind: "deliver",
+ payloads: [{ inputResponses: [{ optionId: "approve", requestId: "req-1" }] }],
},
- sessionState: anchoredSessionState,
- });
-
- const oldReturn = createIteratorReturn();
- const oldDispose = vi.fn();
- const newReturn = createIteratorReturn();
- const newDispose = vi.fn();
-
- installHookMocks({
- parkHooks: [
- {
- dispose: oldDispose,
- return: oldReturn,
- token: "slack:C01:",
- values: [createSubagentInputRequest()],
- },
- {
- dispose: newDispose,
- return: newReturn,
- token: "slack:C01:1800000000.123456",
- values: [
- {
- kind: "runtime-action-result",
- results: [
- {
- callId: "call-1",
- kind: "subagent-result",
- output: "child done",
- subagentName: "linear",
- },
- ],
- },
- ],
- },
- ],
- turnCompletions: [
- turnResult({
- action: "dispatch-runtime-actions",
- pendingActionKeys: subagentPendingActionKeys("linear"),
- sessionState: pendingSessionState,
- }),
- turnResult({
- action: "done",
- output: "done after rekey",
- sessionState: resumedSessionState,
- }),
- ],
+ kind: "driver-delivery",
+ requestId: "delivery-1",
});
-
- const result = await workflowEntry({
- input: { message: "hi" },
- serializedContext: createSerializedContext({
- "eve.capabilities": { requestInput: true },
- "eve.channel": { kind: "slack", state: {} },
- "eve.continuationToken": "slack:C01:",
- }),
- });
-
- expect(result).toEqual({ output: "done after rekey" });
- expect(nonTurnHookTokens()).toEqual(["slack:C01:", "slack:C01:1800000000.123456"]);
- expect(vi.mocked(dispatchTurnStep).mock.calls[1]?.[0].delivery).toEqual({
- kind: "runtime-action-result",
- results: [
- {
- callId: "call-1",
- kind: "subagent-result",
- output: "child done",
- subagentName: "linear",
- },
- ],
- });
- expect(oldReturn).toHaveBeenCalledTimes(1);
- expect(oldDispose).toHaveBeenCalledTimes(1);
- expect(newReturn).toHaveBeenCalledTimes(1);
- expect(newDispose).toHaveBeenCalledTimes(1);
});
- it("routes mid-wait HITL responses down to the child instead of buffering them", async () => {
- const baseSessionState = createBaseSessionState();
- const pendingSessionState = createPendingSubagentSessionState("linear");
- const resumedSessionState: DurableSessionState = {
- ...baseSessionState,
- };
- const userResponse = [{ optionId: "approve", requestId: "req-1", text: undefined }];
-
- vi.mocked(createSessionStep).mockResolvedValue(
- createSessionStepResultForMock(baseSessionState),
- );
- vi.mocked(runProxyInputRequestStep).mockImplementation(
- async ({ serializedContext, sessionState }) => ({
- serializedContext,
- sessionState: {
- ...sessionState,
- hasProxyInputRequests: true,
- },
- }),
- );
- vi.mocked(routeProxiedDeliverStep).mockResolvedValueOnce({ remainder: undefined });
+ it("preserves a public delivery when the active turn cancels its request", async () => {
+ const sessionState = createBaseSessionState();
+ vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));
- installHookMocks({
- parkHooks: [
- {
- token: "http:test",
+ vi.mocked(createHook).mockImplementation((options?: { readonly token?: string }) => {
+ const token = options?.token ?? "";
+ if (token.endsWith(":turn-control:0")) {
+ return createMockHook({
+ token,
values: [
- createSubagentInputRequest(),
{
- auth: null,
- kind: "deliver",
- payloads: [{ inputResponses: userResponse }],
- },
- {
- kind: "runtime-action-result",
- results: [
- {
- callId: "call-1",
- kind: "subagent-result",
- output: "child done",
- subagentName: "linear",
- },
- ],
+ continuationToken: "http:test",
+ inboxToken: "turn-inbox",
+ kind: "turn-delivery-request",
+ requestId: "delivery-1",
},
+ { kind: "turn-delivery-cancelled", requestId: "delivery-1" },
+ turnResult({ action: "park", sessionState }),
],
- },
- ],
- turnCompletions: [
- turnResult({
- action: "dispatch-runtime-actions",
- pendingActionKeys: subagentPendingActionKeys("linear"),
- sessionState: pendingSessionState,
- }),
- turnResult({
- action: "done",
- output: "finished after hitl",
- sessionState: resumedSessionState,
- }),
- ],
+ }) as never;
+ }
+ if (token.endsWith(":turn-control:1")) {
+ return createMockHook({
+ token,
+ values: [turnResult({ action: "done", output: "after delivery", sessionState })],
+ }) as never;
+ }
+ if (token.endsWith(":auth")) {
+ return createMockHook({ token, values: [] }) as never;
+ }
+ return createMockHook({
+ token,
+ values: [{ kind: "deliver", payloads: [{ message: "not for the child" }] }],
+ }) as never;
});
const result = await workflowEntry({
- input: { message: "hi" },
- serializedContext: createSerializedContext({
- "eve.capabilities": { requestInput: true },
- }),
+ input: { message: "delegate" },
+ serializedContext: createSerializedContext(),
});
- expect(result).toEqual({ output: "finished after hitl" });
- expect(routeProxiedDeliverStep).toHaveBeenCalledTimes(1);
- const routedCall = vi.mocked(routeProxiedDeliverStep).mock.calls[0]?.[0];
- expect(routedCall?.payload).toEqual({ inputResponses: userResponse });
+ expect(result).toEqual({ output: "after delivery" });
+ expect(dispatchTurnStep).toHaveBeenCalledTimes(2);
expect(vi.mocked(dispatchTurnStep).mock.calls[1]?.[0].delivery).toEqual({
- kind: "runtime-action-result",
- results: [
- {
- callId: "call-1",
- kind: "subagent-result",
- output: "child done",
- subagentName: "linear",
- },
- ],
+ auth: undefined,
+ kind: "deliver",
+ payloads: [{ message: "not for the child" }],
+ requestId: undefined,
});
+ expect(resumeHook).not.toHaveBeenCalled();
});
- it("skips the routing step when there are no proxy input requests on the session", async () => {
+ it("skips child routing when a turn completes without yielding to a delivery", async () => {
const sessionState = createBaseSessionState();
vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));
installHookMocks({
- turnCompletions: [
+ turnControls: [
turnResult({
action: "done",
output: "ok",
@@ -698,7 +414,7 @@ describe("workflowEntry", () => {
});
expect(result).toEqual({ output: "ok" });
- expect(routeProxiedDeliverStep).not.toHaveBeenCalled();
+ expect(routeDeliverToChildren).not.toHaveBeenCalled();
});
it("parks the first hook under the re-keyed continuation token", async () => {
@@ -717,7 +433,7 @@ describe("workflowEntry", () => {
const rekeyedReturn = createIteratorReturn();
const rekeyedDispose = vi.fn();
installHookMocks({
- parkHooks: [
+ deliveryHooks: [
{
dispose: initialDispose,
return: initialReturn,
@@ -731,7 +447,7 @@ describe("workflowEntry", () => {
values: [],
},
],
- turnCompletions: [turnResult({ action: "park", sessionState: rekeyedSessionState })],
+ turnControls: [turnResult({ action: "park", sessionState: rekeyedSessionState })],
});
const result = await workflowEntry({
@@ -745,13 +461,13 @@ describe("workflowEntry", () => {
expect(result).toEqual({ output: "" });
// Initial hook created before the turn, then rekeyed after.
expect(nonTurnHookTokens()).toEqual(["slack:C01:", "slack:C01:1800000000.123456"]);
- expect(initialReturn).toHaveBeenCalledTimes(1);
+ expect(initialReturn).not.toHaveBeenCalled();
expect(initialDispose).toHaveBeenCalledTimes(1);
- expect(rekeyedReturn).toHaveBeenCalledTimes(1);
+ expect(rekeyedReturn).not.toHaveBeenCalled();
expect(rekeyedDispose).toHaveBeenCalledTimes(1);
});
- it("defers the first park hook until an empty continuation token is anchored", async () => {
+ it("defers the first delivery hook until an empty continuation token is anchored", async () => {
const baseSessionState = createBaseSessionState({ continuationToken: "" });
const anchoredSessionState: DurableSessionState = {
...baseSessionState,
@@ -765,7 +481,7 @@ describe("workflowEntry", () => {
const anchoredReturn = createIteratorReturn();
const anchoredDispose = vi.fn();
installHookMocks({
- parkHooks: [
+ deliveryHooks: [
{
dispose: anchoredDispose,
return: anchoredReturn,
@@ -773,7 +489,7 @@ describe("workflowEntry", () => {
values: [],
},
],
- turnCompletions: [turnResult({ action: "park", sessionState: anchoredSessionState })],
+ turnControls: [turnResult({ action: "park", sessionState: anchoredSessionState })],
});
const result = await workflowEntry({
@@ -786,11 +502,11 @@ describe("workflowEntry", () => {
expect(result).toEqual({ output: "" });
expect(nonTurnHookTokens()).toEqual(["slack:C01:1800000000.123456"]);
- expect(anchoredReturn).toHaveBeenCalledTimes(1);
+ expect(anchoredReturn).not.toHaveBeenCalled();
expect(anchoredDispose).toHaveBeenCalledTimes(1);
});
- it("recreates the park hook when a later turn re-keys the session", async () => {
+ it("recreates the delivery hook when a later turn re-keys the session", async () => {
const baseSessionState = createBaseSessionState({ continuationToken: "slack:C01:" });
const rekeyedSessionState: DurableSessionState = {
...baseSessionState,
@@ -808,7 +524,7 @@ describe("workflowEntry", () => {
const newDispose = vi.fn();
const newGetConflict = vi.fn(async () => null);
installHookMocks({
- parkHooks: [
+ deliveryHooks: [
{
dispose: oldDispose,
getConflict: oldGetConflict,
@@ -829,7 +545,7 @@ describe("workflowEntry", () => {
values: [],
},
],
- turnCompletions: [
+ turnControls: [
turnResult({ action: "park", sessionState: baseSessionState }),
turnResult({ action: "park", sessionState: rekeyedSessionState }),
],
@@ -849,148 +565,17 @@ describe("workflowEntry", () => {
kind: "deliver",
payloads: [{ message: "follow up" }],
});
- expect(oldReturn).toHaveBeenCalledTimes(1);
+ expect(oldReturn).not.toHaveBeenCalled();
expect(oldDispose).toHaveBeenCalledTimes(1);
- expect(newReturn).toHaveBeenCalledTimes(1);
+ expect(newReturn).not.toHaveBeenCalled();
expect(newDispose).toHaveBeenCalledTimes(1);
expect(oldGetConflict).toHaveBeenCalledOnce();
expect(newGetConflict).toHaveBeenCalledOnce();
- expect(newGetConflict.mock.invocationCallOrder[0]).toBeLessThan(
- vi.mocked(oldReturn).mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
- );
expect(newGetConflict.mock.invocationCallOrder[0]).toBeLessThan(
oldDispose.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
);
});
- it.each(["iterator", "hook"] as const)(
- "cleans both hooks once when the old %s fails during rekey",
- async (failurePoint) => {
- const baseSessionState = createBaseSessionState({ continuationToken: "slack:C01:" });
- const rekeyedSessionState: DurableSessionState = {
- ...baseSessionState,
- continuationToken: "slack:C01:1800000000.123456",
- };
- const releaseError = new Error(`${failurePoint} release failed`);
- const oldReturn = vi.fn(async (): Promise<IteratorResult<HookPayload>> => {
- if (failurePoint === "iterator") throw releaseError;
- return { done: true, value: undefined };
- });
- const oldDispose = vi.fn(() => {
- if (failurePoint === "hook") throw releaseError;
- });
- const candidateDispose = vi.fn();
- const candidateGetConflict = vi.fn(async () => null);
- vi.mocked(createSessionStep).mockResolvedValue(
- createSessionStepResultForMock(baseSessionState),
- );
- installHookMocks({
- parkHooks: [
- {
- dispose: oldDispose,
- return: oldReturn,
- token: "slack:C01:",
- values: [
- {
- kind: "deliver",
- payloads: [{ message: "follow up" }],
- },
- ],
- },
- {
- dispose: candidateDispose,
- getConflict: candidateGetConflict,
- token: "slack:C01:1800000000.123456",
- },
- ],
- turnCompletions: [
- turnResult({ action: "park", sessionState: baseSessionState }),
- turnResult({ action: "park", sessionState: rekeyedSessionState }),
- ],
- });
-
- await expect(
- workflowEntry({
- input: { message: "hello" },
- serializedContext: createSerializedContext({
- "eve.channel": { kind: "slack", state: {} },
- "eve.continuationToken": "slack:C01:",
- }),
- }),
- ).rejects.toBe(releaseError);
-
- expect(candidateGetConflict).toHaveBeenCalledOnce();
- expect(oldReturn).toHaveBeenCalledOnce();
- expect(oldDispose).toHaveBeenCalledOnce();
- expect(candidateDispose).toHaveBeenCalledOnce();
- },
- );
-
- it("disposes a conflicting rekey candidate before cleaning up the active hook", async () => {
- const baseSessionState = createBaseSessionState({ continuationToken: "slack:C01:" });
- const rekeyedSessionState: DurableSessionState = {
- ...baseSessionState,
- continuationToken: "slack:C01:1800000000.123456",
- };
- vi.mocked(createSessionStep).mockResolvedValue(
- createSessionStepResultForMock(baseSessionState),
- );
-
- const oldReturn = createIteratorReturn();
- const oldDispose = vi.fn();
- const candidateDispose = vi.fn();
- const candidateGetConflict = vi.fn(async () => ({ runId: "wrun_owner" }));
- installHookMocks({
- parkHooks: [
- {
- dispose: oldDispose,
- return: oldReturn,
- token: "slack:C01:",
- values: [
- {
- kind: "deliver",
- payloads: [{ message: "follow up" }],
- },
- ],
- },
- {
- dispose: candidateDispose,
- getConflict: candidateGetConflict,
- token: "slack:C01:1800000000.123456",
- },
- ],
- turnCompletions: [
- turnResult({ action: "park", sessionState: baseSessionState }),
- turnResult({ action: "park", sessionState: rekeyedSessionState }),
- ],
- });
-
- await expect(
- workflowEntry({
- input: { message: "hello" },
- serializedContext: createSerializedContext({
- "eve.channel": { kind: "slack", state: {} },
- "eve.continuationToken": "slack:C01:",
- }),
- }),
- ).rejects.toMatchObject({
- conflictingRunId: "wrun_owner",
- name: "HookConflictError",
- token: "slack:C01:1800000000.123456",
- });
-
- expect(candidateGetConflict).toHaveBeenCalledOnce();
- expect(candidateDispose).toHaveBeenCalledOnce();
- expect(oldReturn).toHaveBeenCalledOnce();
- expect(oldDispose).toHaveBeenCalledOnce();
- expect(candidateDispose.mock.invocationCallOrder[0]).toBeLessThan(
- vi.mocked(oldReturn).mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
- );
- expect(candidateDispose.mock.invocationCallOrder[0]).toBeLessThan(
- oldDispose.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
- );
- });
-
it("disposes the workflow hook after the loop exits", async () => {
const sessionState = createBaseSessionState();
vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));
@@ -999,7 +584,7 @@ describe("workflowEntry", () => {
const symbolDispose = vi.fn();
const returnIterator = createIteratorReturn();
installHookMocks({
- parkHooks: [
+ deliveryHooks: [
{
dispose,
return: returnIterator,
@@ -1013,7 +598,7 @@ describe("workflowEntry", () => {
},
],
symbolDispose,
- turnCompletions: [
+ turnControls: [
turnResult({ action: "park", sessionState }),
turnResult({ action: "done", output: "after resume", sessionState }),
],
@@ -1025,7 +610,7 @@ describe("workflowEntry", () => {
});
expect(result).toEqual({ output: "after resume" });
- expect(returnIterator).toHaveBeenCalledTimes(1);
+ expect(returnIterator).not.toHaveBeenCalled();
expect(dispose).toHaveBeenCalledTimes(1);
expect(symbolDispose).not.toHaveBeenCalled();
});
@@ -1053,86 +638,12 @@ function createBaseSessionState(overrides: Partial<DurableSessionState> = {}): D
};
}
-function createPendingSubagentSessionState(
- _subagentName: string,
- overrides: Partial<DurableSessionState> = {},
-): DurableSessionState {
- return createBaseSessionState(overrides);
-}
-
-function createPendingRemoteAgentSessionState(
- _remoteAgentName: string,
- overrides: Partial<DurableSessionState> = {},
-): DurableSessionState {
- return createBaseSessionState(overrides);
-}
-
-function subagentPendingActionKeys(subagentName: string): readonly string[] {
- return [
- getRuntimeActionRequestKey({
- callId: "call-1",
- description: "Delegate the work.",
- input: { topic: subagentName },
- kind: "subagent-call",
- name: subagentName,
- nodeId: `subagents/${subagentName}`,
- subagentName,
- }),
- ];
-}
-
-function remoteAgentPendingActionKeys(remoteAgentName: string): readonly string[] {
- return [
- getRuntimeActionRequestKey({
- callId: "call-1",
- description: "Delegate the work.",
- input: { topic: remoteAgentName },
- kind: "remote-agent-call",
- name: remoteAgentName,
- nodeId: `remote/${remoteAgentName}`,
- remoteAgentName,
- }),
- ];
-}
-
-function createSubagentInputRequest(): HookPayload {
- return {
- callId: "call-1",
- childContinuationToken: "subagent:wrun_test_123:call-1",
- childSessionId: "child-session",
- event: {
- requests: [
- {
- action: {
- callId: "tool-call-1",
- input: {},
- kind: "tool-call",
- toolName: "dangerous_tool",
- },
- options: [
- { id: "approve", label: "Approve" },
- { id: "deny", label: "Deny" },
- ],
- prompt: "Approve?",
- requestId: "req-1",
- },
- ],
- sequence: 0,
- stepIndex: 0,
- turnId: "child-turn",
- },
- kind: "subagent-input-request",
- subagentName: "linear",
- };
-}
-
function turnResult(input: {
- readonly action: "done" | "park" | "dispatch-runtime-actions";
+ readonly action: "done" | "park";
readonly output?: string;
- readonly pendingActionKeys?: readonly string[];
readonly serializedContext?: Record<string, unknown>;
readonly sessionState: DurableSessionState;
-}): TurnCompletionPayload {
+}): TurnControlPayload {
const serializedContext = input.serializedContext ?? { "eve.sessionId": "wrun_test_123" };
if (input.action === "done") {
return {
@@ -1145,17 +656,6 @@ function turnResult(input: {
kind: "turn-result",
};
}
- if (input.action === "dispatch-runtime-actions") {
- return {
- action: {
- kind: "dispatch-runtime-actions",
- pendingActionKeys: input.pendingActionKeys ?? [],
- serializedContext,
- sessionState: input.sessionState,
- },
- kind: "turn-result",
- };
- }
return {
action: {
kind: "park",
@@ -1167,20 +667,20 @@ function turnResult(input: {
}
function installHookMocks(input: {
- readonly parkHooks?: readonly ParkHookConfig[];
+ readonly deliveryHooks?: readonly DeliveryHookConfig[];
readonly symbolDispose?: () => void;
- readonly turnCompletions: readonly TurnCompletionPayload[];
+ readonly turnControls: readonly TurnControlPayload[];
}): void {
- const turnCompletions = [...input.turnCompletions];
- const parkHooks = [...(input.parkHooks ?? [])];
+ const turnControls = [...input.turnControls];
+ const deliveryHooks = [...(input.deliveryHooks ?? [])];
vi.mocked(createHook).mockImplementation((options?: { readonly token?: string }) => {
const token = options?.token;
if (token === undefined || isTurnCompletionToken(token)) {
- const value = turnCompletions.shift();
+ const value = turnControls.shift();
return createMockHook({
- token: token ?? "turn-completion",
+ token: token ?? "turn-control",
values: value === undefined ? [] : [value],
}) as never;
}
@@ -1189,9 +689,9 @@ function installHookMocks(input: {
return createMockHook({ token, values: [] }) as never;
}
- const config = parkHooks.shift() ?? { token, values: [] };
+ const config = deliveryHooks.shift() ?? { token, values: [] };
if (config.token !== token) {
- throw new Error(`Expected park hook token "${config.token}", received "${token}".`);
+ throw new Error(`Expected delivery hook token "${config.token}", received "${token}".`);
}
return createMockHook({
@@ -1261,13 +761,6 @@ function nonTurnHookTokens(): string[] {
);
}
-function turnCompletionTokens(): string[] {
- return vi
- .mocked(createHook)
- .mock.calls.map((call) => call[0]?.token)
- .filter((token): token is string => token !== undefined && isTurnCompletionToken(token));
-}
-
function isTurnCompletionToken(token: string): boolean {
- return /:turn-completion:\d+$/.test(token);
+ return /:turn-control:\d+$/.test(token);
}
diff --git a/packages/eve/src/execution/workflow-entry.ts b/packages/eve/src/execution/workflow-entry.ts
index 2f4cdf3e8..dbc82e2aa 100644
--- a/packages/eve/src/execution/workflow-entry.ts
+++ b/packages/eve/src/execution/workflow-entry.ts
@@ -1,9 +1,4 @@
-import {
- createHook,
- getWorkflowMetadata,
- getWritable,
- type Hook,
-} from "#compiled/@workflow/core/index.js";
+import { createHook, getWorkflowMetadata, getWritable } from "#compiled/@workflow/core/index.js";
import type {
DeliverHookPayload,
@@ -14,11 +9,8 @@ import type {
} from "#channel/types.js";
import { coalesceDeliveries } from "#harness/messages.js";
import { readChannelRequestId, readRootSessionId } from "#execution/eve-workflow-attributes.js";
-import { accumulateRuntimeActionResults } from "#harness/runtime-actions.js";
import type { RunMode } from "#shared/run-mode.js";
-import type { RuntimeSubagentResultActionResult } from "#runtime/actions/types.js";
import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
-import type { InputResponse } from "#runtime/input/types.js";
import { notifyDelegatedParentStep } from "#execution/delegated-parent-notification.js";
import {
createDelegatedSubagentErrorResult,
@@ -26,23 +18,17 @@ import {
} from "#execution/delegated-parent-result.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
import type { NextDriverAction } from "#execution/next-driver-action.js";
-import type { TurnCompletionPayload } from "#execution/turn-workflow.js";
-import {
- normalizeSerializableError,
- rebuildSerializableError,
-} from "#execution/workflow-errors.js";
-import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";
+import { routeDeliverToChildren } from "#execution/route-child-delivery.js";
+import { dispatchAndAwaitTurn } from "#execution/turn-dispatch.js";
+import { normalizeSerializableError } from "#execution/workflow-errors.js";
import { createSessionStep } from "#execution/create-session-step.js";
-import { dispatchWorkflowRuntimeActionsStep } from "#execution/dispatch-workflow-runtime-actions-step.js";
-import { dispatchRuntimeActionsStep } from "#execution/dispatch-runtime-actions-step.js";
-import {
- dispatchTurnStep,
- emitTerminalSessionFailureStep,
- routeProxiedDeliverStep,
- runProxyInputRequestStep,
-} from "#execution/workflow-steps.js";
+import { emitTerminalSessionFailureStep } from "#execution/workflow-steps.js";
import { fireSessionCallbackStep } from "#execution/session-callback-step.js";
-import { claimHookOwnership, closeHookIterator, disposeHook } from "#execution/hook-ownership.js";
+import { closeHookIterator, disposeHook } from "#execution/hook-ownership.js";
+import {
+ createSessionDeliveryHook,
+ type SessionDeliveryHook,
+} from "#execution/session-delivery-hook.js";
// workflow-entry.ts is the durable workflow body — the bundler rejects
// node built-ins here, so `internal/logging.ts` cannot be imported.
@@ -69,10 +55,12 @@ export interface WorkflowEntryResult {
* on a child stream and resume the parked parent with a
* `subagent-result` on completion.
*
- * Dispatches on the closed-contract {@link NextDriverAction} returned
- * by each step. The only session-shape flag the driver reads (besides
- * identity) is `hasProxyInputRequests`, the documented short-circuit
- * for hook-payload routing.
+ * Owns the public delivery hook and the session lifecycle; each turn-owned
+ * turn resolves its own runtime actions in-line and reports back only
+ * `done`/`park` via the closed-contract {@link NextDriverAction}. The
+ * only session-shape flag the driver reads (besides identity) is
+ * `hasProxyInputRequests`, the documented short-circuit for hook-payload
+ * routing to any descendant still active when the parent parks.
*/
export async function workflowEntry(input: WorkflowEntryInput): Promise<WorkflowEntryResult> {
"use workflow";
@@ -165,251 +153,129 @@ async function runDriverLoop(input: {
});
const authIterator: AsyncIterator<HookPayload> = authHook[Symbol.asyncIterator]();
// Fast descendant resumes can start the next turn before the prior
- // completion hook disposal is persisted by the Workflow SDK, so each
+ // control hook disposal is persisted by the Workflow SDK, so each
// turn needs its own session-scoped token.
let turnDispatchIndex = 0;
- const nextTurnCompletionToken = (): string =>
- `${input.sessionState.sessionId}:turn-completion:${String(turnDispatchIndex++)}`;
-
- // Claim before the first turn when a placeholder token exists.
- // Tokenless channels must anchor during that turn before hook registration.
- let parkToken = "";
- let hook: Hook<HookPayload> | undefined;
- let iterator: AsyncIterator<HookPayload> | undefined;
- let pendingNext: Promise<IteratorResult<HookPayload>> | null = null;
- const bufferedDeliveries: DeliverHookPayload[] = [];
-
- const getNextPromise = (): Promise<IteratorResult<HookPayload>> => {
- if (iterator === undefined) {
- throw new Error("Cannot wait for deliveries before a continuation token is available.");
- }
-
- pendingNext ??= iterator.next();
- return pendingNext;
- };
-
- const consumeNext = (): void => {
- pendingNext = null;
- };
-
- /**
- * Stops accepting deliveries on the current park hook and releases its
- * token. In-flight deliveries to that token after this returns are dropped.
- */
- const closeParkHook = async (): Promise<void> => {
- const currentIterator = iterator;
- const currentHook = hook;
- hook = undefined;
- iterator = undefined;
- pendingNext = null;
-
- if (currentIterator !== undefined) {
- try {
- await closeHookIterator(currentIterator);
- } catch (error) {
- if (currentHook !== undefined) {
- try {
- await disposeHook(currentHook);
- } catch {
- // The iterator failure is authoritative; cleanup must not replace it.
- }
- }
- throw error;
- }
- }
- if (currentHook !== undefined) {
- await disposeHook(currentHook);
- }
- };
-
- const rekeyHook = async (nextToken: string): Promise<void> => {
- if (!nextToken || (hook !== undefined && nextToken === parkToken)) return;
-
- // Claim the replacement before releasing the current token. A failed
- // claim leaves the active hook intact until normal failure cleanup.
- const nextHook = createHook<HookPayload>({ token: nextToken });
- await claimHookOwnership(nextHook);
-
- try {
- await closeParkHook();
- } catch (error) {
- try {
- await disposeHook(nextHook);
- } catch {
- // The active hook release failure is authoritative.
- }
- throw error;
- }
+ const nextTurnControlToken = (): string =>
+ `${input.sessionState.sessionId}:turn-control:${String(turnDispatchIndex++)}`;
- parkToken = nextToken;
- hook = nextHook;
- iterator = nextHook[Symbol.asyncIterator]();
- pendingNext = null;
- };
+ const bufferedDeliveries: DeliverHookPayload[] = [];
+ const deliveryHook = createSessionDeliveryHook(bufferedDeliveries);
try {
if (input.sessionState.continuationToken) {
- await rekeyHook(input.sessionState.continuationToken);
+ await deliveryHook.rekey(input.sessionState.continuationToken);
}
let action: NextDriverAction = await dispatchAndAwaitTurn({
+ bufferedDeliveries,
capabilities: input.capabilities,
- completionToken: nextTurnCompletionToken(),
+ controlToken: nextTurnControlToken(),
delivery: input.initialInput,
+ deliveryHook,
mode: input.mode,
parentWritable: input.driverWritable,
serializedContext: input.serializedContext,
sessionState: input.sessionState,
});
- if (action.kind === "done") {
- return await finalizeDone({
- action,
- driverWritable: input.driverWritable,
- });
- }
+ while (true) {
+ if (action.kind === "done") {
+ return await finalizeDone({
+ action,
+ driverWritable: input.driverWritable,
+ });
+ }
- if (!action.sessionState.continuationToken) {
- throw new Error(
- "Cannot park: no continuation token available. The channel must " +
- "post the first message during the initial turn (anchoring the " +
- "session) or `send()` must be called with an explicit " +
- "continuationToken.",
- );
- }
+ if (action.kind !== "park") {
+ // Turn-owned turns resolve runtime actions in-line and only ever
+ // report `done`/`park`. The driver-owned `dispatch-*` arms exist
+ // solely for pre-change pinned drivers, which run their own code.
+ throw new Error(`Driver received unexpected turn action "${action.kind}".`);
+ }
- // Rekey if the first turn changed the continuation token.
- await rekeyHook(action.sessionState.continuationToken);
+ if (!action.sessionState.continuationToken) {
+ throw new Error(
+ "Cannot park: no continuation token available. The channel must " +
+ "post the first message during the initial turn (anchoring the " +
+ "session) or `send()` must be called with an explicit " +
+ "continuationToken.",
+ );
+ }
- while (true) {
- switch (action.kind) {
- case "done":
- return await finalizeDone({
- action,
- driverWritable: input.driverWritable,
- });
-
- case "dispatch-workflow-runtime-actions":
- case "dispatch-runtime-actions": {
- const dispatchStep =
- action.kind === "dispatch-workflow-runtime-actions"
- ? dispatchWorkflowRuntimeActionsStep
- : dispatchRuntimeActionsStep;
-
- const dispatchResult = await dispatchStep({
- callbackBaseUrl: resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url),
- parentWritable: input.driverWritable,
- serializedContext: action.serializedContext,
- sessionState: action.sessionState,
- });
-
- const runtimeResults = await waitForPendingRuntimeActionResults({
- bufferedDeliveries,
- consumeNext,
- getNextPromise,
- initialResults: dispatchResult.results,
- parentWritable: input.driverWritable,
- pendingActionKeys: action.pendingActionKeys,
- rekeyHook,
- serializedContext: action.serializedContext,
- sessionState: dispatchResult.sessionState,
- });
-
- if (runtimeResults === null) {
- return { output: "" };
- }
+ // Rekey to the parked turn's continuation token before awaiting the next
+ // delivery — covers both the first turn's anchor and any later rekey.
+ await deliveryHook.rekey(action.sessionState.continuationToken);
- action = await dispatchAndAwaitTurn({
- capabilities: input.capabilities,
- completionToken: nextTurnCompletionToken(),
- delivery: {
- kind: "runtime-action-result",
- results: runtimeResults.results,
- },
- mode: input.mode,
- parentWritable: input.driverWritable,
- serializedContext: runtimeResults.serializedContext,
- sessionState: runtimeResults.sessionState,
- });
-
- await rekeyHook(action.sessionState.continuationToken);
- break;
- }
+ if (action.authorizationNames && action.authorizationNames.length > 0) {
+ const expected = action.authorizationNames.length;
+ const allPayloads: DeliverPayload[] = [];
- case "park": {
- if (action.authorizationNames && action.authorizationNames.length > 0) {
- const expected = action.authorizationNames.length;
- const allPayloads: DeliverPayload[] = [];
-
- while (allPayloads.length < expected) {
- const next = await authIterator.next();
- if (next.done) break;
- if (next.value.kind === "deliver") {
- allPayloads.push(...next.value.payloads);
- }
- }
-
- action = await dispatchAndAwaitTurn({
- capabilities: input.capabilities,
- completionToken: nextTurnCompletionToken(),
- delivery: {
- kind: "deliver",
- payloads: allPayloads,
- },
- mode: input.mode,
- parentWritable: input.driverWritable,
- serializedContext: action.serializedContext,
- sessionState: action.sessionState,
- });
-
- await rekeyHook(action.sessionState.continuationToken);
- break;
+ while (allPayloads.length < expected) {
+ const next = await authIterator.next();
+ if (next.done) break;
+ if (next.value.kind === "deliver") {
+ allPayloads.push(...next.value.payloads);
}
+ }
- const nextDeliver = await waitForNextDeliver({
- bufferedDeliveries,
- consumeNext,
- getNextPromise,
- });
+ action = await dispatchAndAwaitTurn({
+ bufferedDeliveries,
+ capabilities: input.capabilities,
+ controlToken: nextTurnControlToken(),
+ delivery: {
+ kind: "deliver",
+ payloads: allPayloads,
+ },
+ deliveryHook,
+ mode: input.mode,
+ parentWritable: input.driverWritable,
+ serializedContext: action.serializedContext,
+ sessionState: action.sessionState,
+ });
+ continue;
+ }
- if (nextDeliver === null) {
- return { output: "" };
- }
+ const nextDeliver = await waitForNextDeliver({
+ bufferedDeliveries,
+ deliveryHook,
+ });
- const remainder = await routeDeliverForChildren({
- auth: nextDeliver.auth,
- parentWritable: input.driverWritable,
- payloads: nextDeliver.payloads,
- sessionState: action.sessionState,
- });
+ if (nextDeliver === null) {
+ return { output: "" };
+ }
- if (remainder === undefined) {
- // Fully routed to a descendant; parent has no turn to run.
- continue;
- }
+ const remainder = await routeDeliverToChildren({
+ auth: nextDeliver.auth,
+ parentWritable: input.driverWritable,
+ payloads: nextDeliver.payloads,
+ sessionState: action.sessionState,
+ });
- action = await dispatchAndAwaitTurn({
- capabilities: input.capabilities,
- completionToken: nextTurnCompletionToken(),
- delivery: {
- auth: nextDeliver.auth,
- kind: "deliver",
- payloads: [remainder],
- requestId: nextDeliver.requestId,
- },
- mode: input.mode,
- parentWritable: input.driverWritable,
- serializedContext: action.serializedContext,
- sessionState: action.sessionState,
- });
-
- await rekeyHook(action.sessionState.continuationToken);
- break;
- }
+ if (remainder === undefined) {
+ // Fully routed to a descendant; parent has no turn to run.
+ continue;
}
+
+ action = await dispatchAndAwaitTurn({
+ bufferedDeliveries,
+ capabilities: input.capabilities,
+ controlToken: nextTurnControlToken(),
+ delivery: {
+ auth: nextDeliver.auth,
+ kind: "deliver",
+ payloads: [remainder],
+ requestId: nextDeliver.requestId,
+ },
+ deliveryHook,
+ mode: input.mode,
+ parentWritable: input.driverWritable,
+ serializedContext: action.serializedContext,
+ sessionState: action.sessionState,
+ });
}
} finally {
- await closeParkHook();
+ await deliveryHook.dispose();
await closeHookIterator(authIterator);
await disposeHook(authHook);
}
@@ -437,181 +303,17 @@ async function finalizeDone(input: {
return { output };
}
-async function dispatchAndAwaitTurn(input: {
- readonly capabilities?: SessionCapabilities;
- readonly completionToken: string;
- readonly delivery: HookPayload;
- readonly mode: RunMode;
- readonly parentWritable: WritableStream<Uint8Array>;
- readonly serializedContext: Record<string, unknown>;
- readonly sessionState: DurableSessionState;
-}): Promise<NextDriverAction> {
- const completion = createHook<TurnCompletionPayload>({ token: input.completionToken });
- const completionToken = completion.token;
-
- try {
- await dispatchTurnStep({
- capabilities: input.capabilities,
- completionToken,
- delivery: input.delivery,
- mode: input.mode,
- parentWritable: input.parentWritable,
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- });
-
- const payload = await awaitHookPayload(completion);
-
- if (payload.kind === "turn-error") {
- throw rebuildSerializableError(payload.error);
- }
-
- return payload.action;
- } finally {
- await disposeHook(completion);
- }
-}
-
-async function awaitHookPayload<T>(hook: Hook<T>): Promise<T> {
- for await (const value of hook) {
- return value;
- }
- throw new Error("Turn completion hook closed before delivering a result.");
-}
-
-interface PendingRuntimeActionResultsOutcome {
- readonly results: readonly RuntimeSubagentResultActionResult[];
- readonly serializedContext: Record<string, unknown>;
- readonly sessionState: DurableSessionState;
-}
-
-async function waitForPendingRuntimeActionResults(input: {
- readonly bufferedDeliveries: DeliverHookPayload[];
- readonly consumeNext: () => void;
- readonly getNextPromise: () => Promise<IteratorResult<HookPayload>>;
- readonly initialResults?: readonly RuntimeSubagentResultActionResult[];
- readonly parentWritable: WritableStream<Uint8Array>;
- readonly pendingActionKeys: readonly string[];
- readonly rekeyHook: (nextToken: string) => Promise<void>;
- readonly serializedContext: Record<string, unknown>;
- readonly sessionState: DurableSessionState;
-}): Promise<PendingRuntimeActionResultsOutcome | null> {
- let currentSessionState = input.sessionState;
- // Thread the post-proxy serialized context forward so subsequent
- // deliveries and the post-wait `turnStep` observe adapter-state
- // mutations (e.g. Slack's `pendingRequests` cache).
- let currentSerializedContext = input.serializedContext;
-
- const results = await accumulateRuntimeActionResults({
- bufferedDeliveries: input.bufferedDeliveries,
- async getNext() {
- while (true) {
- const next = await input.getNextPromise();
- input.consumeNext();
-
- if (next.done) {
- return null;
- }
-
- const value = next.value;
-
- if (value.kind === "deliver") {
- // Route descendant-bound `inputResponses` down to the owning
- // child before buffering — otherwise the response would sit
- // in the buffer until the child completes, which it cannot
- // do without the response (parent↔child deadlock).
- const remainder = await routeDeliverForChildren({
- auth: value.auth,
- parentWritable: input.parentWritable,
- payloads: value.payloads,
- sessionState: currentSessionState,
- });
-
- if (remainder === undefined) {
- // Fully proxied; keep waiting.
- continue;
- }
-
- return {
- kind: "deliver",
- value: { ...value, payloads: [remainder] },
- };
- }
-
- if (value.kind === "runtime-action-result") {
- return { kind: "runtime-action-result", results: value.results };
- }
-
- // subagent-input-request: proxy the child's HITL through the
- // parent's adapter, record the routing entry, keep waiting.
- const proxyResult = await runProxyInputRequestStep({
- hookPayload: value,
- parentWritable: input.parentWritable,
- serializedContext: currentSerializedContext,
- sessionState: currentSessionState,
- });
- currentSessionState = proxyResult.sessionState;
- currentSerializedContext = proxyResult.serializedContext;
- await input.rekeyHook(currentSessionState.continuationToken);
- }
- },
- initialResults: input.initialResults,
- pendingActionKeys: input.pendingActionKeys,
- });
-
- if (results === null) {
- return null;
- }
-
- return {
- results: results as readonly RuntimeSubagentResultActionResult[],
- serializedContext: currentSerializedContext,
- sessionState: currentSessionState,
- };
-}
-
-/**
- * Routes one inbound deliver down to descendant subagents with
- * matching proxied HITL requests. Returns the parent-local remainder
- * (or `undefined` when the entire payload was routed away).
- *
- * Short-circuits via `hasProxyInputRequests` so the common
- * no-active-descendant path skips a durable step boundary.
- */
-async function routeDeliverForChildren(input: {
- readonly auth: DeliverHookPayload["auth"];
- readonly parentWritable: WritableStream<Uint8Array>;
- readonly payloads: readonly DeliverPayload[];
- readonly sessionState: DurableSessionState;
-}): Promise<DeliverPayload | undefined> {
- const coalesced = coalescePayloads(input.payloads);
-
- if (!input.sessionState.hasProxyInputRequests) {
- return coalesced;
- }
-
- const routed = await routeProxiedDeliverStep({
- auth: input.auth,
- parentWritable: input.parentWritable,
- payload: coalesced,
- sessionState: input.sessionState,
- });
-
- return routed.remainder;
-}
-
async function waitForNextDeliver(input: {
readonly bufferedDeliveries: DeliverHookPayload[];
- readonly consumeNext: () => void;
- readonly getNextPromise: () => Promise<IteratorResult<HookPayload>>;
+ readonly deliveryHook: SessionDeliveryHook;
}): Promise<DeliverHookPayload | null> {
if (input.bufferedDeliveries.length > 0) {
return coalesceDeliveries(input.bufferedDeliveries.splice(0));
}
while (true) {
- const first = await input.getNextPromise();
- input.consumeNext();
+ const first = await input.deliveryHook.next();
+ input.deliveryHook.consumeNext();
if (first.done) {
return null;
@@ -624,13 +326,13 @@ async function waitForNextDeliver(input: {
let coalesced = first.value;
while (true) {
- const ready = await takeReadyPayload(input.getNextPromise());
+ const ready = await takeReadyPayload(input.deliveryHook.next());
if (ready === NO_READY_MESSAGE) {
break;
}
- input.consumeNext();
+ input.deliveryHook.consumeNext();
if (ready.done) {
break;
@@ -647,41 +349,6 @@ async function waitForNextDeliver(input: {
}
}
-function coalescePayloads(payloads: readonly DeliverPayload[]): DeliverPayload {
- if (payloads.length === 0) {
- return {};
- }
-
- if (payloads.length === 1) {
- return payloads[0] ?? {};
- }
-
- const merged: Record<string, unknown> = {};
- const inputResponses: InputResponse[] = [];
-
- for (const payload of payloads) {
- for (const [key, value] of Object.entries(payload)) {
- if (key === "inputResponses") {
- continue;
- }
-
- if (value !== undefined) {
- merged[key] = value;
- }
- }
-
- if (payload.inputResponses !== undefined) {
- inputResponses.push(...payload.inputResponses);
- }
- }
-
- if (inputResponses.length > 0) {
- merged.inputResponses = inputResponses;
- }
-
- return merged as DeliverPayload;
-}
-
const NO_READY_MESSAGE = Symbol("no-ready-message");
async function takeReadyPayload<T>(promise: Promise<T>): Promise<T | typeof NO_READY_MESSAGE> {
diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.ts
index e31560a4c..1c41dc503 100644
--- a/packages/eve/src/execution/workflow-steps.test.ts
+++ b/packages/eve/src/execution/workflow-steps.test.ts
@@ -22,7 +22,6 @@ import {
import { createTurnWorkflowInput } from "#execution/durable-session-migrations/turn-workflow.js";
import { projectToDurableSession } from "#execution/session.js";
import { createExecutionNodeStep } from "#execution/node-step.js";
-import { turnWorkflow } from "#execution/turn-workflow.js";
import { dispatchRuntimeActionsStep } from "#execution/dispatch-runtime-actions-step.js";
import {
dispatchTurnStep,
@@ -33,6 +32,7 @@ import {
} from "#execution/workflow-steps.js";
import {
LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE,
+ turnWorkflowReference,
workflowEntryReference,
} from "#execution/workflow-runtime.js";
@@ -190,7 +190,7 @@ describe("dispatchTurnStep", () => {
return {
capabilities: undefined,
- completionToken: "turn-complete",
+ completionToken: "turn-control",
delivery: {
kind: "deliver",
payloads: [{ message: "hello" }],
@@ -210,16 +210,20 @@ describe("dispatchTurnStep", () => {
await expect(dispatchTurnStep(input)).resolves.toEqual({ runId: "turn-run" });
- expect(startMock).toHaveBeenCalledWith(turnWorkflow, [createTurnWorkflowInput(input)], {
- allowReservedAttributes: true,
- attributes: {
- "$eve.channel_request_id": "req_turn",
- "$eve.parent": "sess-test",
- "$eve.root": "sess-test",
- "$eve.type": "turn",
+ expect(startMock).toHaveBeenCalledWith(
+ turnWorkflowReference,
+ [createTurnWorkflowInput(input)],
+ {
+ allowReservedAttributes: true,
+ attributes: {
+ "$eve.channel_request_id": "req_turn",
+ "$eve.parent": "sess-test",
+ "$eve.root": "sess-test",
+ "$eve.type": "turn",
+ },
+ deploymentId: "latest",
},
- deploymentId: "latest",
- });
+ );
});
it("pins turn workflows to the current deployment off production", async () => {
@@ -230,15 +234,19 @@ describe("dispatchTurnStep", () => {
await expect(dispatchTurnStep(input)).resolves.toEqual({ runId: "turn-run" });
expect(startMock).toHaveBeenCalledTimes(1);
- expect(startMock).toHaveBeenCalledWith(turnWorkflow, [createTurnWorkflowInput(input)], {
- allowReservedAttributes: true,
- attributes: {
- "$eve.channel_request_id": "req_turn",
- "$eve.parent": "sess-test",
- "$eve.root": "sess-test",
- "$eve.type": "turn",
+ expect(startMock).toHaveBeenCalledWith(
+ turnWorkflowReference,
+ [createTurnWorkflowInput(input)],
+ {
+ allowReservedAttributes: true,
+ attributes: {
+ "$eve.channel_request_id": "req_turn",
+ "$eve.parent": "sess-test",
+ "$eve.root": "sess-test",
+ "$eve.type": "turn",
+ },
},
- });
+ );
});
it("falls back to the current deployment when latest is unsupported", async () => {
@@ -251,7 +259,7 @@ describe("dispatchTurnStep", () => {
await expect(dispatchTurnStep(input)).resolves.toEqual({ runId: "turn-run" });
const wireInput = createTurnWorkflowInput(input);
- expect(startMock).toHaveBeenNthCalledWith(1, turnWorkflow, [wireInput], {
+ expect(startMock).toHaveBeenNthCalledWith(1, turnWorkflowReference, [wireInput], {
allowReservedAttributes: true,
attributes: {
"$eve.channel_request_id": "req_turn",
@@ -261,7 +269,7 @@ describe("dispatchTurnStep", () => {
},
deploymentId: "latest",
});
- expect(startMock).toHaveBeenNthCalledWith(2, turnWorkflow, [wireInput], {
+ expect(startMock).toHaveBeenNthCalledWith(2, turnWorkflowReference, [wireInput], {
allowReservedAttributes: true,
attributes: {
"$eve.channel_request_id": "req_turn",
@@ -333,6 +341,7 @@ describe("dispatchRuntimeActionsStep", () => {
});
const result = await dispatchRuntimeActionsStep({
+ parentContinuationToken: "turn-inbox",
parentWritable: createTestWritable(),
serializedContext: createSerializedContext(),
sessionState,
@@ -347,7 +356,10 @@ describe("dispatchRuntimeActionsStep", () => {
message: expect.stringContaining("investigate latest routing"),
},
serializedContext: expect.objectContaining({
- "eve.channel": expect.objectContaining({ kind: "subagent" }),
+ "eve.channel": expect.objectContaining({
+ kind: "subagent",
+ state: expect.objectContaining({ parentContinuationToken: "turn-inbox" }),
+ }),
}),
}),
],
@@ -394,7 +406,8 @@ describe("dispatchRuntimeActionsStep", () => {
turnAgent: TestTurnAgent,
} as never;
vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(compiledBundle);
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(null, { status: 503 })));
+ const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 503 }));
+ vi.stubGlobal("fetch", fetchMock);
const session = setPendingRuntimeActionBatch({
actions: [
@@ -425,6 +438,7 @@ describe("dispatchRuntimeActionsStep", () => {
await expect(
dispatchRuntimeActionsStep({
callbackBaseUrl: "https://caller.example.com",
+ parentContinuationToken: "turn-inbox",
parentWritable: createTestWritable(),
serializedContext: createSerializedContext(),
sessionState,
@@ -446,6 +460,9 @@ describe("dispatchRuntimeActionsStep", () => {
// so the step returns the input sessionState unchanged.
sessionState,
});
+ expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string).callback.token).toBe(
+ "turn-inbox",
+ );
expect(workflowWritesByNamespace.get(DEFAULT_WORKFLOW_STREAM_NAMESPACE)).toBeUndefined();
});
});
diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.ts
index 9c69514e5..a0c56af94 100644
--- a/packages/eve/src/execution/workflow-steps.ts
+++ b/packages/eve/src/execution/workflow-steps.ts
@@ -61,8 +61,11 @@ import { emitProxiedInputRequest, routeDeliverPayload } from "#execution/subagen
import { hydrateDurableSession, refreshSessionFromTurnAgent } from "#execution/session.js";
import { buildTurnAttributes, readRootSessionId } from "#execution/eve-workflow-attributes.js";
import { normalizeEveAttributes } from "#runtime/attributes/normalize.js";
-import { turnWorkflow } from "#execution/turn-workflow.js";
-import { createWorkflowRuntime, startWorkflowPreferLatest } from "#execution/workflow-runtime.js";
+import {
+ createWorkflowRuntime,
+ startWorkflowPreferLatest,
+ turnWorkflowReference,
+} from "#execution/workflow-runtime.js";
import { resumeHook } from "#internal/workflow/runtime.js";
/**
@@ -640,16 +643,20 @@ export async function dispatchTurnStep(
): Promise<{ readonly runId: string }> {
"use step";
- const run = await startWorkflowPreferLatest(turnWorkflow, [createTurnWorkflowInput(input)], {
- allowReservedAttributes: true,
- attributes: normalizeEveAttributes(
- buildTurnAttributes({
- parentSessionId: input.sessionState.sessionId,
- requestId: input.delivery.kind === "deliver" ? input.delivery.requestId : undefined,
- rootSessionId: readRootSessionId(input.serializedContext) ?? input.sessionState.sessionId,
- }),
- ),
- });
+ const run = await startWorkflowPreferLatest(
+ turnWorkflowReference,
+ [createTurnWorkflowInput(input)],
+ {
+ allowReservedAttributes: true,
+ attributes: normalizeEveAttributes(
+ buildTurnAttributes({
+ parentSessionId: input.sessionState.sessionId,
+ requestId: input.delivery.kind === "deliver" ? input.delivery.requestId : undefined,
+ rootSessionId: readRootSessionId(input.serializedContext) ?? input.sessionState.sessionId,
+ }),
+ ),
+ },
+ );
return { runId: run.runId };
}
diff --git a/packages/eve/src/harness/runtime-actions.ts b/packages/eve/src/harness/runtime-actions.ts
index 833bd9032..c43d13df4 100644
--- a/packages/eve/src/harness/runtime-actions.ts
+++ b/packages/eve/src/harness/runtime-actions.ts
@@ -140,71 +140,6 @@ export function recordPendingSubagentChildToken(input: {
return { ...input.session, state };
}
-/**
- * Discriminated item consumed by {@link accumulateRuntimeActionResults}
- * so the loop can process interleaved deliveries and results without
- * coupling to a concrete `HookPayload` shape.
- */
-type RuntimeActionAccumulatorItem<TDeliver> =
- | { readonly kind: "deliver"; readonly value: TDeliver }
- | { readonly kind: "runtime-action-result"; readonly results: readonly RuntimeActionResult[] };
-
-/**
- * Accumulates runtime-action results until every pending key has a
- * matching result. The caller passes the ordered key list so the
- * workflow runtime can drive the loop without hydrating a session.
- */
-export async function accumulateRuntimeActionResults<TDeliver>(input: {
- readonly bufferedDeliveries: TDeliver[];
- readonly getNext: () => Promise<RuntimeActionAccumulatorItem<TDeliver> | null>;
- readonly initialResults?: readonly RuntimeActionResult[];
- readonly pendingActionKeys: readonly string[] | undefined;
-}): Promise<RuntimeActionResult[] | null> {
- const pendingKeys = input.pendingActionKeys;
- const buffered: RuntimeActionResult[] = [...(input.initialResults ?? [])];
-
- if (pendingKeys !== undefined && buffered.length > 0) {
- const ready = resolveRuntimeActionResultsForKeys({
- pendingKeys,
- results: buffered,
- });
-
- if (ready !== undefined) {
- return ready;
- }
- }
-
- while (true) {
- const item = await input.getNext();
-
- if (item === null) {
- return null;
- }
-
- if (item.kind === "deliver") {
- input.bufferedDeliveries.push(item.value);
- continue;
- }
-
- buffered.push(...item.results);
-
- if (pendingKeys === undefined) {
- // No pending batch; nothing to resolve. Keep draining so the
- // stream state stays consistent.
- continue;
- }
-
- const ready = resolveRuntimeActionResultsForKeys({
- pendingKeys,
- results: buffered,
- });
-
- if (ready !== undefined) {
- return ready;
- }
- }
-}
-
/**
* Returns the stable ordered runtime-action results for the current pending
* batch when every action has a matching result. Unknown and duplicate results
@@ -233,7 +168,8 @@ function resolveRuntimeActionResultsForBatch(input: {
});
}
-function resolveRuntimeActionResultsForKeys(input: {
+/** Returns results in pending-key order once every requested action has completed. */
+export function resolveRuntimeActionResultsForKeys(input: {
readonly pendingKeys: readonly string[];
readonly results: readonly RuntimeActionResult[];
}): RuntimeActionResult[] | undefined {
diff --git a/packages/eve/src/internal/testing/session-delivery-hook-workflow.ts b/packages/eve/src/internal/testing/session-delivery-hook-workflow.ts
new file mode 100644
index 000000000..7808b3990
--- /dev/null
+++ b/packages/eve/src/internal/testing/session-delivery-hook-workflow.ts
@@ -0,0 +1,55 @@
+import type { DeliverHookPayload, HookPayload } from "#channel/types.js";
+import {
+ createSessionDeliveryHook,
+ type SessionDeliveryHook,
+} from "#execution/session-delivery-hook.js";
+
+export async function sessionDeliveryHookWorkflow(input: {
+ readonly nextToken: string;
+ readonly token: string;
+}): Promise<string[]> {
+ "use workflow";
+
+ const bufferedDeliveries: DeliverHookPayload[] = [];
+ const deliveryHook = createSessionDeliveryHook(bufferedDeliveries);
+
+ try {
+ await deliveryHook.rekey(input.token);
+ const pendingDelivery = deliveryHook.next();
+ await deliveryHook.rekey(input.nextToken);
+
+ const messages: string[] = [];
+ collectMessages(await pendingDelivery, deliveryHook, messages);
+
+ while (messages.length < 2) {
+ const buffered = bufferedDeliveries.shift();
+ if (buffered !== undefined) {
+ appendMessages(buffered, messages);
+ continue;
+ }
+
+ collectMessages(await deliveryHook.next(), deliveryHook, messages);
+ }
+
+ return messages;
+ } finally {
+ await deliveryHook.dispose();
+ }
+}
+
+function collectMessages(
+ result: IteratorResult<HookPayload>,
+ deliveryHook: SessionDeliveryHook,
+ messages: string[],
+): void {
+ deliveryHook.consumeNext();
+ if (!result.done && result.value.kind === "deliver") {
+ appendMessages(result.value, messages);
+ }
+}
+
+function appendMessages(delivery: DeliverHookPayload, messages: string[]): void {
+ for (const payload of delivery.payloads) {
+ if (typeof payload.message === "string") messages.push(payload.message);
+ }
+}
diff --git a/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts b/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts
index d06a460af..20624bb35 100644
--- a/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts
+++ b/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts
@@ -1,9 +1,28 @@
import { describe, expect, it } from "vitest";
+import { resolvePackageRoot, resolvePackageSourceFilePath } from "#internal/application/package.js";
+
import { applyWorkflowTransform } from "./workflow-builders.js";
import { transformWorkflowDirectives } from "./workflow-transformer.js";
describe("applyWorkflowTransform", () => {
+ it("keeps eve workflow references stable when eve is the project root", async () => {
+ const filename = "src/execution/turn-workflow.ts";
+ const transformed = await applyWorkflowTransform(
+ filename,
+ ["export async function turnWorkflow(): Promise<void> {", ' "use workflow";', "}", ""].join(
+ "\n",
+ ),
+ "workflow",
+ resolvePackageSourceFilePath(filename),
+ resolvePackageRoot(),
+ );
+
+ expect(transformed.workflowManifest.workflows?.[filename]?.turnWorkflow).toEqual({
+ workflowId: "workflow//eve//turnWorkflow",
+ });
+ });
+
it("registers step functions in step mode", async () => {
const transformed = await applyWorkflowTransform(
"steps/ping.ts",
@@ -80,16 +99,16 @@ describe("applyWorkflowTransform", () => {
workflows: {
"src/execution/workflow-entry.ts": {
workflowEntry: {
- workflowId: "workflow//./src/execution/workflow-entry//workflowEntry",
+ workflowId: "workflow//eve//workflowEntry",
},
},
},
});
expect(transformed.code).toContain(
- 'workflowEntry.workflowId = "workflow//./src/execution/workflow-entry//workflowEntry";',
+ 'workflowEntry.workflowId = "workflow//eve//workflowEntry";',
);
expect(transformed.code).toContain(
- 'globalThis.__private_workflows.set("workflow//./src/execution/workflow-entry//workflowEntry", workflowEntry);',
+ 'globalThis.__private_workflows.set("workflow//eve//workflowEntry", workflowEntry);',
);
});
@@ -128,7 +147,7 @@ describe("applyWorkflowTransform", () => {
workflows: {
"src/execution/workflow-entry.ts": {
workflowEntry: {
- workflowId: "workflow//./src/execution/workflow-entry//workflowEntry",
+ workflowId: "workflow//eve//workflowEntry",
},
},
},
diff --git a/packages/eve/src/internal/workflow-bundle/workflow-builders.ts b/packages/eve/src/internal/workflow-bundle/workflow-builders.ts
index 547a4be37..dc87d84c8 100644
--- a/packages/eve/src/internal/workflow-bundle/workflow-builders.ts
+++ b/packages/eve/src/internal/workflow-bundle/workflow-builders.ts
@@ -3,6 +3,7 @@ import { readFile } from "node:fs/promises";
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
import { STABLE_WORKFLOW_NAMES } from "#execution/workflow-runtime.js";
+import { EVE_PACKAGE_NAME } from "#internal/package-name.js";
import { EVE_WORKFLOW_QUEUE_TOPIC } from "#internal/workflow/queue-namespace.js";
import { transformWorkflowDirectives } from "./workflow-transformer.js";
@@ -144,13 +145,15 @@ function resolveModuleSpecifier(
} {
const inNodeModules = isInNodeModules(filePath);
const inWorkspace = !inNodeModules && isWorkspacePackage(filePath, projectRoot);
+ const pkg = findPackageJson(filePath);
if (!inNodeModules && !inWorkspace) {
- return { moduleSpecifier: undefined, stableModuleSpecifier: undefined };
+ return {
+ moduleSpecifier: undefined,
+ stableModuleSpecifier: pkg?.name === EVE_PACKAGE_NAME ? EVE_PACKAGE_NAME : undefined,
+ };
}
- const pkg = findPackageJson(filePath);
-
if (pkg === null) {
return { moduleSpecifier: undefined, stableModuleSpecifier: undefined };
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index ee4bbab74..2181c3c2f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -736,6 +736,31 @@ importers:
specifier: 'catalog:'
version: 7.0.1-rc
+ e2e/fixtures/agent-workflow-stress:
+ dependencies:
+ '@opentelemetry/core':
+ specifier: 2.6.1
+ version: 2.6.1(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace-base':
+ specifier: 2.6.1
+ version: 2.6.1(@opentelemetry/[email protected])
+ '@vercel/otel':
+ specifier: 2.1.2
+ version: 2.1.2(@opentelemetry/[email protected])(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))
+ ai:
+ specifier: 'catalog:'
+ version: 7.0.0([email protected])
+ eve:
+ specifier: workspace:*
+ version: link:../../../packages/eve
+ devDependencies:
+ '@types/node':
+ specifier: 'catalog:'
+ version: 25.9.1
+ typescript:
+ specifier: 'catalog:'
+ version: 7.0.1-rc
+
packages/eve:
dependencies:
'@opentelemetry/api':