Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

perf(eve): start workflow tools and their agents sooner (#4687)

Andrew Barba4ef1ad9354ee
diff --git a/.changeset/faster-workflow-tool-agents.md b/.changeset/faster-workflow-tool-agents.md
new file mode 100644
index 000000000..820eb75f3
--- /dev/null
+++ b/.changeset/faster-workflow-tool-agents.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Workflow tools and the agents they open start faster. Tasks begin work sooner, `ctx.agent().send()` no longer waits for the agent's session to boot, a model step that starts several workflow tool runs starts them in parallel, and a fan-out's agent starts, progress, and results reach the session in batches instead of one at a time.
diff --git a/packages/eve/src/execution/agent-sessions/session.ts b/packages/eve/src/execution/agent-sessions/session.ts
index b43ae9fbf..0d1da8eac 100644
--- a/packages/eve/src/execution/agent-sessions/session.ts
+++ b/packages/eve/src/execution/agent-sessions/session.ts
@@ -111,6 +111,9 @@ class RunAgentSession implements AgentSession {
const outputSchema = normalizeRequestedOutputSchema(
serializeOutputSchema(options.outputSchema),
);
+ // Unlike hooks the session can answer at once, this one isn't registered
+ // before its token goes out: the child resumes it only after booting and
+ // finishing a turn, long after this suspension writes the hook.
const reply = this.#awaitReply(outputSchema !== undefined);
try {
await this.#deliver({
diff --git a/packages/eve/src/execution/agent-sessions/steps.test.ts b/packages/eve/src/execution/agent-sessions/steps.test.ts
new file mode 100644
index 000000000..b9b5e436b
--- /dev/null
+++ b/packages/eve/src/execution/agent-sessions/steps.test.ts
@@ -0,0 +1,176 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";
+import type { AgentSessionContext } from "#execution/agent-sessions/context.js";
+import {
+ cancelAgentSessionTurnStep,
+ endAgentSessionsStep,
+ openAgentSessionStep,
+ sendAgentSessionMessageStep,
+} from "#execution/agent-sessions/steps.js";
+
+const mocks = vi.hoisted(() => ({
+ attempt: 1,
+ createSession: vi.fn(),
+ dispatch: vi.fn(),
+ resolveSessionInbox: vi.fn(),
+ waitForCommandHookOwner: vi.fn(),
+ waitForSessionInbox: vi.fn(),
+}));
+
+vi.mock("#compiled/@workflow/core/index.js", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("#compiled/@workflow/core/index.js")>()),
+ getStepMetadata: () => ({ attempt: mocks.attempt }),
+}));
+vi.mock("#execution/workflow-runtime.js", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("#execution/workflow-runtime.js")>()),
+ createWorkflowRuntime: () => ({ createSession: mocks.createSession }),
+ dispatchWorkflowSessionCommand: mocks.dispatch,
+ waitForCommandHookOwner: mocks.waitForCommandHookOwner,
+ waitForSessionInbox: mocks.waitForSessionInbox,
+}));
+vi.mock("#execution/session-inbox/resume.js", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("#execution/session-inbox/resume.js")>()),
+ resolveSessionInbox: mocks.resolveSessionInbox,
+}));
+vi.mock("#runtime/sessions/compiled-agent-cache.js", () => ({
+ getCompiledRuntimeAgentBundle: async () => ({ graph: {} }),
+}));
+vi.mock("#runtime/durable-compiled-artifacts-source.js", () => ({
+ resolveDurableCompiledArtifactsSource: (source: unknown) => source,
+}));
+vi.mock("#execution/agent-sessions/target.js", () => {
+ const action = { callId: "call-1", name: "reviewer", nodeId: "reviewer" };
+ return {
+ resolveAgentAction: () => action,
+ resolveAgentStartTarget: () => ({ action, kind: "local", source: { type: "declared" } }),
+ };
+});
+vi.mock("#subagents/tool.js", () => ({
+ buildSubagentRunInput: (input: { readonly continuationKey: string }) => ({
+ childContinuationToken: `subagent:${input.continuationKey}`,
+ runInput: {},
+ }),
+}));
+
+const context = {
+ bundle: { source: {} },
+ dynamicSelections: {},
+ parent: { callId: "call-1", rootSessionId: "parent-1", sessionId: "parent-1" },
+ sandbox: {},
+ trace: {},
+} as AgentSessionContext;
+
+const session = {
+ address: {
+ continuationToken: "child-continuation",
+ kind: "local",
+ name: "reviewer",
+ nodeId: "reviewer",
+ sessionId: "child-1",
+ },
+ context,
+ key: "run-1:0",
+} as const;
+
+const message = {
+ ...session,
+ auth: { current: null, initiator: null },
+ message: "Bob asks for a second look at the plan.",
+ replyTo: "reply-1",
+} as const;
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.attempt = 1;
+});
+
+describe("openAgentSessionStep", () => {
+ const open = () => openAgentSessionStep({ ...message, name: "reviewer" });
+
+ it("returns the session it started without waiting for the session to boot", async () => {
+ mocks.createSession.mockResolvedValue({ sessionId: "child-1" });
+
+ await expect(open()).resolves.toEqual({
+ continuationToken: "subagent:run-1:0",
+ kind: "local",
+ name: "reviewer",
+ nodeId: "reviewer",
+ sessionId: "child-1",
+ });
+ expect(mocks.waitForCommandHookOwner).not.toHaveBeenCalled();
+ });
+
+ it("returns the run that claimed the session when a retried attempt may have started two", async () => {
+ mocks.attempt = 2;
+ mocks.createSession.mockResolvedValue({ sessionId: "child-2" });
+ mocks.waitForCommandHookOwner.mockResolvedValue({ runId: "child-1" });
+
+ await expect(open()).resolves.toMatchObject({ sessionId: "child-1" });
+ expect(mocks.waitForCommandHookOwner).toHaveBeenCalledWith(
+ expect.stringContaining("subagent:run-1:0"),
+ );
+ });
+});
+
+describe("commands to a session that opened without waiting", () => {
+ it.each([
+ {
+ command: "send",
+ refused: { status: "session_not_active" },
+ delivered: { sessionId: "child-1", status: "accepted" },
+ run: () => sendAgentSessionMessageStep(message),
+ },
+ {
+ command: "cancel",
+ refused: { status: "no_active_turn" },
+ delivered: { sessionId: "child-1", status: "accepted" },
+ run: () => cancelAgentSessionTurnStep(session),
+ },
+ {
+ command: "reset",
+ refused: { status: "no_active_session" },
+ delivered: { previousSessionId: "child-1", status: "reset" },
+ run: () => endAgentSessionsStep({ sessions: [session] }),
+ },
+ ])("delivers $command once the session claims its inbox", async (step) => {
+ mocks.dispatch.mockResolvedValueOnce(step.refused).mockResolvedValueOnce(step.delivered);
+ mocks.waitForSessionInbox.mockResolvedValue(true);
+
+ await step.run();
+
+ expect(mocks.waitForSessionInbox).toHaveBeenCalledWith("child-1");
+ expect(mocks.dispatch).toHaveBeenCalledTimes(2);
+ expect(mocks.dispatch).toHaveBeenLastCalledWith({
+ command: expect.objectContaining({ kind: step.command }),
+ sessionId: "child-1",
+ });
+ });
+
+ it("delivers to the session a duplicate start claimed when the recorded run lost it", async () => {
+ mocks.dispatch.mockResolvedValueOnce({ status: "session_not_active" }).mockResolvedValueOnce({
+ sessionId: "child-2",
+ status: "accepted",
+ });
+ mocks.waitForSessionInbox.mockResolvedValue(false);
+ mocks.resolveSessionInbox.mockResolvedValue({ sessionId: "child-2" });
+
+ await sendAgentSessionMessageStep(message);
+
+ expect(mocks.resolveSessionInbox).toHaveBeenCalledWith("child-continuation");
+ expect(mocks.dispatch).toHaveBeenLastCalledWith(
+ expect.objectContaining({ sessionId: "child-2" }),
+ );
+ });
+
+ it("fails a message to a session that ended", async () => {
+ mocks.dispatch.mockResolvedValue({ status: "session_not_active" });
+ mocks.waitForSessionInbox.mockResolvedValue(false);
+ mocks.resolveSessionInbox.mockRejectedValue(new HookNotFoundError("child-continuation"));
+
+ await expect(sendAgentSessionMessageStep(message)).rejects.toThrow(
+ 'Agent "reviewer" can no longer receive messages; its session ended.',
+ );
+ expect(mocks.dispatch).toHaveBeenCalledOnce();
+ });
+});
diff --git a/packages/eve/src/execution/agent-sessions/steps.ts b/packages/eve/src/execution/agent-sessions/steps.ts
index 795d54eb5..f4e293dda 100644
--- a/packages/eve/src/execution/agent-sessions/steps.ts
+++ b/packages/eve/src/execution/agent-sessions/steps.ts
@@ -1,4 +1,4 @@
-import { getWorkflowMetadata } from "#compiled/@workflow/core/index.js";
+import { getStepMetadata, getWorkflowMetadata } from "#compiled/@workflow/core/index.js";
import { SessionStrandedError } from "#channel/session-stranded-error.js";
import { ContextContainer, contextStorage } from "#context/container.js";
import type { SessionAuth } from "#context/session-context.js";
@@ -16,9 +16,11 @@ import {
import {
createWorkflowRuntime,
dispatchWorkflowSessionCommand,
- requestWorkflowTurnCancellation,
waitForCommandHookOwner,
+ resolveContinuation,
+ waitForSessionInbox,
} from "#execution/workflow-runtime.js";
+import type { SessionCommand, SessionCommandResult } from "#channel/types.js";
import { createLogger, logError } from "#internal/logging.js";
import { createEveCallbackRoutePath } from "#protocol/routes.js";
import { resolveDurableCompiledArtifactsSource } from "#runtime/durable-compiled-artifacts-source.js";
@@ -49,6 +51,8 @@ export type AgentSessionAddress =
readonly name: string;
readonly nodeId: string;
readonly sessionId: string;
+ /** Names the session to whichever run holds its inbox. */
+ readonly continuationToken: string;
}
| {
readonly callbackBaseUrl: string;
@@ -147,8 +151,9 @@ export async function sendAgentSessionMessageStep(
});
return;
}
- const result = await dispatchWorkflowSessionCommand({
- command: {
+ const result = await commandLocalSession(
+ { ...input, address },
+ {
auth: input.auth.current,
schedule: context.schedule,
caller: {
@@ -159,8 +164,7 @@ export async function sendAgentSessionMessageStep(
kind: "send",
payload: { message: input.message, outputSchema: input.outputSchema },
},
- sessionId: address.sessionId,
- }).catch((error: unknown) => {
+ ).catch((error: unknown) => {
if (!SessionStrandedError.is(error)) throw error;
throw new Error(`Agent "${address.name}" can no longer receive messages: ${error.message}`, {
cause: error,
@@ -182,7 +186,7 @@ export async function cancelAgentSessionTurnStep(input: OpenedAgentSession): Pro
await cancelRemoteAgentTurn({ remote, sessionId: address.sessionId });
return;
}
- await requestWorkflowTurnCancellation({ sessionId: address.sessionId });
+ await commandLocalSession({ ...input, address }, { kind: "cancel" });
} catch (error) {
logError(log, "failed to cancel an agent session turn", error, {
name: address.name,
@@ -200,7 +204,8 @@ export async function endAgentSessionsStep(input: {
await Promise.all(input.sessions.map(endAgentSession));
}
-async function endAgentSession({ address, context }: OpenedAgentSession): Promise<void> {
+async function endAgentSession(opened: OpenedAgentSession): Promise<void> {
+ const { address, context } = opened;
try {
if (address.kind === "remote") {
const remote = await resolveSessionRemote(context, address);
@@ -211,10 +216,10 @@ async function endAgentSession({ address, context }: OpenedAgentSession): Promis
});
return;
}
- await dispatchWorkflowSessionCommand({
- command: { kind: "reset", reason: RUN_FINISHED_REASON },
- sessionId: address.sessionId,
- });
+ await commandLocalSession(
+ { ...opened, address },
+ { kind: "reset", reason: RUN_FINISHED_REASON },
+ );
} catch (error) {
logError(log, "failed to end an agent session", error, {
name: address.name,
@@ -223,6 +228,30 @@ async function endAgentSession({ address, context }: OpenedAgentSession): Promis
}
}
+type LocalAgentSession = OpenedAgentSession & {
+ readonly address: Extract<AgentSessionAddress, { readonly kind: "local" }>;
+};
+
+/**
+ * Sends a command to a local session. A session opens without waiting for its
+ * run to claim its inbox, so a command it refuses before then waits for it.
+ * A duplicate start of the session can claim it instead of the run the open
+ * recorded, and the command then goes to the session holding its continuation.
+ */
+async function commandLocalSession<TCommand extends SessionCommand>(
+ opened: LocalAgentSession,
+ command: TCommand,
+): Promise<SessionCommandResult<TCommand>> {
+ const { continuationToken, sessionId } = opened.address;
+ const result = await dispatchWorkflowSessionCommand({ command, sessionId });
+ if (result.status === "accepted" || result.status === "reset") return result;
+ const current = (await waitForSessionInbox(sessionId))
+ ? sessionId
+ : (await resolveContinuation(continuationToken))?.sessionId;
+ if (current === undefined) return result;
+ return await dispatchWorkflowSessionCommand({ command, sessionId: current });
+}
+
interface SessionStart<Target extends SubagentStartTarget> {
readonly auth: SessionAuth;
readonly bundle: CompiledBundle;
@@ -270,14 +299,30 @@ async function startLocalSession(
agentPath: stubToolPath(childToolStubs, action.name),
};
}
- await contextStorage.run(new ContextContainer({ localDevRequest: context.localDevRequest }), () =>
- childRuntime.createSession({
- ...runInput,
- toolStubs: childToolStubs,
- }),
+ const started = await contextStorage.run(
+ new ContextContainer({ localDevRequest: context.localDevRequest }),
+ () =>
+ childRuntime.createSession({
+ ...runInput,
+ toolStubs: childToolStubs,
+ }),
);
- const owner = await waitForCommandHookOwner(sessionInboxHookToken(childContinuationToken));
- return { kind: "local", name: action.name, nodeId: action.nodeId, sessionId: owner.runId };
+ // Waiting for the run to claim the session would hold the caller for the
+ // child's boot. A retried attempt may have started a second run, so it waits
+ // to learn which run claimed the session; later commands resolve it again.
+ let sessionId = started.sessionId;
+ if (getStepMetadata().attempt > 1) {
+ ({ runId: sessionId } = await waitForCommandHookOwner(
+ sessionInboxHookToken(childContinuationToken),
+ ));
+ }
+ return {
+ continuationToken: childContinuationToken,
+ kind: "local",
+ name: action.name,
+ nodeId: action.nodeId,
+ sessionId,
+ };
}
async function startRemoteSession(
diff --git a/packages/eve/src/execution/coordination-dispatch-step.ts b/packages/eve/src/execution/coordination-dispatch-step.ts
index 8921530ae..86dabb255 100644
--- a/packages/eve/src/execution/coordination-dispatch-step.ts
+++ b/packages/eve/src/execution/coordination-dispatch-step.ts
@@ -11,8 +11,18 @@ import {
withSessionStateDelta,
type WithSessionStateDelta,
} from "#execution/session/state-delta.js";
-import { startWorkflowTask, type StartWorkflowTaskInput } from "#execution/tools/workflow/start.js";
-import { sendToTask, startTaskRun } from "#execution/tasks/start.js";
+import {
+ startWorkflowTask,
+ startWorkflowToolCallRun,
+ type StartWorkflowTaskInput,
+} from "#execution/tools/workflow/start.js";
+import {
+ runEntryToStart,
+ sendToTask,
+ startsEveryRun,
+ startTaskRun,
+} from "#execution/tasks/start.js";
+import { readTaskTable, type TaskTable } from "#execution/tasks/table.js";
import {
captureAgentSessionContext,
resolveStepAgentLimits,
@@ -56,8 +66,8 @@ async function dispatchCoordination(
const started: TaskStartedStreamEvent["data"][] = [];
const agentLimits = resolveStepAgentLimits(prepared);
- for (const task of prepared.plan) {
- const start = {
+ const starts = withPrestartedRuns(
+ prepared.plan.map((task) => ({
agentContext: captureAgentSessionContext(prepared, task.callId, agentLimits),
auth: {
current: prepared.auth,
@@ -66,10 +76,14 @@ async function dispatchCoordination(
batchEvent: batch.event,
owner: input.workflowToolRunOwner,
parentSession: prepared.parentSession,
- session: nextSession,
+ session,
task,
- };
- const dispatched = await dispatchWorkflowCall(start);
+ })),
+ readTaskTable(session.state),
+ );
+
+ for (const start of starts) {
+ const dispatched = await dispatchWorkflowCall({ ...start, session: nextSession });
nextSession = dispatched.session;
if (dispatched.result !== undefined) results.push(dispatched.result);
if (dispatched.started !== undefined) started.push(dispatched.started);
@@ -92,6 +106,30 @@ async function dispatchCoordination(
return { results, ...published };
}
+/**
+ * Starts the runs of a batch at once, in place of one after another, when
+ * dispatching it in order is sure to record every one of them. Otherwise
+ * each dispatch starts its own run, as the task cap and earlier calls allow.
+ */
+function withPrestartedRuns(
+ starts: readonly StartWorkflowTaskInput[],
+ table: TaskTable,
+): readonly StartWorkflowTaskInput[] {
+ const tasks = starts.map((start) => start.task);
+ const entries = tasks.map((task) => runEntryToStart(table, task));
+ const together =
+ entries.filter((entry) => entry !== undefined).length > 1 && startsEveryRun(table, tasks);
+ if (!together) return starts;
+ return starts.map((start, index) => {
+ const entry = entries[index];
+ if (entry === undefined) return start;
+ const run = startWorkflowToolCallRun(start, entry);
+ // Each dispatch awaits its own run in order, so a later failure waits unhandled until then.
+ run.catch(() => {});
+ return { ...start, prestarted: { entry, run } };
+ });
+}
+
/**
* Starts the run the call's entry point names, or sends a call with `taskId`
* to the running `serve` task it names.
diff --git a/packages/eve/src/execution/publish-session-events.integration.test.ts b/packages/eve/src/execution/publish-session-events.integration.test.ts
index abe05ce66..25e7d4f2a 100644
--- a/packages/eve/src/execution/publish-session-events.integration.test.ts
+++ b/packages/eve/src/execution/publish-session-events.integration.test.ts
@@ -1,7 +1,7 @@
import { expect, it } from "vitest";
import { replaceDurableSessionSnapshot } from "#execution/durable-session-store.js";
-import { emitWorkflowToolRunReportStep } from "#execution/tools/workflow/emit-workflow-tool-run-report-step.js";
+import { applyRunMessagesStep } from "#execution/tools/workflow/apply-run-messages-step.js";
import { withdrawWorkflowToolRunQuestionStep } from "#execution/tools/workflow/withdraw-step.js";
import { upsertProxyInputRequests } from "#harness/proxy-input-requests.js";
import type { HarnessSession } from "#harness/types.js";
@@ -55,20 +55,25 @@ it("publishes a session step's action.partial to the stream and its hooks", asyn
const { hooked, runtime, sessionWritable, streamed } = await createPublishingRuntime();
await runtime.run(async () => {
- await emitWorkflowToolRunReportStep({
- from: {
- callId: "call-1",
- input: {},
- runId: "run-1",
- sequence: 1,
- stepIndex: 0,
- toolName: "research",
- turnId: "turn-1",
- },
+ await applyRunMessagesStep({
+ messages: [
+ {
+ from: {
+ callId: "call-1",
+ input: {},
+ runId: "run-1",
+ sequence: 1,
+ stepIndex: 0,
+ toolName: "research",
+ turnId: "turn-1",
+ },
+ kind: "report",
+ update: { progress: "halfway" },
+ },
+ ],
serializedContext,
sessionState: createTestSessionState(),
sessionWritable,
- update: { progress: "halfway" },
});
});
diff --git a/packages/eve/src/execution/session-inbox/inbox.test.ts b/packages/eve/src/execution/session-inbox/inbox.test.ts
index 683fdcc20..9bc6f4089 100644
--- a/packages/eve/src/execution/session-inbox/inbox.test.ts
+++ b/packages/eve/src/execution/session-inbox/inbox.test.ts
@@ -1,5 +1,6 @@
import { sessionInboxHookToken } from "#execution/session-inbox/address.js";
import { beforeEach, describe, expect, it, vi } from "vitest";
+import { takeLeadingAppliedRunMessages } from "#execution/session-workflow-tool-run.js";
import {
createSessionInbox,
@@ -130,6 +131,59 @@ describe("createSessionInbox", () => {
expect(await inbox.release()).toEqual([]);
});
+ it("reads a run's relayed messages separately, and takes them a batch's budget at a time", async () => {
+ const from = {
+ callId: "call",
+ input: {},
+ runId: "tool-run",
+ sequence: 0,
+ stepIndex: 0,
+ toolName: "review",
+ turnId: "turn-1",
+ };
+ const opened: SessionInboxPayload = {
+ from,
+ kind: "agent-started",
+ session: {
+ continuationToken: "subagent:child-1",
+ kind: "local",
+ name: "reviewer",
+ nodeId: "reviewer",
+ sessionId: "child-1",
+ },
+ };
+ // Alice's reviewers report long findings, more than one step applies at once.
+ const findings = (label: string): SessionInboxPayload => ({
+ from,
+ kind: "report",
+ update: label.padEnd(40_000, "."),
+ });
+ const batch = {
+ kind: "workflow-batch",
+ messages: [opened, findings("first"), findings("second")],
+ };
+ installHooks(
+ createMockHook({
+ token: "stable",
+ reads: [
+ Promise.resolve(resolved(batch as never)),
+ Promise.resolve(resolved(send("Bob asks how it is going."))),
+ ],
+ }),
+ );
+ const inbox = createSessionInbox("session-1");
+ await inbox.claimSessionHook("stable");
+ await vi.waitFor(() => expect(inbox.hasPending()).toBe(true));
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+
+ expect(takeLeadingAppliedRunMessages(inbox)).toEqual([opened, findings("first")]);
+ expect(takeLeadingAppliedRunMessages(inbox)).toEqual([findings("second")]);
+ // Taking run messages from the front stops at Bob's message.
+ expect(takeLeadingAppliedRunMessages(inbox)).toEqual([]);
+ expect(inbox.drain()).toEqual([send("Bob asks how it is going.")]);
+ await inbox.dispose();
+ });
+
it("keeps a pushed cancellation queued for the consumer", async () => {
const input = createDeferred<IteratorResult<SessionInboxPayload>>();
installHooks(createMockHook({ token: "stable", reads: [input.promise] }));
diff --git a/packages/eve/src/execution/session-inbox/inbox.ts b/packages/eve/src/execution/session-inbox/inbox.ts
index 5d9042f80..19afa8f1e 100644
--- a/packages/eve/src/execution/session-inbox/inbox.ts
+++ b/packages/eve/src/execution/session-inbox/inbox.ts
@@ -4,7 +4,10 @@ import { releaseSessionHooksStep } from "#execution/session-inbox/release-step.j
import type { DeliverPayload, HookPayload, SessionCommand } from "#channel/types.js";
import { claimHookOwnership, disposeHook } from "#execution/hook-ownership.js";
-import type { WorkflowToolRunMessage } from "#execution/tools/workflow/messages.js";
+import type {
+ WorkflowToolRunMessage,
+ WorkflowToolRunMessageBatch,
+} from "#execution/tools/workflow/messages.js";
/** All session addresses accept the same protocol. Callback routes construct
* their own message kind; they never accept arbitrary session commands. */
@@ -28,7 +31,7 @@ export type SessionInboxPayload =
interface Source {
readonly token: string;
- readonly hook: Hook<SessionInboxPayload>;
+ readonly hook: Hook<SessionInboxPayload | WorkflowToolRunMessageBatch>;
registered?: Promise<void>;
stopping: boolean;
closed: boolean;
@@ -43,6 +46,10 @@ export interface SessionInboxReader {
next(): Promise<SessionInboxPayload | undefined>;
/** Removes every payload accepted so far, in arrival order. */
drain(): SessionInboxPayload[];
+ /** Removes the payloads at the front of the queue that `accepts` takes, stopping at the first it doesn't. */
+ takeLeading<T extends SessionInboxPayload>(
+ accepts: (payload: SessionInboxPayload) => payload is T,
+ ): T[];
hasPending(): boolean;
/** Resolves once a payload is ready or the inbox closes, without consuming anything. */
whenPending(): Promise<void>;
@@ -55,6 +62,7 @@ export interface SessionInboxReader {
onInterrupt(handler: (payload: SessionInboxPayload) => void): () => void;
/** Observes deliveries without consuming them; replays unread deliveries on subscription. */
onDelivery(handler: (payload: SessionInboxPayload) => void): () => void;
+ /** Requeues payloads a successor handed back, ahead of everything pumped since. */
restore(payloads: readonly SessionInboxPayload[]): void;
}
@@ -111,11 +119,17 @@ export function createSessionInbox(sessionId: string): SessionInboxHandle {
while (!source.stopping) {
const result = await iterator.next();
if (result.done) break;
- queue.push(result.value);
- if (result.value.kind === "send" || result.value.kind === "deliver")
- for (const handler of deliveryHandlers) handler(result.value);
- if (isInterrupt(result.value))
- for (const handler of interruptHandlers) handler(result.value);
+ const payload = result.value;
+ if (payload.kind === "workflow-batch") {
+ // A run's messages carry no deliveries or interrupts.
+ queue.push(...payload.messages);
+ notify();
+ continue;
+ }
+ queue.push(payload);
+ if (payload.kind === "send" || payload.kind === "deliver")
+ for (const handler of deliveryHandlers) handler(payload);
+ if (isInterrupt(payload)) for (const handler of interruptHandlers) handler(payload);
notify();
}
} catch (error) {
@@ -143,7 +157,7 @@ export function createSessionInbox(sessionId: string): SessionInboxHandle {
if (sources.length >= 256) throw new Error("A session may claim at most 256 addresses.");
const source: Source = {
token,
- hook: createHook<SessionInboxPayload>({
+ hook: createHook<SessionInboxPayload | WorkflowToolRunMessageBatch>({
token: sessionInboxHookToken(token),
metadata: { sessionId },
}),
@@ -184,6 +198,17 @@ export function createSessionInbox(sessionId: string): SessionInboxHandle {
if (failure !== undefined) throw failure.error;
return queue.splice(0);
},
+ takeLeading<T extends SessionInboxPayload>(
+ accepts: (payload: SessionInboxPayload) => payload is T,
+ ): T[] {
+ if (failure !== undefined) throw failure.error;
+ const taken: T[] = [];
+ for (let next = queue[0]; next !== undefined && accepts(next); next = queue[0]) {
+ taken.push(next);
+ queue.shift();
+ }
+ return taken;
+ },
hasPending() {
if (failure !== undefined) throw failure.error;
return queue.length > 0;
diff --git a/packages/eve/src/execution/session-workflow-tool-run.integration.test.ts b/packages/eve/src/execution/session-workflow-tool-run.integration.test.ts
index 87e440953..ac77e84a6 100644
--- a/packages/eve/src/execution/session-workflow-tool-run.integration.test.ts
+++ b/packages/eve/src/execution/session-workflow-tool-run.integration.test.ts
@@ -1,8 +1,8 @@
import { describe, expect, it } from "vitest";
import { handleWorkflowToolRunMessage } from "#execution/session-workflow-tool-run.js";
+import { applyRunMessagesStep } from "#execution/tools/workflow/apply-run-messages-step.js";
import { SessionStateCursor } from "#execution/session/state-cursor.js";
-import { applyTaskRunMessageStep } from "#execution/tasks/steps.js";
import {
createTask,
markTaskRunStarted,
@@ -67,7 +67,7 @@ describe("handleWorkflowToolRunMessage", () => {
},
}),
});
- const from: WorkflowToolRunRef = {
+ const from: WorkflowToolRunRef & { readonly taskId: string } = {
callId: "reviewer-call",
input: { message: "Review the release notes." },
runId: "reviewer-run",
@@ -107,13 +107,15 @@ describe("handleWorkflowToolRunMessage", () => {
},
});
await cursor.advance((state) =>
- applyTaskRunMessageStep({
+ applyRunMessagesStep({
...state,
- message: {
- from,
- kind: "outcome",
- result: { error: "The reviewer's model call failed.", status: "failed" },
- },
+ messages: [
+ {
+ from,
+ kind: "outcome",
+ result: { error: "The reviewer's model call failed.", status: "failed" },
+ },
+ ],
}),
);
});
diff --git a/packages/eve/src/execution/session-workflow-tool-run.ts b/packages/eve/src/execution/session-workflow-tool-run.ts
index bfd471273..ed9b5fb93 100644
--- a/packages/eve/src/execution/session-workflow-tool-run.ts
+++ b/packages/eve/src/execution/session-workflow-tool-run.ts
@@ -1,21 +1,20 @@
import { deliverWorkflowAuthorization } from "#execution/tools/workflow/owner.js";
+import type { AppliedRunMessage } from "#execution/tools/workflow/apply-run-messages-step.js";
import {
- emitAgentStartedStep,
- emitWorkflowToolRunReportStep,
-} from "#execution/tools/workflow/emit-workflow-tool-run-report-step.js";
-import type {
- WorkflowToolAskRequest,
- WorkflowToolRunAgentStartedMessage,
- WorkflowToolRunMessage,
- WorkflowToolRunOutcomeMessage,
- WorkflowToolRunRequestMessage,
- WorkflowToolRunWithdrawMessage,
+ runMessageBatchBudget,
+ type WorkflowToolAskRequest,
+ type WorkflowToolRunMessage,
+ type WorkflowToolRunOutcomeMessage,
+ type WorkflowToolRunRequestMessage,
+ type WorkflowToolRunWithdrawMessage,
} from "#execution/tools/workflow/messages.js";
import {
withdrawFinishedRunQuestionsStep,
withdrawWorkflowToolRunQuestionStep,
} from "#execution/tools/workflow/withdraw-step.js";
import type { SessionStateCursor } from "#execution/session/state-cursor.js";
+import { isWorkflowMessage, type SessionInboxReader } from "#execution/session-inbox/inbox.js";
+import { isTaskRunMessage } from "#execution/tasks/session.js";
import {
workflowToolRunOutcomeToToolResult,
workflowToolRunRequestToInputRequestPayload,
@@ -33,12 +32,34 @@ interface HandlerInput<T> {
readonly message: T;
}
+export function isAppliedRunMessage(message: WorkflowToolRunMessage): message is AppliedRunMessage {
+ return message.kind === "agent-started" || message.kind === "report" || isTaskRunMessage(message);
+}
+
+/**
+ * Removes the applied run messages at the front of the inbox, in arrival
+ * order, while `admits` takes them. One batch's caller passes its budget on.
+ */
+export function takeLeadingAppliedRunMessages(
+ inbox: SessionInboxReader,
+ admits = runMessageBatchBudget(),
+): AppliedRunMessage[] {
+ return inbox.takeLeading(
+ (payload): payload is AppliedRunMessage =>
+ isWorkflowMessage(payload) && isAppliedRunMessage(payload) && admits(payload),
+ );
+}
+
+/**
+ * Handles a run message the session does not apply as it reads it: a
+ * question, its withdrawal, or an `execute` run's outcome.
+ */
export async function handleWorkflowToolRunMessage(
- input: HandlerInput<WorkflowToolRunMessage>,
+ input: HandlerInput<Exclude<WorkflowToolRunMessage, AppliedRunMessage>>,
): Promise<RuntimeActionResult | undefined> {
const { message } = input;
switch (message.kind) {
- // Only task runs report started, reply, or usage, and the session applies those to the task table.
+ // Only task runs report started, reply, or usage, and the session applies those as it reads them.
case "started":
case "reply":
case "usage":
@@ -51,34 +72,7 @@ export async function handleWorkflowToolRunMessage(
case "withdraw":
await handleWorkflowToolRunWithdraw({ ...input, message });
return undefined;
- case "report":
- await input.cursor.advance((state) =>
- emitWorkflowToolRunReportStep({ ...state, from: message.from, update: message.update }),
- );
- return undefined;
- case "agent-started":
- await input.cursor.advance((state) =>
- emitAgentStartedStep({ ...state, messages: [message] }),
- );
- return undefined;
- }
-}
-
-/** Boundary messages in admission order, with consecutive `agent-started` messages grouped. */
-type BoundaryBatch =
- | { readonly kind: "agent-started"; readonly messages: WorkflowToolRunAgentStartedMessage[] }
- | { readonly kind: "message"; readonly message: WorkflowToolRunMessage };
-
-/** Groups consecutive `agent-started` messages so one `emitAgentStartedStep` publishes each group. */
-export function batchAgentStarts(messages: readonly WorkflowToolRunMessage[]): BoundaryBatch[] {
- const batches: BoundaryBatch[] = [];
- for (const message of messages) {
- const last = batches.at(-1);
- if (message.kind !== "agent-started") batches.push({ kind: "message", message });
- else if (last?.kind === "agent-started") last.messages.push(message);
- else batches.push({ kind: "agent-started", messages: [message] });
}
- return batches;
}
/**
diff --git a/packages/eve/src/execution/session/active-turn.ts b/packages/eve/src/execution/session/active-turn.ts
index ed5602b50..e0f91fb3c 100644
--- a/packages/eve/src/execution/session/active-turn.ts
+++ b/packages/eve/src/execution/session/active-turn.ts
@@ -13,7 +13,15 @@ import type { SessionExecutionInput } from "#execution/session/turn.js";
import { createTurnControl, type TurnControl } from "#execution/session/turn-control.js";
import type { SessionInboxPayload } from "#execution/session-inbox/inbox.js";
import { decodeSessionInboxPayload } from "#execution/session-inbox/protocol.js";
-import type { WorkflowToolRunMessage } from "#execution/tools/workflow/messages.js";
+import {
+ runMessageBatchBudget,
+ type WorkflowToolRunMessage,
+} from "#execution/tools/workflow/messages.js";
+import {
+ isAppliedRunMessage,
+ takeLeadingAppliedRunMessages,
+} from "#execution/session-workflow-tool-run.js";
+import type { AppliedRunMessage } from "#execution/tools/workflow/apply-run-messages-step.js";
import { readDurableSession } from "#execution/durable-session-read.js";
import { activeTurnId, storedProjection, turnPosition } from "#harness/session-machine/view.js";
import { coalesceDeliveries } from "#harness/messages.js";
@@ -162,6 +170,29 @@ export class ActiveTurn {
return taken;
}
+ /**
+ * Removes the run messages read after one the session just took, as long as
+ * each is one it applies as it reads it and they fit one batch. Those it
+ * already admitted come first, then those still in the inbox, so arrival
+ * order holds.
+ */
+ takeAppliedRunMessages(): AppliedRunMessage[] {
+ const admits = runMessageBatchBudget();
+ const taken: AppliedRunMessage[] = [];
+ for (let next = this.runtimeResults[0]; next !== undefined; next = this.runtimeResults[0]) {
+ if (
+ next === "cancelled" ||
+ next.kind !== "workflow" ||
+ !isAppliedRunMessage(next.message) ||
+ !admits(next.message)
+ )
+ return taken;
+ taken.push(next.message);
+ this.runtimeResults.shift();
+ }
+ return [...taken, ...takeLeadingAppliedRunMessages(this.input.inbox, admits)];
+ }
+
/**
* Next runtime result, workflow message, steering, or timeout, admitting
* inbox traffic while waiting. Deliveries admitted before the wait began are
diff --git a/packages/eve/src/execution/session/checkpoint-migrations.ts b/packages/eve/src/execution/session/checkpoint-migrations.ts
index 01a203ed7..c627b0980 100644
--- a/packages/eve/src/execution/session/checkpoint-migrations.ts
+++ b/packages/eve/src/execution/session/checkpoint-migrations.ts
@@ -94,6 +94,9 @@ const CHECKPOINT_UPGRADES: Readonly<
// Version 13 prevents older deployments from ignoring stubs and running real tools.
// Existing checkpoints need no data changes.
12: (checkpoint) => checkpoint,
+ // Version 14 prevents older deployments from dropping the batched messages
+ // workflow tool runs relay. Existing checkpoints need no data changes.
+ 13: (checkpoint) => checkpoint,
};
/**
diff --git a/packages/eve/src/execution/session/handoff.test.ts b/packages/eve/src/execution/session/handoff.test.ts
index 6d44adcd9..cfe922588 100644
--- a/packages/eve/src/execution/session/handoff.test.ts
+++ b/packages/eve/src/execution/session/handoff.test.ts
@@ -346,6 +346,7 @@ function createInbox(input: { released?: SessionInboxPayload[] } = {}): SessionI
claimSessionHook: vi.fn(async () => {}),
claimSessionHooks: vi.fn(async () => {}),
claimedTokens: [],
+ takeLeading: () => [],
dispose: vi.fn(async () => {}),
drain: vi.fn(() => []),
hasPending: vi.fn(() => false),
diff --git a/packages/eve/src/execution/session/handoff.ts b/packages/eve/src/execution/session/handoff.ts
index c677ea01e..e7150bd19 100644
--- a/packages/eve/src/execution/session/handoff.ts
+++ b/packages/eve/src/execution/session/handoff.ts
@@ -26,7 +26,7 @@ import { isObject } from "#shared/guards.js";
* A newer successor must always accept older checkpoints: every bump adds the
* upgrade from the previous version in `checkpoint-migrations.ts`.
*/
-export const SESSION_CHECKPOINT_VERSION = 13;
+export const SESSION_CHECKPOINT_VERSION = 14;
/** Everything a successor needs to continue an idle session. Hooks are derived from the state. */
export interface SessionCheckpoint {
diff --git a/packages/eve/src/execution/session/next-input.test.ts b/packages/eve/src/execution/session/next-input.test.ts
index dafaccbbc..bef8ba714 100644
--- a/packages/eve/src/execution/session/next-input.test.ts
+++ b/packages/eve/src/execution/session/next-input.test.ts
@@ -29,6 +29,7 @@ function createMockInbox(reads: readonly ScriptedRead[]): SessionInbox {
return {
claimedTokens: [],
+ takeLeading: () => [],
async claimSessionHook() {},
async claimSessionHooks() {},
drain() {
diff --git a/packages/eve/src/execution/session/turn-step.test.ts b/packages/eve/src/execution/session/turn-step.test.ts
index 5b3ac9fdf..670b3f33e 100644
--- a/packages/eve/src/execution/session/turn-step.test.ts
+++ b/packages/eve/src/execution/session/turn-step.test.ts
@@ -36,6 +36,13 @@ import { startWorkflowTask } from "#execution/tools/workflow/start.js";
import { TurnCancelledError } from "#harness/turn-cancellation.js";
import { createToolLoopHarness } from "#harness/tool-loop.js";
import { queuedInput, storedProjection } from "#harness/session-machine/view.js";
+import {
+ MAX_WORKING_TASKS,
+ readTaskTable,
+ writeTaskTable,
+ type TaskRecord,
+} from "#execution/tasks/table.js";
+import { applyValueDelta } from "#shared/value-delta.js";
import { APPROVED_CALL_INTERRUPTED_MESSAGE } from "#harness/hitl/approved-calls.js";
import { textStreamResult } from "#internal/testing/approval-resume.js";
import { openInputs } from "#protocol/session-projection.js";
@@ -80,7 +87,7 @@ import { turnStep as runTurnStep } from "#execution/session/turn-step.js";
import { dispatchCoordinationStep } from "#execution/coordination-dispatch-step.js";
import type { TurnStepInput, TurnStepPayload } from "#execution/session/turn-step-types.js";
import type { DeliverHookPayload } from "#channel/types.js";
-import type { RuntimeActionResult } from "#shared/action-types.js";
+import type { RuntimeActionResult, RuntimeWorkflowTaskRequest } from "#shared/action-types.js";
import { setEveAttributes } from "#runtime/attributes/emit.js";
import { ensureSandboxAccess } from "#execution/sandbox/ensure.js";
import { isSandboxRefUrl } from "#internal/attachments/sandbox-refs.js";
@@ -159,7 +166,8 @@ vi.mock("#instrumentation/runtime.js", async (importOriginal) => {
};
});
-vi.mock("#execution/tools/workflow/start.js", () => ({
+vi.mock("#execution/tools/workflow/start.js", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("#execution/tools/workflow/start.js")>()),
startWorkflowTask: vi.fn(async ({ session }: { session: unknown }) => ({ session })),
}));
@@ -972,6 +980,117 @@ describe("dispatchCoordinationStep", () => {
sessionId: expected,
});
});
+
+ describe("when one batch starts several task runs", () => {
+ // The override below gives the real reader to a mock other tests configure themselves.
+ afterEach(() => vi.mocked(readDurableSession).mockReset());
+
+ function batchOfReviews(running: number): HarnessSession {
+ const call = (taskId: string): RuntimeWorkflowTaskRequest => ({
+ callId: `call-${taskId}`,
+ entry: { entryPoint: "serve", taskId },
+ executeInput: { message: "Bob asks for a review of the plan." },
+ input: { message: "Bob asks for a review of the plan." },
+ kind: "workflow-task",
+ toolName: "reviewer",
+ workflowId: "workflow//eve//reviewer",
+ });
+ const record = (id: string, run?: string): TaskRecord => ({
+ calls: [{ callId: `call-${id}`, turnId: "turn_3" }],
+ id,
+ kind: "agent",
+ name: "reviewer",
+ results: [],
+ resumable: true,
+ ...(run !== undefined && { run: { hookToken: `hook-${id}`, runId: run, started: true } }),
+ });
+ const busy = Array.from({ length: running }, (_, index) =>
+ record(`busy-${String(index)}`, `run-busy-${String(index)}`),
+ );
+ const parked = withParkedStep(createStubSession(), {
+ event: { sequence: 3, stepIndex: 2, turnId: "turn_3" },
+ messages: [],
+ tasks: [call("alice"), call("bob")],
+ });
+ return writeTaskTable(parked, { tasks: [...busy, record("alice"), record("bob")] });
+ }
+
+ async function dispatch(session: HarnessSession) {
+ mockCoordinationBundle();
+ // The step reads the parked session, then the state its own writes produce.
+ const actual = await vi.importActual<typeof import("../durable-session-store.js")>(
+ "../durable-session-store.js",
+ );
+ vi.mocked(readDurableSession)
+ .mockImplementation(actual.readDurableSession)
+ .mockImplementationOnce(() => session);
+ vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_current");
+ const sessionState = createStubSessionState();
+ const dispatched = await dispatchCoordinationStep({
+ action: "park",
+ workflowToolRunOwner: { inbox: "owner-inbox" },
+ sessionWritable: createTestWritable(),
+ serializedContext: createSerializedContext(),
+ sessionState,
+ });
+ const next = applyValueDelta(sessionState, dispatched.stateDelta.sessionState);
+ return { results: dispatched.results, table: readTaskTable(next.snapshot.session.state) };
+ }
+
+ it("starts them together and records each run on its task", async () => {
+ const starts = [
+ Promise.withResolvers<{ runId: string }>(),
+ Promise.withResolvers<{ runId: string }>(),
+ ];
+ startMock.mockImplementation(() => starts[startMock.mock.calls.length - 1]?.promise);
+
+ const dispatching = dispatch(batchOfReviews(0));
+ // Both runs start before either start returns.
+ await vi.waitFor(() => expect(startMock).toHaveBeenCalledTimes(2));
+ starts[1]?.resolve({ runId: "run-bob" });
+ starts[0]?.resolve({ runId: "run-alice" });
+ const { table } = await dispatching;
+
+ expect(table.tasks.map((task) => [task.id, task.run?.runId])).toEqual([
+ ["alice", "run-alice"],
+ ["bob", "run-bob"],
+ ]);
+ });
+
+ it("starts them one by one when the task cap could refuse one, so no run is left unrecorded", async () => {
+ startMock.mockResolvedValue({ runId: "run-alice" });
+
+ const { results, table } = await dispatch(batchOfReviews(MAX_WORKING_TASKS - 1));
+
+ expect(startMock).toHaveBeenCalledOnce();
+ expect(table.tasks.find((task) => task.id === "alice")?.run?.runId).toBe("run-alice");
+ expect(table.tasks.some((task) => task.id === "bob")).toBe(false);
+ expect(results.find((result) => result.callId === "call-bob")).toMatchObject({
+ isError: true,
+ });
+ });
+
+ it("fails only the call whose run did not start", async () => {
+ const alice = Promise.withResolvers<{ runId: string }>();
+ startMock
+ .mockImplementationOnce(() => alice.promise)
+ .mockRejectedValueOnce(new Error("Workflow start rejected"));
+
+ const dispatching = dispatch(batchOfReviews(0));
+ // Bob's start fails while Alice's is still on its way.
+ await vi.waitFor(() => expect(startMock).toHaveBeenCalledTimes(2));
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ alice.resolve({ runId: "run-alice" });
+ const { results, table } = await dispatching;
+
+ expect(table.tasks.map((task) => [task.id, task.run?.runId])).toEqual([
+ ["alice", "run-alice"],
+ ]);
+ expect(results.find((result) => result.callId === "call-bob")).toMatchObject({
+ isError: true,
+ });
+ });
+ });
});
describe("turnStep", () => {
diff --git a/packages/eve/src/execution/session/turn.test.ts b/packages/eve/src/execution/session/turn.test.ts
index 5c7cd59c5..e78aa08df 100644
--- a/packages/eve/src/execution/session/turn.test.ts
+++ b/packages/eve/src/execution/session/turn.test.ts
@@ -30,10 +30,7 @@ import {
import { getSessionTokenUsage } from "#harness/turn-tag-state.js";
import { registerWorkflowToolRun } from "#harness/workflow-tool-runs.js";
import { interruptWorkflowToolRun } from "#execution/tools/workflow/interrupt.js";
-import {
- emitAgentStartedStep,
- emitWorkflowToolRunReportStep,
-} from "#execution/tools/workflow/emit-workflow-tool-run-report-step.js";
+import { applyRunMessagesStep } from "#execution/tools/workflow/apply-run-messages-step.js";
import type {
WorkflowToolRunMessage,
WorkflowToolRunRef,
@@ -66,12 +63,15 @@ vi.mock("#execution/session/task-tool-tracing-step.js", () => ({
startTaskToolCallsStep: vi.fn(async () => Date.now()),
traceTaskToolCallStep: vi.fn(async () => ({ stateDelta: {} })),
}));
-vi.mock("#execution/tools/workflow/emit-workflow-tool-run-report-step.js", () => ({
- emitAgentStartedStep: vi.fn(),
- emitWorkflowToolRunReportStep: vi.fn(),
-}));
+vi.mock("#execution/tools/workflow/apply-run-messages-step.js", async (importOriginal) => {
+ const actual =
+ await importOriginal<typeof import("#execution/tools/workflow/apply-run-messages-step.js")>();
+ return { ...actual, applyRunMessagesStep: vi.fn(actual.applyRunMessagesStep) };
+});
beforeEach(() => {
+ // Tests that record publishing replace the real step; the rest apply messages for real.
+ vi.mocked(applyRunMessagesStep).mockReset();
vi.mocked(traceTaskToolCallStep).mockClear();
vi.mocked(routeDeliverToChildren)
.mockReset()
@@ -186,6 +186,7 @@ describe("SessionExecution checkpoints", () => {
it("binds the delegated caller on the turn's first step only", async () => {
const inbox: SessionInbox = {
claimedTokens: [],
+ takeLeading: () => [],
claimSessionHook: vi.fn(),
claimSessionHooks: vi.fn(),
drain: () => [],
@@ -225,6 +226,7 @@ describe("SessionExecution checkpoints", () => {
const pending: SessionInboxPayload[] = [];
const inbox: SessionInbox = {
claimedTokens: [],
+ takeLeading: () => [],
claimSessionHook: vi.fn(),
claimSessionHooks: vi.fn(),
drain: () => pending.splice(0),
@@ -278,6 +280,7 @@ describe("SessionExecution checkpoints", () => {
let drainingFirst = true;
const inbox: SessionInbox = {
claimedTokens: [],
+ takeLeading: () => [],
claimSessionHook: vi.fn(),
claimSessionHooks: vi.fn(),
drain: () => {
@@ -345,6 +348,7 @@ describe("SessionExecution checkpoints", () => {
const pending: SessionInboxPayload[] = [];
const inbox: SessionInbox = {
claimedTokens: [],
+ takeLeading: () => [],
claimSessionHook: vi.fn(),
claimSessionHooks: vi.fn(),
drain: () => pending.splice(0),
@@ -416,6 +420,7 @@ describe("SessionExecution checkpoints", () => {
const pending: SessionInboxPayload[] = [];
const inbox: SessionInbox = {
claimedTokens: [],
+ takeLeading: () => [],
claimSessionHook: vi.fn(),
claimSessionHooks: vi.fn(),
drain: () => pending.splice(0),
@@ -476,6 +481,7 @@ describe("SessionExecution checkpoints", () => {
let notify: (payload: SessionInboxPayload) => void = () => {};
const inbox: SessionInbox = {
claimedTokens: [],
+ takeLeading: () => [],
claimSessionHook: vi.fn(),
claimSessionHooks: vi.fn(),
drain: () => [],
@@ -509,6 +515,7 @@ describe("SessionExecution checkpoints", () => {
const sessionState = stateWithBlockingRun();
const inbox: SessionInbox = {
claimedTokens: [],
+ takeLeading: () => [],
claimSessionHook: vi.fn(),
claimSessionHooks: vi.fn(),
drain: vi
@@ -565,6 +572,7 @@ describe("SessionExecution checkpoints", () => {
let interrupt: ((payload: SessionInboxPayload) => void) | undefined;
const inbox: SessionInbox = {
claimedTokens: [],
+ takeLeading: () => [],
claimSessionHook: vi.fn(),
claimSessionHooks: vi.fn(),
drain: vi
@@ -618,6 +626,7 @@ describe("SessionExecution checkpoints", () => {
};
const inbox: SessionInbox = {
claimedTokens: [],
+ takeLeading: () => [],
claimSessionHook: vi.fn(),
claimSessionHooks: vi.fn(),
drain: vi.fn().mockReturnValueOnce([steering]).mockReturnValue([]),
@@ -680,6 +689,7 @@ describe("SessionExecution checkpoints", () => {
const queue = new SessionInputQueue();
const inbox: SessionInbox = {
claimedTokens: [],
+ takeLeading: () => [],
claimSessionHook: vi.fn(),
claimSessionHooks: vi.fn(),
drain: vi.fn().mockReturnValueOnce([followUp]).mockReturnValue([]),
@@ -728,6 +738,7 @@ describe("SessionExecution checkpoints", () => {
async ({ capabilities, holds, serializedContext }) => {
const inbox: SessionInbox = {
claimedTokens: [],
+ takeLeading: () => [],
claimSessionHook: vi.fn(),
claimSessionHooks: vi.fn(),
drain: vi.fn(() => []),
@@ -788,6 +799,7 @@ describe("SessionExecution checkpoints", () => {
const queue = new SessionInputQueue();
const inbox: SessionInbox = {
claimedTokens: [],
+ takeLeading: () => [],
claimSessionHook: vi.fn(),
claimSessionHooks: vi.fn(),
drain: vi.fn().mockReturnValueOnce([cancel, followUp]).mockReturnValue([]),
@@ -837,6 +849,7 @@ describe("SessionExecution checkpoints", () => {
const queue = new SessionInputQueue();
const inbox: SessionInbox = {
claimedTokens: [],
+ takeLeading: () => [],
claimSessionHook: vi.fn(),
claimSessionHooks: vi.fn(),
drain: vi.fn(() => []),
@@ -911,6 +924,7 @@ describe("SessionExecution checkpoints", () => {
const runtimePayloads: SessionInboxPayload[] = [answerAndCorrection, { kind: "cancel" }];
const inbox: SessionInbox = {
claimedTokens: [],
+ takeLeading: () => [],
claimSessionHook: vi.fn(),
claimSessionHooks: vi.fn(),
drain: vi.fn(() => []),
@@ -994,6 +1008,7 @@ describe("SessionExecution checkpoints", () => {
];
const inbox: SessionInbox = {
claimedTokens: [],
+ takeLeading: () => [],
claimSessionHook: vi.fn(),
claimSessionHooks: vi.fn(),
drain: vi.fn(() => []),
@@ -1086,6 +1101,7 @@ describe("SessionExecution checkpoints", () => {
];
const inbox: SessionInbox = {
claimedTokens: [],
+ takeLeading: () => [],
claimSessionHook: vi.fn(),
claimSessionHooks: vi.fn(),
drain: vi.fn(() => []),
@@ -1137,6 +1153,170 @@ describe("SessionExecution checkpoints", () => {
});
});
+ it("applies the run messages read together while the turn waits in one step, in order", async () => {
+ const sessionState = state("");
+ const from = (taskId?: string): WorkflowToolRunRef => ({
+ callId: "triage-call",
+ input: {},
+ runId: "triage-run",
+ sequence: 0,
+ stepIndex: 0,
+ ...(taskId !== undefined && { taskId }),
+ toolName: "triage_issues",
+ turnId: "turn_0",
+ });
+ const opened = (sessionId: string): SessionInboxPayload => ({
+ from: from(),
+ kind: "agent-started",
+ session: {
+ continuationToken: `subagent:${sessionId}`,
+ kind: "local",
+ name: "reviewer",
+ nodeId: "reviewer",
+ sessionId,
+ },
+ });
+ // Alice's triage opens two reviewers and reports, then Bob cancels the turn.
+ const payloads: SessionInboxPayload[] = [
+ opened("child-1"),
+ opened("child-2"),
+ { from: from(), kind: "report", update: "Two reviewers started." },
+ { kind: "cancel" },
+ ];
+ const inbox: SessionInbox = {
+ claimedTokens: [],
+ takeLeading: <T extends SessionInboxPayload>(
+ accepts: (payload: SessionInboxPayload) => payload is T,
+ ): T[] => {
+ const taken: T[] = [];
+ for (let next = payloads[0]; next !== undefined && accepts(next); next = payloads[0]) {
+ taken.push(next);
+ payloads.shift();
+ }
+ return taken;
+ },
+ claimSessionHook: vi.fn(),
+ claimSessionHooks: vi.fn(),
+ drain: vi.fn(() => []),
+ hasPending: vi.fn(() => payloads.length > 0),
+ whenPending: () => new Promise<void>(() => {}),
+ next: vi.fn(async () => payloads.shift()),
+ onDelivery: vi.fn(() => () => {}),
+ onInterrupt: vi.fn(() => () => {}),
+ restore: vi.fn(),
+ };
+ const cursor = createCursor({ inbox, sessionState });
+ publishIntoContext();
+ vi.mocked(turnStep)
+ .mockReset()
+ .mockImplementation(
+ turnStepWork(async () => ({
+ action: "park",
+ pendingCoordinationCallIds: ["triage-call"],
+ serializedContext: {},
+ sessionState,
+ })),
+ );
+ vi.mocked(dispatchCoordinationStep)
+ .mockReset()
+ .mockImplementation(
+ dispatchWork(async () => ({ results: [], serializedContext: {}, sessionState })),
+ );
+
+ await expect(
+ createExecution({ cursor, inbox, sessionState }).runTurn({
+ delivery: { kind: "deliver", payloads: [{ message: "Triage the open issues." }] },
+ }),
+ ).resolves.toEqual({ cancelled: true, kind: "park" });
+
+ expect(cursor.serializedContext[PUBLISHED]).toEqual(["child-1+child-2+Two reviewers started."]);
+ });
+
+ it("applies reports the turn already admitted before those still in the inbox, and stops at the outcome", async () => {
+ const sessionState = stateWithBlockingRun();
+ const from: WorkflowToolRunRef = {
+ callId: "hold-call",
+ input: {},
+ runId: "hold-run",
+ sequence: 0,
+ stepIndex: 0,
+ toolName: "hold",
+ turnId: "turn_0",
+ };
+ const report = (update: string): SessionInboxPayload => ({ from, kind: "report", update });
+ // Alice's run reported twice while the model step ran, then once more and finished.
+ const pending: SessionInboxPayload[] = [
+ report("Third check passed."),
+ { from, kind: "outcome", result: { output: "held", status: "completed" } },
+ ];
+ const inbox: SessionInbox = {
+ claimedTokens: [],
+ takeLeading: <T extends SessionInboxPayload>(
+ accepts: (payload: SessionInboxPayload) => payload is T,
+ ): T[] => {
+ const taken: T[] = [];
+ for (let next = pending[0]; next !== undefined && accepts(next); next = pending[0]) {
+ taken.push(next);
+ pending.shift();
+ }
+ return taken;
+ },
+ claimSessionHook: vi.fn(),
+ claimSessionHooks: vi.fn(),
+ drain: vi
+ .fn()
+ .mockReturnValueOnce([report("First check passed."), report("Second check passed.")])
+ .mockReturnValue([]),
+ hasPending: vi.fn(() => pending.length > 0),
+ whenPending: () => new Promise<void>(() => {}),
+ next: vi.fn(async () => pending.shift() ?? new Promise<never>(() => {})),
+ onDelivery: vi.fn(() => () => {}),
+ onInterrupt: vi.fn(() => () => {}),
+ restore: vi.fn(),
+ };
+ const cursor = createCursor({ inbox, sessionState });
+ publishIntoContext();
+ vi.mocked(turnStep)
+ .mockReset()
+ .mockImplementationOnce(
+ turnStepWork(async () => ({
+ action: "park",
+ pendingCoordinationCallIds: ["hold-call"],
+ serializedContext: {},
+ sessionState,
+ })),
+ )
+ .mockImplementationOnce(
+ turnStepWork(async (input) => ({
+ action: "done",
+ output: "done",
+ serializedContext: input.serializedContext,
+ sessionState,
+ })),
+ );
+ vi.mocked(dispatchCoordinationStep)
+ .mockReset()
+ .mockImplementation(
+ dispatchWork(async () => ({ results: [], serializedContext: {}, sessionState })),
+ );
+
+ await expect(
+ createExecution({ cursor, inbox, sessionState }).runTurn({
+ delivery: {
+ kind: "deliver",
+ payloads: [{ message: "Hold the rollout until checks pass." }],
+ },
+ }),
+ ).resolves.toMatchObject({ kind: "done" });
+
+ expect(cursor.serializedContext[PUBLISHED]).toEqual([
+ "First check passed.+Second check passed.+Third check passed.",
+ ]);
+ expect(vi.mocked(turnStep).mock.calls[1]?.[0].input?.runtimeResults?.results).toEqual([
+ expect.objectContaining({ callId: "hold-call" }),
+ ]);
+ });
+
it("hands the step each workflow run's delegated usage once, even when its outcome arrives twice", async () => {
const base = state("");
const tools = ["draft", "review"];
@@ -1179,6 +1359,7 @@ describe("SessionExecution checkpoints", () => {
const payloads = [outcome("draft", 300), outcome("draft", 300), outcome("review", 500)];
const inbox: SessionInbox = {
claimedTokens: [],
+ takeLeading: () => [],
claimSessionHook: vi.fn(),
claimSessionHooks: vi.fn(),
drain: vi.fn(() => []),
@@ -1245,6 +1426,7 @@ describe("SessionExecution checkpoints", () => {
let signalDelivery: (payload: SessionInboxPayload) => void = () => {};
const inbox: SessionInbox = {
claimedTokens: [],
+ takeLeading: () => [],
claimSessionHook: vi.fn(),
claimSessionHooks: vi.fn(),
drain: vi.fn(() => []),
@@ -1303,7 +1485,7 @@ describe("SessionExecution checkpoints", () => {
expect(continuation).toEqual({ delivery: steering, steered: false });
});
- it("publishes and adopts consecutive boundary agent-started messages in one step, keeping admission order", async () => {
+ it("publishes and adopts consecutive boundary run messages in one step, keeping admission order", async () => {
const { inbox, planner, progress, reviewer, writer } = boundaryRunMessages();
const cursor = createCursor({ inbox, sessionState: state("") });
publishIntoContext();
@@ -1327,9 +1509,7 @@ describe("SessionExecution checkpoints", () => {
).resolves.toMatchObject({ kind: "park", settled: { output: "Done." } });
expect(cursor.serializedContext[PUBLISHED]).toEqual([
- "planner-session+reviewer-session",
- "Halfway through the sources.",
- "writer-session",
+ "planner-session+reviewer-session+Halfway through the sources.+writer-session",
]);
});
@@ -1351,7 +1531,6 @@ describe("SessionExecution checkpoints", () => {
// The boundary still ran: it handled the task's report and dropped only the child.
expect(cursor.serializedContext[PUBLISHED]).toEqual(["Halfway through the sources."]);
- expect(emitAgentStartedStep).not.toHaveBeenCalled();
});
it("announces a child opened before a cancel ahead of cancelling the turn's work", async () => {
@@ -1387,7 +1566,7 @@ describe("SessionExecution checkpoints", () => {
kind: "park",
});
- const [announced] = vi.mocked(emitAgentStartedStep).mock.invocationCallOrder;
+ const [announced] = vi.mocked(applyRunMessagesStep).mock.invocationCallOrder;
const [cancelled] = vi.mocked(cancelDescendantTurnsStep).mock.invocationCallOrder;
expect(announced).toBeLessThan(cancelled!);
});
@@ -1404,23 +1583,24 @@ function publishIntoContext(): void {
[PUBLISHED]: [...((context[PUBLISHED] as string[] | undefined) ?? []), entry],
},
});
- vi.mocked(emitAgentStartedStep)
+ vi.mocked(applyRunMessagesStep)
.mockReset()
.mockImplementation(
- stepWork(async (input: Parameters<typeof emitAgentStartedStep>[0]) =>
+ stepWork(async (input: Parameters<typeof applyRunMessagesStep>[0]) =>
append(
input.serializedContext,
- input.messages.map((message) => message.session.sessionId).join("+"),
+ input.messages
+ .map((message) =>
+ message.kind === "agent-started"
+ ? message.session.sessionId
+ : message.kind === "report"
+ ? String(message.update)
+ : message.kind,
+ )
+ .join("+"),
),
),
);
- vi.mocked(emitWorkflowToolRunReportStep)
- .mockReset()
- .mockImplementation(
- stepWork(async (input: Parameters<typeof emitWorkflowToolRunReportStep>[0]) =>
- append(input.serializedContext, String(input.update)),
- ),
- );
}
/**
@@ -1441,10 +1621,17 @@ function boundaryRunMessages() {
const opened = (callId: string, name: string): WorkflowToolRunMessage => ({
from: from(callId),
kind: "agent-started",
- session: { kind: "local", name, nodeId: name, sessionId: `${name}-session` },
+ session: {
+ continuationToken: `subagent:${name}`,
+ kind: "local",
+ name,
+ nodeId: name,
+ sessionId: `${name}-session`,
+ },
});
const inbox: SessionInbox = {
claimedTokens: [],
+ takeLeading: () => [],
claimSessionHook: vi.fn(),
claimSessionHooks: vi.fn(),
drain: () => [],
@@ -1485,6 +1672,7 @@ function createCursor(input: {
function idleInbox(): SessionInbox {
return {
claimedTokens: [],
+ takeLeading: () => [],
claimSessionHook: vi.fn(),
claimSessionHooks: vi.fn(),
drain: () => [],
diff --git a/packages/eve/src/execution/session/turn.ts b/packages/eve/src/execution/session/turn.ts
index c8be8ab84..f77b69c01 100644
--- a/packages/eve/src/execution/session/turn.ts
+++ b/packages/eve/src/execution/session/turn.ts
@@ -12,10 +12,8 @@ import { renderTaskWaitResult } from "#execution/tasks/render.js";
import {
answerTaskCancel,
cancelWorkingTasks,
- isTaskRunMessage,
sessionTaskTable,
} from "#execution/tasks/session.js";
-import { applyTaskRunMessageStep } from "#execution/tasks/steps.js";
import { taskWaitResult } from "#execution/tasks/table.js";
import {
sessionCommandHookToken,
@@ -25,10 +23,14 @@ import type { SessionInboxReader } from "#execution/session-inbox/inbox.js";
import { publishTurnWaitingStep } from "#execution/session/turn-waiting-step.js";
import type { SessionStateCursor } from "#execution/session/state-cursor.js";
import {
- batchAgentStarts,
handleWorkflowToolRunMessage,
+ isAppliedRunMessage,
+ takeLeadingAppliedRunMessages,
} from "#execution/session-workflow-tool-run.js";
-import { emitAgentStartedStep } from "#execution/tools/workflow/emit-workflow-tool-run-report-step.js";
+import {
+ applyRunMessagesStep,
+ type AppliedRunMessage,
+} from "#execution/tools/workflow/apply-run-messages-step.js";
import { interruptWorkflowToolRun } from "#execution/tools/workflow/interrupt.js";
import type { WorkflowToolRunMessage } from "#execution/tools/workflow/messages.js";
import type {
@@ -136,23 +138,30 @@ export class SessionExecution {
/**
* Applies what runs reported while the model step ran, so the next step sees
- * it. Consecutive `agent-started` messages, such as a fan-out's, share one step.
- * An ending session drops them: its stream is closed, and finalizing the
- * session terminates the children.
+ * it. Consecutive messages the session applies as it reads them, such as a
+ * fan-out's, share one step. An ending session drops `agent-started`: its
+ * stream is closed, and finalizing the session terminates the children.
*/
private async handleBoundaryMessages(
messages: readonly WorkflowToolRunMessage[],
ending = false,
): Promise<void> {
- for (const batch of batchAgentStarts(messages)) {
- if (batch.kind === "message") {
- await this.handleWorkflowMessage(batch.message);
- } else if (!ending) {
- await this.input.cursor.advance((state) =>
- emitAgentStartedStep({ ...state, messages: batch.messages }),
- );
+ let applied: AppliedRunMessage[] = [];
+ for (const message of messages) {
+ if (!isAppliedRunMessage(message)) {
+ await this.applyRunMessages(applied);
+ applied = [];
+ await handleWorkflowToolRunMessage({ cursor: this.input.cursor, message });
+ } else if (!ending || message.kind !== "agent-started") {
+ applied.push(message);
}
}
+ await this.applyRunMessages(applied);
+ }
+
+ private async applyRunMessages(messages: readonly AppliedRunMessage[]): Promise<void> {
+ if (messages.length === 0) return;
+ await this.input.cursor.advance((state) => applyRunMessagesStep({ ...state, messages }));
}
private async runTurnSteps(
@@ -266,11 +275,19 @@ export class SessionExecution {
return dispatched.results;
}
+ /**
+ * Handles a run message the session just read. One it applies as it reads
+ * it takes along those read after it, from `turn` while a turn runs, so a
+ * fan-out's messages share one step.
+ */
async handleWorkflowMessage(
message: WorkflowToolRunMessage,
+ turn?: ActiveTurn,
): Promise<RuntimeActionResult | undefined> {
- if (isTaskRunMessage(message)) {
- await this.input.cursor.advance((state) => applyTaskRunMessageStep({ ...state, message }));
+ if (isAppliedRunMessage(message)) {
+ const following =
+ turn?.takeAppliedRunMessages() ?? takeLeadingAppliedRunMessages(this.input.inbox);
+ await this.applyRunMessages([message, ...following]);
return undefined;
}
return await handleWorkflowToolRunMessage({
@@ -321,7 +338,7 @@ export class SessionExecution {
interrupted = true;
continue;
case "workflow":
- await this.handleWorkflowMessage(next.message);
+ await this.handleWorkflowMessage(next.message, turn);
continue;
case "input":
case "runtime-action-result":
@@ -355,7 +372,7 @@ export class SessionExecution {
if (steering !== undefined) return steering;
const next = await turn.nextRuntimeEvent([]);
if (next === "cancelled") return next;
- if (next.kind === "workflow") await this.handleWorkflowMessage(next.message);
+ if (next.kind === "workflow") await this.handleWorkflowMessage(next.message, turn);
}
}
@@ -432,7 +449,7 @@ export class SessionExecution {
continue;
}
- const result = await this.handleWorkflowMessage(next.message);
+ const result = await this.handleWorkflowMessage(next.message, input.turn);
if (result === undefined) continue;
accept(result);
if (next.message.kind === "outcome" && next.message.usage !== undefined) {
diff --git a/packages/eve/src/execution/tasks/session.test.ts b/packages/eve/src/execution/tasks/session.test.ts
index dae0b0e7f..6187a1715 100644
--- a/packages/eve/src/execution/tasks/session.test.ts
+++ b/packages/eve/src/execution/tasks/session.test.ts
@@ -3,8 +3,8 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import type { DurableSession } from "#execution/durable-session-store.js";
import type { SessionInbox } from "#execution/session-inbox/inbox.js";
import { SessionStateCursor } from "#execution/session/state-cursor.js";
+import { applyRunMessagesStep } from "#execution/tools/workflow/apply-run-messages-step.js";
import { answerTaskCancel } from "#execution/tasks/session.js";
-import { applyTaskRunMessageStep } from "#execution/tasks/steps.js";
import {
createTask,
markTaskRunStarted,
@@ -97,7 +97,49 @@ describe("answerTaskCancel", () => {
});
});
-describe("applyTaskRunMessageStep", () => {
+describe("applyRunMessagesStep", () => {
+ it("publishes a batch's reports and task results in the order they arrived", async () => {
+ const research = startedTask(readTaskTable(undefined), "research");
+ const summarize = startedTask(research.table, "summarize");
+ const cursor = cursorFor(
+ writeTaskTable(
+ createTestSessionState({ sessionId: "session-1" }).snapshot.session,
+ summarize.table,
+ ),
+ );
+ const from = (name: string, taskId: string) => ({
+ callId: `${name}-call`,
+ input: {},
+ runId: `${name}-run`,
+ sequence: 3,
+ stepIndex: 1,
+ taskId,
+ toolName: name,
+ turnId: "turn_1",
+ });
+
+ await cursor.advance((state) =>
+ applyRunMessagesStep({
+ ...state,
+ messages: [
+ { from: from("research", research.taskId), kind: "report", update: "sources found" },
+ {
+ from: from("research", research.taskId),
+ kind: "outcome",
+ result: { output: "Alice's brief", status: "completed" },
+ },
+ { from: from("summarize", summarize.taskId), kind: "report", update: "drafting" },
+ ],
+ }),
+ );
+
+ expect(published.map((entry) => (entry as { event: { type: string } }).event.type)).toEqual([
+ "action.partial",
+ "task.settled",
+ "action.partial",
+ ]);
+ });
+
it("withdraws the questions of a task() run that fails on its own, and only those", async () => {
const research = startedTask(readTaskTable(undefined), "research");
const summarize = startedTask(research.table, "summarize");
@@ -110,22 +152,24 @@ describe("applyTaskRunMessageStep", () => {
const cursor = cursorFor(session);
await cursor.advance((state) =>
- applyTaskRunMessageStep({
+ applyRunMessagesStep({
...state,
- message: {
- from: {
- callId: "research-call",
- input: {},
- runId: "research-run",
- sequence: 3,
- stepIndex: 1,
- taskId: research.taskId,
- toolName: "research",
- turnId: "turn_1",
+ messages: [
+ {
+ from: {
+ callId: "research-call",
+ input: {},
+ runId: "research-run",
+ sequence: 3,
+ stepIndex: 1,
+ taskId: research.taskId,
+ toolName: "research",
+ turnId: "turn_1",
+ },
+ kind: "outcome",
+ result: { error: "The research service is unavailable.", status: "failed" },
},
- kind: "outcome",
- result: { error: "The research service is unavailable.", status: "failed" },
- },
+ ],
}),
);
diff --git a/packages/eve/src/execution/tasks/start.ts b/packages/eve/src/execution/tasks/start.ts
index 77ea9ff23..ae4d832be 100644
--- a/packages/eve/src/execution/tasks/start.ts
+++ b/packages/eve/src/execution/tasks/start.ts
@@ -29,7 +29,11 @@ import { createLogger, logError } from "#internal/logging.js";
import type { HarnessSessionBase } from "#harness/types.js";
import type { TaskStartedStreamEvent } from "#protocol/message.js";
import { TOO_MANY_TASKS_CODE, UNKNOWN_TASK_CODE } from "#protocol/task-tools.js";
-import type { RuntimeToolResultActionResult, WorkflowToolRunEntry } from "#shared/action-types.js";
+import type {
+ RuntimeToolResultActionResult,
+ RuntimeWorkflowTaskRequest,
+ WorkflowToolRunEntry,
+} from "#shared/action-types.js";
const log = createLogger("execution.tasks");
@@ -59,11 +63,8 @@ export async function startTaskRun(
const dispatch = { ...input, taskId };
const receipt = startReceipt(dispatch, entry.entryPoint === "serve");
const table = readTaskTable(session.state);
- const record = findTask(table, taskId);
- // Cancelled before the session could start it: there is nothing to run.
- if (record === undefined || !isTaskWorking(record)) {
- return { result: receipt, session };
- }
+ const record = startableTask(table, taskId);
+ if (record === undefined) return { result: receipt, session };
const overCap = tooManyTasks(dispatch, table);
if (overCap !== undefined) {
@@ -125,14 +126,65 @@ export async function sendToTask(input: TaskDispatchInput): Promise<TaskDispatch
};
}
+/**
+ * The entry of the run that dispatching `task` starts, or `undefined` when it
+ * starts none: a call to a running task, or a task cancelled before the
+ * session could start it. The task cap can still refuse a task's run.
+ */
+export function runEntryToStart(
+ table: TaskTable,
+ task: RuntimeWorkflowTaskRequest,
+): WorkflowToolRunEntry | undefined {
+ const { entry } = task;
+ switch (entry.entryPoint) {
+ case "execute":
+ return { entryPoint: "execute" };
+ case "task":
+ case "serve":
+ return startableTask(table, entry.taskId) === undefined ? undefined : entry;
+ case "receive":
+ return undefined;
+ }
+}
+
+/** The task's record while it still needs its run, which it doesn't once cancelled. */
+function startableTask(table: TaskTable, taskId: string): TaskRecord | undefined {
+ const record = findTask(table, taskId);
+ return record !== undefined && isTaskWorking(record) ? record : undefined;
+}
+
+/**
+ * Whether dispatching `tasks` in order starts every run {@link runEntryToStart}
+ * names. A call to a running task can take a slot under the task cap, and
+ * sending to it can fail the batch, so such a batch never qualifies.
+ */
+export function startsEveryRun(
+ table: TaskTable,
+ tasks: readonly RuntimeWorkflowTaskRequest[],
+): boolean {
+ if (tasks.some((task) => task.entry.entryPoint === "receive")) return false;
+ const starting = tasks.filter(
+ (task) => task.entry.entryPoint !== "execute" && runEntryToStart(table, task) !== undefined,
+ );
+ return hasTaskSlots(table, starting.length);
+}
+
+function runningTasks(table: TaskTable): readonly TaskRecord[] {
+ return workingTasks(table).filter((candidate) => candidate.run !== undefined);
+}
+
+/** Whether the task cap leaves room to run `count` more tasks. */
+function hasTaskSlots(table: TaskTable, count: number): boolean {
+ return runningTasks(table).length + count <= MAX_WORKING_TASKS;
+}
+
/** The `TOO_MANY_TASKS` error when the session already runs as many tasks as it may. */
function tooManyTasks(
input: TaskDispatchInput,
table: TaskTable,
): RuntimeToolResultActionResult | undefined {
- const running = workingTasks(table).filter((candidate) => candidate.run !== undefined);
- if (running.length < MAX_WORKING_TASKS) return undefined;
- const runningIds = running.map((candidate) => candidate.id);
+ if (hasTaskSlots(table, 1)) return undefined;
+ const runningIds = runningTasks(table).map((candidate) => candidate.id);
return createRuntimeToolResultFromValue({
callId: input.task.callId,
isError: true,
diff --git a/packages/eve/src/execution/tasks/steps.ts b/packages/eve/src/execution/tasks/steps.ts
index fd97599da..ab62c1d8d 100644
--- a/packages/eve/src/execution/tasks/steps.ts
+++ b/packages/eve/src/execution/tasks/steps.ts
@@ -54,15 +54,11 @@ export type TaskRunMessage = Extract<
const TASK_CANCEL_REASON = "The task was cancelled.";
-/** Applies one message from a task's run: started, a reply, usage no reply carried, or the run's outcome. */
-export async function applyTaskRunMessageStep(
- input: SessionStepState & { readonly message: TaskRunMessage },
-): Promise<SessionStateTransition> {
- "use step";
- return await withSessionStateDelta(input, applyTaskRunMessage);
-}
-
-async function applyTaskRunMessage(
+/**
+ * Applies one message from a task's run: started, a reply, usage no reply
+ * carried, or the run's outcome. Call from a step and adopt the result.
+ */
+export async function applyTaskRunMessage(
input: SessionStepState & { readonly message: TaskRunMessage },
): Promise<PublishedSessionEvents> {
const { message } = input;
diff --git a/packages/eve/src/execution/tasks/task-run-usage.test.ts b/packages/eve/src/execution/tasks/task-run-usage.test.ts
index bd247f6bf..3bc1f5c2d 100644
--- a/packages/eve/src/execution/tasks/task-run-usage.test.ts
+++ b/packages/eve/src/execution/tasks/task-run-usage.test.ts
@@ -82,6 +82,7 @@ function sessionWithTask(input: {
claimSessionHooks: vi.fn(),
onDelivery: () => () => {},
onInterrupt: () => () => {},
+ takeLeading: () => [],
} as Partial<SessionInbox> as SessionInbox;
const cursor = new SessionStateCursor({
history: [],
diff --git a/packages/eve/src/execution/tools/workflow/apply-run-messages-step.ts b/packages/eve/src/execution/tools/workflow/apply-run-messages-step.ts
new file mode 100644
index 000000000..0607094e7
--- /dev/null
+++ b/packages/eve/src/execution/tools/workflow/apply-run-messages-step.ts
@@ -0,0 +1,96 @@
+import { publishSessionEvents, type SessionStepState } from "#execution/publish-session-events.js";
+import {
+ withSessionStateDelta,
+ type SessionStateTransition,
+} from "#execution/session/state-delta.js";
+import { applyTaskRunMessage, type TaskRunMessage } from "#execution/tasks/steps.js";
+import type {
+ WorkflowToolRunAgentStartedMessage,
+ WorkflowToolRunMessage,
+ WorkflowToolRunRef,
+} from "#execution/tools/workflow/messages.js";
+import { createRuntimeToolResultFromValue } from "#harness/action-result-helpers.js";
+import {
+ createActionPartialEvent,
+ createAgentStartedEvent,
+ type UnstampedMessageStreamEvent,
+} from "#protocol/message.js";
+import type { JsonValue } from "#shared/json.js";
+
+/** A workflow tool run's `ctx.report()` update, as `action.partial`. */
+function workflowToolRunReportEvent(
+ from: WorkflowToolRunRef,
+ update: JsonValue,
+): UnstampedMessageStreamEvent {
+ return createActionPartialEvent({
+ result: createRuntimeToolResultFromValue({
+ callId: from.callId,
+ output: update,
+ toolName: from.toolName,
+ }),
+ sequence: from.sequence,
+ stepIndex: from.stepIndex,
+ turnId: from.turnId,
+ });
+}
+
+/** `agent.started` for a session a workflow tool run opened. */
+function agentStartedEvent(
+ parentSessionId: string,
+ { from, session }: WorkflowToolRunAgentStartedMessage,
+): UnstampedMessageStreamEvent {
+ return createAgentStartedEvent({
+ callId: from.callId,
+ name: session.name,
+ parentSessionId,
+ remote:
+ session.kind === "remote"
+ ? {
+ url: session.url,
+ ...(session.resolverId !== undefined && { resolverId: session.resolverId }),
+ }
+ : undefined,
+ sessionId: session.sessionId,
+ ...(from.taskId !== undefined && { taskId: from.taskId }),
+ turnId: from.turnId,
+ });
+}
+
+/** A run's message the session applies as it reads it, which answers no call a turn waits on. */
+export type AppliedRunMessage =
+ | Extract<WorkflowToolRunMessage, { readonly kind: "agent-started" | "report" }>
+ // Only a task's run reports these to the task table; an `execute` run's outcome answers its call.
+ | (TaskRunMessage & { readonly from: { readonly taskId: string } });
+
+/**
+ * Applies run messages in the order they arrived, in one step however many
+ * there are: a fan-out's starts, reports, and replies would otherwise cost a
+ * step each.
+ */
+export async function applyRunMessagesStep(
+ input: SessionStepState & { readonly messages: readonly AppliedRunMessage[] },
+): Promise<SessionStateTransition> {
+ "use step";
+ return await withSessionStateDelta(input, async ({ messages, ...target }) => {
+ let state: SessionStepState = target;
+ // Consecutive starts and reports publish together, as one turn's events do.
+ let events: UnstampedMessageStreamEvent[] = [];
+ const publish = async (): Promise<void> => {
+ if (events.length === 0) return;
+ state = { ...state, ...(await publishSessionEvents(state, events)) };
+ events = [];
+ };
+ for (const message of messages) {
+ if (message.kind === "agent-started") {
+ events.push(agentStartedEvent(state.sessionState.sessionId, message));
+ } else if (message.kind === "report") {
+ events.push(workflowToolRunReportEvent(message.from, message.update));
+ } else {
+ await publish();
+ state = { ...state, ...(await applyTaskRunMessage({ ...state, message })) };
+ }
+ }
+ await publish();
+ return { serializedContext: state.serializedContext, sessionState: state.sessionState };
+ });
+}
diff --git a/packages/eve/src/execution/tools/workflow/ask.ts b/packages/eve/src/execution/tools/workflow/ask.ts
index f71080d72..999a503b3 100644
--- a/packages/eve/src/execution/tools/workflow/ask.ts
+++ b/packages/eve/src/execution/tools/workflow/ask.ts
@@ -77,7 +77,6 @@ const UNAVAILABLE: ToolInputResponse = { status: "unavailable" };
interface PendingAsk {
readonly resolve: (response: ToolInputResponse) => void;
- readonly reject: (error: unknown) => void;
/** Sends the session the request to withdraw the question; unset once sent. */
withdraw: (() => Promise<void>) | undefined;
}
@@ -109,8 +108,8 @@ export class WorkflowToolRunAsks {
this.opened += 1;
const requestId = `${this.runId}-ask-${String(this.opened)}`;
let entry!: PendingAsk;
- const answer = new Promise<ToolInputResponse>((resolve, reject) => {
- entry = { reject, resolve, withdraw: undefined };
+ const answer = new Promise<ToolInputResponse>((resolve) => {
+ entry = { resolve, withdraw: undefined };
});
this.pending.set(requestId, entry);
entry.withdraw = send(requestId);
@@ -127,7 +126,7 @@ export class WorkflowToolRunAsks {
const withdraw = entry?.withdraw;
if (entry === undefined || withdraw === undefined) return;
entry.withdraw = undefined;
- const sending = withdraw().catch((error: unknown) => this.fail(requestId, error));
+ const sending = withdraw();
this.withdrawing.add(sending);
void sending.then(() => this.withdrawing.delete(sending));
}
@@ -151,10 +150,6 @@ export class WorkflowToolRunAsks {
this.take(decision.requestId)?.resolve(response);
}
- fail(requestId: string, error: unknown): void {
- this.take(requestId)?.reject(error);
- }
-
/** The session stopped the work, so it answers none of its questions anymore. */
cancelAll(): void {
for (const requestId of this.pending.keys()) {
@@ -199,7 +194,6 @@ export function ask(
replyTo,
request: { control, kind: "ask", request },
});
- sent.catch((error: unknown) => asks.fail(replyTo, error));
// The withdrawal must not overtake the request it withdraws.
return () => sent.then(() => owner.send({ control, from, kind: "withdraw", replyTo }));
});
diff --git a/packages/eve/src/execution/tools/workflow/emit-workflow-tool-run-report-step.ts b/packages/eve/src/execution/tools/workflow/emit-workflow-tool-run-report-step.ts
deleted file mode 100644
index c86393978..000000000
--- a/packages/eve/src/execution/tools/workflow/emit-workflow-tool-run-report-step.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import { publishSessionEvents, type SessionStepState } from "#execution/publish-session-events.js";
-import {
- withSessionStateDelta,
- type SessionStateTransition,
-} from "#execution/session/state-delta.js";
-import type {
- WorkflowToolRunAgentStartedMessage,
- WorkflowToolRunRef,
-} from "#execution/tools/workflow/messages.js";
-import { createRuntimeToolResultFromValue } from "#harness/action-result-helpers.js";
-import { createActionPartialEvent, createAgentStartedEvent } from "#protocol/message.js";
-import type { JsonValue } from "#shared/json.js";
-
-/** Publishes a workflow tool run's `ctx.report()` update as `action.partial`. */
-export async function emitWorkflowToolRunReportStep(
- input: SessionStepState & {
- readonly from: WorkflowToolRunRef;
- readonly update: JsonValue;
- },
-): Promise<SessionStateTransition> {
- "use step";
-
- const event = createActionPartialEvent({
- result: createRuntimeToolResultFromValue({
- callId: input.from.callId,
- output: input.update,
- toolName: input.from.toolName,
- }),
- sequence: input.from.sequence,
- stepIndex: input.from.stepIndex,
- turnId: input.from.turnId,
- });
- return await withSessionStateDelta(input, (target) => publishSessionEvents(target, [event]));
-}
-
-/** Publishes `agent.started`, in order, for sessions workflow tool runs opened. */
-export async function emitAgentStartedStep(
- input: SessionStepState & {
- readonly messages: readonly WorkflowToolRunAgentStartedMessage[];
- },
-): Promise<SessionStateTransition> {
- "use step";
-
- const events = input.messages.map(({ from, session }) =>
- createAgentStartedEvent({
- callId: from.callId,
- name: session.name,
- parentSessionId: input.sessionState.sessionId,
- remote:
- session.kind === "remote"
- ? {
- url: session.url,
- ...(session.resolverId !== undefined && { resolverId: session.resolverId }),
- }
- : undefined,
- sessionId: session.sessionId,
- ...(from.taskId !== undefined && { taskId: from.taskId }),
- turnId: from.turnId,
- }),
- );
- return await withSessionStateDelta(input, (target) => publishSessionEvents(target, events));
-}
diff --git a/packages/eve/src/execution/tools/workflow/interrupt.test.ts b/packages/eve/src/execution/tools/workflow/interrupt.test.ts
new file mode 100644
index 000000000..3aeaa2e08
--- /dev/null
+++ b/packages/eve/src/execution/tools/workflow/interrupt.test.ts
@@ -0,0 +1,70 @@
+import { beforeEach, expect, it, vi } from "vitest";
+
+import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";
+import { interruptWorkflowToolRun } from "#execution/tools/workflow/interrupt.js";
+
+const mocks = vi.hoisted(() => ({ getRun: vi.fn(), resumeHook: vi.fn() }));
+
+vi.mock("#internal/workflow/runtime.js", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("#internal/workflow/runtime.js")>()),
+ getRun: mocks.getRun,
+ resumeHook: mocks.resumeHook,
+}));
+
+const run = { hookToken: "hold-control", runId: "hold-run" };
+
+beforeEach(() => {
+ vi.resetAllMocks();
+});
+
+it("interrupts a run that registers its control hook after the turn is steered", async () => {
+ // Alice steers the turn just as it starts the run, before the run's first suspension.
+ mocks.resumeHook
+ .mockRejectedValueOnce(new HookNotFoundError("hold-control"))
+ .mockRejectedValueOnce(new HookNotFoundError("hold-control"))
+ .mockResolvedValueOnce({ runId: "hold-run" });
+ mocks.getRun.mockReturnValue({ status: Promise.resolve("running") });
+
+ await interruptWorkflowToolRun(run);
+
+ expect(mocks.resumeHook).toHaveBeenCalledTimes(3);
+ expect(mocks.resumeHook).toHaveBeenLastCalledWith("hold-control", { kind: "interrupt" });
+});
+
+it("leaves a run that already ended alone", async () => {
+ mocks.resumeHook.mockRejectedValue(new HookNotFoundError("hold-control"));
+ mocks.getRun.mockReturnValue({ status: Promise.resolve("completed") });
+
+ await interruptWorkflowToolRun(run);
+
+ expect(mocks.resumeHook).toHaveBeenCalledOnce();
+});
+
+it("fails instead of dropping the interrupt when the run registers its hook after the deadline", async () => {
+ vi.useFakeTimers();
+ try {
+ // Bob's deploy run is slow to start and registers its control hook only after 40 seconds.
+ const registeredAt = Date.now() + 40_000;
+ mocks.resumeHook.mockImplementation(async () => {
+ if (Date.now() < registeredAt) throw new HookNotFoundError("hold-control");
+ return { runId: "hold-run" };
+ });
+ mocks.getRun.mockReturnValue({ status: Promise.resolve("running") });
+
+ const attempt = expect(interruptWorkflowToolRun(run)).rejects.toThrow(
+ 'Workflow tool run "hold-run" did not start taking commands within 30 seconds',
+ );
+ await vi.advanceTimersByTimeAsync(31_000);
+ await attempt;
+
+ // The runtime retries the failed step, which delivers the interrupt once the hook exists.
+ await vi.advanceTimersByTimeAsync(10_000);
+ await interruptWorkflowToolRun(run);
+ expect(mocks.resumeHook).toHaveBeenLastCalledWith("hold-control", { kind: "interrupt" });
+ await expect(mocks.resumeHook.mock.results.at(-1)?.value).resolves.toEqual({
+ runId: "hold-run",
+ });
+ } finally {
+ vi.useRealTimers();
+ }
+});
diff --git a/packages/eve/src/execution/tools/workflow/interrupt.ts b/packages/eve/src/execution/tools/workflow/interrupt.ts
index 7bb4096ee..cbbb2de80 100644
--- a/packages/eve/src/execution/tools/workflow/interrupt.ts
+++ b/packages/eve/src/execution/tools/workflow/interrupt.ts
@@ -1,13 +1,36 @@
import type { WorkflowToolRunControlMessage } from "#execution/tools/workflow/messages.js";
-import { resumeHookStep } from "#execution/tools/workflow/resume-hook-step.js";
import type { WorkflowToolRunAddress } from "#execution/tools/workflow/types.js";
+import { isTaskWorkflowTargetGone } from "#execution/tasks/workflow-target.js";
+import { hasRunEnded, pollUntil } from "#execution/workflow-runtime.js";
+import { resumeHook } from "#internal/workflow/runtime.js";
const INTERRUPT: WorkflowToolRunControlMessage = { kind: "interrupt" };
+/** How long a steered turn waits for a run that is still starting to take its interrupt. */
+const RUN_START_TIMEOUT_MS = 30_000;
+
/**
- * Aborts the `execute` call's `abortSignal`. A run that already finished has nothing
- * left to interrupt, so a missing hook is not an error.
+ * Aborts the `execute` call's `abortSignal`. A turn steered right after it
+ * started the run can get here before the run registers its control hook, so
+ * a live run's missing hook is waited for. A run that ended has nothing left
+ * to interrupt. A run still without its hook at the deadline fails the step,
+ * which the runtime retries, since the interrupt was not delivered.
*/
export async function interruptWorkflowToolRun(run: WorkflowToolRunAddress): Promise<void> {
- await resumeHookStep(run.hookToken, INTERRUPT, { ifPresent: true });
+ "use step";
+
+ const settled = await pollUntil(async () => {
+ try {
+ await resumeHook(run.hookToken, INTERRUPT);
+ return true;
+ } catch (error) {
+ if (!isTaskWorkflowTargetGone(error)) throw error;
+ }
+ return (await hasRunEnded(run.runId)) ? true : undefined;
+ }, RUN_START_TIMEOUT_MS);
+ if (settled === undefined) {
+ throw new Error(
+ `Workflow tool run "${run.runId}" did not start taking commands within ${RUN_START_TIMEOUT_MS / 1000} seconds, so it has not received the interrupt yet.`,
+ );
+ }
}
diff --git a/packages/eve/src/execution/tools/workflow/messages.ts b/packages/eve/src/execution/tools/workflow/messages.ts
index dd470c55a..2ca692b4f 100644
--- a/packages/eve/src/execution/tools/workflow/messages.ts
+++ b/packages/eve/src/execution/tools/workflow/messages.ts
@@ -155,6 +155,49 @@ export type WorkflowToolRunMessage =
| ({ readonly kind: "usage" } & WorkflowToolRunUsageMessage)
| ({ readonly kind: "outcome" } & WorkflowToolRunOutcomeMessage);
+/**
+ * Messages a run relays to its session in one delivery, in the order its body
+ * sent them. The session's inbox reads them as separate messages.
+ */
+export interface WorkflowToolRunMessageBatch {
+ readonly kind: "workflow-batch";
+ readonly messages: readonly WorkflowToolRunMessage[];
+}
+
+/**
+ * Approximate size cap for one batch of run messages, both a run's relay and
+ * the session step that applies them. Workflow keeps a hook payload or step
+ * input up to 64 KB inline in the event log and moves a larger one to blob
+ * storage, which every replay then reads back.
+ */
+const RUN_MESSAGE_BATCH_MAX_CHARS = 64_000;
+
+/**
+ * Returns a predicate that admits messages, in order, while their batch stays
+ * under the size cap. The first message always fits, so one larger than the
+ * cap still goes, alone.
+ */
+export function runMessageBatchBudget(): (message: WorkflowToolRunMessage) => boolean {
+ let used = 0;
+ let admitted = false;
+ return (message) => {
+ const size = serializedLength(message);
+ if (admitted && used + size > RUN_MESSAGE_BATCH_MAX_CHARS) return false;
+ used += size;
+ admitted = true;
+ return true;
+ };
+}
+
+function serializedLength(value: unknown): number {
+ try {
+ return JSON.stringify(value)?.length ?? 0;
+ } catch {
+ // Values JSON can't encode, such as a bigint, still serialize for the workflow.
+ return Number.POSITIVE_INFINITY;
+ }
+}
+
/**
* A later call to a `serve` task, which its run hands to `receive()`. It
* carries everything the session knew of the call when it admitted it, as a
diff --git a/packages/eve/src/execution/tools/workflow/owner.test.ts b/packages/eve/src/execution/tools/workflow/owner.test.ts
new file mode 100644
index 000000000..a87352ce2
--- /dev/null
+++ b/packages/eve/src/execution/tools/workflow/owner.test.ts
@@ -0,0 +1,105 @@
+import { expect, it, vi } from "vitest";
+
+import type { WorkflowToolRunMessage } from "#execution/tools/workflow/messages.js";
+import { raceChannelReads } from "#execution/tools/workflow/owner-channels.js";
+import { openWorkflowToolRunOwnerInbox } from "#execution/tools/workflow/owner.js";
+import { createBlockingWorkflow } from "#execution/tools/workflow/workflow-owner-blocking.js";
+import type { WorkflowToolRunInput } from "#execution/tools/workflow/types.js";
+
+const mocks = vi.hoisted(() => ({ resumeHookStep: vi.fn(async () => {}) }));
+
+vi.mock("#compiled/@workflow/core/index.js", () => ({
+ createHook: () => ({ [Symbol.asyncIterator]: () => ({ next: () => new Promise(() => {}) }) }),
+}));
+vi.mock("#execution/tools/workflow/resume-hook-step.js", () => ({
+ resumeHookStep: mocks.resumeHookStep,
+}));
+
+const from = {
+ callId: "call-1",
+ input: {},
+ runId: "run-1",
+ sequence: 0,
+ stepIndex: 0,
+ taskId: "task-1",
+ toolName: "triage_issues",
+ turnId: "turn-1",
+};
+
+function opened(sessionId: string): Extract<WorkflowToolRunMessage, { kind: "agent-started" }> {
+ return {
+ from,
+ kind: "agent-started",
+ session: {
+ continuationToken: `subagent:${sessionId}`,
+ kind: "local",
+ name: "reviewer",
+ nodeId: "reviewer",
+ sessionId,
+ },
+ };
+}
+
+it("relays what a fan-out sent between relays as one delivery, in order", async () => {
+ const inbox = openWorkflowToolRunOwnerInbox();
+ const owner = createBlockingWorkflow({
+ owner: { inbox: "session-inbox" },
+ } as WorkflowToolRunInput);
+ // Alice's triage opens three reviewers before the run reads its inbox.
+ for (const sessionId of ["child-1", "child-2", "child-3"])
+ await inbox.owner.send(opened(sessionId));
+
+ const read = await raceChannelReads([inbox.reader]);
+ if (read.next.done) throw new Error("The inbox ended.");
+ await owner.relay(read.next.value);
+
+ expect(inbox.owner.sent).toBe(3);
+ expect(mocks.resumeHookStep).toHaveBeenCalledExactlyOnceWith("session-inbox", {
+ kind: "workflow-batch",
+ messages: [opened("child-1"), opened("child-2"), opened("child-3")],
+ });
+});
+
+it("splits what queued up into deliveries of at most 64,000 characters, in order", async () => {
+ const inbox = openWorkflowToolRunOwnerInbox();
+ const report = (
+ label: string,
+ size: number,
+ ): Extract<WorkflowToolRunMessage, { kind: "report" }> => ({
+ from,
+ kind: "report",
+ update: label.padEnd(size, "."),
+ });
+ // Alice's reviewers report long findings faster than the run relays them.
+ const sent = [
+ report("first", 25_000),
+ report("second", 25_000),
+ report("third", 25_000),
+ report("oversized", 70_000),
+ report("fifth", 10),
+ report("sixth", 10),
+ ];
+ for (const message of sent) await inbox.owner.send(message);
+
+ const deliveries: WorkflowToolRunMessage[][] = [];
+ while (deliveries.flat().length < sent.length) {
+ const read = await raceChannelReads([inbox.reader]);
+ if (read.next.done) throw new Error("The inbox ended.");
+ deliveries.push(read.next.value);
+ }
+
+ expect(deliveries).toEqual([sent.slice(0, 2), sent.slice(2, 3), sent.slice(3, 4), sent.slice(4)]);
+});
+
+it("relays a lone message as itself", async () => {
+ mocks.resumeHookStep.mockClear();
+ const owner = createBlockingWorkflow({
+ owner: { inbox: "session-inbox" },
+ } as WorkflowToolRunInput);
+
+ await owner.relay([opened("child-1")]);
+
+ expect(mocks.resumeHookStep).toHaveBeenCalledExactlyOnceWith("session-inbox", opened("child-1"), {
+ ifPresent: false,
+ });
+});
diff --git a/packages/eve/src/execution/tools/workflow/owner.ts b/packages/eve/src/execution/tools/workflow/owner.ts
index a9fdf8cef..e06975c40 100644
--- a/packages/eve/src/execution/tools/workflow/owner.ts
+++ b/packages/eve/src/execution/tools/workflow/owner.ts
@@ -1,8 +1,8 @@
-import { createHook } from "#compiled/@workflow/core/index.js";
-import type {
- WorkflowToolRunMessage,
- WorkflowToolRunRequestMessage,
- WorkflowToolAuthorizationRequest,
+import {
+ runMessageBatchBudget,
+ type WorkflowToolRunMessage,
+ type WorkflowToolRunRequestMessage,
+ type WorkflowToolAuthorizationRequest,
} from "#execution/tools/workflow/messages.js";
import {
createChannelReader,
@@ -18,29 +18,58 @@ import { resumeHookStep } from "#execution/tools/workflow/resume-hook-step.js";
export interface WorkflowToolRunInbox {
/** Messages that reached the run's inbox so far. */
readonly sent: number;
- send(message: Exclude<WorkflowToolRunMessage, { readonly kind: "outcome" }>): Promise<void>;
+ send(message: WorkflowToolRunBodyMessage): Promise<void>;
}
+/** What a body sends its session through the run: everything but the outcome, which the run sends. */
+type WorkflowToolRunBodyMessage = Exclude<WorkflowToolRunMessage, { readonly kind: "outcome" }>;
+
export interface WorkflowToolRunOwnerInbox {
readonly owner: WorkflowToolRunInbox;
- readonly reader: ChannelReader<"workflow", WorkflowToolRunMessage>;
+ /** What was sent since the last read, in order, up to a batch's size cap. */
+ readonly reader: ChannelReader<"workflow", WorkflowToolRunBodyMessage[]>;
}
-/** Receives body messages before routing them to the waiting turn. */
+/**
+ * Receives body messages before routing them to the waiting turn. The body
+ * and the run share one workflow, which replays both deterministically, so
+ * the inbox is an in-memory queue; a durable hop would add a step and a
+ * replay to every message. The run relays what queued up together, within a
+ * size cap, so a fan-out's messages share a relay. A relay can run before hooks created in
+ * the same suspension are registered, so a body that hands the session a
+ * hook token registers that hook before sending it.
+ */
export function openWorkflowToolRunOwnerInbox(): WorkflowToolRunOwnerInbox {
- const hook = createHook<WorkflowToolRunMessage>();
+ const queued: WorkflowToolRunBodyMessage[] = [];
+ let wake: (() => void) | undefined;
let sent = 0;
+ async function* read(): AsyncGenerator<WorkflowToolRunBodyMessage[]> {
+ for (;;) {
+ if (queued.length > 0) {
+ const admits = runMessageBatchBudget();
+ const overflow = queued.findIndex((message) => !admits(message));
+ yield queued.splice(0, overflow === -1 ? queued.length : overflow);
+ continue;
+ }
+ await new Promise<void>((resolve) => {
+ wake = resolve;
+ });
+ }
+ }
return {
owner: {
get sent() {
return sent;
},
async send(message) {
- await resumeHookStep(hook.token, message);
+ queued.push(message);
sent += 1;
+ const woken = wake;
+ wake = undefined;
+ woken?.();
},
},
- reader: createChannelReader("workflow", hook),
+ reader: createChannelReader("workflow", read()),
};
}
diff --git a/packages/eve/src/execution/tools/workflow/serve.test.ts b/packages/eve/src/execution/tools/workflow/serve.test.ts
index 83117fcf7..85d8160a4 100644
--- a/packages/eve/src/execution/tools/workflow/serve.test.ts
+++ b/packages/eve/src/execution/tools/workflow/serve.test.ts
@@ -44,14 +44,17 @@ vi.mock("#execution/agent-sessions/steps.js", () => ({
vi.mock("#compiled/@workflow/core/index.js", () => ({
createHook: (options?: { readonly token?: string }) =>
options?.token === "control"
- ? (async function* () {
- while (true) {
- const command = mocks.commands.shift();
- if (command !== undefined) yield command;
- else await new Promise<void>((resolve) => (mocks.wakeCommands = resolve));
- }
- })()
- : // Agent turns and the run's inbox never report; only what the run sends matters here.
+ ? Object.assign(
+ (async function* () {
+ while (true) {
+ const command = mocks.commands.shift();
+ if (command !== undefined) yield command;
+ else await new Promise<void>((resolve) => (mocks.wakeCommands = resolve));
+ }
+ })(),
+ { getConflict: async () => null },
+ )
+ : // Agent turns never report; only what the run sends matters here.
{
[Symbol.asyncIterator]: () => ({ next: () => new Promise(() => {}) }),
token: "agent-turn",
diff --git a/packages/eve/src/execution/tools/workflow/start.ts b/packages/eve/src/execution/tools/workflow/start.ts
index e367efbf8..ce7654e23 100644
--- a/packages/eve/src/execution/tools/workflow/start.ts
+++ b/packages/eve/src/execution/tools/workflow/start.ts
@@ -58,15 +58,33 @@ export interface StartWorkflowTaskInput {
};
readonly owner: WorkflowToolRunOwner;
readonly parentSession: SessionParent | undefined;
+ /**
+ * The call's run, when its batch already started it alongside the others.
+ * The dispatch records it in place of starting one.
+ */
+ readonly prestarted?: PrestartedWorkflowToolRun;
readonly session: HarnessSessionBase;
readonly task: RuntimeWorkflowTaskRequest;
}
+/** A call's run its batch started early, and the entry it was started with. */
+export interface PrestartedWorkflowToolRun {
+ readonly entry: WorkflowToolRunEntry;
+ readonly run: Promise<WorkflowToolRunAddress>;
+}
+
/** Starts the run for one call, which invokes `entry`. */
export async function startWorkflowToolCallRun(
input: StartWorkflowTaskInput,
entry: WorkflowToolRunEntry,
): Promise<WorkflowToolRunAddress> {
+ const { prestarted } = input;
+ if (prestarted !== undefined) {
+ if (!isSameRunEntry(prestarted.entry, entry)) {
+ throw new Error(`Call "${input.task.callId}" was started for a different entry point.`);
+ }
+ return await prestarted.run;
+ }
const { task, batchEvent, session } = input;
return await startWorkflowToolRun({
agentContext: input.agentContext,
@@ -87,6 +105,12 @@ export async function startWorkflowToolCallRun(
});
}
+function isSameRunEntry(a: WorkflowToolRunEntry, b: WorkflowToolRunEntry): boolean {
+ if (a.entryPoint === "execute" || b.entryPoint === "execute")
+ return a.entryPoint === b.entryPoint;
+ return a.entryPoint === b.entryPoint && a.taskId === b.taskId;
+}
+
/** Starts the run of an `execute` call the turn waits on and records it on the owning session. */
export async function startWorkflowTask(input: StartWorkflowTaskInput): Promise<{
readonly result?: RuntimeToolResultActionResult;
diff --git a/packages/eve/src/execution/tools/workflow/step.ts b/packages/eve/src/execution/tools/workflow/step.ts
index 4509c022f..669f7775c 100644
--- a/packages/eve/src/execution/tools/workflow/step.ts
+++ b/packages/eve/src/execution/tools/workflow/step.ts
@@ -220,6 +220,10 @@ async function reportAuthorization(
const event = runSignIn(run.from, challenge, outcome);
const acknowledged = createHook<void>();
try {
+ // The relay can run before this suspension registers the hook, and the
+ // session's acknowledgement skips a hook it can't find. A generated token
+ // can't conflict, so this only waits for registration.
+ await acknowledged.getConflict();
await withAbort(
run.owner.send({
kind: "request",
diff --git a/packages/eve/src/execution/tools/workflow/workflow-owner-blocking.ts b/packages/eve/src/execution/tools/workflow/workflow-owner-blocking.ts
index fc425af80..f9ca09945 100644
--- a/packages/eve/src/execution/tools/workflow/workflow-owner-blocking.ts
+++ b/packages/eve/src/execution/tools/workflow/workflow-owner-blocking.ts
@@ -1,10 +1,12 @@
import { createHook } from "#compiled/@workflow/core/index.js";
+import { isHookConflictError } from "#execution/hook-ownership.js";
import {
createChannelReader,
type ChannelReader,
} from "#execution/tools/workflow/owner-channels.js";
import type {
WorkflowToolRunMessage,
+ WorkflowToolRunMessageBatch,
WorkflowToolRunControlMessage,
} from "#execution/tools/workflow/messages.js";
import { resumeHookStep } from "#execution/tools/workflow/resume-hook-step.js";
@@ -13,18 +15,48 @@ import type { WorkflowToolRunInput } from "#execution/tools/workflow/types.js";
export interface BlockingWorkflowOwner {
/** The session's commands, from the run's control hook. */
readonly commands: ChannelReader<"control", WorkflowToolRunControlMessage>;
+ /**
+ * Waits until the control hook is registered, so the session's commands
+ * reach the run, and resolves `false` when another run already holds its
+ * token. A pending wait keeps the suspension that registers the hook from
+ * running its steps inline, so call it only once the run needs the answer.
+ */
+ register(): Promise<boolean>;
handleMessage(message: WorkflowToolRunMessage): Promise<void>;
+ /**
+ * Relays the body's messages to the session in one delivery, which is one
+ * durable write: the session gets all of them or none, never a prefix.
+ */
+ relay(messages: readonly WorkflowToolRunMessage[]): Promise<void>;
}
/** The run's link to its session: commands arrive on its control hook, and its messages go to the session's inbox. */
export function createBlockingWorkflow(input: WorkflowToolRunInput): BlockingWorkflowOwner {
const hook = createHook<WorkflowToolRunControlMessage>({ token: input.hookToken });
+ let registered: Promise<boolean> | undefined;
+ const handleMessage = (message: WorkflowToolRunMessage): Promise<void> =>
+ resumeHookStep(input.owner.inbox, message, {
+ ifPresent: message.kind === "outcome" && message.result.status === "cancelled",
+ });
return {
commands: createChannelReader("control", hook),
- handleMessage(message: WorkflowToolRunMessage) {
- return resumeHookStep(input.owner.inbox, message, {
- ifPresent: message.kind === "outcome" && message.result.status === "cancelled",
- });
+ register() {
+ registered ??= hook.getConflict().then(
+ (conflict) => conflict === null,
+ // A World that can't name the holder rejects instead.
+ (error: unknown) => {
+ if (isHookConflictError(error)) return false;
+ throw error;
+ },
+ );
+ return registered;
+ },
+ handleMessage,
+ relay(messages) {
+ // A lone message keeps the shape every session reads.
+ if (messages.length === 1) return handleMessage(messages[0]!);
+ const batch: WorkflowToolRunMessageBatch = { kind: "workflow-batch", messages };
+ return resumeHookStep(input.owner.inbox, batch);
},
};
}
diff --git a/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts b/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts
index 3d77130e7..820c59b51 100644
--- a/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts
+++ b/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts
@@ -588,7 +588,7 @@ describe("workflow tools", () => {
expect(filterEventsByType(settled, "action.partial")).toHaveLength(1);
const inputs = await readStepInputs(run.runId);
- const reportInputs = inputs.get("emitWorkflowToolRunReportStep") ?? [];
+ const reportInputs = inputs.get("applyRunMessagesStep") ?? [];
expect(reportInputs).toHaveLength(1);
expect(reportInputs[0]).not.toContain(earlyNote);
expect(inputs.get("turnStep")?.at(-1)).toContain(earlyNote);
diff --git a/packages/eve/src/execution/tools/workflow/workflow.test.ts b/packages/eve/src/execution/tools/workflow/workflow.test.ts
index 7baefb722..fa15c7953 100644
--- a/packages/eve/src/execution/tools/workflow/workflow.test.ts
+++ b/packages/eve/src/execution/tools/workflow/workflow.test.ts
@@ -105,7 +105,7 @@ it("emits every persisted report before the terminal outcome", async () => {
(async function* () {
// The body settles before the persisted report reaches its owner.
await new Promise<void>((resolve) => setTimeout(resolve, 0));
- yield report;
+ yield [report];
})(),
),
});
@@ -194,7 +194,7 @@ it.each(["completed", "failed", "cancelled", "throw", "blocked"] as const)(
it("preserves the pending inbox read across cancellation and drains the report before settling", async () => {
const controller = new AbortController();
- const pending = Promise.withResolvers<IteratorResult<WorkflowToolRunMessage>>();
+ const pending = Promise.withResolvers<IteratorResult<WorkflowToolRunMessage[]>>();
const next = vi.fn(() => pending.promise);
const report: WorkflowToolRunMessage = {
from: {
@@ -219,7 +219,7 @@ it("preserves the pending inbox read across cancellation and drains the report b
await vi.waitFor(() => expect(next).toHaveBeenCalledOnce());
controller.abort(new Error("stop"));
await vi.waitFor(() => expect(mocks.sleep).toHaveBeenCalledOnce());
- pending.resolve({ done: false, value: report });
+ pending.resolve({ done: false, value: [report] });
await completion;
expect(mocks.deliver).toHaveBeenNthCalledWith(1, "parent", report, { ifPresent: false });
expect(next).toHaveBeenCalledOnce();
@@ -234,6 +234,13 @@ it("preserves the pending inbox read across cancellation and drains the report b
);
});
+/** A relay that hands the session each message in turn; owner.test covers batching. */
+function relayThrough(deliver: (message: never) => unknown) {
+ return async (messages: readonly WorkflowToolRunMessage[]): Promise<void> => {
+ for (const message of messages) await deliver(message as never);
+ };
+}
+
function setControl(controller: AbortController) {
const { signal } = controller;
mocks.body.runSignal = signal;
@@ -253,6 +260,8 @@ function setControl(controller: AbortController) {
mocks.deliver("parent", message, {
ifPresent: message.kind === "outcome" && message.result.status === "cancelled",
}),
+ register: async () => true,
+ relay: relayThrough((message) => mocks.deliver("parent", message, { ifPresent: false })),
});
}
@@ -286,7 +295,12 @@ it("applies cancellation buffered during the last report delivery before publish
await vi.waitFor(() => expect(commands.landed).toHaveLength(1));
}
});
- mocks.owner.mockReturnValue({ commands, handleMessage: deliver });
+ mocks.owner.mockReturnValue({
+ commands,
+ handleMessage: deliver,
+ register: async () => true,
+ relay: relayThrough(deliver),
+ });
mocks.body.runSignal = controller.signal;
mocks.applyCommand.mockImplementation(() => controller.abort(new Error("stop")));
mocks.sleep.mockReturnValue(new Promise<void>(() => {}));
@@ -296,7 +310,7 @@ it("applies cancellation buffered during the last report delivery before publish
"workflow",
(async function* () {
await new Promise<void>((resolve) => setTimeout(resolve, 0));
- yield report;
+ yield [report];
await new Promise<void>(() => {});
})(),
),
@@ -317,6 +331,8 @@ it("keeps waiting for the body after the control hook closes", async () => {
mocks.owner.mockReturnValue({
commands: createChannelReader("control", (async function* () {})()),
handleMessage: mocks.deliver,
+ relay: relayThrough(mocks.deliver),
+ register: async () => true,
});
mocks.body.runSignal = new AbortController().signal;
mocks.runBody.mockResolvedValue({ status: "completed", output: "done" });
@@ -337,6 +353,137 @@ it("keeps waiting for the body after the control hook closes", async () => {
);
});
+it("reports a task started once its control hook is registered, without holding its body back", async () => {
+ const registered = Promise.withResolvers<void>();
+ const startedDelivered = Promise.withResolvers<void>();
+ const report: WorkflowToolRunMessage = {
+ from: {
+ callId: input.callId,
+ input: {},
+ runId: "run-1",
+ sequence: 0,
+ stepIndex: 0,
+ taskId: "task-1",
+ toolName: input.toolName,
+ turnId: "turn-1",
+ },
+ kind: "report",
+ update: "opened an agent",
+ };
+ const delivered: string[] = [];
+ mocks.deliver.mockImplementation(async (_inbox: string, message: WorkflowToolRunMessage) => {
+ delivered.push(message.kind);
+ if (message.kind === "started") await startedDelivered.promise;
+ });
+ mocks.owner.mockReturnValue({
+ commands: createChannelReader("control", {
+ [Symbol.asyncIterator]: () => ({ next: () => new Promise<never>(() => {}) }),
+ }),
+ handleMessage: (message: WorkflowToolRunMessage) =>
+ mocks.deliver("parent", message, { ifPresent: false }),
+ relay: relayThrough((message) => mocks.deliver("parent", message, { ifPresent: false })),
+ register: async () => {
+ await registered.promise;
+ return true;
+ },
+ });
+ // The body sends a message at once; the session must hear started before it.
+ mocks.openWorkflowToolRunOwnerInbox.mockReturnValue({
+ owner: { send: vi.fn(), sent: 1 },
+ reader: createChannelReader(
+ "workflow",
+ (async function* () {
+ yield [report];
+ await new Promise<void>(() => {});
+ })(),
+ ),
+ });
+
+ const completion = workflowToolRunWorkflow({
+ ...input,
+ entry: { entryPoint: "task", taskId: "task-1" },
+ });
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ expect(mocks.runBody).not.toHaveBeenCalled();
+ expect(delivered).toEqual([]);
+
+ registered.resolve();
+ await vi.waitFor(() => expect(delivered).toEqual(["started"]));
+ // The body started while started was still on its way.
+ expect(mocks.runBody).toHaveBeenCalledOnce();
+
+ startedDelivered.resolve();
+ await completion;
+ expect(delivered).toEqual(["started", "report", "outcome"]);
+});
+
+it("relays a question only once the control hook that takes its answer is registered", async () => {
+ const registered = Promise.withResolvers<boolean>();
+ const question: WorkflowToolRunMessage = {
+ from: {
+ callId: input.callId,
+ input: {},
+ runId: "run-1",
+ sequence: 0,
+ stepIndex: 0,
+ toolName: input.toolName,
+ turnId: "turn-1",
+ },
+ kind: "request",
+ replyTo: "run-1-ask-1",
+ request: { control: "control", kind: "ask", request: { prompt: "Deploy to production?" } },
+ };
+ mocks.owner.mockReturnValue({
+ commands: createChannelReader("control", {
+ [Symbol.asyncIterator]: () => ({ next: () => new Promise<never>(() => {}) }),
+ }),
+ handleMessage: mocks.deliver,
+ relay: relayThrough(mocks.deliver),
+ register: () => registered.promise,
+ });
+ mocks.openWorkflowToolRunOwnerInbox.mockReturnValue({
+ owner: { send: vi.fn(), sent: 1 },
+ reader: createChannelReader(
+ "workflow",
+ (async function* () {
+ yield [question];
+ await new Promise<void>(() => {});
+ })(),
+ ),
+ });
+
+ const completion = workflowToolRunWorkflow(input);
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ expect(mocks.deliver).not.toHaveBeenCalled();
+
+ registered.resolve(true);
+ await completion;
+ expect(mocks.deliver).toHaveBeenNthCalledWith(1, question);
+});
+
+it("reports a duplicate task start as started without starting its body", async () => {
+ mocks.owner.mockReturnValue({
+ commands: createChannelReader("control", (async function* () {})()),
+ handleMessage: mocks.deliver,
+ relay: relayThrough(mocks.deliver),
+ register: async () => false,
+ });
+ mocks.openWorkflowToolRunOwnerInbox.mockReturnValue({
+ owner: { send: vi.fn(), sent: 0 },
+ reader: createChannelReader("workflow", (async function* () {})()),
+ });
+
+ await workflowToolRunWorkflow({ ...input, entry: { entryPoint: "task", taskId: "task-1" } });
+
+ expect(mocks.runBody).not.toHaveBeenCalled();
+ // The session may have recorded this run; its started releases the held commands to the hook.
+ expect(mocks.deliver).toHaveBeenCalledExactlyOnceWith(
+ "parent",
+ expect.objectContaining({ kind: "started" }),
+ { ifPresent: true },
+ );
+});
+
it("propagates terminal delivery failure instead of replacing the invocation outcome", async () => {
mocks.runBody.mockResolvedValue({ status: "completed", output: "done" });
mocks.openWorkflowToolRunOwnerInbox.mockReturnValue({
diff --git a/packages/eve/src/execution/tools/workflow/workflow.ts b/packages/eve/src/execution/tools/workflow/workflow.ts
index f61c73b3c..c9101249e 100644
--- a/packages/eve/src/execution/tools/workflow/workflow.ts
+++ b/packages/eve/src/execution/tools/workflow/workflow.ts
@@ -10,6 +10,7 @@ import {
import {
isWorkflowToolRunAskDecision,
isWorkflowToolRunControlMessage,
+ type WorkflowToolRunMessage,
type WorkflowToolRunOutcome,
} from "#execution/tools/workflow/messages.js";
import {
@@ -32,8 +33,18 @@ export async function workflowToolRunWorkflow(input: WorkflowToolRunInput): Prom
const owner = createBlockingWorkflow(input);
const inbox = openWorkflowToolRunOwnerInbox();
- if (input.entry.entryPoint !== "execute") await reportTaskStarted(input);
+ const isTask = input.entry.entryPoint !== "execute";
+ // A task's session holds its commands until the run reports started, and a
+ // command that reaches the control hook before it is registered is lost.
+ if (isTask && !(await owner.register())) {
+ // A duplicate start of the task: the run holding the hook does its work.
+ // Started still releases the commands the session holds to that hook.
+ await reportTaskStarted(input);
+ return;
+ }
const started = startWorkflowBody({ ...input, owner: inbox.owner });
+ // Reported alongside the body's first step instead of before it.
+ const reported = isTask ? reportTaskStarted(input) : undefined;
const signal = started.control.runSignal;
const body: ChannelReader<"body", WorkflowToolRunOutcome> = createChannelReader(
"body",
@@ -48,6 +59,8 @@ export async function workflowToolRunWorkflow(input: WorkflowToolRunInput): Prom
// Close the body on every exit: a relay throws once the calling session's
// inbox is gone, which is exactly when what the body opened must stop.
try {
+ // A task's session must hear started before anything else.
+ await reported;
while (true) {
if (started.control.unwinding) {
cleanupDeadline ??= sleep(WORKFLOW_CANCELLATION_CLEANUP_MS).then(() => "cancel");
@@ -96,12 +109,9 @@ export async function workflowToolRunWorkflow(input: WorkflowToolRunInput): Prom
commandsOpen = false;
continue;
}
- if (read.channel === "body") {
- outcome = { status: "failed", error: "Workflow body ended without an outcome." };
- break;
- }
- if (signal.aborted) break;
- return;
+ // The inbox never ends, so only the body can.
+ outcome = { status: "failed", error: "Workflow body ended without an outcome." };
+ break;
}
if (read.channel === "control") {
// The deadline counts from the cancel the body is unwinding now.
@@ -113,10 +123,11 @@ export async function workflowToolRunWorkflow(input: WorkflowToolRunInput): Prom
bodyOutcome = read.next.value;
continue;
}
- const message = read.next.value;
- if (message.kind === "outcome") continue;
- relayedMessages += 1;
- await owner.handleMessage(message);
+ const messages = read.next.value;
+ relayedMessages += messages.length;
+ // An execute run's generated token can't be held by another run.
+ if (messages.some(isAnsweredOnControlHook)) await owner.register();
+ await owner.relay(messages);
}
} finally {
await started.close();
@@ -140,9 +151,8 @@ export async function workflowToolRunWorkflow(input: WorkflowToolRunInput): Prom
}
/**
- * Tells the session a task's run can take commands. Sending suspends the run,
- * which registers its control hook before the session hears of it, so a cancel
- * the session held until now reaches the body.
+ * Tells the session a task's run can take commands. Call it only once a run
+ * holds the control hook, so a cancel the session held until now reaches it.
*/
async function reportTaskStarted(input: WorkflowToolRunInput): Promise<void> {
await resumeHookStep(
@@ -166,6 +176,17 @@ function applyControlMessage(started: StartedWorkflowBody, message: unknown): vo
started.control.apply(message);
}
+/**
+ * The session may answer a question, or its withdrawal, on the control hook
+ * as soon as it reads it, so the hook must be registered before the relay.
+ * Waiting for that only when needed keeps the run's first steps inline.
+ */
+function isAnsweredOnControlHook(message: WorkflowToolRunMessage): boolean {
+ return (
+ message.kind === "withdraw" || (message.kind === "request" && message.request.kind === "ask")
+ );
+}
+
/** Starts the body the run's entry point names. */
function startWorkflowBody(input: WorkflowBodyInput): StartedWorkflowBody {
switch (input.entry.entryPoint) {
diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.ts
index 701be939f..357fda31e 100644
--- a/packages/eve/src/execution/workflow-runtime.test.ts
+++ b/packages/eve/src/execution/workflow-runtime.test.ts
@@ -8,13 +8,14 @@ import {
context as otelContext,
trace as otelTrace,
} from "#compiled/@opentelemetry/api/index.js";
-import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";
+import { HookNotFoundError, WorkflowRunNotFoundError } from "#compiled/@workflow/errors/index.js";
import type { ChannelAdapter } from "#channel/adapter.js";
import { ChannelRequestIdKey, SessionTitleKey } from "#context/keys.js";
import { resolveInstalledPackageInfo } from "#internal/application/package.js";
import {
createWorkflowRuntime,
waitForCommandHookOwner,
+ waitForSessionInbox,
sessionTimeoutWorkflowReference,
startSessionOwnerStep,
startWorkflowOnCurrentDeployment,
@@ -520,6 +521,49 @@ describe("waitForCommandHookOwner", () => {
});
});
+describe("waitForSessionInbox", () => {
+ const inboxToken = sessionInboxHookToken(sessionCommandHookToken("child-session"));
+
+ it("waits for a started session to claim its inbox", async () => {
+ getHookByTokenMock
+ .mockRejectedValueOnce(new HookNotFoundError(inboxToken))
+ .mockResolvedValueOnce({ runId: "child-session" });
+ // `start()` may accept a run before it can be read.
+ getRunMock.mockReturnValue({
+ get status() {
+ return Promise.reject(new WorkflowRunNotFoundError("child-session"));
+ },
+ });
+
+ await expect(waitForSessionInbox("child-session")).resolves.toBe(true);
+ expect(getHookByTokenMock).toHaveBeenLastCalledWith(inboxToken);
+ });
+
+ it("stops waiting once the session's run ended without an inbox", async () => {
+ getHookByTokenMock.mockRejectedValue(new HookNotFoundError(inboxToken));
+ getRunMock.mockReturnValue({ status: Promise.resolve("completed") });
+
+ await expect(waitForSessionInbox("child-session")).resolves.toBe(false);
+ });
+
+ it("gives up on a running session that never claims its inbox", async () => {
+ vi.useFakeTimers();
+ try {
+ getHookByTokenMock.mockRejectedValue(new HookNotFoundError(inboxToken));
+ getRunMock.mockReturnValue({ status: Promise.resolve("running") });
+
+ const waiting = waitForSessionInbox("child-session");
+ const settled = expect(waiting).rejects.toThrow(
+ 'Session "child-session" did not start taking commands within 30 seconds.',
+ );
+ await vi.advanceTimersByTimeAsync(31_000);
+ await settled;
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
+
describe("createWorkflowRuntime#createSession", () => {
const adapter: ChannelAdapter = { kind: "http" };
diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.ts
index 7bbac9b51..5e6b54bae 100644
--- a/packages/eve/src/execution/workflow-runtime.ts
+++ b/packages/eve/src/execution/workflow-runtime.ts
@@ -8,8 +8,6 @@ import {
} from "#compiled/@workflow/errors/index.js";
import type {
- CancelTurnInput,
- CancelTurnResult,
DispatchContinuationInput,
DispatchSessionInput,
GetEventStreamOptions,
@@ -80,6 +78,7 @@ import {
} from "#execution/session-inbox/resume.js";
import {
assertRunnableSessionInbox,
+ findSessionHookHolder,
StrandedSessionOwnerError,
} from "#execution/session-inbox/owner.js";
import { describeStrandedSession, SessionStrandedError } from "#channel/session-stranded-error.js";
@@ -293,21 +292,7 @@ export function createWorkflowRuntime(config: {
return await readSessionStreamTailIndex(sessionId);
},
- async resolveContinuation(
- continuationToken: string,
- ): Promise<{ sessionId: string } | undefined> {
- try {
- return await resolveSessionInbox(continuationToken);
- } catch (error) {
- if (HookNotFoundError.is(error)) {
- return undefined;
- }
- logError(log, "failed to resolve session by continuation token", error, {
- continuationToken,
- });
- throw error;
- }
- },
+ resolveContinuation,
};
}
@@ -465,15 +450,6 @@ export async function dispatchWorkflowSessionCommand<TCommand extends SessionCom
}
}
-/** Requests cancellation through a session's stable command inbox. */
-export async function requestWorkflowTurnCancellation(
- input: CancelTurnInput,
-): Promise<CancelTurnResult> {
- const command: { kind: "cancel"; turnId?: string } = { kind: "cancel" };
- if (input.turnId !== undefined) command.turnId = input.turnId;
- return await dispatchWorkflowSessionCommand({ command, sessionId: input.sessionId });
-}
-
async function isRunActive(runId: string): Promise<boolean> {
try {
const status = await getRun(runId).status;
@@ -499,20 +475,87 @@ function isInactiveCommandTarget(error: unknown): boolean {
return false;
}
+/** The session holding a continuation token's inbox, if any does. */
+export async function resolveContinuation(
+ continuationToken: string,
+): Promise<{ sessionId: string } | undefined> {
+ try {
+ return await resolveSessionInbox(continuationToken);
+ } catch (error) {
+ if (HookNotFoundError.is(error)) {
+ return undefined;
+ }
+ logError(log, "failed to resolve session by continuation token", error, {
+ continuationToken,
+ });
+ throw error;
+ }
+}
+
/**
* Resolves hook ownership for replay-idempotent work already running inside a
* durable step. Request handlers must return from start/resume acceptance and
* leave ownership arbitration to the workflow.
*/
export async function waitForCommandHookOwner(token: string): Promise<WorkflowHookRecord> {
- const deadline = Date.now() + SESSION_HOOK_HANDOVER_TIMEOUT_MS;
- while (true) {
+ const owner = await pollUntil(async () => {
try {
return normalizeWorkflowHook(await getHookByToken(token));
} catch (error) {
- if (!HookNotFoundError.is(error) || Date.now() >= deadline) throw error;
- await new Promise<void>((resolve) => setTimeout(resolve, 20));
+ if (!HookNotFoundError.is(error)) throw error;
+ return undefined;
+ }
+ }, SESSION_HOOK_HANDOVER_TIMEOUT_MS);
+ if (owner === undefined) throw new HookNotFoundError(token);
+ return owner;
+}
+
+/**
+ * Waits until a started session claims its inbox, which it does when its run
+ * first suspends. Resolves `false` when the run ended without an inbox, so
+ * there is nothing left to command.
+ */
+export async function waitForSessionInbox(sessionId: string): Promise<boolean> {
+ const token = sessionInboxHookToken(sessionCommandHookToken(sessionId));
+ const opened = await pollUntil(async () => {
+ if ((await findSessionHookHolder(token)) !== undefined) return true;
+ return (await hasRunEnded(sessionId)) ? false : undefined;
+ }, SESSION_HOOK_HANDOVER_TIMEOUT_MS);
+ if (opened === undefined) {
+ throw new Error(
+ `Session "${sessionId}" did not start taking commands within ${SESSION_HOOK_HANDOVER_TIMEOUT_MS / 1000} seconds.`,
+ );
+ }
+ return opened;
+}
+
+/**
+ * Calls `check` until it returns a value, backing off from 20 ms to 200 ms
+ * between calls, and resolves `undefined` once `timeoutMs` passes without one.
+ */
+export async function pollUntil<T>(
+ check: () => Promise<T | undefined>,
+ timeoutMs: number,
+): Promise<T | undefined> {
+ const deadline = Date.now() + timeoutMs;
+ for (let delayMs = 20; ; delayMs = Math.min(delayMs * 2, 200)) {
+ const value = await check();
+ if (value !== undefined || Date.now() >= deadline) return value;
+ await new Promise<void>((resolve) => setTimeout(resolve, delayMs));
+ }
+}
+
+/** A run `start()` accepted may not be readable yet, which is not an ended run. */
+export async function hasRunEnded(runId: string): Promise<boolean> {
+ try {
+ const status = await getRun(runId).status;
+ return status !== "pending" && status !== "running";
+ } catch (error) {
+ for (const cause of walkCauseChain(error)) {
+ if (WorkflowRunNotFoundError.is(cause)) return false;
}
+ if (isInactiveCommandTarget(error)) return true;
+ throw error;
}
}