Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): run subagents as durable background tasks (#1806)

Rui046981e3dd8e
diff --git a/.changeset/background-tasks.md b/.changeset/background-tasks.md
new file mode 100644
index 000000000..c309a4db6
--- /dev/null
+++ b/.changeset/background-tasks.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Add experimental background tasks for local and remote subagents. With `experimental.tasks` enabled, subagent calls return durable task receipts; parents can inspect, continue, or cancel work while lifecycle notifications and human-input requests arrive asynchronously. Remote child streams are exposed through an authenticated parent-origin proxy so clients never receive remote credentials.
diff --git a/.changeset/loopback-remote-task-hitl.md b/.changeset/loopback-remote-task-hitl.md
new file mode 100644
index 000000000..e57ad3b1a
--- /dev/null
+++ b/.changeset/loopback-remote-task-hitl.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Preserve remote task HITL response routes for loopback HTTP children and Vercel deployments configured with Protection Bypass for Automation. HTTPS remains required for every non-loopback remote child.
diff --git a/docs/tools/human-in-the-loop.md b/docs/tools/human-in-the-loop.md
index 738ecdb24..980a61094 100644
--- a/docs/tools/human-in-the-loop.md
+++ b/docs/tools/human-in-the-loop.md
@@ -109,7 +109,9 @@ semantics.
The run picks back up exactly where it parked. Because the pause is durable, nothing is held in memory while it waits — the process can restart and the parked turn survives.
-For approval requests, unrelated follow-up text does not deny the tool call — and it does not wait behind it either. The message runs as an ordinary turn while the approval stays pending and answerable; a later structured answer still resolves the original tool call. Text that exactly matches an option (like `approve`) still resolves the request directly.
+When a background subagent requests input, eve emits the same `input.requested` event on its parent session. Answering through that parent session routes the response directly to the blocked child without invoking the parent model.
+
+For approval requests, unrelated follow-up text does not deny the tool call. eve keeps the approval pending and holds that text until the approval is answered, then replays it as the next message in the session.
See [Sessions, runs & streaming](/docs/concepts/sessions-runs-and-streaming) for the full event and resume contract that this builds on.
diff --git a/packages/eve/extension-contracts/compatibility/dynamicInstructions/v11.ts b/packages/eve/extension-contracts/compatibility/dynamicInstructions/v11.ts
new file mode 100644
index 000000000..02a61cf70
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicInstructions/v11.ts
@@ -0,0 +1,10 @@
+import { defineDynamic, defineInstructions } from "#public/instructions/index.js";
+
+export default defineDynamic({
+ events: {
+ "session.started": (_event, ctx) =>
+ defineInstructions({
+ markdown: `Use session ${ctx.session.id} when correlating evidence.`,
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/dynamicSkill/v10.ts b/packages/eve/extension-contracts/compatibility/dynamicSkill/v10.ts
new file mode 100644
index 000000000..3c6e1498e
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicSkill/v10.ts
@@ -0,0 +1,11 @@
+import { defineDynamic, defineSkill } from "#public/skills/index.js";
+
+export default defineDynamic({
+ events: {
+ "turn.started": (_event, ctx) =>
+ defineSkill({
+ description: `Review evidence for session ${ctx.session.id}.`,
+ markdown: "# Evidence review\n\nCheck every claim against its source.",
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/dynamicTool/v16.ts b/packages/eve/extension-contracts/compatibility/dynamicTool/v16.ts
new file mode 100644
index 000000000..76b54cd92
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicTool/v16.ts
@@ -0,0 +1,14 @@
+import { z as z3 } from "zod/v3";
+
+import { defineDynamic, defineTool } from "#public/tools/index.js";
+
+export default defineDynamic({
+ events: {
+ "session.started": (_event, ctx) =>
+ defineTool({
+ description: "Return the active session identifier.",
+ inputSchema: z3.object({ prefix: z3.string() }),
+ execute: ({ prefix }) => ({ sessionId: `${prefix}:${ctx.session.id}` }),
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/hook/v12.ts b/packages/eve/extension-contracts/compatibility/hook/v12.ts
new file mode 100644
index 000000000..38ecc7e06
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/hook/v12.ts
@@ -0,0 +1,13 @@
+import { defineHook } from "#public/hooks/index.js";
+
+export default defineHook({
+ events: {
+ "subagent.completed"(event, ctx) {
+ console.info("subagent completed", {
+ output: event.data.output,
+ sessionId: ctx.session.id,
+ subagentName: event.data.subagentName,
+ });
+ },
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/tool/v12.ts b/packages/eve/extension-contracts/compatibility/tool/v12.ts
new file mode 100644
index 000000000..eae0f5b7e
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/tool/v12.ts
@@ -0,0 +1,11 @@
+import { z as z3 } from "zod/v3";
+
+import { defineTool } from "#public/tools/index.js";
+
+export default defineTool({
+ description: "Look up a report.",
+ inputSchema: z3.object({ reportId: z3.string() }),
+ execute(input, ctx) {
+ return { callId: ctx.callId, reportId: input.reportId };
+ },
+});
diff --git a/packages/eve/extension-contracts/reports/dynamicInstructions/v12.json b/packages/eve/extension-contracts/reports/dynamicInstructions/v12.json
new file mode 100644
index 000000000..401fb3ae9
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicInstructions/v12.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicInstructions",
+ "epoch": 12,
+ "sha256": "2b2e511371131bfe51781071f5a7fe30a1c4206acbe176079c8b0ca524f33770",
+ "exports": ["defineDynamic"]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicSkill/v11.json b/packages/eve/extension-contracts/reports/dynamicSkill/v11.json
new file mode 100644
index 000000000..bd572d118
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicSkill/v11.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicSkill",
+ "epoch": 11,
+ "sha256": "f8b67fef8c16ef5c551c53abf2bacc4e5e5ea8429b096c842797237d842e20b2",
+ "exports": ["defineDynamic"]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v17.json b/packages/eve/extension-contracts/reports/dynamicTool/v17.json
new file mode 100644
index 000000000..e2acb192d
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicTool/v17.json
@@ -0,0 +1,13 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicTool",
+ "epoch": 17,
+ "sha256": "cd73a286314786790b89746bc50fa525d6ce972fb18b9cd17efd2a5c0a54c0be",
+ "exports": [
+ "DynamicToolEntry",
+ "DynamicToolEvents",
+ "DynamicToolResult",
+ "DynamicToolSet",
+ "defineDynamic"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/hook/v13.json b/packages/eve/extension-contracts/reports/hook/v13.json
new file mode 100644
index 000000000..65b822f46
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/hook/v13.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "hook",
+ "epoch": 13,
+ "sha256": "db1c9dc64d990dcb4d6ced1ab243a9158ac4ab76d7ac14627d2d8e16ea80f541",
+ "exports": ["defineHook"]
+}
diff --git a/packages/eve/extension-contracts/reports/tool/v13.json b/packages/eve/extension-contracts/reports/tool/v13.json
new file mode 100644
index 000000000..ae9433bee
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/tool/v13.json
@@ -0,0 +1,22 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "tool",
+ "epoch": 13,
+ "sha256": "c670d12d56c658affcbda235c5cb4b1cf90dcd4c7ffc15aa01e0be13520ec785",
+ "exports": [
+ "defineBashTool",
+ "defineGlobTool",
+ "defineGrepTool",
+ "defineReadFileTool",
+ "defineTool",
+ "defineWriteFileTool",
+ "disableTool",
+ "experimental_workflow",
+ "isDisabledToolSentinel",
+ "isExperimentalWorkflowToolDefinition",
+ "toolOutput",
+ "toolOutputPart",
+ "toolResultFrom",
+ "webSearch"
+ ]
+}
diff --git a/packages/eve/src/channel/session-callback.ts b/packages/eve/src/channel/session-callback.ts
index 31c60dec6..868f234a2 100644
--- a/packages/eve/src/channel/session-callback.ts
+++ b/packages/eve/src/channel/session-callback.ts
@@ -19,6 +19,7 @@ const sessionCallbackSchema = z
.object({
callId: z.string().min(1),
subagentName: z.string().min(1),
+ taskId: z.string().min(1).optional(),
token: z.string().min(1),
url: z.string().min(1),
})
diff --git a/packages/eve/src/channel/session.test.ts b/packages/eve/src/channel/session.test.ts
index 7e20941e1..02578fccc 100644
--- a/packages/eve/src/channel/session.test.ts
+++ b/packages/eve/src/channel/session.test.ts
@@ -123,8 +123,9 @@ describe("fixed session operations", () => {
auth: null,
caller: {
callId: "call_1",
- replyTo: { kind: "callback", url: callback.url },
+ replyTo: { kind: "callback", token: callback.token, url: callback.url },
subagentName: "research",
+ taskId: undefined,
},
kind: "send",
payload: { message: "continue" },
diff --git a/packages/eve/src/channel/session.ts b/packages/eve/src/channel/session.ts
index 807d4d2f1..9ba1a996c 100644
--- a/packages/eve/src/channel/session.ts
+++ b/packages/eve/src/channel/session.ts
@@ -38,8 +38,8 @@ export interface Session {
inputResponses: readonly InputResponse[],
options: SessionRespondOptions,
): Promise<SessionSendCommandResult>;
- /** Requests cancellation of this exact session's active turn. */
- cancel(options?: { turnId?: string }): Promise<CancelTurnResult>;
+ /** Requests cancellation of this exact session's active turn or one owned task. */
+ cancel(options?: { taskId?: string; turnId?: string }): Promise<CancelTurnResult>;
/** Queues compaction on this exact session ID. */
compact(): Promise<CompactSessionResult>;
/** Queues a context clear on this exact session ID. */
@@ -135,9 +135,9 @@ export function createSession(
sessionId: id,
});
},
- async cancel(options?: { turnId?: string }) {
+ async cancel(options?: { taskId?: string; turnId?: string }) {
return await runtime.dispatchSession({
- command: { kind: "cancel", turnId: options?.turnId },
+ command: { kind: "cancel", taskId: options?.taskId, turnId: options?.turnId },
sessionId: id,
});
},
@@ -233,7 +233,8 @@ export function sessionCallbackToTurnCaller(
? undefined
: {
callId: callback.callId,
- replyTo: { kind: "callback", url: callback.url },
+ replyTo: { kind: "callback", token: callback.token, url: callback.url },
subagentName: callback.subagentName,
+ taskId: callback.taskId,
};
}
diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.ts
index 044bd6b6a..623f2e907 100644
--- a/packages/eve/src/channel/types.ts
+++ b/packages/eve/src/channel/types.ts
@@ -142,7 +142,7 @@ export interface TurnCaller {
readonly taskId?: string;
readonly replyTo:
| { readonly kind: "hook"; readonly token: string }
- | { readonly kind: "callback"; readonly url: string };
+ | { readonly kind: "callback"; readonly token: string; readonly url: string };
}
/**
@@ -174,8 +174,8 @@ export interface DeliverPayload {
readonly hookPayload: SubagentAuthorizationEventHookPayload;
readonly taskId: string;
}[];
- /** Terminal snapshots cached before task-run retention expires. */
- readonly snapshots?: readonly TaskView[];
+ /** Terminal views cached before task-run retention expires. */
+ readonly views?: readonly TaskView[];
};
readonly [key: string]: unknown;
}
diff --git a/packages/eve/src/cli/dev/tui/tool-presentation.test.ts b/packages/eve/src/cli/dev/tui/tool-presentation.test.ts
index e4b25af13..1de393e84 100644
--- a/packages/eve/src/cli/dev/tui/tool-presentation.test.ts
+++ b/packages/eve/src/cli/dev/tui/tool-presentation.test.ts
@@ -178,6 +178,10 @@ describe("presentTool", () => {
grep: { pattern: "useEve" },
load_skill: { skill: "commit" },
read_file: { filePath: "/workspace/a.ts" },
+ task_cancel: { taskIds: ["task_abc"] },
+ task_peek: { taskIds: ["task_abc"] },
+ task_send: { message: "Continue with the next region.", taskId: "task_abc" },
+ task_sleep: { seconds: 30 },
todo: { todos: [] },
web_fetch: { url: "https://example.com" },
web_search: { query: "eve framework" },
diff --git a/packages/eve/src/cli/dev/tui/tool-presentation.ts b/packages/eve/src/cli/dev/tui/tool-presentation.ts
index 0bd23fbb8..a27542e24 100644
--- a/packages/eve/src/cli/dev/tui/tool-presentation.ts
+++ b/packages/eve/src/cli/dev/tui/tool-presentation.ts
@@ -123,6 +123,37 @@ const BUILTIN_TOOL_COPY: Readonly<Record<string, BuiltinToolCopy>> = {
singularNoun: "file",
pluralNoun: "files",
},
+ task_cancel: {
+ verb: "Cancel",
+ pastVerb: "Cancelled",
+ argKey: "taskIds",
+ extractItem: taskIdsArg,
+ singularNoun: "task",
+ pluralNoun: "tasks",
+ },
+ task_peek: {
+ verb: "Check",
+ pastVerb: "Checked",
+ argKey: "taskIds",
+ extractItem: taskIdsArg,
+ singularNoun: "task",
+ pluralNoun: "tasks",
+ },
+ task_send: {
+ verb: "Send",
+ pastVerb: "Sent",
+ argKey: "taskId",
+ singularNoun: "task",
+ pluralNoun: "tasks",
+ },
+ task_sleep: {
+ verb: "Pause",
+ pastVerb: "Paused",
+ argKey: "seconds",
+ extractItem: sleepSecondsArg,
+ singularNoun: "pause",
+ pluralNoun: "pauses",
+ },
web_fetch: {
verb: "Fetch",
pastVerb: "Fetched",
@@ -359,6 +390,24 @@ function webSearchActionArg(input: unknown): string | undefined {
* renders verbatim in aggregated rows, so a model-controlled value must lose
* its terminal controls here, not at the render call sites.
*/
+/** Joins a `taskIds: string[]` argument into one salient line. */
+function taskIdsArg(input: unknown): string | undefined {
+ if (input === null || typeof input !== "object" || Array.isArray(input)) return undefined;
+ const value = (input as Record<string, unknown>).taskIds;
+ if (!Array.isArray(value)) return undefined;
+ const ids = value.filter((id): id is string => typeof id === "string");
+ if (ids.length === 0) return undefined;
+ return salientLine(ids.join(", "));
+}
+
+/** Formats a `seconds: number` argument as a duration. */
+function sleepSecondsArg(input: unknown): string | undefined {
+ if (input === null || typeof input !== "object" || Array.isArray(input)) return undefined;
+ const value = (input as Record<string, unknown>).seconds;
+ if (typeof value !== "number" || !Number.isFinite(value)) return undefined;
+ return `${String(value)}s`;
+}
+
function salientArg(input: unknown, key: string): string | undefined {
if (input === null || typeof input !== "object" || Array.isArray(input)) return undefined;
const value = (input as Record<string, unknown>)[key];
diff --git a/packages/eve/src/client/session.test.ts b/packages/eve/src/client/session.test.ts
index 2aa6fac5c..f08b83171 100644
--- a/packages/eve/src/client/session.test.ts
+++ b/packages/eve/src/client/session.test.ts
@@ -950,4 +950,42 @@ describe("ClientSession", () => {
streamIndex: 2,
});
});
+
+ it("hands the cursor from an aborted idle follow to the next send", async () => {
+ const streamStartIndices: Array<string | null> = [];
+ vi.spyOn(globalThis, "fetch").mockImplementation(async (request, init) => {
+ if ((init?.method ?? "GET") === "POST") return createAcceptedResponse();
+ const url =
+ typeof request === "string" ? request : request instanceof URL ? request.href : request.url;
+ streamStartIndices.push(new URL(url).searchParams.get("startIndex"));
+ return createStreamResponse([
+ { type: "turn.started", data: {} },
+ {
+ type: "session.waiting",
+ data: { continuationToken: "eve:test", wait: "next-user-message" },
+ },
+ ]);
+ });
+ const session = createSession({
+ sessionId: "session_1",
+ streamIndex: 0,
+ });
+ const idleAbort = new AbortController();
+
+ vi.useFakeTimers();
+ try {
+ for await (const event of session.stream({ signal: idleAbort.signal })) {
+ if (event.type === "session.waiting") idleAbort.abort();
+ }
+
+ expect(session.state.streamIndex).toBe(2);
+ expect(await collectEventTypes(await session.send("follow up"))).toEqual([
+ "turn.started",
+ "session.waiting",
+ ]);
+ } finally {
+ vi.useRealTimers();
+ }
+ expect(streamStartIndices).toEqual([null, "2"]);
+ });
});
diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.ts
index b2d5a94aa..6ebebf389 100644
--- a/packages/eve/src/compiler/extension-compatibility.ts
+++ b/packages/eve/src/compiler/extension-compatibility.ts
@@ -21,16 +21,16 @@ interface ExtensionCapabilityContract {
const EXTENSION_CAPABILITY_CONTRACTS = {
extension: { current: 1, supported: [1], dropped: {} },
- tool: { current: 12, supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], dropped: {} },
+ tool: { current: 13, supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], dropped: {} },
dynamicTool: {
- current: 16,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
+ current: 17,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
dropped: {},
},
connection: { current: 5, supported: [1, 2, 3, 4, 5], dropped: {} },
hook: {
- current: 12,
- supported: [10, 11, 12],
+ current: 13,
+ supported: [10, 11, 12, 13],
dropped: {
1: "Model identity moved from session.started runtime metadata to step.started call attribution.",
2: "Model identity moved from session.started runtime metadata to step.started call attribution.",
@@ -44,11 +44,11 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
skill: { current: 1, supported: [1], dropped: {} },
- dynamicSkill: { current: 10, supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dropped: {} },
+ dynamicSkill: { current: 11, supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], dropped: {} },
instructions: { current: 2, supported: [1, 2], dropped: {} },
dynamicInstructions: {
- current: 11,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
+ current: 12,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
dropped: {},
},
config: { current: 1, supported: [1], dropped: {} },
diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.ts
index e86aaf598..7df110869 100644
--- a/packages/eve/src/compiler/manifest.ts
+++ b/packages/eve/src/compiler/manifest.ts
@@ -443,6 +443,7 @@ const compiledAgentConfigBaseFields = {
.object({
instrumentationProviders: z.boolean().optional(),
subagentPersistentSessions: z.boolean().optional(),
+ tasks: z.boolean().optional(),
workflow: compiledAgentWorkflowDefinitionSchema.optional(),
})
.strict()
@@ -920,6 +921,7 @@ function cloneCompiledAgentDefinition(config: CompiledAgentDefinition): Compiled
: {
instrumentationProviders: config.experimental.instrumentationProviders,
subagentPersistentSessions: config.experimental.subagentPersistentSessions,
+ tasks: config.experimental.tasks,
workflow:
config.experimental.workflow === undefined
? undefined
diff --git a/packages/eve/src/compiler/normalize-agent-config.ts b/packages/eve/src/compiler/normalize-agent-config.ts
index 0c0bc81b7..765431ed6 100644
--- a/packages/eve/src/compiler/normalize-agent-config.ts
+++ b/packages/eve/src/compiler/normalize-agent-config.ts
@@ -193,6 +193,10 @@ function normalizeExperimentalDefinition(
compiledExperimental.subagentPersistentSessions = experimental.subagentPersistentSessions;
}
+ if (experimental.tasks !== undefined) {
+ compiledExperimental.tasks = experimental.tasks;
+ }
+
if (experimental.workflow !== undefined) {
compiledExperimental.workflow = {
world: experimental.workflow.world,
diff --git a/packages/eve/src/compiler/normalize-manifest.test.ts b/packages/eve/src/compiler/normalize-manifest.test.ts
index 824529aa6..8ddbdee61 100644
--- a/packages/eve/src/compiler/normalize-manifest.test.ts
+++ b/packages/eve/src/compiler/normalize-manifest.test.ts
@@ -148,6 +148,53 @@ describe("compileAgentManifest", () => {
});
});
+ it("rejects background-task configuration on subagents", async () => {
+ const subagentManifest = createAgentSourceManifest({
+ agentId: "research",
+ agentRoot: "/app/agent/subagents/research",
+ appRoot: "/app",
+ configModule: createModuleSourceRef({
+ logicalPath: "agent.ts",
+ }),
+ });
+ const manifest = createAgentSourceManifest({
+ agentId: "root",
+ agentRoot: "/app/agent",
+ appRoot: "/app",
+ subagents: [
+ createLocalSubagentSourceRef({
+ entryPath: "subagents/research/agent.ts",
+ logicalPath: "subagents/research",
+ manifest: subagentManifest,
+ rootPath: "/app/agent/subagents/research",
+ subagentId: "research",
+ }),
+ ],
+ });
+
+ mocks.compileAgentConfig.mockImplementation(async (input: AgentSourceManifest) => {
+ if (input.agentId === "research") {
+ return createConfig({
+ description: "Research subagent",
+ name: "research",
+ experimental: {
+ tasks: true,
+ },
+ });
+ }
+
+ return createConfig({ name: "root" });
+ });
+ mocks.loadModuleBackedDefinition.mockResolvedValue({
+ description: "Research subagent",
+ model: "openai/gpt-5.5",
+ });
+
+ await expect(compileAgentManifest(manifest)).rejects.toThrow(
+ 'Remove "experimental.tasks" from "research"',
+ );
+ });
+
it("compiles experimental Workflow tool configuration", async () => {
const manifest = createAgentSourceManifest({
agentId: "root",
diff --git a/packages/eve/src/compiler/normalize-manifest.ts b/packages/eve/src/compiler/normalize-manifest.ts
index e998ec8d9..9181a3a08 100644
--- a/packages/eve/src/compiler/normalize-manifest.ts
+++ b/packages/eve/src/compiler/normalize-manifest.ts
@@ -67,7 +67,7 @@ async function compileAgentNodeManifest(
options: {
readonly agentConfigDefinition?: unknown;
readonly externalDependencies?: readonly string[];
- readonly allowWorkflowConfig?: boolean;
+ readonly allowRootOnlyConfig?: boolean;
} = {},
): Promise<CompiledAgentNodeManifest> {
const rawConfig = Object.hasOwn(options, "agentConfigDefinition")
@@ -75,11 +75,16 @@ async function compileAgentNodeManifest(
definition: options.agentConfigDefinition,
})
: await compileAgentConfig(manifest, context);
- if (options.allowWorkflowConfig === false && rawConfig.experimental?.workflow !== undefined) {
+ if (options.allowRootOnlyConfig === false && rawConfig.experimental?.workflow !== undefined) {
throw new Error(
`Workflow runtime configuration is only supported on the root agent config. Remove "experimental.workflow" from "${manifest.agentId}".`,
);
}
+ if (options.allowRootOnlyConfig === false && rawConfig.experimental?.tasks !== undefined) {
+ throw new Error(
+ `Background tasks are only supported on the root agent config. Remove "experimental.tasks" from "${manifest.agentId}".`,
+ );
+ }
const externalDependencies = mergeExternalDependencies(
options.externalDependencies,
rawConfig.build?.externalDependencies,
diff --git a/packages/eve/src/compiler/normalize-subagent.ts b/packages/eve/src/compiler/normalize-subagent.ts
index 07c6b2fb2..182291061 100644
--- a/packages/eve/src/compiler/normalize-subagent.ts
+++ b/packages/eve/src/compiler/normalize-subagent.ts
@@ -45,7 +45,7 @@ export type CompileAgentNodeManifestFn = (
options?: {
readonly agentConfigDefinition?: unknown;
readonly externalDependencies?: readonly string[];
- readonly allowWorkflowConfig?: boolean;
+ readonly allowRootOnlyConfig?: boolean;
},
) => Promise<CompiledAgentNodeManifest>;
@@ -218,7 +218,7 @@ async function compileSubagent(input: {
if (input.configResolver === undefined) {
const agent = await input.compileAgentNodeManifest(sourceManifest, input.context, {
agentConfigDefinition: input.agentConfigDefinition,
- allowWorkflowConfig: false,
+ allowRootOnlyConfig: false,
externalDependencies: inheritedExternalDependencies,
});
const description = agent.config.description;
diff --git a/packages/eve/src/evals/runner/derive-run-facts.test.ts b/packages/eve/src/evals/runner/derive-run-facts.test.ts
index b45803288..265451829 100644
--- a/packages/eve/src/evals/runner/derive-run-facts.test.ts
+++ b/packages/eve/src/evals/runner/derive-run-facts.test.ts
@@ -355,6 +355,7 @@ describe("deriveRunFacts", () => {
data: {
callId: "c1",
childSessionId: "s1",
+ childStreamPath: "/eve/v1/session/s0/subagents/c1/s1/stream",
sessionId: "s0",
sequence: 1,
name: "weather",
diff --git a/packages/eve/src/evals/runner/execute-task.test.ts b/packages/eve/src/evals/runner/execute-task.test.ts
index c6ff9f535..ab4c02b3a 100644
--- a/packages/eve/src/evals/runner/execute-task.test.ts
+++ b/packages/eve/src/evals/runner/execute-task.test.ts
@@ -852,6 +852,7 @@ function subagentCalled(
data: {
callId: "call_subagent",
childSessionId,
+ childStreamPath: `/eve/v1/session/${encodeURIComponent(childSessionId)}/stream`,
sessionId: "parent-session",
sequence: 1,
name,
diff --git a/packages/eve/src/execution/agent-handle-dispatch.ts b/packages/eve/src/execution/agent-handle-dispatch.ts
index 59c03899e..472c19fc5 100644
--- a/packages/eve/src/execution/agent-handle-dispatch.ts
+++ b/packages/eve/src/execution/agent-handle-dispatch.ts
@@ -10,8 +10,18 @@
import { AGENT_BUSY, AGENT_MISMATCH, AGENT_UNREACHABLE } from "#harness/agent-handle-errors.js";
import { deriveAgentOperationId } from "#harness/handles/operation-id.js";
-import type { AgentAddress, AgentHandle, ContinueOperation } from "#harness/handles/store.js";
-import { prepareAgentContinuation, rejectAgentEffect } from "#harness/handles/transitions.js";
+import {
+ getAgentHandleStore,
+ type AgentAddress,
+ type AgentHandle,
+ type AgentIdentity,
+ type ContinueOperation,
+} from "#harness/handles/store.js";
+import {
+ prepareAgentContinuation,
+ rejectAgentEffect,
+ removeTaskAgentAddress,
+} from "#harness/handles/transitions.js";
import type {
RuntimeActionRequest,
RuntimeRemoteAgentCallActionRequest,
@@ -21,6 +31,7 @@ import type {
import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
import {
continueRemoteAgentSession,
+ isAmbiguousRemoteAgentContinueError,
isRetryableRemoteAgentContinueError,
resolveRemoteAgentForAction,
} from "#execution/remote-agent-dispatch.js";
@@ -32,6 +43,7 @@ import { createWorkflowCallbackUrl } from "#execution/workflow-callback-url.js";
import { createLogger, logError } from "#internal/logging.js";
import { createEveCallbackRoutePath } from "#protocol/routes.js";
import { err, ok, type Result } from "#shared/result.js";
+import { readTaskIdFromInboxToken } from "#tasks/task-id.js";
const log = createLogger("execution.agent-handle-dispatch");
@@ -70,6 +82,7 @@ export type DispatchOutcome =
readonly toolName: string;
}
| {
+ readonly deliveryAmbiguous?: boolean;
readonly kind: "error";
readonly result: RuntimeSubagentDispatchFailure;
readonly session: RuntimeSession;
@@ -164,10 +177,11 @@ export async function dispatchToAgentHandle(input: {
// accepted for child starts. The callee has no receiver-side dedup for
// this; `prepareAgentContinuation` treating the recorded operation as a
// replay only makes the parent-side transition idempotent.
- const delivery = await deliverToAgentHandle({
+ const delivery = await deliverToAgentAddress({
action,
+ address: handle.address,
bundle,
- handle,
+ identity: handle.identity,
parentToken: input.parentToken,
});
if (!delivery.ok) {
@@ -183,6 +197,7 @@ export async function dispatchToAgentHandle(input: {
// child's accumulated conversation); a transiently unreachable agent is
// restored to `parked` so the model can retry the same agentId.
return {
+ deliveryAmbiguous: delivery.error.deliveryAmbiguous,
kind: "error",
result: createAgentErrorResult({
action,
@@ -208,6 +223,86 @@ export async function dispatchToAgentHandle(input: {
};
}
+/** Delivers a tasks-mode continuation without creating a second lifecycle claim. */
+export async function dispatchToTaskAgentAddress(input: {
+ readonly action: RuntimeAgentHandleAction;
+ readonly agentId: string;
+ readonly bundle: CompiledBundle;
+ readonly currentSession: RuntimeSession;
+ readonly parentToken: string;
+}): Promise<DispatchOutcome> {
+ const { action, agentId } = input;
+ const invokedName =
+ action.kind === "remote-agent-call" ? action.remoteAgentName : action.subagentName;
+ const record = (getAgentHandleStore(input.currentSession.state)?.handles ?? []).find(
+ (handle): handle is Extract<AgentHandle, { phase: "addressed" }> =>
+ handle.phase === "addressed" && handle.identity.id === agentId,
+ );
+ if (record === undefined) {
+ return {
+ kind: "error",
+ result: createAgentErrorResult({
+ action,
+ code: AGENT_UNREACHABLE,
+ message: `Agent with id "${agentId}" is no longer reachable.`,
+ }),
+ session: input.currentSession,
+ };
+ }
+ if (record.identity.name !== invokedName) {
+ return {
+ kind: "error",
+ result: createAgentErrorResult({
+ action,
+ code: AGENT_MISMATCH,
+ message: `Agent "${agentId}" from the <agents> list does not belong to "${invokedName}".`,
+ }),
+ session: input.currentSession,
+ };
+ }
+
+ const delivery = await deliverToAgentAddress({
+ action,
+ address: record.address,
+ bundle: input.bundle,
+ identity: record.identity,
+ parentToken: input.parentToken,
+ });
+ if (!delivery.ok) {
+ const { cause, permanent } = delivery.error;
+ logError(log, "task agent delivery failed", cause, {
+ agentId,
+ callId: action.callId,
+ nodeId: record.identity.nodeId,
+ permanent,
+ subagentName: record.identity.name,
+ });
+ return {
+ deliveryAmbiguous: delivery.error.deliveryAmbiguous,
+ kind: "error",
+ result: createAgentErrorResult({
+ action,
+ code: AGENT_UNREACHABLE,
+ message: permanent
+ ? `Agent "${record.identity.name}" with id "${agentId}" is no longer reachable.`
+ : `Agent "${record.identity.name}" with id "${agentId}" is temporarily unreachable. Try again.`,
+ }),
+ session: permanent
+ ? removeTaskAgentAddress(input.currentSession, agentId)
+ : input.currentSession,
+ };
+ }
+
+ return {
+ address: record.address,
+ callId: action.callId,
+ kind: "called",
+ name: action.name,
+ session: input.currentSession,
+ toolName: record.identity.name,
+ };
+}
+
/**
* Attempts the continuation delivery once and classifies the failure.
*
@@ -218,14 +313,19 @@ export async function dispatchToAgentHandle(input: {
* Throwing is equally unsafe — a durable-step retry would re-dispatch
* already-started siblings.
*/
-async function deliverToAgentHandle(input: {
+async function deliverToAgentAddress(input: {
readonly action: RuntimeAgentHandleAction;
+ readonly address: AgentAddress;
readonly bundle: CompiledBundle;
- readonly handle: Extract<AgentHandle, { phase: "running" }>;
+ readonly identity: AgentIdentity;
readonly parentToken: string;
-}): Promise<Result<void, { readonly cause: unknown; readonly permanent: boolean }>> {
- const { action, bundle, handle } = input;
- const { address, identity } = handle;
+}): Promise<
+ Result<
+ void,
+ { readonly cause: unknown; readonly deliveryAmbiguous: boolean; readonly permanent: boolean }
+ >
+> {
+ const { action, address, bundle, identity } = input;
if (address.kind === "agent/remote") {
let resolvedRemote;
@@ -238,13 +338,14 @@ async function deliverToAgentHandle(input: {
} catch (error) {
// The agent's node is gone from the compiled bundle; no retry can
// reach this handle again.
- return err({ cause: error, permanent: true });
+ return err({ cause: error, deliveryAmbiguous: false, permanent: true });
}
try {
await continueRemoteAgentSession({
callback: {
callId: action.callId,
subagentName: identity.name,
+ taskId: readTaskIdFromInboxToken(input.parentToken),
token: input.parentToken,
url: createWorkflowCallbackUrl(
address.callbackBaseUrl,
@@ -259,6 +360,7 @@ async function deliverToAgentHandle(input: {
} catch (error) {
return err({
cause: error,
+ deliveryAmbiguous: isAmbiguousRemoteAgentContinueError(error),
permanent: !isRetryableRemoteAgentContinueError(error),
});
}
@@ -276,6 +378,7 @@ async function deliverToAgentHandle(input: {
callId: action.callId,
replyTo: { kind: "hook", token: input.parentToken },
subagentName: identity.name,
+ taskId: readTaskIdFromInboxToken(input.parentToken),
},
kind: "send",
payload: {
@@ -288,16 +391,18 @@ async function deliverToAgentHandle(input: {
if (result.status === "session_not_active") {
return err({
cause: new Error(`Agent session "${address.sessionId}" is no longer active.`),
+ deliveryAmbiguous: false,
permanent: true,
});
}
} catch (error) {
- return err({ cause: error, permanent: isRuntimeNoActiveSessionError(error) });
+ const permanent = isRuntimeNoActiveSessionError(error);
+ return err({ cause: error, deliveryAmbiguous: !permanent, permanent });
}
return ok(undefined);
}
-function createAgentErrorResult(input: {
+export function createAgentErrorResult(input: {
readonly action: RuntimeAgentHandleAction;
readonly code: string;
readonly message: string;
diff --git a/packages/eve/src/execution/agent-messaging.scenario.test.ts b/packages/eve/src/execution/agent-messaging.scenario.test.ts
index 0317e9d54..4b027bf14 100644
--- a/packages/eve/src/execution/agent-messaging.scenario.test.ts
+++ b/packages/eve/src/execution/agent-messaging.scenario.test.ts
@@ -15,6 +15,7 @@ const SCENARIO_TIMEOUT_MS = 360_000;
const EVENT_TIMEOUT_MS = 30_000;
const CODEWORD = "LANTERN-COMET-7319";
const PARENT_RESULT = `PARENT_RECALLED=${CODEWORD}`;
+const REMOTE_MEMORY_TOKEN = "remote-memory-scenario-token";
function createScriptedParentAgentSource(subagentName: string): string {
const agentIdPattern = `<agent id="([^"]+)" name="${subagentName}">`;
@@ -93,6 +94,21 @@ import { eveChannel } from "eve/channels/eve";
export default eveChannel({ auth: none() });
`;
+const AUTHENTICATED_EVE_CHANNEL_SOURCE = `import { eveChannel } from "eve/channels/eve";
+
+export default eveChannel({
+ auth(request) {
+ if (request.headers.get("authorization") !== "Bearer ${REMOTE_MEMORY_TOKEN}") return null;
+ return {
+ attributes: {},
+ authenticator: "scenario-bearer",
+ principalId: "remote-memory-parent",
+ principalType: "service",
+ };
+ },
+});
+`;
+
const MEMORY_AGENT_SOURCE = `import { defineAgent } from "eve";
import { mockModel } from "eve/evals";
@@ -137,7 +153,7 @@ const AGENT_MESSAGING_DESCRIPTOR: ScenarioAppDescriptor = {
const REMOTE_MEMORY_AGENT_DESCRIPTOR: ScenarioAppDescriptor = {
files: {
"agent/agent.ts": MEMORY_AGENT_SOURCE,
- "agent/channels/eve.ts": EVE_CHANNEL_SOURCE,
+ "agent/channels/eve.ts": AUTHENTICATED_EVE_CHANNEL_SOURCE,
"agent/instructions.md":
"Remember facts from earlier turns and answer follow-up questions from that history.\n",
},
@@ -152,8 +168,10 @@ function createRemoteAgentMessagingDescriptor(remoteUrl: string): ScenarioAppDes
"agent/channels/eve.ts": EVE_CHANNEL_SOURCE,
"agent/instructions.md": "Run the scripted remote-memory-child exchanges.\n",
"agent/subagents/remote-memory-child.ts": `import { defineRemoteAgent } from "eve";
+import { bearer } from "eve/agents/auth";
export default defineRemoteAgent({
+ auth: bearer(${JSON.stringify(REMOTE_MEMORY_TOKEN)}),
description: "Remember a fact and recall it in a later agent exchange.",
url: ${JSON.stringify(remoteUrl)},
});
@@ -211,7 +229,10 @@ describe("agent messaging", () => {
});
await expectRetainedChildConversation({
childSessionId,
- client: new Client({ host: remoteServer.url }),
+ client: new Client({
+ auth: { bearer: REMOTE_MEMORY_TOKEN },
+ host: remoteServer.url,
+ }),
});
} catch (error) {
throw new Error(
diff --git a/packages/eve/src/execution/delegated-parent-notification.test.ts b/packages/eve/src/execution/delegated-parent-notification.test.ts
index a77ae2882..8b6373549 100644
--- a/packages/eve/src/execution/delegated-parent-notification.test.ts
+++ b/packages/eve/src/execution/delegated-parent-notification.test.ts
@@ -2,11 +2,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ContextContainer } from "#context/container.js";
import { serializeContext } from "#context/serialize.js";
-import { SessionIdKey } from "#context/keys.js";
+import { SessionCallbackKey, SessionIdKey } from "#context/keys.js";
import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
import {
+ bindTurnCallerContextStep,
notifyDelegatedParentStep,
+ notifyTaskTurnStartedStep,
notifyTurnCallerStep,
resolveInitialTurnCallerStep,
} from "#execution/delegated-parent-notification.js";
@@ -115,7 +117,7 @@ describe("notifyDelegatedParentStep", () => {
});
});
- it("never attaches usage to error results", async () => {
+ it("attaches usage to error results", async () => {
const errorResult: RuntimeSubagentChildResult = {
callId: "call-1",
isError: true,
@@ -141,7 +143,13 @@ describe("notifyDelegatedParentStep", () => {
expect(resumeHookMock).toHaveBeenCalledWith("parent-tok", {
kind: "runtime-action-result",
- results: [errorResult],
+ results: [
+ {
+ ...errorResult,
+ outcome: { ...errorResult.outcome, usageDelta: USAGE },
+ usage: USAGE,
+ },
+ ],
});
});
});
@@ -177,6 +185,50 @@ describe("turn caller notification", () => {
expect(resumeHookMock).not.toHaveBeenCalled();
});
+ it("binds a local task hook to the exact child turn before execution", async () => {
+ await notifyTaskTurnStartedStep({
+ caller: {
+ callId: "call-task",
+ replyTo: { kind: "hook", token: "task-token" },
+ subagentName: "research",
+ taskId: "task-1",
+ },
+ childSessionId: "child-session",
+ childTurnId: "turn_child_7",
+ });
+
+ expect(resumeHookMock).toHaveBeenCalledWith("task-token", {
+ childSessionId: "child-session",
+ childTurnId: "turn_child_7",
+ kind: "turn-started",
+ taskId: "task-1",
+ });
+ });
+
+ it("posts the same task turn identity through a remote callback", async () => {
+ await notifyTaskTurnStartedStep({
+ caller: {
+ callId: "call-task",
+ replyTo: {
+ kind: "callback",
+ token: "task-token",
+ url: "https://parent.example/eve/v1/callback/task-token",
+ },
+ subagentName: "research",
+ taskId: "task-1",
+ },
+ childSessionId: "child-session",
+ childTurnId: "turn_child_7",
+ });
+
+ expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string)).toMatchObject({
+ kind: "turn.started",
+ sessionId: "child-session",
+ taskId: "task-1",
+ turnId: "turn_child_7",
+ });
+ });
+
it("uses the adapter state for the child's first settled turn", async () => {
const serializedContext = createSerializedContext();
const caller = await resolveInitialTurnCallerStep({ serializedContext });
@@ -355,6 +407,7 @@ describe("turn caller notification", () => {
callId: "call-remote",
replyTo: {
kind: "callback",
+ token: "parent-turn",
url: "https://caller.example/eve/v1/callback/parent-turn",
},
subagentName: "remote",
@@ -415,3 +468,61 @@ describe("turn caller notification", () => {
}
});
});
+
+describe("task turn caller binding", () => {
+ it("rebinds local adapter forwarding to the current task", async () => {
+ const serializedContext = {
+ [ChannelKey.name]: {
+ kind: SUBAGENT_ADAPTER_KIND,
+ state: {
+ callId: "call-old",
+ parentContinuationToken: "task-old",
+ parentSessionId: "parent",
+ subagentName: "research",
+ },
+ },
+ };
+
+ await expect(
+ bindTurnCallerContextStep({
+ caller: {
+ callId: "call-new",
+ replyTo: { kind: "hook", token: "task-new" },
+ subagentName: "research",
+ taskId: "task-new",
+ },
+ serializedContext,
+ }),
+ ).resolves.toMatchObject({
+ [ChannelKey.name]: {
+ state: { callId: "call-new", parentContinuationToken: "task-new" },
+ },
+ });
+ });
+
+ it("rebinds remote callback forwarding to the current task", async () => {
+ await expect(
+ bindTurnCallerContextStep({
+ caller: {
+ callId: "call-new",
+ replyTo: {
+ kind: "callback",
+ token: "task-new",
+ url: "https://parent.example/eve/v1/callback/task-new",
+ },
+ subagentName: "research",
+ taskId: "task-new",
+ },
+ serializedContext: {},
+ }),
+ ).resolves.toEqual({
+ [SessionCallbackKey.name]: {
+ callId: "call-new",
+ subagentName: "research",
+ taskId: "task-new",
+ token: "task-new",
+ url: "https://parent.example/eve/v1/callback/task-new",
+ },
+ });
+ });
+});
diff --git a/packages/eve/src/execution/delegated-parent-notification.ts b/packages/eve/src/execution/delegated-parent-notification.ts
index 66b39334a..7c89a0c87 100644
--- a/packages/eve/src/execution/delegated-parent-notification.ts
+++ b/packages/eve/src/execution/delegated-parent-notification.ts
@@ -12,6 +12,7 @@ import { SessionCallbackKey } from "#context/keys.js";
import {
isSubagentAdapterState,
SUBAGENT_ADAPTER_KIND,
+ type SubagentAdapterState,
} from "#execution/subagent-adapter-state.js";
import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";
import { SUBAGENT_EXECUTION_FAILED } from "#harness/agent-handle-errors.js";
@@ -22,6 +23,8 @@ import { parseJsonValue } from "#shared/json.js";
import type { TokenUsage } from "#shared/token-usage.js";
import { resumeHook } from "#internal/workflow/runtime.js";
import { postSessionCallbackRequest } from "#execution/session-callback-request.js";
+import type { TaskInboundTurnStarted } from "#tasks/types.js";
+import { readTaskIdFromInboxToken } from "#tasks/task-id.js";
const log = createLogger("execution.delegated-parent-notification");
@@ -60,7 +63,7 @@ export async function notifyDelegatedParentStep(input: {
// are the turn's usage delta; the terminal envelope carries them so the
// parent folds spend from the outcome alone.
const result =
- input.usage === undefined || input.result.isError === true
+ input.usage === undefined
? input.result
: {
...input.result,
@@ -129,6 +132,76 @@ export async function notifyTurnCallerStep(input: {
await resumeSettledTurnHook(input.caller.replyTo.token, result);
}
+/** Settles a task-owned caller after the child turn is cooperatively cancelled. */
+export async function notifyCancelledTaskCallerStep(input: {
+ readonly caller: TurnCaller | undefined;
+ readonly sessionId: string;
+ readonly usage?: TokenUsage;
+}): Promise<void> {
+ "use step";
+
+ if (input.caller?.taskId === undefined) return;
+ const usageDelta = input.usage ?? ZERO_TOKEN_USAGE;
+ const base: RuntimeSubagentChildResult = {
+ callId: input.caller.callId,
+ kind: "subagent-result",
+ origin: "child",
+ outcome: {
+ kind: "parked",
+ result: { kind: "cancelled" },
+ usageDelta,
+ },
+ output: "",
+ subagentName: input.caller.subagentName,
+ };
+ const result = input.usage === undefined ? base : { ...base, usage: input.usage };
+ if (input.caller.replyTo.kind === "callback") {
+ await postSettledTurnCallback({
+ result,
+ sessionId: input.sessionId,
+ url: input.caller.replyTo.url,
+ });
+ return;
+ }
+ await resumeSettledTurnHook(input.caller.replyTo.token, result);
+}
+
+/** Binds a durable task to the exact child turn before execution starts. */
+export async function notifyTaskTurnStartedStep(input: {
+ readonly caller: TurnCaller | undefined;
+ readonly childSessionId: string;
+ readonly childTurnId: string;
+}): Promise<void> {
+ "use step";
+
+ const taskId = input.caller?.taskId;
+ if (input.caller === undefined || taskId === undefined) return;
+ const payload: TaskInboundTurnStarted = {
+ childSessionId: input.childSessionId,
+ childTurnId: input.childTurnId,
+ kind: "turn-started",
+ taskId,
+ };
+ if (input.caller.replyTo.kind === "hook") {
+ await resumeHook(input.caller.replyTo.token, payload);
+ return;
+ }
+ const response = await postSessionCallbackRequest({
+ body: {
+ callId: input.caller.callId,
+ kind: "turn.started",
+ sessionId: input.childSessionId,
+ subagentName: input.caller.subagentName,
+ taskId,
+ turnId: input.childTurnId,
+ },
+ url: input.caller.replyTo.url,
+ });
+ if (!response.ok) {
+ throw new Error(`Task turn-start callback failed with HTTP ${response.status}.`);
+ }
+}
+
function createSettledTurnResult(input: {
readonly caller: TurnCaller;
readonly lifecycle: AgentTurnOutcome["kind"];
@@ -191,8 +264,13 @@ export async function resolveInitialTurnCallerStep(input: {
}
return {
callId: parsed.callback.callId,
- replyTo: { kind: "callback", url: parsed.callback.url },
+ replyTo: {
+ kind: "callback",
+ token: parsed.callback.token,
+ url: parsed.callback.url,
+ },
subagentName: parsed.callback.subagentName,
+ taskId: parsed.callback.taskId ?? readTaskIdFromInboxToken(parsed.callback.token),
};
}
@@ -206,6 +284,53 @@ export async function resolveInitialTurnCallerStep(input: {
callId: adapter.state.callId,
replyTo: { kind: "hook", token: adapter.state.parentContinuationToken },
subagentName: adapter.state.subagentName,
+ taskId: readTaskIdFromInboxToken(adapter.state.parentContinuationToken),
+ };
+}
+
+/** Rebinds child event forwarding to the task that owns the next accepted turn. */
+export async function bindTurnCallerContextStep(input: {
+ readonly caller: TurnCaller | undefined;
+ readonly serializedContext: Record<string, unknown>;
+}): Promise<Record<string, unknown>> {
+ "use step";
+
+ const caller = input.caller;
+ if (caller?.taskId === undefined) return input.serializedContext;
+ if (caller.replyTo.kind === "callback") {
+ return {
+ ...input.serializedContext,
+ [SessionCallbackKey.name]: {
+ callId: caller.callId,
+ subagentName: caller.subagentName,
+ taskId: caller.taskId,
+ token: caller.replyTo.token,
+ url: caller.replyTo.url,
+ },
+ };
+ }
+
+ const adapter = input.serializedContext[ChannelKey.name];
+ if (
+ adapter === null ||
+ typeof adapter !== "object" ||
+ Reflect.get(adapter, "kind") !== SUBAGENT_ADAPTER_KIND ||
+ !isSubagentAdapterState(Reflect.get(adapter, "state"))
+ ) {
+ throw new Error("Task-owned local turn is missing its subagent adapter binding.");
+ }
+ const state = Reflect.get(adapter, "state") as SubagentAdapterState;
+ return {
+ ...input.serializedContext,
+ [ChannelKey.name]: {
+ ...adapter,
+ state: {
+ ...state,
+ callId: caller.callId,
+ parentContinuationToken: caller.replyTo.token,
+ subagentName: caller.subagentName,
+ },
+ },
};
}
diff --git a/packages/eve/src/execution/deliver-payloads.ts b/packages/eve/src/execution/deliver-payloads.ts
index 8aeff8087..2f4940fff 100644
--- a/packages/eve/src/execution/deliver-payloads.ts
+++ b/packages/eve/src/execution/deliver-payloads.ts
@@ -2,7 +2,15 @@ import type { DeliverPayload } from "#channel/types.js";
import { coalesceTurnInputs } from "#harness/messages.js";
import type { StepInput } from "#harness/types.js";
-const COALESCED_DELIVER_FIELDS = ["context", "inputResponses", "message", "outputSchema"] as const;
+const COALESCED_DELIVER_FIELDS = [
+ "context",
+ "inputResponses",
+ "message",
+ "outputSchema",
+ "task",
+] as const;
+
+type TaskEnvelope = NonNullable<DeliverPayload["task"]>;
/** Coalesces channel payloads while preserving turn input and adapter-specific fields. */
export function coalesceDeliverPayloads(payloads: readonly DeliverPayload[]): DeliverPayload {
@@ -10,9 +18,15 @@ export function coalesceDeliverPayloads(payloads: readonly DeliverPayload[]): De
if (payloads.length === 1) return payloads[0] ?? {};
const merged: Record<string, unknown> = {};
+ const inputRequests: NonNullable<TaskEnvelope["inputRequests"]>[number][] = [];
+ const authorizationEvents: NonNullable<TaskEnvelope["authorizationEvents"]>[number][] = [];
+ const views: NonNullable<TaskEnvelope["views"]>[number][] = [];
let turnInput: StepInput = {};
for (const payload of payloads) {
+ inputRequests.push(...(payload.task?.inputRequests ?? []));
+ authorizationEvents.push(...(payload.task?.authorizationEvents ?? []));
+ views.push(...(payload.task?.views ?? []));
for (const [key, value] of Object.entries(payload)) {
if (value !== undefined) {
merged[key] = value;
@@ -25,5 +39,11 @@ export function coalesceDeliverPayloads(payloads: readonly DeliverPayload[]): De
delete merged[field];
}
+ const task: Record<string, unknown> = {};
+ if (inputRequests.length > 0) task.inputRequests = inputRequests;
+ if (authorizationEvents.length > 0) task.authorizationEvents = authorizationEvents;
+ if (views.length > 0) task.views = views;
+ if (Object.keys(task).length > 0) merged.task = task;
+
return Object.assign(merged, turnInput);
}
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-shared.ts b/packages/eve/src/execution/dispatch-runtime-actions-shared.ts
new file mode 100644
index 000000000..f7fb06351
--- /dev/null
+++ b/packages/eve/src/execution/dispatch-runtime-actions-shared.ts
@@ -0,0 +1,522 @@
+/**
+ * Machinery shared by the two runtime-action dispatch steps:
+ * `dispatchRuntimeActionsStep` (plain mode) and `dispatchTaskStep`
+ * (task mode). Both run the same preflight → plan → dispatch → emit
+ * skeleton over one pending batch and differ only in the per-entry
+ * delegation lifecycle, so planning, subagent starts, and the
+ * replay-safe `subagent.called` emission tail live here.
+ */
+
+import { buildAdapterContext } from "#channel/adapter-context.js";
+import {
+ callAdapterEventHandler,
+ type ChannelAdapter,
+ type ChannelAdapterContext,
+} from "#channel/adapter.js";
+import {
+ AuthKey,
+ CapabilitiesKey,
+ ChannelInstrumentationKey,
+ InitiatorAuthKey,
+} from "#context/keys.js";
+import {
+ BundleKey,
+ ChannelKey,
+ type CompiledBundle,
+} from "#runtime/sessions/runtime-context-keys.js";
+import { deserializeContext } from "#context/serialize.js";
+import {
+ type DispatchOutcome,
+ isAgentHandleAction,
+ type RuntimeAgentHandleAction,
+ type RuntimeSession,
+} from "#execution/agent-handle-dispatch.js";
+import { getAgentHandleStore } from "#harness/handles/store.js";
+import { readActionTraceContext } from "#tracing/agent-trace-context-store.js";
+import {
+ assertUniqueRuntimeActionCallIds,
+ getPendingRuntimeActionBatch,
+} from "#harness/runtime-actions.js";
+import {
+ createSubagentCalledEvent,
+ encodeMessageStreamEvent,
+ stampMessageStreamEvent,
+} from "#protocol/message.js";
+import type {
+ RuntimeActionRequest,
+ RuntimeActionResult,
+ RuntimeRemoteAgentCallActionRequest,
+ RuntimeSubagentCallActionRequest,
+ RuntimeSubagentDispatchFailure,
+ RuntimeToolCallActionRequest,
+} from "#runtime/actions/types.js";
+import { type DurableSessionState, readDurableSession } from "#execution/durable-session-store.js";
+import {
+ createRecursiveAgentRootOnlyResult,
+ createUnavailableDynamicSubagentResult,
+ getSubagentName,
+} from "#execution/dispatch-action-failures.js";
+import { startLocalSubagent } from "#execution/subagent-start-local.js";
+import { startRemoteSubagent } from "#execution/subagent-start-remote.js";
+import { hydrateDurableSession } from "#execution/session.js";
+import { buildSubagentRunInput, type SubagentInputSource } from "#execution/subagent-tool.js";
+import { workflowEntryReference } from "#execution/workflow-runtime.js";
+import { createLogger, logError } from "#internal/logging.js";
+import { readSessionTraceContext } from "#tracing/agent-trace-context-store.js";
+import { resolveSubagentDepth } from "#harness/subagent-depth.js";
+import { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";
+import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
+import { isTaskControlAction } from "#execution/tasks/parent/dispatch.js";
+
+const log = createLogger("execution.dispatch-runtime-actions");
+
+type DynamicSubagentAgentConfig = NonNullable<
+ Extract<
+ ReturnType<typeof getDynamicSubagentSelection>,
+ { readonly kind: "subagent" }
+ >["agentConfig"]
+>;
+
+type DynamicRemoteAgentConfig = NonNullable<
+ Extract<
+ ReturnType<typeof getDynamicSubagentSelection>,
+ { readonly kind: "remote" }
+ >["remoteAgent"]
+>;
+
+export type DispatchPlanEntry =
+ | {
+ readonly kind: "resume";
+ readonly action: RuntimeAgentHandleAction;
+ readonly agentId: string;
+ readonly dynamicRemoteAgent?: DynamicRemoteAgentConfig;
+ }
+ | { readonly kind: "reject"; readonly result: RuntimeSubagentDispatchFailure }
+ | { readonly kind: "start"; readonly target: DispatchStartTarget }
+ | { readonly kind: "task-control"; readonly action: RuntimeToolCallActionRequest };
+
+export type DispatchStartTarget =
+ | {
+ readonly kind: "local";
+ readonly action: RuntimeSubagentCallActionRequest;
+ readonly dynamicSubagentAgentConfig?: DynamicSubagentAgentConfig;
+ readonly source: SubagentInputSource;
+ }
+ | {
+ readonly kind: "remote";
+ readonly action: RuntimeRemoteAgentCallActionRequest;
+ readonly dynamicRemoteAgent?: DynamicRemoteAgentConfig;
+ };
+
+/** Input contract shared by both dispatch steps so the turn workflow can select either. */
+export interface RuntimeActionDispatchInput {
+ readonly callbackBaseUrl?: string;
+ /** Internal hook that receives child completion and HITL payloads. */
+ readonly parentContinuationToken?: string;
+ readonly parentWritable: WritableStream<Uint8Array>;
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+}
+
+/**
+ * Result contract shared by both dispatch steps. `pendingTasks` is
+ * always empty in plain mode; keeping it on both keeps the turn
+ * workflow's acknowledgement call site uniform.
+ */
+export interface RuntimeActionDispatchResult {
+ readonly results: readonly RuntimeActionResult[];
+ readonly sessionState: DurableSessionState;
+ readonly pendingTasks: readonly {
+ readonly taskInboxToken: string;
+ readonly taskId: string;
+ readonly taskRunId: string;
+ }[];
+}
+
+/** Everything preflight produces before either step's dispatch loop runs. */
+export interface PreparedRuntimeActionDispatch {
+ readonly adapter: ChannelAdapter;
+ readonly adapterCtx: ChannelAdapterContext;
+ readonly auth: Parameters<typeof buildSubagentRunInput>[0]["auth"];
+ readonly batch: NonNullable<ReturnType<typeof getPendingRuntimeActionBatch>>;
+ readonly bundle: CompiledBundle;
+ readonly capabilities: Parameters<typeof buildSubagentRunInput>[0]["capabilities"];
+ readonly channelMetadata: Parameters<typeof buildSubagentRunInput>[0]["channelMetadata"];
+ /**
+ * Number of freshly started local subagents in the plan. The parent's
+ * remaining token quota is split across these, the children that
+ * actually receive an enforced cap: continuations already run under
+ * their own budget, and remote agents run on their own deployment
+ * under their own limits, so neither dilutes the local shares.
+ */
+ readonly fanoutSize: number;
+ readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];
+ readonly parentTraceContext: Parameters<typeof buildSubagentRunInput>[0]["parentTraceContext"];
+ readonly serializedContext: Record<string, unknown>;
+ readonly plan: readonly DispatchPlanEntry[];
+ readonly session: RuntimeSession;
+}
+
+/**
+ * Runs every dispatch precondition that may throw — durable reads, context
+ * deserialization, handle-store validation, and batch planning — before
+ * the caller acquires the parent stream writer, so a preflight failure
+ * never leaks the writer lock. Returns undefined when no actions are
+ * pending.
+ */
+export async function prepareRuntimeActionDispatch(input: {
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+ /**
+ * Classify `task_peek` / `task_cancel` / `task_send` calls as
+ * task-control plan entries. Only task mode plans them; in plain mode
+ * those calls fail as unsupported batch actions.
+ */
+ readonly taskControls: boolean;
+}): Promise<PreparedRuntimeActionDispatch | undefined> {
+ const durableSession = await readDurableSession(input.sessionState);
+ const batch = getPendingRuntimeActionBatch(durableSession.state);
+
+ if (batch === undefined || batch.actions.length === 0) return undefined;
+ assertUniqueRuntimeActionCallIds(batch.actions);
+
+ const ctx = await deserializeContext(input.serializedContext);
+ const bundle = ctx.require(BundleKey);
+ const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);
+ const session = hydrateDurableSession({
+ compactionOverrides: {
+ thresholdPercent: effectiveAgent.thresholdPercent,
+ },
+ durable: durableSession,
+ turnAgent: effectiveAgent.turnAgent,
+ });
+ const adapter = ctx.require(ChannelKey);
+
+ // A corrupt handle store throws; surface that before anything dispatches.
+ // A mid-loop throw after a sibling started would durably replay the whole
+ // batch and re-dispatch that sibling.
+ getAgentHandleStore(durableSession.state);
+ const plan = planDispatch({
+ actions: batch.actions,
+ bundle,
+ ctx,
+ session,
+ taskControls: input.taskControls,
+ });
+
+ return {
+ adapter,
+ adapterCtx: buildAdapterContext(adapter, ctx),
+ auth: ctx.get(AuthKey) ?? null,
+ batch,
+ bundle,
+ capabilities: ctx.get(CapabilitiesKey),
+ channelMetadata: ctx.get(ChannelInstrumentationKey),
+ fanoutSize: plan.filter((entry) => entry.kind === "start" && entry.target.kind === "local")
+ .length,
+ initiatorAuth: ctx.get(InitiatorAuthKey) ?? null,
+ parentTraceContext: readSessionTraceContext(input.serializedContext, session.sessionId),
+ plan,
+ serializedContext: input.serializedContext,
+ session,
+ };
+}
+
+/**
+ * Emits the parent `subagent.called` control-plane event for one adopted
+ * child. Emission is observability, not control flow: a failure is logged
+ * and swallowed, because a throw escaping the dispatch loop would durably
+ * replay the step and re-dispatch children that already started.
+ */
+export async function emitSubagentCalled(input: {
+ readonly adapter: ChannelAdapter;
+ readonly adapterCtx: ChannelAdapterContext;
+ readonly batchEvent: { readonly sequence: number; readonly turnId: string };
+ readonly entry: Extract<DispatchPlanEntry, { readonly kind: "resume" | "start" }>;
+ readonly outcome: Extract<DispatchOutcome, { readonly kind: "called" }>;
+ readonly sessionId: string;
+ readonly writer: WritableStreamDefaultWriter<Uint8Array>;
+}): Promise<void> {
+ const { entry, outcome } = input;
+ try {
+ const action = entry.kind === "resume" ? entry.action : entry.target.action;
+ const dynamicRemoteAgent =
+ entry.kind === "resume"
+ ? entry.dynamicRemoteAgent
+ : entry.target.kind === "remote"
+ ? entry.target.dynamicRemoteAgent
+ : undefined;
+ const parentEvent = await callAdapterEventHandler(
+ input.adapter,
+ createSubagentCalledEvent({
+ callId: outcome.callId,
+ childSessionId: outcome.address.sessionId,
+ name: outcome.name,
+ remote:
+ outcome.address.kind === "agent/remote"
+ ? {
+ // The proxy route re-resolves outbound auth from this key via
+ // resolveRemoteAgentStreamHeaders: a node id lands in
+ // subagentRegistry.subagentsByNodeId (static definition), a
+ // credentialsStepId lands in the step registry (dynamic
+ // definition). Both sides of this ternary must stay in sync
+ // with that lookup order.
+ resolverId:
+ dynamicRemoteAgent === undefined
+ ? action.nodeId
+ : dynamicRemoteAgent.credentialsStepId,
+ url: outcome.address.url,
+ }
+ : undefined,
+ sequence: input.batchEvent.sequence,
+ sessionId: input.sessionId,
+ toolName: outcome.toolName,
+ turnId: input.batchEvent.turnId,
+ workflowId: workflowEntryReference.workflowId,
+ }),
+ input.adapterCtx,
+ );
+ await input.writer.write(encodeMessageStreamEvent(stampMessageStreamEvent(parentEvent)));
+ } catch (error) {
+ logError(log, "subagent.called emission failed", error, {
+ callId: outcome.callId,
+ childSessionId: outcome.address.sessionId,
+ toolName: outcome.toolName,
+ });
+ }
+}
+
+/**
+ * Classifies every batch action before anything dispatches, so invalid
+ * batches fail without starting children and rejections never interleave
+ * with dispatch work.
+ *
+ * This is the single place that decides fresh start vs. continuation:
+ * an omitted, null, empty, or whitespace-only agentId is a fresh start
+ * (strict tool-calling providers force every schema property to be present,
+ * so models emit `""`/`null` when they mean "no continuation"), and an
+ * agentId that matches no stored handle also falls back to a fresh start —
+ * models sometimes pass a hallucinated or stale id, and hard-failing made
+ * them conclude the subagent itself was unavailable. Only an id that
+ * resolves to a stored handle becomes a resume.
+ */
+function planDispatch(input: {
+ readonly actions: readonly RuntimeActionRequest[];
+ readonly bundle: CompiledBundle;
+ readonly ctx: Parameters<typeof getDynamicSubagentSelection>[0];
+ readonly session: RuntimeSession;
+ readonly taskControls: boolean;
+}): DispatchPlanEntry[] {
+ const handles = getAgentHandleStore(input.session.state)?.handles ?? [];
+
+ return input.actions.map((action): DispatchPlanEntry => {
+ if (input.taskControls && isTaskControlAction(action)) {
+ return { action, kind: "task-control" };
+ }
+
+ const rawAgentId = action.input.agentId;
+ const agentId =
+ typeof rawAgentId === "string" && rawAgentId.trim() !== "" ? rawAgentId : undefined;
+ if (agentId !== undefined && isAgentHandleAction(action)) {
+ // Resume classification runs before the recursion guard: an agentId
+ // continuation resumes an already-adopted child rather than starting
+ // a new one. Unknown ids go through classifyFreshStart below, which
+ // re-applies the guard the resume path bypasses.
+ if (handles.some((handle) => handle.identity.id === agentId)) {
+ const dynamicSubagentSelection =
+ input.bundle.subagentRegistry.dynamicNodeIds?.has(action.nodeId) === true
+ ? getDynamicSubagentSelection(input.ctx, action.nodeId)
+ : undefined;
+ return {
+ action,
+ agentId,
+ dynamicRemoteAgent:
+ action.kind === "remote-agent-call" && dynamicSubagentSelection?.kind === "remote"
+ ? dynamicSubagentSelection.remoteAgent
+ : undefined,
+ kind: "resume",
+ };
+ }
+ log.warn("unknown agentId on subagent call; starting a new agent", {
+ agentId,
+ callId: action.callId,
+ });
+ }
+
+ return classifyFreshStart({
+ action,
+ bundle: input.bundle,
+ ctx: input.ctx,
+ session: input.session,
+ });
+ });
+}
+
+/**
+ * Classifies one action for fresh dispatch: rejected by the recursion guard,
+ * or started against a local/remote target. Shared by plain starts and the
+ * unknown-agentId fallback, so both paths enforce the same guard.
+ */
+function classifyFreshStart(input: {
+ readonly action: RuntimeActionRequest;
+ readonly bundle: CompiledBundle;
+ readonly ctx: Parameters<typeof getDynamicSubagentSelection>[0];
+ readonly session: RuntimeSession;
+}): Extract<DispatchPlanEntry, { kind: "reject" | "start" }> {
+ const { action } = input;
+ const registry = input.bundle.subagentRegistry.subagentsByNodeId;
+ const subagentDepth = resolveSubagentDepth(input.session);
+ const rootOnly = input.session.rootSessionId !== undefined || subagentDepth.currentDepth > 0;
+
+ const isDynamicSubagent =
+ (action.kind === "subagent-call" || action.kind === "remote-agent-call") &&
+ input.bundle.subagentRegistry.dynamicNodeIds?.has(action.nodeId) === true;
+ const dynamicSubagentSelection = isDynamicSubagent
+ ? getDynamicSubagentSelection(input.ctx, action.nodeId)
+ : undefined;
+ if (
+ isDynamicSubagent &&
+ (dynamicSubagentSelection === undefined ||
+ (action.kind === "subagent-call" && dynamicSubagentSelection.kind !== "subagent") ||
+ (action.kind === "remote-agent-call" && dynamicSubagentSelection.kind !== "remote"))
+ ) {
+ const subagentName = getSubagentName(action);
+ log.warn("dynamic subagent call blocked after availability changed", {
+ callId: action.callId,
+ nodeId: action.nodeId,
+ subagentName,
+ });
+ return { kind: "reject", result: createUnavailableDynamicSubagentResult(action) };
+ }
+
+ if (isRecursiveAgentAction(action, registry) && rootOnly) {
+ log.warn("recursive agent call blocked outside the root session", {
+ callId: action.callId,
+ currentDepth: subagentDepth.currentDepth,
+ nodeId: action.nodeId,
+ subagentName: action.subagentName,
+ });
+ return { kind: "reject", result: createRecursiveAgentRootOnlyResult(action) };
+ }
+
+ switch (action.kind) {
+ case "subagent-call": {
+ const dynamicAgentConfig =
+ dynamicSubagentSelection?.kind === "subagent"
+ ? dynamicSubagentSelection.agentConfig
+ : undefined;
+ const registered = registry.get(action.nodeId);
+ const description =
+ dynamicAgentConfig?.description ??
+ (registered?.definition.kind === "subagent"
+ ? registered.definition.description
+ : undefined);
+ const source: SubagentInputSource =
+ description !== undefined ? { description, type: "local" } : { type: "runtime" };
+ return {
+ kind: "start",
+ target: {
+ action,
+ dynamicSubagentAgentConfig: dynamicAgentConfig,
+ kind: "local",
+ source,
+ },
+ };
+ }
+ case "remote-agent-call":
+ return {
+ kind: "start",
+ target: {
+ action,
+ dynamicRemoteAgent:
+ dynamicSubagentSelection?.kind === "remote"
+ ? dynamicSubagentSelection.remoteAgent
+ : undefined,
+ kind: "remote",
+ },
+ };
+ default:
+ throw new Error(`Unsupported runtime action kind "${action.kind}" in workflow runtime.`);
+ }
+}
+
+/** Starts one planned fresh child against its local or remote target. */
+export async function startSubagent(input: {
+ readonly auth: Parameters<typeof buildSubagentRunInput>[0]["auth"];
+ readonly batchEvent: { readonly sequence: number; readonly turnId: string };
+ readonly bundle: CompiledBundle;
+ readonly callbackBaseUrl: string | undefined;
+ readonly capabilities: Parameters<typeof buildSubagentRunInput>[0]["capabilities"];
+ readonly channelMetadata: Parameters<typeof buildSubagentRunInput>[0]["channelMetadata"];
+ readonly currentSession: RuntimeSession;
+ readonly fanoutSize: number;
+ readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];
+ readonly parentContinuationToken: string | undefined;
+ readonly parentTraceContext: Parameters<typeof buildSubagentRunInput>[0]["parentTraceContext"];
+ readonly persistentSessions: boolean;
+ readonly serializedContext: Record<string, unknown>;
+ readonly session: RuntimeSession;
+ readonly taskOwned: boolean;
+ readonly target: DispatchStartTarget;
+}): Promise<DispatchOutcome> {
+ const parentTraceContext =
+ readActionTraceContext(
+ input.serializedContext,
+ input.session.sessionId,
+ input.batchEvent.turnId,
+ input.target.action.callId,
+ ) ?? input.parentTraceContext;
+
+ switch (input.target.kind) {
+ case "local":
+ return startLocalSubagent({
+ action: input.target.action,
+ auth: input.auth,
+ batchEvent: input.batchEvent,
+ bundle: input.bundle,
+ capabilities: input.capabilities,
+ channelMetadata: input.channelMetadata,
+ currentSession: input.currentSession,
+ dynamicSubagentAgentConfig: input.target.dynamicSubagentAgentConfig,
+ fanoutSize: input.fanoutSize,
+ initiatorAuth: input.initiatorAuth,
+ parentContinuationToken: input.parentContinuationToken,
+ parentTraceContext,
+ persistentSessions: input.persistentSessions,
+ session: input.session,
+ source: input.target.source,
+ taskOwned: input.taskOwned,
+ });
+ case "remote":
+ return startRemoteSubagent({
+ action: input.target.action,
+ auth: input.auth,
+ batchEvent: input.batchEvent,
+ bundle: input.bundle,
+ callbackBaseUrl: input.callbackBaseUrl,
+ currentSession: input.currentSession,
+ dynamicRemoteAgent: input.target.dynamicRemoteAgent,
+ initiatorAuth: input.initiatorAuth,
+ parentContinuationToken: input.parentContinuationToken,
+ parentTraceContext,
+ persistentSessions: input.persistentSessions,
+ session: input.session,
+ taskOwned: input.taskOwned,
+ });
+ default: {
+ const _exhaustive: never = input.target;
+ return _exhaustive;
+ }
+ }
+}
+
+function isRecursiveAgentAction(
+ action: RuntimeActionRequest,
+ subagentsByNodeId: ReadonlyMap<string, unknown>,
+): action is RuntimeSubagentCallActionRequest {
+ return (
+ action.kind === "subagent-call" &&
+ action.subagentName === "agent" &&
+ !subagentsByNodeId.has(action.nodeId)
+ );
+}
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts
index 2b271a6fc..caedd2803 100644
--- a/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts
+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts
@@ -2,10 +2,11 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ChannelAdapter } from "#channel/adapter.js";
import { RemoteAgentContinueRequestError } from "#execution/remote-agent-dispatch.js";
+import { RuntimeSessionOwnershipConflictError } from "#execution/runtime-errors.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
import { dispatchRuntimeActionsStep } from "#execution/dispatch-runtime-actions-step.js";
+import { dispatchTaskStep } from "#execution/tasks/parent/dispatch-task-step.js";
import {
- getPendingRuntimeActionBatch,
resolvePendingRuntimeActions,
setPendingRuntimeActionBatch,
} from "#harness/runtime-actions.js";
@@ -17,6 +18,9 @@ import {
type AgentHandle,
} from "#harness/handles/store.js";
import type { HarnessSession } from "#harness/types.js";
+import { getSessionTaskIndex } from "#tasks/session-index.js";
+import { recordSessionTask } from "#tasks/session-index.js";
+import * as taskRunControl from "#execution/tasks/parent/run-parent.js";
import {
AuthKey,
CapabilitiesKey,
@@ -32,8 +36,10 @@ const mocks = vi.hoisted(() => ({
dispatchSession: vi.fn(),
hydrateDurableSession: vi.fn(),
readDurableSession: vi.fn(),
+ resumeHook: vi.fn(),
createSession: vi.fn(),
startRemoteAgentSession: vi.fn(),
+ startWorkflowPreferLatest: vi.fn(),
}));
vi.mock("#context/serialize.js", () => ({
@@ -45,6 +51,11 @@ vi.mock("#execution/durable-session-store.js", () => ({
readDurableSession: mocks.readDurableSession,
}));
+vi.mock("#internal/workflow/runtime.js", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("#internal/workflow/runtime.js")>()),
+ resumeHook: mocks.resumeHook,
+}));
+
vi.mock("#execution/session.js", () => ({
hydrateDurableSession: mocks.hydrateDurableSession,
mintSubagentContinuationToken: (seed: string) => `subagent:${seed}`,
@@ -56,6 +67,9 @@ vi.mock("#execution/workflow-runtime.js", () => ({
dispatchSession: mocks.dispatchSession,
}),
workflowEntryReference: { workflowId: "workflow//eve//workflowEntry" },
+ startWorkflowPreferLatest: mocks.startWorkflowPreferLatest,
+ taskRunWorkflowReference: { workflowId: "workflow//eve//taskRun" },
+ waitForCommandHookOwner: vi.fn().mockResolvedValue({ runId: "task-run-1" }),
}));
// Only the network calls are mocked; error classification and registry
@@ -133,6 +147,8 @@ beforeEach(() => {
mocks.startRemoteAgentSession.mockResolvedValue({
sessionId: "remote-session-123456789012",
});
+ mocks.startWorkflowPreferLatest.mockResolvedValue({ runId: "task-run-1" });
+ mocks.resumeHook.mockResolvedValue({ runId: "task-run-1" });
mocks.hydrateDurableSession.mockImplementation(({ durable }) => durable);
mocks.createDurableSessionState.mockImplementation(({ session }) => ({
...BASE_STATE,
@@ -217,63 +233,114 @@ describe("dispatchRuntimeActionsStep child starts", () => {
expect(writes).toHaveLength(1);
});
- it("uses the active session turn when pending batch metadata has an empty turn id", async () => {
- const session = createStartSession({
- event: { sequence: 3, stepIndex: 2, turnId: "" },
- kind: "local",
- });
- installContext(session, {
- definition: { description: "Research", kind: "subagent" },
- nodeId: "subagents/research",
+ it("records a tasks-mode child as an address and derives task identity separately", async () => {
+ const session = createStartSession({ kind: "local" });
+ installContext(
+ session,
+ { definition: { description: "Research", kind: "subagent" }, nodeId: "subagents/research" },
+ true,
+ );
+ vi.spyOn(taskRunControl, "sendTaskCommandToOwner").mockResolvedValue({
+ runId: "task-run-1",
});
- const result = await dispatchRuntimeActionsStep({
+ // Tasks-mode dispatch routes through dispatchTaskStep; the turn workflow
+ // never sends `experimental.tasks` agents to dispatchRuntimeActionsStep.
+ const result = await dispatchTaskStep({
parentContinuationToken: "turn-inbox",
parentWritable: createWritable(),
serializedContext: {},
- sessionState: {
- ...BASE_STATE,
- emissionState: { sequence: 3, sessionStarted: true, stepIndex: 2, turnId: "" },
- },
+ sessionState: BASE_STATE,
});
+ const state = readResultSessionState(result, session);
+ const agentId = deriveAgentId("research", startOperationId);
- const resultState = readResultSessionState(result, session);
- expect(getPendingRuntimeActionBatch(resultState)?.event.turnId).toBe("turn_3");
- expect(getAgentHandleStore(resultState)).toMatchObject({
+ expect(result.results[0]).toMatchObject({
+ origin: "child",
+ output: { agentId, status: "working" },
+ });
+ expect(getAgentHandleStore(state)).toEqual({
handles: [
{
- operation: {
- parentTurnId: "turn_3",
+ address: {
+ continuationToken: "subagent:parent-session:call-1",
+ kind: "agent/local",
+ sessionId: CHILD_SESSION_ID,
+ },
+ identity: {
+ id: agentId,
+ name: "research",
+ nodeId: "subagents/research",
},
+ phase: "addressed",
},
],
});
+ expect(getSessionTaskIndex(state)).toEqual([
+ expect.objectContaining({
+ metadata: expect.objectContaining({ agentId }),
+ taskRunId: "task-run-1",
+ }),
+ ]);
});
- it("persists the active turn when dispatch leaves agent handles unchanged", async () => {
- const session = createStartSession({
- event: { sequence: 3, stepIndex: 2, turnId: "" },
- kind: "remote",
+ it("silently rejects a tasks-mode start that failed before index admission", async () => {
+ const session = createStartSession({ kind: "local" });
+ installContext(
+ session,
+ { definition: { description: "Research", kind: "subagent" }, nodeId: "subagents/research" },
+ true,
+ );
+ mocks.createSession.mockRejectedValue(new Error("child start failed"));
+ vi.spyOn(taskRunControl, "sendTaskCommandToOwner").mockResolvedValue({ runId: "task-run-1" });
+
+ const result = await dispatchTaskStep({
+ parentContinuationToken: "turn-inbox",
+ parentWritable: createWritable(),
+ serializedContext: {},
+ sessionState: BASE_STATE,
});
+ const state = readResultSessionState(result, session);
+
+ expect(result.pendingTasks).toEqual([]);
+ expect(getSessionTaskIndex(state)).toEqual([]);
+ expect(result.results[0]).toMatchObject({
+ isError: true,
+ output: { code: "SUBAGENT_START_FAILED" },
+ });
+ expect(mocks.resumeHook).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ command: expect.objectContaining({ kind: "reject-dispatch" }) }),
+ );
+ });
+
+ it("adopts the child a replayed start already created instead of failing it", async () => {
+ const session = createStartSession({ kind: "local" });
installContext(session, {
- definition: REMOTE_REGISTRY_DEFINITION,
- nodeId: "remote/research",
+ definition: { description: "Research", kind: "subagent" },
+ nodeId: "subagents/research",
});
+ // A retried dispatch step re-derives the same deterministic child
+ // continuation token, so the first attempt's child owns it.
+ mocks.createSession.mockRejectedValue(
+ new RuntimeSessionOwnershipConflictError({
+ continuationToken: "subagent:parent-session:call-1",
+ ownerSessionId: CHILD_SESSION_ID,
+ sessionId: "duplicate-child",
+ }),
+ );
const result = await dispatchRuntimeActionsStep({
parentContinuationToken: "turn-inbox",
parentWritable: createWritable(),
serializedContext: {},
- sessionState: {
- ...BASE_STATE,
- emissionState: { sequence: 3, sessionStarted: true, stepIndex: 2, turnId: "" },
- },
+ sessionState: BASE_STATE,
});
- const resultState = readResultSessionState(result, session);
- expect(getAgentHandleStore(resultState)).toBeUndefined();
- expect(getPendingRuntimeActionBatch(resultState)?.event.turnId).toBe("turn_3");
- expect(mocks.createDurableSessionState).toHaveBeenCalledTimes(1);
+ expect(result.results).toEqual([]);
+ expect(getAgentHandleStore(readResultSessionState(result, session))?.handles[0]).toMatchObject({
+ address: { kind: "agent/local", sessionId: CHILD_SESSION_ID },
+ });
});
it("rejects the prepared handle when the local start fails", async () => {
@@ -302,6 +369,44 @@ describe("dispatchRuntimeActionsStep child starts", () => {
});
});
+ it("adopts the child a replayed start already created instead of failing it", async () => {
+ const session = createStartSession({ kind: "local" });
+ installContext(session, {
+ definition: { description: "Research", kind: "subagent" },
+ nodeId: "subagents/research",
+ });
+ // A retried dispatch step re-derives the same deterministic child
+ // continuation token, so the first attempt's child owns it.
+ mocks.createSession.mockRejectedValue(
+ new RuntimeSessionOwnershipConflictError({
+ continuationToken: "subagent:parent-session:call-1",
+ ownerSessionId: CHILD_SESSION_ID,
+ sessionId: "duplicate-child",
+ }),
+ );
+
+ const result = await dispatchRuntimeActionsStep({
+ parentContinuationToken: "turn-inbox",
+ parentWritable: createWritable(),
+ serializedContext: {},
+ sessionState: BASE_STATE,
+ });
+
+ expect(result.results).toEqual([]);
+ expect(getAgentHandleStore(readResultSessionState(result, session))).toEqual({
+ handles: [
+ expect.objectContaining({
+ address: {
+ continuationToken: "subagent:parent-session:call-1",
+ kind: "agent/local",
+ sessionId: CHILD_SESSION_ID,
+ },
+ phase: "running",
+ }),
+ ],
+ });
+ });
+
it("owns a remote child with its confirmed remote address", async () => {
const session = createStartSession({ kind: "remote" });
const traceId = "4".repeat(32);
@@ -462,6 +567,56 @@ describe("dispatchRuntimeActionsStep child starts", () => {
});
describe("dispatchRuntimeActionsStep agent delivery", () => {
+ it("rejects a tasks-mode continuation while the addressed agent has active work", async () => {
+ const addressedHandle: AgentHandle = {
+ address: LOCAL_PARKED_HANDLE.address,
+ identity: LOCAL_PARKED_HANDLE.identity,
+ phase: "addressed",
+ };
+ let session = createPendingSession({
+ handle: addressedHandle,
+ agentId: addressedHandle.identity.id,
+ });
+ session = recordSessionTask(session, {
+ taskInboxToken: "task-token",
+ createdByTurnId: "turn-previous",
+ metadata: {
+ agentId: addressedHandle.identity.id,
+ kind: "subagent",
+ mode: "local",
+ name: addressedHandle.identity.name,
+ },
+ operationId: "operation-active",
+ taskId: "task_active",
+ taskRunId: "task-run-active",
+ });
+ installContext(session, undefined, true);
+ vi.spyOn(taskRunControl, "readLatestTaskView").mockResolvedValue({
+ metadata: {
+ agentId: addressedHandle.identity.id,
+ kind: "subagent",
+ mode: "local",
+ name: addressedHandle.identity.name,
+ },
+ status: "working",
+ taskId: "task_active",
+ });
+
+ const result = await dispatchTaskStep({
+ parentContinuationToken: "turn-inbox",
+ parentWritable: createWritable(),
+ serializedContext: {},
+ sessionState: BASE_STATE,
+ });
+
+ expect(result.results[0]).toMatchObject({
+ isError: true,
+ output: { code: "AGENT_BUSY", message: expect.stringContaining("task_active") },
+ });
+ expect(mocks.dispatchSession).not.toHaveBeenCalled();
+ expect(mocks.startWorkflowPreferLatest).not.toHaveBeenCalled();
+ });
+
const continueOperationId = deriveAgentOperationId({
callId: "call-1",
parentSessionId: "parent-session",
@@ -681,7 +836,7 @@ describe("dispatchRuntimeActionsStep agent delivery", () => {
mocks.continueRemoteAgentSession.mockRejectedValue(
new RemoteAgentContinueRequestError(
"continue-session request failed permanently with HTTP 404.",
- { retryable: false },
+ { deliveryAmbiguous: false, retryable: false },
),
);
@@ -862,6 +1017,7 @@ function createPendingSession(input: {
function installContext(
session: HarnessSession,
remote?: { readonly definition: unknown; readonly nodeId: string },
+ tasks = false,
): void {
const subagentsByNodeId = new Map<string, { definition: unknown }>();
if (remote !== undefined) {
@@ -869,7 +1025,7 @@ function installContext(
}
const bundle = {
compiledArtifactsSource: {},
- resolvedAgent: { config: {} },
+ resolvedAgent: { config: tasks ? { experimental: { tasks: true } } : {} },
subagentRegistry: { subagentsByNodeId },
turnAgent: {
id: "test-agent",
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.ts
index c11c803a2..b5d2bd6ba 100644
--- a/packages/eve/src/execution/dispatch-runtime-actions-step.ts
+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.ts
@@ -1,184 +1,66 @@
-/** Starts or continues pending actions, committing ownership before side effects. */
+/**
+ * Starts or continues every pending runtime action for the parked parent
+ * session, with children reporting straight back to the parent turn via
+ * `parentContinuationToken`.
+ *
+ * The batch is classified into a dispatch plan first (reject / resume /
+ * start), then each entry dispatches and emits one
+ * parent `subagent.called` control-plane event through a single tail.
+ * Every start commits an agent handle (`starting`) before its side effect
+ * and confirms it (`running`) once the child reports coordinates, so the
+ * returned snapshot-bearing state owns every child it may have created.
+ *
+ * Agents running `experimental.tasks` never reach this step: the turn
+ * workflow selects `dispatchTaskStep`, the task-mode sibling that wraps
+ * each dispatch in the delegated-task lifecycle.
+ */
-import { buildAdapterContext } from "#channel/adapter-context.js";
-import { callAdapterEventHandler } from "#channel/adapter.js";
-import {
- AuthKey,
- CapabilitiesKey,
- ChannelInstrumentationKey,
- InitiatorAuthKey,
-} from "#context/keys.js";
-import {
- BundleKey,
- ChannelKey,
- type CompiledBundle,
-} from "#runtime/sessions/runtime-context-keys.js";
-import { deserializeContext } from "#context/serialize.js";
-import {
- dispatchToAgentHandle,
- isAgentHandleAction,
- type DispatchOutcome,
- type RuntimeAgentHandleAction,
- type RuntimeSession,
-} from "#execution/agent-handle-dispatch.js";
+import { type DispatchOutcome, dispatchToAgentHandle } from "#execution/agent-handle-dispatch.js";
import { createAgentContinuationBundle } from "#execution/agent-continuation-bundle.js";
-import { SUBAGENT_START_FAILED } from "#harness/agent-handle-errors.js";
-import { getAgentHandleStore } from "#harness/handles/store.js";
-import {
- confirmAgentStarted,
- prepareAgentStart,
- rejectAgentEffect,
-} from "#harness/handles/transitions.js";
-import {
- getPendingRuntimeActionBatch,
- setPendingRuntimeActionBatch,
-} from "#harness/runtime-actions.js";
-import {
- createSubagentCalledEvent,
- encodeMessageStreamEvent,
- stampMessageStreamEvent,
-} from "#protocol/message.js";
-import type {
- RuntimeActionRequest,
- RuntimeRemoteAgentCallActionRequest,
- RuntimeSubagentCallActionRequest,
- RuntimeSubagentDispatchFailure,
- RuntimeSubagentResult,
-} from "#runtime/actions/types.js";
-import {
- createDurableSessionState,
- type DurableSessionState,
- readDurableSession,
-} from "#execution/durable-session-store.js";
import {
- resolveRemoteAgentForAction,
- startRemoteAgentSession,
-} from "#execution/remote-agent-dispatch.js";
-import {
- createRecursiveAgentRootOnlyResult,
- createRemoteAgentStartFailureResult,
- createUnavailableDynamicSubagentResult,
- getSubagentName,
-} from "#execution/dispatch-action-failures.js";
-import { mintStartOperation } from "#execution/dispatch-start-operation.js";
-import { hydrateDurableSession } from "#execution/session.js";
-import { buildSubagentRunInput, type SubagentInputSource } from "#execution/subagent-tool.js";
-import { createWorkflowRuntime, workflowEntryReference } from "#execution/workflow-runtime.js";
-import { createLogger, logError } from "#internal/logging.js";
-import { toErrorMessage } from "#shared/errors.js";
-import * as traceState from "#tracing/agent-trace-context-store.js";
-import { resolveSubagentDepth } from "#harness/subagent-depth.js";
-import { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";
-import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
-import { activeTurnId } from "#harness/active-turn-id.js";
-
-const log = createLogger("execution.dispatch-runtime-actions");
-
-type DynamicSubagentAgentConfig = NonNullable<
- Extract<
- ReturnType<typeof getDynamicSubagentSelection>,
- { readonly kind: "subagent" }
- >["agentConfig"]
->;
-
-type DynamicRemoteAgentConfig = NonNullable<
- Extract<
- ReturnType<typeof getDynamicSubagentSelection>,
- { readonly kind: "remote" }
- >["remoteAgent"]
->;
-
-type DispatchPlanEntry =
- | {
- readonly kind: "resume";
- readonly action: RuntimeAgentHandleAction;
- readonly agentId: string;
- readonly dynamicRemoteAgent?: DynamicRemoteAgentConfig;
- }
- | { readonly kind: "reject"; readonly result: RuntimeSubagentDispatchFailure }
- | { readonly kind: "start"; readonly target: DispatchStartTarget };
-
-type DispatchStartTarget =
- | {
- readonly kind: "local";
- readonly action: RuntimeSubagentCallActionRequest;
- readonly dynamicSubagentAgentConfig?: DynamicSubagentAgentConfig;
- readonly source: SubagentInputSource;
- }
- | {
- readonly kind: "remote";
- readonly action: RuntimeRemoteAgentCallActionRequest;
- readonly dynamicRemoteAgent?: DynamicRemoteAgentConfig;
- };
-
-export async function dispatchRuntimeActionsStep(input: {
- readonly callbackBaseUrl?: string;
- /** Internal hook that receives child completion and HITL payloads. */
- readonly parentContinuationToken?: string;
- readonly parentWritable: WritableStream<Uint8Array>;
- readonly serializedContext: Record<string, unknown>;
- readonly sessionState: DurableSessionState;
-}): Promise<{
- readonly results: readonly RuntimeSubagentResult[];
- readonly sessionState: DurableSessionState;
-}> {
+ emitSubagentCalled,
+ prepareRuntimeActionDispatch,
+ type RuntimeActionDispatchInput,
+ type RuntimeActionDispatchResult,
+ startSubagent,
+} from "#execution/dispatch-runtime-actions-shared.js";
+import { createDurableSessionState } from "#execution/durable-session-store.js";
+import type { RuntimeActionResult } from "#runtime/actions/types.js";
+
+export async function dispatchRuntimeActionsStep(
+ input: RuntimeActionDispatchInput,
+): Promise<RuntimeActionDispatchResult> {
"use step";
- const durableSession = await readDurableSession(input.sessionState);
- const batch = getPendingRuntimeActionBatch(durableSession.state);
-
- if (batch === undefined || batch.actions.length === 0) {
- return { results: [], sessionState: input.sessionState };
- }
-
- const parentTurnId = batch.event.turnId || activeTurnId(input.sessionState.emissionState);
- const batchEvent = { ...batch.event, turnId: parentTurnId };
-
- const ctx = await deserializeContext(input.serializedContext);
- const bundle = ctx.require(BundleKey);
- const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);
- const session = setPendingRuntimeActionBatch({
- ...batch,
- event: batchEvent,
- session: hydrateDurableSession({
- compactionOverrides: { thresholdPercent: effectiveAgent.thresholdPercent },
- durable: durableSession,
- turnAgent: effectiveAgent.turnAgent,
- }),
+ const prepared = await prepareRuntimeActionDispatch({
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
+ taskControls: false,
});
- const adapter = ctx.require(ChannelKey);
- const auth = ctx.get(AuthKey) ?? null;
- const capabilities = ctx.get(CapabilitiesKey);
- const channelMetadata = ctx.get(ChannelInstrumentationKey);
- const initiatorAuth = ctx.get(InitiatorAuthKey) ?? null;
+ if (prepared === undefined) {
+ return { results: [], sessionState: input.sessionState, pendingTasks: [] };
+ }
- const adapterCtx = buildAdapterContext(adapter, ctx);
- // This is the last place the parent's session-scoped trace state is visible.
- const sessionTraceContext = traceState.readSessionTraceContext(
- input.serializedContext,
- session.sessionId,
- );
+ const { batch, bundle, session } = prepared;
const persistentSessions =
bundle.resolvedAgent.config?.experimental?.subagentPersistentSessions === true;
- // Fail before dispatch; replaying after a sibling starts would duplicate it.
- getAgentHandleStore(durableSession.state);
- const plan = planDispatch({ actions: batch.actions, bundle, ctx, session });
+ // Acquired only once preflight can no longer throw, so a planning failure
+ // never leaks the writer lock.
const writer = input.parentWritable.getWriter();
- // Only fresh local starts share the remaining quota; continuations and
- // remote agents already enforce their own budgets.
- const fanoutSize = plan.filter(
- (entry) => entry.kind === "start" && entry.target.kind === "local",
- ).length;
let nextSession = session;
- const results: RuntimeSubagentResult[] = [];
+ const results: RuntimeActionResult[] = [];
try {
- for (const entry of plan) {
+ for (const entry of prepared.plan) {
if (entry.kind === "reject") {
results.push(entry.result);
continue;
}
+ if (entry.kind === "task-control") {
+ // Unreachable: the plan was built with `taskControls: false`.
+ throw new Error("Task-control actions require the task dispatch step.");
+ }
let outcome: DispatchOutcome;
switch (entry.kind) {
@@ -193,30 +75,26 @@ export async function dispatchRuntimeActionsStep(input: {
}),
currentSession: nextSession,
parentToken: input.parentContinuationToken ?? session.continuationToken,
- parentTurnId,
+ parentTurnId: batch.event.turnId,
});
break;
case "start":
outcome = await startSubagent({
- auth,
- batchEvent,
+ auth: prepared.auth,
+ batchEvent: batch.event,
bundle,
callbackBaseUrl: input.callbackBaseUrl,
- capabilities,
- channelMetadata,
+ capabilities: prepared.capabilities,
+ channelMetadata: prepared.channelMetadata,
currentSession: nextSession,
- fanoutSize,
- initiatorAuth,
+ fanoutSize: prepared.fanoutSize,
+ initiatorAuth: prepared.initiatorAuth,
parentContinuationToken: input.parentContinuationToken,
- parentTraceContext:
- traceState.readActionTraceContext(
- input.serializedContext,
- session.sessionId,
- batch.event.turnId,
- entry.target.action.callId,
- ) ?? sessionTraceContext,
+ parentTraceContext: prepared.parentTraceContext,
persistentSessions,
+ serializedContext: prepared.serializedContext,
session,
+ taskOwned: false,
target: entry.target,
});
break;
@@ -228,471 +106,26 @@ export async function dispatchRuntimeActionsStep(input: {
continue;
}
- // Emission is observability, not control flow: a failure here must not
- // escape the loop, because a durable-step retry would re-dispatch the
- // children that already started.
- try {
- const parentEvent = await callAdapterEventHandler(
- adapter,
- createSubagentCalledEvent({
- callId: outcome.callId,
- childSessionId: outcome.address.sessionId,
- name: outcome.name,
- remote:
- outcome.address.kind === "agent/remote" ? { url: outcome.address.url } : undefined,
- sequence: batchEvent.sequence,
- sessionId: session.sessionId,
- toolName: outcome.toolName,
- turnId: parentTurnId,
- workflowId: workflowEntryReference.workflowId,
- }),
- adapterCtx,
- );
- await writer.write(encodeMessageStreamEvent(stampMessageStreamEvent(parentEvent)));
- } catch (error) {
- logError(log, "subagent.called emission failed", error, {
- callId: outcome.callId,
- childSessionId: outcome.address.sessionId,
- toolName: outcome.toolName,
- });
- }
+ await emitSubagentCalled({
+ adapter: prepared.adapter,
+ adapterCtx: prepared.adapterCtx,
+ batchEvent: batch.event,
+ entry,
+ outcome,
+ sessionId: session.sessionId,
+ writer,
+ });
}
} finally {
writer.releaseLock();
}
- const nextState =
- nextSession === session && batch.event.turnId === parentTurnId
- ? input.sessionState
- : createDurableSessionState({ session: nextSession });
-
return {
results,
- sessionState: nextState,
- };
-}
-
-/**
- * Classifies every batch action before anything dispatches, so invalid
- * batches fail without starting children and rejections never interleave
- * with dispatch work.
- *
- * This is the single place that decides fresh start vs. continuation:
- * an omitted, null, empty, or whitespace-only agentId is a fresh start
- * (strict tool-calling providers force every schema property to be present,
- * so models emit `""`/`null` when they mean "no continuation"), and an
- * agentId that matches no stored handle also falls back to a fresh start —
- * models sometimes pass a hallucinated or stale id, and hard-failing made
- * them conclude the subagent itself was unavailable. Only an id that
- * resolves to a stored handle becomes a resume.
- */
-function planDispatch(input: {
- readonly actions: readonly RuntimeActionRequest[];
- readonly bundle: CompiledBundle;
- readonly ctx: Parameters<typeof getDynamicSubagentSelection>[0];
- readonly session: RuntimeSession;
-}): DispatchPlanEntry[] {
- const handles = getAgentHandleStore(input.session.state)?.handles ?? [];
-
- return input.actions.map((action): DispatchPlanEntry => {
- const rawAgentId = action.input.agentId;
- const agentId =
- typeof rawAgentId === "string" && rawAgentId.trim() !== "" ? rawAgentId : undefined;
- if (agentId !== undefined && isAgentHandleAction(action)) {
- // Resume classification runs before the recursion guard: an agentId
- // continuation resumes an already-adopted child rather than starting
- // a new one. Unknown ids go through classifyFreshStart below, which
- // re-applies the guard the resume path bypasses.
- if (handles.some((handle) => handle.identity.id === agentId)) {
- const dynamicSubagentSelection =
- input.bundle.subagentRegistry.dynamicNodeIds?.has(action.nodeId) === true
- ? getDynamicSubagentSelection(input.ctx, action.nodeId)
- : undefined;
- return {
- action,
- agentId,
- dynamicRemoteAgent:
- action.kind === "remote-agent-call" && dynamicSubagentSelection?.kind === "remote"
- ? dynamicSubagentSelection.remoteAgent
- : undefined,
- kind: "resume",
- };
- }
- log.warn("unknown agentId on subagent call; starting a new agent", {
- agentId,
- callId: action.callId,
- });
- }
-
- return classifyFreshStart({
- action,
- bundle: input.bundle,
- ctx: input.ctx,
- session: input.session,
- });
- });
-}
-
-/**
- * Classifies one action for fresh dispatch: rejected by the recursion guard,
- * or started against a local/remote target. Shared by plain starts and the
- * unknown-agentId fallback, so both paths enforce the same guard.
- */
-function classifyFreshStart(input: {
- readonly action: RuntimeActionRequest;
- readonly bundle: CompiledBundle;
- readonly ctx: Parameters<typeof getDynamicSubagentSelection>[0];
- readonly session: RuntimeSession;
-}): Extract<DispatchPlanEntry, { kind: "reject" | "start" }> {
- const { action } = input;
- const registry = input.bundle.subagentRegistry.subagentsByNodeId;
- const subagentDepth = resolveSubagentDepth(input.session);
- const rootOnly = input.session.rootSessionId !== undefined || subagentDepth.currentDepth > 0;
-
- const isDynamicSubagent =
- (action.kind === "subagent-call" || action.kind === "remote-agent-call") &&
- input.bundle.subagentRegistry.dynamicNodeIds?.has(action.nodeId) === true;
- const dynamicSubagentSelection = isDynamicSubagent
- ? getDynamicSubagentSelection(input.ctx, action.nodeId)
- : undefined;
- if (
- isDynamicSubagent &&
- (dynamicSubagentSelection === undefined ||
- (action.kind === "subagent-call" && dynamicSubagentSelection.kind !== "subagent") ||
- (action.kind === "remote-agent-call" && dynamicSubagentSelection.kind !== "remote"))
- ) {
- const subagentName = getSubagentName(action);
- log.warn("dynamic subagent call blocked after availability changed", {
- callId: action.callId,
- nodeId: action.nodeId,
- subagentName,
- });
- return { kind: "reject", result: createUnavailableDynamicSubagentResult(action) };
- }
-
- if (isRecursiveAgentAction(action, registry) && rootOnly) {
- log.warn("recursive agent call blocked outside the root session", {
- callId: action.callId,
- currentDepth: subagentDepth.currentDepth,
- nodeId: action.nodeId,
- subagentName: action.subagentName,
- });
- return { kind: "reject", result: createRecursiveAgentRootOnlyResult(action) };
- }
-
- switch (action.kind) {
- case "subagent-call": {
- const dynamicAgentConfig =
- dynamicSubagentSelection?.kind === "subagent"
- ? dynamicSubagentSelection.agentConfig
- : undefined;
- const registered = registry.get(action.nodeId);
- const description =
- dynamicAgentConfig?.description ??
- (registered?.definition.kind === "subagent"
- ? registered.definition.description
- : undefined);
- const source: SubagentInputSource =
- description !== undefined ? { description, type: "local" } : { type: "runtime" };
- return {
- kind: "start",
- target: {
- action,
- dynamicSubagentAgentConfig: dynamicAgentConfig,
- kind: "local",
- source,
- },
- };
- }
- case "remote-agent-call":
- return {
- kind: "start",
- target: {
- action,
- dynamicRemoteAgent:
- dynamicSubagentSelection?.kind === "remote"
- ? dynamicSubagentSelection.remoteAgent
- : undefined,
- kind: "remote",
- },
- };
- default:
- throw new Error(`Unsupported runtime action kind "${action.kind}" in workflow runtime.`);
- }
-}
-
-async function startSubagent(input: {
- readonly auth: Parameters<typeof buildSubagentRunInput>[0]["auth"];
- readonly batchEvent: { readonly sequence: number; readonly turnId: string };
- readonly bundle: CompiledBundle;
- readonly callbackBaseUrl: string | undefined;
- readonly capabilities: Parameters<typeof buildSubagentRunInput>[0]["capabilities"];
- readonly channelMetadata: Parameters<typeof buildSubagentRunInput>[0]["channelMetadata"];
- readonly currentSession: RuntimeSession;
- readonly fanoutSize: number;
- readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];
- readonly parentContinuationToken: string | undefined;
- readonly parentTraceContext: Parameters<typeof buildSubagentRunInput>[0]["parentTraceContext"];
- readonly persistentSessions: boolean;
- readonly session: RuntimeSession;
- readonly target: DispatchStartTarget;
-}): Promise<DispatchOutcome> {
- switch (input.target.kind) {
- case "local":
- return startLocalSubagent({
- action: input.target.action,
- auth: input.auth,
- batchEvent: input.batchEvent,
- bundle: input.bundle,
- capabilities: input.capabilities,
- channelMetadata: input.channelMetadata,
- currentSession: input.currentSession,
- dynamicSubagentAgentConfig: input.target.dynamicSubagentAgentConfig,
- fanoutSize: input.fanoutSize,
- initiatorAuth: input.initiatorAuth,
- parentContinuationToken: input.parentContinuationToken,
- parentTraceContext: input.parentTraceContext,
- persistentSessions: input.persistentSessions,
- session: input.session,
- source: input.target.source,
- });
- case "remote":
- return startRemoteSubagent({
- action: input.target.action,
- auth: input.auth,
- batchEvent: input.batchEvent,
- bundle: input.bundle,
- callbackBaseUrl: input.callbackBaseUrl,
- currentSession: input.currentSession,
- dynamicRemoteAgent: input.target.dynamicRemoteAgent,
- initiatorAuth: input.initiatorAuth,
- parentContinuationToken: input.parentContinuationToken,
- parentTraceContext: input.parentTraceContext,
- persistentSessions: input.persistentSessions,
- session: input.session,
- });
- default: {
- const _exhaustive: never = input.target;
- return _exhaustive;
- }
- }
-}
-
-async function startLocalSubagent(input: {
- readonly action: RuntimeSubagentCallActionRequest;
- readonly auth: Parameters<typeof buildSubagentRunInput>[0]["auth"];
- readonly batchEvent: { readonly sequence: number; readonly turnId: string };
- readonly bundle: CompiledBundle;
- readonly capabilities: Parameters<typeof buildSubagentRunInput>[0]["capabilities"];
- readonly channelMetadata: Parameters<typeof buildSubagentRunInput>[0]["channelMetadata"];
- readonly currentSession: RuntimeSession;
- readonly dynamicSubagentAgentConfig?: DynamicSubagentAgentConfig;
- readonly fanoutSize: number;
- readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];
- readonly parentContinuationToken: string | undefined;
- readonly parentTraceContext: Parameters<typeof buildSubagentRunInput>[0]["parentTraceContext"];
- readonly persistentSessions: boolean;
- readonly session: RuntimeSession;
- readonly source: SubagentInputSource;
-}): Promise<DispatchOutcome> {
- const { action, source } = input;
- const childRuntime = createWorkflowRuntime({
- compiledArtifactsSource: input.bundle.compiledArtifactsSource,
- dynamicSubagentAgentConfig: input.dynamicSubagentAgentConfig,
- nodeId: action.nodeId,
- });
- const { childContinuationToken, runInput } = buildSubagentRunInput({
- action,
- auth: input.auth,
- batchEvent: input.batchEvent,
- capabilities: input.capabilities,
- channelMetadata: input.channelMetadata,
- fanoutSize: input.fanoutSize,
- initiatorAuth: input.initiatorAuth,
- parentContinuationToken: input.parentContinuationToken,
- parentTraceContext: input.parentTraceContext,
- persistentSessions: input.persistentSessions,
- session: input.session,
- source,
- });
-
- const targetKind = source.type === "runtime" ? ("agent/self" as const) : ("agent/local" as const);
- const { identity, operation } = mintStartOperation({
- callId: action.callId,
- name: action.subagentName,
- nodeId: action.nodeId,
- parentSessionId: input.session.sessionId,
- parentTurnId: input.batchEvent.turnId,
- });
- // Ownership is recorded before the start side effect, and the prepared
- // (or rejected) store rides every outcome into the step result. The
- // guarantee is intra-step: a crash between the accepted start and the
- // step-result commit still replays the whole dispatch step, so the
- // orphan window shrinks to that boundary rather than disappearing.
- const preparedSession = prepareAgentStart(input.currentSession, {
- identity,
- operation,
- target: { continuationToken: childContinuationToken, kind: targetKind },
- });
-
- let childSessionId: string;
- try {
- const handle = await childRuntime.createSession(runInput);
- childSessionId = handle.sessionId;
- } catch (error) {
- logError(log, "local subagent start failed", error, {
- callId: action.callId,
- nodeId: action.nodeId,
- subagentName: action.subagentName,
- });
- return {
- kind: "error",
- result: {
- callId: action.callId,
- isError: true,
- kind: "subagent-result",
- origin: "dispatch",
- output: {
- code: SUBAGENT_START_FAILED,
- message: toErrorMessage(error),
- },
- subagentName: action.subagentName,
- },
- session: rejectAgentEffect(preparedSession, {
- disposition: "dead",
- operationId: operation.id,
- }),
- };
- }
-
- const address = {
- continuationToken: childContinuationToken,
- kind: targetKind,
- sessionId: childSessionId,
- } as const;
- return {
- address,
- callId: action.callId,
- kind: "called",
- name: action.name,
- session: confirmAgentStarted(preparedSession, {
- address,
- operationId: operation.id,
- }),
- toolName: action.subagentName,
+ sessionState:
+ nextSession === session
+ ? input.sessionState
+ : createDurableSessionState({ session: nextSession }),
+ pendingTasks: [],
};
}
-
-async function startRemoteSubagent(input: {
- readonly action: RuntimeRemoteAgentCallActionRequest;
- readonly auth: Parameters<typeof startRemoteAgentSession>[0]["auth"];
- readonly batchEvent: { readonly sequence: number; readonly turnId: string };
- readonly bundle: CompiledBundle;
- readonly callbackBaseUrl: string | undefined;
- readonly currentSession: RuntimeSession;
- readonly dynamicRemoteAgent?: DynamicRemoteAgentConfig;
- readonly initiatorAuth: Parameters<typeof startRemoteAgentSession>[0]["initiatorAuth"];
- readonly parentContinuationToken: string | undefined;
- readonly parentTraceContext: Parameters<typeof startRemoteAgentSession>[0]["parentTraceContext"];
- readonly persistentSessions: boolean;
- readonly session: RuntimeSession;
-}): Promise<DispatchOutcome> {
- const { action } = input;
-
- // Preflight resolution failures happen before ownership exists, so they
- // reject without touching the handle store.
- let callbackBaseUrl: string;
- let resolvedRemote: ReturnType<typeof resolveRemoteAgentForAction>;
- try {
- if (input.callbackBaseUrl === undefined) {
- throw new Error("Cannot dispatch remote agent without a callback base URL.");
- }
- callbackBaseUrl = input.callbackBaseUrl;
- resolvedRemote = resolveRemoteAgentForAction({
- dynamicRemoteAgent: input.dynamicRemoteAgent,
- nodeId: action.nodeId,
- remoteAgentName: action.remoteAgentName,
- registry: input.bundle.subagentRegistry.subagentsByNodeId,
- });
- } catch (error) {
- logError(log, "remote agent start failed", error, {
- remoteAgentName: action.remoteAgentName,
- nodeId: action.nodeId,
- callId: action.callId,
- });
- return {
- kind: "error",
- result: createRemoteAgentStartFailureResult({ action, error }),
- session: input.currentSession,
- };
- }
-
- const { identity, operation } = mintStartOperation({
- callId: action.callId,
- name: action.remoteAgentName,
- nodeId: action.nodeId,
- parentSessionId: input.session.sessionId,
- parentTurnId: input.batchEvent.turnId,
- });
- const preparedSession = prepareAgentStart(input.currentSession, {
- identity,
- operation,
- target: { callbackBaseUrl, kind: "agent/remote", url: resolvedRemote.url },
- });
-
- try {
- const child = await startRemoteAgentSession({
- action,
- auth: input.auth,
- callbackBaseUrl,
- callbackToken: input.parentContinuationToken,
- initiatorAuth: input.initiatorAuth,
- parentTraceContext: input.parentTraceContext,
- persistentSessions: input.persistentSessions,
- remote: resolvedRemote,
- session: input.session,
- });
- const address = {
- callbackBaseUrl,
- kind: "agent/remote",
- sessionId: child.sessionId,
- url: resolvedRemote.url,
- } as const;
- return {
- address,
- callId: action.callId,
- kind: "called",
- name: action.name,
- session: confirmAgentStarted(preparedSession, {
- address,
- operationId: operation.id,
- }),
- toolName: action.remoteAgentName,
- };
- } catch (error) {
- logError(log, "remote agent start failed", error, {
- remoteAgentName: action.remoteAgentName,
- nodeId: action.nodeId,
- callId: action.callId,
- });
- return {
- kind: "error",
- result: createRemoteAgentStartFailureResult({ action, error }),
- session: rejectAgentEffect(preparedSession, {
- disposition: "dead",
- operationId: operation.id,
- }),
- };
- }
-}
-
-function isRecursiveAgentAction(
- action: RuntimeActionRequest,
- subagentsByNodeId: ReadonlyMap<string, unknown>,
-): action is RuntimeSubagentCallActionRequest {
- return (
- action.kind === "subagent-call" &&
- action.subagentName === "agent" &&
- !subagentsByNodeId.has(action.nodeId)
- );
-}
diff --git a/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts
index 47379b3f6..6606c015e 100644
--- a/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts
+++ b/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts
@@ -1,5 +1,6 @@
import { deserializeContext } from "#context/serialize.js";
import { dispatchRuntimeActionsStep } from "#execution/dispatch-runtime-actions-step.js";
+import { dispatchTaskStep } from "#execution/tasks/parent/dispatch-task-step.js";
import {
createDurableSessionState,
type DurableSessionState,
@@ -19,7 +20,7 @@ import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
import type {
RuntimeActionRequest,
RuntimeSubagentDispatchFailure,
- RuntimeSubagentResult,
+ RuntimeActionResult,
} from "#runtime/actions/types.js";
import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
@@ -33,17 +34,26 @@ export async function dispatchWorkflowRuntimeActionsStep(input: {
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
}): Promise<{
- readonly results: readonly RuntimeSubagentResult[];
+ readonly results: readonly RuntimeActionResult[];
readonly sessionState: DurableSessionState;
+ readonly pendingTasks: readonly {
+ readonly taskInboxToken: string;
+ readonly taskId: string;
+ readonly taskRunId: string;
+ }[];
}> {
"use step";
const durableSession = await readDurableSession(input.sessionState);
const pending = getPendingWorkflowInterrupt(durableSession.state);
- if (pending === undefined) return { results: [], sessionState: input.sessionState };
+ if (pending === undefined) {
+ return { results: [], sessionState: input.sessionState, pendingTasks: [] };
+ }
const actions = buildRuntimeActionsFromWorkflowInterrupt(pending.interrupt);
- if (actions.length === 0) return { results: [], sessionState: input.sessionState };
+ if (actions.length === 0) {
+ return { results: [], sessionState: input.sessionState, pendingTasks: [] };
+ }
const ctx = await deserializeContext(input.serializedContext);
const bundle = ctx.require(BundleKey);
@@ -68,7 +78,7 @@ export async function dispatchWorkflowRuntimeActionsStep(input: {
});
if (plan.allowed.length === 0) {
- return { results: blockedResults, sessionState: input.sessionState };
+ return { results: blockedResults, sessionState: input.sessionState, pendingTasks: [] };
}
const session = hydrateDurableSession({
@@ -86,7 +96,13 @@ export async function dispatchWorkflowRuntimeActionsStep(input: {
session,
});
- const dispatched = await dispatchRuntimeActionsStep({
+ // Interrupt-sourced batches obey the same mode split as model-authored
+ // ones: task agents wrap every delegation in the task lifecycle.
+ const dispatchStep =
+ bundle.resolvedAgent.config?.experimental?.tasks === true
+ ? dispatchTaskStep
+ : dispatchRuntimeActionsStep;
+ const dispatched = await dispatchStep({
callbackBaseUrl: input.callbackBaseUrl,
parentContinuationToken: input.parentContinuationToken,
parentWritable: input.parentWritable,
@@ -101,6 +117,7 @@ export async function dispatchWorkflowRuntimeActionsStep(input: {
return {
results: [...dispatched.results, ...blockedResults],
sessionState: dispatched.sessionState,
+ pendingTasks: dispatched.pendingTasks,
};
}
diff --git a/packages/eve/src/execution/effective-output-schema.ts b/packages/eve/src/execution/effective-output-schema.ts
new file mode 100644
index 000000000..7fd777513
--- /dev/null
+++ b/packages/eve/src/execution/effective-output-schema.ts
@@ -0,0 +1,34 @@
+import type { HarnessSession, StepInput } from "#harness/types.js";
+import type { JsonObject } from "#shared/json.js";
+import type { RunMode } from "#shared/run-mode.js";
+
+/**
+ * Resolves the single output schema in effect for this turn, decoupling schema
+ * enforcement from {@link RunMode}: downstream the harness reads
+ * `session.outputSchema` unconditionally and never re-derives it from mode.
+ *
+ * A run-scoped (client-supplied) schema on the turn's {@link StepInput} always
+ * wins. With no run-scoped schema, a task run adopts the agent's declared
+ * return schema — its function-output contract, which only applies when the
+ * agent is invoked as a function (subagent / schedule / job), i.e. task mode.
+ * A conversation run with no run-scoped schema enforces nothing. Continuation
+ * steps (no new `StepInput`) preserve whatever is already in effect.
+ */
+export function resolveEffectiveOutputSchema(input: {
+ readonly agentOutputSchema: JsonObject | undefined;
+ readonly input: StepInput | undefined;
+ readonly mode: RunMode;
+ readonly session: HarnessSession;
+}): HarnessSession {
+ const { agentOutputSchema, input: stepInput, mode, session } = input;
+
+ if (stepInput?.outputSchema !== undefined) {
+ return { ...session, outputSchema: stepInput.outputSchema };
+ }
+
+ if (mode === "task" && session.outputSchema === undefined && agentOutputSchema !== undefined) {
+ return { ...session, outputSchema: agentOutputSchema };
+ }
+
+ return session;
+}
diff --git a/packages/eve/src/execution/node-step.test.ts b/packages/eve/src/execution/node-step.test.ts
index 069741ad8..d9541db25 100644
--- a/packages/eve/src/execution/node-step.test.ts
+++ b/packages/eve/src/execution/node-step.test.ts
@@ -274,6 +274,51 @@ describe("createNodeHarnessTools", () => {
expect(tools.has("agent")).toBe(false);
});
+
+ it("does not inject task tools without experimental.tasks", () => {
+ const tools = createNodeHarnessTools({ node: createTestNode() });
+
+ for (const name of ["task_peek", "task_cancel", "task_send", "task_sleep"]) {
+ expect(tools.has(name)).toBe(false);
+ }
+ });
+
+ it("injects the task tools when experimental.tasks is on", () => {
+ const node = createTestNode();
+ const tools = createNodeHarnessTools({
+ node: {
+ ...node,
+ agent: {
+ ...node.agent,
+ config: { experimental: { tasks: true }, model: { id: "test-model" }, name: "test" },
+ },
+ },
+ });
+
+ for (const name of ["task_peek", "task_cancel", "task_send"]) {
+ expect(tools.get(name)?.runtimeAction).toEqual({ kind: "task-control" });
+ expect(tools.get(name)?.execute).toBeUndefined();
+ }
+ expect(tools.get("task_sleep")?.execute).toBeDefined();
+ expect(tools.get("task_sleep")?.runtimeAction).toBeUndefined();
+ });
+
+ it("respects disableTool for individual task tools", () => {
+ const node = createTestNode();
+ const tools = createNodeHarnessTools({
+ node: {
+ ...node,
+ agent: {
+ ...node.agent,
+ config: { experimental: { tasks: true }, model: { id: "test-model" }, name: "test" },
+ disabledFrameworkTools: ["task_cancel"],
+ },
+ },
+ });
+
+ expect(tools.has("task_peek")).toBe(true);
+ expect(tools.has("task_cancel")).toBe(false);
+ });
});
describe("createExecutionNodeStep", () => {
diff --git a/packages/eve/src/execution/node-step.ts b/packages/eve/src/execution/node-step.ts
index 1d98b5f6a..7ca7aabbb 100644
--- a/packages/eve/src/execution/node-step.ts
+++ b/packages/eve/src/execution/node-step.ts
@@ -23,6 +23,10 @@ import {
AGENT_TOOL_NAME,
isImplicitAgentToolAvailable,
} from "#runtime/framework-tools/agent.js";
+import {
+ createTaskToolHarnessDefinitions,
+ isTaskToolAvailable,
+} from "#runtime/framework-tools/tasks.js";
import type { ResolvedRuntimeAgentNode } from "#runtime/graph.js";
import type { PreparedRuntimeTool } from "#runtime/sessions/turn.js";
@@ -109,6 +113,7 @@ export function createExecutionNodeStep(input: CreateExecutionNodeStepInput): St
mode: input.mode,
onCompaction: preserveFrameworkStateOnCompaction,
persistentSubagentSessions:
+ input.node.agent.config?.experimental?.tasks === true ||
input.node.agent.config?.experimental?.subagentPersistentSessions === true,
dispatchDynamicModelEvent: dispatchModelEvent,
resolveModel,
@@ -210,6 +215,7 @@ export function createNodeHarnessTools(input: {
tools.set(AGENT_TOOL_NAME, {
description: AGENT_TOOL_DESCRIPTION,
inputSchema:
+ input.node.agent.config?.experimental?.tasks === true ||
input.node.agent.config?.experimental?.subagentPersistentSessions === true
? PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA
: SUBAGENT_TOOL_INPUT_SCHEMA,
@@ -222,6 +228,20 @@ export function createNodeHarnessTools(input: {
});
}
+ const tasksEnabled = input.node.agent.config?.experimental?.tasks === true;
+ for (const definition of createTaskToolHarnessDefinitions()) {
+ if (
+ isTaskToolAvailable({
+ disabledFrameworkTools: input.node.agent.disabledFrameworkTools,
+ hasAuthoredTool: tools.has(definition.name),
+ tasksEnabled,
+ toolName: definition.name,
+ })
+ ) {
+ tools.set(definition.name, definition);
+ }
+ }
+
return tools;
}
diff --git a/packages/eve/src/execution/parked-delivery-wait.test.ts b/packages/eve/src/execution/parked-delivery-wait.test.ts
index 4e5541c7b..e768021f2 100644
--- a/packages/eve/src/execution/parked-delivery-wait.test.ts
+++ b/packages/eve/src/execution/parked-delivery-wait.test.ts
@@ -9,6 +9,7 @@ import type {
SessionInboxSource,
} from "#execution/session-command-inbox.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
+import { SessionStateCursor } from "#execution/session-state-cursor.js";
vi.mock("./route-child-delivery.js", () => ({
routeDeliverToChildren: vi.fn(),
@@ -90,13 +91,6 @@ function messageRead(message: string): ScriptedRead {
};
}
-function runtimeActionResultRead(): ScriptedRead {
- return {
- result: { done: false, value: { kind: "runtime-action-result", results: [] } },
- source: "session",
- };
-}
-
// Routing never runs in these tests: scripted reads stop at authorization
// instructions or exhaust before any deliver-kind turn payload.
const sessionState = { sessionId: "ses-parked-wait" } as DurableSessionState;
@@ -108,19 +102,11 @@ function waitInput(inbox: SessionCommandInbox): Parameters<typeof nextTurnDelive
bufferedSessionControls: [],
commandInbox: inbox,
driverWritable: new WritableStream<Uint8Array>(),
- sessionState,
+ stateCursor: new SessionStateCursor({ serializedContext: {}, sessionState }),
};
}
describe("nextTurnDelivery", () => {
- beforeEach(() => {
- vi.mocked(routeDeliverToChildren).mockImplementation(async ({ delivery, sessionState }) => ({
- kind: "continue",
- remainder: delivery,
- sessionState,
- }));
- });
-
afterEach(() => {
vi.mocked(routeDeliverToChildren).mockReset();
});
@@ -149,20 +135,6 @@ describe("nextTurnDelivery", () => {
expect(inbox.windowTransitions).toEqual([true, false]);
});
- it("ignores child results already owned by the runtime-action collector", async () => {
- const inbox = createMockInbox([runtimeActionResultRead(), messageRead("follow up")]);
-
- const next = await nextTurnDelivery({
- ...waitInput(inbox),
- awaitAuthorizationCallbacks: false,
- });
-
- expect(next).toMatchObject({
- kind: "turn",
- remainder: { kind: "deliver", payloads: [{ message: "follow up" }] },
- });
- });
-
it("does not let buffered deliveries bypass a ready authorization callback", async () => {
const inbox = createMockInbox([authorizationRead()], true);
const bufferedDeliveries: DeliverHookPayload[] = [
@@ -220,11 +192,13 @@ describe("nextTurnDelivery", () => {
.mockResolvedValueOnce({
kind: "continue",
remainder: undefined,
+ serializedContext: {},
sessionState: retiredState,
})
.mockResolvedValueOnce({
kind: "continue",
remainder: { kind: "deliver", payloads: [{ message: "parent turn" }] },
+ serializedContext: {},
sessionState: retiredState,
});
@@ -234,6 +208,69 @@ describe("nextTurnDelivery", () => {
});
expect(vi.mocked(routeDeliverToChildren).mock.calls[1]?.[0].sessionState).toBe(retiredState);
- expect(next).toMatchObject({ kind: "turn", sessionState: retiredState });
+ expect(next).toMatchObject({
+ delivery: { payloads: [{ message: "parent turn" }] },
+ kind: "turn",
+ });
+ });
+});
+
+describe("nextTurnDelivery routing", () => {
+ beforeEach(() => vi.clearAllMocks());
+ it("keeps waiting instead of starting a parent turn for a fully routed task response", async () => {
+ const sessionState = {
+ continuationToken: "token",
+ emissionState: { sequence: 0, sessionStarted: false, stepIndex: 0, turnId: "turn" },
+ hasProxyInputRequests: true,
+ sessionId: "session",
+ version: 1,
+ } as const;
+ const routedSessionState = { ...sessionState, hasProxyInputRequests: false };
+ vi.mocked(routeDeliverToChildren)
+ .mockResolvedValueOnce({
+ kind: "continue",
+ remainder: undefined,
+ serializedContext: {},
+ sessionState,
+ })
+ .mockResolvedValueOnce({
+ kind: "continue",
+ remainder: { kind: "deliver", payloads: [{ message: "ordinary" }] },
+ serializedContext: {},
+ sessionState: routedSessionState,
+ });
+ const commands = [
+ { kind: "send" as const, payload: { inputResponses: [{ requestId: "task-request" }] } },
+ { kind: "send" as const, payload: { message: "ordinary" } },
+ ];
+ const commandInbox: SessionCommandInbox = {
+ claimAuthorization: vi.fn(),
+ claimStable: vi.fn(),
+ consumeNext: vi.fn(),
+ hasReadyAuthorization: vi.fn(() => false),
+ next: vi.fn(async () => ({ done: false as const, value: commands.shift()! })),
+ nextWithSource: vi.fn(async () => ({
+ result: { done: false as const, value: commands.shift()! },
+ source: "session" as const,
+ })),
+ rekeyContinuation: vi.fn(),
+ setAuthorizationWindow: vi.fn(),
+ };
+
+ const stateCursor = new SessionStateCursor({ serializedContext: {}, sessionState });
+ const result = await nextTurnDelivery({
+ bufferedDeliveries: [],
+ bufferedSessionControls: [],
+ commandInbox,
+ driverWritable: new WritableStream<Uint8Array>(),
+ stateCursor,
+ });
+
+ expect(result).toMatchObject({
+ delivery: { payloads: [{ message: "ordinary" }] },
+ kind: "turn",
+ });
+ expect(routeDeliverToChildren).toHaveBeenCalledTimes(2);
+ expect(stateCursor.sessionState).toBe(routedSessionState);
});
});
diff --git a/packages/eve/src/execution/parked-delivery-wait.ts b/packages/eve/src/execution/parked-delivery-wait.ts
index da9afb9f9..27be2d275 100644
--- a/packages/eve/src/execution/parked-delivery-wait.ts
+++ b/packages/eve/src/execution/parked-delivery-wait.ts
@@ -1,8 +1,8 @@
import type { DeliverHookPayload, DeliverPayload } from "#channel/types.js";
-import type { DurableSessionState } from "#execution/durable-session-store.js";
import { routeDeliverToChildren } from "#execution/route-child-delivery.js";
import type { SessionCommandInbox } from "#execution/session-command-inbox.js";
import { sendCommandToDelivery } from "#execution/session-command-wire.js";
+import type { SessionStateCursor } from "#execution/session-state-cursor.js";
import { coalesceDeliveries } from "#harness/messages.js";
type NextSessionAction =
@@ -10,7 +10,7 @@ type NextSessionAction =
| { readonly kind: "compact" }
| { readonly kind: "expired" }
| { readonly kind: "reset" }
- | Omit<AuthorizationCallbackInstruction, "sessionState">
+ | AuthorizationCallbackInstruction
| {
readonly delivery: DeliverHookPayload | null;
readonly kind: "delivery";
@@ -22,23 +22,20 @@ export interface AuthorizationCallbackInstruction {
/** True when the authorization hook closed; no further callbacks can arrive. */
readonly closed: boolean;
readonly payloads: readonly DeliverPayload[];
- readonly sessionState: DurableSessionState;
}
/** What the parked driver should do with the next session activity. */
export type NextTurnInstruction =
- | { readonly kind: "clear"; readonly sessionState: DurableSessionState }
- | { readonly kind: "compact"; readonly sessionState: DurableSessionState }
- | { readonly kind: "expired"; readonly sessionState: DurableSessionState }
- | { readonly kind: "reset"; readonly sessionState: DurableSessionState }
- | { readonly kind: "closed"; readonly sessionState: DurableSessionState }
- | { readonly kind: "cancel-turn"; readonly sessionState: DurableSessionState }
+ | { readonly kind: "clear" }
+ | { readonly kind: "compact" }
+ | { readonly kind: "expired" }
+ | { readonly kind: "reset" }
+ | { readonly kind: "closed" }
+ | { readonly kind: "cancel-turn" }
| AuthorizationCallbackInstruction
| {
readonly kind: "turn";
- readonly deliver: DeliverHookPayload;
- readonly remainder: DeliverHookPayload;
- readonly sessionState: DurableSessionState;
+ readonly delivery: DeliverHookPayload;
};
/**
@@ -53,15 +50,20 @@ export type NextTurnInstruction =
* without producing a parent turn (no-op cancels, fully-routed descendant
* deliveries) — so an open challenge's callback surfaces as an
* `"authorization"` instruction no matter when it arrives.
+ *
+ * Routing steps mutate durable state; each transition is adopted into the
+ * caller-owned `stateCursor`, so returns carry only the instruction kind.
*/
export async function nextTurnDelivery(input: {
readonly awaitAuthorizationCallbacks?: boolean;
readonly bufferedDeliveries: DeliverHookPayload[];
readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;
+ readonly cancelledTaskIds?: Set<string>;
readonly commandInbox: SessionCommandInbox;
readonly deferDeliveries?: boolean;
readonly driverWritable: WritableStream<Uint8Array>;
- readonly sessionState: DurableSessionState;
+ readonly seenTaskDeliveries?: Set<string>;
+ readonly stateCursor: SessionStateCursor;
}): Promise<NextTurnInstruction> {
if (input.awaitAuthorizationCallbacks !== true) {
return await awaitNextTurnDelivery(input);
@@ -78,43 +80,48 @@ export async function nextTurnDelivery(input: {
async function awaitNextTurnDelivery(input: {
readonly bufferedDeliveries: DeliverHookPayload[];
readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;
+ readonly cancelledTaskIds?: Set<string>;
readonly commandInbox: SessionCommandInbox;
readonly deferDeliveries?: boolean;
readonly driverWritable: WritableStream<Uint8Array>;
- readonly sessionState: DurableSessionState;
+ readonly seenTaskDeliveries?: Set<string>;
+ readonly stateCursor: SessionStateCursor;
}): Promise<NextTurnInstruction> {
- let sessionState = input.sessionState;
-
+ const cancelledTaskIds = input.cancelledTaskIds ?? new Set<string>();
+ const seenTaskDeliveries = input.seenTaskDeliveries ?? new Set<string>();
while (true) {
const nextAction = await waitForNextSessionAction({
bufferedDeliveries: input.bufferedDeliveries,
bufferedSessionControls: input.bufferedSessionControls,
+ cancelledTaskIds,
commandInbox: input.commandInbox,
deferDeliveries: input.deferDeliveries,
+ seenTaskDeliveries,
});
if (nextAction.kind === "authorization") {
- return { ...nextAction, sessionState };
+ return nextAction;
}
if (nextAction.kind !== "delivery") {
- return { kind: nextAction.kind, sessionState };
+ return { kind: nextAction.kind };
}
const deliver = nextAction.delivery;
if (deliver === null) {
- return { kind: "closed", sessionState };
+ return { kind: "closed" };
}
const routed = await routeDeliverToChildren({
delivery: deliver,
parentWritable: input.driverWritable,
- sessionState,
+ serializedContext: input.stateCursor.serializedContext,
+ sessionState: input.stateCursor.sessionState,
});
- sessionState = routed.sessionState;
+ input.stateCursor.adoptState(routed);
if (routed.kind === "cancel-turn") {
- return { kind: "cancel-turn", sessionState };
+ return { kind: "cancel-turn" };
}
if (routed.remainder === undefined) {
@@ -122,21 +129,29 @@ async function awaitNextTurnDelivery(input: {
continue;
}
- return { deliver, kind: "turn", remainder: routed.remainder, sessionState };
+ return { delivery: routed.remainder, kind: "turn" };
}
}
async function waitForNextSessionAction(input: {
readonly bufferedDeliveries: DeliverHookPayload[];
readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;
+ readonly cancelledTaskIds: Set<string>;
readonly commandInbox: SessionCommandInbox;
readonly deferDeliveries?: boolean;
+ readonly seenTaskDeliveries: Set<string>;
}): Promise<NextSessionAction> {
const pendingSessionControl = input.bufferedSessionControls.shift();
if (pendingSessionControl !== undefined) {
return { kind: pendingSessionControl };
}
+ while (
+ input.bufferedDeliveries[0] !== undefined &&
+ isCancelledTaskDelivery(input.bufferedDeliveries[0], input.cancelledTaskIds)
+ ) {
+ input.bufferedDeliveries.shift();
+ }
if (
input.deferDeliveries !== true &&
!input.commandInbox.hasReadyAuthorization() &&
@@ -180,6 +195,13 @@ async function waitForNextSessionAction(input: {
}
if (first.value.kind === "cancel") {
+ if (first.value.taskId !== undefined) {
+ input.cancelledTaskIds.add(first.value.taskId);
+ const kept = input.bufferedDeliveries.filter(
+ (delivery) => !isCancelledTaskDelivery(delivery, input.cancelledTaskIds),
+ );
+ input.bufferedDeliveries.splice(0, input.bufferedDeliveries.length, ...kept);
+ }
continue;
}
@@ -189,6 +211,15 @@ async function waitForNextSessionAction(input: {
continue;
}
+ const deliveryId = first.value.taskDeliveryId ?? first.value.caller?.taskId;
+ if (deliveryId !== undefined && isCancelledTaskDeliveryId(deliveryId, input.cancelledTaskIds)) {
+ continue;
+ }
+ if (deliveryId !== undefined) {
+ if (input.seenTaskDeliveries.has(deliveryId)) continue;
+ input.seenTaskDeliveries.add(deliveryId);
+ }
+
if (first.value.kind === "deliver") {
if (input.deferDeliveries === true) {
input.bufferedDeliveries.push(first.value);
@@ -206,6 +237,23 @@ async function waitForNextSessionAction(input: {
}
}
+function isCancelledTaskDelivery(
+ delivery: DeliverHookPayload,
+ cancelledTaskIds: ReadonlySet<string>,
+): boolean {
+ const deliveryId = delivery.taskDeliveryId ?? delivery.caller?.taskId;
+ return deliveryId !== undefined && isCancelledTaskDeliveryId(deliveryId, cancelledTaskIds);
+}
+
+function isCancelledTaskDeliveryId(
+ deliveryId: string,
+ cancelledTaskIds: ReadonlySet<string>,
+): boolean {
+ return [...cancelledTaskIds].some(
+ (taskId) => deliveryId === taskId || deliveryId.startsWith(`${taskId}:`),
+ );
+}
+
function takeBufferedTurnDelivery(bufferedDeliveries: DeliverHookPayload[]): DeliverHookPayload {
const first = bufferedDeliveries.shift();
if (first === undefined) {
@@ -216,7 +264,12 @@ function takeBufferedTurnDelivery(bufferedDeliveries: DeliverHookPayload[]): Del
let caller = first.caller;
while (bufferedDeliveries.length > 0) {
const next = bufferedDeliveries[0];
- if (next === undefined || (caller !== undefined && next.caller !== undefined)) {
+ if (
+ next === undefined ||
+ first.taskDeliveryId !== undefined ||
+ next.taskDeliveryId !== undefined ||
+ (caller !== undefined && next.caller !== undefined)
+ ) {
break;
}
diff --git a/packages/eve/src/execution/proxied-deliver-step.ts b/packages/eve/src/execution/proxied-deliver-step.ts
new file mode 100644
index 000000000..93653e64d
--- /dev/null
+++ b/packages/eve/src/execution/proxied-deliver-step.ts
@@ -0,0 +1,239 @@
+import type { DeliverHookPayload, DeliverPayload, SessionAuthContext } from "#channel/types.js";
+import { coalesceDeliverPayloads } from "#execution/deliver-payloads.js";
+import {
+ type DurableSessionState,
+ readDurableSession,
+ replaceDurableSessionSnapshot,
+} from "#execution/durable-session-store.js";
+import { routeDeliverPayload } from "#execution/subagent-hitl-proxy.js";
+import { sendTaskInboundPayload } from "#execution/tasks/parent/run-parent.js";
+import { resumeHook } from "#internal/workflow/runtime.js";
+import type { InputResponse } from "#runtime/input/types.js";
+import { findSessionTaskEntry } from "#tasks/session-index.js";
+import {
+ createTaskInputRequestId,
+ retireProxyInputRequests,
+} from "#harness/proxy-input-requests.js";
+
+export type RoutedDeliverResult =
+ | {
+ readonly kind: "cancel-turn";
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+ }
+ | {
+ readonly kind: "continue";
+ readonly remainder: DeliverHookPayload | undefined;
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+ };
+
+type LegacyRoutedDeliverResult =
+ | {
+ readonly kind: "cancel-turn";
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+ }
+ | {
+ readonly kind: "continue";
+ readonly remainder: DeliverPayload | undefined;
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+ };
+
+interface ChildBucket {
+ readonly childContinuationToken: string;
+ readonly childResponseUrl?: string;
+ readonly metadata: NonNullable<DeliverHookPayload["deliveryMetadata"]>[number][];
+ readonly payloads: DeliverPayload[];
+ readonly retireRequestIds: string[];
+ readonly sourcePayloadIndexes: number[];
+ readonly taskId?: string;
+}
+
+/** Splits an envelope and validates task routes before forwarding descendant input. */
+export function routeProxiedDeliverStep(input: {
+ readonly delivery: DeliverHookPayload;
+ readonly parentWritable: WritableStream<Uint8Array>;
+ readonly serializedContext?: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+}): Promise<RoutedDeliverResult>;
+export function routeProxiedDeliverStep(input: {
+ readonly auth?: SessionAuthContext | null;
+ readonly parentWritable: WritableStream<Uint8Array>;
+ readonly payload: DeliverPayload;
+ readonly serializedContext?: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+}): Promise<LegacyRoutedDeliverResult>;
+export async function routeProxiedDeliverStep(
+ input:
+ | {
+ readonly delivery: DeliverHookPayload;
+ readonly parentWritable: WritableStream<Uint8Array>;
+ readonly serializedContext?: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+ }
+ | {
+ readonly auth?: SessionAuthContext | null;
+ readonly parentWritable: WritableStream<Uint8Array>;
+ readonly payload: DeliverPayload;
+ readonly serializedContext?: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+ },
+): Promise<LegacyRoutedDeliverResult | RoutedDeliverResult> {
+ "use step";
+
+ let durableSession = await readDurableSession(input.sessionState);
+ const legacyInput = !("delivery" in input);
+ const sourceDelivery: DeliverHookPayload =
+ "delivery" in input
+ ? input.delivery
+ : { auth: input.auth, kind: "deliver", payloads: [input.payload] };
+ const parentPayloads = new Map<number, DeliverPayload>();
+ const children = new Map<string, ChildBucket>();
+ let parentAction: { readonly kind: "cancel-turn" } | undefined;
+
+ for (const [sourcePayloadIndex, payload] of sourceDelivery.payloads.entries()) {
+ const routed = routeDeliverPayload({
+ allowRoute: (_requestId, route) =>
+ route.taskId === undefined ||
+ findSessionTaskEntry(durableSession.state, route.taskId) !== undefined,
+ payload,
+ state: durableSession.state,
+ });
+ parentAction ??= routed.parentAction;
+ if (routed.forSelf !== undefined) parentPayloads.set(sourcePayloadIndex, routed.forSelf);
+
+ for (const [childIndex, forChild] of routed.forChildren.entries()) {
+ const key =
+ forChild.taskId === undefined
+ ? forChild.childContinuationToken
+ : [
+ forChild.childContinuationToken,
+ forChild.childResponseUrl ?? "",
+ forChild.taskId,
+ ].join("\0");
+ const child = children.get(key) ?? {
+ childContinuationToken: forChild.childContinuationToken,
+ childResponseUrl: forChild.childResponseUrl,
+ metadata: [],
+ payloads: [],
+ retireRequestIds: [],
+ sourcePayloadIndexes: [],
+ taskId: forChild.taskId,
+ };
+ const childPayloadIndex = child.payloads.length;
+ child.payloads.push(forChild.payload);
+ child.retireRequestIds.push(...forChild.retireRequestIds);
+ child.sourcePayloadIndexes.push(sourcePayloadIndex);
+ if (routed.forSelf === undefined && childIndex === 0) {
+ for (const metadata of sourceDelivery.deliveryMetadata ?? []) {
+ if (metadata.payloadIndex === sourcePayloadIndex) {
+ child.metadata.push({ ...metadata, payloadIndex: childPayloadIndex });
+ }
+ }
+ }
+ children.set(key, child);
+ }
+ }
+
+ let retired = false;
+ for (const child of children.values()) {
+ // Task-owned children are addressed through their run, never
+ // directly: the run must forward and clear the batch under one
+ // durable decision, or a late answer could unblock a question the
+ // child raised after this one.
+ const taskId = child.taskId;
+ if (taskId !== undefined) {
+ const entry = findSessionTaskEntry(durableSession.state, taskId);
+ if (entry === undefined) {
+ mergeStrandedResponses(parentPayloads, child, taskId);
+ continue;
+ }
+ const delivery = await sendTaskInboundPayload({
+ taskInboxToken: entry.taskInboxToken,
+ payload: {
+ auth: sourceDelivery.auth,
+ childContinuationToken: child.childContinuationToken,
+ childResponseUrl: child.childResponseUrl,
+ inputResponses: coalesceDeliverPayloads(child.payloads).inputResponses ?? [],
+ kind: "input-response",
+ taskId,
+ },
+ });
+ if (delivery === "unreachable") {
+ mergeStrandedResponses(parentPayloads, child, taskId);
+ continue;
+ }
+ // Hand-off to the task run succeeded. Retire the parent-visible
+ // routes so a later click cannot re-enter the same batch after the
+ // run has already accepted (or no-op'd) this answer.
+ durableSession = retireProxyInputRequests(durableSession, child.retireRequestIds);
+ retired = true;
+ continue;
+ }
+
+ const childDelivery: DeliverHookPayload = {
+ ...sourceDelivery,
+ deliveryMetadata: child.metadata.length === 0 ? undefined : child.metadata,
+ payloads: child.payloads,
+ };
+ await resumeHook(child.childContinuationToken, {
+ ...childDelivery,
+ payload: coalesceDeliverPayloads(child.payloads),
+ });
+ // Successfully forwarded request IDs are retired so later deliveries
+ // cannot route through stale entries.
+ durableSession = retireProxyInputRequests(durableSession, child.retireRequestIds);
+ retired = true;
+ }
+
+ const context = {
+ serializedContext: input.serializedContext ?? {},
+ sessionState: retired
+ ? replaceDurableSessionSnapshot({ session: durableSession, state: input.sessionState })
+ : input.sessionState,
+ };
+ if (parentAction !== undefined) return { ...context, ...parentAction };
+ const orderedParentPayloads = [...parentPayloads].sort(([a], [b]) => a - b);
+ const parentMetadata = orderedParentPayloads.flatMap(([sourcePayloadIndex], payloadIndex) =>
+ (sourceDelivery.deliveryMetadata ?? [])
+ .filter((metadata) => metadata.payloadIndex === sourcePayloadIndex)
+ .map((metadata) => ({ ...metadata, payloadIndex })),
+ );
+ const remainder =
+ orderedParentPayloads.length === 0
+ ? undefined
+ : legacyInput
+ ? coalesceDeliverPayloads(orderedParentPayloads.map(([, payload]) => payload))
+ : {
+ ...sourceDelivery,
+ deliveryMetadata: parentMetadata.length === 0 ? undefined : parentMetadata,
+ payloads: orderedParentPayloads.map(([, payload]) => payload),
+ };
+ return { ...context, kind: "continue", remainder };
+}
+
+// Answers to a task that finished mid-flight rejoin the parent-local
+// remainder, where the model sees them as stale rather than silently
+// vanishing.
+function mergeStrandedResponses(
+ parentPayloads: Map<number, DeliverPayload>,
+ child: ChildBucket,
+ taskId: string,
+): void {
+ for (const [childPayloadIndex, payload] of child.payloads.entries()) {
+ const sourcePayloadIndex = child.sourcePayloadIndexes[childPayloadIndex];
+ if (sourcePayloadIndex === undefined) continue;
+ const strandedResponses: InputResponse[] = (payload.inputResponses ?? []).map((response) => ({
+ ...response,
+ requestId: createTaskInputRequestId(taskId, response.requestId),
+ }));
+ if (strandedResponses.length === 0) continue;
+ const forSelf = parentPayloads.get(sourcePayloadIndex);
+ parentPayloads.set(sourcePayloadIndex, {
+ ...forSelf,
+ inputResponses: [...(forSelf?.inputResponses ?? []), ...strandedResponses],
+ });
+ }
+}
diff --git a/packages/eve/src/execution/remote-agent-dispatch.test.ts b/packages/eve/src/execution/remote-agent-dispatch.test.ts
index 1cf7aaca0..c667b27b1 100644
--- a/packages/eve/src/execution/remote-agent-dispatch.test.ts
+++ b/packages/eve/src/execution/remote-agent-dispatch.test.ts
@@ -4,9 +4,11 @@ import type { SessionAuthContext } from "#channel/types.js";
import {
cancelRemoteAgentTurn,
continueRemoteAgentSession,
+ isAmbiguousRemoteAgentContinueError,
isRetryableRemoteAgentCancelError,
isRetryableRemoteAgentContinueError,
resolveRemoteAgentForAction,
+ resolveRemoteAgentStreamHeaders,
startRemoteAgentSession,
} from "#execution/remote-agent-dispatch.js";
import type { RuntimeRemoteAgentCallActionRequest } from "#runtime/actions/types.js";
@@ -70,12 +72,133 @@ describe("resolveRemoteAgentForAction", () => {
});
});
+describe("resolveRemoteAgentStreamHeaders", () => {
+ it("resolves static and dynamic authored credentials without storing them in events", async () => {
+ const staticRemote = {
+ definition: {
+ auth: async () => ({ headers: { authorization: "Bearer static" } }),
+ description: "Research",
+ headers: { "x-static": "yes" },
+ kind: "remote",
+ logicalPath: "subagents/research.ts",
+ name: "research",
+ nodeId: "subagents/research",
+ path: "/eve/v1/session",
+ sourceId: "subagents/research.ts",
+ sourceKind: "module",
+ url: "https://static.example",
+ },
+ } as const;
+ const bundle = {
+ graph: {
+ nodesByNodeId: new Map(),
+ root: {
+ subagentRegistry: {
+ subagentsByNodeId: new Map([[staticRemote.definition.nodeId, staticRemote]]),
+ },
+ },
+ },
+ } as never;
+
+ await expect(
+ resolveRemoteAgentStreamHeaders({
+ bundle,
+ name: "research",
+ resolverId: staticRemote.definition.nodeId,
+ url: staticRemote.definition.url,
+ }),
+ ).resolves.toEqual({ authorization: "Bearer static", "x-static": "yes" });
+
+ const credentialsStepId = "eve:dynamic-remote-agent//stream-research";
+ const registryKey = Symbol.for("@workflow/core//registeredSteps");
+ const globalRecord = globalThis as Record<symbol, Map<string, Function> | undefined>;
+ const stepRegistry = globalRecord[registryKey] ?? new Map<string, Function>();
+ globalRecord[registryKey] = stepRegistry;
+ stepRegistry.set(credentialsStepId, () => ({
+ auth: async () => ({ headers: { authorization: "Bearer dynamic" } }),
+ }));
+
+ await expect(
+ resolveRemoteAgentStreamHeaders({
+ bundle,
+ name: "research",
+ resolverId: credentialsStepId,
+ url: "https://dynamic.example",
+ }),
+ ).resolves.toEqual({ authorization: "Bearer dynamic" });
+ });
+
+ it("rejects a static resolver whose authored URL does not match the event", async () => {
+ const definition = {
+ description: "Research",
+ kind: "remote",
+ logicalPath: "subagents/research.ts",
+ name: "research",
+ nodeId: "subagents/research",
+ path: "/eve/v1/session",
+ sourceId: "subagents/research.ts",
+ sourceKind: "module",
+ url: "https://static.example",
+ } as const;
+ const bundle = {
+ graph: {
+ nodesByNodeId: new Map(),
+ root: {
+ subagentRegistry: {
+ subagentsByNodeId: new Map([[definition.nodeId, { definition }]]),
+ },
+ },
+ },
+ } as never;
+
+ await expect(
+ resolveRemoteAgentStreamHeaders({
+ bundle,
+ name: "research",
+ resolverId: definition.nodeId,
+ url: "https://forged.example",
+ }),
+ ).rejects.toThrow(/does not match/);
+ });
+});
+
describe("startRemoteAgentSession", () => {
afterEach(() => {
vi.unstubAllGlobals();
vi.unstubAllEnvs();
});
+ it("carries a replay-stable operation id so the receiver can create once", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValue(
+ Response.json(
+ { ok: true, sessionId: "remote-session", status: "accepted" },
+ { status: 202 },
+ ),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ await startRemoteAgentSession({
+ action: createAction(),
+ callbackBaseUrl: "https://caller.example.com",
+ operationId: "operation-1",
+ remote: createRemoteAgent(),
+ session: {
+ agent: { modelReference: { id: "mock/test" }, system: "", tools: [] },
+ compaction: { recentWindowSize: 10, threshold: 100000 },
+ continuationToken: "eve:parent-token",
+ history: [],
+ sessionId: "parent-session",
+ state: {},
+ },
+ });
+
+ expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string)).toMatchObject({
+ operationId: "operation-1",
+ });
+ });
+
it("posts the formatted subagent message and callback metadata", async () => {
const fetchMock = vi.fn().mockResolvedValue(
new Response(
@@ -590,6 +713,7 @@ describe("continueRemoteAgentSession", () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(new Response(null, { status: 503 }))
+ .mockResolvedValueOnce(new Response(null, { status: 401 }))
.mockResolvedValueOnce(
new Response(JSON.stringify({ code: "SESSION_NOT_RESUMABLE" }), { status: 410 }),
)
@@ -610,7 +734,10 @@ describe("continueRemoteAgentSession", () => {
const transient = await continueRemoteAgentSession(continueInput()).catch(
(error: unknown) => error,
);
- const notResumable = await continueRemoteAgentSession(continueInput()).catch(
+ const rejected = await continueRemoteAgentSession(continueInput()).catch(
+ (error: unknown) => error,
+ );
+ const sessionNotResumable = await continueRemoteAgentSession(continueInput()).catch(
(error: unknown) => error,
);
const missing = await continueRemoteAgentSession(continueInput()).catch(
@@ -618,9 +745,15 @@ describe("continueRemoteAgentSession", () => {
);
expect(isRetryableRemoteAgentContinueError(transient)).toBe(true);
- expect(isRetryableRemoteAgentContinueError(notResumable)).toBe(false);
+ expect(isAmbiguousRemoteAgentContinueError(transient)).toBe(true);
+ expect(isRetryableRemoteAgentContinueError(rejected)).toBe(true);
+ expect(isAmbiguousRemoteAgentContinueError(rejected)).toBe(false);
+ expect(isRetryableRemoteAgentContinueError(sessionNotResumable)).toBe(false);
+ expect(isAmbiguousRemoteAgentContinueError(sessionNotResumable)).toBe(false);
expect(isRetryableRemoteAgentContinueError(missing)).toBe(false);
+ expect(isAmbiguousRemoteAgentContinueError(missing)).toBe(false);
expect(isRetryableRemoteAgentContinueError(new TypeError("network unavailable"))).toBe(true);
+ expect(isAmbiguousRemoteAgentContinueError(new TypeError("network unavailable"))).toBe(true);
});
});
@@ -671,6 +804,26 @@ describe("cancelRemoteAgentTurn", () => {
});
});
+ it("sends the observed child turn guard", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValue(
+ Response.json({ ok: true, sessionId: "child-1", status: "accepted" }, { status: 202 }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ await cancelRemoteAgentTurn({
+ remote: createRemoteAgent(),
+ sessionId: "child-1",
+ turnId: "turn_child_7",
+ });
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ "https://remote.example.com/eve/v1/session/child-1/cancel",
+ expect.objectContaining({ body: JSON.stringify({ turnId: "turn_child_7" }), method: "POST" }),
+ );
+ });
+
it("preserves a prefixed remote base path on cancel-turn requests", async () => {
const fetchMock = vi
.fn()
diff --git a/packages/eve/src/execution/remote-agent-dispatch.ts b/packages/eve/src/execution/remote-agent-dispatch.ts
index c36537f0e..b544e8f83 100644
--- a/packages/eve/src/execution/remote-agent-dispatch.ts
+++ b/packages/eve/src/execution/remote-agent-dispatch.ts
@@ -10,6 +10,7 @@ import type { CancelTurnResult, SessionAuthContext, SessionTraceContext } from "
import type { ForwardedPrincipal } from "#channel/forwarded-principal.js";
import type { HeadersValue } from "#client/types.js";
import { createWorkflowCallbackUrl } from "#execution/workflow-callback-url.js";
+import { createRemoteAgentRouteUrl } from "#execution/remote-agent-route-url.js";
import { formatTraceparent } from "#protocol/traceparent.js";
import {
formatSubagentInput,
@@ -19,9 +20,11 @@ import type { HarnessSession } from "#harness/types.js";
import type { RuntimeRemoteAgentCallActionRequest } from "#runtime/actions/types.js";
import type { RuntimeSubagentRegistry } from "#runtime/subagents/registry.js";
import type { DynamicRemoteAgentConfig } from "#runtime/subagents/dynamic-remote-agent-config.js";
+import type { CompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
import type { ResolvedRuntimeRemoteAgentNode } from "#runtime/types.js";
import { expectFunction, expectObjectRecord } from "#internal/authored-module.js";
import type { JsonObject } from "#shared/json.js";
+import { readTaskIdFromInboxToken } from "#tasks/task-id.js";
const CreateSessionResponseSchema = z.object({
ok: z.literal(true),
@@ -51,6 +54,12 @@ export async function startRemoteAgentSession(input: {
readonly callbackToken?: string;
/** The root initiator's principal, forwarded alongside {@link auth}. */
readonly initiatorAuth?: SessionAuthContext | null;
+ /**
+ * Replay-stable identity of this create attempt. A retried dispatch step
+ * re-sends the same value, letting the receiver return the child it already
+ * created instead of starting a second one.
+ */
+ readonly operationId?: string;
/**
* Whether the dispatching agent opted into
* `experimental.subagentPersistentSessions`. Persistent remote children run
@@ -75,18 +84,21 @@ export async function startRemoteAgentSession(input: {
callback: {
callId: string;
subagentName: string;
+ taskId?: string;
token: string;
url: string;
};
forwardedPrincipal?: ForwardedPrincipal;
message: string;
mode: "conversation" | "task";
+ operationId?: string;
outputSchema?: object;
} = {
capabilities: {},
callback: {
callId: input.action.callId,
subagentName: input.action.remoteAgentName,
+ taskId: readTaskIdFromInboxToken(callbackToken),
token: callbackToken,
url: createWorkflowCallbackUrl(
input.callbackBaseUrl,
@@ -105,6 +117,9 @@ export async function startRemoteAgentSession(input: {
if (forwardedPrincipal !== undefined) {
requestBody.forwardedPrincipal = forwardedPrincipal;
}
+ if (input.operationId !== undefined) {
+ requestBody.operationId = input.operationId;
+ }
const headers = await resolveRemoteAgentRequestHeaders(input.remote);
const traceparent = formatTraceparent(input.parentTraceContext);
@@ -153,6 +168,7 @@ export async function continueRemoteAgentSession(input: {
readonly callback: {
readonly callId: string;
readonly subagentName: string;
+ readonly taskId?: string;
readonly token: string;
readonly url: string;
};
@@ -182,7 +198,10 @@ export async function continueRemoteAgentSession(input: {
`Remote agent "${input.remote.name}" continue-session request failed${
permanent ? " permanently" : ""
} with HTTP ${response.status}.`,
- { retryable: !permanent },
+ {
+ deliveryAmbiguous: isAmbiguousRemoteContinueStatus(response.status),
+ retryable: !permanent,
+ },
);
}
}
@@ -193,11 +212,16 @@ export async function continueRemoteAgentSession(input: {
* with real instances instead of re-encoding the classification.
*/
export class RemoteAgentContinueRequestError extends Error {
+ readonly deliveryAmbiguous: boolean;
readonly retryable: boolean;
- constructor(message: string, options: { readonly retryable: boolean }) {
+ constructor(
+ message: string,
+ options: { readonly deliveryAmbiguous: boolean; readonly retryable: boolean },
+ ) {
super(message);
this.name = "RemoteAgentContinueRequestError";
+ this.deliveryAmbiguous = options.deliveryAmbiguous;
this.retryable = options.retryable;
}
}
@@ -215,6 +239,15 @@ export function isRetryableRemoteAgentContinueError(error: unknown): boolean {
return !(error instanceof RemoteAgentContinueRequestError) || error.retryable;
}
+/** Whether the callee may have accepted the continuation before delivery failed. */
+export function isAmbiguousRemoteAgentContinueError(error: unknown): boolean {
+ return !(error instanceof RemoteAgentContinueRequestError) || error.deliveryAmbiguous;
+}
+
+function isAmbiguousRemoteContinueStatus(status: number): boolean {
+ return status === 408 || status === 425 || status >= 500;
+}
+
async function readRemoteAgentErrorCode(response: Response): Promise<string | undefined> {
let body: unknown;
try {
@@ -254,9 +287,15 @@ function buildForwardedPrincipalField(input: {
export async function cancelRemoteAgentTurn(input: {
readonly remote: ResolvedRuntimeRemoteAgentNode;
readonly sessionId: string;
+ readonly taskId?: string;
+ readonly turnId?: string;
}): Promise<CancelTurnResult> {
const headers = await resolveRemoteAgentRequestHeaders(input.remote);
const response = await fetch(createRemoteAgentCancelTurnUrl(input.remote, input.sessionId), {
+ body:
+ input.turnId === undefined && input.taskId === undefined
+ ? undefined
+ : JSON.stringify({ taskId: input.taskId, turnId: input.turnId }),
headers,
method: "POST",
});
@@ -355,6 +394,51 @@ export function resolveRemoteAgentForAction(input: {
return definition;
}
+/**
+ * Resolves authored outbound headers for a server-authored remote child event.
+ *
+ * `resolverId` is the key persisted on the `subagent.called` event (see
+ * `SubagentCalledStreamEvent`): it identifies the authored credential
+ * functions, never their resolved values. Lookup order mirrors how dispatch
+ * chose the key — first as a subagent node id (static remote definition),
+ * then as a `credentialsStepId` in the step registry (dynamic remote
+ * definition). The matched static definition must still agree with the
+ * event's `name`/`url`, so a stale or mismatched key fails closed rather
+ * than minting headers for the wrong upstream.
+ */
+export async function resolveRemoteAgentStreamHeaders(input: {
+ readonly bundle: CompiledRuntimeAgentBundle;
+ readonly name: string;
+ readonly resolverId?: string;
+ readonly url: string;
+}): Promise<Record<string, string>> {
+ if (input.resolverId === undefined) {
+ return {};
+ }
+
+ const nodes = new Set([input.bundle.graph.root, ...input.bundle.graph.nodesByNodeId.values()]);
+ for (const node of nodes) {
+ const definition = node.subagentRegistry.subagentsByNodeId.get(input.resolverId)?.definition;
+ if (definition === undefined) continue;
+ if (
+ definition.kind !== "remote" ||
+ definition.name !== input.name ||
+ definition.url !== input.url
+ ) {
+ throw new Error("Remote child stream resolver does not match the authored remote agent.");
+ }
+ return await resolveRemoteAgentRequestHeaders(definition);
+ }
+
+ const credentials = resolveDynamicRemoteAgentCredentials({
+ credentialsStepId: input.resolverId,
+ description: "",
+ path: "",
+ url: input.url,
+ });
+ return await resolveRemoteAgentRequestHeaders(credentials);
+}
+
function resolveDynamicRemoteAgentCredentials(config: DynamicRemoteAgentConfig): {
readonly auth?: ResolvedRuntimeRemoteAgentNode["auth"];
readonly headers?: HeadersValue;
@@ -424,16 +508,12 @@ function createRemoteAgentContinueUrl(
return createRemoteAgentRouteUrl(remote.url, createEveSessionRoutePath(sessionId));
}
-function createRemoteAgentRouteUrl(baseUrl: string, routePath: string): string {
- return new URL(routePath.replace(/^\/+/, ""), `${trimTrailingSlash(baseUrl)}/`).toString();
-}
-
function isRetryableRemoteCancelStatus(status: number): boolean {
return status === 408 || status === 425 || status === 429 || status >= 500;
}
async function resolveRemoteAgentRequestHeaders(
- remote: ResolvedRuntimeRemoteAgentNode,
+ remote: Pick<ResolvedRuntimeRemoteAgentNode, "auth" | "headers">,
): Promise<Record<string, string>> {
const headers: Record<string, string> = {};
if (remote.headers !== undefined) {
@@ -462,7 +542,3 @@ function formatRemoteAgentCallInputMessage(input: {
type: "remote",
}).message;
}
-
-function trimTrailingSlash(value: string): string {
- return value.endsWith("/") ? value.slice(0, -1) : value;
-}
diff --git a/packages/eve/src/execution/remote-agent-route-url.test.ts b/packages/eve/src/execution/remote-agent-route-url.test.ts
new file mode 100644
index 000000000..33da92373
--- /dev/null
+++ b/packages/eve/src/execution/remote-agent-route-url.test.ts
@@ -0,0 +1,14 @@
+import { describe, expect, it } from "vitest";
+
+import { createRemoteAgentRouteUrl } from "#execution/remote-agent-route-url.js";
+
+describe("createRemoteAgentRouteUrl", () => {
+ it("preserves a mounted remote agent base path", () => {
+ expect(
+ createRemoteAgentRouteUrl(
+ "https://remote.example/eve/agents/researcher",
+ "/eve/v1/task-input/capability",
+ ),
+ ).toBe("https://remote.example/eve/agents/researcher/eve/v1/task-input/capability");
+ });
+});
diff --git a/packages/eve/src/execution/remote-agent-route-url.ts b/packages/eve/src/execution/remote-agent-route-url.ts
new file mode 100644
index 000000000..73c864fbb
--- /dev/null
+++ b/packages/eve/src/execution/remote-agent-route-url.ts
@@ -0,0 +1,8 @@
+/** Joins an eve route to a remote agent base URL without dropping its path prefix. */
+export function createRemoteAgentRouteUrl(baseUrl: string, routePath: string): string {
+ return new URL(routePath.replace(/^\/+/, ""), `${trimTrailingSlash(baseUrl)}/`).toString();
+}
+
+function trimTrailingSlash(value: string): string {
+ return value.endsWith("/") ? value.slice(0, -1) : value;
+}
diff --git a/packages/eve/src/execution/route-child-delivery.test.ts b/packages/eve/src/execution/route-child-delivery.test.ts
new file mode 100644
index 000000000..447529881
--- /dev/null
+++ b/packages/eve/src/execution/route-child-delivery.test.ts
@@ -0,0 +1,157 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { routeDeliverToChildren } from "#execution/route-child-delivery.js";
+import { emitRecordedTaskInputRequestStep } from "#execution/subagent-event-proxy-step.js";
+import { recordTaskInputRequestStep } from "#execution/tasks/parent/hitl-proxy-steps.js";
+import { routeProxiedDeliverStep } from "#execution/proxied-deliver-step.js";
+import type { DurableSessionState } from "#execution/durable-session-store.js";
+
+vi.mock("#execution/subagent-event-proxy-step.js", () => ({
+ emitRecordedTaskInputRequestStep: vi.fn(),
+}));
+vi.mock("#execution/tasks/parent/hitl-proxy-steps.js", () => ({
+ recordTaskInputRequestStep: vi.fn(),
+}));
+vi.mock("#execution/proxied-deliver-step.js", () => ({
+ routeProxiedDeliverStep: vi.fn(),
+}));
+
+const state = (hasProxyInputRequests: boolean): DurableSessionState => ({
+ continuationToken: "parent-token",
+ emissionState: { sequence: 0, sessionStarted: true, stepIndex: 0, turnId: "" },
+ hasProxyInputRequests,
+ sessionId: "parent-session",
+ version: 1,
+});
+
+const hookPayload = {
+ callId: "call-task",
+ childContinuationToken: "child-token",
+ childSessionId: "child-session",
+ event: {
+ requests: [
+ {
+ action: { callId: "call-q", input: {}, kind: "tool-call" as const, toolName: "ask" },
+ kind: "question" as const,
+ prompt: "Which?",
+ requestId: "request-1",
+ },
+ ],
+ sequence: 1,
+ stepIndex: 2,
+ turnId: "turn_child",
+ },
+ kind: "subagent-input-request" as const,
+ subagentName: "research",
+};
+
+describe("task HITL delivery routing", () => {
+ beforeEach(() => vi.resetAllMocks());
+
+ it("commits the task route before emitting and consumes the framework-only delivery", async () => {
+ const recordedState = state(true);
+ vi.mocked(recordTaskInputRequestStep).mockResolvedValue({
+ accepted: true,
+ hookPayload,
+ sessionState: recordedState,
+ });
+ vi.mocked(emitRecordedTaskInputRequestStep).mockResolvedValue({
+ serializedContext: { adapter: "updated" },
+ sessionState: recordedState,
+ });
+ vi.mocked(routeProxiedDeliverStep).mockResolvedValue({
+ kind: "continue",
+ remainder: undefined,
+ serializedContext: { adapter: "updated" },
+ sessionState: recordedState,
+ });
+
+ const result = await routeDeliverToChildren({
+ delivery: {
+ kind: "deliver",
+ payloads: [{ task: { inputRequests: [{ hookPayload, taskId: "task-1" }] } }],
+ },
+ parentWritable: new WritableStream<Uint8Array>(),
+ serializedContext: {},
+ sessionState: state(false),
+ });
+
+ expect(result).toMatchObject({ kind: "continue", remainder: undefined });
+ expect(recordTaskInputRequestStep).toHaveBeenCalledOnce();
+ expect(emitRecordedTaskInputRequestStep).toHaveBeenCalledOnce();
+ expect(emitRecordedTaskInputRequestStep).toHaveBeenCalledWith(
+ expect.objectContaining({ hookPayload }),
+ );
+ expect(vi.mocked(recordTaskInputRequestStep).mock.invocationCallOrder[0]).toBeLessThan(
+ vi.mocked(emitRecordedTaskInputRequestStep).mock.invocationCallOrder[0] ?? 0,
+ );
+ });
+
+ it("drops an unowned task envelope before it can reach the parent model", async () => {
+ vi.mocked(recordTaskInputRequestStep).mockResolvedValue({
+ accepted: false,
+ sessionState: state(false),
+ });
+
+ const result = await routeDeliverToChildren({
+ delivery: {
+ kind: "deliver",
+ payloads: [{ task: { inputRequests: [{ hookPayload, taskId: "foreign-task" }] } }],
+ },
+ parentWritable: new WritableStream<Uint8Array>(),
+ serializedContext: {},
+ sessionState: state(false),
+ });
+
+ expect(result).toMatchObject({ kind: "continue", remainder: undefined });
+ expect(emitRecordedTaskInputRequestStep).not.toHaveBeenCalled();
+ expect(routeProxiedDeliverStep).not.toHaveBeenCalled();
+ });
+
+ it("reindexes ordinary metadata after consuming task-only payloads", async () => {
+ const routedState = state(true);
+ vi.mocked(routeProxiedDeliverStep).mockResolvedValue({
+ kind: "continue",
+ remainder: undefined,
+ serializedContext: {},
+ sessionState: routedState,
+ });
+ const caller = {
+ callId: "call-parent",
+ replyTo: { kind: "hook" as const, token: "parent-turn" },
+ subagentName: "research",
+ };
+
+ await routeDeliverToChildren({
+ delivery: {
+ caller,
+ deliveryMetadata: [
+ { channelKind: "test", channelName: "main", deliveryId: "task", payloadIndex: 0 },
+ { channelKind: "test", channelName: "main", deliveryId: "ordinary", payloadIndex: 1 },
+ ],
+ kind: "deliver",
+ payloads: [{ task: { views: [] } }, { message: "parent message" }],
+ requestId: "request-1",
+ taskDeliveryId: "task-delivery-1",
+ turnPolicy: "queue",
+ },
+ parentWritable: new WritableStream<Uint8Array>(),
+ serializedContext: {},
+ sessionState: routedState,
+ });
+
+ expect(routeProxiedDeliverStep).toHaveBeenCalledWith(
+ expect.objectContaining({
+ delivery: {
+ caller,
+ deliveryMetadata: [expect.objectContaining({ deliveryId: "ordinary", payloadIndex: 0 })],
+ kind: "deliver",
+ payloads: [{ message: "parent message" }],
+ requestId: "request-1",
+ taskDeliveryId: "task-delivery-1",
+ turnPolicy: "queue",
+ },
+ }),
+ );
+ });
+});
diff --git a/packages/eve/src/execution/route-child-delivery.ts b/packages/eve/src/execution/route-child-delivery.ts
index 5262f6973..a4d76d2ed 100644
--- a/packages/eve/src/execution/route-child-delivery.ts
+++ b/packages/eve/src/execution/route-child-delivery.ts
@@ -1,9 +1,19 @@
-import type { DeliverHookPayload } from "#channel/types.js";
+import type { DeliverHookPayload, DeliverPayload } from "#channel/types.js";
+import { coalesceDeliverPayloads } from "#execution/deliver-payloads.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
import {
routeProxiedDeliverStep,
type RoutedDeliverResult,
-} from "#execution/route-proxied-deliver-step.js";
+} from "#execution/proxied-deliver-step.js";
+import {
+ emitRecordedTaskAuthorizationEventStep,
+ emitRecordedTaskInputRequestStep,
+} from "#execution/subagent-event-proxy-step.js";
+import {
+ acceptTaskAuthorizationEventStep,
+ recordTerminalTaskViewsStep,
+ recordTaskInputRequestStep,
+} from "#execution/tasks/parent/hitl-proxy-steps.js";
/**
* Coalesces inbound deliver payloads and routes any descendant-bound input
@@ -19,14 +29,93 @@ export async function routeDeliverToChildren(input: {
readonly delivery: DeliverHookPayload;
readonly parentWritable: WritableStream<Uint8Array>;
readonly sessionState: DurableSessionState;
+ readonly serializedContext: Record<string, unknown>;
}): Promise<RoutedDeliverResult> {
- if (!input.sessionState.hasProxyInputRequests) {
- return { kind: "continue", remainder: input.delivery, sessionState: input.sessionState };
+ const payload = coalesceDeliverPayloads(input.delivery.payloads);
+ let serializedContext = input.serializedContext;
+ let sessionState = input.sessionState;
+
+ if ((payload.task?.views?.length ?? 0) > 0) {
+ sessionState = await recordTerminalTaskViewsStep({
+ sessionState,
+ views: payload.task?.views ?? [],
+ });
+ }
+
+ for (const request of payload.task?.inputRequests ?? []) {
+ const recorded = await recordTaskInputRequestStep({
+ hookPayload: request.hookPayload,
+ serializedContext,
+ sessionState,
+ taskId: request.taskId,
+ });
+ sessionState = recorded.sessionState;
+ if (!recorded.accepted) continue;
+ const emitted = await emitRecordedTaskInputRequestStep({
+ hookPayload: recorded.hookPayload,
+ parentWritable: input.parentWritable,
+ serializedContext,
+ sessionState,
+ });
+ serializedContext = emitted.serializedContext;
+ sessionState = emitted.sessionState;
+ }
+
+ for (const request of payload.task?.authorizationEvents ?? []) {
+ const accepted = await acceptTaskAuthorizationEventStep({
+ hookPayload: request.hookPayload,
+ sessionState,
+ taskId: request.taskId,
+ });
+ if (!accepted) continue;
+ const emitted = await emitRecordedTaskAuthorizationEventStep({
+ hookPayload: request.hookPayload,
+ parentWritable: input.parentWritable,
+ serializedContext,
+ sessionState,
+ });
+ serializedContext = emitted.serializedContext;
+ sessionState = emitted.sessionState;
+ }
+
+ const ordinaryPayloads: DeliverPayload[] = [];
+ const ordinaryMetadata: NonNullable<DeliverHookPayload["deliveryMetadata"]>[number][] = [];
+ for (const [sourcePayloadIndex, sourcePayload] of input.delivery.payloads.entries()) {
+ const ordinaryPayload = { ...sourcePayload };
+ delete ordinaryPayload.task;
+ if (Object.keys(ordinaryPayload).length === 0) continue;
+ const payloadIndex = ordinaryPayloads.length;
+ ordinaryPayloads.push(ordinaryPayload);
+ for (const metadata of input.delivery.deliveryMetadata ?? []) {
+ if (metadata.payloadIndex === sourcePayloadIndex) {
+ ordinaryMetadata.push({ ...metadata, payloadIndex });
+ }
+ }
+ }
+ const delivery: DeliverHookPayload | undefined =
+ ordinaryPayloads.length === 0
+ ? undefined
+ : {
+ ...input.delivery,
+ deliveryMetadata: ordinaryMetadata.length === 0 ? undefined : ordinaryMetadata,
+ payloads: ordinaryPayloads,
+ };
+ if (delivery === undefined) {
+ return { kind: "continue", remainder: undefined, serializedContext, sessionState };
+ }
+ if (!sessionState.hasProxyInputRequests) {
+ return {
+ kind: "continue",
+ remainder: delivery,
+ serializedContext,
+ sessionState,
+ };
}
return await routeProxiedDeliverStep({
- delivery: input.delivery,
+ delivery,
parentWritable: input.parentWritable,
- sessionState: input.sessionState,
+ serializedContext,
+ sessionState,
});
}
diff --git a/packages/eve/src/execution/route-proxied-deliver-step.ts b/packages/eve/src/execution/route-proxied-deliver-step.ts
deleted file mode 100644
index 50ff04296..000000000
--- a/packages/eve/src/execution/route-proxied-deliver-step.ts
+++ /dev/null
@@ -1,140 +0,0 @@
-import type { DeliverHookPayload, DeliverPayload, SessionAuthContext } from "#channel/types.js";
-import { coalesceDeliverPayloads } from "#execution/deliver-payloads.js";
-import {
- type DurableSessionState,
- readDurableSession,
- replaceDurableSessionSnapshot,
-} from "#execution/durable-session-store.js";
-import { routeDeliverPayload } from "#execution/subagent-hitl-proxy.js";
-import { retireProxyInputRequests } from "#harness/proxy-input-requests.js";
-import { resumeHook } from "#internal/workflow/runtime.js";
-
-export type RoutedDeliverResult =
- | { readonly kind: "cancel-turn"; readonly sessionState: DurableSessionState }
- | {
- readonly kind: "continue";
- readonly remainder: DeliverHookPayload | undefined;
- readonly sessionState: DurableSessionState;
- };
-
-type LegacyRoutedDeliverResult =
- | { readonly kind: "cancel-turn"; readonly sessionState: DurableSessionState }
- | {
- readonly kind: "continue";
- readonly remainder: DeliverPayload | undefined;
- readonly sessionState: DurableSessionState;
- };
-
-/**
- * Splits an inbound deliver payload into parent-local and proxied-child buckets.
- * Successfully forwarded request IDs are retired from the returned snapshot.
- */
-export function routeProxiedDeliverStep(input: {
- readonly delivery: DeliverHookPayload;
- readonly parentWritable: WritableStream<Uint8Array>;
- readonly sessionState: DurableSessionState;
-}): Promise<RoutedDeliverResult>;
-export function routeProxiedDeliverStep(input: {
- readonly auth?: SessionAuthContext | null;
- readonly parentWritable: WritableStream<Uint8Array>;
- readonly payload: DeliverPayload;
- readonly sessionState: DurableSessionState;
-}): Promise<LegacyRoutedDeliverResult>;
-export async function routeProxiedDeliverStep(
- input:
- | {
- readonly delivery: DeliverHookPayload;
- readonly parentWritable: WritableStream<Uint8Array>;
- readonly sessionState: DurableSessionState;
- }
- | {
- readonly auth?: SessionAuthContext | null;
- readonly parentWritable: WritableStream<Uint8Array>;
- readonly payload: DeliverPayload;
- readonly sessionState: DurableSessionState;
- },
-): Promise<LegacyRoutedDeliverResult | RoutedDeliverResult> {
- "use step";
-
- let durableSession = await readDurableSession(input.sessionState);
- const legacyInput = !("delivery" in input);
- const sourceDelivery: DeliverHookPayload =
- "delivery" in input
- ? input.delivery
- : { auth: input.auth, kind: "deliver", payloads: [input.payload] };
- const metadataByPayload = new Map(
- (sourceDelivery.deliveryMetadata ?? []).map((entry) => [entry.payloadIndex, entry]),
- );
- const parentPayloads: DeliverPayload[] = [];
- const parentMetadata: NonNullable<DeliverHookPayload["deliveryMetadata"]>[number][] = [];
- const children = new Map<
- string,
- {
- metadata: NonNullable<DeliverHookPayload["deliveryMetadata"]>[number][];
- payloads: DeliverPayload[];
- retireRequestIds: string[];
- }
- >();
- let parentAction: { readonly kind: "cancel-turn" } | undefined;
-
- for (const [payloadIndex, payload] of sourceDelivery.payloads.entries()) {
- const routed = routeDeliverPayload({ payload, state: durableSession.state });
- parentAction ??= routed.parentAction;
- const metadata = metadataByPayload.get(payloadIndex);
-
- if (routed.forSelf !== undefined) {
- const nextIndex = parentPayloads.length;
- parentPayloads.push(routed.forSelf);
- if (metadata !== undefined) parentMetadata.push({ ...metadata, payloadIndex: nextIndex });
- }
-
- for (const [childIndex, forChild] of routed.forChildren.entries()) {
- const child = children.get(forChild.childContinuationToken) ?? {
- metadata: [],
- payloads: [],
- retireRequestIds: [],
- };
- const nextIndex = child.payloads.length;
- child.payloads.push(forChild.payload);
- child.retireRequestIds.push(...forChild.retireRequestIds);
- if (metadata !== undefined && routed.forSelf === undefined && childIndex === 0) {
- child.metadata.push({ ...metadata, payloadIndex: nextIndex });
- }
- children.set(forChild.childContinuationToken, child);
- }
- }
-
- for (const [childContinuationToken, child] of children) {
- const delivery: DeliverHookPayload = {
- auth: sourceDelivery.auth,
- caller: sourceDelivery.caller,
- deliveryMetadata: child.metadata.length === 0 ? undefined : child.metadata,
- kind: "deliver",
- payloads: child.payloads,
- requestId: sourceDelivery.requestId,
- };
- await resumeHook(childContinuationToken, {
- ...delivery,
- payload: coalesceDeliverPayloads(child.payloads),
- });
- durableSession = retireProxyInputRequests(durableSession, child.retireRequestIds);
- }
-
- const sessionState =
- children.size === 0
- ? input.sessionState
- : replaceDurableSessionSnapshot({ session: durableSession, state: input.sessionState });
-
- if (parentAction !== undefined) return { ...parentAction, sessionState };
- const remainder =
- parentPayloads.length === 0
- ? undefined
- : legacyInput
- ? coalesceDeliverPayloads(parentPayloads)
- : {
- ...sourceDelivery,
- deliveryMetadata: parentMetadata.length === 0 ? undefined : parentMetadata,
- payloads: parentPayloads,
- };
- return { kind: "continue", remainder, sessionState };
-}
diff --git a/packages/eve/src/execution/session-callback-step.test.ts b/packages/eve/src/execution/session-callback-step.test.ts
index 7ed5eb7cd..b09cc9c73 100644
--- a/packages/eve/src/execution/session-callback-step.test.ts
+++ b/packages/eve/src/execution/session-callback-step.test.ts
@@ -138,7 +138,7 @@ describe("fireSessionCallbackStep", () => {
expect(errorSpy).not.toHaveBeenCalled();
});
- it("never includes usage on failed callbacks", async () => {
+ it("includes usage on failed callbacks", async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 202 }));
vi.stubGlobal("fetch", fetchMock);
@@ -149,7 +149,7 @@ describe("fireSessionCallbackStep", () => {
usage: USAGE,
});
- expect(parsePostedBody(fetchMock).usage).toBeUndefined();
+ expect(parsePostedBody(fetchMock).usage).toEqual(USAGE);
});
it("posts the failed callback with the normalized error message", async () => {
diff --git a/packages/eve/src/execution/session-callback-step.ts b/packages/eve/src/execution/session-callback-step.ts
index ceed02bac..d0a17d8d1 100644
--- a/packages/eve/src/execution/session-callback-step.ts
+++ b/packages/eve/src/execution/session-callback-step.ts
@@ -1,4 +1,4 @@
-import type { SessionCallback } from "#channel/types.js";
+import type { SessionCallback, SubagentAuthorizationEvent } from "#channel/types.js";
import { parseSessionCallback } from "#channel/session-callback.js";
import { SessionCallbackKey } from "#context/keys.js";
import { postSessionCallbackRequest } from "#execution/session-callback-request.js";
@@ -6,9 +6,42 @@ import { SESSION_FAILED } from "#harness/agent-handle-errors.js";
import { createLogger } from "#internal/logging.js";
import { toErrorMessage } from "#shared/errors.js";
import type { TokenUsage } from "#shared/token-usage.js";
+import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
const log = createLogger("execution.session-callback");
+/** Sends task-owned remote HITL and authorization events to the parent callback capability. */
+export async function fireTaskEventCallbackStep(input: {
+ readonly callback: unknown;
+ readonly childContinuationToken: string;
+ readonly childSessionId: string;
+ readonly event:
+ | SubagentAuthorizationEvent
+ | Extract<UnstampedMessageStreamEvent, { type: "input.requested" }>;
+}): Promise<void> {
+ "use step";
+
+ const callback = parseSerializedSessionCallback(input.callback);
+ if (callback.taskId === undefined) return;
+ const inputRequested = input.event.type === "input.requested";
+ const kind = inputRequested ? "task.input-requested" : "task.authorization";
+ const response = await postSessionCallbackRequest({
+ body: {
+ callId: callback.callId,
+ childContinuationToken: input.childContinuationToken,
+ childSessionId: input.childSessionId,
+ event: inputRequested ? input.event.data : input.event,
+ kind,
+ subagentName: callback.subagentName,
+ taskId: callback.taskId,
+ },
+ url: callback.url,
+ });
+ if (!response.ok) {
+ throw new Error(`Task event callback failed with HTTP ${response.status}.`);
+ }
+}
+
/**
* Sends the configured session terminal callback.
*
@@ -57,6 +90,7 @@ export async function fireSessionCallbackStep(input: {
kind: "session.failed" as const,
sessionId,
subagentName: callback.subagentName,
+ usage: input.usage,
};
const response = await postSessionCallbackRequest({ body, url: callback.url });
diff --git a/packages/eve/src/execution/session-command-wire.ts b/packages/eve/src/execution/session-command-wire.ts
index 7c44e08bb..d90d59c29 100644
--- a/packages/eve/src/execution/session-command-wire.ts
+++ b/packages/eve/src/execution/session-command-wire.ts
@@ -33,6 +33,7 @@ export function sendCommandToDelivery(
payload: command.payload,
payloads: [command.payload],
requestId: command.requestId,
+ taskDeliveryId: command.taskDeliveryId,
turnPolicy: command.turnPolicy,
};
}
diff --git a/packages/eve/src/execution/session-state-cursor.ts b/packages/eve/src/execution/session-state-cursor.ts
new file mode 100644
index 000000000..119caab8f
--- /dev/null
+++ b/packages/eve/src/execution/session-state-cursor.ts
@@ -0,0 +1,41 @@
+import type { DurableSessionState } from "#execution/durable-session-store.js";
+
+/** A durable-state transition; absent fields keep the cursor's current value. */
+export interface SessionStateTransition {
+ readonly serializedContext?: Record<string, unknown>;
+ readonly sessionState?: DurableSessionState;
+}
+
+/**
+ * Owns the mutable serialized-context / session-state pair that durable
+ * steps thread through a run. Holders adopt each step's transition instead
+ * of rebinding both values by hand at every callsite.
+ */
+export class SessionStateCursor {
+ private currentSerializedContext: Record<string, unknown>;
+ private currentSessionState: DurableSessionState;
+
+ constructor(input: {
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+ }) {
+ this.currentSerializedContext = input.serializedContext;
+ this.currentSessionState = input.sessionState;
+ }
+
+ /** Latest adopted serialized runtime context. */
+ get serializedContext(): Record<string, unknown> {
+ return this.currentSerializedContext;
+ }
+
+ /** Latest adopted durable session state. */
+ get sessionState(): DurableSessionState {
+ return this.currentSessionState;
+ }
+
+ /** Adopts a state transition; fields a step did not change carry forward. */
+ adoptState(transition: SessionStateTransition): void {
+ this.currentSerializedContext = transition.serializedContext ?? this.currentSerializedContext;
+ this.currentSessionState = transition.sessionState ?? this.currentSessionState;
+ }
+}
diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.ts b/packages/eve/src/execution/settle-cancelled-turn-step.ts
index ba3817084..5a0193659 100644
--- a/packages/eve/src/execution/settle-cancelled-turn-step.ts
+++ b/packages/eve/src/execution/settle-cancelled-turn-step.ts
@@ -29,6 +29,7 @@ import { abandonRunningAgentTurns } from "#harness/handles/transitions.js";
import { clearPendingRuntimeActionBatch } from "#harness/runtime-actions.js";
import { createInstrumentationHandleEvent } from "#harness/instrumentation/native-events.js";
import { getInstrumentationRuntime } from "#harness/instrumentation/runtime.js";
+import { getTurnUsageState, toUsage } from "#harness/turn-tag-state.js";
import { clearPendingWorkflowInterrupt } from "#harness/workflow-interrupt-state.js";
import {
encodeMessageStreamEvent,
@@ -37,10 +38,12 @@ import {
} from "#protocol/message.js";
import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
+import type { TokenUsage } from "#shared/token-usage.js";
export interface CancelledTurnSettleResult {
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
+ readonly usage?: TokenUsage;
}
/**
@@ -147,9 +150,11 @@ export async function settleCancelledTurnStep(input: {
emissionState,
),
);
+ const totals = getTurnUsageState(session.state)?.session;
- return {
+ const base = {
serializedContext: serializeContext(ctx),
sessionState: createDurableSessionState({ session: cancelledSession }),
};
+ return totals === undefined ? base : { ...base, usage: toUsage(totals) };
}
diff --git a/packages/eve/src/execution/subagent-event-proxy-step.ts b/packages/eve/src/execution/subagent-event-proxy-step.ts
index 8416a7b2d..acb2e6654 100644
--- a/packages/eve/src/execution/subagent-event-proxy-step.ts
+++ b/packages/eve/src/execution/subagent-event-proxy-step.ts
@@ -57,12 +57,53 @@ export async function runProxySubagentEventStep(input: {
});
}
+/** Emits a task request whose proxy routes were committed by a prior step. */
+export async function emitRecordedTaskInputRequestStep(input: {
+ readonly hookPayload: SubagentInputRequestHookPayload;
+ readonly parentWritable: WritableStream<Uint8Array>;
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+}): Promise<ProxySubagentEventResult> {
+ "use step";
+
+ const durableSession = await readDurableSession(input.sessionState);
+ const ctx = await deserializeContext(input.serializedContext);
+ return emitProxiedSubagentEvent({
+ ctx,
+ durableSession,
+ hookPayload: input.hookPayload,
+ parentWritable: input.parentWritable,
+ recordProxyInputRequests: false,
+ });
+}
+
+/** Emits a task authorization event after its ownership was validated. */
+export async function emitRecordedTaskAuthorizationEventStep(input: {
+ readonly hookPayload: SubagentAuthorizationEventHookPayload;
+ readonly parentWritable: WritableStream<Uint8Array>;
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+}): Promise<ProxySubagentEventResult> {
+ "use step";
+
+ const durableSession = await readDurableSession(input.sessionState);
+ const ctx = await deserializeContext(input.serializedContext);
+ return emitProxiedSubagentEvent({
+ ctx,
+ durableSession,
+ hookPayload: input.hookPayload,
+ parentWritable: input.parentWritable,
+ recordProxyInputRequests: false,
+ });
+}
+
/** Applies one proxied child event to an already-hydrated parent context. */
export async function emitProxiedSubagentEvent(input: {
readonly ctx: ContextContainer;
readonly durableSession: DurableSession;
readonly hookPayload: SubagentEventHookPayload;
readonly parentWritable: WritableStream<Uint8Array>;
+ readonly recordProxyInputRequests?: boolean;
}): Promise<ProxySubagentEventResult> {
const { ctx } = input;
const adapter = ctx.require(ChannelKey);
@@ -110,7 +151,11 @@ export async function emitProxiedSubagentEvent(input: {
setChannelContext(ctx, { ...adapter, state: { ...adapterCtx.state } });
- if (proxyEntries !== undefined && input.hookPayload.kind === "subagent-input-request") {
+ if (
+ input.recordProxyInputRequests !== false &&
+ proxyEntries !== undefined &&
+ input.hookPayload.kind === "subagent-input-request"
+ ) {
scopedSession = upsertProxyInputRequests({
entries: proxyEntries,
forChildContinuationToken: input.hookPayload.childContinuationToken,
diff --git a/packages/eve/src/execution/subagent-hitl-proxy.test.ts b/packages/eve/src/execution/subagent-hitl-proxy.test.ts
index a76cc51c3..480ef0114 100644
--- a/packages/eve/src/execution/subagent-hitl-proxy.test.ts
+++ b/packages/eve/src/execution/subagent-hitl-proxy.test.ts
@@ -1,10 +1,6 @@
import { describe, expect, it } from "vitest";
-import {
- retireProxyInputRequests,
- upsertProxyInputRequests,
-} from "#harness/proxy-input-requests.js";
-import type { ProxyInputRequest } from "#harness/proxy-input-requests.js";
+import { upsertProxyInputRequests } from "#harness/proxy-input-requests.js";
import type { HarnessSession } from "#harness/types.js";
import { routeDeliverPayload } from "#execution/subagent-hitl-proxy.js";
@@ -23,26 +19,6 @@ function createSession(state?: Record<string, unknown>): HarnessSession {
};
}
-function addBatchRoutes(
- session: HarnessSession,
- requests: readonly { readonly kind: ProxyInputRequest["kind"]; readonly requestId: string }[],
-): HarnessSession {
- const batch = {
- approvalRequestIds: requests.flatMap((request) =>
- request.kind === "tool-approval" ? [request.requestId] : [],
- ),
- requestIds: requests.map((request) => request.requestId),
- };
- return upsertProxyInputRequests({
- entries: requests.map((request) => [
- request.requestId,
- { batch, childContinuationToken: "child-a", kind: request.kind },
- ]),
- forChildContinuationToken: "child-a",
- session,
- });
-}
-
describe("routeDeliverPayload", () => {
it("routes responses to matching descendants and keeps unknown ones on forSelf", () => {
const session = upsertProxyInputRequests({
@@ -109,16 +85,38 @@ describe("routeDeliverPayload", () => {
expect(routed.forSelf).toBeUndefined();
});
- it("asks the parent to cancel after routing Stop to a descendant session-limit request", () => {
+ it("keeps one task response batch atomic and marks it for its task run", () => {
const session = upsertProxyInputRequests({
- entries: [["req-limit", { childContinuationToken: "child-a", kind: "session-limit" }]],
+ entries: [
+ [
+ "task-1:req-a",
+ {
+ childContinuationToken: "child-a",
+ childRequestId: "req-a",
+ kind: "tool-approval",
+ taskId: "task-1",
+ },
+ ],
+ [
+ "task-1:req-b",
+ {
+ childContinuationToken: "child-a",
+ childRequestId: "req-b",
+ kind: "question",
+ taskId: "task-1",
+ },
+ ],
+ ],
forChildContinuationToken: "child-a",
session: createSession(),
});
const routed = routeDeliverPayload({
payload: {
- inputResponses: [{ optionId: "stop", requestId: "req-limit" }],
+ inputResponses: [
+ { optionId: "approve", requestId: "task-1:req-a" },
+ { text: "west", requestId: "task-1:req-b" },
+ ],
},
state: session.state,
});
@@ -126,82 +124,88 @@ describe("routeDeliverPayload", () => {
expect(routed.forChildren).toEqual([
{
childContinuationToken: "child-a",
- payload: { inputResponses: [{ optionId: "stop", requestId: "req-limit" }] },
- retireRequestIds: ["req-limit"],
+ payload: {
+ inputResponses: [
+ { optionId: "approve", requestId: "req-a" },
+ { text: "west", requestId: "req-b" },
+ ],
+ },
+ retireRequestIds: ["task-1:req-a", "task-1:req-b"],
+ taskId: "task-1",
},
]);
- expect(routed.parentAction).toEqual({ kind: "cancel-turn" });
});
- it("retires an entire question batch after one answer", () => {
- const session = addBatchRoutes(createSession(), [
- { kind: "question", requestId: "question-1" },
- { kind: "question", requestId: "question-2" },
- ]);
-
- const routed = routeDeliverPayload({
- payload: { inputResponses: [{ requestId: "question-1", text: "answer" }] },
- state: session.state,
+ it("keeps identical child-local ids isolated across tasks", () => {
+ let session = upsertProxyInputRequests({
+ entries: [
+ [
+ "task-1:req-shared",
+ {
+ childContinuationToken: "child-a",
+ childRequestId: "req-shared",
+ kind: "tool-approval",
+ taskId: "task-1",
+ },
+ ],
+ ],
+ forChildContinuationToken: "child-a",
+ session: createSession(),
+ });
+ session = upsertProxyInputRequests({
+ entries: [
+ [
+ "task-2:req-shared",
+ {
+ childContinuationToken: "child-b",
+ childRequestId: "req-shared",
+ kind: "tool-approval",
+ taskId: "task-2",
+ },
+ ],
+ ],
+ forChildContinuationToken: "child-b",
+ session,
});
-
- expect(new Set(routed.forChildren[0]?.retireRequestIds)).toEqual(
- new Set(["question-1", "question-2"]),
- );
- });
-
- it("retires a mixed batch when all of its approvals are answered", () => {
- const session = addBatchRoutes(createSession(), [
- { kind: "question", requestId: "question-1" },
- { kind: "tool-approval", requestId: "approval-1" },
- ]);
const routed = routeDeliverPayload({
- payload: { inputResponses: [{ optionId: "approve", requestId: "approval-1" }] },
+ payload: {
+ inputResponses: [{ optionId: "approve", requestId: "task-1:req-shared" }],
+ },
state: session.state,
});
- expect(new Set(routed.forChildren[0]?.retireRequestIds)).toEqual(
- new Set(["question-1", "approval-1"]),
- );
- });
-
- it("keeps unresolved approval routes across partial multi-approval responses", () => {
- let session = addBatchRoutes(createSession(), [
- { kind: "tool-approval", requestId: "approval-1" },
- { kind: "tool-approval", requestId: "approval-2" },
+ expect(routed.forChildren).toEqual([
+ {
+ childContinuationToken: "child-a",
+ payload: { inputResponses: [{ optionId: "approve", requestId: "req-shared" }] },
+ retireRequestIds: ["task-1:req-shared"],
+ taskId: "task-1",
+ },
]);
-
- const partial = routeDeliverPayload({
- payload: { inputResponses: [{ optionId: "approve", requestId: "approval-1" }] },
- state: session.state,
- });
- expect(partial.forChildren[0]?.retireRequestIds).toEqual(["approval-1"]);
-
- session = retireProxyInputRequests(session, partial.forChildren[0]?.retireRequestIds ?? []);
- const completed = routeDeliverPayload({
- payload: { inputResponses: [{ optionId: "cancel", requestId: "approval-2" }] },
- state: session.state,
- });
- expect(new Set(completed.forChildren[0]?.retireRequestIds)).toEqual(
- new Set(["approval-1", "approval-2"]),
- );
});
- it("keeps request-only retirement for legacy routes without batch metadata", () => {
+ it("asks the parent to cancel after routing Stop to a descendant session-limit request", () => {
const session = upsertProxyInputRequests({
- entries: [
- ["question-1", { childContinuationToken: "child-a", kind: "question" }],
- ["question-2", { childContinuationToken: "child-a", kind: "question" }],
- ],
+ entries: [["req-limit", { childContinuationToken: "child-a", kind: "session-limit" }]],
forChildContinuationToken: "child-a",
session: createSession(),
});
const routed = routeDeliverPayload({
- payload: { inputResponses: [{ requestId: "question-1", text: "answer" }] },
+ payload: {
+ inputResponses: [{ optionId: "stop", requestId: "req-limit" }],
+ },
state: session.state,
});
- expect(routed.forChildren[0]?.retireRequestIds).toEqual(["question-1"]);
+ expect(routed.forChildren).toEqual([
+ {
+ childContinuationToken: "child-a",
+ payload: { inputResponses: [{ optionId: "stop", requestId: "req-limit" }] },
+ retireRequestIds: ["req-limit"],
+ },
+ ]);
+ expect(routed.parentAction).toEqual({ kind: "cancel-turn" });
});
});
diff --git a/packages/eve/src/execution/subagent-hitl-proxy.ts b/packages/eve/src/execution/subagent-hitl-proxy.ts
index 7cb379166..8fce34f07 100644
--- a/packages/eve/src/execution/subagent-hitl-proxy.ts
+++ b/packages/eve/src/execution/subagent-hitl-proxy.ts
@@ -60,40 +60,56 @@ export async function emitProxiedInputRequest(input: {
// Downward deliver routing
// ---------------------------------------------------------------------------
+/** One proxied-child bucket of a routed deliver payload. */
+export interface RoutedChildDelivery {
+ readonly childContinuationToken: string;
+ readonly childResponseUrl?: string;
+ readonly payload: { readonly inputResponses: readonly InputResponse[] };
+ /** Parent-visible request IDs safe to retire once this bucket is forwarded. */
+ readonly retireRequestIds: readonly string[];
+ /** Present when the child is owned by a task run, which delivers on the parent's behalf. */
+ readonly taskId?: string;
+}
+
/**
* Outcome of splitting one deliver payload by the session's proxy map.
* `forSelf` is the parent-local remainder (or `undefined` when fully
* routed); `forChildren` carries one entry per descendant token.
*/
export interface RoutedDeliverPayload {
- readonly forChildren: readonly {
- readonly childContinuationToken: string;
- readonly payload: { readonly inputResponses: readonly InputResponse[] };
- readonly retireRequestIds: readonly string[];
- }[];
+ readonly forChildren: readonly RoutedChildDelivery[];
readonly forSelf: DeliverPayload | undefined;
readonly parentAction: { readonly kind: "cancel-turn" } | undefined;
}
+/** In-progress accumulation for one `forChildren` bucket. */
+interface ChildResponseBucket {
+ readonly childContinuationToken: string;
+ readonly childResponseUrl?: string;
+ /** Parent-visible request IDs answered in this bucket. */
+ readonly parentRequestIds: string[];
+ readonly responses: InputResponse[];
+ readonly routes: ProxyInputRequest[];
+ readonly taskId?: string;
+}
+
/** Splits a deliver payload into parent-local and proxied-child buckets. */
export function routeDeliverPayload(input: {
+ readonly allowRoute?: (requestId: string, route: ProxyInputRequest) => boolean;
readonly payload: DeliverPayload;
readonly state: SessionStateMap | undefined;
}): RoutedDeliverPayload {
const entries = getProxyInputRequests(input.state);
const inputResponses = input.payload.inputResponses ?? [];
- const responsesByChild = new Map<
- string,
- { responses: InputResponse[]; routes: ProxyInputRequest[] }
- >();
+ const responsesByChild = new Map<string, ChildResponseBucket>();
const unroutedResponses: InputResponse[] = [];
let parentAction: RoutedDeliverPayload["parentAction"];
for (const response of inputResponses) {
const route = entries.get(response.requestId);
- if (route === undefined) {
+ if (route === undefined || input.allowRoute?.(response.requestId, route) === false) {
unroutedResponses.push(response);
continue;
}
@@ -102,25 +118,44 @@ export function routeDeliverPayload(input: {
parentAction = { kind: "cancel-turn" };
}
- const existing = responsesByChild.get(route.childContinuationToken);
+ const bucketKey =
+ route.taskId === undefined
+ ? route.childContinuationToken
+ : `${route.childContinuationToken}\0${route.childResponseUrl ?? "local"}\0${route.taskId}`;
+ const existing = responsesByChild.get(bucketKey);
if (existing === undefined) {
- responsesByChild.set(route.childContinuationToken, {
- responses: [response],
+ responsesByChild.set(bucketKey, {
+ childContinuationToken: route.childContinuationToken,
+ parentRequestIds: [response.requestId],
+ responses: [toChildInputResponse(response, route)],
routes: [route],
+ ...(route.childResponseUrl !== undefined && { childResponseUrl: route.childResponseUrl }),
+ ...(route.taskId !== undefined && { taskId: route.taskId }),
});
} else {
- existing.responses.push(response);
+ existing.parentRequestIds.push(response.requestId);
+ existing.responses.push(toChildInputResponse(response, route));
existing.routes.push(route);
}
}
- const forChildren: RoutedDeliverPayload["forChildren"] = [...responsesByChild.entries()].map(
- ([childContinuationToken, bucket]) => {
- const responseIds = new Set(bucket.responses.map((response) => response.requestId));
+ const forChildren = [...responsesByChild.values()].map(
+ ({
+ childContinuationToken,
+ childResponseUrl,
+ parentRequestIds,
+ responses,
+ routes,
+ taskId,
+ }): RoutedChildDelivery => {
+ const responseIds = new Set(parentRequestIds);
const retireRequestIds = new Set(responseIds);
- for (const route of bucket.routes) {
+ // A fully-answered approval batch retires its sibling requests
+ // too, so a late free-form answer cannot route through a stale
+ // sibling entry after the batch already resolved.
+ for (const route of routes) {
if (
route.batch !== undefined &&
batchResolves({ batch: route.batch, childContinuationToken, entries, responseIds })
@@ -131,8 +166,10 @@ export function routeDeliverPayload(input: {
return {
childContinuationToken,
- payload: { inputResponses: bucket.responses },
+ payload: { inputResponses: responses },
retireRequestIds: [...retireRequestIds],
+ ...(childResponseUrl !== undefined && { childResponseUrl }),
+ ...(taskId !== undefined && { taskId }),
};
},
);
@@ -187,3 +224,9 @@ function sameBatch(
route.batch.requestIds.every((requestId, index) => requestId === input.batch.requestIds[index])
);
}
+
+function toChildInputResponse(response: InputResponse, route: ProxyInputRequest): InputResponse {
+ return route.childRequestId === undefined
+ ? response
+ : { ...response, requestId: route.childRequestId };
+}
diff --git a/packages/eve/src/execution/subagent-start-local.ts b/packages/eve/src/execution/subagent-start-local.ts
new file mode 100644
index 000000000..7d184d43f
--- /dev/null
+++ b/packages/eve/src/execution/subagent-start-local.ts
@@ -0,0 +1,135 @@
+import type { DispatchOutcome, RuntimeSession } from "#execution/agent-handle-dispatch.js";
+import { mintStartOperation } from "#execution/dispatch-start-operation.js";
+import { isRuntimeSessionOwnershipConflictError } from "#execution/runtime-errors.js";
+import { buildSubagentRunInput, type SubagentInputSource } from "#execution/subagent-tool.js";
+import { createWorkflowRuntime } from "#execution/workflow-runtime.js";
+import { SUBAGENT_START_FAILED } from "#harness/agent-handle-errors.js";
+import {
+ confirmAgentStarted,
+ confirmTaskAgentAddress,
+ prepareAgentStart,
+ rejectAgentEffect,
+} from "#harness/handles/transitions.js";
+import { createLogger, logError } from "#internal/logging.js";
+import type { RuntimeSubagentCallActionRequest } from "#runtime/actions/types.js";
+import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
+import { toErrorMessage } from "#shared/errors.js";
+
+const log = createLogger("execution.subagent-start-local");
+
+type DynamicSubagentAgentConfig = Parameters<
+ typeof createWorkflowRuntime
+>[0]["dynamicSubagentAgentConfig"];
+
+/** Starts one local subagent after dispatch planning has selected its target. */
+export async function startLocalSubagent(input: {
+ readonly action: RuntimeSubagentCallActionRequest;
+ readonly auth: Parameters<typeof buildSubagentRunInput>[0]["auth"];
+ readonly batchEvent: { readonly sequence: number; readonly turnId: string };
+ readonly bundle: CompiledBundle;
+ readonly capabilities: Parameters<typeof buildSubagentRunInput>[0]["capabilities"];
+ readonly channelMetadata: Parameters<typeof buildSubagentRunInput>[0]["channelMetadata"];
+ readonly currentSession: RuntimeSession;
+ readonly dynamicSubagentAgentConfig?: DynamicSubagentAgentConfig;
+ readonly fanoutSize: number;
+ readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];
+ readonly parentContinuationToken: string | undefined;
+ readonly parentTraceContext: Parameters<typeof buildSubagentRunInput>[0]["parentTraceContext"];
+ readonly persistentSessions: boolean;
+ readonly session: RuntimeSession;
+ readonly source: SubagentInputSource;
+ readonly taskOwned: boolean;
+}): Promise<DispatchOutcome> {
+ const { action, source } = input;
+ const childRuntime = createWorkflowRuntime({
+ compiledArtifactsSource: input.bundle.compiledArtifactsSource,
+ dynamicSubagentAgentConfig: input.dynamicSubagentAgentConfig,
+ nodeId: action.nodeId,
+ });
+ const { childContinuationToken, runInput } = buildSubagentRunInput({
+ action,
+ auth: input.auth,
+ batchEvent: input.batchEvent,
+ capabilities: input.capabilities,
+ channelMetadata: input.channelMetadata,
+ fanoutSize: input.fanoutSize,
+ initiatorAuth: input.initiatorAuth,
+ parentContinuationToken: input.parentContinuationToken,
+ parentTraceContext: input.parentTraceContext,
+ persistentSessions: input.persistentSessions,
+ session: input.session,
+ source,
+ });
+
+ const targetKind = source.type === "runtime" ? ("agent/self" as const) : ("agent/local" as const);
+ const { identity, operation } = mintStartOperation({
+ callId: action.callId,
+ name: action.subagentName,
+ nodeId: action.nodeId,
+ parentSessionId: input.session.sessionId,
+ parentTurnId: input.batchEvent.turnId,
+ });
+ // Ownership is recorded before the start side effect, and the prepared
+ // (or rejected) store rides every outcome into the step result. The
+ // guarantee is intra-step: a crash between the accepted start and the
+ // step-result commit still replays the whole dispatch step, so the
+ // orphan window shrinks to that boundary rather than disappearing.
+ const preparedSession = prepareAgentStart(input.currentSession, {
+ identity,
+ operation,
+ target: { continuationToken: childContinuationToken, kind: targetKind },
+ });
+
+ let childSessionId: string;
+ try {
+ const handle = await childRuntime.createSession(runInput);
+ childSessionId = handle.sessionId;
+ } catch (error) {
+ if (!isRuntimeSessionOwnershipConflictError(error)) {
+ logError(log, "local subagent start failed", error, {
+ callId: action.callId,
+ nodeId: action.nodeId,
+ subagentName: action.subagentName,
+ });
+ return {
+ kind: "error",
+ result: {
+ callId: action.callId,
+ isError: true,
+ kind: "subagent-result",
+ origin: "dispatch",
+ output: {
+ code: SUBAGENT_START_FAILED,
+ message: toErrorMessage(error),
+ },
+ subagentName: action.subagentName,
+ },
+ session: rejectAgentEffect(preparedSession, {
+ disposition: "dead",
+ operationId: operation.id,
+ }),
+ };
+ }
+ // A replayed step re-derives the same deterministic child continuation
+ // token, so the run holding it is the child this operation already
+ // started. Adopt it instead of failing live work and starting a second
+ // child on the next attempt.
+ childSessionId = error.ownerSessionId;
+ }
+
+ const address = {
+ continuationToken: childContinuationToken,
+ kind: targetKind,
+ sessionId: childSessionId,
+ } as const;
+ return {
+ address,
+ callId: action.callId,
+ kind: "called",
+ name: action.name,
+ session: input.taskOwned
+ ? confirmTaskAgentAddress(preparedSession, { address, operationId: operation.id })
+ : confirmAgentStarted(preparedSession, { address, operationId: operation.id }),
+ toolName: action.subagentName,
+ };
+}
diff --git a/packages/eve/src/execution/subagent-start-remote.ts b/packages/eve/src/execution/subagent-start-remote.ts
new file mode 100644
index 000000000..63cfbc5af
--- /dev/null
+++ b/packages/eve/src/execution/subagent-start-remote.ts
@@ -0,0 +1,125 @@
+import type { DispatchOutcome, RuntimeSession } from "#execution/agent-handle-dispatch.js";
+import { createRemoteAgentStartFailureResult } from "#execution/dispatch-action-failures.js";
+import { mintStartOperation } from "#execution/dispatch-start-operation.js";
+import {
+ resolveRemoteAgentForAction,
+ startRemoteAgentSession,
+} from "#execution/remote-agent-dispatch.js";
+import {
+ confirmAgentStarted,
+ confirmTaskAgentAddress,
+ prepareAgentStart,
+ rejectAgentEffect,
+} from "#harness/handles/transitions.js";
+import { createLogger, logError } from "#internal/logging.js";
+import type { RuntimeRemoteAgentCallActionRequest } from "#runtime/actions/types.js";
+import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
+
+const log = createLogger("execution.subagent-start-remote");
+
+/** Starts one remote subagent after dispatch planning has selected its target. */
+export async function startRemoteSubagent(input: {
+ readonly action: RuntimeRemoteAgentCallActionRequest;
+ readonly auth: Parameters<typeof startRemoteAgentSession>[0]["auth"];
+ readonly batchEvent: { readonly sequence: number; readonly turnId: string };
+ readonly bundle: CompiledBundle;
+ readonly callbackBaseUrl: string | undefined;
+ readonly currentSession: RuntimeSession;
+ readonly dynamicRemoteAgent?: NonNullable<
+ Parameters<typeof resolveRemoteAgentForAction>[0]["dynamicRemoteAgent"]
+ >;
+ readonly initiatorAuth: Parameters<typeof startRemoteAgentSession>[0]["initiatorAuth"];
+ readonly parentContinuationToken: string | undefined;
+ readonly parentTraceContext: Parameters<typeof startRemoteAgentSession>[0]["parentTraceContext"];
+ readonly persistentSessions: boolean;
+ readonly session: RuntimeSession;
+ readonly taskOwned: boolean;
+}): Promise<DispatchOutcome> {
+ const { action } = input;
+
+ // Preflight resolution failures happen before ownership exists, so they
+ // reject without touching the handle store.
+ let callbackBaseUrl: string;
+ let resolvedRemote: ReturnType<typeof resolveRemoteAgentForAction>;
+ try {
+ if (input.callbackBaseUrl === undefined) {
+ throw new Error("Cannot dispatch remote agent without a callback base URL.");
+ }
+ callbackBaseUrl = input.callbackBaseUrl;
+ resolvedRemote = resolveRemoteAgentForAction({
+ dynamicRemoteAgent: input.dynamicRemoteAgent,
+ nodeId: action.nodeId,
+ remoteAgentName: action.remoteAgentName,
+ registry: input.bundle.subagentRegistry.subagentsByNodeId,
+ });
+ } catch (error) {
+ logError(log, "remote agent start failed", error, {
+ remoteAgentName: action.remoteAgentName,
+ nodeId: action.nodeId,
+ callId: action.callId,
+ });
+ return {
+ kind: "error",
+ result: createRemoteAgentStartFailureResult({ action, error }),
+ session: input.currentSession,
+ };
+ }
+
+ const { identity, operation } = mintStartOperation({
+ callId: action.callId,
+ name: action.remoteAgentName,
+ nodeId: action.nodeId,
+ parentSessionId: input.session.sessionId,
+ parentTurnId: input.batchEvent.turnId,
+ });
+ const preparedSession = prepareAgentStart(input.currentSession, {
+ identity,
+ operation,
+ target: { callbackBaseUrl, kind: "agent/remote", url: resolvedRemote.url },
+ });
+
+ try {
+ const child = await startRemoteAgentSession({
+ action,
+ auth: input.auth,
+ callbackBaseUrl,
+ callbackToken: input.parentContinuationToken,
+ initiatorAuth: input.initiatorAuth,
+ operationId: operation.id,
+ parentTraceContext: input.parentTraceContext,
+ persistentSessions: input.persistentSessions,
+ remote: resolvedRemote,
+ session: input.session,
+ });
+ const address = {
+ callbackBaseUrl,
+ kind: "agent/remote",
+ sessionId: child.sessionId,
+ url: resolvedRemote.url,
+ } as const;
+ return {
+ address,
+ callId: action.callId,
+ kind: "called",
+ name: action.name,
+ session: input.taskOwned
+ ? confirmTaskAgentAddress(preparedSession, { address, operationId: operation.id })
+ : confirmAgentStarted(preparedSession, { address, operationId: operation.id }),
+ toolName: action.remoteAgentName,
+ };
+ } catch (error) {
+ logError(log, "remote agent start failed", error, {
+ remoteAgentName: action.remoteAgentName,
+ nodeId: action.nodeId,
+ callId: action.callId,
+ });
+ return {
+ kind: "error",
+ result: createRemoteAgentStartFailureResult({ action, error }),
+ session: rejectAgentEffect(preparedSession, {
+ disposition: "dead",
+ operationId: operation.id,
+ }),
+ };
+ }
+}
diff --git a/packages/eve/src/execution/task-event-callback.ts b/packages/eve/src/execution/task-event-callback.ts
new file mode 100644
index 000000000..d55aac986
--- /dev/null
+++ b/packages/eve/src/execution/task-event-callback.ts
@@ -0,0 +1,35 @@
+import type { ContextContainer } from "#context/container.js";
+import { ContinuationTokenKey, SessionCallbackKey, SessionIdKey } from "#context/keys.js";
+import { fireTaskEventCallbackStep } from "#execution/session-callback-step.js";
+import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
+
+/**
+ * Forwards one task child's blocking transition to its parent's session
+ * callback.
+ *
+ * Task children report HITL and authorization transitions to the parent's
+ * task run before local emission, so the run can block/unblock the task
+ * under one durable decision. A session without a callback capability
+ * (non-delegated runs) is a no-op, as is any event outside the three
+ * blocking transitions.
+ */
+export async function forwardTaskEventToSessionCallback(
+ ctx: ContextContainer,
+ event: UnstampedMessageStreamEvent,
+): Promise<void> {
+ const callback = ctx.get(SessionCallbackKey);
+ if (callback === undefined) return;
+ if (
+ event.type !== "input.requested" &&
+ event.type !== "authorization.required" &&
+ event.type !== "authorization.completed"
+ ) {
+ return;
+ }
+ await fireTaskEventCallbackStep({
+ callback,
+ childContinuationToken: ctx.require(ContinuationTokenKey),
+ childSessionId: ctx.require(SessionIdKey),
+ event,
+ });
+}
diff --git a/packages/eve/src/execution/task-input-capability.test.ts b/packages/eve/src/execution/task-input-capability.test.ts
new file mode 100644
index 000000000..a04ff4d37
--- /dev/null
+++ b/packages/eve/src/execution/task-input-capability.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ createTaskInputCapabilityToken,
+ readTaskInputTargetToken,
+} from "#execution/task-input-capability.js";
+
+const DIGEST = "0123456789abcdef0123456789abcdef";
+
+describe("task input capabilities", () => {
+ it("round-trips only an eve create-once session hook", () => {
+ const capability = createTaskInputCapabilityToken(`eve:eve:op:${DIGEST}`);
+
+ expect(capability).toBe(`eve:task-input:${DIGEST}`);
+ expect(readTaskInputTargetToken(capability)).toBe(`eve:eve:op:${DIGEST}`);
+ });
+
+ it.each(["eve:session:victim:inbox", "task:task_1:0123456789abcdef0123456789abcdef"])(
+ "does not mint a task-input capability for %s",
+ (token) => {
+ expect(() => createTaskInputCapabilityToken(token)).toThrow(
+ "requires an eve create-once session capability",
+ );
+ },
+ );
+
+ it("rejects malformed task-input capabilities", () => {
+ expect(readTaskInputTargetToken("eve:task-input:not-a-digest")).toBeUndefined();
+ });
+});
diff --git a/packages/eve/src/execution/task-input-capability.ts b/packages/eve/src/execution/task-input-capability.ts
new file mode 100644
index 000000000..d1150a0f6
--- /dev/null
+++ b/packages/eve/src/execution/task-input-capability.ts
@@ -0,0 +1,24 @@
+const OPERATION_TOKEN_PREFIX = "eve:eve:op:";
+const TASK_INPUT_TOKEN_PREFIX = "eve:task-input:";
+const TOKEN_DIGEST = /^[a-f0-9]{32}$/;
+
+/** Narrows one private create-once session token to task-input delivery only. */
+export function createTaskInputCapabilityToken(operationToken: string): string {
+ const digest = readTokenDigest(operationToken, OPERATION_TOKEN_PREFIX);
+ if (digest === undefined) {
+ throw new Error("Remote task input requires an eve create-once session capability.");
+ }
+ return `${TASK_INPUT_TOKEN_PREFIX}${digest}`;
+}
+
+/** Resolves a task-input capability to the create-once session hook it may address. */
+export function readTaskInputTargetToken(capabilityToken: string): string | undefined {
+ const digest = readTokenDigest(capabilityToken, TASK_INPUT_TOKEN_PREFIX);
+ return digest === undefined ? undefined : `${OPERATION_TOKEN_PREFIX}${digest}`;
+}
+
+function readTokenDigest(token: string, prefix: string): string | undefined {
+ if (!token.startsWith(prefix)) return undefined;
+ const digest = token.slice(prefix.length);
+ return TOKEN_DIGEST.test(digest) ? digest : undefined;
+}
diff --git a/packages/eve/src/execution/tasks/run-task.ts b/packages/eve/src/execution/tasks/child/steps.ts
similarity index 81%
rename from packages/eve/src/execution/tasks/run-task.ts
rename to packages/eve/src/execution/tasks/child/steps.ts
index b241f7e81..d64aaaed2 100644
--- a/packages/eve/src/execution/tasks/run-task.ts
+++ b/packages/eve/src/execution/tasks/child/steps.ts
@@ -1,23 +1,17 @@
import { getWritable } from "#compiled/@workflow/core/index.js";
-import {
- EntityConflictError,
- HookNotFoundError,
- RunExpiredError,
- WorkflowRunNotFoundError,
-} from "#compiled/@workflow/errors/index.js";
-
import type {
SessionAuthContext,
SessionCommand,
SubagentAuthorizationEventHookPayload,
SubagentInputRequestHookPayload,
} from "#channel/types.js";
+import { isTaskWorkflowTargetGone } from "#execution/tasks/workflow-target.js";
import { resumeHook } from "#internal/workflow/runtime.js";
import { createLogger } from "#internal/logging.js";
-import { walkCauseChain } from "#shared/errors.js";
import {
isTerminalTaskStatus,
- TASK_SNAPSHOT_STREAM_NAMESPACE,
+ taskAuthorizationRequestId,
+ TASK_VIEW_STREAM_NAMESPACE,
type TaskInboundAnswerInput,
type TaskInboundAuthorizationEvent,
type TaskInboundInputRequest,
@@ -27,14 +21,14 @@ import {
const log = createLogger("execution.tasks.run");
/**
- * Appends one full task snapshot to the owning task run's `eve.task`
+ * Appends one full task view to the owning task run's `eve.task`
* stream. Only the task run workflow calls this, which is what makes
* the run the single writer readers can trust without re-validating.
*/
-export async function appendTaskSnapshotStep(input: { readonly view: TaskView }): Promise<void> {
+export async function appendTaskViewStep(input: { readonly view: TaskView }): Promise<void> {
"use step";
- const writable = getWritable<TaskView>({ namespace: TASK_SNAPSHOT_STREAM_NAMESPACE });
+ const writable = getWritable<TaskView>({ namespace: TASK_VIEW_STREAM_NAMESPACE });
const writer = writable.getWriter();
try {
await writer.write(input.view);
@@ -58,11 +52,6 @@ export async function wakeTaskAuthorizationParentStep(input: {
kind: "subagent-authorization-event",
subagentName: input.request.subagentName,
};
- const eventId =
- input.request.event.type === "approval.candidate" ||
- input.request.event.type === "approval.settled"
- ? input.request.event.data.requestId
- : input.request.event.data.name;
const data = input.request.event.data;
const payload: {
message?: string;
@@ -79,12 +68,12 @@ export async function wakeTaskAuthorizationParentStep(input: {
const command: SessionCommand = {
kind: "send",
payload,
- taskDeliveryId: `${input.taskId}:authorization:${input.request.event.type}:${data.turnId}:${data.stepIndex}:${data.sequence}:${eventId}`,
+ taskDeliveryId: `${input.taskId}:authorization:${input.request.event.type}:${data.turnId}:${data.stepIndex}:${data.sequence}:${taskAuthorizationRequestId(input.request.event)}`,
};
try {
await resumeHook(input.token, command);
} catch (error) {
- if (isGoneParentTarget(error)) return;
+ if (isTaskWorkflowTargetGone(error)) return;
throw error;
}
}
@@ -103,10 +92,10 @@ export async function wakeTaskParentStep(input: {
}): Promise<void> {
"use step";
- const payload: { message: string; task?: { snapshots: readonly TaskView[] } } = {
+ const payload: { message: string; task?: { views: readonly TaskView[] } } = {
message: formatTaskNotification(input.view),
};
- if (isTerminalTaskStatus(input.view.status)) payload.task = { snapshots: [input.view] };
+ if (isTerminalTaskStatus(input.view.status)) payload.task = { views: [input.view] };
const command: SessionCommand = {
kind: "send",
payload,
@@ -115,7 +104,7 @@ export async function wakeTaskParentStep(input: {
try {
await resumeHook(input.token, command);
} catch (error) {
- if (isGoneParentTarget(error)) {
+ if (isTaskWorkflowTargetGone(error)) {
log.warn("task wake target is gone; the parent session already ended", {
status: input.view.status,
taskId: input.view.taskId,
@@ -151,7 +140,7 @@ export async function wakeTaskInputRequestParentStep(input: {
try {
await resumeHook(input.token, command);
} catch (error) {
- if (isGoneParentTarget(error)) return;
+ if (isTaskWorkflowTargetGone(error)) return;
throw error;
}
}
@@ -160,7 +149,7 @@ export async function wakeTaskInputRequestParentStep(input: {
* Forwards answered input to the blocked child.
*
* The task run performs this itself so the child unblocks and the
- * snapshot leaves `input_required` under one durable decision. Returns
+ * view leaves `input_required` under one durable decision. Returns
* `unreachable` when the child hook is already gone, which leaves the
* outstanding batch untouched rather than reporting a task as working
* when nothing received the answer.
@@ -198,7 +187,7 @@ export async function deliverTaskInputResponsesStep(input: {
}
return "delivered";
} catch (error) {
- if (isGoneParentTarget(error)) {
+ if (isTaskWorkflowTargetGone(error)) {
log.warn("task input answer target is gone; the child turn already ended", {
taskId: input.answer.taskId,
});
@@ -215,17 +204,3 @@ function formatTaskNotification(view: TaskView): string {
}
return `${subject} is ${view.status}. Use task_peek to read its output.`;
}
-
-function isGoneParentTarget(error: unknown): boolean {
- for (const candidate of walkCauseChain(error)) {
- if (
- HookNotFoundError.is(candidate) ||
- WorkflowRunNotFoundError.is(candidate) ||
- RunExpiredError.is(candidate) ||
- EntityConflictError.is(candidate)
- ) {
- return true;
- }
- }
- return false;
-}
diff --git a/packages/eve/src/execution/tasks/run-task-workflow.test.ts b/packages/eve/src/execution/tasks/child/workflow.test.ts
similarity index 71%
rename from packages/eve/src/execution/tasks/run-task-workflow.test.ts
rename to packages/eve/src/execution/tasks/child/workflow.test.ts
index 280284ad1..1db95602d 100644
--- a/packages/eve/src/execution/tasks/run-task-workflow.test.ts
+++ b/packages/eve/src/execution/tasks/child/workflow.test.ts
@@ -1,15 +1,16 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { createHook, type Hook } from "#compiled/@workflow/core/index.js";
+import type { SubagentAuthorizationEventHookPayload } from "#channel/types.js";
import { claimHookOwnership, disposeHook } from "#execution/hook-ownership.js";
import {
- appendTaskSnapshotStep,
+ appendTaskViewStep,
deliverTaskInputResponsesStep,
wakeTaskAuthorizationParentStep,
wakeTaskInputRequestParentStep,
wakeTaskParentStep,
-} from "#execution/tasks/run-task.js";
-import { taskRunWorkflow } from "#execution/tasks/run-task-workflow.js";
+} from "#execution/tasks/child/steps.js";
+import { taskRunWorkflow } from "#execution/tasks/child/workflow.js";
import type {
TaskCommandHookPayload,
TaskInboundAnswerInput,
@@ -21,14 +22,14 @@ vi.mock("#compiled/@workflow/core/index.js", () => ({
createHook: vi.fn(),
}));
-vi.mock("../hook-ownership.js", async (importOriginal) => ({
- ...(await importOriginal<typeof import("../hook-ownership.js")>()),
+vi.mock("#execution/hook-ownership.js", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("#execution/hook-ownership.js")>()),
claimHookOwnership: vi.fn(),
disposeHook: vi.fn(),
}));
-vi.mock("./run-task.js", () => ({
- appendTaskSnapshotStep: vi.fn(),
+vi.mock("#execution/tasks/child/steps.js", () => ({
+ appendTaskViewStep: vi.fn(),
deliverTaskInputResponsesStep: vi.fn(),
wakeTaskAuthorizationParentStep: vi.fn(),
wakeTaskInputRequestParentStep: vi.fn(),
@@ -52,7 +53,9 @@ function createWorkingView(): TaskView {
};
}
-function mockCommandHook(payloads: readonly TaskRunInboundPayload[]): void {
+function mockCommandHook(
+ payloads: readonly (TaskRunInboundPayload | SubagentAuthorizationEventHookPayload)[],
+): void {
const queue = [...payloads];
const hook = {
[Symbol.asyncIterator]: () => ({
@@ -62,17 +65,18 @@ function mockCommandHook(payloads: readonly TaskRunInboundPayload[]): void {
: { done: true as const, value: undefined },
}),
token: "task-token",
- } as Hook<TaskRunInboundPayload>;
+ } as Hook<TaskRunInboundPayload | SubagentAuthorizationEventHookPayload>;
vi.mocked(createHook).mockReturnValue(hook);
}
function appendedStatuses(): readonly string[] {
- return vi.mocked(appendTaskSnapshotStep).mock.calls.map(([input]) => input.view.status);
+ return vi.mocked(appendTaskViewStep).mock.calls.map(([input]) => input.view.status);
}
describe("taskRunWorkflow", () => {
- it("publishes the initial snapshot, applies commands, and stops at terminal", async () => {
+ it("publishes the initial view, applies commands, and stops at terminal", async () => {
mockCommandHook([
+ { command: { kind: "ready" }, kind: "task-command" },
{
command: {
inputRequests: [{ question: "which?", requestId: "req-1" }],
@@ -87,23 +91,29 @@ describe("taskRunWorkflow", () => {
]);
await taskRunWorkflow({
- continuationToken: "task-token",
+ taskInboxToken: "task-token",
initialView: createWorkingView(),
parentContinuationToken: "parent-session-token",
});
- expect(appendedStatuses()).toEqual(["working", "input_required", "working", "completed"]);
+ expect(appendedStatuses()).toEqual([
+ "working",
+ "working",
+ "input_required",
+ "working",
+ "completed",
+ ]);
expect(disposeHook).toHaveBeenCalledTimes(1);
});
- it("skips snapshots for rejected and noop commands", async () => {
+ it("skips views for rejected and noop commands", async () => {
mockCommandHook([
{ command: { kind: "answered", requestIds: ["req-1"] }, kind: "task-command" }, // noop on working
{ command: { kind: "cancel" }, kind: "task-command" },
]);
await taskRunWorkflow({
- continuationToken: "task-token",
+ taskInboxToken: "task-token",
initialView: createWorkingView(),
parentContinuationToken: "parent-session-token",
});
@@ -118,12 +128,12 @@ describe("taskRunWorkflow", () => {
);
await taskRunWorkflow({
- continuationToken: "task-token",
+ taskInboxToken: "task-token",
initialView: createWorkingView(),
parentContinuationToken: "parent-session-token",
});
- expect(appendTaskSnapshotStep).not.toHaveBeenCalled();
+ expect(appendTaskViewStep).not.toHaveBeenCalled();
expect(disposeHook).not.toHaveBeenCalled();
});
@@ -133,7 +143,7 @@ describe("taskRunWorkflow", () => {
]);
await taskRunWorkflow({
- continuationToken: "task-token",
+ taskInboxToken: "task-token",
initialView: createWorkingView(),
parentContinuationToken: "parent-session-token",
});
@@ -145,6 +155,7 @@ describe("taskRunWorkflow", () => {
it("translates a settled child turn from the wire and wakes the parent once ready", async () => {
const ZERO = { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 0, outputTokens: 0 };
mockCommandHook([
+ { command: { kind: "ready" }, kind: "task-command" },
{
kind: "runtime-action-result",
results: [
@@ -161,7 +172,7 @@ describe("taskRunWorkflow", () => {
]);
await taskRunWorkflow({
- continuationToken: "task-token",
+ taskInboxToken: "task-token",
initialView: {
...createWorkingView(),
metadata: {
@@ -174,7 +185,7 @@ describe("taskRunWorkflow", () => {
parentContinuationToken: "parent-session-token",
});
- expect(appendedStatuses()).toEqual(["working", "completed"]);
+ expect(appendedStatuses()).toEqual(["working", "working", "completed"]);
expect(wakeTaskParentStep).toHaveBeenCalledTimes(1);
expect(vi.mocked(wakeTaskParentStep).mock.calls[0]?.[0]).toMatchObject({
token: "parent-session-token",
@@ -200,12 +211,32 @@ describe("taskRunWorkflow", () => {
]);
await taskRunWorkflow({
- continuationToken: "task-token",
+ taskInboxToken: "task-token",
initialView: createWorkingView(),
parentContinuationToken: "parent-session-token",
});
expect(appendedStatuses()).toEqual(["working", "completed"]);
+ expect(wakeTaskParentStep).toHaveBeenCalledTimes(1);
+ expect(disposeHook).toHaveBeenCalledTimes(1);
+ });
+
+ it("silently terminates a dispatch rejected before parent indexing", async () => {
+ mockCommandHook([
+ {
+ command: { data: { code: "START_FAILED" }, kind: "reject-dispatch" },
+ kind: "task-command",
+ },
+ ]);
+
+ await taskRunWorkflow({
+ taskInboxToken: "task-token",
+ initialView: createWorkingView(),
+ parentContinuationToken: "parent-session-token",
+ });
+
+ expect(appendedStatuses()).toEqual(["working", "failed"]);
+ expect(wakeTaskParentStep).not.toHaveBeenCalled();
expect(disposeHook).toHaveBeenCalledTimes(1);
});
@@ -235,7 +266,7 @@ describe("taskRunWorkflow", () => {
]);
await taskRunWorkflow({
- continuationToken: "task-token",
+ taskInboxToken: "task-token",
initialView: createWorkingView(),
parentContinuationToken: "parent-session-token",
});
@@ -244,13 +275,14 @@ describe("taskRunWorkflow", () => {
expect(wakeTaskParentStep).not.toHaveBeenCalled();
});
- it("holds a fast authorization event until the readiness barrier", async () => {
+ it("normalizes and holds a local authorization event until the readiness barrier", async () => {
mockCommandHook([
{
callId: "call-task",
childSessionId: "child-session",
event: {
data: {
+ attemptId: "github-1",
description: "Authorize GitHub",
name: "github",
sequence: 1,
@@ -259,27 +291,105 @@ describe("taskRunWorkflow", () => {
},
type: "authorization.required",
},
- kind: "authorization-event",
+ kind: "subagent-authorization-event",
+ subagentName: "research",
+ },
+ {
+ callId: "call-task",
+ childSessionId: "child-session",
+ event: {
+ data: {
+ attemptId: "linear-1",
+ description: "Authorize Linear",
+ name: "linear",
+ sequence: 1,
+ stepIndex: 2,
+ turnId: "turn-child",
+ },
+ type: "authorization.required",
+ },
+ kind: "subagent-authorization-event",
subagentName: "research",
},
{ command: { kind: "ready" }, kind: "task-command" },
]);
await taskRunWorkflow({
- continuationToken: "task-token",
+ taskInboxToken: "task-token",
initialView: createWorkingView(),
parentContinuationToken: "parent-session-token",
});
- expect(appendedStatuses()).toEqual(["working", "input_required", "input_required"]);
- expect(wakeTaskAuthorizationParentStep).toHaveBeenCalledTimes(1);
+ expect(appendedStatuses()).toEqual([
+ "working",
+ "input_required",
+ "input_required",
+ "input_required",
+ ]);
+ expect(wakeTaskAuthorizationParentStep).toHaveBeenCalledTimes(2);
+ expect(wakeTaskAuthorizationParentStep).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({
+ request: expect.objectContaining({
+ event: expect.objectContaining({
+ data: expect.objectContaining({ name: "github" }),
+ }),
+ }),
+ }),
+ );
+ expect(wakeTaskAuthorizationParentStep).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({
+ request: expect.objectContaining({
+ event: expect.objectContaining({
+ data: expect.objectContaining({ name: "linear" }),
+ }),
+ }),
+ }),
+ );
expect(vi.mocked(wakeTaskAuthorizationParentStep).mock.invocationCallOrder[0]).toBeGreaterThan(
- vi.mocked(appendTaskSnapshotStep).mock.invocationCallOrder[2] ?? 0,
+ vi.mocked(appendTaskViewStep).mock.invocationCallOrder[2] ?? 0,
+ );
+ });
+
+ it("ignores approval lifecycle events and still wakes on terminal settlement", async () => {
+ mockCommandHook([
+ { command: { kind: "ready" }, kind: "task-command" },
+ {
+ callId: "call-task",
+ childSessionId: "child-session-1",
+ event: {
+ data: {
+ outcome: "approved",
+ requestId: "stale-1",
+ responderPrincipalId: "user-1",
+ sequence: 1,
+ stepIndex: 2,
+ turnId: "turn-child",
+ },
+ type: "approval.settled",
+ },
+ kind: "subagent-authorization-event",
+ subagentName: "research",
+ },
+ { command: { data: "done", kind: "complete" }, kind: "task-command" },
+ ]);
+
+ await taskRunWorkflow({
+ taskInboxToken: "task-token",
+ initialView: createWorkingView(),
+ parentContinuationToken: "parent-session-token",
+ });
+
+ expect(wakeTaskAuthorizationParentStep).not.toHaveBeenCalled();
+ expect(wakeTaskParentStep).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ view: expect.objectContaining({ status: "completed" }) }),
);
});
it("never wakes twice for one blocked child", async () => {
mockCommandHook([
+ { command: { kind: "ready" }, kind: "task-command" },
{
command: { inputRequests: [{ q: 1, requestId: "q1" }], kind: "require-input" },
kind: "task-command",
@@ -292,7 +402,7 @@ describe("taskRunWorkflow", () => {
]);
await taskRunWorkflow({
- continuationToken: "task-token",
+ taskInboxToken: "task-token",
initialView: createWorkingView(),
parentContinuationToken: "parent-session-token",
});
@@ -331,7 +441,7 @@ describe("taskRunWorkflow", () => {
]);
await taskRunWorkflow({
- continuationToken: "task-token",
+ taskInboxToken: "task-token",
initialView: createWorkingView(),
parentContinuationToken: "parent-session-token",
});
@@ -350,8 +460,7 @@ describe("taskRunWorkflow", () => {
);
const firstInputWakeOrder =
vi.mocked(wakeTaskInputRequestParentStep).mock.invocationCallOrder[0] ?? 0;
- const firstInputAppendOrder =
- vi.mocked(appendTaskSnapshotStep).mock.invocationCallOrder[2] ?? 0;
+ const firstInputAppendOrder = vi.mocked(appendTaskViewStep).mock.invocationCallOrder[2] ?? 0;
expect(firstInputAppendOrder).toBeLessThan(firstInputWakeOrder);
});
});
@@ -385,7 +494,7 @@ describe("taskRunWorkflow answered input", () => {
]);
await taskRunWorkflow({
- continuationToken: "task-token",
+ taskInboxToken: "task-token",
initialView: createWorkingView(),
parentContinuationToken: "parent-session-token",
});
@@ -396,7 +505,7 @@ describe("taskRunWorkflow answered input", () => {
});
expect(appendedStatuses()).toEqual(["working", "input_required", "working", "completed"]);
const deliveryOrder = vi.mocked(deliverTaskInputResponsesStep).mock.invocationCallOrder[0] ?? 0;
- const unblockOrder = vi.mocked(appendTaskSnapshotStep).mock.invocationCallOrder[2] ?? 0;
+ const unblockOrder = vi.mocked(appendTaskViewStep).mock.invocationCallOrder[2] ?? 0;
expect(deliveryOrder).toBeLessThan(unblockOrder);
});
@@ -410,7 +519,7 @@ describe("taskRunWorkflow answered input", () => {
]);
await taskRunWorkflow({
- continuationToken: "task-token",
+ taskInboxToken: "task-token",
initialView: createWorkingView(),
parentContinuationToken: "parent-session-token",
});
@@ -433,7 +542,7 @@ describe("taskRunWorkflow answered input", () => {
]);
await taskRunWorkflow({
- continuationToken: "task-token",
+ taskInboxToken: "task-token",
initialView: createWorkingView(),
parentContinuationToken: "parent-session-token",
});
@@ -442,7 +551,7 @@ describe("taskRunWorkflow answered input", () => {
answer: answer("q1", "unknown"),
requestIds: ["q1"],
});
- const blockedAgain = vi.mocked(appendTaskSnapshotStep).mock.calls[2]?.[0].view;
+ const blockedAgain = vi.mocked(appendTaskViewStep).mock.calls[2]?.[0].view;
expect(blockedAgain?.status).toBe("input_required");
expect(blockedAgain?.inputRequests).toEqual([{ prompt: "q2", requestId: "q2" }]);
});
@@ -456,7 +565,7 @@ describe("taskRunWorkflow answered input", () => {
]);
await taskRunWorkflow({
- continuationToken: "task-token",
+ taskInboxToken: "task-token",
initialView: createWorkingView(),
parentContinuationToken: "parent-session-token",
});
@@ -473,7 +582,7 @@ describe("taskRunWorkflow answered input", () => {
]);
await taskRunWorkflow({
- continuationToken: "task-token",
+ taskInboxToken: "task-token",
initialView: createWorkingView(),
parentContinuationToken: "parent-session-token",
});
diff --git a/packages/eve/src/execution/tasks/run-task-workflow.ts b/packages/eve/src/execution/tasks/child/workflow.ts
similarity index 71%
rename from packages/eve/src/execution/tasks/run-task-workflow.ts
rename to packages/eve/src/execution/tasks/child/workflow.ts
index 6cf94e9c9..30afb0f9a 100644
--- a/packages/eve/src/execution/tasks/run-task-workflow.ts
+++ b/packages/eve/src/execution/tasks/child/workflow.ts
@@ -1,13 +1,14 @@
import { createHook } from "#compiled/@workflow/core/index.js";
+import type { SubagentAuthorizationEventHookPayload } from "#channel/types.js";
import { claimHookOwnership, disposeHook, isHookConflictError } from "#execution/hook-ownership.js";
import {
- appendTaskSnapshotStep,
+ appendTaskViewStep,
deliverTaskInputResponsesStep,
wakeTaskAuthorizationParentStep,
wakeTaskInputRequestParentStep,
wakeTaskParentStep,
-} from "#execution/tasks/run-task.js";
+} from "#execution/tasks/child/steps.js";
import { applyTaskTransition } from "#tasks/transitions.js";
import { translateTaskInboundPayload } from "#tasks/wire.js";
import {
@@ -25,14 +26,16 @@ import {
/** Input for one durable task run. */
export interface TaskRunWorkflowInput {
- /** Private continuation token; a routing credential, never model-visible. */
- readonly continuationToken: string;
- /** The creation snapshot, normally `working`. */
+ /** Private task inbox token; a routing credential, never model-visible. */
+ readonly taskInboxToken: string;
+ /** The creation view, normally `working`. */
readonly initialView: TaskView;
/** Parent session delivery token used to wake the task's owning parent. */
readonly parentContinuationToken: string;
}
+type TaskRunHookPayload = TaskRunInboundPayload | SubagentAuthorizationEventHookPayload;
+
function isTaskRunFinished(view: TaskView, dispatchAcknowledged: boolean): boolean {
if (!isTerminalTaskStatus(view.status) || !dispatchAcknowledged) return false;
@@ -46,7 +49,7 @@ function isTaskRunFinished(view: TaskView, dispatchAcknowledged: boolean): boole
*
* Consumes commands and child wire payloads over its private hook,
* applies the pure transition function, and appends a full `TaskView`
- * snapshot per accepted command to its `eve.task` run stream. Competing
+ * per accepted command to its `eve.task` run stream. Competing
* completion, cancellation, and input transitions serialize here;
* rejected commands (for example a late child result after `cancelled`)
* change nothing.
@@ -56,7 +59,7 @@ function isTaskRunFinished(view: TaskView, dispatchAcknowledged: boolean): boole
* session. A parked parent starts a turn; an active turn observes the
* delivery at its next safe boundary. Nothing else wakes the parent.
*
- * The run ends when the task reaches a terminal status. Its snapshot
+ * The run ends when the task reaches a terminal status. Its view
* stream stays readable, so terminal tasks remain peekable; the
* disposed hook makes any later command fail loudly instead of queueing
* against a finished task.
@@ -64,7 +67,7 @@ function isTaskRunFinished(view: TaskView, dispatchAcknowledged: boolean): boole
export async function taskRunWorkflow(input: TaskRunWorkflowInput): Promise<void> {
"use workflow";
- const commands = createHook<TaskRunInboundPayload>({ token: input.continuationToken });
+ const commands = createHook<TaskRunHookPayload>({ token: input.taskInboxToken });
// The iterator shares the hook's durable cursor; create it before
// claiming so conflict replay is consumed by getConflict(), not a
// later iterator read.
@@ -85,21 +88,39 @@ export async function taskRunWorkflow(input: TaskRunWorkflowInput): Promise<void
let view = input.initialView;
let pendingInputRequest: TaskInboundInputRequest | undefined;
- let pendingAuthorizationEvent: TaskInboundAuthorizationEvent | undefined;
+ let pendingAuthorizationEvents: TaskInboundAuthorizationEvent[] = [];
let dispatchAcknowledged = false;
- await appendTaskSnapshotStep({ view });
+ await appendTaskViewStep({ view });
while (!isTaskRunFinished(view, dispatchAcknowledged)) {
const next = await iterator.next();
if (next.done === true) return;
- if (next.value.kind === "task-command") dispatchAcknowledged = true;
- if (next.value.kind === "subagent-input-request") {
- pendingInputRequest = next.value;
+ const payload: TaskRunInboundPayload =
+ next.value.kind === "subagent-authorization-event"
+ ? { ...next.value, kind: "authorization-event" }
+ : next.value;
+ // Approval lifecycle events (`approval.candidate`/`approval.settled`)
+ // are intra-child responder bookkeeping, not task blockers: only
+ // `authorization.required`/`authorization.completed` may block or
+ // unblock a task. Forwarding them would mint bogus `answered`
+ // commands and race the terminal wake.
+ if (
+ payload.kind === "authorization-event" &&
+ (payload.event.type === "approval.candidate" || payload.event.type === "approval.settled")
+ ) {
+ continue;
+ }
+ const isReadinessCommand =
+ payload.kind === "task-command" && payload.command.kind === "ready";
+ const isRejectedDispatch =
+ payload.kind === "task-command" && payload.command.kind === "reject-dispatch";
+ if (isReadinessCommand || isRejectedDispatch) dispatchAcknowledged = true;
+ if (payload.kind === "subagent-input-request") {
+ pendingInputRequest = payload;
}
- if (next.value.kind === "authorization-event") {
- pendingAuthorizationEvent = next.value;
+ if (payload.kind === "authorization-event") {
+ pendingAuthorizationEvents.push(payload);
}
- const payload = next.value;
const isExecutorResultAfterCancellation =
view.status === "cancelled" && payload.kind === "runtime-action-result";
const isTaskInputAnswer = payload.kind === "input-response";
@@ -117,21 +138,27 @@ export async function taskRunWorkflow(input: TaskRunWorkflowInput): Promise<void
command = translateTaskInboundPayload(payload);
}
if (command === undefined) continue;
+ if (isReadinessCommand && isTerminalTaskStatus(view.status)) {
+ await wakeTaskParentStep({ token: input.parentContinuationToken, view });
+ continue;
+ }
const result = applyTaskTransition(view, command);
if (result.outcome !== "accepted") continue;
const becameTerminal =
!isTerminalTaskStatus(view.status) && isTerminalTaskStatus(result.view.status);
const becameReady = !isReadyTaskStatus(view.status) && isReadyTaskStatus(result.view.status);
view = result.view;
- await appendTaskSnapshotStep({ view });
- if (pendingAuthorizationEvent !== undefined && dispatchAcknowledged) {
+ await appendTaskViewStep({ view });
+ const routableAuthorizationEvents =
+ dispatchAcknowledged && !becameTerminal ? pendingAuthorizationEvents : [];
+ for (const request of routableAuthorizationEvents) {
await wakeTaskAuthorizationParentStep({
- request: pendingAuthorizationEvent,
+ request,
taskId: view.taskId,
token: input.parentContinuationToken,
});
- pendingAuthorizationEvent = undefined;
}
+ if (becameTerminal || routableAuthorizationEvents.length > 0) pendingAuthorizationEvents = [];
const routableInputRequest =
pendingInputRequest !== undefined &&
dispatchAcknowledged &&
@@ -143,7 +170,12 @@ export async function taskRunWorkflow(input: TaskRunWorkflowInput): Promise<void
token: input.parentContinuationToken,
});
pendingInputRequest = undefined;
- } else if (becameTerminal || (becameReady && pendingInputRequest === undefined)) {
+ } else if (
+ !isRejectedDispatch &&
+ routableAuthorizationEvents.length === 0 &&
+ dispatchAcknowledged &&
+ (becameTerminal || (becameReady && pendingInputRequest === undefined))
+ ) {
await wakeTaskParentStep({ token: input.parentContinuationToken, view });
}
// An unrouted request cannot outlive the block it described, or a
diff --git a/packages/eve/src/execution/tasks/parent/agent-identity.ts b/packages/eve/src/execution/tasks/parent/agent-identity.ts
new file mode 100644
index 000000000..47c826b91
--- /dev/null
+++ b/packages/eve/src/execution/tasks/parent/agent-identity.ts
@@ -0,0 +1,33 @@
+import { mintStartOperation } from "#execution/dispatch-start-operation.js";
+import type { RuntimeAgentHandleAction } from "#execution/agent-handle-dispatch.js";
+
+/** Resolves the persistent agent identity attached to one delegated task. */
+export function describeTaskAgent(input: {
+ readonly action: RuntimeAgentHandleAction;
+ readonly agentId?: string;
+ readonly parentSessionId: string;
+ readonly parentTurnId: string;
+}): {
+ readonly agentId: string;
+ readonly callId: string;
+ readonly mode: "local" | "remote";
+ readonly name: string;
+} {
+ const { action } = input;
+ const name = action.kind === "remote-agent-call" ? action.remoteAgentName : action.subagentName;
+ const agentId =
+ input.agentId ??
+ mintStartOperation({
+ callId: action.callId,
+ name,
+ nodeId: action.nodeId,
+ parentSessionId: input.parentSessionId,
+ parentTurnId: input.parentTurnId,
+ }).identity.id;
+ return {
+ agentId,
+ callId: action.callId,
+ mode: action.kind === "remote-agent-call" ? "remote" : "local",
+ name,
+ };
+}
diff --git a/packages/eve/src/execution/tasks/parent/agent-views.test.ts b/packages/eve/src/execution/tasks/parent/agent-views.test.ts
new file mode 100644
index 000000000..f88d01295
--- /dev/null
+++ b/packages/eve/src/execution/tasks/parent/agent-views.test.ts
@@ -0,0 +1,129 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import {
+ appendTaskAgentAnnouncement,
+ readTaskAgentViews,
+} from "#execution/tasks/parent/agent-views.js";
+import { findActiveTaskForAgent } from "#execution/tasks/parent/control-shared.js";
+import { readLatestTaskView } from "#execution/tasks/parent/run-parent.js";
+import { AGENT_HANDLES_STATE_KEY } from "#harness/handles/store.js";
+import type { HarnessSession } from "#harness/types.js";
+import { SESSION_TASKS_STATE_KEY } from "#tasks/session-index.js";
+import type { TaskStatus, TaskView } from "#tasks/types.js";
+
+vi.mock("#execution/tasks/parent/run-parent.js", () => ({
+ readLatestTaskView: vi.fn(),
+}));
+
+const metadata = {
+ agentId: "ag_research:abcdef123456",
+ kind: "subagent" as const,
+ mode: "local" as const,
+ name: "research",
+};
+
+function createSession(taskRunIds: readonly string[]): HarnessSession {
+ return {
+ agent: { modelReference: { id: "model" }, system: "", tools: [] },
+ compaction: { recentWindowSize: 4, threshold: 1_000_000 },
+ continuationToken: "parent-token",
+ history: [],
+ sessionId: "parent-session",
+ state: {
+ [AGENT_HANDLES_STATE_KEY]: {
+ handles: [
+ {
+ address: {
+ continuationToken: "child-token",
+ kind: "agent/local",
+ sessionId: "child-session",
+ },
+ identity: { id: metadata.agentId, name: metadata.name, nodeId: "node-research" },
+ phase: "addressed",
+ },
+ ],
+ },
+ [SESSION_TASKS_STATE_KEY]: {
+ tasks: taskRunIds.map((taskRunId, index) => ({
+ taskInboxToken: `task-token-${index}`,
+ createdByTurnId: `turn-${index}`,
+ metadata,
+ operationId: `operation-${index}`,
+ taskId: `task_${index}`,
+ taskRunId,
+ })),
+ },
+ },
+ };
+}
+
+function task(taskId: string, status: TaskStatus): TaskView {
+ // Cast on purpose: mock views omit the per-status payload fields the
+ // TaskView union requires (e.g. lastOutput on completed).
+ return { metadata, status, taskId } as TaskView;
+}
+
+describe("task-derived agent availability", () => {
+ beforeEach(() => vi.resetAllMocks());
+
+ it("renders a nonterminal task as busy and a terminal task as available", async () => {
+ vi.mocked(readLatestTaskView)
+ .mockResolvedValueOnce(task("task_0", "working"))
+ .mockResolvedValueOnce(task("task_0", "completed"));
+ const session = createSession(["run-0"]);
+
+ await expect(readTaskAgentViews(session)).resolves.toEqual([
+ {
+ availability: "busy",
+ id: metadata.agentId,
+ name: metadata.name,
+ statusLine: undefined,
+ taskId: "task_0",
+ taskStatus: "working",
+ },
+ ]);
+ await expect(readTaskAgentViews(session)).resolves.toEqual([
+ {
+ availability: "available",
+ id: metadata.agentId,
+ name: metadata.name,
+ statusLine: undefined,
+ },
+ ]);
+ });
+
+ it("finds the active task used for the continuation availability check", async () => {
+ vi.mocked(readLatestTaskView).mockResolvedValue(task("task_0", "input_required"));
+
+ await expect(
+ findActiveTaskForAgent(createSession(["run-0"]), metadata.agentId),
+ ).resolves.toMatchObject({
+ view: { status: "input_required", taskId: "task_0" },
+ });
+ });
+
+ it("appends the busy projection without exposing routing coordinates", async () => {
+ vi.mocked(readLatestTaskView).mockResolvedValue(task("task_0", "working"));
+
+ const next = await appendTaskAgentAnnouncement(createSession(["run-0"]));
+ const message = next.history.at(-1);
+ const announcement = message?.content;
+
+ expect(message?.role).toBe("user");
+ expect(announcement).toContain('availability="busy"');
+ expect(announcement).toContain('taskId="task_0"');
+ expect(announcement).not.toContain("child-token");
+ expect(announcement).not.toContain("child-session");
+ await expect(appendTaskAgentAnnouncement(next)).resolves.toBe(next);
+ });
+
+ it("rejects two nonterminal tasks bound to one child agent", async () => {
+ vi.mocked(readLatestTaskView)
+ .mockResolvedValueOnce(task("task_0", "working"))
+ .mockResolvedValueOnce(task("task_1", "input_required"));
+
+ await expect(readTaskAgentViews(createSession(["run-0", "run-1"]))).rejects.toThrow(
+ "more than one nonterminal task",
+ );
+ });
+});
diff --git a/packages/eve/src/execution/tasks/parent/agent-views.ts b/packages/eve/src/execution/tasks/parent/agent-views.ts
new file mode 100644
index 000000000..a21b6719f
--- /dev/null
+++ b/packages/eve/src/execution/tasks/parent/agent-views.ts
@@ -0,0 +1,69 @@
+import type { HarnessSession } from "#harness/types.js";
+import { resolveAgentsAnnouncement, type AgentView } from "#harness/handles/prompt.js";
+import { formatAgentStatus, getAgentHandleStore } from "#harness/handles/store.js";
+import { readTaskViews } from "#execution/tasks/parent/control-shared.js";
+import { getSessionTaskIndex } from "#tasks/session-index.js";
+
+/** Derives model-visible task-agent availability from authoritative task views. */
+export async function readTaskAgentViews(session: HarnessSession): Promise<readonly AgentView[]> {
+ const addresses = (getAgentHandleStore(session.state)?.handles ?? []).filter(
+ (handle) => handle.phase === "addressed",
+ );
+ if (addresses.length === 0) return [];
+
+ const entries = getSessionTaskIndex(session.state);
+ const views = await readTaskViews(entries);
+ const byAgent = new Map<string, typeof views>();
+ for (const view of views) {
+ const current = byAgent.get(view.metadata.agentId) ?? [];
+ byAgent.set(view.metadata.agentId, [...current, view]);
+ }
+
+ return addresses.map((address) => {
+ const agentTasks = byAgent.get(address.identity.id) ?? [];
+ const active = agentTasks.filter(
+ (view) => view.status === "working" || view.status === "input_required",
+ );
+ if (active.length > 1) {
+ throw new Error(`Agent "${address.identity.id}" has more than one nonterminal task.`);
+ }
+ const task = active[0];
+ if (task !== undefined) {
+ const taskStatus = task.status === "input_required" ? "input_required" : "working";
+ return {
+ availability: "busy",
+ id: address.identity.id,
+ name: address.identity.name,
+ taskId: task.taskId,
+ taskStatus,
+ };
+ }
+
+ const latest = agentTasks.at(-1);
+ return {
+ availability: "available",
+ id: address.identity.id,
+ name: address.identity.name,
+ statusLine:
+ latest?.lastOutput === undefined ? undefined : formatAgentStatus(latest.lastOutput.data),
+ };
+ });
+}
+
+/** Appends the changed task-agent projection before the next model call. */
+export async function appendTaskAgentAnnouncement(
+ session: HarnessSession,
+): Promise<HarnessSession> {
+ const agentViews = await readTaskAgentViews(session);
+ const announcement = resolveAgentsAnnouncement({
+ agentViews,
+ messages: session.history,
+ store: getAgentHandleStore(session.state),
+ });
+ return announcement === undefined
+ ? session
+ : {
+ ...session,
+ history: [...session.history, { content: announcement, role: "user" }],
+ };
+}
diff --git a/packages/eve/src/execution/tasks/parent/continuation-dispatch.test.ts b/packages/eve/src/execution/tasks/parent/continuation-dispatch.test.ts
new file mode 100644
index 000000000..fef89ce1f
--- /dev/null
+++ b/packages/eve/src/execution/tasks/parent/continuation-dispatch.test.ts
@@ -0,0 +1,76 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { settleTaskDispatchError } from "#execution/tasks/parent/continuation-dispatch.js";
+import {
+ failDelegatedDispatch,
+ rejectDelegatedDispatch,
+} from "#execution/tasks/parent/delegate.js";
+
+vi.mock("#execution/tasks/parent/delegate.js", () => ({
+ failDelegatedDispatch: vi.fn(),
+ rejectDelegatedDispatch: vi.fn(),
+ settleDelegatedDispatch: vi.fn(),
+}));
+
+const task = {
+ taskInboxToken: "task-token",
+ createdByTurnId: "turn-parent",
+ metadata: {
+ agentId: "agent-1",
+ kind: "subagent" as const,
+ mode: "remote" as const,
+ name: "research",
+ },
+ operationId: "operation-1",
+ taskId: "task_1",
+ taskRunId: "run-1",
+};
+
+function outcome(deliveryAmbiguous: boolean) {
+ return {
+ deliveryAmbiguous,
+ kind: "error" as const,
+ result: {
+ callId: "call-1",
+ isError: true as const,
+ kind: "subagent-result" as const,
+ origin: "dispatch" as const,
+ output: { code: "AGENT_UNREACHABLE", message: "rejected" },
+ subagentName: "research",
+ },
+ session: {} as never,
+ };
+}
+
+describe("settleTaskDispatchError", () => {
+ beforeEach(() => vi.resetAllMocks());
+
+ it("fails an indexed task after a definitive continuation rejection", async () => {
+ const rejected = outcome(false);
+
+ await settleTaskDispatchError({
+ delegated: task,
+ outcome: rejected,
+ persisted: { receipt: {} as never, session: rejected.session },
+ });
+
+ expect(failDelegatedDispatch).toHaveBeenCalledWith({
+ error: rejected.result.output,
+ task,
+ });
+ expect(rejectDelegatedDispatch).not.toHaveBeenCalled();
+ });
+
+ it("leaves an indexed task pending only when delivery was ambiguous", async () => {
+ const ambiguous = outcome(true);
+
+ await settleTaskDispatchError({
+ delegated: task,
+ outcome: ambiguous,
+ persisted: { receipt: {} as never, session: ambiguous.session },
+ });
+
+ expect(failDelegatedDispatch).not.toHaveBeenCalled();
+ expect(rejectDelegatedDispatch).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/eve/src/execution/tasks/parent/continuation-dispatch.ts b/packages/eve/src/execution/tasks/parent/continuation-dispatch.ts
new file mode 100644
index 000000000..0eae970ab
--- /dev/null
+++ b/packages/eve/src/execution/tasks/parent/continuation-dispatch.ts
@@ -0,0 +1,107 @@
+import {
+ createAgentErrorResult,
+ type DispatchOutcome,
+ type RuntimeAgentHandleAction,
+ type RuntimeSession,
+} from "#execution/agent-handle-dispatch.js";
+import {
+ findActiveTaskForAgent,
+ findTaskAgentAddress,
+} from "#execution/tasks/parent/control-shared.js";
+import {
+ failDelegatedDispatch,
+ rejectDelegatedDispatch,
+ settleDelegatedDispatch,
+ type DelegatedTask,
+} from "#execution/tasks/parent/delegate.js";
+import { describeTaskAgent } from "#execution/tasks/parent/agent-identity.js";
+import { AGENT_BUSY } from "#harness/agent-handle-errors.js";
+import type { RuntimeSubagentDispatchFailure } from "#runtime/actions/types.js";
+import type { JsonValue } from "#shared/json.js";
+
+export type PersistedContinuationTask = Awaited<ReturnType<typeof settleDelegatedDispatch>>;
+
+/** Describes task identity from the stored address when continuing an agent. */
+export function describeTaskDispatch(input: {
+ readonly action: RuntimeAgentHandleAction;
+ readonly agentId: string | undefined;
+ readonly parentSessionId: string;
+ readonly parentTurnId: string;
+ readonly session: RuntimeSession;
+}): ReturnType<typeof describeTaskAgent> {
+ const described = describeTaskAgent(input);
+ const handle =
+ input.agentId === undefined ? undefined : findTaskAgentAddress(input.session, input.agentId);
+ return handle === undefined
+ ? described
+ : {
+ ...described,
+ mode: handle.address.kind === "agent/remote" ? "remote" : "local",
+ };
+}
+
+export async function checkTaskContinuationAvailability(input: {
+ readonly action: RuntimeAgentHandleAction;
+ readonly agentId: string;
+ readonly parentStepIndex: number;
+ readonly parentTurnId: string;
+ readonly session: RuntimeSession;
+}): Promise<RuntimeSubagentDispatchFailure | undefined> {
+ const active = await findActiveTaskForAgent(
+ input.session,
+ input.agentId,
+ input.parentTurnId,
+ input.parentStepIndex,
+ );
+ return active === undefined
+ ? undefined
+ : createAgentErrorResult({
+ action: input.action,
+ code: AGENT_BUSY,
+ message: `Agent "${input.agentId}" is busy with task "${active.view.taskId}" (${active.view.status}).`,
+ });
+}
+
+/**
+ * Persists the task's ownership and routing entry in the parent session's
+ * `eve.tasks` index and creates its parked tool-call receipt before dispatch.
+ */
+export async function persistContinuationTaskInParentSession(input: {
+ readonly action: RuntimeAgentHandleAction;
+ readonly agentId: string;
+ readonly delegated: DelegatedTask;
+ readonly session: RuntimeSession;
+}): Promise<PersistedContinuationTask | undefined> {
+ const handle = findTaskAgentAddress(input.session, input.agentId);
+ if (handle === undefined) return undefined;
+ return settleDelegatedDispatch({
+ callId: input.action.callId,
+ session: input.session,
+ subagentName: handle.identity.name,
+ task: input.delegated,
+ });
+}
+
+export async function settleTaskDispatchError(input: {
+ readonly delegated: DelegatedTask;
+ readonly outcome: Extract<DispatchOutcome, { readonly kind: "error" }>;
+ readonly persisted: PersistedContinuationTask | undefined;
+}): Promise<RuntimeSubagentDispatchFailure> {
+ const ambiguous = input.persisted !== undefined && input.outcome.deliveryAmbiguous === true;
+ if (!ambiguous) {
+ const settle = input.persisted === undefined ? rejectDelegatedDispatch : failDelegatedDispatch;
+ await settle({ error: input.outcome.result.output, task: input.delegated });
+ }
+ return input.persisted === undefined
+ ? input.outcome.result
+ : {
+ ...input.outcome.result,
+ output: attachTaskId(input.outcome.result.output, input.delegated.taskId),
+ };
+}
+
+function attachTaskId(output: JsonValue, taskId: string): JsonValue {
+ return output !== null && typeof output === "object" && !Array.isArray(output)
+ ? { ...output, taskId }
+ : { error: output, taskId };
+}
diff --git a/packages/eve/src/execution/tasks/parent/control-shared.ts b/packages/eve/src/execution/tasks/parent/control-shared.ts
new file mode 100644
index 000000000..7eec18eaa
--- /dev/null
+++ b/packages/eve/src/execution/tasks/parent/control-shared.ts
@@ -0,0 +1,140 @@
+import type { RuntimeSession } from "#execution/agent-handle-dispatch.js";
+import { readLatestTaskView } from "#execution/tasks/parent/run-parent.js";
+import { isTaskWorkflowTargetGone } from "#execution/tasks/workflow-target.js";
+import { getAgentHandleStore, type AgentHandle } from "#harness/handles/store.js";
+import type { RuntimeActionResult, RuntimeToolCallActionRequest } from "#runtime/actions/types.js";
+import { taskViewsToJson } from "#tasks/json.js";
+import {
+ findSessionTaskEntry,
+ getSessionTaskIndex,
+ type SessionTaskIndexEntry,
+} from "#tasks/session-index.js";
+import type { TaskView } from "#tasks/types.js";
+
+/**
+ * Result and lookup helpers shared by the task-control executors
+ * (`task_peek`/`task_cancel` in the dispatch module,
+ * `task_send` in its own).
+ */
+
+/** Resolves owned index entries, or the ids this session does not own. */
+export function lookupTaskEntries(
+ session: RuntimeSession,
+ taskIds: readonly string[],
+):
+ | { readonly entries: SessionTaskIndexEntry[]; readonly kind: "found" }
+ | { readonly kind: "unknown"; readonly unknown: string[] } {
+ const entries: SessionTaskIndexEntry[] = [];
+ const unknown: string[] = [];
+ for (const taskId of taskIds) {
+ const entry = findSessionTaskEntry(session.state, taskId);
+ if (entry === undefined) {
+ unknown.push(taskId);
+ } else {
+ entries.push(entry);
+ }
+ }
+ return unknown.length > 0 ? { kind: "unknown", unknown } : { entries, kind: "found" };
+}
+
+/** Reads the latest view of every entry, defaulting to `working`. */
+export async function readTaskViews(
+ entries: readonly SessionTaskIndexEntry[],
+): Promise<TaskView[]> {
+ return Promise.all(entries.map(readTaskView));
+}
+
+export async function readTaskView(entry: SessionTaskIndexEntry): Promise<TaskView> {
+ try {
+ return (
+ (await readLatestTaskView({ taskRunId: entry.taskRunId })) ?? createPendingTaskView(entry)
+ );
+ } catch (error) {
+ if (isTaskWorkflowTargetGone(error) && entry.terminalView !== undefined) {
+ return entry.terminalView;
+ }
+ throw error;
+ }
+}
+
+/** The placeholder view for a run that has not published anything yet. */
+function createPendingTaskView(entry: SessionTaskIndexEntry): TaskView {
+ return {
+ metadata: entry.metadata,
+ status: "working",
+ taskId: entry.taskId,
+ };
+}
+
+/** Finds the persistent address record for one task-owned agent. */
+export function findTaskAgentAddress(
+ session: RuntimeSession,
+ agentId: string,
+): Extract<AgentHandle, { phase: "addressed" }> | undefined {
+ const handles = getAgentHandleStore(session.state)?.handles ?? [];
+ return handles.find(
+ (candidate): candidate is Extract<AgentHandle, { phase: "addressed" }> =>
+ candidate.phase === "addressed" && candidate.identity.id === agentId,
+ );
+}
+
+/** Returns the one nonterminal task owning an agent, if any. */
+export async function findActiveTaskForAgent(
+ session: RuntimeSession,
+ agentId: string,
+ parentTurnId?: string,
+ parentStepIndex?: number,
+): Promise<{ readonly entry: SessionTaskIndexEntry; readonly view: TaskView } | undefined> {
+ const entries = getSessionTaskIndex(session.state).filter(
+ (entry) => entry.metadata.agentId === agentId,
+ );
+ const views = await readTaskViews(entries);
+ const active = entries.flatMap((entry, index) => {
+ const view = views[index];
+ return view !== undefined &&
+ ((entry.createdByTurnId === parentTurnId && entry.createdByStepIndex === parentStepIndex) ||
+ view.status === "working" ||
+ view.status === "input_required")
+ ? [{ entry, view }]
+ : [];
+ });
+ return active[0];
+}
+
+/** One successful task-control result carrying full task views. */
+export function createTaskViewsResult(
+ action: RuntimeToolCallActionRequest,
+ views: readonly TaskView[],
+): RuntimeActionResult {
+ return {
+ callId: action.callId,
+ kind: "tool-result",
+ output: taskViewsToJson(views),
+ toolName: action.toolName,
+ };
+}
+
+/** One task-control error the model can act on. */
+export function createTaskControlError(
+ action: RuntimeToolCallActionRequest,
+ message: string,
+): RuntimeActionResult {
+ return {
+ callId: action.callId,
+ isError: true,
+ kind: "tool-result",
+ output: { message },
+ toolName: action.toolName,
+ };
+}
+
+/** The ownership error for ids outside this session's task index. */
+export function createUnknownTasksError(
+ action: RuntimeToolCallActionRequest,
+ unknown: readonly string[],
+): RuntimeActionResult {
+ return createTaskControlError(
+ action,
+ `Unknown task ids: ${unknown.join(", ")}. Tasks belong to the session that created them.`,
+ );
+}
diff --git a/packages/eve/src/execution/tasks/parent/delegate.test.ts b/packages/eve/src/execution/tasks/parent/delegate.test.ts
new file mode 100644
index 000000000..2cba8f0fb
--- /dev/null
+++ b/packages/eve/src/execution/tasks/parent/delegate.test.ts
@@ -0,0 +1,63 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { RuntimeSession } from "#execution/agent-handle-dispatch.js";
+import {
+ acknowledgeDelegatedTasksStep,
+ settleDelegatedDispatch,
+ type DelegatedTask,
+} from "#execution/tasks/parent/delegate.js";
+import { sendTaskCommandToOwner } from "#execution/tasks/parent/run-parent.js";
+import { getSessionTaskIndex } from "#tasks/session-index.js";
+
+vi.mock("#execution/tasks/parent/run-parent.js", () => ({
+ readLatestTaskView: vi.fn(),
+ sendTaskCommandToOwner: vi.fn(),
+}));
+
+describe("delegated task settlement", () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ vi.mocked(sendTaskCommandToOwner).mockResolvedValue({ runId: "run-owner" });
+ });
+
+ it("indexes the resolved command-hook owner before readiness", async () => {
+ const session = {
+ agent: { modelReference: { id: "model" }, system: "", tools: [] },
+ compaction: { recentWindowSize: 4, threshold: 1_000_000 },
+ continuationToken: "parent-token",
+ history: [],
+ sessionId: "parent-session",
+ } as RuntimeSession;
+ const task: DelegatedTask = {
+ taskInboxToken: "task-token",
+ createdByTurnId: "turn-parent",
+ metadata: {
+ agentId: "agent-1",
+ kind: "subagent",
+ mode: "local",
+ name: "research",
+ },
+ operationId: "operation-1",
+ taskId: "task-1",
+ taskRunId: "run-candidate",
+ };
+
+ const result = await settleDelegatedDispatch({
+ callId: "call-task",
+ session,
+ subagentName: "research",
+ task,
+ });
+
+ expect(sendTaskCommandToOwner).not.toHaveBeenCalled();
+ expect(getSessionTaskIndex(result.session.state)[0]).toMatchObject({
+ taskId: "task-1",
+ taskRunId: "run-candidate",
+ });
+
+ await acknowledgeDelegatedTasksStep({ tasks: [task] });
+ expect(sendTaskCommandToOwner).toHaveBeenCalledWith(
+ expect.objectContaining({ command: { kind: "ready" } }),
+ );
+ });
+});
diff --git a/packages/eve/src/execution/tasks/parent/delegate.ts b/packages/eve/src/execution/tasks/parent/delegate.ts
new file mode 100644
index 000000000..45485e90a
--- /dev/null
+++ b/packages/eve/src/execution/tasks/parent/delegate.ts
@@ -0,0 +1,183 @@
+/**
+ * Delegation policy for the subagent dispatch path: derives task identity,
+ * builds metadata and the parked-tool-call receipt, records the session
+ * index, and defines failure semantics for an unacknowledged dispatch.
+ * Task-run transport (start/command/view) lives in `run-parent.ts`, which
+ * this module composes and which other non-delegation callers share.
+ */
+import type { RuntimeSession } from "#execution/agent-handle-dispatch.js";
+import {
+ readLatestTaskView,
+ sendTaskCommand,
+ sendTaskCommandToOwner,
+ startTaskRun,
+ waitForTaskCommandOwner,
+} from "#execution/tasks/parent/run-parent.js";
+import { sessionCommandHookToken } from "#execution/session-command-token.js";
+import { deriveAgentOperationId } from "#harness/handles/operation-id.js";
+import type { RuntimeSubagentChildResult } from "#runtime/actions/types.js";
+import type { JsonValue } from "#shared/json.js";
+import { recordSessionTask } from "#tasks/session-index.js";
+import { deriveTaskInboxToken, deriveTaskId } from "#tasks/task-id.js";
+import { isTerminalTaskStatus, type TaskMetadata } from "#tasks/types.js";
+
+/** A prepared delegated task: identity plus its started durable run. */
+export interface DelegatedTask {
+ readonly taskInboxToken: string;
+ readonly createdByStepIndex?: number;
+ readonly createdByTurnId: string;
+ readonly metadata: TaskMetadata;
+ readonly operationId: string;
+ readonly taskId: string;
+ readonly taskRunId: string;
+}
+
+/**
+ * Creates the durable task record for one delegated subagent call,
+ * before the child dispatch side effect. The task must exist first so
+ * a fast child always finds a live command hook; a duplicate replay
+ * re-derives the same token and the loser exits on the hook claim.
+ */
+export async function beginDelegatedTask(input: {
+ readonly agentId: string;
+ readonly callId: string;
+ readonly mode: "local" | "remote";
+ readonly name: string;
+ readonly parentSessionId: string;
+ readonly parentStepIndex?: number;
+ readonly parentTurnId: string;
+ readonly session: RuntimeSession;
+}): Promise<DelegatedTask> {
+ const taskId = deriveTaskId({
+ callId: input.callId,
+ parentSessionId: input.parentSessionId,
+ parentTurnId: input.parentTurnId,
+ });
+ const taskInboxToken = deriveTaskInboxToken({
+ parentContinuationToken: input.session.continuationToken,
+ taskId,
+ });
+ const operationId = deriveAgentOperationId({
+ callId: input.callId,
+ parentSessionId: input.parentSessionId,
+ parentTurnId: input.parentTurnId,
+ });
+ const metadata: TaskMetadata = {
+ agentId: input.agentId,
+ kind: "subagent",
+ mode: input.mode,
+ name: input.name,
+ };
+ await startTaskRun({
+ taskInboxToken,
+ initialView: {
+ metadata,
+ status: "working",
+ taskId,
+ },
+ parentContinuationToken: sessionCommandHookToken(input.session.sessionId),
+ });
+ const owner = await waitForTaskCommandOwner({ taskInboxToken });
+ return {
+ taskInboxToken,
+ createdByStepIndex: input.parentStepIndex ?? 0,
+ createdByTurnId: input.parentTurnId,
+ metadata,
+ operationId,
+ taskId,
+ taskRunId: owner.runId,
+ };
+}
+
+/**
+ * Settles a delegated dispatch that acknowledged a child: persists the task
+ * in the session index and returns the receipt that resolves the originating
+ * tool call. Agent identity and routing remain in the persistent address
+ * record; task state owns execution availability.
+ */
+export async function settleDelegatedDispatch(input: {
+ readonly callId: string;
+ readonly session: RuntimeSession;
+ readonly subagentName: string;
+ readonly task: DelegatedTask;
+}): Promise<{ readonly receipt: RuntimeSubagentChildResult; readonly session: RuntimeSession }> {
+ const receiptOutput = {
+ agentId: input.task.metadata.agentId,
+ status: "working" as const,
+ taskId: input.task.taskId,
+ };
+ return {
+ receipt: {
+ backgroundTask: { status: receiptOutput.status, taskId: receiptOutput.taskId },
+ callId: input.callId,
+ kind: "subagent-result",
+ origin: "child",
+ outcome: {
+ kind: "parked",
+ result: {
+ kind: "succeeded",
+ output: `Delegated as background task ${input.task.taskId} (working).`,
+ },
+ usageDelta: { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 0, outputTokens: 0 },
+ },
+ output: receiptOutput,
+ subagentName: input.subagentName,
+ },
+ session: recordSessionTask(input.session, {
+ taskInboxToken: input.task.taskInboxToken,
+ createdByStepIndex: input.task.createdByStepIndex,
+ createdByTurnId: input.task.createdByTurnId,
+ metadata: input.task.metadata,
+ operationId: input.task.operationId,
+ taskId: input.task.taskId,
+ taskRunId: input.task.taskRunId,
+ }),
+ };
+}
+
+/** Releases task events only after the parent session index committed. */
+export async function acknowledgeDelegatedTasksStep(input: {
+ readonly tasks: readonly {
+ readonly taskInboxToken: string;
+ readonly taskId: string;
+ readonly taskRunId: string;
+ }[];
+}): Promise<void> {
+ "use step";
+
+ for (const task of input.tasks) {
+ const owner = await sendTaskCommandToOwner({
+ command: { kind: "ready" },
+ taskInboxToken: task.taskInboxToken,
+ retryUnreachable: { attempts: 20, delayMs: 250 },
+ });
+ if (owner !== undefined) continue;
+ const view = await readLatestTaskView({ taskRunId: task.taskRunId });
+ if (view !== undefined && isTerminalTaskStatus(view.status)) continue;
+ throw new Error(`Task run "${task.taskId}" did not accept its readiness command.`);
+ }
+}
+
+/** Fails an indexed task whose child dispatch was definitively rejected. */
+export async function failDelegatedDispatch(input: {
+ readonly error: JsonValue;
+ readonly task: DelegatedTask;
+}): Promise<void> {
+ await sendTaskCommand({
+ command: { data: input.error, kind: "fail" },
+ taskInboxToken: input.task.taskInboxToken,
+ retryUnreachable: { attempts: 20, delayMs: 250 },
+ });
+}
+
+/** Silently terminates a task whose child dispatch failed before parent indexing. */
+export async function rejectDelegatedDispatch(input: {
+ readonly error: JsonValue;
+ readonly task: DelegatedTask;
+}): Promise<void> {
+ await sendTaskCommand({
+ command: { data: input.error, kind: "reject-dispatch" },
+ taskInboxToken: input.task.taskInboxToken,
+ retryUnreachable: { attempts: 20, delayMs: 250 },
+ });
+}
diff --git a/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts b/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts
new file mode 100644
index 000000000..2b8641fcb
--- /dev/null
+++ b/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts
@@ -0,0 +1,219 @@
+/**
+ * Task-mode sibling of `dispatchRuntimeActionsStep`, selected by the turn
+ * workflow when the agent enables `experimental.tasks`.
+ *
+ * Same plan → dispatch → emit skeleton, but every delegation is wrapped in
+ * the durable task lifecycle: the task record and its inbox token
+ * exist *before* the child dispatch side effect (`beginDelegatedTask`),
+ * continuations pass the availability check and enter the parent session's
+ * task index first, and the task settles against the dispatch outcome.
+ * Children report through their task's inbox token rather than the
+ * parent turn inbox, and every start dispatches a conversation-mode
+ * (persistent) child so the background task stays resumable.
+ *
+ * Task-control calls (`task_peek` / `task_cancel` / `task_send`) execute
+ * inline in this step, which holds the session ownership index and world
+ * access they need.
+ */
+
+import {
+ type DispatchOutcome,
+ dispatchToTaskAgentAddress,
+} from "#execution/agent-handle-dispatch.js";
+import { createAgentContinuationBundle } from "#execution/agent-continuation-bundle.js";
+import {
+ emitSubagentCalled,
+ prepareRuntimeActionDispatch,
+ type RuntimeActionDispatchInput,
+ type RuntimeActionDispatchResult,
+ startSubagent,
+} from "#execution/dispatch-runtime-actions-shared.js";
+import { createDurableSessionState } from "#execution/durable-session-store.js";
+import {
+ beginDelegatedTask,
+ type DelegatedTask,
+ settleDelegatedDispatch,
+} from "#execution/tasks/parent/delegate.js";
+import { executeTaskControlAction } from "#execution/tasks/parent/dispatch.js";
+import {
+ checkTaskContinuationAvailability,
+ describeTaskDispatch,
+ persistContinuationTaskInParentSession,
+ settleTaskDispatchError,
+ type PersistedContinuationTask,
+} from "#execution/tasks/parent/continuation-dispatch.js";
+import type { RuntimeActionResult } from "#runtime/actions/types.js";
+
+export async function dispatchTaskStep(
+ input: RuntimeActionDispatchInput,
+): Promise<RuntimeActionDispatchResult> {
+ "use step";
+
+ const prepared = await prepareRuntimeActionDispatch({
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
+ taskControls: true,
+ });
+ if (prepared === undefined) {
+ return { results: [], sessionState: input.sessionState, pendingTasks: [] };
+ }
+
+ const { batch, bundle, session } = prepared;
+ // Acquired only once preflight can no longer throw, so a planning failure
+ // never leaks the writer lock.
+ const writer = input.parentWritable.getWriter();
+
+ let nextSession = session;
+ const results: RuntimeActionResult[] = [];
+ const pendingTasks: DelegatedTask[] = [];
+
+ try {
+ for (const entry of prepared.plan) {
+ if (entry.kind === "reject") {
+ results.push(entry.result);
+ continue;
+ }
+
+ if (entry.kind === "task-control") {
+ const control = await executeTaskControlAction({
+ action: entry.action,
+ bundle,
+ parentStepIndex: batch.event.stepIndex,
+ parentTurnId: batch.event.turnId,
+ session: nextSession,
+ });
+ nextSession = control.session;
+ if (control.pendingTask !== undefined) pendingTasks.push(control.pendingTask);
+ results.push(control.result);
+ continue;
+ }
+
+ if (entry.kind === "resume") {
+ const busy = await checkTaskContinuationAvailability({
+ action: entry.action,
+ agentId: entry.agentId,
+ parentStepIndex: batch.event.stepIndex,
+ parentTurnId: batch.event.turnId,
+ session: nextSession,
+ });
+ if (busy !== undefined) {
+ results.push(busy);
+ continue;
+ }
+ }
+
+ const delegated = await beginDelegatedTask({
+ ...describeTaskDispatch({
+ action: entry.kind === "resume" ? entry.action : entry.target.action,
+ agentId: entry.kind === "resume" ? entry.agentId : undefined,
+ parentSessionId: session.sessionId,
+ parentTurnId: batch.event.turnId,
+ session: nextSession,
+ }),
+ parentSessionId: session.sessionId,
+ parentStepIndex: batch.event.stepIndex,
+ parentTurnId: batch.event.turnId,
+ session: nextSession,
+ });
+ let persistedContinuation: PersistedContinuationTask | undefined;
+ if (entry.kind === "resume") {
+ persistedContinuation = await persistContinuationTaskInParentSession({
+ action: entry.action,
+ agentId: entry.agentId,
+ delegated,
+ session: nextSession,
+ });
+ nextSession = persistedContinuation?.session ?? nextSession;
+ }
+
+ let outcome: DispatchOutcome;
+ switch (entry.kind) {
+ case "resume":
+ outcome = await dispatchToTaskAgentAddress({
+ action: entry.action,
+ agentId: entry.agentId,
+ bundle: createAgentContinuationBundle({
+ action: entry.action,
+ bundle,
+ dynamicRemoteAgent: entry.dynamicRemoteAgent,
+ }),
+ currentSession: nextSession,
+ parentToken: delegated.taskInboxToken,
+ });
+ break;
+ case "start":
+ outcome = await startSubagent({
+ auth: prepared.auth,
+ batchEvent: batch.event,
+ bundle,
+ callbackBaseUrl: input.callbackBaseUrl,
+ capabilities: prepared.capabilities,
+ channelMetadata: prepared.channelMetadata,
+ currentSession: nextSession,
+ fanoutSize: prepared.fanoutSize,
+ initiatorAuth: prepared.initiatorAuth,
+ parentContinuationToken: delegated.taskInboxToken,
+ parentTraceContext: prepared.parentTraceContext,
+ // Background tasks require resumable children, so task mode
+ // always dispatches conversation-mode (persistent) sessions;
+ // `experimental.subagentPersistentSessions` never produces a
+ // third mode here.
+ persistentSessions: true,
+ serializedContext: prepared.serializedContext,
+ session,
+ taskOwned: true,
+ target: entry.target,
+ });
+ break;
+ }
+
+ nextSession = outcome.session;
+ if (outcome.kind === "error") {
+ results.push(
+ await settleTaskDispatchError({
+ delegated,
+ outcome,
+ persisted: persistedContinuation,
+ }),
+ );
+ if (persistedContinuation !== undefined) pendingTasks.push(delegated);
+ continue;
+ }
+
+ if (persistedContinuation !== undefined) {
+ results.push(persistedContinuation.receipt);
+ } else {
+ const settled = await settleDelegatedDispatch({
+ callId: outcome.callId,
+ session: nextSession,
+ subagentName: outcome.toolName,
+ task: delegated,
+ });
+ nextSession = settled.session;
+ results.push(settled.receipt);
+ }
+ pendingTasks.push(delegated);
+
+ await emitSubagentCalled({
+ adapter: prepared.adapter,
+ adapterCtx: prepared.adapterCtx,
+ batchEvent: batch.event,
+ entry,
+ outcome,
+ sessionId: session.sessionId,
+ writer,
+ });
+ }
+ } finally {
+ writer.releaseLock();
+ }
+
+ return {
+ results,
+ sessionState:
+ nextSession === session
+ ? input.sessionState
+ : createDurableSessionState({ session: nextSession }),
+ pendingTasks,
+ };
+}
diff --git a/packages/eve/src/execution/tasks/parent/dispatch.test.ts b/packages/eve/src/execution/tasks/parent/dispatch.test.ts
new file mode 100644
index 000000000..67098dbbb
--- /dev/null
+++ b/packages/eve/src/execution/tasks/parent/dispatch.test.ts
@@ -0,0 +1,201 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { RuntimeSession } from "#execution/agent-handle-dispatch.js";
+import {
+ cancelRemoteAgentTurn,
+ resolveRemoteAgentForAction,
+} from "#execution/remote-agent-dispatch.js";
+import { executeTaskControlAction } from "#execution/tasks/parent/dispatch.js";
+import { readLatestTaskView, sendTaskCommand } from "#execution/tasks/parent/run-parent.js";
+import { requestWorkflowTurnCancellation } from "#execution/workflow-runtime.js";
+import { AGENT_HANDLES_STATE_KEY } from "#harness/handles/store.js";
+import type { RuntimeToolCallActionRequest } from "#runtime/actions/types.js";
+import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
+import { SESSION_TASKS_STATE_KEY } from "#tasks/session-index.js";
+
+vi.mock("#execution/tasks/parent/run-parent.js", () => ({
+ readLatestTaskView: vi.fn(),
+ sendTaskCommand: vi.fn(),
+}));
+vi.mock("#execution/workflow-runtime.js", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("#execution/workflow-runtime.js")>()),
+ requestWorkflowTurnCancellation: vi.fn(),
+}));
+vi.mock("#execution/remote-agent-dispatch.js", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("#execution/remote-agent-dispatch.js")>()),
+ cancelRemoteAgentTurn: vi.fn(),
+ resolveRemoteAgentForAction: vi.fn(),
+}));
+
+const action: RuntimeToolCallActionRequest = {
+ callId: "call-cancel",
+ input: { taskIds: ["task-1"] },
+ kind: "tool-call",
+ toolName: "task_cancel",
+};
+
+function createSession(mode: "local" | "remote"): RuntimeSession {
+ const address =
+ mode === "local"
+ ? { continuationToken: "child-token", kind: "agent/local" as const, sessionId: "child-1" }
+ : {
+ callbackBaseUrl: "https://parent.example",
+ kind: "agent/remote" as const,
+ sessionId: "child-1",
+ url: "https://child.example",
+ };
+ return {
+ agent: { modelReference: { id: "model" }, system: "", tools: [] },
+ compaction: { recentWindowSize: 4, threshold: 1_000_000 },
+ continuationToken: "parent-token",
+ history: [],
+ sessionId: "parent-session",
+ state: {
+ [AGENT_HANDLES_STATE_KEY]: {
+ handles: [
+ {
+ address,
+ identity: { id: "agent-1", name: "research", nodeId: "node-1" },
+ phase: "addressed",
+ },
+ ],
+ },
+ [SESSION_TASKS_STATE_KEY]: {
+ tasks: [
+ {
+ taskInboxToken: "task-token",
+ createdByTurnId: "turn-1",
+ metadata: {
+ agentId: "agent-1",
+ kind: "subagent",
+ mode,
+ name: "research",
+ },
+ operationId: "operation-1",
+ taskId: "task-1",
+ taskRunId: "run-1",
+ },
+ ],
+ },
+ },
+ } as RuntimeSession;
+}
+
+describe("task cancellation identity", () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ vi.mocked(sendTaskCommand).mockResolvedValue("delivered");
+ vi.mocked(readLatestTaskView).mockResolvedValue({
+ metadata: {
+ agentId: "agent-1",
+ kind: "subagent",
+ mode: "local",
+ name: "research",
+ },
+ executor: { childSessionId: "child-1", childTurnId: "turn_child_7" },
+ status: "cancelled",
+ taskId: "task-1",
+ });
+ vi.mocked(resolveRemoteAgentForAction).mockReturnValue({ name: "research" } as never);
+ vi.mocked(requestWorkflowTurnCancellation).mockResolvedValue({
+ sessionId: "child-1",
+ status: "accepted",
+ });
+ vi.mocked(cancelRemoteAgentTurn).mockResolvedValue({
+ sessionId: "child-1",
+ status: "accepted",
+ });
+ });
+
+ it.each(["local", "remote"] as const)(
+ "guards %s cancellation with the task's child turn",
+ async (mode) => {
+ const result = await executeTaskControlAction({
+ action,
+ bundle: { subagentRegistry: { subagentsByNodeId: new Map() } } as never,
+ parentTurnId: "turn-parent",
+ session: createSession(mode),
+ });
+
+ if (mode === "local") {
+ expect(requestWorkflowTurnCancellation).toHaveBeenCalledWith({
+ sessionId: "child-1",
+ taskId: "task-1",
+ turnId: "turn_child_7",
+ });
+ expect(cancelRemoteAgentTurn).not.toHaveBeenCalled();
+ } else {
+ expect(cancelRemoteAgentTurn).toHaveBeenCalledWith(
+ expect.objectContaining({
+ sessionId: "child-1",
+ taskId: "task-1",
+ turnId: "turn_child_7",
+ }),
+ );
+ expect(requestWorkflowTurnCancellation).not.toHaveBeenCalled();
+ }
+ expect(result.result).toMatchObject({ output: { tasks: [{ status: "cancelled" }] } });
+ expect(result.session.state?.[AGENT_HANDLES_STATE_KEY]).toMatchObject({
+ handles: [{ phase: "addressed" }],
+ });
+ },
+ );
+
+ it("uses task-scoped cancellation before child-turn identity arrives", async () => {
+ vi.mocked(readLatestTaskView).mockResolvedValue({
+ metadata: { agentId: "agent-1", kind: "subagent", mode: "local", name: "research" },
+ status: "cancelled",
+ taskId: "task-1",
+ });
+
+ await executeTaskControlAction({
+ action,
+ bundle: {} as CompiledBundle,
+ parentTurnId: "turn-parent",
+ session: createSession("local"),
+ });
+
+ expect(requestWorkflowTurnCancellation).toHaveBeenCalledWith({
+ sessionId: "child-1",
+ taskId: "task-1",
+ });
+ expect(cancelRemoteAgentTurn).not.toHaveBeenCalled();
+ });
+
+ it("does not propagate a repeated cancel after the task hook is disposed", async () => {
+ vi.mocked(sendTaskCommand).mockResolvedValue("unreachable");
+
+ await executeTaskControlAction({
+ action,
+ bundle: {} as CompiledBundle,
+ parentTurnId: "turn-parent",
+ session: createSession("local"),
+ });
+
+ expect(requestWorkflowTurnCancellation).not.toHaveBeenCalled();
+ expect(cancelRemoteAgentTurn).not.toHaveBeenCalled();
+ });
+
+ it("fails instead of reporting success when cancellation does not commit", async () => {
+ vi.useFakeTimers();
+ vi.mocked(readLatestTaskView).mockResolvedValue({
+ metadata: { agentId: "agent-1", kind: "subagent", mode: "local", name: "research" },
+ status: "working",
+ taskId: "task-1",
+ });
+ try {
+ const pending = executeTaskControlAction({
+ action,
+ bundle: {} as CompiledBundle,
+ parentTurnId: "turn-parent",
+ session: createSession("local"),
+ });
+ const rejected = expect(pending).rejects.toThrow("did not commit cancellation");
+ await vi.runAllTimersAsync();
+ await rejected;
+ expect(requestWorkflowTurnCancellation).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/packages/eve/src/execution/tasks/parent/dispatch.ts b/packages/eve/src/execution/tasks/parent/dispatch.ts
new file mode 100644
index 000000000..e6de0e9d4
--- /dev/null
+++ b/packages/eve/src/execution/tasks/parent/dispatch.ts
@@ -0,0 +1,217 @@
+import type { RuntimeSession } from "#execution/agent-handle-dispatch.js";
+import {
+ cancelRemoteAgentTurn,
+ resolveRemoteAgentForAction,
+} from "#execution/remote-agent-dispatch.js";
+import {
+ createTaskControlError,
+ createTaskViewsResult,
+ createUnknownTasksError,
+ findTaskAgentAddress,
+ lookupTaskEntries,
+ readTaskViews,
+ readTaskView,
+} from "#execution/tasks/parent/control-shared.js";
+import { executeTaskSend } from "#execution/tasks/parent/send.js";
+import type { DelegatedTask } from "#execution/tasks/parent/delegate.js";
+import { sendTaskCommand } from "#execution/tasks/parent/run-parent.js";
+import { requestWorkflowTurnCancellation } from "#execution/workflow-runtime.js";
+import { createLogger, logError } from "#internal/logging.js";
+import type {
+ RuntimeActionRequest,
+ RuntimeActionResult,
+ RuntimeToolCallActionRequest,
+} from "#runtime/actions/types.js";
+import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
+import {
+ TASK_CANCEL_TOOL_NAME,
+ TASK_CONTROL_TOOL_NAMES,
+ TASK_PEEK_TOOL_NAME,
+ TASK_SEND_TOOL_NAME,
+} from "#runtime/framework-tools/tasks.js";
+import type { SessionTaskIndexEntry } from "#tasks/session-index.js";
+import { isTerminalTaskStatus, type TaskView } from "#tasks/types.js";
+
+const log = createLogger("execution.tasks.dispatch");
+
+const CANCEL_COMMIT_POLL_ATTEMPTS = 10;
+const CANCEL_COMMIT_POLL_DELAY_MS = 250;
+
+/** True for `task_peek` / `task_cancel` / `task_send` calls. */
+export function isTaskControlAction(
+ action: RuntimeActionRequest,
+): action is RuntimeToolCallActionRequest {
+ return action.kind === "tool-call" && TASK_CONTROL_TOOL_NAMES.has(action.toolName);
+}
+
+/**
+ * Executes one task-control call inside the dispatch step, which holds
+ * the durable session state (ownership index) and world access the
+ * tools need.
+ *
+ * Returns the (possibly updated) session: `task_send` follow-ups record
+ * new tasks and settle the continued agent handle.
+ */
+export async function executeTaskControlAction(input: {
+ readonly action: RuntimeToolCallActionRequest;
+ readonly bundle: CompiledBundle;
+ readonly parentStepIndex?: number;
+ readonly parentTurnId: string;
+ readonly session: RuntimeSession;
+}): Promise<{
+ readonly result: RuntimeActionResult;
+ readonly session: RuntimeSession;
+ readonly pendingTask?: DelegatedTask;
+}> {
+ const { action, session } = input;
+
+ if (action.toolName === TASK_SEND_TOOL_NAME) {
+ return executeTaskSend(input);
+ }
+
+ const taskIds = readTaskIds(action.input);
+ if (taskIds === undefined || taskIds.length === 0) {
+ return {
+ result: createTaskControlError(action, "Provide a non-empty `taskIds` array."),
+ session,
+ };
+ }
+
+ const lookup = lookupTaskEntries(session, taskIds);
+ if (lookup.kind === "unknown") {
+ return { result: createUnknownTasksError(action, lookup.unknown), session };
+ }
+ const entries = lookup.entries;
+
+ switch (action.toolName) {
+ case TASK_PEEK_TOOL_NAME: {
+ const views = await readTaskViews(entries);
+ return { result: createTaskViewsResult(action, views), session };
+ }
+ case TASK_CANCEL_TOOL_NAME: {
+ const views: TaskView[] = [];
+ for (const entry of entries) {
+ views.push(await cancelOwnedTask({ bundle: input.bundle, entry, session }));
+ }
+ return { result: createTaskViewsResult(action, views), session };
+ }
+ default:
+ return {
+ result: createTaskControlError(action, `Unsupported task control "${action.toolName}".`),
+ session,
+ };
+ }
+}
+
+/** Commits task cancellation, then propagates it to the addressed executor. */
+export async function cancelOwnedTask(input: {
+ readonly bundle: CompiledBundle;
+ readonly entry: SessionTaskIndexEntry;
+ readonly session: RuntimeSession;
+}): Promise<TaskView> {
+ const { entry } = input;
+ const delivery = await sendTaskCommand({
+ command: { kind: "cancel" },
+ taskInboxToken: entry.taskInboxToken,
+ });
+
+ // The `cancelled` state must commit before the executor abort
+ // propagates, so a late child result can never revive the task.
+ let view = await readTaskView(entry);
+ for (
+ let attempt = 0;
+ attempt < CANCEL_COMMIT_POLL_ATTEMPTS && !isTerminalTaskStatus(view.status);
+ attempt += 1
+ ) {
+ await new Promise((resolve) => setTimeout(resolve, CANCEL_COMMIT_POLL_DELAY_MS));
+ view = await readTaskView(entry);
+ }
+ if (!isTerminalTaskStatus(view.status)) {
+ throw new Error(`Task "${entry.taskId}" did not commit cancellation before timeout.`);
+ }
+ const settledView = view;
+
+ if (settledView.status === "cancelled" && delivery === "delivered") {
+ await propagateTaskCancel({ bundle: input.bundle, session: input.session, view: settledView });
+ }
+ return settledView;
+}
+
+/**
+ * Best-effort cooperative abort of the cancelled task's child turn,
+ * routed through the agent handle that owns the child address. A task
+ * whose handle is already gone has nothing left to abort.
+ */
+async function propagateTaskCancel(input: {
+ readonly bundle: CompiledBundle;
+ readonly session: RuntimeSession;
+ readonly view: TaskView;
+}): Promise<void> {
+ const handle = findTaskAgentAddress(input.session, input.view.metadata.agentId);
+ if (handle === undefined) return;
+ const childSessionId = handle.address.sessionId;
+ const childTurnId = input.view.executor?.childTurnId;
+ if (
+ input.view.executor?.childSessionId !== undefined &&
+ input.view.executor.childSessionId !== childSessionId
+ ) {
+ return;
+ }
+
+ try {
+ if (handle.address.kind === "agent/remote") {
+ const resolved = resolveRemoteAgentForAction({
+ nodeId: handle.identity.nodeId,
+ remoteAgentName: handle.identity.name,
+ registry: input.bundle.subagentRegistry.subagentsByNodeId,
+ });
+ const cancelInput: {
+ readonly remote: typeof resolved & { readonly url: string };
+ readonly sessionId: string;
+ readonly taskId: string;
+ turnId?: string;
+ } = {
+ remote: { ...resolved, url: handle.address.url },
+ sessionId: childSessionId,
+ taskId: input.view.taskId,
+ };
+ if (childTurnId !== undefined) cancelInput.turnId = childTurnId;
+ const result = await cancelRemoteAgentTurn(cancelInput);
+ if (result.status === "no_active_turn") {
+ await cancelRemoteAgentTurn({
+ remote: { ...resolved, url: handle.address.url },
+ sessionId: childSessionId,
+ taskId: input.view.taskId,
+ });
+ }
+ return;
+ }
+ const cancelInput: {
+ readonly sessionId: string;
+ readonly taskId: string;
+ turnId?: string;
+ } = {
+ sessionId: childSessionId,
+ taskId: input.view.taskId,
+ };
+ if (childTurnId !== undefined) cancelInput.turnId = childTurnId;
+ const result = await requestWorkflowTurnCancellation(cancelInput);
+ if (result.status === "no_active_turn") {
+ await requestWorkflowTurnCancellation({
+ sessionId: childSessionId,
+ taskId: input.view.taskId,
+ });
+ }
+ } catch (error) {
+ logError(log, "task cancel propagation failed; the child may run to completion", error, {
+ childSessionId,
+ taskId: input.view.taskId,
+ });
+ }
+}
+
+function readTaskIds(input: Record<string, unknown>): readonly string[] | undefined {
+ const value = input.taskIds;
+ if (!Array.isArray(value)) return undefined;
+ return value.filter((id): id is string => typeof id === "string" && id.trim() !== "");
+}
diff --git a/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts b/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts
new file mode 100644
index 000000000..16057d797
--- /dev/null
+++ b/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts
@@ -0,0 +1,185 @@
+import type { SubagentInputRequestHookPayload } from "#channel/types.js";
+import type { SubagentAuthorizationEventHookPayload } from "#channel/types.js";
+import { type DurableSessionState, readDurableSession } from "#execution/durable-session-store.js";
+import { createTaskInputCapabilityToken } from "#execution/task-input-capability.js";
+import { readLatestTaskView } from "#execution/tasks/parent/run-parent.js";
+import { createRemoteTaskInputCallbackUrl } from "#execution/workflow-callback-url.js";
+import {
+ createTaskInputRequestId,
+ toProxyInputRequestEntries,
+ upsertProxyInputRequestState,
+} from "#harness/proxy-input-requests.js";
+import { getAgentHandleStore } from "#harness/handles/store.js";
+import { removeTaskAgentAddressFromState } from "#harness/handles/transitions.js";
+import { isInputRequest } from "#runtime/input/types.js";
+import { cacheTerminalTaskView, findSessionTaskEntry } from "#tasks/session-index.js";
+import { createEveTaskInputRoutePath } from "#protocol/routes.js";
+import { isTerminalTaskStatus, type TaskView } from "#tasks/types.js";
+
+/** Validates and durably records one task-owned child HITL route batch. */
+export async function recordTaskInputRequestStep(input: {
+ readonly hookPayload: SubagentInputRequestHookPayload;
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+ readonly taskId: string;
+}): Promise<
+ | { readonly accepted: false; readonly sessionState: DurableSessionState }
+ | {
+ readonly accepted: true;
+ readonly hookPayload: SubagentInputRequestHookPayload;
+ readonly sessionState: DurableSessionState;
+ }
+> {
+ "use step";
+
+ const durableSession = await readDurableSession(input.sessionState);
+ const entry = findSessionTaskEntry(durableSession.state, input.taskId);
+ const handle = (getAgentHandleStore(durableSession.state)?.handles ?? []).find(
+ (candidate) =>
+ candidate.phase === "addressed" && candidate.identity.id === entry?.metadata.agentId,
+ );
+ if (
+ entry === undefined ||
+ handle?.phase !== "addressed" ||
+ handle.address.sessionId !== input.hookPayload.childSessionId
+ ) {
+ return { accepted: false, sessionState: input.sessionState };
+ }
+ // Remote creates are ID-addressed and return no continuation token, so
+ // provenance rests on the sessionId match above plus the strict view
+ // checks below; the child-advertised token is only used as the answer
+ // route, never as an identity anchor.
+ const view = await readLatestTaskView({ taskRunId: entry.taskRunId });
+ const eventRequestIds = input.hookPayload.event.requests.map((request) => request.requestId);
+ const viewRequestIds =
+ view?.inputRequests?.map((request) =>
+ request !== null && typeof request === "object" && !Array.isArray(request)
+ ? Reflect.get(request, "requestId")
+ : undefined,
+ ) ?? [];
+ if (
+ view?.status !== "input_required" ||
+ !input.hookPayload.event.requests.every(isInputRequest) ||
+ view.metadata.mode !== (handle.address.kind === "agent/remote" ? "remote" : "local") ||
+ view.metadata.agentId !== entry.metadata.agentId ||
+ view.executor?.childSessionId !== input.hookPayload.childSessionId ||
+ new Set(eventRequestIds).size !== eventRequestIds.length ||
+ eventRequestIds.length !== viewRequestIds.length ||
+ eventRequestIds.some((requestId, index) => requestId !== viewRequestIds[index])
+ ) {
+ return { accepted: false, sessionState: input.sessionState };
+ }
+
+ const hookPayload = namespaceTaskInputRequests(input.hookPayload, input.taskId);
+ let entries = toProxyInputRequestEntries(hookPayload, input.taskId).map(
+ ([requestId, route], index) => {
+ const childRequestId = input.hookPayload.event.requests[index]!.requestId;
+ return [
+ requestId,
+ {
+ ...route,
+ childRequestId,
+ },
+ ] as const;
+ },
+ );
+ if (handle.address.kind === "agent/remote") {
+ const childResponseUrl = createRemoteTaskInputCallbackUrl(
+ handle.address.url,
+ createEveTaskInputRoutePath(
+ createTaskInputCapabilityToken(input.hookPayload.childContinuationToken),
+ ),
+ );
+ entries = entries.map(
+ ([requestId, route]) => [requestId, { ...route, childResponseUrl }] as const,
+ );
+ }
+ const state = upsertProxyInputRequestState({
+ entries,
+ forChildContinuationToken: input.hookPayload.childContinuationToken,
+ state: durableSession.state,
+ });
+ return {
+ accepted: true,
+ hookPayload,
+ sessionState: {
+ ...input.sessionState,
+ hasProxyInputRequests: true,
+ snapshot: {
+ session: { ...durableSession, state },
+ version: input.sessionState.version,
+ },
+ },
+ };
+}
+
+function namespaceTaskInputRequests(
+ hookPayload: SubagentInputRequestHookPayload,
+ taskId: string,
+): SubagentInputRequestHookPayload {
+ return {
+ ...hookPayload,
+ event: {
+ ...hookPayload.event,
+ requests: hookPayload.event.requests.map((request) => ({
+ ...request,
+ requestId: createTaskInputRequestId(taskId, request.requestId),
+ })),
+ },
+ };
+}
+
+/** Validates that one task authorization event came from its owned child address. */
+export async function acceptTaskAuthorizationEventStep(input: {
+ readonly hookPayload: SubagentAuthorizationEventHookPayload;
+ readonly sessionState: DurableSessionState;
+ readonly taskId: string;
+}): Promise<boolean> {
+ "use step";
+
+ const durableSession = await readDurableSession(input.sessionState);
+ const entry = findSessionTaskEntry(durableSession.state, input.taskId);
+ if (entry === undefined) return false;
+ const handle = (getAgentHandleStore(durableSession.state)?.handles ?? []).find(
+ (candidate) =>
+ candidate.phase === "addressed" && candidate.identity.id === entry.metadata.agentId,
+ );
+ if (
+ handle?.phase !== "addressed" ||
+ handle.address.sessionId !== input.hookPayload.childSessionId
+ ) {
+ return false;
+ }
+ const view = await readLatestTaskView({ taskRunId: entry.taskRunId });
+ return (
+ view !== undefined &&
+ !isTerminalTaskStatus(view.status) &&
+ view.executor?.childSessionId === input.hookPayload.childSessionId &&
+ view.metadata.agentId === entry.metadata.agentId
+ );
+}
+
+/** Caches terminal task views before their workflow runs can expire. */
+export async function recordTerminalTaskViewsStep(input: {
+ readonly sessionState: DurableSessionState;
+ readonly views: readonly TaskView[];
+}): Promise<DurableSessionState> {
+ "use step";
+
+ const durableSession = await readDurableSession(input.sessionState);
+ let state = durableSession.state;
+ for (const view of input.views) {
+ state = cacheTerminalTaskView(state, view);
+ if (view.executor?.lifecycle === "terminal") {
+ state = removeTaskAgentAddressFromState(state, view.metadata.agentId);
+ }
+ }
+ if (state === durableSession.state) return input.sessionState;
+ return {
+ ...input.sessionState,
+ snapshot: {
+ session: { ...durableSession, state },
+ version: input.sessionState.version,
+ },
+ };
+}
diff --git a/packages/eve/src/execution/tasks/run-parent.ts b/packages/eve/src/execution/tasks/parent/run-parent.ts
similarity index 52%
rename from packages/eve/src/execution/tasks/run-parent.ts
rename to packages/eve/src/execution/tasks/parent/run-parent.ts
index a08e47f1c..690f35a0c 100644
--- a/packages/eve/src/execution/tasks/run-parent.ts
+++ b/packages/eve/src/execution/tasks/parent/run-parent.ts
@@ -1,40 +1,42 @@
-import {
- EntityConflictError,
- HookNotFoundError,
- RunExpiredError,
- WorkflowRunNotFoundError,
-} from "#compiled/@workflow/errors/index.js";
-
-import type { TaskRunWorkflowInput } from "#execution/tasks/run-task-workflow.js";
+import type { TaskRunWorkflowInput } from "#execution/tasks/child/workflow.js";
+import { isTaskWorkflowTargetGone } from "#execution/tasks/workflow-target.js";
import {
startWorkflowPreferLatest,
taskRunWorkflowReference,
+ waitForCommandHookOwner,
} from "#execution/workflow-runtime.js";
import { getRun, resumeHook } from "#internal/workflow/runtime.js";
-import { walkCauseChain } from "#shared/errors.js";
import {
- TASK_SNAPSHOT_STREAM_NAMESPACE,
- isReadyTaskStatus,
+ TASK_VIEW_STREAM_NAMESPACE,
type TaskCommand,
type TaskCommandHookPayload,
type TaskRunInboundPayload,
type TaskView,
} from "#tasks/types.js";
-const TASK_SNAPSHOT_READ_TIMEOUT_MS = 10_000;
+const TASK_VIEW_READ_TIMEOUT_MS = 10_000;
/**
- * Node-side controls for durable task runs. Every export must be called
- * from inside a `"use step"` body; none of these are steps themselves so
- * dispatch and tool steps can compose them inside one durable boundary.
+ * Node-side controls for durable task runs — the generic transport layer.
+ * This module only speaks `TaskCommand`/`TaskView`; it knows nothing about
+ * subagents, receipts, or the session index. Caller-specific policy (e.g.
+ * subagent delegation in `delegate.ts`) composes these primitives.
+ *
+ * Every export must be called from inside a `"use step"` body; none of
+ * these are steps themselves so dispatch and tool steps can compose them
+ * inside one durable boundary.
*/
/** Starts the durable run owning one task's lifecycle. */
-export async function startTaskRun(
- input: TaskRunWorkflowInput,
-): Promise<{ readonly runId: string }> {
- const run = await startWorkflowPreferLatest(taskRunWorkflowReference, [input]);
- return { runId: run.runId };
+export async function startTaskRun(input: TaskRunWorkflowInput): Promise<void> {
+ await startWorkflowPreferLatest(taskRunWorkflowReference, [input]);
+}
+
+/** Resolves the task run that won ownership of one replay-stable command token. */
+export async function waitForTaskCommandOwner(input: {
+ readonly taskInboxToken: string;
+}): Promise<{ readonly runId: string }> {
+ return await waitForCommandHookOwner(input.taskInboxToken);
}
/**
@@ -42,14 +44,14 @@ export async function startTaskRun(
*
* `unreachable` means the hook is not resumable — either the run
* already finished and disposed it (the task is terminal; read the
- * final snapshot) or, right after creation, the freshly started run has
+ * final view) or, right after creation, the freshly started run has
* not registered it yet. Senders racing that startup window pass
* `retryUnreachable`; senders addressing an established task treat
* `unreachable` as the terminal signal.
*/
export async function sendTaskCommand(input: {
readonly command: TaskCommand;
- readonly continuationToken: string;
+ readonly taskInboxToken: string;
readonly retryUnreachable?: { readonly attempts: number; readonly delayMs: number };
}): Promise<"delivered" | "unreachable"> {
return (await sendTaskCommandToOwner(input)) === undefined ? "unreachable" : "delivered";
@@ -58,27 +60,25 @@ export async function sendTaskCommand(input: {
/** Delivers one command and returns the accepting task workflow's run id. */
export async function sendTaskCommandToOwner(input: {
readonly command: TaskCommand;
- readonly continuationToken: string;
+ readonly taskInboxToken: string;
readonly retryUnreachable?: { readonly attempts: number; readonly delayMs: number };
}): Promise<{ readonly runId: string } | undefined> {
const payload: TaskCommandHookPayload = { command: input.command, kind: "task-command" };
const attempts = Math.max(1, input.retryUnreachable?.attempts ?? 1);
for (let attempt = 0; ; attempt += 1) {
try {
- const owner = await resumeHook(input.continuationToken, payload);
+ const owner = await resumeHook(input.taskInboxToken, payload);
if (
typeof owner !== "object" ||
owner === null ||
!("runId" in owner) ||
typeof owner.runId !== "string"
) {
- throw new Error(
- `Task continuation hook "${input.continuationToken}" returned no owner run id.`,
- );
+ throw new Error(`Task inbox hook "${input.taskInboxToken}" returned no owner run id.`);
}
return { runId: owner.runId };
} catch (error) {
- if (!isFinishedTaskRunTarget(error)) {
+ if (!isTaskWorkflowTargetGone(error)) {
throw error;
}
if (attempt + 1 >= attempts) {
@@ -98,14 +98,14 @@ export async function sendTaskCommandToOwner(input: {
* hook, so the payload is stale by definition.
*/
export async function sendTaskInboundPayload(input: {
- readonly continuationToken: string;
+ readonly taskInboxToken: string;
readonly payload: TaskRunInboundPayload;
}): Promise<"delivered" | "unreachable"> {
try {
- await resumeHook(input.continuationToken, input.payload);
+ await resumeHook(input.taskInboxToken, input.payload);
return "delivered";
} catch (error) {
- if (!isFinishedTaskRunTarget(error)) {
+ if (!isTaskWorkflowTargetGone(error)) {
throw error;
}
return "unreachable";
@@ -113,18 +113,18 @@ export async function sendTaskInboundPayload(input: {
}
/**
- * Reads the latest snapshot a task run has published, or `undefined`
- * when the run has not committed its first snapshot yet (the caller
+ * Reads the latest view a task run has published, or `undefined`
+ * when the run has not committed its first view yet (the caller
* already holds the creation receipt, which is `working`).
*
- * Snapshots are trusted without re-validation: the task run is the
+ * Views are trusted without re-validation: the task run is the
* single writer and every write passed the transition function.
*/
-export async function readLatestTaskSnapshot(input: {
+export async function readLatestTaskView(input: {
readonly taskRunId: string;
}): Promise<TaskView | undefined> {
const stream = getRun<unknown>(input.taskRunId).getReadable<TaskView>({
- namespace: TASK_SNAPSHOT_STREAM_NAMESPACE,
+ namespace: TASK_VIEW_STREAM_NAMESPACE,
startIndex: -1,
});
const tailIndex = await stream.getTailIndex();
@@ -133,45 +133,10 @@ export async function readLatestTaskSnapshot(input: {
if (tailIndex < 0) {
return undefined;
}
- const result = await readWithTimeout(reader, "latest task snapshot");
+ const result = await readWithTimeout(reader, "latest task view");
return result;
} finally {
- await reader.cancel("eve task snapshot read complete").catch(() => {});
- reader.releaseLock();
- }
-}
-
-/**
- * Waits until a task run publishes a ready snapshot — terminal or
- * `input_required` — starting from the latest published state. Returns
- * immediately when the task is already ready.
- *
- * Unlike {@link readLatestTaskSnapshot} this read has no timeout; the
- * caller owns cancellation by racing this promise (for example against
- * turn cancellation) and abandoning it.
- */
-export async function waitForReadyTaskSnapshot(input: {
- readonly taskRunId: string;
-}): Promise<TaskView> {
- const stream = getRun<unknown>(input.taskRunId).getReadable<TaskView>({
- namespace: TASK_SNAPSHOT_STREAM_NAMESPACE,
- startIndex: -1,
- });
- const reader = stream.getReader();
- try {
- while (true) {
- const { done, value } = await reader.read();
- if (done || value === undefined) {
- throw new Error(
- `Task run "${input.taskRunId}" closed its snapshot stream without a ready snapshot.`,
- );
- }
- if (isReadyTaskStatus(value.status)) {
- return value;
- }
- }
- } finally {
- await reader.cancel("eve task snapshot wait complete").catch(() => {});
+ await reader.cancel("eve task view read complete").catch(() => {});
reader.releaseLock();
}
}
@@ -185,11 +150,11 @@ async function readWithTimeout(
const result = await Promise.race([
reader.read().then((read) => ({ kind: "read" as const, read })),
new Promise<{ readonly kind: "timeout" }>((resolve) => {
- timeout = setTimeout(() => resolve({ kind: "timeout" }), TASK_SNAPSHOT_READ_TIMEOUT_MS);
+ timeout = setTimeout(() => resolve({ kind: "timeout" }), TASK_VIEW_READ_TIMEOUT_MS);
}),
]);
if (result.kind === "timeout") {
- throw new Error(`Timed out reading ${what} after ${TASK_SNAPSHOT_READ_TIMEOUT_MS}ms.`);
+ throw new Error(`Timed out reading ${what} after ${TASK_VIEW_READ_TIMEOUT_MS}ms.`);
}
if (result.read.done) {
return undefined;
@@ -201,17 +166,3 @@ async function readWithTimeout(
}
}
}
-
-export function isFinishedTaskRunTarget(error: unknown): boolean {
- for (const candidate of walkCauseChain(error)) {
- if (
- HookNotFoundError.is(candidate) ||
- WorkflowRunNotFoundError.is(candidate) ||
- RunExpiredError.is(candidate) ||
- EntityConflictError.is(candidate)
- ) {
- return true;
- }
- }
- return false;
-}
diff --git a/packages/eve/src/execution/tasks/parent/send.test.ts b/packages/eve/src/execution/tasks/parent/send.test.ts
new file mode 100644
index 000000000..4fe3cec98
--- /dev/null
+++ b/packages/eve/src/execution/tasks/parent/send.test.ts
@@ -0,0 +1,284 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import {
+ dispatchToTaskAgentAddress,
+ type RuntimeSession,
+} from "#execution/agent-handle-dispatch.js";
+import {
+ beginDelegatedTask,
+ failDelegatedDispatch,
+ settleDelegatedDispatch,
+} from "#execution/tasks/parent/delegate.js";
+import { readLatestTaskView } from "#execution/tasks/parent/run-parent.js";
+import { executeTaskSend } from "#execution/tasks/parent/send.js";
+import { AGENT_HANDLES_STATE_KEY } from "#harness/handles/store.js";
+import type { RuntimeToolCallActionRequest } from "#runtime/actions/types.js";
+import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
+import { SESSION_TASKS_STATE_KEY } from "#tasks/session-index.js";
+import type { TaskStatus, TaskView } from "#tasks/types.js";
+
+vi.mock("#execution/agent-handle-dispatch.js", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("#execution/agent-handle-dispatch.js")>()),
+ dispatchToTaskAgentAddress: vi.fn(),
+}));
+
+vi.mock("#execution/tasks/parent/delegate.js", () => ({
+ beginDelegatedTask: vi.fn(),
+ failDelegatedDispatch: vi.fn(),
+ settleDelegatedDispatch: vi.fn(),
+}));
+
+vi.mock("#execution/tasks/parent/run-parent.js", () => ({
+ readLatestTaskView: vi.fn(),
+ sendTaskCommand: vi.fn(),
+}));
+
+const agentId = "ag_research:abcdef123456";
+const metadata = { agentId, kind: "subagent" as const, mode: "local" as const, name: "research" };
+
+function task(taskId: string, status: TaskStatus): TaskView {
+ // Cast on purpose: mock views omit the per-status payload fields the
+ // TaskView union requires (e.g. lastOutput on completed).
+ return { metadata, status, taskId } as TaskView;
+}
+
+function createSession(includeActive = false, activeCreatedByTurnId = "turn-1"): RuntimeSession {
+ const tasks = [
+ {
+ taskInboxToken: "task-token-terminal",
+ createdByTurnId: "turn-1",
+ metadata,
+ operationId: "operation-terminal",
+ taskId: "task_terminal",
+ taskRunId: "run-terminal",
+ },
+ ...(includeActive
+ ? [
+ {
+ taskInboxToken: "task-token-active",
+ createdByTurnId: activeCreatedByTurnId,
+ metadata,
+ operationId: "operation-active",
+ taskId: "task_active",
+ taskRunId: "run-active",
+ },
+ ]
+ : []),
+ ];
+ return {
+ agent: { modelReference: { id: "model" }, system: "", tools: [] },
+ compaction: { recentWindowSize: 4, threshold: 1_000_000 },
+ continuationToken: "parent-token",
+ history: [],
+ sessionId: "parent-session",
+ state: {
+ [AGENT_HANDLES_STATE_KEY]: {
+ handles: [
+ {
+ address: {
+ continuationToken: "child-token",
+ kind: "agent/local",
+ sessionId: "child-session",
+ },
+ identity: { id: agentId, name: "research", nodeId: "node-research" },
+ phase: "addressed",
+ },
+ ],
+ },
+ [SESSION_TASKS_STATE_KEY]: { tasks },
+ },
+ } as RuntimeSession;
+}
+
+const action: RuntimeToolCallActionRequest = {
+ callId: "call-send",
+ input: { message: "continue", taskId: "task_terminal" },
+ kind: "tool-call",
+ toolName: "task_send",
+};
+
+describe("task_send persistent-agent availability", () => {
+ beforeEach(() => vi.resetAllMocks());
+
+ it("starts a new task on the same address after terminal work", async () => {
+ const session = createSession();
+ vi.mocked(readLatestTaskView).mockResolvedValue(task("task_terminal", "completed"));
+ vi.mocked(beginDelegatedTask).mockResolvedValue({
+ taskInboxToken: "task-token-new",
+ createdByTurnId: "turn-2",
+ metadata,
+ operationId: "operation-new",
+ taskId: "task_new",
+ taskRunId: "run-new",
+ });
+ vi.mocked(dispatchToTaskAgentAddress).mockResolvedValue({
+ address: {
+ continuationToken: "child-token",
+ kind: "agent/local",
+ sessionId: "child-session",
+ },
+ callId: action.callId,
+ kind: "called",
+ name: "research",
+ session,
+ toolName: "research",
+ });
+ vi.mocked(settleDelegatedDispatch).mockResolvedValue({
+ receipt: {} as never,
+ session,
+ });
+
+ const result = await executeTaskSend({
+ action,
+ bundle: {} as CompiledBundle,
+ parentTurnId: "turn-2",
+ session,
+ });
+
+ expect(beginDelegatedTask).toHaveBeenCalledWith(expect.objectContaining({ agentId }));
+ expect(dispatchToTaskAgentAddress).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId, currentSession: session }),
+ );
+ expect(result.result).toMatchObject({
+ output: { agentId, status: "working", taskId: "task_new" },
+ });
+ });
+
+ it("rejects a follow-up while another nonterminal task owns the agent", async () => {
+ const session = createSession(true);
+ vi.mocked(readLatestTaskView).mockImplementation(async ({ taskRunId }) =>
+ taskRunId === "run-active"
+ ? task("task_active", "input_required")
+ : task("task_terminal", "completed"),
+ );
+
+ const result = await executeTaskSend({
+ action,
+ bundle: {} as CompiledBundle,
+ parentTurnId: "turn-2",
+ session,
+ });
+
+ expect(result.result).toMatchObject({
+ isError: true,
+ output: { message: expect.stringContaining("task_active") },
+ });
+ expect(beginDelegatedTask).not.toHaveBeenCalled();
+ expect(dispatchToTaskAgentAddress).not.toHaveBeenCalled();
+ expect(failDelegatedDispatch).not.toHaveBeenCalled();
+ });
+
+ it("rejects a second same-batch follow-up even if the first task already completed", async () => {
+ const session = createSession(true, "turn-2");
+ vi.mocked(readLatestTaskView).mockImplementation(async ({ taskRunId }) =>
+ taskRunId === "run-active"
+ ? task("task_active", "completed")
+ : task("task_terminal", "completed"),
+ );
+
+ const result = await executeTaskSend({
+ action,
+ bundle: {} as CompiledBundle,
+ parentTurnId: "turn-2",
+ session,
+ });
+
+ expect(result.result).toMatchObject({
+ isError: true,
+ output: { message: expect.stringContaining("AGENT_BUSY") },
+ });
+ expect(beginDelegatedTask).not.toHaveBeenCalled();
+ expect(dispatchToTaskAgentAddress).not.toHaveBeenCalled();
+ });
+
+ it("persists the continuation task before an ambiguous delivery", async () => {
+ const current = createSession();
+ const persisted = createSession(true, "turn-2");
+ vi.mocked(readLatestTaskView).mockResolvedValue(task("task_terminal", "completed"));
+ vi.mocked(beginDelegatedTask).mockResolvedValue({
+ taskInboxToken: "task-token-new",
+ createdByTurnId: "turn-2",
+ metadata,
+ operationId: "operation-new",
+ taskId: "task_active",
+ taskRunId: "run-active",
+ });
+ vi.mocked(settleDelegatedDispatch).mockResolvedValue({
+ receipt: {} as never,
+ session: persisted,
+ });
+ vi.mocked(dispatchToTaskAgentAddress).mockResolvedValue({
+ deliveryAmbiguous: true,
+ kind: "error",
+ result: {
+ callId: action.callId,
+ isError: true,
+ kind: "subagent-result",
+ origin: "dispatch",
+ output: { code: "AGENT_UNREACHABLE", message: "response lost" },
+ subagentName: "research",
+ },
+ session: persisted,
+ });
+
+ const result = await executeTaskSend({
+ action,
+ bundle: {} as CompiledBundle,
+ parentTurnId: "turn-2",
+ session: current,
+ });
+
+ expect(vi.mocked(settleDelegatedDispatch).mock.invocationCallOrder[0]).toBeLessThan(
+ vi.mocked(dispatchToTaskAgentAddress).mock.invocationCallOrder[0] ?? 0,
+ );
+ expect(dispatchToTaskAgentAddress).toHaveBeenCalledWith(
+ expect.objectContaining({ currentSession: persisted }),
+ );
+ expect(result.result).toMatchObject({ isError: true, output: { taskId: "task_active" } });
+ expect(result.session).toBe(persisted);
+ expect(failDelegatedDispatch).not.toHaveBeenCalled();
+ });
+
+ it("fails a persisted continuation after a definitive remote rejection", async () => {
+ const current = createSession();
+ const persisted = createSession(true, "turn-2");
+ vi.mocked(readLatestTaskView).mockResolvedValue(task("task_terminal", "completed"));
+ vi.mocked(beginDelegatedTask).mockResolvedValue({
+ taskInboxToken: "task-token-new",
+ createdByTurnId: "turn-2",
+ metadata,
+ operationId: "operation-new",
+ taskId: "task_active",
+ taskRunId: "run-active",
+ });
+ vi.mocked(settleDelegatedDispatch).mockResolvedValue({
+ receipt: {} as never,
+ session: persisted,
+ });
+ vi.mocked(dispatchToTaskAgentAddress).mockResolvedValue({
+ deliveryAmbiguous: false,
+ kind: "error",
+ result: {
+ callId: action.callId,
+ isError: true,
+ kind: "subagent-result",
+ origin: "dispatch",
+ output: { code: "AGENT_UNREACHABLE", message: "HTTP 401" },
+ subagentName: "research",
+ },
+ session: persisted,
+ });
+
+ await executeTaskSend({
+ action,
+ bundle: {} as CompiledBundle,
+ parentTurnId: "turn-2",
+ session: current,
+ });
+
+ expect(failDelegatedDispatch).toHaveBeenCalledWith({
+ error: { code: "AGENT_UNREACHABLE", message: "HTTP 401" },
+ task: expect.objectContaining({ taskId: "task_active" }),
+ });
+ });
+});
diff --git a/packages/eve/src/execution/tasks/parent/send.ts b/packages/eve/src/execution/tasks/parent/send.ts
new file mode 100644
index 000000000..4b865c871
--- /dev/null
+++ b/packages/eve/src/execution/tasks/parent/send.ts
@@ -0,0 +1,219 @@
+import {
+ dispatchToTaskAgentAddress,
+ type RuntimeAgentHandleAction,
+ type RuntimeSession,
+} from "#execution/agent-handle-dispatch.js";
+import {
+ createTaskControlError,
+ createUnknownTasksError,
+ findActiveTaskForAgent,
+ findTaskAgentAddress,
+ readTaskView,
+} from "#execution/tasks/parent/control-shared.js";
+import {
+ beginDelegatedTask,
+ type DelegatedTask,
+ failDelegatedDispatch,
+ settleDelegatedDispatch,
+} from "#execution/tasks/parent/delegate.js";
+import { AGENT_BUSY, AGENT_UNREACHABLE } from "#harness/agent-handle-errors.js";
+import type { RuntimeActionResult, RuntimeToolCallActionRequest } from "#runtime/actions/types.js";
+import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
+import { findSessionTaskEntry } from "#tasks/session-index.js";
+import type { TaskView } from "#tasks/types.js";
+
+/**
+ * Routes one `task_send`:
+ *
+ * - `working` tasks are busy — the send surfaces `AGENT_BUSY` instead
+ * of queueing (settled decision; queueing is the reversible follow-up);
+ * - `input_required` tasks reject model-authored sends; clients answer
+ * them through the parent channel's direct HITL route;
+ * - terminal tasks accept a `message` follow-up, which starts a new
+ * task bound to the same child session and returns its receipt.
+ */
+export async function executeTaskSend(input: {
+ readonly action: RuntimeToolCallActionRequest;
+ readonly bundle: CompiledBundle;
+ readonly parentStepIndex?: number;
+ readonly parentTurnId: string;
+ readonly session: RuntimeSession;
+}): Promise<{
+ readonly result: RuntimeActionResult;
+ readonly session: RuntimeSession;
+ readonly pendingTask?: DelegatedTask;
+}> {
+ const { action, session } = input;
+ const send = readTaskSendInput(action.input);
+ if (send.kind === "invalid") {
+ return { result: createTaskControlError(action, send.message), session };
+ }
+
+ const entry = findSessionTaskEntry(session.state, send.taskId);
+ if (entry === undefined) {
+ return { result: createUnknownTasksError(action, [send.taskId]), session };
+ }
+
+ const view = await readTaskView(entry);
+
+ if (view.status === "working") {
+ return {
+ result: createTaskControlError(
+ action,
+ `${AGENT_BUSY}: task "${view.taskId}" is still working. Let it finish, or cancel it first.`,
+ ),
+ session,
+ };
+ }
+
+ if (view.status === "input_required") {
+ return {
+ result: createTaskControlError(
+ action,
+ `Task "${view.taskId}" is waiting on input; the human must answer through the parent channel.`,
+ ),
+ session,
+ };
+ }
+
+ return followUpTerminalTask({
+ action,
+ bundle: input.bundle,
+ message: send.message,
+ parentStepIndex: input.parentStepIndex,
+ parentTurnId: input.parentTurnId,
+ session,
+ view,
+ });
+}
+
+async function followUpTerminalTask(input: {
+ readonly action: RuntimeToolCallActionRequest;
+ readonly bundle: CompiledBundle;
+ readonly message: string;
+ readonly parentStepIndex?: number;
+ readonly parentTurnId: string;
+ readonly session: RuntimeSession;
+ readonly view: TaskView;
+}): Promise<{
+ readonly result: RuntimeActionResult;
+ readonly session: RuntimeSession;
+ readonly pendingTask?: DelegatedTask;
+}> {
+ const { action, view } = input;
+ const active = await findActiveTaskForAgent(
+ input.session,
+ view.metadata.agentId,
+ input.parentTurnId,
+ input.parentStepIndex,
+ );
+ if (active !== undefined) {
+ return {
+ result: createTaskControlError(
+ action,
+ `${AGENT_BUSY}: agent "${view.metadata.agentId}" is busy with task "${active.view.taskId}" (${active.view.status}).`,
+ ),
+ session: input.session,
+ };
+ }
+ const handle = findTaskAgentAddress(input.session, view.metadata.agentId);
+ if (handle === undefined) {
+ return {
+ result: createTaskControlError(
+ action,
+ `${AGENT_UNREACHABLE}: task "${view.taskId}"'s agent is no longer addressable.`,
+ ),
+ session: input.session,
+ };
+ }
+ const continuation: RuntimeAgentHandleAction =
+ handle.address.kind === "agent/remote"
+ ? {
+ callId: action.callId,
+ description: "",
+ input: { message: input.message },
+ kind: "remote-agent-call",
+ name: handle.identity.name,
+ nodeId: handle.identity.nodeId,
+ remoteAgentName: handle.identity.name,
+ }
+ : {
+ callId: action.callId,
+ description: "",
+ input: { message: input.message },
+ kind: "subagent-call",
+ name: handle.identity.name,
+ nodeId: handle.identity.nodeId,
+ subagentName: handle.identity.name,
+ };
+
+ const task = await beginDelegatedTask({
+ agentId: handle.identity.id,
+ callId: action.callId,
+ mode: handle.address.kind === "agent/remote" ? "remote" : "local",
+ name: handle.identity.name,
+ parentSessionId: input.session.sessionId,
+ parentStepIndex: input.parentStepIndex,
+ parentTurnId: input.parentTurnId,
+ session: input.session,
+ });
+ // Persist the task in the parent session before the ambiguous delivery side effect.
+ const persisted = await settleDelegatedDispatch({
+ callId: action.callId,
+ session: input.session,
+ subagentName: handle.identity.name,
+ task,
+ });
+ const outcome = await dispatchToTaskAgentAddress({
+ action: continuation,
+ agentId: handle.identity.id,
+ bundle: input.bundle,
+ currentSession: persisted.session,
+ parentToken: task.taskInboxToken,
+ });
+ if (outcome.kind === "error") {
+ if (outcome.deliveryAmbiguous !== true) {
+ await failDelegatedDispatch({ error: outcome.result.output, task });
+ }
+ return {
+ result: {
+ callId: action.callId,
+ isError: true,
+ kind: "tool-result",
+ output: { error: outcome.result.output, taskId: task.taskId },
+ toolName: action.toolName,
+ },
+ session: outcome.session,
+ pendingTask: task,
+ };
+ }
+
+ return {
+ result: {
+ callId: action.callId,
+ kind: "tool-result",
+ output: { agentId: task.metadata.agentId, status: "working", taskId: task.taskId },
+ toolName: action.toolName,
+ },
+ session: outcome.session,
+ pendingTask: task,
+ };
+}
+
+type TaskSendInput =
+ | { readonly kind: "invalid"; readonly message: string }
+ | { readonly kind: "send"; readonly message: string; readonly taskId: string };
+
+function readTaskSendInput(input: Record<string, unknown>): TaskSendInput {
+ const taskId =
+ typeof input.taskId === "string" && input.taskId.trim() !== "" ? input.taskId : undefined;
+ if (taskId === undefined) {
+ return { kind: "invalid", message: "Provide the `taskId` from a task receipt." };
+ }
+ const message =
+ typeof input.message === "string" && input.message.trim() !== "" ? input.message : undefined;
+ if (message !== undefined) {
+ return { kind: "send", message, taskId };
+ }
+ return { kind: "invalid", message: "Provide a non-empty `message`." };
+}
diff --git a/packages/eve/src/execution/tasks/workflow-target.ts b/packages/eve/src/execution/tasks/workflow-target.ts
new file mode 100644
index 000000000..ee45b0d18
--- /dev/null
+++ b/packages/eve/src/execution/tasks/workflow-target.ts
@@ -0,0 +1,23 @@
+import {
+ EntityConflictError,
+ HookNotFoundError,
+ RunExpiredError,
+ WorkflowRunNotFoundError,
+} from "#compiled/@workflow/errors/index.js";
+
+import { walkCauseChain } from "#shared/errors.js";
+
+/** Whether a workflow hook or run can no longer accept task traffic. */
+export function isTaskWorkflowTargetGone(error: unknown): boolean {
+ for (const candidate of walkCauseChain(error)) {
+ if (
+ HookNotFoundError.is(candidate) ||
+ WorkflowRunNotFoundError.is(candidate) ||
+ RunExpiredError.is(candidate) ||
+ EntityConflictError.is(candidate)
+ ) {
+ return true;
+ }
+ }
+ return false;
+}
diff --git a/packages/eve/src/execution/terminate-child-sessions-step.test.ts b/packages/eve/src/execution/terminate-child-sessions-step.test.ts
index 13bc23c96..abda9a959 100644
--- a/packages/eve/src/execution/terminate-child-sessions-step.test.ts
+++ b/packages/eve/src/execution/terminate-child-sessions-step.test.ts
@@ -3,12 +3,36 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { AGENT_HANDLES_STATE_KEY, type AgentHandle } from "#harness/handles/store.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
import { terminateChildSessionsStep } from "#execution/terminate-child-sessions-step.js";
+import { SESSION_TASKS_STATE_KEY, type SessionTaskIndexEntry } from "#tasks/session-index.js";
-const { cancelRunMock, getWorldMock } = vi.hoisted(() => ({
+const {
+ cancelOwnedTaskMock,
+ cancelRunMock,
+ deserializeContextMock,
+ getWorldMock,
+ hydrateDurableSessionMock,
+ resolveEffectiveAgentRuntimeMock,
+} = vi.hoisted(() => ({
+ cancelOwnedTaskMock: vi.fn(),
cancelRunMock: vi.fn(),
+ deserializeContextMock: vi.fn(),
getWorldMock: vi.fn(),
+ hydrateDurableSessionMock: vi.fn(),
+ resolveEffectiveAgentRuntimeMock: vi.fn(),
}));
+vi.mock("#context/serialize.js", () => ({
+ deserializeContext: deserializeContextMock,
+}));
+vi.mock("#execution/effective-agent-config.js", () => ({
+ resolveEffectiveAgentRuntime: resolveEffectiveAgentRuntimeMock,
+}));
+vi.mock("#execution/session.js", () => ({
+ hydrateDurableSession: hydrateDurableSessionMock,
+}));
+vi.mock("#execution/tasks/parent/dispatch.js", () => ({
+ cancelOwnedTask: cancelOwnedTaskMock,
+}));
vi.mock("#internal/workflow/runtime.js", () => ({
cancelRun: cancelRunMock,
getWorld: getWorldMock,
@@ -16,10 +40,18 @@ vi.mock("#internal/workflow/runtime.js", () => ({
describe("terminateChildSessionsStep", () => {
beforeEach(() => {
+ cancelOwnedTaskMock.mockReset();
+ cancelOwnedTaskMock.mockResolvedValue(undefined);
cancelRunMock.mockReset();
cancelRunMock.mockResolvedValue(undefined);
+ deserializeContextMock.mockReset();
+ deserializeContextMock.mockResolvedValue({ require: vi.fn().mockReturnValue("bundle") });
getWorldMock.mockReset();
getWorldMock.mockResolvedValue("world");
+ hydrateDurableSessionMock.mockReset();
+ hydrateDurableSessionMock.mockReturnValue("runtime-session");
+ resolveEffectiveAgentRuntimeMock.mockReset();
+ resolveEffectiveAgentRuntimeMock.mockReturnValue({ turnAgent: "turn-agent" });
});
it("terminates running and parked local/self children", async () => {
@@ -67,6 +99,87 @@ describe("terminateChildSessionsStep", () => {
});
});
+ it("settles every indexed task cancellation before terminating local children", async () => {
+ const firstCancellation = createDeferred();
+ const secondCancellation = createDeferred();
+ const order: string[] = [];
+ cancelOwnedTaskMock
+ .mockImplementationOnce(async () => {
+ await firstCancellation.promise;
+ order.push("task-1-settled");
+ })
+ .mockImplementationOnce(async () => {
+ await secondCancellation.promise;
+ order.push("task-2-settled");
+ });
+ cancelRunMock.mockImplementation(async () => {
+ order.push("child-cancelled");
+ });
+
+ const termination = terminateChildSessionsStep({
+ serializedContext: { context: "serialized" },
+ sessionState: makeSessionState(
+ [runningHandle({ id: "ag_local:1", kind: "agent/local", sessionId: "session-local" })],
+ [indexedTask("task-1"), indexedTask("task-2")],
+ ),
+ });
+
+ await vi.waitFor(() => expect(cancelOwnedTaskMock).toHaveBeenCalledTimes(1));
+ expect(cancelRunMock).not.toHaveBeenCalled();
+
+ firstCancellation.resolve();
+ await vi.waitFor(() => expect(cancelOwnedTaskMock).toHaveBeenCalledTimes(2));
+ expect(order).toEqual(["task-1-settled"]);
+ expect(cancelRunMock).not.toHaveBeenCalled();
+
+ secondCancellation.resolve();
+ await termination;
+
+ expect(order).toEqual(["task-1-settled", "task-2-settled", "child-cancelled"]);
+ expect(cancelRunMock).toHaveBeenCalledExactlyOnceWith("world", "session-local", {
+ cancelReason: "Parent session ended",
+ });
+ });
+
+ it("continues finalization after an indexed task cancellation fails", async () => {
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ cancelOwnedTaskMock
+ .mockRejectedValueOnce(new Error("task cancellation unavailable"))
+ .mockResolvedValueOnce(undefined);
+
+ try {
+ await expect(
+ terminateChildSessionsStep({
+ serializedContext: { context: "serialized" },
+ sessionState: makeSessionState(
+ [
+ parkedHandle({
+ id: "ag_local:1",
+ kind: "agent/local",
+ sessionId: "session-local",
+ }),
+ ],
+ [indexedTask("task-1"), indexedTask("task-2")],
+ ),
+ }),
+ ).resolves.toBeUndefined();
+
+ expect(cancelOwnedTaskMock).toHaveBeenCalledTimes(2);
+ expect(cancelRunMock).toHaveBeenCalledExactlyOnceWith("world", "session-local", {
+ cancelReason: "Parent session ended",
+ });
+ expect(errorSpy).toHaveBeenCalledWith(
+ "[eve:execution.terminate-child-sessions] failed to cancel task during parent finalization",
+ expect.objectContaining({
+ parentSessionId: "parent-session",
+ taskId: "task-1",
+ }),
+ );
+ } finally {
+ errorSpy.mockRestore();
+ }
+ });
+
it("continues terminating children after one termination fails", async () => {
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
cancelRunMock
@@ -163,7 +276,26 @@ function startingHandle(input: {
};
}
-function makeSessionState(handles: readonly AgentHandle[]): DurableSessionState {
+function indexedTask(taskId: string): SessionTaskIndexEntry {
+ return {
+ taskInboxToken: `${taskId}:inbox`,
+ createdByTurnId: "turn-1",
+ metadata: {
+ agentId: "ag_local:1",
+ kind: "subagent",
+ mode: "local",
+ name: "research",
+ },
+ operationId: `op-${taskId}`,
+ taskId,
+ taskRunId: `run-${taskId}`,
+ };
+}
+
+function makeSessionState(
+ handles: readonly AgentHandle[],
+ tasks: readonly SessionTaskIndexEntry[] = [],
+): DurableSessionState {
return {
continuationToken: "parent-token",
emissionState: {
@@ -180,12 +312,21 @@ function makeSessionState(handles: readonly AgentHandle[]): DurableSessionState
continuationToken: "parent-token",
history: [],
sessionId: "parent-session",
- state: {
- [AGENT_HANDLES_STATE_KEY]: { handles },
- },
+ state:
+ tasks.length === 0
+ ? { [AGENT_HANDLES_STATE_KEY]: { handles } }
+ : { [AGENT_HANDLES_STATE_KEY]: { handles }, [SESSION_TASKS_STATE_KEY]: { tasks } },
},
version: 1,
},
version: 1,
};
}
+
+function createDeferred(): { readonly promise: Promise<void>; resolve(): void } {
+ let resolve!: () => void;
+ const promise = new Promise<void>((next) => {
+ resolve = next;
+ });
+ return { promise, resolve };
+}
diff --git a/packages/eve/src/execution/terminate-child-sessions-step.ts b/packages/eve/src/execution/terminate-child-sessions-step.ts
index f979c018d..34452427f 100644
--- a/packages/eve/src/execution/terminate-child-sessions-step.ts
+++ b/packages/eve/src/execution/terminate-child-sessions-step.ts
@@ -1,7 +1,13 @@
+import { deserializeContext } from "#context/serialize.js";
import { readDurableSession, type DurableSessionState } from "#execution/durable-session-store.js";
+import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
+import { hydrateDurableSession } from "#execution/session.js";
+import { cancelOwnedTask } from "#execution/tasks/parent/dispatch.js";
import { getAgentHandleStore, type AgentHandle } from "#harness/handles/store.js";
import { createLogger, logError } from "#internal/logging.js";
import { cancelRun, getWorld } from "#internal/workflow/runtime.js";
+import { getSessionTaskIndex } from "#tasks/session-index.js";
+import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
const log = createLogger("execution.terminate-child-sessions");
@@ -17,6 +23,7 @@ const log = createLogger("execution.terminate-child-sessions");
* remote-termination protocol exists.
*/
export async function terminateChildSessionsStep(input: {
+ readonly serializedContext?: Record<string, unknown>;
readonly sessionState: DurableSessionState;
}): Promise<void> {
"use step";
@@ -31,6 +38,35 @@ export async function terminateChildSessionsStep(input: {
return;
}
+ // Cooperatively cancel live tasks first: their runs are the single
+ // writers for task state, and committing `cancelled` before the child
+ // terminations below means no child termination can race a completion
+ // into an ended parent. Already-terminal tasks report `unreachable`,
+ // which is the expected no-op.
+ const taskEntries = readSessionTaskIndex(session.state, session.sessionId);
+ if (taskEntries.length > 0) {
+ if (input.serializedContext === undefined) {
+ throw new Error("Task finalization requires serialized runtime context.");
+ }
+ const ctx = await deserializeContext(input.serializedContext);
+ const bundle = ctx.require(BundleKey);
+ const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);
+ const runtimeSession = hydrateDurableSession({
+ durable: session,
+ turnAgent: effectiveAgent.turnAgent,
+ });
+ for (const entry of taskEntries) {
+ try {
+ await cancelOwnedTask({ bundle, entry, session: runtimeSession });
+ } catch (error) {
+ logError(log, "failed to cancel task during parent finalization", error, {
+ parentSessionId: session.sessionId,
+ taskId: entry.taskId,
+ });
+ }
+ }
+ }
+
const handles = (getAgentHandleStore(session.state)?.handles ?? []).filter(isLocalChildHandle);
if (handles.length === 0) {
return;
@@ -64,3 +100,17 @@ function isLocalChildHandle(handle: AgentHandle): boolean {
const kind = handle.phase === "starting" ? handle.target.kind : handle.address.kind;
return kind === "agent/local" || kind === "agent/self";
}
+
+function readSessionTaskIndex(
+ state: Parameters<typeof getSessionTaskIndex>[0],
+ parentSessionId: string,
+): ReturnType<typeof getSessionTaskIndex> {
+ try {
+ return getSessionTaskIndex(state);
+ } catch (error) {
+ logError(log, "failed to read the task index during parent finalization", error, {
+ parentSessionId,
+ });
+ return [];
+ }
+}
diff --git a/packages/eve/src/execution/turn-cancellation.integration.test.ts b/packages/eve/src/execution/turn-cancellation.integration.test.ts
index a6013cf30..bc676ff94 100644
--- a/packages/eve/src/execution/turn-cancellation.integration.test.ts
+++ b/packages/eve/src/execution/turn-cancellation.integration.test.ts
@@ -449,9 +449,12 @@ describe("turn cancellation integration", () => {
expectNoFailureEvents(cancelledTurn);
expect(fixture.toolAborts()).toBe(1);
+ const started = filterEventsByType(cancelledTurn, "turn.started")[0];
+ if (started === undefined) throw new Error("Expected the cancelled turn to have started.");
+
// The stable inbox remains owned while the session is parked, so a
- // duplicate cancellation is durably accepted and consumed as a no-op.
- const duplicate = await cancelViaRoute(run.runId);
+ // guarded duplicate is harmless even if another alias resolves first.
+ const duplicate = await cancelViaRoute(run.runId, { turnId: started.data.turnId });
await expectCancelResponse(duplicate, { sessionId: run.runId, status: "accepted" });
await waitForHook({ runId: run.runId }, { token: continuationToken });
diff --git a/packages/eve/src/execution/turn-control-receiver.test.ts b/packages/eve/src/execution/turn-control-receiver.test.ts
index cd1548fce..76d4a5b3c 100644
--- a/packages/eve/src/execution/turn-control-receiver.test.ts
+++ b/packages/eve/src/execution/turn-control-receiver.test.ts
@@ -146,50 +146,78 @@ describe("TurnControlReceiver", () => {
expect(bufferedSessionControls).toEqual(["clear", "compact", "expired"]);
});
- it("buffers a steering message before cancelling the active turn", async () => {
+ it("consumes a replayed task delivery only once", async () => {
installControlHook([parkResult()], true);
const bufferedDeliveries: DeliverHookPayload[] = [];
- vi.mocked(forwardTurnCancellationStep).mockImplementation(async () => {
- expect(bufferedDeliveries).toEqual([
- expect.objectContaining({
- payloads: [{ message: "replace this turn" }],
- turnPolicy: "steer",
- }),
- ]);
- return true;
+ const caller = {
+ callId: "call-task",
+ replyTo: { kind: "hook" as const, token: "task-token" },
+ subagentName: "research",
+ taskId: "task-1",
+ };
+
+ await runReceiver(bufferedDeliveries, {
+ commandInbox: createCommandInbox([
+ { caller, kind: "send", payload: { message: "once" } },
+ { caller, kind: "send", payload: { message: "duplicate" } },
+ ]),
+ seenTaskDeliveries: new Set(),
});
+ expect(bufferedDeliveries.map((delivery) => delivery.payloads[0]?.message)).toEqual(["once"]);
+ });
+
+ it("deduplicates a replayed task response without dropping a different partial response", async () => {
+ installControlHook([parkResult()], true);
+ const bufferedDeliveries: DeliverHookPayload[] = [];
+
await runReceiver(bufferedDeliveries, {
commandInbox: createCommandInbox([
{
kind: "send",
- payload: { message: "replace this turn" },
- turnPolicy: "steer",
+ payload: { inputResponses: [{ requestId: "q1" }] },
+ taskDeliveryId: "task-1:q1",
+ },
+ {
+ kind: "send",
+ payload: { inputResponses: [{ requestId: "q1" }] },
+ taskDeliveryId: "task-1:q1",
+ },
+ {
+ kind: "send",
+ payload: { inputResponses: [{ requestId: "q2" }] },
+ taskDeliveryId: "task-1:q2",
},
]),
+ seenTaskDeliveries: new Set(),
});
- expect(forwardTurnCancellationStep).toHaveBeenCalledWith({
- payload: {},
- token: "turn-control:cancel",
- });
+ expect(
+ bufferedDeliveries.map((delivery) => delivery.payloads[0]?.inputResponses?.[0]?.requestId),
+ ).toEqual(["q1", "q2"]);
});
- it("does not cancel for queued messages or input responses", async () => {
+ it("discards queued deliveries when their task is cancelled", async () => {
installControlHook([parkResult()], true);
+ const bufferedDeliveries: DeliverHookPayload[] = [];
- await runReceiver([], {
+ await runReceiver(bufferedDeliveries, {
commandInbox: createCommandInbox([
- { kind: "send", payload: { message: "later" }, turnPolicy: "queue" },
{
kind: "send",
- payload: { inputResponses: [{ optionId: "yes", requestId: "input-1" }] },
- turnPolicy: "steer",
+ payload: { inputResponses: [{ requestId: "q1" }] },
+ taskDeliveryId: "task-1:q1",
},
+ { kind: "cancel", taskId: "task-1", turnId: "turn_3" },
]),
+ seenTaskDeliveries: new Set(),
});
- expect(forwardTurnCancellationStep).not.toHaveBeenCalled();
+ expect(bufferedDeliveries).toEqual([]);
+ expect(forwardTurnCancellationStep).toHaveBeenCalledWith({
+ payload: {},
+ token: "turn-control:cancel",
+ });
});
it("forwards cancel and reset through the active turn's private hook", async () => {
@@ -222,12 +250,15 @@ function runReceiver(
options: {
readonly bufferedSessionControls?: Array<"clear" | "compact" | "expired" | "reset">;
readonly commandInbox?: SessionCommandInbox;
+ readonly seenTaskDeliveries?: Set<string>;
} = {},
): ReturnType<TurnControlReceiver["waitForAction"]> {
const receiver = new TurnControlReceiver({
bufferedDeliveries,
bufferedSessionControls: options.bufferedSessionControls ?? [],
commandInbox: options.commandInbox ?? createCommandInbox(),
+ expectedTurnId: "turn_0",
+ seenTaskDeliveries: options.seenTaskDeliveries,
token: "turn-control",
});
return receiver.waitForAction().finally(() => receiver.dispose());
diff --git a/packages/eve/src/execution/turn-control-receiver.ts b/packages/eve/src/execution/turn-control-receiver.ts
index a264dec52..475a1be54 100644
--- a/packages/eve/src/execution/turn-control-receiver.ts
+++ b/packages/eve/src/execution/turn-control-receiver.ts
@@ -1,6 +1,6 @@
import { createHook, type Hook } from "#compiled/@workflow/core/index.js";
-import type { DeliverHookPayload } from "#channel/types.js";
+import type { DeliverHookPayload, SessionCommand } from "#channel/types.js";
import { forwardTurnCancellationStep } from "#execution/forward-turn-cancellation-step.js";
import type { TurnControlPayload } from "#execution/turn-control-protocol.js";
import { forwardTurnDeliveryStep } from "#execution/forward-turn-delivery-step.js";
@@ -22,19 +22,28 @@ export class TurnControlReceiver {
private readonly commandInbox: SessionCommandInbox;
private readonly control: Hook<TurnControlPayload>;
private readonly controlIterator: AsyncIterator<TurnControlPayload>;
+ private readonly expectedTurnId: string;
+ private readonly cancelledTaskIds: Set<string>;
+ private readonly seenTaskDeliveries: Set<string>;
private pendingControl: Promise<IteratorResult<TurnControlPayload>> | null = null;
constructor(input: {
readonly bufferedDeliveries: DeliverHookPayload[];
readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;
+ readonly cancelledTaskIds?: Set<string>;
readonly commandInbox: SessionCommandInbox;
+ readonly expectedTurnId: string;
+ readonly seenTaskDeliveries?: Set<string>;
readonly token: string;
}) {
this.bufferedDeliveries = input.bufferedDeliveries;
this.bufferedSessionControls = input.bufferedSessionControls;
+ this.cancelledTaskIds = input.cancelledTaskIds ?? new Set();
this.commandInbox = input.commandInbox;
+ this.seenTaskDeliveries = input.seenTaskDeliveries ?? new Set();
this.control = createHook<TurnControlPayload>({ token: input.token });
this.controlIterator = this.control[Symbol.asyncIterator]();
+ this.expectedTurnId = input.expectedTurnId;
}
/** Token passed to the turn workflow so it can publish control messages. */
@@ -73,10 +82,12 @@ export class TurnControlReceiver {
command: SessionInboxPayload,
): Promise<TurnDriverAction | undefined> {
if (command.kind === "deliver") {
+ if (!this.acceptTaskDelivery(command)) return undefined;
await this.bufferDelivery(command);
return undefined;
}
if (command.kind === "send") {
+ if (!this.acceptTaskDelivery(command)) return undefined;
await this.bufferDelivery(sendCommandToDelivery(command));
return undefined;
}
@@ -92,8 +103,15 @@ export class TurnControlReceiver {
return undefined;
}
if (command.kind === "cancel") {
+ if (command.taskId !== undefined) this.discardTaskDeliveries(command.taskId);
+ const turnId =
+ command.taskId !== undefined &&
+ command.turnId !== undefined &&
+ command.turnId !== this.expectedTurnId
+ ? undefined
+ : command.turnId;
await forwardTurnCancellationStep({
- payload: command.turnId === undefined ? {} : { turnId: command.turnId },
+ payload: turnId === undefined ? {} : { turnId },
token: turnCancellationHookToken(this.control.token),
});
return undefined;
@@ -123,7 +141,9 @@ export class TurnControlReceiver {
payload: Extract<TurnControlPayload, { readonly kind: "turn-result" }>,
): void {
if (payload.bufferedDeliveries !== undefined) {
- this.bufferedDeliveries.unshift(...payload.bufferedDeliveries);
+ this.bufferedDeliveries.unshift(
+ ...payload.bufferedDeliveries.filter((delivery) => !this.shouldDiscard(delivery)),
+ );
}
}
@@ -210,11 +230,18 @@ export class TurnControlReceiver {
}
this.commandInbox.consumeNext();
- if (winner.value.value.kind === "deliver" || winner.value.value.kind === "send") {
- const candidate =
- winner.value.value.kind === "deliver"
- ? winner.value.value
- : sendCommandToDelivery(winner.value.value);
+ if (winner.value.value.kind === "deliver") {
+ if (!this.acceptTaskDelivery(winner.value.value)) continue;
+ if (deliveryHasMessage(winner.value.value)) {
+ await this.bufferDelivery(winner.value.value);
+ } else {
+ delivery = winner.value.value;
+ }
+ continue;
+ }
+ if (winner.value.value.kind === "send") {
+ if (!this.acceptTaskDelivery(winner.value.value)) continue;
+ const candidate = sendCommandToDelivery(winner.value.value);
if (deliveryHasMessage(candidate)) {
await this.bufferDelivery(candidate);
} else {
@@ -266,7 +293,7 @@ export class TurnControlReceiver {
if (winner.kind === "command") {
const terminal = await this.handleSessionCommand(winner.command);
if (terminal !== undefined) {
- this.bufferedDeliveries.unshift(outstanding);
+ if (!this.shouldDiscard(outstanding)) this.bufferedDeliveries.unshift(outstanding);
return terminal;
}
continue;
@@ -279,18 +306,54 @@ export class TurnControlReceiver {
}
if (payload.kind === "turn-delivery-cancelled" && payload.requestId === requestId) {
- this.bufferedDeliveries.unshift(outstanding);
+ if (!this.shouldDiscard(outstanding)) this.bufferedDeliveries.unshift(outstanding);
return undefined;
}
if (payload.kind === "turn-result") {
- this.bufferedDeliveries.unshift(outstanding);
+ if (!this.shouldDiscard(outstanding)) this.bufferedDeliveries.unshift(outstanding);
}
const terminal = this.readTerminalControl(payload);
if (terminal !== undefined) return terminal;
}
}
+
+ private acceptTaskDelivery(
+ command: DeliverHookPayload | Extract<SessionCommand, { readonly kind: "send" }>,
+ ): boolean {
+ const deliveryId = command.taskDeliveryId ?? command.caller?.taskId;
+ if (deliveryId === undefined) return true;
+ if (this.originatesFromCancelledTask(deliveryId)) return false;
+ if (this.seenTaskDeliveries.has(deliveryId)) return false;
+ this.seenTaskDeliveries.add(deliveryId);
+ return true;
+ }
+
+ private discardTaskDeliveries(taskId: string): void {
+ this.cancelledTaskIds.add(taskId);
+ const kept = this.bufferedDeliveries.filter((delivery) => !this.shouldDiscard(delivery));
+ this.bufferedDeliveries.splice(0, this.bufferedDeliveries.length, ...kept);
+ }
+
+ private originatesFromCancelledTask(deliveryId: string): boolean {
+ return [...this.cancelledTaskIds].some((taskId) =>
+ deliveryOriginatesFromTask(deliveryId, taskId),
+ );
+ }
+
+ private shouldDiscard(delivery: DeliverHookPayload): boolean {
+ const deliveryId = delivery.taskDeliveryId ?? delivery.caller?.taskId;
+ return deliveryId !== undefined && this.originatesFromCancelledTask(deliveryId);
+ }
+}
+
+/**
+ * Task delivery ids are either a bare task id (the `caller.taskId` fallback)
+ * or `${taskId}:${discriminator}` as minted in tasks/child/steps.ts.
+ */
+function deliveryOriginatesFromTask(deliveryId: string, taskId: string): boolean {
+ return deliveryId === taskId || deliveryId.startsWith(`${taskId}:`);
}
function deliveryHasMessage(delivery: DeliverHookPayload): boolean {
diff --git a/packages/eve/src/execution/turn-dispatch.ts b/packages/eve/src/execution/turn-dispatch.ts
index 7313d6447..545dcc3e8 100644
--- a/packages/eve/src/execution/turn-dispatch.ts
+++ b/packages/eve/src/execution/turn-dispatch.ts
@@ -5,6 +5,7 @@ import type { DurableSessionState } from "#execution/durable-session-store.js";
import type { SessionCommandInbox } from "#execution/session-command-inbox.js";
import type { TurnDriverAction } from "#execution/turn-control-receiver.js";
import type { RunMode } from "#shared/run-mode.js";
+import { activeTurnId } from "#harness/active-turn-id.js";
/** One settled turn: its terminal driver action plus deferred hook cleanup. */
export interface DispatchedTurn {
@@ -25,18 +26,23 @@ export async function dispatchAndAwaitTurn(input: {
readonly bufferedDeliveries: DeliverHookPayload[];
readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;
readonly capabilities?: SessionCapabilities;
+ readonly cancelledTaskIds?: Set<string>;
readonly controlToken: string;
readonly delivery: HookPayload;
readonly commandInbox: SessionCommandInbox;
readonly mode: RunMode;
readonly parentWritable: WritableStream<Uint8Array>;
readonly serializedContext: Record<string, unknown>;
+ readonly seenTaskDeliveries?: Set<string>;
readonly sessionState: DurableSessionState;
}): Promise<DispatchedTurn> {
const control = new TurnControlReceiver({
bufferedDeliveries: input.bufferedDeliveries,
bufferedSessionControls: input.bufferedSessionControls,
+ cancelledTaskIds: input.cancelledTaskIds,
commandInbox: input.commandInbox,
+ expectedTurnId: activeTurnId(input.sessionState.emissionState),
+ seenTaskDeliveries: input.seenTaskDeliveries ?? new Set(),
token: input.controlToken,
});
diff --git a/packages/eve/src/execution/turn-execution-cursor.ts b/packages/eve/src/execution/turn-execution-cursor.ts
index bec37131a..bdd082320 100644
--- a/packages/eve/src/execution/turn-execution-cursor.ts
+++ b/packages/eve/src/execution/turn-execution-cursor.ts
@@ -6,6 +6,7 @@ import type {
TurnStepInput,
TurnStepPayload,
} from "#execution/durable-session-migrations/turn-workflow.js";
+import { SessionStateCursor } from "#execution/session-state-cursor.js";
import type { SettledTurn } from "#harness/types.js";
import type { TokenUsage } from "#shared/token-usage.js";
@@ -31,12 +32,10 @@ type TurnTerminalAction =
};
/** Owns the mutable durable state cursor for one active turn workflow. */
-export class TurnExecutionCursor {
+export class TurnExecutionCursor extends SessionStateCursor {
readonly controlToken: string;
readonly parentWritable: WritableStream<Uint8Array>;
- private currentSerializedContext: Record<string, unknown>;
- private currentSessionState: DurableSessionState;
private lastReportedContinuationToken: string;
constructor(input: {
@@ -45,26 +44,15 @@ export class TurnExecutionCursor {
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
}) {
+ super({ serializedContext: input.serializedContext, sessionState: input.sessionState });
this.controlToken = input.controlToken;
- this.currentSerializedContext = input.serializedContext;
- this.currentSessionState = input.sessionState;
this.lastReportedContinuationToken = input.sessionState.continuationToken;
this.parentWritable = input.parentWritable;
}
- /** Latest serialized runtime context adopted by the active turn. */
- get serializedContext(): Record<string, unknown> {
- return this.currentSerializedContext;
- }
-
- /** Latest durable session state adopted by the active turn. */
- get sessionState(): DurableSessionState {
- return this.currentSessionState;
- }
-
/** Adopts a state transition and reports any continuation-token change once. */
async adopt(transition: TurnTransition): Promise<void> {
- this.setState(transition);
+ this.adoptState(transition);
const nextToken = transition.sessionState.continuationToken;
if (nextToken === "" || nextToken === this.lastReportedContinuationToken) return;
@@ -79,8 +67,8 @@ export class TurnExecutionCursor {
abortSignal,
input,
parentWritable: this.parentWritable,
- serializedContext: this.currentSerializedContext,
- sessionState: this.currentSessionState,
+ serializedContext: this.serializedContext,
+ sessionState: this.sessionState,
};
}
@@ -94,12 +82,12 @@ export class TurnExecutionCursor {
action: TurnTerminalAction,
bufferedDeliveries: readonly DeliverHookPayload[],
): Promise<void> {
- this.setState(transition);
+ this.adoptState(transition);
await this.send({
action: {
...action,
- serializedContext: this.currentSerializedContext,
- sessionState: this.currentSessionState,
+ serializedContext: this.serializedContext,
+ sessionState: this.sessionState,
},
bufferedDeliveries: bufferedDeliveries.length === 0 ? undefined : [...bufferedDeliveries],
kind: "turn-result",
@@ -110,9 +98,4 @@ export class TurnExecutionCursor {
async send(payload: TurnControlPayload): Promise<void> {
await sendTurnControlStep({ controlToken: this.controlToken, payload });
}
-
- private setState(transition: TurnTransition): void {
- this.currentSerializedContext = transition.serializedContext ?? this.currentSerializedContext;
- this.currentSessionState = transition.sessionState;
- }
}
diff --git a/packages/eve/src/execution/turn-workflow.test.ts b/packages/eve/src/execution/turn-workflow.test.ts
index 08f00e324..81c842d58 100644
--- a/packages/eve/src/execution/turn-workflow.test.ts
+++ b/packages/eve/src/execution/turn-workflow.test.ts
@@ -586,6 +586,7 @@ describe("turnWorkflow", () => {
sessionState: withRunningChildren(pendingState, [
{ callId: "call-1", sessionId: "child-session" },
]),
+ pendingTasks: [],
});
vi.mocked(turnStep)
.mockResolvedValueOnce({
@@ -658,11 +659,16 @@ describe("turnWorkflow", () => {
const pendingState = createSessionState({ continuationToken: "http:parent:turn" });
const adoptedState = createSessionState({ continuationToken: "http:parent:turn:adopted" });
let finishDispatch:
- | ((value: { results: readonly []; sessionState: DurableSessionState }) => void)
+ | ((value: {
+ results: readonly [];
+ sessionState: DurableSessionState;
+ pendingTasks: readonly [];
+ }) => void)
| undefined;
const dispatchResult = new Promise<{
results: readonly [];
sessionState: DurableSessionState;
+ pendingTasks: readonly [];
}>((resolve) => {
finishDispatch = resolve;
});
@@ -692,7 +698,7 @@ describe("turnWorkflow", () => {
await vi.waitFor(() => expect(dispatchRuntimeActionsStep).toHaveBeenCalledOnce());
expect(cancelDescendantTurnsStep).not.toHaveBeenCalled();
- finishDispatch?.({ results: [], sessionState: adoptedState });
+ finishDispatch?.({ results: [], sessionState: adoptedState, pendingTasks: [] });
await workflow;
expect(vi.mocked(turnStep).mock.calls[1]?.[0].abortSignal?.aborted).toBe(true);
@@ -722,6 +728,7 @@ describe("turnWorkflow", () => {
},
],
sessionState: pendingState,
+ pendingTasks: [],
});
vi.mocked(turnStep)
.mockResolvedValueOnce({
@@ -805,6 +812,7 @@ describe("turnWorkflow", () => {
vi.mocked(dispatchRuntimeActionsStep).mockResolvedValue({
results: [],
sessionState: withRunningChildren(pendingState, runningChildren),
+ pendingTasks: [],
});
vi.mocked(runProxySubagentEventStep).mockResolvedValue({
serializedContext: { state: "proxied" },
@@ -813,6 +821,7 @@ describe("turnWorkflow", () => {
vi.mocked(routeDeliverToChildren).mockResolvedValue({
kind: "continue",
remainder: undefined,
+ serializedContext: { state: "proxied" },
sessionState: retiredProxyState,
});
vi.mocked(turnStep)
@@ -887,6 +896,7 @@ describe("turnWorkflow", () => {
vi.mocked(dispatchRuntimeActionsStep).mockResolvedValue({
results: [],
sessionState: pendingState,
+ pendingTasks: [],
});
vi.mocked(runProxySubagentEventStep).mockResolvedValue({
serializedContext: { state: "proxied" },
@@ -894,6 +904,7 @@ describe("turnWorkflow", () => {
});
vi.mocked(routeDeliverToChildren).mockResolvedValue({
kind: "cancel-turn",
+ serializedContext: { state: "proxied" },
sessionState: retiredProxyState,
});
vi.mocked(turnStep).mockResolvedValueOnce({
@@ -989,6 +1000,7 @@ describe("turnWorkflow", () => {
vi.mocked(dispatchRuntimeActionsStep).mockResolvedValue({
results: [],
sessionState: dispatchedState,
+ pendingTasks: [],
});
vi.mocked(runProxySubagentEventStep)
.mockResolvedValueOnce({
@@ -1104,10 +1116,12 @@ describe("turnWorkflow", () => {
{ callId: "call-1", sessionId: "child-session-1" },
{ callId: "call-2", sessionId: "child-session-2" },
]),
+ pendingTasks: [],
});
vi.mocked(routeDeliverToChildren).mockResolvedValue({
kind: "continue",
remainder: undefined,
+ serializedContext: {},
sessionState: pendingState,
});
vi.mocked(turnStep)
diff --git a/packages/eve/src/execution/turn-workflow.ts b/packages/eve/src/execution/turn-workflow.ts
index 04f8fc064..928e2b7bf 100644
--- a/packages/eve/src/execution/turn-workflow.ts
+++ b/packages/eve/src/execution/turn-workflow.ts
@@ -10,6 +10,8 @@ import { preserveSerializedSessionDynamicModelSelection } from "#context/seriali
import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-step.js";
import { sendTurnControlStep, type TurnInboxPayload } from "#execution/turn-control-protocol.js";
import { dispatchRuntimeActionsStep } from "#execution/dispatch-runtime-actions-step.js";
+import { acknowledgeDelegatedTasksStep } from "#execution/tasks/parent/delegate.js";
+import { dispatchTaskStep } from "#execution/tasks/parent/dispatch-task-step.js";
import { dispatchWorkflowRuntimeActionsStep } from "#execution/dispatch-workflow-runtime-actions-step.js";
import {
migrateTurnWorkflowInput,
@@ -162,13 +164,20 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {
// A pending runtime-action batch (model-driven `park` or dynamic-workflow
// interrupt) is resolved in-line so the turn stays alive across the wait;
- // the two arms differ only in their dispatch path.
+ // the arms differ only in their dispatch path: the workflow adapter for
+ // interrupt-sourced batches, and the task-mode sibling when the agent
+ // runs `experimental.tasks`.
if (pendingActionKeys !== undefined) {
await cursor.adopt(result);
- const dispatch =
- result.action === "dispatch-workflow-runtime-actions"
- ? dispatchWorkflowRuntimeActionsStep
- : dispatchRuntimeActionsStep;
+ const hasPendingTasks = result.action === "park" && result.tasksEnabled;
+ let dispatch;
+ if (result.action === "dispatch-workflow-runtime-actions") {
+ dispatch = dispatchWorkflowRuntimeActionsStep;
+ } else if (hasPendingTasks) {
+ dispatch = dispatchTaskStep;
+ } else {
+ dispatch = dispatchRuntimeActionsStep;
+ }
const dispatchResult = await dispatch({
callbackBaseUrl: resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url),
parentContinuationToken: inbox.token,
@@ -178,6 +187,7 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {
});
const initialAcceptedAtMs = dispatchResult.results.length === 0 ? undefined : Date.now();
await cursor.adopt(dispatchResult);
+ await acknowledgeDelegatedTasksStep({ tasks: dispatchResult.pendingTasks });
const results = await waitForRuntimeActionResults({
bufferedDeliveries,
@@ -272,6 +282,11 @@ async function waitForTurnSleep(
// These sentinels stay outside `RuntimeActionResult`. That union is the
// schema-validated wire type projected into harness resume calls; these are
// turn-workflow control outcomes that never leave the workflow.
+interface AcceptedRuntimeActionBatch {
+ readonly acceptedAtMsByCallId: Readonly<Record<string, number>>;
+ readonly results: readonly RuntimeActionResult[];
+}
+
async function waitForRuntimeActionResults(input: {
readonly bufferedDeliveries: DeliverHookPayload[];
readonly cancellation: TurnCancellationControl | undefined;
@@ -394,9 +409,13 @@ async function waitForRuntimeActionResults(input: {
const routed = await routeDeliverToChildren({
delivery: value.delivery,
parentWritable: input.cursor.parentWritable,
+ serializedContext: input.cursor.serializedContext,
sessionState: input.cursor.sessionState,
});
- await input.cursor.adopt(routed);
+ await input.cursor.adopt({
+ serializedContext: routed.serializedContext ?? input.cursor.serializedContext,
+ sessionState: routed.sessionState ?? input.cursor.sessionState,
+ });
if (routed.kind === "cancel-turn") {
return routed.kind;
}
@@ -407,11 +426,6 @@ async function waitForRuntimeActionResults(input: {
}
}
-interface AcceptedRuntimeActionBatch {
- readonly acceptedAtMsByCallId: Readonly<Record<string, number>>;
- readonly results: readonly RuntimeActionResult[];
-}
-
async function runLegacyTurnWorkflow(input: TurnWorkflowInput): Promise<void> {
let currentStepInput: TurnStepInput = input.stepInput;
diff --git a/packages/eve/src/execution/workflow-callback-url.test.ts b/packages/eve/src/execution/workflow-callback-url.test.ts
index e81f98587..2d5529922 100644
--- a/packages/eve/src/execution/workflow-callback-url.test.ts
+++ b/packages/eve/src/execution/workflow-callback-url.test.ts
@@ -1,6 +1,7 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import {
+ createRemoteTaskInputCallbackUrl,
createWorkflowCallbackUrl,
resolveVercelProductionCallbackBaseUrl,
resolveWorkflowCallbackBaseUrl,
@@ -134,3 +135,41 @@ describe("createWorkflowCallbackUrl", () => {
);
});
});
+
+describe("createRemoteTaskInputCallbackUrl", () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it("adds the bypass only for the current Vercel deployment host", () => {
+ vi.stubEnv("VERCEL_AUTOMATION_BYPASS_SECRET", "secret");
+ vi.stubEnv("VERCEL_URL", "current-deployment.vercel.app");
+
+ expect(
+ createRemoteTaskInputCallbackUrl(
+ "https://current-deployment.vercel.app",
+ "/eve/v1/task-input/token",
+ ),
+ ).toBe(
+ "https://current-deployment.vercel.app/eve/v1/task-input/token?x-vercel-protection-bypass=secret",
+ );
+ });
+
+ it("does not disclose the bypass to an external remote host", () => {
+ vi.stubEnv("VERCEL_AUTOMATION_BYPASS_SECRET", "secret");
+ vi.stubEnv("VERCEL_URL", "current-deployment.vercel.app");
+
+ expect(
+ createRemoteTaskInputCallbackUrl("https://remote.example", "/eve/v1/task-input/token"),
+ ).toBe("https://remote.example/eve/v1/task-input/token");
+ });
+
+ it("does not add the Vercel bypass to loopback HTTP", () => {
+ vi.stubEnv("VERCEL_AUTOMATION_BYPASS_SECRET", "secret");
+ vi.stubEnv("VERCEL_URL", "127.0.0.1");
+
+ expect(
+ createRemoteTaskInputCallbackUrl("http://127.0.0.1:3000", "/eve/v1/task-input/token"),
+ ).toBe("http://127.0.0.1:3000/eve/v1/task-input/token");
+ });
+});
diff --git a/packages/eve/src/execution/workflow-callback-url.ts b/packages/eve/src/execution/workflow-callback-url.ts
index 7f8abdbf4..54e847491 100644
--- a/packages/eve/src/execution/workflow-callback-url.ts
+++ b/packages/eve/src/execution/workflow-callback-url.ts
@@ -6,6 +6,11 @@ import {
const PRODUCTION_ENVIRONMENT = "production";
const VERCEL_PROTECTION_BYPASS_QUERY = "x-vercel-protection-bypass";
const WORKFLOW_LOCAL_BASE_URL_ENV = "WORKFLOW_LOCAL_BASE_URL";
+const VERCEL_CALLBACK_HOST_ENVS = [
+ "VERCEL_URL",
+ "VERCEL_BRANCH_URL",
+ "VERCEL_PROJECT_PRODUCTION_URL",
+] as const;
/**
* Workflow metadata is deployment-specific, so on Vercel it can point at
@@ -66,3 +71,19 @@ export function createWorkflowCallbackUrl(baseUrl: string, callbackPath: string)
return url.toString();
}
+
+/**
+ * Builds a callback to a remote task child without disclosing this deployment's
+ * protection bypass secret to an authored external origin.
+ */
+export function createRemoteTaskInputCallbackUrl(baseUrl: string, callbackPath: string): string {
+ const url = new URL(`${baseUrl.replace(/\/$/, "")}${callbackPath}`);
+ const bypassSecret = process.env.VERCEL_AUTOMATION_BYPASS_SECRET?.trim();
+ const isCurrentVercelHost = VERCEL_CALLBACK_HOST_ENVS.some(
+ (name) => process.env[name]?.trim().toLowerCase() === url.hostname.toLowerCase(),
+ );
+ if (bypassSecret && url.protocol === "https:" && isCurrentVercelHost) {
+ url.searchParams.set(VERCEL_PROTECTION_BYPASS_QUERY, bypassSecret);
+ }
+ return url.toString();
+}
diff --git a/packages/eve/src/execution/workflow-entry.test.ts b/packages/eve/src/execution/workflow-entry.test.ts
index e126ea25f..bfeb165f9 100644
--- a/packages/eve/src/execution/workflow-entry.test.ts
+++ b/packages/eve/src/execution/workflow-entry.test.ts
@@ -58,15 +58,23 @@ vi.mock("./create-session-step.js", () => ({
}));
vi.mock("./route-child-delivery.js", () => ({
- routeDeliverToChildren: vi.fn().mockImplementation(async ({ delivery, sessionState }) => ({
- kind: "continue",
- remainder: delivery,
- sessionState,
- })),
+ routeDeliverToChildren: vi
+ .fn()
+ .mockImplementation(async ({ delivery, serializedContext = {}, sessionState }) => ({
+ kind: "continue",
+ remainder: delivery,
+ serializedContext,
+ sessionState,
+ })),
}));
vi.mock("./delegated-parent-notification.js", () => ({
+ bindTurnCallerContextStep: vi
+ .fn()
+ .mockImplementation(async ({ serializedContext }) => serializedContext),
+ notifyCancelledTaskCallerStep: vi.fn().mockResolvedValue(undefined),
notifyDelegatedParentStep: vi.fn().mockResolvedValue(undefined),
+ notifyTaskTurnStartedStep: vi.fn().mockResolvedValue(undefined),
notifyTurnCallerStep: vi.fn().mockResolvedValue(undefined),
resolveInitialTurnCallerStep: vi.fn().mockResolvedValue(undefined),
}));
@@ -196,7 +204,10 @@ describe("workflowEntry", () => {
expect(getConflict.mock.invocationCallOrder[0]).toBeLessThan(
vi.mocked(dispatchTurnStep).mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
);
- expect(terminateChildSessionsStep).toHaveBeenCalledWith({ sessionState });
+ expect(terminateChildSessionsStep).toHaveBeenCalledWith({
+ serializedContext: expect.any(Object),
+ sessionState,
+ });
});
it("exits a conflicting initial continuation before dispatching the first turn", async () => {
@@ -334,7 +345,10 @@ describe("workflowEntry", () => {
token: sessionCommandHookToken("wrun_test_123"),
});
expect(timeoutControl.dispose).toHaveBeenCalledOnce();
- expect(terminateChildSessionsStep).toHaveBeenCalledWith({ sessionState });
+ expect(terminateChildSessionsStep).toHaveBeenCalledWith({
+ serializedContext: expect.any(Object),
+ sessionState,
+ });
expect(emitTerminalSessionFailureStep).not.toHaveBeenCalled();
expect(emitTerminalSessionCompletionStep).toHaveBeenCalledWith({
parentWritable: expect.any(WritableStream),
@@ -531,7 +545,10 @@ describe("workflowEntry", () => {
error: expect.objectContaining({ message: "persistent recoverable failure" }),
}),
);
- expect(terminateChildSessionsStep).toHaveBeenCalledWith({ sessionState });
+ expect(terminateChildSessionsStep).toHaveBeenCalledWith({
+ serializedContext: expect.any(Object),
+ sessionState,
+ });
expect(notifyDelegatedParentStep).not.toHaveBeenCalled();
expect(notifyTurnCallerStep).toHaveBeenCalledOnce();
expect(notifyTurnCallerStep).toHaveBeenCalledWith({
@@ -1083,6 +1100,7 @@ describe("workflowEntry", () => {
vi.mocked(routeDeliverToChildren).mockResolvedValueOnce({
kind: "continue",
remainder: undefined,
+ serializedContext: {},
sessionState,
});
installHookMocks({
@@ -1119,6 +1137,7 @@ describe("workflowEntry", () => {
vi.mocked(routeDeliverToChildren).mockResolvedValueOnce({
kind: "continue",
remainder: undefined,
+ serializedContext: {},
sessionState: retiredState,
});
installHookMocks({
diff --git a/packages/eve/src/execution/workflow-entry.ts b/packages/eve/src/execution/workflow-entry.ts
index ae1a8d5dd..b069027d6 100644
--- a/packages/eve/src/execution/workflow-entry.ts
+++ b/packages/eve/src/execution/workflow-entry.ts
@@ -12,7 +12,10 @@ import { readChannelRequestId, readRootSessionId } from "#execution/eve-workflow
import type { RunMode } from "#shared/run-mode.js";
import type { DurableCompiledArtifactsSource } from "#runtime/durable-compiled-artifacts-source.js";
import {
+ bindTurnCallerContextStep,
+ notifyCancelledTaskCallerStep,
notifyDelegatedParentStep,
+ notifyTaskTurnStartedStep,
notifyTurnCallerStep,
resolveInitialTurnCallerStep,
} from "#execution/delegated-parent-notification.js";
@@ -23,6 +26,7 @@ import {
import type { DurableSessionState } from "#execution/durable-session-store.js";
import type { NextDriverAction } from "#execution/next-driver-action.js";
import { nextTurnDelivery, type NextTurnInstruction } from "#execution/parked-delivery-wait.js";
+import { SessionStateCursor } from "#execution/session-state-cursor.js";
import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-step.js";
import { dispatchAndAwaitTurn } from "#execution/turn-dispatch.js";
import type { TurnDriverAction } from "#execution/turn-control-receiver.js";
@@ -33,6 +37,7 @@ import { emitTerminalSessionFailureStep } from "#execution/terminal-session-fail
import { fireSessionCallbackStep } from "#execution/session-callback-step.js";
import { isHookConflictError } from "#execution/hook-ownership.js";
import { createSessionCommandInbox } from "#execution/session-command-inbox.js";
+import { activeTurnId } from "#harness/active-turn-id.js";
import { sessionCommandHookToken } from "#execution/session-command-token.js";
import { DEFAULT_SESSION_TIMEOUT_MS } from "#execution/session-timeout.js";
import { emitTerminalSessionCompletionStep } from "#execution/terminal-session-completion-step.js";
@@ -232,6 +237,7 @@ export async function workflowEntry(input: WorkflowEntryInput): Promise<Workflow
// channel still sees a terminal event.
if (crashCleanupState.lastSessionState !== undefined) {
await terminateChildSessionsStep({
+ serializedContext: input.serializedContext,
sessionState: crashCleanupState.lastSessionState,
});
}
@@ -317,16 +323,10 @@ async function runDriverLoop(input: {
*/
const nextParkedActivity = async (park: {
readonly expectedAttemptIds: readonly string[];
- readonly sessionState: DurableSessionState;
}): Promise<
- | {
- readonly kind: "authorization-resume";
- readonly payloads: DeliverPayload[];
- readonly sessionState: DurableSessionState;
- }
+ | { readonly kind: "authorization-resume"; readonly payloads: DeliverPayload[] }
| Exclude<NextTurnInstruction, { kind: "authorization" }>
> => {
- let sessionState = park.sessionState;
const expectedAttemptIds = new Set(park.expectedAttemptIds);
for (const attemptId of collectedAuthPayloads.keys()) {
if (!expectedAttemptIds.has(attemptId)) collectedAuthPayloads.delete(attemptId);
@@ -341,19 +341,20 @@ async function runDriverLoop(input: {
collectedAuthPayloads.get(attemptId)!,
);
collectedAuthPayloads.clear();
- return { kind: "authorization-resume", payloads, sessionState };
+ return { kind: "authorization-resume", payloads };
}
const next = await nextTurnDelivery({
awaitAuthorizationCallbacks: expectedAttemptIds.size > 0,
bufferedDeliveries,
bufferedSessionControls,
+ cancelledTaskIds,
commandInbox,
deferDeliveries: input.mode === "task" && expectedAttemptIds.size > 0,
driverWritable: input.driverWritable,
- sessionState,
+ seenTaskDeliveries,
+ stateCursor,
});
- sessionState = next.sessionState;
if (next.kind !== "authorization") return next;
for (const payload of next.payloads) {
@@ -371,7 +372,7 @@ async function runDriverLoop(input: {
if (next.closed) {
const payloads = [...collectedAuthPayloads.values()];
collectedAuthPayloads.clear();
- return { kind: "authorization-resume", payloads, sessionState };
+ return { kind: "authorization-resume", payloads };
}
}
};
@@ -384,6 +385,8 @@ async function runDriverLoop(input: {
const bufferedDeliveries: DeliverHookPayload[] = [];
const bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset"> = [];
+ const cancelledTaskIds = new Set<string>();
+ const seenTaskDeliveries = new Set<string>();
const commandInbox = createSessionCommandInbox();
const stableCommandToken = sessionCommandHookToken(input.sessionState.sessionId);
await commandInbox.claimStable(stableCommandToken);
@@ -401,27 +404,48 @@ async function runDriverLoop(input: {
token: stableCommandToken,
});
+ // Durable state accumulated across turns and the parked waits between
+ // them. Turn results and settle/routing steps are adopted here, so the
+ // loop never threads `serializedContext`/`sessionState` pairs by hand.
+ const stateCursor = new SessionStateCursor({
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
+ });
+
// Control-hook disposal is deferred one turn — see DispatchedTurn.
let disposeSettledTurnControl: (() => Promise<void>) | undefined;
- const runTurn = async (args: {
- readonly delivery: HookPayload;
- readonly serializedContext: Record<string, unknown>;
- readonly sessionState: DurableSessionState;
- }): Promise<TurnDriverAction> => {
+ const runTurn = async (delivery: HookPayload): Promise<TurnDriverAction> => {
+ const caller = input.crashCleanupState.caller;
+ if (caller?.taskId !== undefined) {
+ seenTaskDeliveries.add(caller.taskId);
+ await notifyTaskTurnStartedStep({
+ caller,
+ childSessionId: stateCursor.sessionState.sessionId,
+ childTurnId: activeTurnId(stateCursor.sessionState.emissionState),
+ });
+ }
+ const serializedContext = await bindTurnCallerContextStep({
+ caller,
+ serializedContext: stateCursor.serializedContext,
+ });
const turn = await dispatchAndAwaitTurn({
bufferedDeliveries,
bufferedSessionControls,
+ cancelledTaskIds,
capabilities: input.capabilities,
commandInbox,
controlToken: nextTurnControlToken(),
- delivery: args.delivery,
+ delivery,
mode: input.mode,
parentWritable: input.driverWritable,
- serializedContext: args.serializedContext,
- sessionState: args.sessionState,
+ serializedContext,
+ seenTaskDeliveries,
+ sessionState: stateCursor.sessionState,
});
await disposeSettledTurnControl?.();
disposeSettledTurnControl = turn.dispose;
+ stateCursor.adoptState(turn.action);
+ input.crashCleanupState.lastSessionState = stateCursor.sessionState;
return turn.action;
};
@@ -430,20 +454,17 @@ async function runDriverLoop(input: {
try {
await commandInbox.rekeyContinuation(input.sessionState.continuationToken);
} catch (error) {
- // A concurrent create may start multiple candidates before one owns
- // the shared alias. The loser exits before dispatching its first turn.
+ // A concurrent create can start two candidate runs before either
+ // publishes the shared continuation alias. The runtime adopts the
+ // alias owner; the losing candidate must exit before its first turn
+ // instead of emitting a second session failure for the same create.
if (!isHookConflictError(error)) throw error;
return { kind: "result", result: { output: "" } };
}
}
await sessionTimeout?.start();
- let action: TurnDriverAction = await runTurn({
- delivery: input.initialInput,
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- });
- input.crashCleanupState.lastSessionState = action.sessionState;
+ let action: TurnDriverAction = await runTurn(input.initialInput);
while (true) {
if (action.kind === "done") {
@@ -467,21 +488,26 @@ async function runDriverLoop(input: {
if (action.cancelled === true) {
const settled = await settleCancelledTurnStep({
parentWritable: input.driverWritable,
- serializedContext: action.serializedContext,
- sessionState: action.sessionState,
+ serializedContext: stateCursor.serializedContext,
+ sessionState: stateCursor.sessionState,
});
- action = {
- ...action,
- serializedContext: settled.serializedContext,
- sessionState: settled.sessionState,
+ stateCursor.adoptState(settled);
+ const cancelledCaller = {
+ caller: input.crashCleanupState.caller,
+ sessionId: stateCursor.sessionState.sessionId,
};
- input.crashCleanupState.lastSessionState = action.sessionState;
+ await notifyCancelledTaskCallerStep(
+ settled.usage === undefined
+ ? cancelledCaller
+ : { ...cancelledCaller, usage: settled.usage },
+ );
+ input.crashCleanupState.lastSessionState = stateCursor.sessionState;
}
// Channel-created sessions may rekey their dynamic alias. Sessions
// without one remain reachable through the stable command inbox only.
- if (action.sessionState.continuationToken) {
- await commandInbox.rekeyContinuation(action.sessionState.continuationToken);
+ if (stateCursor.sessionState.continuationToken) {
+ await commandInbox.rekeyContinuation(stateCursor.sessionState.continuationToken);
}
// `settled` rides the typed park arm exclusively; `run-step` preserves
@@ -491,7 +517,7 @@ async function runDriverLoop(input: {
await notifyTurnCallerStep({
caller: input.crashCleanupState.caller,
lifecycle: "parked",
- sessionId: action.sessionState.sessionId,
+ sessionId: stateCursor.sessionState.sessionId,
settled,
});
input.crashCleanupState.caller = undefined;
@@ -504,44 +530,38 @@ async function runDriverLoop(input: {
// waits for its callback, and the callback surfaces through the same
// parked wait as everything else. The pending challenge survives
// intervening turns because every park re-derives
- // `authorizationNames` from durable session state.
+ // `authorizationAttemptIds` from durable session state.
const next = await nextParkedActivity({
expectedAttemptIds: action.authorizationAttemptIds ?? [],
- sessionState: action.sessionState,
});
- action = { ...action, sessionState: next.sessionState };
- input.crashCleanupState.lastSessionState = action.sessionState;
+ input.crashCleanupState.lastSessionState = stateCursor.sessionState;
if (next.kind === "authorization-resume") {
action = await runTurn({
- delivery: { kind: "deliver", payloads: next.payloads },
- serializedContext: action.serializedContext,
- sessionState: action.sessionState,
+ kind: "deliver",
+ payloads: next.payloads,
});
- input.crashCleanupState.lastSessionState = action.sessionState;
continue;
}
if (next.kind === "expired") {
return {
kind: "expired",
- serializedContext: action.serializedContext,
- sessionState: action.sessionState,
+ serializedContext: stateCursor.serializedContext,
+ sessionState: stateCursor.sessionState,
};
}
if (next.kind === "reset") {
- await terminateChildSessionsStep({ sessionState: action.sessionState });
+ await terminateChildSessionsStep({
+ serializedContext: stateCursor.serializedContext,
+ sessionState: stateCursor.sessionState,
+ });
return { kind: "result", result: { output: "" } };
}
if (next.kind === "clear" || next.kind === "compact") {
- action = await runTurn({
- delivery: { kind: next.kind },
- serializedContext: action.serializedContext,
- sessionState: action.sessionState,
- });
- input.crashCleanupState.lastSessionState = action.sessionState;
+ action = await runTurn({ kind: next.kind });
continue;
}
@@ -551,40 +571,28 @@ async function runDriverLoop(input: {
if (next.kind === "cancel-turn") {
await cancelDescendantTurnsStep({
- serializedContext: action.serializedContext,
- sessionState: action.sessionState,
+ serializedContext: stateCursor.serializedContext,
+ sessionState: stateCursor.sessionState,
});
const cancelled = await settleCancelledTurnStep({
parentWritable: input.driverWritable,
- serializedContext: action.serializedContext,
- sessionState: action.sessionState,
+ serializedContext: stateCursor.serializedContext,
+ sessionState: stateCursor.sessionState,
});
+ stateCursor.adoptState(cancelled);
// Re-enter with `settled` cleared: the parked answer was already
// delivered to its caller before this wait, so the next iteration
// must not treat it as a fresh settlement.
- action = {
- ...action,
- serializedContext: cancelled.serializedContext,
- sessionState: cancelled.sessionState,
- settled: undefined,
- };
+ action = { ...action, settled: undefined };
input.crashCleanupState.caller = undefined;
- input.crashCleanupState.lastSessionState = action.sessionState;
+ input.crashCleanupState.lastSessionState = stateCursor.sessionState;
continue;
}
- if (next.deliver.caller !== undefined) {
- input.crashCleanupState.caller = next.deliver.caller;
+ if (next.delivery.caller !== undefined) {
+ input.crashCleanupState.caller = next.delivery.caller;
}
- action = await runTurn({
- delivery: {
- ...next.remainder,
- kind: "deliver",
- },
- serializedContext: action.serializedContext,
- sessionState: action.sessionState,
- });
- input.crashCleanupState.lastSessionState = action.sessionState;
+ action = await runTurn(next.delivery);
}
} finally {
await disposeSettledTurnControl?.();
@@ -601,6 +609,7 @@ async function finalizeExpiredSession(input: {
readonly sessionState: DurableSessionState;
}): Promise<WorkflowEntryResult> {
await terminateChildSessionsStep({
+ serializedContext: input.serializedContext,
sessionState: input.sessionState,
});
await emitTerminalSessionCompletionStep({
@@ -638,6 +647,7 @@ async function finalizeDone(input: {
const failed = input.action.isError === true;
await terminateChildSessionsStep({
+ serializedContext,
sessionState: input.action.sessionState,
});
if (input.mode === "task") {
@@ -646,14 +656,14 @@ async function finalizeDone(input: {
output: failed ? undefined : output,
serializedContext,
status: failed ? "failed" : "completed",
- usage: failed ? undefined : input.action.usage,
+ usage: input.action.usage,
});
await notifyDelegatedParentStep({
result: failed
? createDelegatedSubagentErrorResult(serializedContext, output)
: createDelegatedSubagentSuccessResult(serializedContext, output),
serializedContext,
- usage: failed ? undefined : input.action.usage,
+ usage: input.action.usage,
});
} else {
const settled: {
diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.ts
index 9720ebbf2..a08ee48e9 100644
--- a/packages/eve/src/execution/workflow-runtime.ts
+++ b/packages/eve/src/execution/workflow-runtime.ts
@@ -321,10 +321,12 @@ function inactiveCommandResult<TCommand extends SessionCommand>(
export async function requestWorkflowTurnCancellation(
input: CancelTurnInput,
): Promise<CancelTurnResult> {
- return await dispatchWorkflowCommand(sessionCommandHookToken(input.sessionId), {
+ const command: { kind: "cancel"; taskId?: string; turnId?: string } = {
kind: "cancel",
- turnId: input.turnId,
- });
+ };
+ if (input.taskId !== undefined) command.taskId = input.taskId;
+ if (input.turnId !== undefined) command.turnId = input.turnId;
+ return await dispatchWorkflowCommand(sessionCommandHookToken(input.sessionId), command);
}
function isInactiveCommandTarget(error: unknown): boolean {
@@ -352,7 +354,7 @@ async function waitForOwnedCommandHook(token: string, sessionId: string): Promis
}
}
-async function waitForCommandHookOwner(token: string): Promise<WorkflowHookRecord> {
+export async function waitForCommandHookOwner(token: string): Promise<WorkflowHookRecord> {
const deadline = Date.now() + COMMAND_HOOK_READY_TIMEOUT_MS;
while (true) {
try {
diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.ts
index e5d6eef8e..70e4e9cdc 100644
--- a/packages/eve/src/execution/workflow-steps.test.ts
+++ b/packages/eve/src/execution/workflow-steps.test.ts
@@ -18,7 +18,7 @@ import {
import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
import { serializeContext } from "#context/serialize.js";
import { setPendingRuntimeActionBatch } from "#harness/runtime-actions.js";
-import { getAgentHandleStore } from "#harness/handles/store.js";
+import { AGENT_HANDLES_STATE_KEY, getAgentHandleStore } from "#harness/handles/store.js";
import { requestTurnSleep } from "#harness/turn-sleep.js";
import { TurnCancelledError } from "#harness/turn-cancellation.js";
import { getPendingAuthorization, setPendingAuthorization } from "#harness/authorization.js";
@@ -41,9 +41,13 @@ import { buildRuntimeIdentity, createExecutionNodeStep } from "#execution/node-s
import { defineTool } from "#public/definitions/tool.js";
import { dispatchRuntimeActionsStep } from "#execution/dispatch-runtime-actions-step.js";
import { runProxySubagentEventStep } from "#execution/subagent-event-proxy-step.js";
+import { readLatestTaskView, sendTaskInboundPayload } from "#execution/tasks/parent/run-parent.js";
+import { recordTaskInputRequestStep } from "#execution/tasks/parent/hitl-proxy-steps.js";
+import { appendTaskAgentAnnouncement } from "#execution/tasks/parent/agent-views.js";
import { emitTerminalSessionFailureStep } from "#execution/terminal-session-failure-step.js";
-import { routeProxiedDeliverStep } from "#execution/route-proxied-deliver-step.js";
-import { resolveEffectiveOutputSchema, turnStep } from "#execution/workflow-steps.js";
+import { resolveEffectiveOutputSchema } from "#execution/effective-output-schema.js";
+import { turnStep } from "#execution/workflow-steps.js";
+import { routeProxiedDeliverStep } from "#execution/proxied-deliver-step.js";
import {
LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE,
turnWorkflowReference,
@@ -58,6 +62,13 @@ vi.mock("./durable-session-store.js", async (importOriginal) => {
readDurableSession: vi.fn(),
};
});
+vi.mock("./tasks/parent/run-parent.js", () => ({
+ readLatestTaskView: vi.fn(),
+ sendTaskInboundPayload: vi.fn(),
+}));
+vi.mock("./tasks/parent/agent-views.js", () => ({
+ appendTaskAgentAnnouncement: vi.fn(async (session) => session),
+}));
function installSessionStoreMocks(
sessions: Awaited<ReturnType<typeof readDurableSession>>[],
@@ -207,6 +218,11 @@ afterEach(() => {
vi.unstubAllGlobals();
vi.unstubAllEnvs();
vi.restoreAllMocks();
+ vi.mocked(readLatestTaskView).mockReset();
+ vi.mocked(sendTaskInboundPayload).mockReset();
+ vi.mocked(sendTaskInboundPayload).mockResolvedValue("delivered");
+ vi.mocked(appendTaskAgentAnnouncement).mockReset();
+ vi.mocked(appendTaskAgentAnnouncement).mockImplementation(async (session) => session);
});
describe("routeProxiedDeliverStep", () => {
@@ -244,11 +260,6 @@ describe("routeProxiedDeliverStep", () => {
});
expect(result).toMatchObject({ kind: "continue", remainder: undefined });
- expect(result.sessionState.hasProxyInputRequests).toBe(true);
- expect([...getProxyInputRequests(result.sessionState.snapshot?.session.state)]).toEqual([
- ["request-2", { childContinuationToken: "child-token", kind: "tool-approval" }],
- ]);
-
expect(resumeHookMock).toHaveBeenCalledWith("child-token", {
auth,
caller: undefined,
@@ -261,120 +272,329 @@ describe("routeProxiedDeliverStep", () => {
});
});
- it("does not retire before forwarding succeeds and ignores a stale retry after retirement", async () => {
+ it("preserves envelope fields and reindexes metadata across routed payloads", async () => {
+ const auth = {
+ attributes: {},
+ authenticator: "test",
+ principalId: "user-1",
+ principalType: "user",
+ };
+ const caller = {
+ callId: "call-parent",
+ replyTo: { kind: "hook" as const, token: "parent-turn" },
+ subagentName: "research",
+ };
const session = upsertProxyInputRequests({
- entries: [["request-1", { childContinuationToken: "child-token", kind: "session-limit" }]],
- forChildContinuationToken: "child-token",
- session: createStubSession(),
+ entries: [
+ ["child-a", { childContinuationToken: "child-token-a", kind: "question" }],
+ ["child-b", { childContinuationToken: "child-token-b", kind: "question" }],
+ ],
+ forChildContinuationToken: "child-token-a",
+ session: upsertProxyInputRequests({
+ entries: [["child-b", { childContinuationToken: "child-token-b", kind: "question" }]],
+ forChildContinuationToken: "child-token-b",
+ session: createStubSession(),
+ }),
});
installSessionStoreMocks([session]);
- const initialState = createDurableSessionState({ session });
- resumeHookMock.mockRejectedValueOnce(new Error("temporary forward failure"));
-
- await expect(
- routeProxiedDeliverStep({
- parentWritable: createTestWritable(),
- payload: { inputResponses: [{ optionId: "stop", requestId: "request-1" }] },
- sessionState: initialState,
- }),
- ).rejects.toThrow("temporary forward failure");
- expect(initialState.hasProxyInputRequests).toBe(true);
- installSessionStoreMocks([session]);
- const forwarded = await routeProxiedDeliverStep({
- parentWritable: createTestWritable(),
- payload: { inputResponses: [{ optionId: "stop", requestId: "request-1" }] },
- sessionState: initialState,
- });
- expect(forwarded.kind).toBe("cancel-turn");
- expect(forwarded.sessionState.hasProxyInputRequests).toBe(false);
+ const delivery = {
+ auth,
+ caller,
+ deliveryMetadata: [
+ { channelKind: "test", channelName: "main", deliveryId: "delivery-0", payloadIndex: 0 },
+ { channelKind: "test", channelName: "main", deliveryId: "delivery-1", payloadIndex: 1 },
+ { channelKind: "test", channelName: "main", deliveryId: "delivery-2", payloadIndex: 2 },
+ ],
+ kind: "deliver" as const,
+ payloads: [
+ { inputResponses: [{ text: "a", requestId: "child-a" }] },
+ {
+ inputResponses: [
+ { text: "b", requestId: "child-b" },
+ { text: "parent", requestId: "parent-response" },
+ ],
+ },
+ { message: "parent message" },
+ ],
+ requestId: "request-1",
+ taskDeliveryId: "task-delivery-1",
+ turnPolicy: "queue" as const,
+ };
- resumeHookMock.mockClear();
- const retiredSession = forwarded.sessionState.snapshot?.session;
- if (retiredSession === undefined) throw new Error("Expected a routed session snapshot.");
- installSessionStoreMocks([retiredSession]);
- const stale = await routeProxiedDeliverStep({
+ const result = await routeProxiedDeliverStep({
+ delivery,
parentWritable: createTestWritable(),
- payload: { inputResponses: [{ optionId: "stop", requestId: "request-1" }] },
- sessionState: forwarded.sessionState,
+ sessionState: createStubSessionState({ hasProxyInputRequests: true }),
});
- expect(stale).toEqual({
+ expect(resumeHookMock).toHaveBeenCalledWith(
+ "child-token-a",
+ expect.objectContaining({
+ ...delivery,
+ deliveryMetadata: [expect.objectContaining({ deliveryId: "delivery-0", payloadIndex: 0 })],
+ payloads: [{ inputResponses: [{ requestId: "child-a", text: "a" }] }],
+ }),
+ );
+ expect(resumeHookMock).toHaveBeenCalledWith(
+ "child-token-b",
+ expect.objectContaining({
+ auth,
+ caller,
+ deliveryMetadata: undefined,
+ requestId: "request-1",
+ taskDeliveryId: "task-delivery-1",
+ turnPolicy: "queue",
+ }),
+ );
+ expect(result).toMatchObject({
kind: "continue",
- remainder: { inputResponses: [{ optionId: "stop", requestId: "request-1" }] },
- sessionState: forwarded.sessionState,
+ remainder: {
+ auth,
+ caller,
+ deliveryMetadata: [
+ { deliveryId: "delivery-1", payloadIndex: 0 },
+ { deliveryId: "delivery-2", payloadIndex: 1 },
+ ],
+ payloads: [
+ { inputResponses: [{ requestId: "parent-response", text: "parent" }] },
+ { message: "parent message" },
+ ],
+ requestId: "request-1",
+ taskDeliveryId: "task-delivery-1",
+ turnPolicy: "queue",
+ },
});
- expect(resumeHookMock).not.toHaveBeenCalled();
});
- it("replays multi-child forwarding in the same order when a later child fails", async () => {
- const session = upsertProxyInputRequests({
+ function createTaskRouteSession(options?: { readonly owned?: boolean }): HarnessSession {
+ return upsertProxyInputRequests({
entries: [
- ["request-a", { childContinuationToken: "child-a", kind: "question" }],
- ["request-b", { childContinuationToken: "child-b", kind: "question" }],
+ [
+ "task-1:request-1",
+ {
+ childContinuationToken: "child-token",
+ childRequestId: "request-1",
+ kind: "tool-approval",
+ taskId: "task-1",
+ },
+ ],
],
- forChildContinuationToken: "child-a",
- session: createStubSession(),
+ forChildContinuationToken: "child-token",
+ session: createStubSession({
+ continuationToken: "parent-token",
+ sessionId: "parent-session",
+ state:
+ options?.owned === false
+ ? undefined
+ : {
+ "eve.tasks": {
+ tasks: [
+ {
+ taskInboxToken: "task-token",
+ createdByTurnId: "turn-parent",
+ metadata: {
+ agentId: "agent-1",
+ kind: "subagent",
+ mode: "local",
+ name: "research",
+ },
+ operationId: "operation-1",
+ taskId: "task-1",
+ taskRunId: "run-1",
+ },
+ ],
+ },
+ },
+ }),
});
- installSessionStoreMocks([session]);
- const initialState = createDurableSessionState({ session });
- resumeHookMock
- .mockResolvedValueOnce(undefined)
- .mockRejectedValueOnce(new Error("child-b down"));
- const input = {
+ }
+
+ const taskRouteInput = {
+ payload: { inputResponses: [{ optionId: "approve", requestId: "task-1:request-1" }] },
+ sessionState: createStubSessionState({ hasProxyInputRequests: true }),
+ };
+
+ it("hands a task-owned answer to the task run instead of the child", async () => {
+ installSessionStoreMocks([createTaskRouteSession()]);
+
+ const result = await routeProxiedDeliverStep({
+ ...taskRouteInput,
parentWritable: createTestWritable(),
+ });
+ expect(result).toMatchObject({ kind: "continue", remainder: undefined });
+ expect(sendTaskInboundPayload).toHaveBeenCalledWith({
+ taskInboxToken: "task-token",
payload: {
- inputResponses: [
- { requestId: "request-a", text: "a" },
- { requestId: "request-b", text: "b" },
- ],
+ auth: undefined,
+ childContinuationToken: "child-token",
+ inputResponses: [{ optionId: "approve", requestId: "request-1" }],
+ kind: "input-response",
+ taskId: "task-1",
},
- sessionState: initialState,
- };
+ });
+ expect(resumeHookMock).not.toHaveBeenCalled();
+ expect(getProxyInputRequests(result.sessionState.snapshot?.session.state).size).toBe(0);
+ });
- await expect(routeProxiedDeliverStep(input)).rejects.toThrow("child-b down");
- expect(resumeHookMock.mock.calls.map(([token]) => token)).toEqual(["child-a", "child-b"]);
- expect(initialState.snapshot?.session.state).toEqual(session.state);
+ it("keeps a response for a task this session does not own on the parent", async () => {
+ installSessionStoreMocks([createTaskRouteSession({ owned: false })]);
- resumeHookMock.mockReset();
- installSessionStoreMocks([session]);
- await routeProxiedDeliverStep(input);
+ await expect(
+ routeProxiedDeliverStep({ ...taskRouteInput, parentWritable: createTestWritable() }),
+ ).resolves.toMatchObject({
+ kind: "continue",
+ remainder: {
+ inputResponses: [{ optionId: "approve", requestId: "task-1:request-1" }],
+ },
+ });
+ expect(sendTaskInboundPayload).not.toHaveBeenCalled();
+ expect(resumeHookMock).not.toHaveBeenCalled();
+ });
+
+ it("returns answers to the parent when the task run already finished", async () => {
+ installSessionStoreMocks([createTaskRouteSession()]);
+ vi.mocked(sendTaskInboundPayload).mockResolvedValue("unreachable");
- expect(resumeHookMock.mock.calls.map(([token]) => token)).toEqual(["child-a", "child-b"]);
+ await expect(
+ routeProxiedDeliverStep({ ...taskRouteInput, parentWritable: createTestWritable() }),
+ ).resolves.toMatchObject({
+ kind: "continue",
+ remainder: {
+ inputResponses: [{ optionId: "approve", requestId: "task-1:request-1" }],
+ },
+ });
});
- it("preserves metadata when the descendant wholly owns the delivery", async () => {
- const session = upsertProxyInputRequests({
- entries: [["request-1", { childContinuationToken: "child-token", kind: "tool-approval" }]],
- forChildContinuationToken: "child-token",
- session: createStubSession({ sessionId: "parent-session" }),
+ it("keeps a task answer retryable after delivery fails", async () => {
+ const session = createTaskRouteSession();
+ installSessionStoreMocks([session, session]);
+ vi.mocked(sendTaskInboundPayload)
+ .mockRejectedValueOnce(new Error("transient"))
+ .mockResolvedValueOnce("delivered");
+
+ await expect(
+ routeProxiedDeliverStep({ ...taskRouteInput, parentWritable: createTestWritable() }),
+ ).rejects.toThrow("transient");
+ await expect(
+ routeProxiedDeliverStep({ ...taskRouteInput, parentWritable: createTestWritable() }),
+ ).resolves.toMatchObject({ kind: "continue", remainder: undefined });
+ expect(sendTaskInboundPayload).toHaveBeenCalledTimes(2);
+ });
+});
+
+describe("recordTaskInputRequestStep", () => {
+ const hookPayload: SubagentInputRequestHookPayload = {
+ callId: "call-task",
+ childContinuationToken: "child-token",
+ childSessionId: "child-session",
+ event: {
+ requests: [
+ {
+ action: { callId: "call-q", input: {}, kind: "tool-call", toolName: "ask" },
+ kind: "question",
+ prompt: "Which?",
+ requestId: "request-1",
+ },
+ ],
+ sequence: 1,
+ stepIndex: 2,
+ turnId: "turn_child",
+ },
+ kind: "subagent-input-request",
+ subagentName: "research",
+ };
+
+ it("records an exact route only for a current task owned by this parent", async () => {
+ const session = createStubSession({
+ state: {
+ [AGENT_HANDLES_STATE_KEY]: {
+ handles: [
+ {
+ address: {
+ continuationToken: "child-token",
+ kind: "agent/local",
+ sessionId: "child-session",
+ },
+ identity: { id: "agent-1", name: "research", nodeId: "node-1" },
+ phase: "addressed",
+ },
+ ],
+ },
+ "eve.tasks": {
+ tasks: [
+ {
+ taskInboxToken: "task-token",
+ createdByTurnId: "turn-parent",
+ metadata: {
+ agentId: "agent-1",
+ kind: "subagent",
+ mode: "local",
+ name: "research",
+ },
+ operationId: "operation-1",
+ taskId: "task-1",
+ taskRunId: "run-1",
+ },
+ ],
+ },
+ },
});
installSessionStoreMocks([session]);
- const metadata = {
- channelKind: "channel:slack",
- channelName: "slack",
- deliveryId: "delivery-1",
- payloadIndex: 0,
- requestId: "request-http-1",
- };
+ vi.mocked(readLatestTaskView).mockResolvedValue({
+ metadata: {
+ agentId: "agent-1",
+ kind: "subagent",
+ mode: "local",
+ name: "research",
+ },
+ executor: { childSessionId: "child-session" },
+ inputRequests: hookPayload.event.requests,
+ status: "input_required",
+ taskId: "task-1",
+ });
- await routeProxiedDeliverStep({
- delivery: {
- deliveryMetadata: [metadata],
- kind: "deliver",
- payloads: [{ inputResponses: [{ optionId: "approve", requestId: "request-1" }] }],
+ const result = await recordTaskInputRequestStep({
+ hookPayload,
+ serializedContext: createSerializedContext(),
+ sessionState: createStubSessionState(),
+ taskId: "task-1",
+ });
+
+ expect(result.accepted).toBe(true);
+ expect(
+ getProxyInputRequests(result.sessionState.snapshot?.session.state).get("task-1:request-1"),
+ ).toEqual({
+ batch: {
+ approvalRequestIds: [],
+ requestIds: ["task-1:request-1"],
},
- parentWritable: createTestWritable(),
- sessionState: createStubSessionState({
- hasProxyInputRequests: true,
- sessionId: "parent-session",
- }),
+ childContinuationToken: "child-token",
+ childRequestId: "request-1",
+ kind: "question",
+ taskId: "task-1",
});
+ expect(result).toMatchObject({
+ accepted: true,
+ hookPayload: {
+ event: { requests: [{ requestId: "task-1:request-1" }] },
+ },
+ });
+ });
- expect(resumeHookMock).toHaveBeenCalledWith(
- "child-token",
- expect.objectContaining({ deliveryMetadata: [metadata] }),
- );
+ it("rejects cross-session and stale batches without recording a route", async () => {
+ const session = createStubSession();
+ installSessionStoreMocks([session, session]);
+ vi.mocked(readLatestTaskView).mockResolvedValue(undefined);
+
+ const result = await recordTaskInputRequestStep({
+ hookPayload,
+ serializedContext: createSerializedContext(),
+ sessionState: createStubSessionState(),
+ taskId: "foreign-task",
+ });
+
+ expect(result).toEqual({ accepted: false, sessionState: createStubSessionState() });
});
});
@@ -596,6 +816,7 @@ describe("dispatchRuntimeActionsStep", () => {
},
],
sessionState: expect.any(Object),
+ pendingTasks: [],
});
// The started child stays owned as a running handle; the dead start's
// prepared handle was rejected.
@@ -1039,6 +1260,7 @@ describe("dispatchRuntimeActionsStep", () => {
},
],
sessionState,
+ pendingTasks: [],
});
expect(startMock).not.toHaveBeenCalled();
expect(warn).toHaveBeenCalledWith(
@@ -1136,6 +1358,7 @@ describe("dispatchRuntimeActionsStep", () => {
},
],
sessionState,
+ pendingTasks: [],
});
expect(startMock).not.toHaveBeenCalled();
});
@@ -1300,6 +1523,125 @@ describe("turnStep", () => {
);
});
+ it("returns tasksEnabled on park results so the turn workflow selects dispatchTaskStep", async () => {
+ // Regression: a stack rebase once dropped `tasksEnabled` from the park
+ // arms while keeping the computation, so every tasks-mode agent silently
+ // fell back to dispatchRuntimeActionsStep and no background task receipt
+ // was ever minted. The park result is the only wire that carries this
+ // flag to the dispatch selection in turn-workflow.ts.
+ const tasksBundle = {
+ adapterRegistry: {
+ adaptersByKind: new Map([[threadContextAdapter.kind, threadContextAdapter]]),
+ },
+ compiledArtifactsSource: {} as never,
+ graph: {
+ nodesByNodeId: new Map(),
+ root: {
+ sandboxRegistry: { sandbox: null },
+ turnAgent: TestTurnAgent,
+ },
+ },
+ moduleMap: { nodes: {} },
+ hookRegistry: createEmptyHookRegistry(),
+ resolvedAgent: { config: { experimental: { tasks: true } } },
+ subagentRegistry: {},
+ toolRegistry: {},
+ turnAgent: TestTurnAgent,
+ } as never;
+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(tasksBundle);
+
+ const session = createStubSession();
+ installSessionStoreMocks([session]);
+ vi.mocked(createExecutionNodeStep).mockImplementation(() => {
+ return async (stepSession): Promise<StepResult> => ({
+ next: null,
+ session: stepSession,
+ });
+ });
+
+ const parked = await turnStep({
+ input: {
+ kind: "deliver",
+ payloads: [{ message: "start a background task" }],
+ },
+ parentWritable: createTestWritable(),
+ serializedContext: createSerializedContext(),
+ sessionState: createStubSessionState(),
+ });
+ expect(parked).toMatchObject({ action: "park", tasksEnabled: true });
+
+ installSessionStoreMocks([session]);
+ vi.mocked(createExecutionNodeStep).mockImplementation(() => {
+ return async (stepSession): Promise<StepResult> => ({
+ next: null,
+ session: stepSession,
+ settledTurn: { output: "settled" },
+ });
+ });
+ const settled = await turnStep({
+ input: {
+ kind: "deliver",
+ payloads: [{ message: "settle" }],
+ },
+ parentWritable: createTestWritable(),
+ serializedContext: createSerializedContext(),
+ sessionState: createStubSessionState(),
+ });
+ expect(settled).toMatchObject({ action: "park", tasksEnabled: true });
+ });
+
+ it("passes task-agent availability projection into execution", async () => {
+ const tasksBundle = {
+ adapterRegistry: {
+ adaptersByKind: new Map([[threadContextAdapter.kind, threadContextAdapter]]),
+ },
+ compiledArtifactsSource: {} as never,
+ graph: {
+ nodesByNodeId: new Map(),
+ root: {
+ sandboxRegistry: { sandbox: null },
+ turnAgent: TestTurnAgent,
+ },
+ },
+ moduleMap: { nodes: {} },
+ hookRegistry: createEmptyHookRegistry(),
+ resolvedAgent: { config: { experimental: { tasks: true } } },
+ subagentRegistry: {},
+ toolRegistry: {},
+ turnAgent: TestTurnAgent,
+ } as never;
+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(tasksBundle);
+
+ const session = createStubSession();
+ const projectedSession = {
+ ...session,
+ history: [{ content: "[Agents]\n<agents>\n</agents>", role: "user" as const }],
+ };
+ installSessionStoreMocks([session]);
+ vi.mocked(appendTaskAgentAnnouncement).mockResolvedValue(projectedSession);
+
+ let executedSession: HarnessSession | undefined;
+ vi.mocked(createExecutionNodeStep).mockImplementation(() => {
+ return async (stepSession): Promise<StepResult> => {
+ executedSession = stepSession;
+ return { next: null, session: stepSession };
+ };
+ });
+
+ await turnStep({
+ input: {
+ kind: "deliver",
+ payloads: [{ message: "check background work" }],
+ },
+ parentWritable: createTestWritable(),
+ serializedContext: createSerializedContext(),
+ sessionState: createStubSessionState(),
+ });
+
+ expect(appendTaskAgentAnnouncement).toHaveBeenCalledOnce();
+ expect(executedSession).toBe(projectedSession);
+ });
+
it("carries a settled turn through the typed park action when no work remains pending", async () => {
const session = createStubSession();
installSessionStoreMocks([session]);
diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.ts
index 31a5be6c3..89982668c 100644
--- a/packages/eve/src/execution/workflow-steps.ts
+++ b/packages/eve/src/execution/workflow-steps.ts
@@ -59,8 +59,6 @@ import { getPendingRuntimeActionBatch } from "#harness/runtime-actions.js";
import type { HarnessSession, SettledTurn, StepInput, StepResult } from "#harness/types.js";
import { getTurnUsageState, takeSessionUsageDelta, toUsage } from "#harness/turn-tag-state.js";
import type { TokenUsage } from "#shared/token-usage.js";
-import type { JsonObject } from "#shared/json.js";
-import type { RunMode } from "#shared/run-mode.js";
import { getRuntimeActionRequestKey } from "#runtime/actions/keys.js";
import {
createAuthorizationCompletedEvent,
@@ -77,6 +75,8 @@ import {
PendingAuthorizationResultKey,
} from "#harness/authorization.js";
import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";
+import { forwardTaskEventToSessionCallback } from "#execution/task-event-callback.js";
+import { resolveEffectiveOutputSchema } from "#execution/effective-output-schema.js";
import {
createDurableSessionState,
type DurableSessionState,
@@ -84,6 +84,7 @@ import {
} from "#execution/durable-session-store.js";
import type { TurnStepInput } from "#execution/durable-session-migrations/turn-workflow.js";
import { buildRuntimeIdentity, createExecutionNodeStep } from "#execution/node-step.js";
+import { appendTaskAgentAnnouncement } from "#execution/tasks/parent/agent-views.js";
import { prepareWorkflowPreambleTrace } from "#execution/workflow-trace-context.js";
import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
import { recordSubagentUsageSpans } from "#execution/subagent-usage-span.js";
@@ -138,6 +139,12 @@ export type DurableStepResult =
readonly hasPendingAuthorization: boolean;
readonly hasPendingInputBatch: boolean;
readonly pendingRuntimeActionKeys?: readonly string[];
+ /**
+ * Selects the dispatch step for `pendingRuntimeActionKeys`:
+ * `dispatchTaskStep` when the agent runs `experimental.tasks`,
+ * `dispatchRuntimeActionsStep` otherwise (including when absent).
+ */
+ readonly tasksEnabled?: boolean;
readonly sleepDurationMs?: number;
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
@@ -165,6 +172,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
const ctx = await deserializeContext(input.serializedContext);
const adapter = ctx.require(ChannelKey);
const bundle = ctx.require(BundleKey);
+ const tasksEnabled = bundle.resolvedAgent.config?.experimental?.tasks === true;
const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);
// Populate the callback base URL so getHookUrl() works during tool
@@ -317,6 +325,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
...derivePendingState(rekeyed),
serializedContext: nextSerializedContext,
sessionState: nextState,
+ tasksEnabled,
};
}
@@ -325,7 +334,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
const dynamicSkillResolvers = bundle.resolvedAgent.dynamicSkillResolvers ?? [];
const dynamicSubagentResolvers = bundle.subagentRegistry.dynamicResolvers ?? [];
const persistentSubagentSessions =
- bundle.resolvedAgent.config?.experimental?.subagentPersistentSessions === true;
+ tasksEnabled || bundle.resolvedAgent.config?.experimental?.subagentPersistentSessions === true;
const dynamicToolResolvers = bundle.resolvedAgent.dynamicToolResolvers ?? [];
const effectiveNode = {
...bundle.graph.root,
@@ -382,6 +391,10 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
event: UnstampedMessageStreamEvent,
messages?: readonly import("ai").ModelMessage[],
): Promise<void> => {
+ // Task children report HITL and authorization transitions to their
+ // parent's session callback before local emission, so the parent's
+ // task run can block/unblock the task under one durable decision.
+ await forwardTaskEventToSessionCallback(ctx, event);
const emitted = await emit(event);
await dispatchStreamEventHooks({ ctx, registry: hookRegistry, event: emitted });
if (emitted.type !== "step.started") {
@@ -472,6 +485,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
)?.candidateId;
await handleEvent(
createAuthorizationCompletedEvent({
+ attemptId: result.attemptId,
authorization,
candidateId,
name: result.name,
@@ -497,6 +511,9 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
session: lifecycleSession,
turnAgent: effectiveAgent.turnAgent,
});
+ const modelSession = tasksEnabled
+ ? await appendTaskAgentAnnouncement(refreshedSession)
+ : refreshedSession;
const step = createExecutionNodeStep({
abortSignal: input.abortSignal,
@@ -513,7 +530,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
node: effectiveNode,
workflowMaxSubagents: refreshedSession.workflowMaxSubagents,
});
- return step(refreshedSession, stepInput);
+ return step(modelSession, stepInput);
};
return runHarnessStep(schemaSession, resolved);
@@ -613,6 +630,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
isError: stepResult.settledTurn.isError,
usage: delta,
},
+ tasksEnabled,
};
}
@@ -622,6 +640,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
...sleepTransition,
serializedContext: nextSerializedContext,
sessionState: nextState,
+ tasksEnabled,
};
}
@@ -663,34 +682,3 @@ function derivePendingState(session: HarnessSession): {
}
return base;
}
-
-/**
- * Resolves the single output schema in effect for this turn, decoupling schema
- * enforcement from {@link RunMode}: downstream the harness reads
- * `session.outputSchema` unconditionally and never re-derives it from mode.
- *
- * A run-scoped (client-supplied) schema on the turn's {@link StepInput} always
- * wins. With no run-scoped schema, a task run adopts the agent's declared
- * return schema — its function-output contract, which only applies when the
- * agent is invoked as a function (subagent / schedule / job), i.e. task mode.
- * A conversation run with no run-scoped schema enforces nothing. Continuation
- * steps (no new `StepInput`) preserve whatever is already in effect.
- */
-export function resolveEffectiveOutputSchema(input: {
- readonly agentOutputSchema: JsonObject | undefined;
- readonly input: StepInput | undefined;
- readonly mode: RunMode;
- readonly session: HarnessSession;
-}): HarnessSession {
- const { agentOutputSchema, input: stepInput, mode, session } = input;
-
- if (stepInput?.outputSchema !== undefined) {
- return { ...session, outputSchema: stepInput.outputSchema };
- }
-
- if (mode === "task" && session.outputSchema === undefined && agentOutputSchema !== undefined) {
- return { ...session, outputSchema: agentOutputSchema };
- }
-
- return session;
-}
diff --git a/packages/eve/src/harness/advertised-tools.test.ts b/packages/eve/src/harness/advertised-tools.test.ts
index f5b3eacce..4b68c600f 100644
--- a/packages/eve/src/harness/advertised-tools.test.ts
+++ b/packages/eve/src/harness/advertised-tools.test.ts
@@ -134,6 +134,34 @@ describe("getAdvertisedTools for definition arrays", () => {
expect(advertisedTools.map((tool) => tool.name)).toEqual(["add", "delegate"]);
});
+
+ it("keeps the task tools in the root session", () => {
+ const tools = new Map([
+ ["add", createTool("add")],
+ ["task_peek", createTaskControlTool("task_peek")],
+ ["task_sleep", createTool("task_sleep")],
+ ]) satisfies HarnessToolMap;
+
+ const advertisedTools = getAdvertisedTools({ session: {}, tools });
+
+ expect([...advertisedTools.keys()]).toEqual(["add", "task_peek", "task_sleep"]);
+ });
+
+ it("removes the task tools from delegated sessions", () => {
+ const tools = new Map([
+ ["add", createTool("add")],
+ ["task_cancel", createTaskControlTool("task_cancel")],
+ ["task_peek", createTaskControlTool("task_peek")],
+ ["task_sleep", createTool("task_sleep")],
+ ]) satisfies HarnessToolMap;
+
+ const advertisedTools = getAdvertisedTools({
+ session: { rootSessionId: "root-session", subagentDepth: 1 },
+ tools,
+ });
+
+ expect([...advertisedTools.keys()]).toEqual(["add"]);
+ });
});
function createTool(name: string): HarnessToolDefinition {
@@ -166,6 +194,13 @@ function createBuiltInAgentTool(): HarnessToolDefinition {
};
}
+function createTaskControlTool(name: string): HarnessToolDefinition {
+ return {
+ ...createTool(name),
+ runtimeAction: { kind: "task-control" },
+ };
+}
+
function createSession(overrides: Partial<HarnessSession> = {}): HarnessSession {
return {
agent: {
diff --git a/packages/eve/src/harness/advertised-tools.ts b/packages/eve/src/harness/advertised-tools.ts
index e1df9f000..301fccbaa 100644
--- a/packages/eve/src/harness/advertised-tools.ts
+++ b/packages/eve/src/harness/advertised-tools.ts
@@ -2,6 +2,7 @@ import type { ToolSet } from "ai";
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
import { resolveSubagentDepth } from "#harness/subagent-depth.js";
import { AGENT_TOOL_NAME } from "#runtime/framework-tools/agent.js";
+import { TASK_TOOL_NAMES } from "#runtime/framework-tools/tasks.js";
import { ROOT_RUNTIME_AGENT_NODE_ID } from "#runtime/graph.js";
import {
ensureWorkflowContinuationSecurity,
@@ -162,15 +163,29 @@ function shouldHideDelegationTool(
definition: HarnessToolDefinition,
session: AdvertisedToolSession,
): boolean {
+ if (isRootOnlyFrameworkTool(definition)) {
+ return session.rootSessionId !== undefined || resolveSubagentDepth(session).currentDepth > 0;
+ }
+
+ return false;
+}
+
+/**
+ * Tools that only a root session may see. The `agent` self-delegation
+ * tool and the `experimental.tasks` controls are injected from the root
+ * node's config, which self-delegated children share — session shape is
+ * the only signal that separates the root from its children.
+ */
+function isRootOnlyFrameworkTool(definition: HarnessToolDefinition): boolean {
if (
- definition.name !== AGENT_TOOL_NAME ||
- definition.runtimeAction?.kind !== "subagent-call" ||
- definition.runtimeAction.nodeId !== ROOT_RUNTIME_AGENT_NODE_ID
+ definition.name === AGENT_TOOL_NAME &&
+ definition.runtimeAction?.kind === "subagent-call" &&
+ definition.runtimeAction.nodeId === ROOT_RUNTIME_AGENT_NODE_ID
) {
- return false;
+ return true;
}
- return session.rootSessionId !== undefined || resolveSubagentDepth(session).currentDepth > 0;
+ return TASK_TOOL_NAMES.has(definition.name);
}
function isToolDefinitionList(
diff --git a/packages/eve/src/harness/authorization.test.ts b/packages/eve/src/harness/authorization.test.ts
index 07500b36a..16b9d19dd 100644
--- a/packages/eve/src/harness/authorization.test.ts
+++ b/packages/eve/src/harness/authorization.test.ts
@@ -1,15 +1,35 @@
-import { describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { ContextContainer, contextStorage } from "#context/container.js";
+import { SessionIdKey } from "#context/keys.js";
import {
+ CallbackBaseUrlKey,
clearPendingAuthorization,
consumeAuthorizationResult,
getPendingAuthorization,
+ getHookUrl,
PendingAuthorizationResultKey,
setPendingAuthorization,
} from "#harness/authorization.js";
import type { ConnectionPrincipal } from "#runtime/connections/types.js";
+afterEach(() => {
+ vi.unstubAllEnvs();
+});
+
+describe("authorization callback URLs", () => {
+ it("includes the Vercel automation bypass query when configured", () => {
+ vi.stubEnv("VERCEL_AUTOMATION_BYPASS_SECRET", "secret value");
+ const ctx = new ContextContainer();
+ ctx.set(CallbackBaseUrlKey, "https://agent.example.com");
+ ctx.set(SessionIdKey, "session-1");
+
+ expect(contextStorage.run(ctx, () => getHookUrl("linear", "attempt-1"))).toBe(
+ "https://agent.example.com/eve/v1/connections/linear/callback/attempt-1/session-1%3Aauth?x-vercel-protection-bypass=secret+value",
+ );
+ });
+});
+
describe("authorization callback results", () => {
it("consumes each callback result once", () => {
const ctx = new ContextContainer();
diff --git a/packages/eve/src/harness/authorization.ts b/packages/eve/src/harness/authorization.ts
index f2eeda658..6adeb53da 100644
--- a/packages/eve/src/harness/authorization.ts
+++ b/packages/eve/src/harness/authorization.ts
@@ -34,6 +34,7 @@
import { loadContext } from "#context/container.js";
import { ContextKey } from "#context/key.js";
import { SessionIdKey } from "#context/keys.js";
+import { createWorkflowCallbackUrl } from "#execution/workflow-callback-url.js";
import type { ConnectionAuthorizationChallenge } from "#public/connections/errors.js";
import type { AuthorizationCallback, ConnectionPrincipal } from "#runtime/connections/types.js";
import type { JsonValue } from "#public/types/json.js";
@@ -176,7 +177,10 @@ export function getHookUrl(name: string, attemptId: string): string | undefined
const baseUrl = ctx.get(CallbackBaseUrlKey);
if (!sessionId || !baseUrl) return undefined;
const token = authHookToken(sessionId);
- return `${baseUrl}${createEveConnectionCallbackRoutePath(name, attemptId, token)}`;
+ return createWorkflowCallbackUrl(
+ baseUrl,
+ createEveConnectionCallbackRoutePath(name, attemptId, token),
+ );
}
/** Mints the identity and callback URL for one interactive authorization attempt. */
diff --git a/packages/eve/src/harness/execute-tool.ts b/packages/eve/src/harness/execute-tool.ts
index cca9701f7..bfb9168ab 100644
--- a/packages/eve/src/harness/execute-tool.ts
+++ b/packages/eve/src/harness/execute-tool.ts
@@ -8,13 +8,20 @@ import type { ToolExecuteOptions } from "#shared/tool-definition.js";
*
* These tools are surfaced to the model without a local `execute` function.
* The harness records the tool call and the runtime executes it later.
+ *
+ * `task-control` marks the `experimental.tasks` parent tools
+ * (`task_peek`, `task_cancel`): they carry no child
+ * address of their own — the dispatch step resolves targets through the
+ * session task index by tool name.
*/
-export type HarnessRuntimeActionDefinition = {
- readonly kind: "remote-agent-call" | "subagent-call";
- readonly nodeId: string;
- readonly remoteAgentName?: string;
- readonly subagentName: string;
-};
+export type HarnessRuntimeActionDefinition =
+ | {
+ readonly kind: "remote-agent-call" | "subagent-call";
+ readonly nodeId: string;
+ readonly remoteAgentName?: string;
+ readonly subagentName: string;
+ }
+ | { readonly kind: "task-control" };
/**
* Unified harness-owned tool definition.
diff --git a/packages/eve/src/harness/handles/prompt.test.ts b/packages/eve/src/harness/handles/prompt.test.ts
index 906a7dd6d..21463f7cd 100644
--- a/packages/eve/src/harness/handles/prompt.test.ts
+++ b/packages/eve/src/harness/handles/prompt.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import {
projectParkedAgentHandles,
+ renderAgentViewsSnippet,
renderAgentsSnippet,
resolveAgentsAnnouncement,
} from "#harness/handles/prompt.js";
@@ -68,6 +69,26 @@ describe("projectParkedAgentHandles / renderAgentsSnippet", () => {
});
});
+describe("renderAgentViewsSnippet", () => {
+ it("keeps task-owned agents visible with derived busy state", () => {
+ const snippet = renderAgentViewsSnippet([
+ {
+ availability: "busy",
+ id: identity.id,
+ name: identity.name,
+ taskId: "task_123",
+ taskStatus: "input_required",
+ },
+ ]);
+
+ expect(snippet).toContain(
+ `<agent id="${identity.id}" name="research" availability="busy" taskId="task_123" taskStatus="input_required">(busy)</agent>`,
+ );
+ expect(snippet).not.toContain("SESSION_ID_SENTINEL");
+ expect(snippet).not.toContain("CONTINUATION_TOKEN_SENTINEL");
+ });
+});
+
describe("resolveAgentsAnnouncement", () => {
it("announces a changed listing without replacing earlier conversation content", () => {
const messages = [{ content: "Earlier response", role: "assistant" as const }];
diff --git a/packages/eve/src/harness/handles/prompt.ts b/packages/eve/src/harness/handles/prompt.ts
index b6399ad55..07cdfe3d2 100644
--- a/packages/eve/src/harness/handles/prompt.ts
+++ b/packages/eve/src/harness/handles/prompt.ts
@@ -9,6 +9,16 @@ import type { AgentHandle, AgentHandleStore } from "#harness/handles/store.js";
*/
export const AGENTS_SNIPPET_LABEL = "[Agents]";
+/** Model-safe projection of one persistent task-mode agent. */
+export interface AgentView {
+ readonly availability: "available" | "busy";
+ readonly id: string;
+ readonly name: string;
+ readonly statusLine?: string;
+ readonly taskId?: string;
+ readonly taskStatus?: "working" | "input_required";
+}
+
/** Returns the resumable handles: the only phase the model may continue. */
export function projectParkedAgentHandles(
store: AgentHandleStore,
@@ -29,6 +39,19 @@ export function renderAgentsSnippet(store: AgentHandleStore): string {
return [AGENTS_SNIPPET_LABEL, "<agents>", ...agents, "</agents>"].join("\n");
}
+/** Renders task-derived availability without exposing private addresses. */
+export function renderAgentViewsSnippet(views: readonly AgentView[]): string {
+ const agents = views.map((view) => {
+ const task =
+ view.taskId === undefined || view.taskStatus === undefined
+ ? ""
+ : ` taskId="${escapeXml(view.taskId)}" taskStatus="${view.taskStatus}"`;
+ const status = view.statusLine ?? (view.availability === "busy" ? "(busy)" : "(available)");
+ return `<agent id="${escapeXml(view.id)}" name="${escapeXml(view.name)}" availability="${view.availability}"${task}>${escapeXml(status)}</agent>`;
+ });
+ return [AGENTS_SNIPPET_LABEL, "<agents>", ...agents, "</agents>"].join("\n");
+}
+
/**
* Returns an append-only announcement when the visible handle listing
* changed since the last one in history, or `undefined` when it is
@@ -48,6 +71,7 @@ export function renderAgentsSnippet(store: AgentHandleStore): string {
* eve-injected so the model does not attribute it to the user.
*/
export function resolveAgentsAnnouncement(input: {
+ readonly agentViews?: readonly AgentView[];
readonly messages: readonly ModelMessage[];
readonly store: AgentHandleStore | undefined;
}): string | undefined {
@@ -58,12 +82,16 @@ export function resolveAgentsAnnouncement(input: {
message.content.startsWith(AGENTS_SNIPPET_LABEL),
);
const store = input.store ?? { handles: [] };
+ const visibleCount = input.agentViews?.length ?? projectParkedAgentHandles(store).length;
- if (latest === undefined && projectParkedAgentHandles(store).length === 0) {
+ if (latest === undefined && visibleCount === 0) {
return undefined;
}
- const rendered = renderAgentsSnippet(store);
+ const rendered =
+ input.agentViews === undefined
+ ? renderAgentsSnippet(store)
+ : renderAgentViewsSnippet(input.agentViews);
return latest?.content === rendered ? undefined : rendered;
}
diff --git a/packages/eve/src/harness/handles/query.ts b/packages/eve/src/harness/handles/query.ts
index 68bc6799c..63d9c9149 100644
--- a/packages/eve/src/harness/handles/query.ts
+++ b/packages/eve/src/harness/handles/query.ts
@@ -64,7 +64,7 @@ export function isResultBoundToRunningHandle(
if (result.kind !== "subagent-result") {
return true;
}
- if (result.origin === "dispatch") {
+ if (result.origin === "dispatch" || result.backgroundTask !== undefined) {
return true;
}
return findRunningAgentHandle(state, { callId: result.callId }) !== undefined;
diff --git a/packages/eve/src/harness/handles/store.test.ts b/packages/eve/src/harness/handles/store.test.ts
index 7d4c8508d..a11947161 100644
--- a/packages/eve/src/harness/handles/store.test.ts
+++ b/packages/eve/src/harness/handles/store.test.ts
@@ -43,6 +43,12 @@ const parkedHandle: AgentHandle = {
phase: "parked",
};
+const addressedHandle: AgentHandle = {
+ address,
+ identity,
+ phase: "addressed",
+};
+
describe("deriveAgentOperationId / deriveAgentId", () => {
it("is deterministic on parent-controlled inputs and independent of the child session", () => {
const again = deriveAgentOperationId({
@@ -105,8 +111,8 @@ describe("getAgentHandleStore", () => {
describe("assertPersistableAgentHandleStore", () => {
it("returns a valid store unchanged in shape", () => {
- expect(assertPersistableAgentHandleStore({ handles: [parkedHandle] })).toEqual({
- handles: [parkedHandle],
+ expect(assertPersistableAgentHandleStore({ handles: [addressedHandle] })).toEqual({
+ handles: [addressedHandle],
});
});
diff --git a/packages/eve/src/harness/handles/store.ts b/packages/eve/src/harness/handles/store.ts
index 319839ded..b9c52d774 100644
--- a/packages/eve/src/harness/handles/store.ts
+++ b/packages/eve/src/harness/handles/store.ts
@@ -92,7 +92,7 @@ export type AgentAddress =
/**
* Durable ownership record for one delegated child.
*
- * The store owns the full nonterminal lifecycle:
+ * Outside tasks mode, the store owns the full nonterminal lifecycle:
*
* - `starting` — the parent committed intent to start; the child may or
* may not exist yet.
@@ -100,7 +100,9 @@ export type AgentAddress =
* - `parked` — the child is idle and resumable; only this phase is
* model-visible.
*
- * A terminal child has no handle: settlement deletes it.
+ * A terminal child has no legacy handle: settlement deletes it. Tasks mode
+ * instead keeps an `addressed` record whose availability is derived from the
+ * tasks bound to its persistent child session.
*/
export type AgentHandle =
| {
@@ -120,6 +122,12 @@ export type AgentHandle =
readonly identity: AgentIdentity;
readonly address: AgentAddress;
readonly lastStatus: string;
+ }
+ | {
+ /** Persistent task-mode identity and routing, with no execution claim. */
+ readonly phase: "addressed";
+ readonly identity: AgentIdentity;
+ readonly address: AgentAddress;
};
/** Lifecycle phase of a delegated agent handle. */
@@ -201,6 +209,11 @@ const agentHandleSchema: z.ZodType<AgentHandle> = z.discriminatedUnion("phase",
lastStatus: z.string().max(MAX_STATUS_LENGTH),
phase: z.literal("parked"),
}),
+ z.strictObject({
+ address: addressSchema,
+ identity: identitySchema,
+ phase: z.literal("addressed"),
+ }),
]);
const agentHandleStoreSchema: z.ZodType<AgentHandleStore> = z
diff --git a/packages/eve/src/harness/handles/transitions.test.ts b/packages/eve/src/harness/handles/transitions.test.ts
index 9ae42ea72..7221d1ffd 100644
--- a/packages/eve/src/harness/handles/transitions.test.ts
+++ b/packages/eve/src/harness/handles/transitions.test.ts
@@ -13,9 +13,11 @@ import {
import {
abandonRunningAgentTurns,
confirmAgentStarted,
+ confirmTaskAgentAddress,
prepareAgentContinuation,
prepareAgentStart,
rejectAgentEffect,
+ removeTaskAgentAddress,
settleAgentTurn,
} from "#harness/handles/transitions.js";
import type { HarnessSession } from "#harness/types.js";
@@ -143,6 +145,26 @@ describe("confirmAgentStarted", () => {
});
});
+describe("task agent addresses", () => {
+ it("confirms a persistent address without an execution phase", () => {
+ const addressed = confirmTaskAgentAddress(preparedSession(), {
+ address,
+ operationId: startOperation.id,
+ });
+
+ expect(handlesOf(addressed)).toEqual([{ address, identity, phase: "addressed" }]);
+ });
+
+ it("removes only the addressed task agent", () => {
+ const addressed = confirmTaskAgentAddress(preparedSession(), {
+ address,
+ operationId: startOperation.id,
+ });
+
+ expect(handlesOf(removeTaskAgentAddress(addressed, identity.id))).toEqual([]);
+ });
+});
+
describe("prepareAgentContinuation", () => {
const continueOperation: ContinueOperation = {
callId: "call_2",
diff --git a/packages/eve/src/harness/handles/transitions.ts b/packages/eve/src/harness/handles/transitions.ts
index bd8574257..f53eb17c4 100644
--- a/packages/eve/src/harness/handles/transitions.ts
+++ b/packages/eve/src/harness/handles/transitions.ts
@@ -9,7 +9,7 @@ import {
type ContinueOperation,
type StartOperation,
} from "#harness/handles/store.js";
-import type { HarnessSession } from "#harness/types.js";
+import type { HarnessSession, SessionStateMap } from "#harness/types.js";
import type { AgentTurnOutcome } from "#shared/agent-turn-outcome.js";
/**
@@ -124,7 +124,8 @@ function findActiveHandle(
): ActiveAgentHandle | undefined {
return handles.find(
(handle): handle is ActiveAgentHandle =>
- handle.phase !== "parked" && handle.operation.id === operationId,
+ (handle.phase === "starting" || handle.phase === "running") &&
+ handle.operation.id === operationId,
);
}
@@ -166,6 +167,60 @@ export function confirmAgentStarted(
);
}
+/** Confirms a task-mode child as a persistent identity/address record. */
+export function confirmTaskAgentAddress(
+ session: HarnessSession,
+ input: {
+ readonly operationId: string;
+ readonly address: AgentAddress;
+ },
+): HarnessSession {
+ const handles = getAgentHandleStore(session.state)?.handles ?? [];
+ const existing = findActiveHandle(handles, input.operationId);
+ if (existing === undefined) {
+ throw new Error(`No prepared agent handle for operation "${input.operationId}".`);
+ }
+ if (existing.phase === "running") {
+ throw new Error(
+ `Task agent operation "${input.operationId}" was confirmed as a running handle.`,
+ );
+ }
+
+ return writeHandles(
+ session,
+ handles.map((handle) =>
+ handle === existing
+ ? {
+ address: input.address,
+ identity: existing.identity,
+ phase: "addressed" as const,
+ }
+ : handle,
+ ),
+ );
+}
+
+/** Removes a task-mode address after permanent delivery failure. */
+export function removeTaskAgentAddress(session: HarnessSession, agentId: string): HarnessSession {
+ return { ...session, state: removeTaskAgentAddressFromState(session.state, agentId) };
+}
+
+/** State-only variant used while consuming a terminal task wake. */
+export function removeTaskAgentAddressFromState(
+ state: SessionStateMap | undefined,
+ agentId: string,
+): SessionStateMap {
+ const handles = getAgentHandleStore(state)?.handles ?? [];
+ return {
+ ...state,
+ [AGENT_HANDLES_STATE_KEY]: assertPersistableAgentHandleStore({
+ handles: handles.filter(
+ (handle) => !(handle.phase === "addressed" && handle.identity.id === agentId),
+ ),
+ }),
+ };
+}
+
/**
* Resolves a dispatch that definitively failed.
*
diff --git a/packages/eve/src/harness/proxy-input-requests.test.ts b/packages/eve/src/harness/proxy-input-requests.test.ts
index 2732a0d68..b58331241 100644
--- a/packages/eve/src/harness/proxy-input-requests.test.ts
+++ b/packages/eve/src/harness/proxy-input-requests.test.ts
@@ -4,7 +4,6 @@ import {
clearProxyInputRequestsForChild,
getProxyInputRequests,
hasProxyInputRequests,
- retireProxyInputRequests,
toProxyInputRequestEntries,
upsertProxyInputRequests,
} from "#harness/proxy-input-requests.js";
@@ -52,7 +51,38 @@ describe("upsertProxyInputRequests", () => {
});
});
- it("keeps two batches from the same child independently addressable", () => {
+ it("round-trips task ownership without exposing malformed ownership as an unscoped route", () => {
+ const next = upsertProxyInputRequests({
+ entries: [
+ [
+ "task-1:req-1",
+ {
+ childContinuationToken: "child-a",
+ childRequestId: "req-1",
+ kind: "question",
+ taskId: "task-1",
+ },
+ ],
+ ],
+ forChildContinuationToken: "child-a",
+ session: createSession(),
+ });
+ expect(getProxyInputRequests(next.state).get("task-1:req-1")).toEqual({
+ childContinuationToken: "child-a",
+ childRequestId: "req-1",
+ kind: "question",
+ taskId: "task-1",
+ });
+ expect(
+ getProxyInputRequests({
+ "eve.runtime.proxyInputRequests": {
+ "req-1": { childContinuationToken: "child-a", kind: "question", taskId: 42 },
+ },
+ }).size,
+ ).toBe(0);
+ });
+
+ it("replaces prior entries for the same child continuation token", () => {
let session = upsertProxyInputRequests({
entries: [["req-1", { childContinuationToken: "child-a", kind: "question" }]],
forChildContinuationToken: "child-a",
@@ -66,18 +96,15 @@ describe("upsertProxyInputRequests", () => {
});
const entries = getProxyInputRequests(session.state);
- expect(entries.size).toBe(2);
- expect(entries.get("req-1")).toEqual({
- childContinuationToken: "child-a",
- kind: "question",
- });
+ expect(entries.size).toBe(1);
+ expect(entries.get("req-1")).toBeUndefined();
expect(entries.get("req-2")).toEqual({
childContinuationToken: "child-a",
kind: "question",
});
});
- it("replaces only a reused request ID", () => {
+ it("drops a prior child's batch when its request ID is claimed by another child", () => {
let session = upsertProxyInputRequests({
entries: [
["req-1", { childContinuationToken: "child-a", kind: "question" }],
@@ -93,10 +120,10 @@ describe("upsertProxyInputRequests", () => {
session,
});
- expect([...getProxyInputRequests(session.state)]).toEqual([
- ["req-1", { childContinuationToken: "child-b", kind: "tool-approval" }],
- ["req-2", { childContinuationToken: "child-a", kind: "question" }],
- ]);
+ expect(Object.fromEntries(getProxyInputRequests(session.state))).toEqual({
+ "req-1": { childContinuationToken: "child-b", kind: "tool-approval" },
+ "req-2": { childContinuationToken: "child-a", kind: "question" },
+ });
});
it("keeps entries from other children when upserting", () => {
@@ -198,30 +225,6 @@ describe("clearProxyInputRequestsForChild", () => {
});
});
-describe("retireProxyInputRequests", () => {
- it("removes only answered request IDs, including partial same-child batches", () => {
- const session = upsertProxyInputRequests({
- entries: [
- ["req-1", { childContinuationToken: "child-a", kind: "question" }],
- ["req-2", { childContinuationToken: "child-a", kind: "question" }],
- ],
- forChildContinuationToken: "child-a",
- session: createSession(),
- });
-
- const next = retireProxyInputRequests(session, ["req-1"]);
-
- expect([...getProxyInputRequests(next.state)]).toEqual([
- ["req-2", { childContinuationToken: "child-a", kind: "question" }],
- ]);
- });
-
- it("is idempotent for an already-retired request ID", () => {
- const session = createSession();
- expect(retireProxyInputRequests(session, ["req-1"])).toBe(session);
- });
-});
-
describe("getProxyInputRequests type safety", () => {
it("returns an empty map when the session carries no proxy state", () => {
const entries = getProxyInputRequests(createSession().state);
@@ -269,4 +272,45 @@ describe("getProxyInputRequests type safety", () => {
["malformed", { childContinuationToken: "child-a", kind: "tool-approval" }],
]);
});
+
+ it("accepts HTTPS child response URLs", () => {
+ expect(readChildResponseUrl("https://remote.example/eve/v1/task-input/token")).toBe(
+ "https://remote.example/eve/v1/task-input/token",
+ );
+ });
+
+ it.each([
+ "http://localhost:3000/eve/v1/task-input/token",
+ "http://worker.localhost:3000/eve/v1/task-input/token",
+ "http://127.0.0.1:3000/eve/v1/task-input/token",
+ "http://127.0.0.2:3000/eve/v1/task-input/token",
+ "http://[::1]:3000/eve/v1/task-input/token",
+ "http://[::ffff:7f00:1]:3000/eve/v1/task-input/token",
+ ])("accepts an HTTP loopback child response URL: %s", (url) => {
+ expect(readChildResponseUrl(url)).toBe(url);
+ });
+
+ it.each([
+ "http://remote.example/eve/v1/task-input/token",
+ "http://10.0.0.1/eve/v1/task-input/token",
+ "http://localhost.example/eve/v1/task-input/token",
+ "ftp://localhost/eve/v1/task-input/token",
+ "not a URL",
+ ])("rejects a non-HTTPS, non-loopback, or malformed child response URL: %s", (url) => {
+ expect(readChildResponseUrl(url)).toBeUndefined();
+ });
});
+
+function readChildResponseUrl(childResponseUrl: string): string | undefined {
+ return getProxyInputRequests({
+ "eve.runtime.proxyInputRequests": {
+ "task-1:req-1": {
+ childContinuationToken: "child-a",
+ childRequestId: "req-1",
+ childResponseUrl,
+ kind: "question",
+ taskId: "task-1",
+ },
+ },
+ }).get("task-1:req-1")?.childResponseUrl;
+}
diff --git a/packages/eve/src/harness/proxy-input-requests.ts b/packages/eve/src/harness/proxy-input-requests.ts
index f19dd9dac..d24046b03 100644
--- a/packages/eve/src/harness/proxy-input-requests.ts
+++ b/packages/eve/src/harness/proxy-input-requests.ts
@@ -1,6 +1,7 @@
import type { SubagentInputRequestHookPayload } from "#channel/types.js";
import type { HarnessSession, SessionStateMap } from "#harness/types.js";
import type { InputRequestKind } from "#runtime/input/types.js";
+import { isLoopbackHostname } from "#shared/network-address.js";
const PROXY_INPUT_REQUESTS_KEY = "eve.runtime.proxyInputRequests";
@@ -15,7 +16,13 @@ export interface ProxyInputRequest {
/** Batch semantics are optional so sessions written before this field remain routable. */
readonly batch?: ProxyInputRequestBatch;
readonly childContinuationToken: string;
+ /** Child-local id restored before forwarding a namespaced task response. */
+ readonly childRequestId?: string;
+ /** Trusted parent-derived capability URL for a remote task child. */
+ readonly childResponseUrl?: string;
readonly kind: InputRequestKind;
+ /** Present when the route is authorized by a parent-owned durable task. */
+ readonly taskId?: string;
}
export interface ProxyInputRequestBatch {
@@ -26,6 +33,11 @@ export interface ProxyInputRequestBatch {
/** `requestId → route` map stored on the parent session. */
type ProxyInputRequestMap = Readonly<Record<string, ProxyInputRequest>>;
+/** Parent-visible id for one task-owned child-local input request. */
+export function createTaskInputRequestId(taskId: string, childRequestId: string): string {
+ return `${taskId}:${childRequestId}`;
+}
+
/**
* Returns the proxy-routing map as a fresh `Map`. Never returns a live
* reference so accidental mutation cannot corrupt session state.
@@ -48,22 +60,51 @@ export function hasProxyInputRequests(state: SessionStateMap | undefined): boole
}
/**
- * Merges the provided routes into the parent session by request ID. Existing
- * routes with different IDs stay independently answerable; re-recording the
- * same request ID replaces only that route, making durable retries idempotent.
+ * Replaces prior entries for `forChildContinuationToken` with the provided
+ * ones. A child raising a fresh batch overwrites its prior batch so the
+ * parent never keeps stale request metadata. Other children's routes stay
+ * independently answerable.
*/
export function upsertProxyInputRequests(input: {
readonly entries: readonly (readonly [requestId: string, route: ProxyInputRequest])[];
readonly forChildContinuationToken: string;
readonly session: HarnessSession;
}): HarnessSession {
- const next = { ...readMap(input.session.state) };
+ return {
+ ...input.session,
+ state: upsertProxyInputRequestState({
+ entries: input.entries,
+ forChildContinuationToken: input.forChildContinuationToken,
+ state: input.session.state,
+ }),
+ };
+}
+
+/** State-only variant for control-plane steps that already hold a durable projection. */
+export function upsertProxyInputRequestState(input: {
+ readonly entries: readonly (readonly [requestId: string, route: ProxyInputRequest])[];
+ readonly forChildContinuationToken: string;
+ readonly state: SessionStateMap | undefined;
+}): SessionStateMap | undefined {
+ const next: Record<string, ProxyInputRequest> = {};
+
+ for (const [requestId, route] of Object.entries(readMap(input.state))) {
+ if (route.childContinuationToken !== input.forChildContinuationToken) {
+ next[requestId] = route;
+ }
+ }
for (const [requestId, route] of input.entries) {
next[requestId] = route;
}
- return writeMap(input.session, next);
+ const state = { ...input.state };
+ if (Object.keys(next).length === 0) {
+ delete state[PROXY_INPUT_REQUESTS_KEY];
+ } else {
+ state[PROXY_INPUT_REQUESTS_KEY] = next;
+ }
+ return Object.keys(state).length > 0 ? state : undefined;
}
/**
@@ -112,6 +153,24 @@ export function retireProxyInputRequests<T extends { readonly state?: SessionSta
return changed ? writeMap(session, next) : session;
}
+/** Removes every proxy route owned by one durable task. */
+export function clearProxyInputRequestsForTask(
+ session: HarnessSession,
+ taskId: string,
+): HarnessSession {
+ const current = readMap(session.state);
+ const next: Record<string, ProxyInputRequest> = {};
+ let changed = false;
+ for (const [requestId, route] of Object.entries(current)) {
+ if (route.taskId === taskId) {
+ changed = true;
+ } else {
+ next[requestId] = route;
+ }
+ }
+ return changed ? writeMap(session, next) : session;
+}
+
/**
* Removes every proxy entry. Called when a cancelled turn orphans its
* descendants so stale HITL responses no longer route to them.
@@ -129,6 +188,7 @@ export function clearAllProxyInputRequests(session: HarnessSession): HarnessSess
*/
export function toProxyInputRequestEntries(
payload: SubagentInputRequestHookPayload,
+ taskId?: string,
): readonly (readonly [requestId: string, route: ProxyInputRequest])[] {
const batch: ProxyInputRequestBatch = {
approvalRequestIds: payload.event.requests.flatMap((request) =>
@@ -136,18 +196,20 @@ export function toProxyInputRequestEntries(
),
requestIds: payload.event.requests.map((request) => request.requestId),
};
-
- return payload.event.requests.map(
- (request) =>
- [
- request.requestId,
- {
- batch,
- childContinuationToken: payload.childContinuationToken,
- kind: request.kind,
- },
- ] as const,
- );
+ return payload.event.requests.map((request) => {
+ const route: {
+ readonly childContinuationToken: string;
+ childResponseUrl?: string;
+ readonly kind: InputRequestKind;
+ taskId?: string;
+ } & { readonly batch: ProxyInputRequestBatch } = {
+ batch,
+ childContinuationToken: payload.childContinuationToken,
+ kind: request.kind,
+ };
+ if (taskId !== undefined) route.taskId = taskId;
+ return [request.requestId, route] as const;
+ });
}
function readMap(state: SessionStateMap | undefined): ProxyInputRequestMap {
@@ -195,26 +257,49 @@ function parseProxyInputRequest(value: unknown, requestId: string): ProxyInputRe
if (typeof value.childContinuationToken !== "string" || !isInputRequestKind(value.kind)) {
return undefined;
}
- const request = {
+ const taskId = "taskId" in value ? value.taskId : undefined;
+ const childRequestId = "childRequestId" in value ? value.childRequestId : undefined;
+ const childResponseUrl = "childResponseUrl" in value ? value.childResponseUrl : undefined;
+ if (taskId !== undefined && (typeof taskId !== "string" || taskId.length === 0)) {
+ return undefined;
+ }
+ if (
+ childRequestId !== undefined &&
+ (typeof childRequestId !== "string" || childRequestId.length === 0)
+ ) {
+ return undefined;
+ }
+ if ((taskId === undefined) !== (childRequestId === undefined)) return undefined;
+ if (
+ childResponseUrl !== undefined &&
+ (typeof childResponseUrl !== "string" || !isAllowedChildResponseUrl(childResponseUrl))
+ ) {
+ return undefined;
+ }
+ const batch = "batch" in value ? parseProxyInputRequestBatch(value.batch) : undefined;
+ const request: {
+ batch?: ProxyInputRequestBatch;
+ readonly childContinuationToken: string;
+ childRequestId?: string;
+ childResponseUrl?: string;
+ readonly kind: InputRequestKind;
+ taskId?: string;
+ } = {
childContinuationToken: value.childContinuationToken,
kind: value.kind,
};
- const batch = "batch" in value ? parseProxyInputRequestBatch(value.batch) : undefined;
- return batch === undefined || !batch.requestIds.includes(requestId)
- ? request
- : { ...request, batch };
+ if (batch !== undefined && batch.requestIds.includes(requestId)) request.batch = batch;
+ if (typeof childRequestId === "string") request.childRequestId = childRequestId;
+ if (typeof childResponseUrl === "string") request.childResponseUrl = childResponseUrl;
+ if (typeof taskId === "string") request.taskId = taskId;
+ return request;
}
function parseProxyInputRequestBatch(value: unknown): ProxyInputRequestBatch | undefined {
- if (value === null || typeof value !== "object" || Array.isArray(value)) {
- return undefined;
- }
- if (!("approvalRequestIds" in value) || !("requestIds" in value)) {
- return undefined;
- }
- if (!isStringArray(value.approvalRequestIds) || !isStringArray(value.requestIds)) {
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;
+ if (!("approvalRequestIds" in value) || !("requestIds" in value)) return undefined;
+ if (!isStringArray(value.approvalRequestIds) || !isStringArray(value.requestIds))
return undefined;
- }
const requestIds = new Set(value.requestIds);
if (
requestIds.size !== value.requestIds.length ||
@@ -222,16 +307,24 @@ function parseProxyInputRequestBatch(value: unknown): ProxyInputRequestBatch | u
) {
return undefined;
}
- return {
- approvalRequestIds: value.approvalRequestIds,
- requestIds: value.requestIds,
- };
+ return { approvalRequestIds: value.approvalRequestIds, requestIds: value.requestIds };
}
function isStringArray(value: unknown): value is string[] {
return Array.isArray(value) && value.every((entry) => typeof entry === "string");
}
+function isAllowedChildResponseUrl(value: string): boolean {
+ let url: URL;
+ try {
+ url = new URL(value);
+ } catch {
+ return false;
+ }
+ if (url.protocol === "https:") return true;
+ return url.protocol === "http:" && isLoopbackHostname(url.hostname);
+}
+
function isInputRequestKind(value: unknown): value is InputRequestKind {
return typeof value === "string" && Object.hasOwn(PROXY_INPUT_REQUEST_KINDS, value);
}
diff --git a/packages/eve/src/harness/runtime-actions.test.ts b/packages/eve/src/harness/runtime-actions.test.ts
index 07afc1be0..abbb839dc 100644
--- a/packages/eve/src/harness/runtime-actions.test.ts
+++ b/packages/eve/src/harness/runtime-actions.test.ts
@@ -15,12 +15,14 @@ import { deriveAgentOperationId } from "#harness/handles/operation-id.js";
import { deriveAgentId, getAgentHandleStore } from "#harness/handles/store.js";
import {
confirmAgentStarted,
+ confirmTaskAgentAddress,
prepareAgentContinuation,
prepareAgentStart,
} from "#harness/handles/transitions.js";
import { getProxyInputRequests, upsertProxyInputRequests } from "#harness/proxy-input-requests.js";
import { getSessionTokenUsage, setTurnUsageState } from "#harness/turn-tag-state.js";
import type { HarnessSession } from "#harness/types.js";
+import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
const CHILD_SESSION_ID = "local-child-123456789012";
const CHILD_CONTINUATION_TOKEN = "subagent:private-token";
@@ -123,6 +125,29 @@ function createParkedSession(): HarnessSession {
});
}
+describe("runtime action batch identity", () => {
+ it("rejects duplicate call ids before persisting the batch", () => {
+ const action = {
+ callId: "duplicate-call",
+ description: "research subagent",
+ input: { message: "go" },
+ kind: "subagent-call" as const,
+ name: "researcher",
+ nodeId: "subagents/researcher",
+ subagentName: "researcher",
+ };
+
+ expect(() =>
+ setPendingRuntimeActionBatch({
+ actions: [action, { ...action, name: "other", subagentName: "other" }],
+ event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
+ responseMessages: [],
+ session: createParkedSession(),
+ }),
+ ).toThrow('duplicate callId "duplicate-call"');
+ });
+});
+
/** Parked session whose call-1 child is owned by a running agent handle. */
function createSessionWithRunningChild(): HarnessSession {
const prepared = prepareAgentStart(createParkedSession(), {
@@ -149,7 +174,72 @@ function createSessionWithRunningChild(): HarnessSession {
});
}
+function createSessionWithTaskAddress(): HarnessSession {
+ const prepared = prepareAgentStart(createParkedSession(), {
+ identity: {
+ id: deriveAgentId("researcher", OPERATION_ID),
+ name: "researcher",
+ nodeId: "subagents/researcher",
+ },
+ operation: {
+ callId: "call-1",
+ id: OPERATION_ID,
+ kind: "start",
+ parentTurnId: "turn_0",
+ },
+ target: { continuationToken: CHILD_CONTINUATION_TOKEN, kind: "agent/local" },
+ });
+ return confirmTaskAgentAddress(prepared, {
+ address: {
+ continuationToken: CHILD_CONTINUATION_TOKEN,
+ kind: "agent/local",
+ sessionId: CHILD_SESSION_ID,
+ },
+ operationId: OPERATION_ID,
+ });
+}
+
describe("resolvePendingRuntimeActions", () => {
+ it("marks a working task receipt as backgrounded on subagent.completed", async () => {
+ const events: UnstampedMessageStreamEvent[] = [];
+ const taskId = "task_0123456789abcdef";
+
+ const resolved = await resolvePendingRuntimeActions({
+ emit: async (event) => {
+ events.push(event);
+ },
+ session: createSessionWithTaskAddress(),
+ stepInput: {
+ runtimeActionResults: [
+ {
+ backgroundTask: { status: "working", taskId },
+ callId: "call-1",
+ kind: "subagent-result",
+ origin: "child",
+ outcome: {
+ kind: "parked",
+ result: { kind: "succeeded", output: "delegated" },
+ usageDelta: ZERO_USAGE,
+ },
+ output: {
+ agentId: deriveAgentId("researcher", OPERATION_ID),
+ status: "working",
+ taskId,
+ },
+ subagentName: "researcher",
+ },
+ ],
+ },
+ });
+
+ expect(events.find((event) => event.type === "subagent.completed")).toMatchObject({
+ data: { backgroundTask: { status: "working", taskId } },
+ });
+ expect(getAgentHandleStore(resolved.session.state)?.handles).toEqual([
+ expect.objectContaining({ phase: "addressed" }),
+ ]);
+ });
+
it("settles the running handle terminally and deletes it with the batch", async () => {
const session = createSessionWithRunningChild();
diff --git a/packages/eve/src/harness/runtime-actions.ts b/packages/eve/src/harness/runtime-actions.ts
index f69f9c90a..32f7c90be 100644
--- a/packages/eve/src/harness/runtime-actions.ts
+++ b/packages/eve/src/harness/runtime-actions.ts
@@ -120,6 +120,7 @@ export function setPendingRuntimeActionBatch(input: {
readonly responseMessages: readonly ModelMessage[];
readonly session: HarnessSession;
}): HarnessSession {
+ assertUniqueRuntimeActionCallIds(input.actions);
const state = { ...input.session.state };
state[PENDING_RUNTIME_ACTION_BATCH_KEY] = {
actions: [...input.actions],
@@ -130,6 +131,17 @@ export function setPendingRuntimeActionBatch(input: {
return { ...input.session, state };
}
+/** Rejects an ambiguous action batch before any result or side effect can bind by call id. */
+export function assertUniqueRuntimeActionCallIds(actions: readonly RuntimeActionRequest[]): void {
+ const seen = new Set<string>();
+ for (const action of actions) {
+ if (seen.has(action.callId)) {
+ throw new Error(`Runtime action batch contains duplicate callId "${action.callId}".`);
+ }
+ seen.add(action.callId);
+ }
+}
+
/**
* Returns the stable ordered runtime-action results for the current pending
* batch when every action has a matching result. Unknown and duplicate results
@@ -202,13 +214,14 @@ export async function resolvePendingRuntimeActions(input: {
if (input.emit !== undefined) {
for (const result of readyResults) {
if (result.kind === "subagent-result" && result.isError !== true) {
+ const backgroundTask = readBackgroundTaskReceipt(result);
+ const data = {
+ callId: result.callId,
+ output: typeof result.output === "string" ? result.output : JSON.stringify(result.output),
+ subagentName: result.subagentName,
+ };
await input.emit({
- data: {
- callId: result.callId,
- output:
- typeof result.output === "string" ? result.output : JSON.stringify(result.output),
- subagentName: result.subagentName,
- },
+ data: backgroundTask === undefined ? data : { ...data, backgroundTask },
type: "subagent.completed",
} satisfies Extract<UnstampedMessageStreamEvent, { type: "subagent.completed" }>);
}
@@ -237,6 +250,11 @@ export async function resolvePendingRuntimeActions(input: {
if (result.kind !== "subagent-result" || result.origin !== "child") {
continue;
}
+ // A background receipt confirms task admission, not child-turn settlement.
+ // The task snapshot later carries the actual parked/terminal outcome.
+ if (readBackgroundTaskReceipt(result) !== undefined) {
+ continue;
+ }
const handle = findRunningAgentHandle(nextSession.state, { callId: result.callId });
if (handle === undefined) {
continue;
@@ -331,6 +349,12 @@ export async function resolvePendingRuntimeActions(input: {
};
}
+function readBackgroundTaskReceipt(
+ result: Extract<RuntimeActionResult, { kind: "subagent-result" }>,
+): { readonly status: "working"; readonly taskId: string } | undefined {
+ return "backgroundTask" in result ? result.backgroundTask : undefined;
+}
+
/**
* Projects one AI SDK tool call into the eve runtime-action contract.
*/
diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.ts
index ebdbe4cc2..314a23504 100644
--- a/packages/eve/src/harness/tool-loop.ts
+++ b/packages/eve/src/harness/tool-loop.ts
@@ -1126,12 +1126,12 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
// assistant-final histories. See resolveAgentsAnnouncement for the role
// rationale (assistant-final rejection, prompt-cache preservation).
if (config.persistentSubagentSessions === true) {
- const announcement = resolveAgentsAnnouncement({
- messages,
- store: getAgentHandleStore(session.state),
- });
- if (announcement !== undefined) {
- messages.push({ content: announcement, role: "user" });
+ const store = getAgentHandleStore(session.state);
+ if (store?.handles.some((handle) => handle.phase === "addressed") !== true) {
+ const announcement = resolveAgentsAnnouncement({ messages, store });
+ if (announcement !== undefined) {
+ messages.push({ content: announcement, role: "user" });
+ }
}
}
@@ -2625,6 +2625,7 @@ async function handleStepResult(input: {
)) {
await emit(
createAuthorizationCompletedEvent({
+ attemptId: superseded.attemptId,
authorization: superseded.challenge,
name: superseded.name,
outcome: "failed",
@@ -2638,6 +2639,7 @@ async function handleStepResult(input: {
for (const ch of challenges) {
await emit(
createAuthorizationRequiredEvent({
+ attemptId: ch.attemptId,
authorization: ch.challenge,
name: ch.name,
description: ch.challenge.instructions ?? `Authorization required for ${ch.name}`,
diff --git a/packages/eve/src/harness/workflow-runtime-action-state.ts b/packages/eve/src/harness/workflow-runtime-action-state.ts
index 46d20864a..36246045a 100644
--- a/packages/eve/src/harness/workflow-runtime-action-state.ts
+++ b/packages/eve/src/harness/workflow-runtime-action-state.ts
@@ -36,15 +36,21 @@ export function buildRuntimeActionFromWorkflowInterrupt(
};
}
- return {
- callId,
- description: "",
- input: toolInput,
- kind: "subagent-call",
- name: toolName,
- nodeId: runtimeAction.nodeId,
- subagentName: runtimeAction.subagentName,
- };
+ if (runtimeAction.kind === "subagent-call") {
+ return {
+ callId,
+ description: "",
+ input: toolInput,
+ kind: "subagent-call",
+ name: toolName,
+ nodeId: runtimeAction.nodeId,
+ subagentName: runtimeAction.subagentName,
+ };
+ }
+
+ // Dynamic workflows only interrupt on delegation tools; task controls
+ // never enter a workflow sandbox.
+ throw new Error(`Workflow runtime actions cannot carry "${runtimeAction.kind}" tools.`);
}
/** Returns every pending runtime-action interrupt in deterministic ledger order. */
diff --git a/packages/eve/src/internal/authored-definition/core.test.ts b/packages/eve/src/internal/authored-definition/core.test.ts
index b8b9368fe..734499cba 100644
--- a/packages/eve/src/internal/authored-definition/core.test.ts
+++ b/packages/eve/src/internal/authored-definition/core.test.ts
@@ -280,6 +280,34 @@ describe("normalizeAgentDefinition", () => {
),
).toThrow('"experimental.subagentPersistentSessions" must be a boolean.');
});
+
+ it("accepts a boolean tasks flag", () => {
+ const definition = normalizeAgentDefinition(
+ {
+ model: "openai/gpt-5.5",
+ experimental: {
+ tasks: true,
+ },
+ },
+ FAILURE_MESSAGE,
+ );
+
+ expect(definition.experimental?.tasks).toBe(true);
+ });
+
+ it("rejects non-boolean tasks values", () => {
+ expect(() =>
+ normalizeAgentDefinition(
+ {
+ model: "openai/gpt-5.5",
+ experimental: {
+ tasks: "yes",
+ },
+ },
+ FAILURE_MESSAGE,
+ ),
+ ).toThrow('"experimental.tasks" must be a boolean.');
+ });
});
describe("normalizeScheduleDefinition", () => {
diff --git a/packages/eve/src/internal/authored-definition/core.ts b/packages/eve/src/internal/authored-definition/core.ts
index f6f116b33..9f80f99e7 100644
--- a/packages/eve/src/internal/authored-definition/core.ts
+++ b/packages/eve/src/internal/authored-definition/core.ts
@@ -260,7 +260,7 @@ function normalizeAgentExperimentalDefinition(
const record = expectObjectRecord(value, message);
expectOnlyKnownKeys(
record,
- ["instrumentationProviders", "subagentPersistentSessions", "workflow"],
+ ["instrumentationProviders", "subagentPersistentSessions", "tasks", "workflow"],
message,
);
const normalizedDefinition: Mutable<NonNullable<NormalizedAgentDefinition["experimental"]>> = {};
@@ -279,6 +279,13 @@ function normalizeAgentExperimentalDefinition(
normalizedDefinition.subagentPersistentSessions = record.subagentPersistentSessions;
}
+ if (record.tasks !== undefined) {
+ if (typeof record.tasks !== "boolean") {
+ throw new Error(`${message} "experimental.tasks" must be a boolean.`);
+ }
+ normalizedDefinition.tasks = record.tasks;
+ }
+
if (record.workflow !== undefined) {
normalizedDefinition.workflow = normalizeAgentWorkflowDefinition(record.workflow, message);
}
diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts
index da6f7f242..72251b0ba 100644
--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts
+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts
@@ -13,6 +13,7 @@ import { DEVELOPMENT_WORKFLOW_SECRET_ENV } from "#internal/workflow/development-
import {
attachAgentInfoRouteResponse,
attachRouteChannelName,
+ attachRemoteAgentStreamHeadersResolver,
attachRouteSessionCreator,
} from "#internal/nitro/routes/channel-route-context.js";
import type { NitroArtifactsConfig } from "#internal/nitro/routes/runtime-artifacts.js";
@@ -279,6 +280,9 @@ function buildRouteArgs(
requestId,
}),
);
+ if (bundle.resolveRemoteAgentStreamHeaders !== undefined) {
+ attachRemoteAgentStreamHeadersResolver(args, bundle.resolveRemoteAgentStreamHeaders);
+ }
return {
args,
diff --git a/packages/eve/src/internal/nitro/routes/channel-route-context.ts b/packages/eve/src/internal/nitro/routes/channel-route-context.ts
index 7a085f226..d3abad60a 100644
--- a/packages/eve/src/internal/nitro/routes/channel-route-context.ts
+++ b/packages/eve/src/internal/nitro/routes/channel-route-context.ts
@@ -11,13 +11,21 @@ export type RouteSessionCreator = (
input: Omit<RunInput, "adapter" | "channelName" | "requestId">,
) => Promise<RunHandle>;
+export type RemoteAgentStreamHeadersResolver = (input: {
+ readonly name: string;
+ readonly resolverId?: string;
+ readonly url: string;
+}) => Promise<Record<string, string>>;
+
const agentInfoRouteResponseKey = "__eveAgentInfoRouteResponse";
const routeChannelNameKey = "__eveRouteChannelName";
+const remoteAgentStreamHeadersResolverKey = "__eveRemoteAgentStreamHeadersResolver";
const routeSessionCreatorKey = "__eveRouteSessionCreator";
type InternalRouteArgs = RouteHandlerArgs & {
[agentInfoRouteResponseKey]?: AgentInfoRouteResponse;
[routeChannelNameKey]?: string;
+ [remoteAgentStreamHeadersResolverKey]?: RemoteAgentStreamHeadersResolver;
[routeSessionCreatorKey]?: RouteSessionCreator;
};
@@ -64,3 +72,19 @@ export function readRouteSessionCreator(args: RouteHandlerArgs): RouteSessionCre
const routeArgs: InternalRouteArgs = args;
return routeArgs[routeSessionCreatorKey];
}
+
+export function attachRemoteAgentStreamHeadersResolver<TArgs extends RouteHandlerArgs>(
+ args: TArgs,
+ resolve: RemoteAgentStreamHeadersResolver,
+): TArgs {
+ const routeArgs: InternalRouteArgs = args;
+ routeArgs[remoteAgentStreamHeadersResolverKey] = resolve;
+ return args;
+}
+
+export function readRemoteAgentStreamHeadersResolver(
+ args: RouteHandlerArgs,
+): RemoteAgentStreamHeadersResolver | undefined {
+ const routeArgs: InternalRouteArgs = args;
+ return routeArgs[remoteAgentStreamHeadersResolverKey];
+}
diff --git a/packages/eve/src/internal/nitro/routes/runtime-stack.ts b/packages/eve/src/internal/nitro/routes/runtime-stack.ts
index f655325c8..27ff5051e 100644
--- a/packages/eve/src/internal/nitro/routes/runtime-stack.ts
+++ b/packages/eve/src/internal/nitro/routes/runtime-stack.ts
@@ -1,5 +1,7 @@
import type { Runtime } from "#channel/types.js";
import { createWorkflowRuntime } from "#execution/workflow-runtime.js";
+import { resolveRemoteAgentStreamHeaders } from "#execution/remote-agent-dispatch.js";
+import type { RemoteAgentStreamHeadersResolver } from "#internal/nitro/routes/channel-route-context.js";
import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
import type { ResolvedChannelDefinition } from "#runtime/types.js";
import {
@@ -18,6 +20,7 @@ import {
*/
export interface NitroChannelRuntimeBundle {
readonly channels: readonly ResolvedChannelDefinition[];
+ readonly resolveRemoteAgentStreamHeaders?: RemoteAgentStreamHeadersResolver;
readonly runtime: Runtime;
}
@@ -40,6 +43,8 @@ export async function resolveNitroChannelRuntimeBundle(
const runtime = createWorkflowRuntime({ compiledArtifactsSource });
return {
channels: bundle.graph.root.channels,
+ resolveRemoteAgentStreamHeaders: async (input) =>
+ await resolveRemoteAgentStreamHeaders({ bundle, ...input }),
runtime,
};
}
diff --git a/packages/eve/src/protocol/message.test.ts b/packages/eve/src/protocol/message.test.ts
index 01688c0aa..b823d0d3c 100644
--- a/packages/eve/src/protocol/message.test.ts
+++ b/packages/eve/src/protocol/message.test.ts
@@ -14,6 +14,7 @@ import {
createResultCompletedEvent,
createSessionWaitingEvent,
createStepStartedEvent,
+ createSubagentCalledEvent,
createTurnCancelledEvent,
encodeMessageStreamEvent,
stampMessageStreamEvent,
@@ -55,6 +56,32 @@ describe("message stream protocol", () => {
});
});
+ it("authors local and remote child stream paths", () => {
+ const input = {
+ callId: "call/1",
+ childSessionId: "child/1",
+ name: "research",
+ sequence: 1,
+ sessionId: "parent/1",
+ toolName: "research",
+ turnId: "turn_1",
+ workflowId: "workflow_1",
+ };
+
+ expect(createSubagentCalledEvent(input).data.childStreamPath).toBe(
+ "/eve/v1/session/child%2F1/stream",
+ );
+ expect(
+ createSubagentCalledEvent({
+ ...input,
+ remote: { resolverId: "remote/research", url: "https://remote.example" },
+ }).data,
+ ).toMatchObject({
+ childStreamPath: "/eve/v1/session/parent%2F1/subagents/call%2F1/child%2F1/stream",
+ remote: { resolverId: "remote/research", url: "https://remote.example" },
+ });
+ });
+
it("publishes the channel-local continuation token on session.waiting", () => {
expect(createSessionWaitingEvent("slack:C1:T1")).toEqual({
data: {
diff --git a/packages/eve/src/protocol/message.ts b/packages/eve/src/protocol/message.ts
index 0b038198e..6557e1387 100644
--- a/packages/eve/src/protocol/message.ts
+++ b/packages/eve/src/protocol/message.ts
@@ -7,6 +7,10 @@ import {
} from "#internal/attachments/url-refs.js";
import { decodeSandboxRef, isSandboxRefUrl } from "#internal/attachments/sandbox-refs.js";
import { createEventId } from "#protocol/event-id.js";
+import {
+ createEveSessionStreamRoutePath,
+ createEveSubagentStreamRoutePath,
+} from "#protocol/routes.js";
import type { ConnectionAuthorizationChallenge } from "#public/connections/errors.js";
import type {
RuntimeActionRequest,
@@ -308,10 +312,22 @@ export interface SubagentCalledStreamEvent {
data: {
callId: string;
childSessionId: string;
+ childStreamPath: string;
sessionId: string;
sequence: number;
name: string;
remote?: {
+ /**
+ * Key to the authored credential functions (`auth`/`headers`) for this
+ * remote child, resolved at stream-proxy time by
+ * `resolveRemoteAgentStreamHeaders`. Static subagent → the node id in
+ * `subagentRegistry.subagentsByNodeId`; dynamic subagent → its
+ * `credentialsStepId` in the step registry. The event stores this key —
+ * never resolved header values — because tokens expire and this event
+ * is persisted and streamed to clients. Absent when the remote child
+ * has no authored credentials.
+ */
+ resolverId?: string;
url: string;
};
toolName: string;
@@ -351,6 +367,15 @@ export interface SubagentChildEventStreamEvent {
*/
export interface SubagentCompletedStreamEvent {
data: {
+ /**
+ * Present when the originating call completed with a background-task
+ * receipt while the child itself kept running. Consumers must not treat
+ * this as the child's terminal boundary; the child stream owns that.
+ */
+ backgroundTask?: {
+ taskId: string;
+ status: "working";
+ };
callId: string;
output: string;
subagentName: string;
@@ -571,6 +596,8 @@ export interface CompactionCompletedStreamEvent {
*/
export interface AuthorizationRequiredStreamEvent {
data: {
+ /** Stable identity of this exact authorization attempt. */
+ attemptId?: string;
authorization?: ConnectionAuthorizationChallenge;
candidateId?: string;
description: string;
@@ -604,6 +631,8 @@ export type ConnectionAuthorizationOutcome = AuthorizationOutcome;
*/
export interface AuthorizationCompletedStreamEvent {
data: {
+ /** Stable identity shared with the matching required event. */
+ attemptId?: string;
candidateId?: string;
/**
* The challenge from the matching `authorization.required` event,
@@ -1035,6 +1064,7 @@ export function createActionsRequestedEvent(input: {
* for `getToken`-only authorization sources that authorize out of band.
*/
export function createAuthorizationRequiredEvent(input: {
+ readonly attemptId?: string;
readonly authorization?: ConnectionAuthorizationChallenge;
readonly candidateId?: string;
readonly description: string;
@@ -1051,6 +1081,9 @@ export function createAuthorizationRequiredEvent(input: {
stepIndex: input.stepIndex,
turnId: input.turnId,
};
+ if (input.attemptId !== undefined) {
+ data.attemptId = input.attemptId;
+ }
if (input.authorization !== undefined) {
data.authorization = input.authorization;
}
@@ -1072,6 +1105,7 @@ export function createAuthorizationRequiredEvent(input: {
* authorization deadline has expired.
*/
export function createAuthorizationCompletedEvent(input: {
+ readonly attemptId?: string;
readonly authorization?: ConnectionAuthorizationChallenge;
readonly candidateId?: string;
readonly name: string;
@@ -1088,6 +1122,9 @@ export function createAuthorizationCompletedEvent(input: {
stepIndex: input.stepIndex,
turnId: input.turnId,
};
+ if (input.attemptId !== undefined) {
+ data.attemptId = input.attemptId;
+ }
if (input.authorization !== undefined) {
data.authorization = input.authorization;
}
@@ -1197,6 +1234,7 @@ export function createSubagentCalledEvent(input: {
readonly sequence: number;
readonly name: string;
readonly remote?: {
+ readonly resolverId?: string;
readonly url: string;
};
readonly toolName: string;
@@ -1207,6 +1245,14 @@ export function createSubagentCalledEvent(input: {
data: {
callId: input.callId,
childSessionId: input.childSessionId,
+ childStreamPath:
+ input.remote === undefined
+ ? createEveSessionStreamRoutePath(input.childSessionId)
+ : createEveSubagentStreamRoutePath({
+ callId: input.callId,
+ childSessionId: input.childSessionId,
+ parentSessionId: input.sessionId,
+ }),
sessionId: input.sessionId,
sequence: input.sequence,
name: input.name,
diff --git a/packages/eve/src/public/channels/eve-subagent-stream.test.ts b/packages/eve/src/public/channels/eve-subagent-stream.test.ts
new file mode 100644
index 000000000..5d93a2a91
--- /dev/null
+++ b/packages/eve/src/public/channels/eve-subagent-stream.test.ts
@@ -0,0 +1,279 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import type { RouteHandlerArgs } from "#channel/routes.js";
+import type { Session } from "#channel/session.js";
+import {
+ attachRemoteAgentStreamHeadersResolver,
+ type RemoteAgentStreamHeadersResolver,
+} from "#internal/nitro/routes/channel-route-context.js";
+import { mockChannelContext } from "#internal/testing/mocks/mock-channel-operations.js";
+import { stampTestEvent } from "#internal/testing/events.js";
+import { createSubagentCalledEvent, type MessageStreamEvent } from "#protocol/message.js";
+import { EVE_SUBAGENT_STREAM_ROUTE_PATTERN } from "#protocol/routes.js";
+import { none, type AuthFn } from "#public/channels/auth.js";
+import { eveChannel } from "#public/channels/eve.js";
+
+const coordinates = {
+ callId: "call-1",
+ childSessionId: "child-1",
+ parentSessionId: "parent-1",
+};
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe("eveChannel remote subagent stream", () => {
+ it("authenticates before reading the parent or fetching upstream", async () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal("fetch", fetchMock);
+ const harness = createHarness({ auth: () => null, events: [remoteCalledEvent()] });
+
+ const response = await harness.fetch(proxyRequest());
+
+ expect(response.status).toBe(401);
+ expect(harness.getSession).not.toHaveBeenCalled();
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it("rejects a forged tuple and a local child without fetching upstream", async () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal("fetch", fetchMock);
+ const forged = createHarness({
+ events: [remoteCalledEvent({ callId: "different-call" })],
+ });
+ const local = createHarness({ events: [localCalledEvent()] });
+
+ expect((await forged.fetch(proxyRequest())).status).toBe(404);
+ expect((await local.fetch(proxyRequest())).status).toBe(404);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it("returns 404 without fetching when the authored remote resolver no longer matches", async () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal("fetch", fetchMock);
+ const harness = createHarness({
+ events: [remoteCalledEvent()],
+ resolveHeaders: vi.fn().mockRejectedValue(new Error("remote URL mismatch")),
+ });
+
+ const response = await harness.fetch(proxyRequest());
+
+ expect(response.status).toBe(404);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it("proxies an exact remote binding incrementally with authored credentials and cursors", async () => {
+ let upstreamController!: ReadableStreamDefaultController<Uint8Array>;
+ const upstreamBody = new ReadableStream<Uint8Array>({
+ start(controller) {
+ upstreamController = controller;
+ },
+ });
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(upstreamBody, {
+ headers: {
+ "content-type": "application/x-ndjson; charset=utf-8",
+ "x-eve-stream-format": "ndjson",
+ "x-eve-stream-tail-index": "8",
+ "x-eve-stream-version": "21",
+ },
+ status: 206,
+ statusText: "Partial Content",
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const resolveHeaders = vi.fn<RemoteAgentStreamHeadersResolver>().mockResolvedValue({
+ authorization: "Bearer authored",
+ "x-authored": "yes",
+ });
+ const bindingCancelled = vi.fn();
+ const harness = createHarness({
+ bindingCancelled,
+ events: [remoteCalledEvent()],
+ resolveHeaders,
+ });
+ const abort = new AbortController();
+
+ const response = await harness.fetch(
+ proxyRequest({
+ headers: { authorization: "Bearer inbound", cookie: "parent=session" },
+ search: "?startIndex=-3&includeTailIndex=true",
+ signal: abort.signal,
+ }),
+ );
+
+ expect(bindingCancelled).toHaveBeenCalledOnce();
+ expect(resolveHeaders).toHaveBeenCalledWith({
+ name: "research",
+ resolverId: "subagents/research",
+ url: "https://remote.example/base",
+ });
+ expect(fetchMock).toHaveBeenCalledOnce();
+ const [url, init] = fetchMock.mock.calls[0] as [URL, RequestInit];
+ expect(url.toString()).toBe(
+ "https://remote.example/base/eve/v1/session/child-1/stream?startIndex=-3&includeTailIndex=1",
+ );
+ expect(init.headers).toEqual({
+ authorization: "Bearer authored",
+ "x-authored": "yes",
+ });
+ expect(init.cache).toBe("no-store");
+ expect(init.redirect).toBe("manual");
+ expect((init.signal as AbortSignal).aborted).toBe(false);
+ expect(response.status).toBe(206);
+ expect(response.statusText).toBe("Partial Content");
+ expect(response.headers.get("x-eve-stream-format")).toBe("ndjson");
+ expect(response.headers.get("x-eve-stream-tail-index")).toBe("8");
+
+ const reader = response.body!.getReader();
+ upstreamController.enqueue(new TextEncoder().encode('{"first":true}\n'));
+ await expect(reader.read()).resolves.toMatchObject({ done: false });
+ upstreamController.enqueue(new TextEncoder().encode('{"second":true}\n'));
+ upstreamController.close();
+ const second = await reader.read();
+ expect(new TextDecoder().decode(second.value)).toBe('{"second":true}\n');
+
+ abort.abort();
+ expect((init.signal as AbortSignal).aborted).toBe(true);
+ });
+
+ it("passes through upstream HTTP error status, headers, and body", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue(
+ new Response("remote denied", {
+ headers: { "x-eve-stream-version": "21" },
+ status: 403,
+ }),
+ ),
+ );
+ const harness = createHarness({ events: [remoteCalledEvent()] });
+
+ const response = await harness.fetch(proxyRequest());
+
+ expect(response.status).toBe(403);
+ expect(response.headers.get("x-eve-stream-version")).toBe("21");
+ await expect(response.text()).resolves.toBe("remote denied");
+ });
+});
+
+function remoteCalledEvent(overrides: Partial<typeof coordinates> = {}): MessageStreamEvent {
+ const values = { ...coordinates, ...overrides };
+ return stampTestEvent(
+ createSubagentCalledEvent({
+ callId: values.callId,
+ childSessionId: values.childSessionId,
+ name: "research",
+ remote: {
+ resolverId: "subagents/research",
+ url: "https://remote.example/base",
+ },
+ sequence: 1,
+ sessionId: values.parentSessionId,
+ toolName: "research",
+ turnId: "turn-1",
+ workflowId: "workflow-1",
+ }),
+ 0,
+ );
+}
+
+function localCalledEvent(): MessageStreamEvent {
+ return stampTestEvent(
+ createSubagentCalledEvent({
+ callId: coordinates.callId,
+ childSessionId: coordinates.childSessionId,
+ name: "research",
+ sequence: 1,
+ sessionId: coordinates.parentSessionId,
+ toolName: "research",
+ turnId: "turn-1",
+ workflowId: "workflow-1",
+ }),
+ 0,
+ );
+}
+
+function createHarness(input: {
+ readonly auth?: AuthFn<Request>;
+ readonly bindingCancelled?: () => void;
+ readonly events: readonly MessageStreamEvent[];
+ readonly resolveHeaders?: RemoteAgentStreamHeadersResolver;
+}) {
+ const channel = eveChannel({ auth: input.auth ?? none() });
+ const route = channel.routes.find(
+ (candidate) =>
+ candidate.method === "GET" && candidate.path === EVE_SUBAGENT_STREAM_ROUTE_PATTERN,
+ );
+ if (route === undefined) throw new Error("No remote subagent stream route found.");
+
+ const session: Session = {
+ id: coordinates.parentSessionId,
+ send: vi.fn(),
+ respond: vi.fn(),
+ async cancel() {
+ return { status: "no_active_turn" };
+ },
+ async compact() {
+ return { sessionId: coordinates.parentSessionId, status: "accepted" };
+ },
+ async clear() {
+ return { sessionId: coordinates.parentSessionId, status: "accepted" };
+ },
+ async reset() {
+ return { previousSessionId: coordinates.parentSessionId, status: "reset" };
+ },
+ async getEventStream() {
+ return new ReadableStream<MessageStreamEvent>({
+ start(controller) {
+ for (const event of input.events) controller.enqueue(event);
+ },
+ cancel() {
+ input.bindingCancelled?.();
+ },
+ });
+ },
+ async getStreamTailIndex() {
+ return input.events.length - 1;
+ },
+ };
+ const getSession = vi.fn().mockReturnValue(session);
+
+ return {
+ getSession,
+ async fetch(request: Request) {
+ const args = attachRemoteAgentStreamHeadersResolver(
+ createRouteArgs(getSession),
+ input.resolveHeaders ?? (async () => ({})),
+ );
+ return await (
+ route as { handler: (req: Request, args: RouteHandlerArgs) => Promise<Response> }
+ ).handler(request, args);
+ },
+ };
+}
+
+function createRouteArgs(attachSession: RouteHandlerArgs["attachSession"]): RouteHandlerArgs {
+ return {
+ ...mockChannelContext(vi.fn()),
+ attachSession,
+ to: vi.fn() as never,
+ params: coordinates,
+ waitUntil: () => undefined,
+ requestIp: "127.0.0.1",
+ };
+}
+
+function proxyRequest(
+ input: {
+ readonly headers?: Readonly<Record<string, string>>;
+ readonly search?: string;
+ readonly signal?: AbortSignal;
+ } = {},
+): Request {
+ return new Request(
+ `https://parent.example/eve/v1/session/parent-1/subagents/call-1/child-1/stream${input.search ?? ""}`,
+ { headers: input.headers, signal: input.signal },
+ );
+}
diff --git a/packages/eve/src/public/channels/eve.test.ts b/packages/eve/src/public/channels/eve.test.ts
index 287c6286e..ee8d35257 100644
--- a/packages/eve/src/public/channels/eve.test.ts
+++ b/packages/eve/src/public/channels/eve.test.ts
@@ -750,6 +750,7 @@ describe("eveChannel — onMessage", () => {
callback: {
callId: "call-2",
subagentName: "research",
+ taskId: "task-2",
token: "tok123",
url: "https://caller.example.com/eve/v1/callback/tok123",
},
@@ -764,6 +765,7 @@ describe("eveChannel — onMessage", () => {
callback: {
callId: "call-2",
subagentName: "research",
+ taskId: "task-2",
token: "tok123",
url: "https://caller.example.com/eve/v1/callback/tok123",
},
diff --git a/packages/eve/src/public/channels/eve.ts b/packages/eve/src/public/channels/eve.ts
index cb03d9c27..4b20e85e4 100644
--- a/packages/eve/src/public/channels/eve.ts
+++ b/packages/eve/src/public/channels/eve.ts
@@ -18,6 +18,7 @@ import { hasInternalRefScheme } from "#internal/attachments/url-refs.js";
import { createLogger, logError } from "#internal/logging.js";
import {
readAgentInfoRouteResponse,
+ readRemoteAgentStreamHeadersResolver,
readRouteSessionCreator,
} from "#internal/nitro/routes/channel-route-context.js";
import {
@@ -28,6 +29,8 @@ import {
EVE_STREAM_FORMAT_HEADER,
EVE_STREAM_TAIL_INDEX_HEADER,
EVE_STREAM_VERSION_HEADER,
+ type MessageStreamEvent,
+ type SubagentCalledStreamEvent,
} from "#protocol/message.js";
import { parseTraceparent } from "#protocol/traceparent.js";
import {
@@ -39,6 +42,9 @@ import {
EVE_SESSION_ROUTE_PATTERN,
EVE_SESSION_RESET_ROUTE_PATTERN,
EVE_SESSION_STREAM_ROUTE_PATTERN,
+ EVE_SUBAGENT_STREAM_ROUTE_PATTERN,
+ createEveSessionStreamRoutePath,
+ createEveSubagentStreamRoutePath,
} from "#protocol/routes.js";
import { type InputResponse, isInputResponse } from "#runtime/input/types.js";
import { type AuthFn, routeAuth } from "#public/channels/auth.js";
@@ -430,7 +436,10 @@ export function eveChannel(input: EveChannelInput): EveChannel {
if (body instanceof Response) return body;
let result: Awaited<ReturnType<Session["cancel"]>>;
try {
- result = await attachSession(sessionId).cancel({ turnId: body.turnId });
+ result = await attachSession(sessionId).cancel({
+ taskId: body.taskId,
+ turnId: body.turnId,
+ });
} catch (error) {
const errorId = logError(log, "cancel-turn request failed", error, { sessionId });
return Response.json(
@@ -553,11 +562,149 @@ export function eveChannel(input: EveChannelInput): EveChannel {
if (sessionId instanceof Response) return sessionId;
return await createSessionStreamResponse(req, attachSession(sessionId));
}),
+
+ GET(EVE_SUBAGENT_STREAM_ROUTE_PATTERN, async (req, args) => {
+ const authResult = await routeAuth(req, input.auth);
+ if (authResult instanceof Response) return authResult;
+
+ const parentSessionId = args.params.parentSessionId;
+ const callId = args.params.callId;
+ const childSessionId = args.params.childSessionId;
+ if (!parentSessionId || !callId || !childSessionId) {
+ return Response.json(
+ { error: "Missing subagent stream coordinates.", ok: false },
+ { status: 400 },
+ );
+ }
+
+ const startIndex = parseStartIndex(req);
+ if (startIndex instanceof Response) return startIndex;
+ const includeTailIndex = parseIncludeTailIndex(req);
+
+ const childStreamPath = createEveSubagentStreamRoutePath({
+ callId,
+ childSessionId,
+ parentSessionId,
+ });
+ let binding: SubagentCalledStreamEvent;
+ try {
+ const parent = args.attachSession(parentSessionId);
+ const found = await findRemoteSubagentBinding({
+ callId,
+ childSessionId,
+ childStreamPath,
+ parentSessionId,
+ parent,
+ });
+ if (found === undefined) {
+ throw new Error("Remote subagent binding not found.");
+ }
+ binding = found;
+ } catch {
+ return Response.json({ error: "Subagent stream not found.", ok: false }, { status: 404 });
+ }
+
+ const resolveHeaders = readRemoteAgentStreamHeadersResolver(args);
+ if (resolveHeaders === undefined) {
+ return Response.json(
+ {
+ error: "Subagent stream proxy requires internal channel dispatch context.",
+ ok: false,
+ },
+ { status: 500 },
+ );
+ }
+
+ let headers: Record<string, string>;
+ try {
+ headers = await resolveHeaders({
+ name: binding.data.toolName,
+ resolverId: binding.data.remote!.resolverId,
+ url: binding.data.remote!.url,
+ });
+ } catch {
+ return Response.json({ error: "Subagent stream not found.", ok: false }, { status: 404 });
+ }
+
+ const upstreamUrl = new URL(
+ createEveSessionStreamRoutePath(childSessionId).replace(/^\/+/, ""),
+ `${binding.data.remote!.url.replace(/\/+$/, "")}/`,
+ );
+ if (startIndex !== undefined) {
+ upstreamUrl.searchParams.set("startIndex", String(startIndex));
+ }
+ if (includeTailIndex) {
+ upstreamUrl.searchParams.set("includeTailIndex", "1");
+ }
+
+ const upstream = await fetch(upstreamUrl, {
+ cache: "no-store",
+ headers,
+ redirect: "manual",
+ signal: req.signal,
+ });
+ const responseHeaders = new Headers();
+ for (const name of [
+ "cache-control",
+ "content-type",
+ "x-accel-buffering",
+ EVE_SESSION_ID_HEADER,
+ EVE_STREAM_FORMAT_HEADER,
+ EVE_STREAM_TAIL_INDEX_HEADER,
+ EVE_STREAM_VERSION_HEADER,
+ ]) {
+ const value = upstream.headers.get(name);
+ if (value !== null) responseHeaders.set(name, value);
+ }
+ return new Response(upstream.body, {
+ headers: responseHeaders,
+ status: upstream.status,
+ statusText: upstream.statusText,
+ });
+ }),
],
events: input.events,
});
}
+async function findRemoteSubagentBinding(input: {
+ readonly callId: string;
+ readonly childSessionId: string;
+ readonly childStreamPath: string;
+ readonly parentSessionId: string;
+ readonly parent: {
+ getEventStream(options?: { startIndex?: number }): Promise<ReadableStream<MessageStreamEvent>>;
+ getStreamTailIndex(): Promise<number>;
+ };
+}): Promise<SubagentCalledStreamEvent | undefined> {
+ const tailIndex = await input.parent.getStreamTailIndex();
+ if (tailIndex < 0) return undefined;
+
+ const events = await input.parent.getEventStream({ startIndex: 0 });
+ const reader = events.getReader();
+ let binding: SubagentCalledStreamEvent | undefined;
+ try {
+ for (let index = 0; index <= tailIndex; index += 1) {
+ const next = await reader.read();
+ if (next.done) break;
+ const event = next.value;
+ if (
+ event.type === "subagent.called" &&
+ event.data.sessionId === input.parentSessionId &&
+ event.data.callId === input.callId &&
+ event.data.childSessionId === input.childSessionId &&
+ event.data.childStreamPath === input.childStreamPath &&
+ event.data.remote !== undefined
+ ) {
+ binding = event;
+ }
+ }
+ } finally {
+ await reader.cancel().catch(() => {});
+ }
+ return binding;
+}
+
function normalizeEveCors(cors: EveChannelCors | undefined): ChannelCors {
if (cors === undefined || cors === false) {
return false;
@@ -797,6 +944,7 @@ function parseSessionMessageBody(
}
interface ParsedCancelTurnBody {
+ taskId?: string;
turnId?: string;
}
@@ -807,16 +955,23 @@ async function parseCancelTurnBody(req: Request): Promise<ParsedCancelTurnBody |
if (tokenRejection !== null) return tokenRejection;
const turnId = payload.turnId;
- if (turnId === undefined) {
- return {};
- }
- if (typeof turnId !== "string" || turnId.length === 0) {
+ const taskId = payload.taskId;
+ if (turnId !== undefined && (typeof turnId !== "string" || turnId.length === 0)) {
return Response.json(
{ error: "Expected 'turnId' to be a non-empty string.", ok: false },
{ status: 400 },
);
}
- return { turnId };
+ if (taskId !== undefined && (typeof taskId !== "string" || taskId.length === 0)) {
+ return Response.json(
+ { error: "Expected 'taskId' to be a non-empty string.", ok: false },
+ { status: 400 },
+ );
+ }
+ const result: ParsedCancelTurnBody = {};
+ if (typeof taskId === "string") result.taskId = taskId;
+ if (typeof turnId === "string") result.turnId = turnId;
+ return result;
}
async function parseJsonRequest(req: Request): Promise<Record<string, unknown> | Response> {
diff --git a/packages/eve/src/runtime/actions/types.ts b/packages/eve/src/runtime/actions/types.ts
index aea8964e3..716c891e7 100644
--- a/packages/eve/src/runtime/actions/types.ts
+++ b/packages/eve/src/runtime/actions/types.ts
@@ -146,6 +146,11 @@ const runtimeToolResultActionResultSchema = z
* so the parent never infers lifecycle from an absent field. `usage`
* carries the turn's token spend so the caller can attribute the
* subagent's tokens.
+ *
+ * `backgroundTask` marks the one parent-produced exception: delegated
+ * dispatch resolves the model's tool call with a parked task receipt before
+ * the child settles. Stream consumers use the marker to keep child lifecycle
+ * open while still recording the receipt as the tool result.
*/
export type RuntimeSubagentChildResult = z.infer<typeof runtimeSubagentChildResultSchema>;
@@ -154,6 +159,12 @@ export type RuntimeSubagentChildResult = z.infer<typeof runtimeSubagentChildResu
*/
const runtimeSubagentChildResultSchema = z
.object({
+ backgroundTask: z
+ .strictObject({
+ status: z.literal("working"),
+ taskId: z.string(),
+ })
+ .optional(),
callId: z.string(),
isError: z.boolean().optional(),
kind: z.literal("subagent-result"),
diff --git a/packages/eve/src/runtime/agent/bootstrap.test.ts b/packages/eve/src/runtime/agent/bootstrap.test.ts
index 41b091fca..3c8feecdd 100644
--- a/packages/eve/src/runtime/agent/bootstrap.test.ts
+++ b/packages/eve/src/runtime/agent/bootstrap.test.ts
@@ -84,6 +84,22 @@ describe("createResolvedRuntimeTurnAgent agent-messaging gating", () => {
expect(turnAgent.instructions).not.toContainEqual(expect.stringContaining("Pass `agentId`"));
});
+ it("explains task-derived busy agents when tasks imply persistent sessions", () => {
+ const turnAgent = createResolvedRuntimeTurnAgent({
+ agent: createResolvedAgentForTest({
+ config: {
+ experimental: { tasks: true },
+ name: "test-agent",
+ } as ResolvedAgent["config"],
+ }),
+ nodeId: ROOT_RUNTIME_AGENT_NODE_ID,
+ tools: [],
+ });
+
+ expect(turnAgent.instructions).toContainEqual(expect.stringContaining("availability=busy"));
+ expect(turnAgent.instructions).toContainEqual(expect.stringContaining("taskId"));
+ });
+
it("omits the messaging instruction when an authored tool named agent shadows the framework tool", () => {
const turnAgent = createResolvedRuntimeTurnAgent({
agent: createResolvedAgentForTest({
diff --git a/packages/eve/src/runtime/agent/bootstrap.ts b/packages/eve/src/runtime/agent/bootstrap.ts
index eacd51f9a..de456584a 100644
--- a/packages/eve/src/runtime/agent/bootstrap.ts
+++ b/packages/eve/src/runtime/agent/bootstrap.ts
@@ -116,8 +116,11 @@ export function createResolvedRuntimeTurnAgent(input: {
instructions: composeRuntimeBasePrompt({
connections: agent.connections,
instructions: agent.instructions,
- persistentSubagentSessions: config?.experimental?.subagentPersistentSessions === true,
+ persistentSubagentSessions:
+ config?.experimental?.tasks === true ||
+ config?.experimental?.subagentPersistentSessions === true,
subagentsAvailable: subagentDeclaredTool || subagentImplicitRootTool,
+ tasksEnabled: config?.experimental?.tasks === true,
toolsAvailable: input.tools.length > 0 || subagentImplicitRootTool,
workspaceSpec: agent.workspaceSpec,
}),
diff --git a/packages/eve/src/runtime/framework-channels/index.ts b/packages/eve/src/runtime/framework-channels/index.ts
index f22c21f31..0b9e9ab3a 100644
--- a/packages/eve/src/runtime/framework-channels/index.ts
+++ b/packages/eve/src/runtime/framework-channels/index.ts
@@ -11,6 +11,10 @@ import {
getSessionCallbackChannelNames,
} from "#runtime/session-callback-route.js";
import type { ResolvedChannelDefinition } from "#runtime/types.js";
+import {
+ getTaskInputResponseChannelDefinitions,
+ getTaskInputResponseChannelNames,
+} from "#runtime/task-input-response-route.js";
const EVE_CHANNEL_NAME = "eve";
@@ -46,6 +50,7 @@ export function getFrameworkChannelDefinitions(): readonly ResolvedChannelDefini
result.push(
...getConnectionCallbackChannelDefinitions(),
...getSessionCallbackChannelDefinitions(),
+ ...getTaskInputResponseChannelDefinitions(),
);
return result;
@@ -56,5 +61,6 @@ export function getAllFrameworkChannelNames(): ReadonlySet<string> {
EVE_CHANNEL_NAME,
...getConnectionCallbackChannelNames(),
...getSessionCallbackChannelNames(),
+ ...getTaskInputResponseChannelNames(),
]);
}
diff --git a/packages/eve/src/runtime/framework-tools/index.ts b/packages/eve/src/runtime/framework-tools/index.ts
index 8495b018a..36c61b533 100644
--- a/packages/eve/src/runtime/framework-tools/index.ts
+++ b/packages/eve/src/runtime/framework-tools/index.ts
@@ -8,6 +8,7 @@ import {
createSkillToolDefinition,
SKILL_TOOL_DEFINITION,
} from "#runtime/framework-tools/skill.js";
+import { TASK_TOOL_DEFINITIONS } from "#runtime/framework-tools/tasks.js";
import { TODO_TOOL_DEFINITION } from "#runtime/framework-tools/todo.js";
import { WEB_FETCH_TOOL_DEFINITION } from "#runtime/framework-tools/web-fetch.js";
import { WEB_SEARCH_TOOL_DEFINITION } from "#runtime/framework-tools/web-search.js";
@@ -60,6 +61,7 @@ const REGISTERED_FRAMEWORK_TOOLS: readonly ResolvedToolDefinition[] = [
const ALL_FRAMEWORK_TOOLS: readonly ResolvedToolDefinition[] = [
...REGISTERED_FRAMEWORK_TOOLS,
AGENT_TOOL_DEFINITION,
+ ...TASK_TOOL_DEFINITIONS,
];
/**
diff --git a/packages/eve/src/runtime/framework-tools/tasks.test.ts b/packages/eve/src/runtime/framework-tools/tasks.test.ts
new file mode 100644
index 000000000..ba9b18cab
--- /dev/null
+++ b/packages/eve/src/runtime/framework-tools/tasks.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from "vitest";
+
+import { TASK_SEND_INPUT_SCHEMA } from "#runtime/framework-tools/tasks.js";
+
+describe("task_send input", () => {
+ it("accepts only terminal-task message follow-ups", () => {
+ expect(
+ TASK_SEND_INPUT_SCHEMA.safeParse({ message: "continue", taskId: "task_1" }).success,
+ ).toBe(true);
+ expect(
+ TASK_SEND_INPUT_SCHEMA.safeParse({
+ inputResponses: [{ optionId: "approve", requestId: "request_1" }],
+ taskId: "task_1",
+ }).success,
+ ).toBe(false);
+ });
+});
diff --git a/packages/eve/src/runtime/framework-tools/tasks.ts b/packages/eve/src/runtime/framework-tools/tasks.ts
new file mode 100644
index 000000000..c19547675
--- /dev/null
+++ b/packages/eve/src/runtime/framework-tools/tasks.ts
@@ -0,0 +1,193 @@
+import { z } from "#compiled/zod/index.js";
+
+import { requestTurnSleep } from "#harness/turn-sleep.js";
+import type { HarnessToolDefinition } from "#harness/execute-tool.js";
+import type { ResolvedToolDefinition } from "#runtime/types.js";
+
+/**
+ * Framework task tools for `experimental.tasks`.
+ *
+ * With the flag on, subagent calls return a task receipt instead of
+ * blocking the parent turn; these tools are the model's controls over
+ * that delegated work. `task_peek` and `task_cancel` are
+ * execute-less runtime actions — they need durable session state and
+ * world access, so the runtime-action dispatch step executes them.
+ * `task_sleep` only records a durable pause and executes in-loop.
+ */
+
+export const TASK_PEEK_TOOL_NAME = "task_peek";
+export const TASK_CANCEL_TOOL_NAME = "task_cancel";
+export const TASK_SEND_TOOL_NAME = "task_send";
+export const TASK_SLEEP_TOOL_NAME = "task_sleep";
+
+/** Every model-visible task tool name, for gating and dispatch matching. */
+export const TASK_TOOL_NAMES: ReadonlySet<string> = new Set([
+ TASK_PEEK_TOOL_NAME,
+ TASK_CANCEL_TOOL_NAME,
+ TASK_SEND_TOOL_NAME,
+ TASK_SLEEP_TOOL_NAME,
+]);
+
+/** Task-control tools executed by the runtime-action dispatch step. */
+export const TASK_CONTROL_TOOL_NAMES: ReadonlySet<string> = new Set([
+ TASK_PEEK_TOOL_NAME,
+ TASK_CANCEL_TOOL_NAME,
+ TASK_SEND_TOOL_NAME,
+]);
+
+const TASK_IDS_SCHEMA = z
+ .array(z.string().min(1))
+ .min(1)
+ .describe("Task ids from earlier subagent task receipts.");
+
+export const TASK_PEEK_INPUT_SCHEMA = z.strictObject({ taskIds: TASK_IDS_SCHEMA });
+export const TASK_CANCEL_INPUT_SCHEMA = z.strictObject({ taskIds: TASK_IDS_SCHEMA });
+
+export const TASK_SEND_INPUT_SCHEMA = z.strictObject({
+ message: z
+ .string()
+ .describe(
+ "Follow-up message for a finished task's agent; starts a new task in the same conversation.",
+ ),
+ taskId: z.string().min(1).describe("Task id from an earlier task receipt."),
+});
+
+const MAX_SLEEP_SECONDS = Math.floor(Number.MAX_SAFE_INTEGER / 1_000);
+
+export const TASK_SLEEP_INPUT_SCHEMA = z.strictObject({
+ seconds: z.number().positive().max(MAX_SLEEP_SECONDS).describe("How long to wait, in seconds."),
+});
+
+const TASK_VIEW_SCHEMA = z.object({
+ inputRequests: z.array(z.unknown()).optional(),
+ lastOutput: z
+ .object({
+ data: z.unknown(),
+ type: z.enum(["result", "error"]),
+ })
+ .optional(),
+ metadata: z.object({
+ agentId: z.string(),
+ kind: z.literal("subagent"),
+ mode: z.enum(["local", "remote"]),
+ name: z.string(),
+ }),
+ status: z.enum(["working", "input_required", "completed", "failed", "cancelled"]),
+ taskId: z.string(),
+});
+
+export const TASK_VIEWS_OUTPUT_SCHEMA = z.object({
+ tasks: z.array(TASK_VIEW_SCHEMA),
+});
+
+export const TASK_SLEEP_OUTPUT_SCHEMA = z.strictObject({
+ waitedSeconds: z.number().positive(),
+});
+
+const TASK_PEEK_DESCRIPTION =
+ "Read the current state of one or more background tasks without waiting. " +
+ "Returns each task's status and, for finished tasks, its output. Does not wake or change the task.";
+
+const TASK_CANCEL_DESCRIPTION =
+ "Request cooperative cancellation of one or more background tasks. " +
+ "Cancellation is final: a task that finishes after you cancel it stays cancelled. Cancelling an already-finished task changes nothing.";
+
+const TASK_SEND_DESCRIPTION =
+ "Send a follow-up message to a finished background task's agent. " +
+ "This starts a new task in the same conversation and returns its receipt. " +
+ "Human input for an input_required task is routed directly through the parent channel. " +
+ "A task that is still working cannot receive sends.";
+
+const TASK_SLEEP_DESCRIPTION =
+ "Pause durably before continuing, for paced background-task checks. " +
+ "Does not read or change any task; follow it with task_peek.";
+
+/**
+ * Builds the harness definitions injected when the root agent enables
+ * `experimental.tasks`. Follows the implicit `agent` tool pattern:
+ * inline definitions, no registry entry, session-shape hiding in
+ * advertised-tools, and re-validation at dispatch.
+ */
+export function createTaskToolHarnessDefinitions(): readonly HarnessToolDefinition[] {
+ return [
+ {
+ description: TASK_PEEK_DESCRIPTION,
+ inputSchema: TASK_PEEK_INPUT_SCHEMA,
+ name: TASK_PEEK_TOOL_NAME,
+ outputSchema: TASK_VIEWS_OUTPUT_SCHEMA,
+ runtimeAction: { kind: "task-control" },
+ },
+ {
+ description: TASK_CANCEL_DESCRIPTION,
+ inputSchema: TASK_CANCEL_INPUT_SCHEMA,
+ name: TASK_CANCEL_TOOL_NAME,
+ outputSchema: TASK_VIEWS_OUTPUT_SCHEMA,
+ runtimeAction: { kind: "task-control" },
+ },
+ {
+ description: TASK_SEND_DESCRIPTION,
+ inputSchema: TASK_SEND_INPUT_SCHEMA,
+ name: TASK_SEND_TOOL_NAME,
+ runtimeAction: { kind: "task-control" },
+ },
+ {
+ description: TASK_SLEEP_DESCRIPTION,
+ execute: async (input: { readonly seconds: number }) => {
+ requestTurnSleep(Math.ceil(input.seconds * 1_000));
+ return { waitedSeconds: input.seconds };
+ },
+ inputSchema: TASK_SLEEP_INPUT_SCHEMA,
+ name: TASK_SLEEP_TOOL_NAME,
+ outputSchema: TASK_SLEEP_OUTPUT_SCHEMA,
+ },
+ ];
+}
+
+/**
+ * Whether one node's sessions receive the task tools.
+ *
+ * Mirrors `isImplicitAgentToolAvailable`: the compile step already
+ * rejects `experimental.tasks` on subagents, authored tools with the
+ * same name shadow the framework tool, and `disableTool(name)` removes
+ * individual tools. Root-node self-delegated children share this node's
+ * config, so advertised-tools additionally hides the tools from any
+ * child-shaped session.
+ */
+export function isTaskToolAvailable(input: {
+ readonly disabledFrameworkTools: readonly string[];
+ readonly hasAuthoredTool: boolean;
+ readonly tasksEnabled: boolean;
+ readonly toolName: string;
+}): boolean {
+ return (
+ input.tasksEnabled &&
+ !input.disabledFrameworkTools.includes(input.toolName) &&
+ !input.hasAuthoredTool
+ );
+}
+
+function createResolvedTaskToolStub(input: {
+ readonly description: string;
+ readonly name: string;
+}): ResolvedToolDefinition {
+ return {
+ description: input.description,
+ inputSchema: null,
+ logicalPath: `eve:framework/${input.name}`,
+ name: input.name,
+ sourceId: `eve:${input.name}-tool`,
+ sourceKind: "module",
+ };
+}
+
+/**
+ * Registry-shaped metadata for the task tools. Not registered in the
+ * tool registry (the harness injects the real definitions per node);
+ * these entries exist so `disableTool(name)` validates the names.
+ */
+export const TASK_TOOL_DEFINITIONS: readonly ResolvedToolDefinition[] = [
+ createResolvedTaskToolStub({ description: TASK_PEEK_DESCRIPTION, name: TASK_PEEK_TOOL_NAME }),
+ createResolvedTaskToolStub({ description: TASK_CANCEL_DESCRIPTION, name: TASK_CANCEL_TOOL_NAME }),
+ createResolvedTaskToolStub({ description: TASK_SEND_DESCRIPTION, name: TASK_SEND_TOOL_NAME }),
+ createResolvedTaskToolStub({ description: TASK_SLEEP_DESCRIPTION, name: TASK_SLEEP_TOOL_NAME }),
+];
diff --git a/packages/eve/src/runtime/prompt/compose.ts b/packages/eve/src/runtime/prompt/compose.ts
index 21eb21220..3ddac2a10 100644
--- a/packages/eve/src/runtime/prompt/compose.ts
+++ b/packages/eve/src/runtime/prompt/compose.ts
@@ -14,6 +14,9 @@ const PARALLEL_ACTION_INSTRUCTION =
const AGENT_MESSAGING_INSTRUCTION =
"Agent messaging\nAgents you have already delegated to stay available after they answer. eve injects the current `<agents>` list into the conversation as a note labeled `[Agents]`; it is added automatically by the framework, not written by the user, and never requires a reply. The list is only a record of those existing agents — their `agentId`, name, and latest status. It does not limit which subagent tools you can call: your tool list is the source of truth, and any subagent tool can always be called without `agentId` to start a new agent, including when the `<agents>` list is empty or absent. Pass `agentId` to the same subagent tool only to continue one of those existing agents' sessions.";
+const TASK_AGENT_MESSAGING_INSTRUCTION =
+ "Agent messaging\nAgents you have already delegated to remain visible in the framework-authored `<agents>` conversation note. `availability=busy` means the listed task still owns that agent session: use task_peek, task_send, or task_cancel with its taskId instead of starting a continuation. `availability=available` means no nonterminal task owns the session, so you may pass agentId to the same subagent tool to continue it. Calling a subagent without agentId always starts a new agent session.";
+
/**
* Input for composing the base authored instructions prompt for one
* resolved agent.
@@ -27,6 +30,7 @@ interface ComposeRuntimeBasePromptInput {
* continuation and the `<agents>` listing.
*/
persistentSubagentSessions?: boolean;
+ tasksEnabled?: boolean;
skills?: readonly ResolvedSkillDefinition[];
subagentsAvailable?: boolean;
toolsAvailable?: boolean;
@@ -43,7 +47,7 @@ export function composeRuntimeBasePrompt(input: ComposeRuntimeBasePromptInput):
...createWorkspacePromptBlocks(input.workspaceSpec),
...(input.toolsAvailable ? [PARALLEL_ACTION_INSTRUCTION] : []),
...(input.subagentsAvailable && input.persistentSubagentSessions
- ? [AGENT_MESSAGING_INSTRUCTION]
+ ? [input.tasksEnabled ? TASK_AGENT_MESSAGING_INSTRUCTION : AGENT_MESSAGING_INSTRUCTION]
: []),
...createConnectionsPromptBlocks(input.connections),
...createSkillsPromptBlocks(input.skills),
diff --git a/packages/eve/src/runtime/resolve-agent-graph.ts b/packages/eve/src/runtime/resolve-agent-graph.ts
index 3b7808ab8..f703bb6b1 100644
--- a/packages/eve/src/runtime/resolve-agent-graph.ts
+++ b/packages/eve/src/runtime/resolve-agent-graph.ts
@@ -217,7 +217,9 @@ async function resolveRuntimeAgentNode(
workspaceResourceRoot: agent.workspaceResourceRoot,
});
const subagentRegistry = createRuntimeSubagentRegistry({
- persistentSessions: agent.config?.experimental?.subagentPersistentSessions === true,
+ persistentSessions:
+ agent.config?.experimental?.tasks === true ||
+ agent.config?.experimental?.subagentPersistentSessions === true,
reservedToolNames: [
LOAD_SKILL_TOOL_NAME,
...toolRegistry.preparedTools.map((tool) => tool.name),
diff --git a/packages/eve/src/runtime/resolve-agent.ts b/packages/eve/src/runtime/resolve-agent.ts
index c81531e9e..d307163e7 100644
--- a/packages/eve/src/runtime/resolve-agent.ts
+++ b/packages/eve/src/runtime/resolve-agent.ts
@@ -202,6 +202,7 @@ function createResolvedAgentConfig(
config.experimental = {
instrumentationProviders: manifest.config.experimental.instrumentationProviders,
subagentPersistentSessions: manifest.config.experimental.subagentPersistentSessions,
+ tasks: manifest.config.experimental.tasks,
workflow:
manifest.config.experimental.workflow === undefined
? undefined
diff --git a/packages/eve/src/runtime/session-callback-route.test.ts b/packages/eve/src/runtime/session-callback-route.test.ts
index bcf8b5e28..42a7417e7 100644
--- a/packages/eve/src/runtime/session-callback-route.test.ts
+++ b/packages/eve/src/runtime/session-callback-route.test.ts
@@ -10,6 +10,8 @@ import {
} from "#runtime/session-callback-route.js";
const resumeHookMock = vi.fn();
+const TASK_ID = "task_1";
+const TASK_TOKEN = `task:${TASK_ID}:0123456789abcdef0123456789abcdef`;
vi.mock("#compiled/@workflow/core/runtime.js", () => ({
resumeHook: (token: string, payload: unknown) => resumeHookMock(token, payload),
@@ -36,6 +38,106 @@ describe("session callback route", () => {
expect([...names].some((name) => name.startsWith(".well-known/"))).toBe(false);
});
+ it("forwards remote task turn-start identity to the task hook", async () => {
+ resumeHookMock.mockResolvedValue(undefined);
+ const response = await handleSessionCallbackRequest(
+ new Request(`https://app.example.com/eve/v1/callback/${TASK_TOKEN}`, {
+ body: JSON.stringify({
+ callId: "call-task",
+ kind: "turn.started",
+ sessionId: "child-session",
+ subagentName: "research",
+ taskId: TASK_ID,
+ turnId: "turn_child_7",
+ }),
+ method: "POST",
+ }),
+ createRouteContext({ token: TASK_TOKEN }),
+ );
+
+ expect(response.status).toBe(202);
+ expect(resumeHookMock).toHaveBeenCalledWith(TASK_TOKEN, {
+ childSessionId: "child-session",
+ childTurnId: "turn_child_7",
+ kind: "turn-started",
+ taskId: TASK_ID,
+ });
+ });
+
+ it("forwards remote task input requests to the owning task hook", async () => {
+ resumeHookMock.mockResolvedValue(undefined);
+ const event = {
+ requests: [
+ {
+ action: {
+ callId: "release-call",
+ input: { marker: "RELEASE" },
+ kind: "tool-call",
+ toolName: "release",
+ },
+ allowFreeform: false,
+ display: "confirmation",
+ kind: "tool-approval",
+ options: [
+ { id: "approve", label: "Approve" },
+ { id: "reject", label: "Reject" },
+ ],
+ requestId: "req-1",
+ prompt: "Approve release",
+ },
+ ],
+ sequence: 3,
+ stepIndex: 2,
+ turnId: "turn-child",
+ };
+ const response = await handleSessionCallbackRequest(
+ new Request(`https://app.example.com/eve/v1/callback/${TASK_TOKEN}`, {
+ body: JSON.stringify({
+ callId: "call-task",
+ childContinuationToken: "remote-child-token",
+ childSessionId: "child-session",
+ event,
+ kind: "task.input-requested",
+ subagentName: "research",
+ taskId: TASK_ID,
+ }),
+ method: "POST",
+ }),
+ createRouteContext({ token: TASK_TOKEN }),
+ );
+
+ expect(response.status).toBe(202);
+ expect(resumeHookMock).toHaveBeenCalledWith(TASK_TOKEN, {
+ callId: "call-task",
+ childContinuationToken: "remote-child-token",
+ childSessionId: "child-session",
+ event,
+ kind: "subagent-input-request",
+ subagentName: "research",
+ });
+ });
+
+ it.each([
+ ["parent turn token", "turn-inbox", TASK_ID],
+ ["different task token", TASK_TOKEN, "task_other"],
+ ])("rejects task events carried by a %s", async (_label, token, taskId) => {
+ const response = await handleSessionCallbackRequest(
+ new Request(`https://app.example.com/eve/v1/callback/${token}`, {
+ body: JSON.stringify({
+ kind: "turn.started",
+ sessionId: "child-session",
+ taskId,
+ turnId: "turn-child",
+ }),
+ method: "POST",
+ }),
+ createRouteContext({ token }),
+ );
+
+ expect(response.status).toBe(403);
+ expect(resumeHookMock).not.toHaveBeenCalled();
+ });
+
it("synthesizes a terminal outcome envelope for session.completed", async () => {
resumeHookMock.mockResolvedValue(undefined);
diff --git a/packages/eve/src/runtime/session-callback-route.ts b/packages/eve/src/runtime/session-callback-route.ts
index a5f9e6ae9..18da40e3c 100644
--- a/packages/eve/src/runtime/session-callback-route.ts
+++ b/packages/eve/src/runtime/session-callback-route.ts
@@ -1,12 +1,22 @@
import { resumeHook } from "#internal/workflow/runtime.js";
+import { z } from "#compiled/zod/index.js";
import { REMOTE_AGENT_FAILED } from "#harness/agent-handle-errors.js";
import { EVE_CALLBACK_ROUTE_PATTERN } from "#protocol/routes.js";
import type { ChannelMethod, RouteContext } from "#public/definitions/channel.js";
+import type { SubagentAuthorizationEvent } from "#channel/types.js";
import type { ResolvedChannelDefinition } from "#runtime/types.js";
import type { RuntimeSubagentChildResult } from "#runtime/actions/types.js";
-import { agentTurnOutcomeSchema, type AgentTurnOutcome } from "#shared/agent-turn-outcome.js";
+import { agentTurnOutcomeSchema } from "#shared/agent-turn-outcome.js";
+import { jsonValueSchema } from "#shared/json-schemas.js";
import type { JsonValue } from "#shared/json.js";
+import { isInputRequest } from "#runtime/input/types.js";
import { tokenUsageSchema, type TokenUsage } from "#shared/token-usage.js";
+import type {
+ TaskInboundAuthorizationEvent,
+ TaskInboundInputRequest,
+ TaskInboundTurnStarted,
+} from "#tasks/types.js";
+import { readTaskIdFromInboxToken } from "#tasks/task-id.js";
export const HTTP_SESSION_CALLBACK_CHANNEL_NAME_PREFIX = "eve/v1/callback";
@@ -19,46 +29,133 @@ const ZERO_TOKEN_USAGE: TokenUsage = {
outputTokens: 0,
};
+// Wire schemas of the child→parent callback route. Possession of the
+// callback token is the authorization to settle; results bind to the
+// pending call by callId. `sessionId` is informational (tracing and
+// diagnostics) and never verified — new senders emit it, older eve
+// deployments may omit it.
+
+const eventCoordinateSchema = z.number().int().nonnegative();
+
+const authorizationChallengeSchema = z.looseObject({
+ displayName: z.string().optional(),
+ expiresAt: z.string().optional(),
+ instructions: z.string().optional(),
+ url: z.string().optional(),
+ userCode: z.string().optional(),
+});
+
/**
- * Wire payload of the child→parent callback route. Possession of the
- * callback token is the authorization to settle; results bind to the
- * pending call by callId. `sessionId` is informational (tracing and
- * diagnostics) and never verified — new senders emit it, older eve
- * deployments may omit it.
+ * Event payloads validate the fields the parent consumes and pass any
+ * remaining keys through unchanged (loose objects): the parent re-emits
+ * the event, so a newer child extending an event is never rejected here.
*/
-type SessionCallbackPayload =
- | {
- readonly callId: string;
- readonly kind: "session.completed";
- readonly output: JsonValue;
- readonly sessionId?: string;
- readonly subagentName: string;
- readonly usage?: TokenUsage;
- }
- | {
- readonly callId: string;
- /** Absent on callbacks from older eve deployments. */
- readonly error?: JsonValue;
- readonly kind: "session.failed";
- readonly sessionId?: string;
- readonly subagentName: string;
- }
- | {
- readonly callId: string;
- readonly kind: "turn.completed";
- readonly outcome: AgentTurnOutcome;
- readonly output: JsonValue;
- readonly sessionId?: string;
- readonly subagentName: string;
- }
- | {
- readonly callId: string;
- readonly error: JsonValue;
- readonly kind: "turn.failed";
- readonly outcome: AgentTurnOutcome;
- readonly sessionId?: string;
- readonly subagentName: string;
- };
+const taskInputEventSchema: z.ZodType<TaskInboundInputRequest["event"]> = z.looseObject({
+ requests: z.array(jsonValueSchema.refine(isInputRequest)).min(1),
+ sequence: eventCoordinateSchema,
+ stepIndex: eventCoordinateSchema,
+ turnId: z.string(),
+});
+
+const taskAuthorizationEventSchema: z.ZodType<SubagentAuthorizationEvent> = z.discriminatedUnion(
+ "type",
+ [
+ z.looseObject({
+ data: z.looseObject({
+ attemptId: z.string().optional(),
+ authorization: authorizationChallengeSchema.optional(),
+ description: z.string(),
+ name: z.string(),
+ sequence: eventCoordinateSchema,
+ stepIndex: eventCoordinateSchema,
+ turnId: z.string(),
+ webhookUrl: z.string().optional(),
+ }),
+ type: z.literal("authorization.required"),
+ }),
+ z.looseObject({
+ data: z.looseObject({
+ attemptId: z.string().optional(),
+ authorization: authorizationChallengeSchema.optional(),
+ name: z.string(),
+ outcome: z.enum(["authorized", "declined", "failed", "timed-out"]),
+ reason: z.string().optional(),
+ sequence: eventCoordinateSchema,
+ stepIndex: eventCoordinateSchema,
+ turnId: z.string(),
+ }),
+ type: z.literal("authorization.completed"),
+ }),
+ ],
+);
+
+const taskEventCallbackSchema = z.discriminatedUnion("kind", [
+ z.object({
+ callId: z.string(),
+ childContinuationToken: z.string(),
+ childSessionId: z.string(),
+ event: taskInputEventSchema,
+ kind: z.literal("task.input-requested"),
+ subagentName: z.string(),
+ taskId: z.string(),
+ }),
+ z.object({
+ callId: z.string(),
+ childContinuationToken: z.string(),
+ childSessionId: z.string(),
+ event: taskAuthorizationEventSchema,
+ kind: z.literal("task.authorization"),
+ subagentName: z.string(),
+ taskId: z.string(),
+ }),
+]);
+
+const taskTurnStartedCallbackSchema = z.object({
+ kind: z.literal("turn.started"),
+ sessionId: z.string().min(1),
+ taskId: z.string().min(1),
+ turnId: z.string().min(1),
+});
+
+/**
+ * Turn callbacks must carry the explicit `AgentTurnOutcome` envelope:
+ * the receiving parent settles the child's handle from `outcome.kind`, so
+ * a turn callback that cannot state its lifecycle is rejected rather than
+ * guessed at (pre-1.0: no wire compatibility shims). `usage` stays
+ * unvalidated here — {@link parseCallbackUsage} drops it, never rejects
+ * it, when malformed.
+ */
+const sessionResultCallbackSchema = z.discriminatedUnion("kind", [
+ z.object({
+ callId: z.string().min(1),
+ kind: z.literal("session.completed"),
+ output: jsonValueSchema.optional(),
+ subagentName: z.string().min(1),
+ usage: z.unknown().optional(),
+ }),
+ z.object({
+ callId: z.string().min(1),
+ /** Absent on callbacks from older eve deployments. */
+ error: jsonValueSchema.optional(),
+ kind: z.literal("session.failed"),
+ subagentName: z.string().min(1),
+ usage: z.unknown().optional(),
+ }),
+ z.object({
+ callId: z.string().min(1),
+ kind: z.literal("turn.completed"),
+ outcome: agentTurnOutcomeSchema,
+ output: jsonValueSchema.optional(),
+ subagentName: z.string().min(1),
+ }),
+ z.object({
+ callId: z.string().min(1),
+ error: jsonValueSchema,
+ kind: z.literal("turn.failed"),
+ outcome: agentTurnOutcomeSchema,
+ subagentName: z.string().min(1),
+ }),
+]);
export function getSessionCallbackChannelDefinitions(): readonly ResolvedChannelDefinition[] {
return HANDLED_METHODS.map((method) => buildCallbackChannelDefinition(method));
@@ -101,6 +198,28 @@ export async function handleSessionCallbackRequest(
return Response.json({ error: "Invalid JSON body.", ok: false }, { status: 400 });
}
+ const taskEvent = projectTaskEvent(body, token);
+ if (taskEvent instanceof Response) return taskEvent;
+ if (taskEvent !== undefined) {
+ try {
+ await resumeHook(token, taskEvent);
+ } catch {
+ return Response.json({ error: "Session callback not pending.", ok: false }, { status: 404 });
+ }
+ return Response.json({ ok: true }, { status: 202 });
+ }
+
+ const started = projectTaskTurnStarted(body, token);
+ if (started instanceof Response) return started;
+ if (started !== undefined) {
+ try {
+ await resumeHook(token, started);
+ } catch {
+ return Response.json({ error: "Session callback not pending.", ok: false }, { status: 404 });
+ }
+ return Response.json({ ok: true }, { status: 202 });
+ }
+
const result = projectSessionCallbackResult(body);
if (result instanceof Response) {
return result;
@@ -118,24 +237,98 @@ export async function handleSessionCallbackRequest(
return Response.json({ ok: true }, { status: 202 });
}
+function callbackKind(value: unknown): unknown {
+ if (value === null || typeof value !== "object") return undefined;
+ return Reflect.get(value, "kind");
+}
+
+function projectTaskEvent(
+ value: unknown,
+ token: string,
+): TaskInboundInputRequest | TaskInboundAuthorizationEvent | Response | undefined {
+ const kind = callbackKind(value);
+ if (kind !== "task.input-requested" && kind !== "task.authorization") return undefined;
+ const parsed = taskEventCallbackSchema.safeParse(value);
+ if (!parsed.success) {
+ return Response.json({ error: "Invalid task event callback.", ok: false }, { status: 400 });
+ }
+ const payload = parsed.data;
+ const tokenRejection = rejectMismatchedTaskToken(token, payload.taskId);
+ if (tokenRejection !== undefined) return tokenRejection;
+ if (payload.kind === "task.input-requested") {
+ return {
+ callId: payload.callId,
+ childContinuationToken: payload.childContinuationToken,
+ childSessionId: payload.childSessionId,
+ event: payload.event,
+ kind: "subagent-input-request",
+ subagentName: payload.subagentName,
+ };
+ }
+ return {
+ callId: payload.callId,
+ childSessionId: payload.childSessionId,
+ event: payload.event,
+ kind: "authorization-event",
+ subagentName: payload.subagentName,
+ };
+}
+
+function projectTaskTurnStarted(
+ value: unknown,
+ token: string,
+): TaskInboundTurnStarted | Response | undefined {
+ if (callbackKind(value) !== "turn.started") return undefined;
+ const parsed = taskTurnStartedCallbackSchema.safeParse(value);
+ if (!parsed.success) {
+ return Response.json(
+ { error: "Invalid task turn-start callback.", ok: false },
+ { status: 400 },
+ );
+ }
+ const tokenRejection = rejectMismatchedTaskToken(token, parsed.data.taskId);
+ if (tokenRejection !== undefined) return tokenRejection;
+ return {
+ childSessionId: parsed.data.sessionId,
+ childTurnId: parsed.data.turnId,
+ kind: "turn-started",
+ taskId: parsed.data.taskId,
+ };
+}
+
+function rejectMismatchedTaskToken(token: string, taskId: string): Response | undefined {
+ return readTaskIdFromInboxToken(token) === taskId
+ ? undefined
+ : Response.json({ error: "Task callback token mismatch.", ok: false }, { status: 403 });
+}
+
function projectSessionCallbackResult(value: unknown): RuntimeSubagentChildResult | Response {
if (value === null || typeof value !== "object") {
return Response.json({ error: "Expected a JSON object.", ok: false }, { status: 400 });
}
- const payload = value as Partial<SessionCallbackPayload>;
- if (typeof payload.callId !== "string" || payload.callId.length === 0) {
- return Response.json({ error: "Missing callback callId.", ok: false }, { status: 400 });
+ const kind = callbackKind(value);
+ if (
+ kind !== "session.completed" &&
+ kind !== "session.failed" &&
+ kind !== "turn.completed" &&
+ kind !== "turn.failed"
+ ) {
+ return Response.json({ error: "Unsupported callback kind.", ok: false }, { status: 400 });
}
- if (typeof payload.subagentName !== "string" || payload.subagentName.length === 0) {
- return Response.json({ error: "Missing callback subagentName.", ok: false }, { status: 400 });
+
+ const parsed = sessionResultCallbackSchema.safeParse(value);
+ if (!parsed.success) {
+ return Response.json({ error: "Invalid session result callback.", ok: false }, { status: 400 });
}
+ const payload = parsed.data;
+
// Task-session terminal callbacks carry no outcome envelope on the wire;
// this boundary synthesizes the terminal verdict (a task session always
// ends with its result) so the parent settles from an explicit outcome.
if (payload.kind === "session.completed") {
const output = payload.output ?? "";
- const usage = parseCallbackUsage((payload as { usage?: unknown }).usage);
+ const usage = parseCallbackUsage(payload.usage);
const base: RuntimeSubagentChildResult = {
callId: payload.callId,
kind: "subagent-result",
@@ -159,7 +352,7 @@ function projectSessionCallbackResult(value: unknown): RuntimeSubagentChildResul
message: "Remote agent failed.",
}
: payload.error;
- const usage = parseCallbackUsage((payload as { usage?: unknown }).usage);
+ const usage = parseCallbackUsage(payload.usage);
return {
callId: payload.callId,
isError: true,
@@ -176,61 +369,28 @@ function projectSessionCallbackResult(value: unknown): RuntimeSubagentChildResul
}
if (payload.kind === "turn.completed") {
- const outcome = parseCallbackOutcome((payload as { outcome?: unknown }).outcome);
- if (outcome instanceof Response) {
- return outcome;
- }
- const result: RuntimeSubagentChildResult = {
+ return {
callId: payload.callId,
kind: "subagent-result",
origin: "child",
- outcome,
+ outcome: payload.outcome,
output: payload.output ?? "",
subagentName: payload.subagentName,
// Per-result usage projection (usage spans); the parent folds
// `outcome.usageDelta`, never this field, when an outcome is present.
- usage: outcome.usageDelta,
+ usage: payload.outcome.usageDelta,
};
- return result;
}
- if (payload.kind === "turn.failed") {
- if (payload.error === undefined) {
- return Response.json({ error: "Missing callback error.", ok: false }, { status: 400 });
- }
- const outcome = parseCallbackOutcome((payload as { outcome?: unknown }).outcome);
- if (outcome instanceof Response) {
- return outcome;
- }
- return {
- callId: payload.callId,
- isError: true,
- kind: "subagent-result",
- origin: "child",
- outcome,
- output: payload.error,
- subagentName: payload.subagentName,
- };
- }
-
- return Response.json({ error: "Unsupported callback kind.", ok: false }, { status: 400 });
-}
-
-/**
- * Turn callbacks must carry the explicit {@link AgentTurnOutcome} envelope:
- * the receiving parent settles the child's handle from `outcome.kind`, so
- * a turn callback that cannot state its lifecycle is rejected rather than
- * guessed at (pre-1.0: no wire compatibility shims).
- */
-function parseCallbackOutcome(value: unknown): AgentTurnOutcome | Response {
- const parsed = agentTurnOutcomeSchema.safeParse(value);
- if (!parsed.success) {
- return Response.json(
- { error: "Missing or invalid callback outcome.", ok: false },
- { status: 400 },
- );
- }
- return parsed.data;
+ return {
+ callId: payload.callId,
+ isError: true,
+ kind: "subagent-result",
+ origin: "child",
+ outcome: payload.outcome,
+ output: payload.error,
+ subagentName: payload.subagentName,
+ };
}
/**
diff --git a/packages/eve/src/runtime/task-input-response-route.test.ts b/packages/eve/src/runtime/task-input-response-route.test.ts
new file mode 100644
index 000000000..90563d0e7
--- /dev/null
+++ b/packages/eve/src/runtime/task-input-response-route.test.ts
@@ -0,0 +1,82 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { sendCommandToDelivery } from "#execution/session-command-wire.js";
+import { EVE_TASK_INPUT_ROUTE_PATTERN } from "#protocol/routes.js";
+import type { RouteContext } from "#public/definitions/channel.js";
+import {
+ getTaskInputResponseChannelDefinitions,
+ handleTaskInputResponseRequest,
+} from "#runtime/task-input-response-route.js";
+
+const resumeHookMock = vi.fn();
+const DIGEST = "0123456789abcdef0123456789abcdef";
+const CAPABILITY_TOKEN = `eve:task-input:${DIGEST}`;
+const TARGET_TOKEN = `eve:eve:op:${DIGEST}`;
+
+vi.mock("#compiled/@workflow/core/runtime.js", () => ({
+ resumeHook: (token: string, payload: unknown) => resumeHookMock(token, payload),
+}));
+
+describe("task input response capability", () => {
+ beforeEach(() => resumeHookMock.mockReset());
+
+ it("registers one capability-scoped POST route", () => {
+ expect(getTaskInputResponseChannelDefinitions()).toEqual([
+ expect.objectContaining({ method: "POST", urlPath: EVE_TASK_INPUT_ROUTE_PATTERN }),
+ ]);
+ });
+
+ it("resumes only the addressed child input batch", async () => {
+ resumeHookMock.mockResolvedValue(undefined);
+ const response = await handleTaskInputResponseRequest(
+ request({ inputResponses: [{ optionId: "approve", requestId: "req-1" }] }),
+ context(CAPABILITY_TOKEN),
+ );
+
+ expect(response.status).toBe(202);
+ expect(resumeHookMock).toHaveBeenCalledWith(
+ TARGET_TOKEN,
+ sendCommandToDelivery({
+ kind: "send",
+ payload: { inputResponses: [{ optionId: "approve", requestId: "req-1" }] },
+ }),
+ );
+ });
+
+ it("rejects messages and empty response batches", async () => {
+ for (const body of [{ message: "not allowed" }, { inputResponses: [] }]) {
+ const response = await handleTaskInputResponseRequest(
+ request(body),
+ context(CAPABILITY_TOKEN),
+ );
+ expect(response.status).toBe(400);
+ }
+ expect(resumeHookMock).not.toHaveBeenCalled();
+ });
+
+ it("rejects generic workflow hook tokens", async () => {
+ const response = await handleTaskInputResponseRequest(
+ request({ inputResponses: [{ requestId: "req-1", text: "forged" }] }),
+ context("eve:session:victim:inbox"),
+ );
+
+ expect(response.status).toBe(403);
+ expect(resumeHookMock).not.toHaveBeenCalled();
+ });
+});
+
+function request(body: unknown): Request {
+ return new Request("https://remote.example/eve/v1/task-input/child-token", {
+ body: JSON.stringify(body),
+ headers: { "content-type": "application/json" },
+ method: "POST",
+ });
+}
+
+function context(token: string): RouteContext {
+ return {
+ params: { token },
+ requestIp: null,
+ waitUntil() {},
+ };
+}
diff --git a/packages/eve/src/runtime/task-input-response-route.ts b/packages/eve/src/runtime/task-input-response-route.ts
new file mode 100644
index 000000000..a180f4bd8
--- /dev/null
+++ b/packages/eve/src/runtime/task-input-response-route.ts
@@ -0,0 +1,92 @@
+import { sendCommandToDelivery } from "#execution/session-command-wire.js";
+import { readTaskInputTargetToken } from "#execution/task-input-capability.js";
+import { resumeHook } from "#internal/workflow/runtime.js";
+import { EVE_TASK_INPUT_ROUTE_PATTERN } from "#protocol/routes.js";
+import type { ChannelMethod, RouteContext } from "#public/definitions/channel.js";
+import type { InputResponse } from "#runtime/input/types.js";
+import type { ResolvedChannelDefinition } from "#runtime/types.js";
+
+const NAME = "eve/v1/task-input/post";
+
+export function getTaskInputResponseChannelDefinitions(): readonly ResolvedChannelDefinition[] {
+ return [
+ {
+ fetch: handleTaskInputResponseRequest,
+ logicalPath: `framework://channels/${NAME}`,
+ method: "POST" satisfies ChannelMethod,
+ name: NAME,
+ sourceId: "eve:framework:task-input-post",
+ sourceKind: "module",
+ urlPath: EVE_TASK_INPUT_ROUTE_PATTERN,
+ },
+ ];
+}
+
+export function getTaskInputResponseChannelNames(): ReadonlySet<string> {
+ return new Set([NAME]);
+}
+
+export async function handleTaskInputResponseRequest(
+ request: Request,
+ ctx: RouteContext,
+): Promise<Response> {
+ const token = ctx.params.token;
+ if (typeof token !== "string" || token.length === 0) {
+ return Response.json({ error: "Missing task input token.", ok: false }, { status: 400 });
+ }
+ const targetToken = readTaskInputTargetToken(token);
+ if (targetToken === undefined) {
+ return Response.json({ error: "Invalid task input token.", ok: false }, { status: 403 });
+ }
+ let body: unknown;
+ try {
+ body = await request.json();
+ } catch {
+ return Response.json({ error: "Invalid JSON body.", ok: false }, { status: 400 });
+ }
+ const inputResponses = readInputResponses(body);
+ if (inputResponses === undefined || inputResponses.length === 0) {
+ return Response.json(
+ { error: "Expected a non-empty inputResponses array.", ok: false },
+ { status: 400 },
+ );
+ }
+ // Child inboxes outlive deployments; cross the hook in the durable
+ // delivery envelope like every other session-inbox producer.
+ const command = sendCommandToDelivery({ kind: "send", payload: { inputResponses } });
+ try {
+ await resumeHook(targetToken, command);
+ } catch {
+ return Response.json(
+ { error: "Task input target is not pending.", ok: false },
+ { status: 404 },
+ );
+ }
+ return Response.json({ ok: true }, { status: 202 });
+}
+
+function readInputResponses(value: unknown): readonly InputResponse[] | undefined {
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;
+ const responses = Reflect.get(value, "inputResponses");
+ if (!Array.isArray(responses)) return undefined;
+ const parsed: InputResponse[] = [];
+ for (const response of responses) {
+ if (response === null || typeof response !== "object" || Array.isArray(response))
+ return undefined;
+ const requestId = Reflect.get(response, "requestId");
+ const optionId = Reflect.get(response, "optionId");
+ const text = Reflect.get(response, "text");
+ if (
+ typeof requestId !== "string" ||
+ (optionId !== undefined && typeof optionId !== "string") ||
+ (text !== undefined && typeof text !== "string")
+ ) {
+ return undefined;
+ }
+ const item: { optionId?: string; requestId: string; text?: string } = { requestId };
+ if (typeof optionId === "string") item.optionId = optionId;
+ if (typeof text === "string") item.text = text;
+ parsed.push(item);
+ }
+ return parsed;
+}
diff --git a/packages/eve/src/shared/agent-definition.ts b/packages/eve/src/shared/agent-definition.ts
index a403b7b4b..aa9d3fb69 100644
--- a/packages/eve/src/shared/agent-definition.ts
+++ b/packages/eve/src/shared/agent-definition.ts
@@ -207,6 +207,13 @@ export interface AgentExperimentalDefinition {
* When unset, delegated children run as one-shot tasks.
*/
readonly subagentPersistentSessions?: boolean;
+ /**
+ * Runs this agent's delegated subagent calls as durable background tasks.
+ * The originating tool call returns a task receipt immediately and the
+ * model manages the work through the `task_*` framework tools. Implies
+ * persistent-session children for subagent dispatch. Root agents only.
+ */
+ readonly tasks?: boolean;
/**
* Durable Workflow runtime configuration. Root agents may use this to select
* the Workflow world backing sessions and runs.
diff --git a/packages/eve/src/tasks/json.ts b/packages/eve/src/tasks/json.ts
index 2ec1a9d96..557d2f842 100644
--- a/packages/eve/src/tasks/json.ts
+++ b/packages/eve/src/tasks/json.ts
@@ -43,23 +43,23 @@ const taskViewJsonSchema = z.discriminatedUnion("status", [
]);
/**
- * Model-visible task snapshot, inferred from {@link taskViewJsonSchema}.
+ * Model-visible task view, inferred from {@link taskViewJsonSchema}.
*
* This is the public projection of `TaskView` (#tasks/types.js), not a
- * replacement for it: the durable snapshot additionally carries private
+ * replacement for it: the durable view additionally carries private
* `executor` and `usage`, and its module must stay zod-free because it is
* bundled into workflow bodies.
*/
-export type TaskViewJson = z.infer<typeof taskViewJsonSchema>;
+type TaskViewJson = z.infer<typeof taskViewJsonSchema>;
-/** Projects a task snapshot into the JSON value carried by tool results. */
+/** Projects a task view into the JSON value carried by tool results. */
export function taskViewToJson(view: TaskView): TaskViewJson {
// `satisfies` couples the schema to `TaskView` at compile time; the runtime
// parse strips the private fields structural typing would let through.
return taskViewJsonSchema.parse(view satisfies TaskViewJson);
}
-/** Projects many snapshots into one `{ tasks }` tool output. */
+/** Projects many views into one `{ tasks }` tool output. */
export function taskViewsToJson(views: readonly TaskView[]): JsonValue {
return { tasks: views.map((view) => taskViewToJson(view)) };
}
diff --git a/packages/eve/src/tasks/session-index.test.ts b/packages/eve/src/tasks/session-index.test.ts
index 536ae9815..278f09881 100644
--- a/packages/eve/src/tasks/session-index.test.ts
+++ b/packages/eve/src/tasks/session-index.test.ts
@@ -37,7 +37,7 @@ describe("session task index", () => {
it("records a task and finds it by id", () => {
const session = recordSessionTask(createSession(), {
- continuationToken: "task:token-1",
+ taskInboxToken: "task:token-1",
createdByTurnId: "turn-1",
metadata,
operationId: "operation-1",
@@ -46,7 +46,7 @@ describe("session task index", () => {
});
expect(findSessionTaskEntry(session.state, "task_a")).toEqual({
- continuationToken: "task:token-1",
+ taskInboxToken: "task:token-1",
createdByTurnId: "turn-1",
metadata,
operationId: "operation-1",
@@ -58,7 +58,7 @@ describe("session task index", () => {
it("replaces the entry on replayed creation instead of duplicating it", () => {
let session = recordSessionTask(createSession(), {
- continuationToken: "task:token-1",
+ taskInboxToken: "task:token-1",
createdByTurnId: "turn-1",
metadata,
operationId: "operation-1",
@@ -66,7 +66,7 @@ describe("session task index", () => {
taskRunId: "run-1",
});
session = recordSessionTask(session, {
- continuationToken: "task:token-2",
+ taskInboxToken: "task:token-2",
createdByTurnId: "turn-1",
metadata,
operationId: "operation-1",
@@ -79,27 +79,25 @@ describe("session task index", () => {
expect(entries[0]?.taskRunId).toBe("run-2");
});
- it("retains only terminal snapshots as expired-run fallbacks", () => {
+ it("retains only terminal views as expired-run fallbacks", () => {
const base = {
- continuationToken: "task:token-1",
+ taskInboxToken: "task:token-1",
createdByTurnId: "turn-1",
metadata,
operationId: "operation-1",
taskId: "task_a",
taskRunId: "run-1",
};
- const terminalSnapshot = {
+ const terminalView = {
lastOutput: { data: "done", type: "result" as const },
metadata,
status: "completed" as const,
taskId: "task_a",
};
- const session = recordSessionTask(createSession(), { ...base, terminalSnapshot });
- expect(findSessionTaskEntry(session.state, "task_a")?.terminalSnapshot).toEqual(
- terminalSnapshot,
- );
- for (const invalidSnapshot of [
+ const session = recordSessionTask(createSession(), { ...base, terminalView });
+ expect(findSessionTaskEntry(session.state, "task_a")?.terminalView).toEqual(terminalView);
+ for (const invalidView of [
{ metadata, status: "working", taskId: "task_a" },
{ metadata, status: "completed", taskId: "task_a" },
{
@@ -121,12 +119,12 @@ describe("session task index", () => {
status: "completed",
taskId: "task_a",
},
- { ...terminalSnapshot, taskId: "task_other" },
+ { ...terminalView, taskId: "task_other" },
]) {
expect(() =>
getSessionTaskIndex({
[SESSION_TASKS_STATE_KEY]: {
- tasks: [{ ...base, terminalSnapshot: invalidSnapshot }],
+ tasks: [{ ...base, terminalView: invalidView }],
},
}),
).toThrow(`Corrupt task index under session state key "${SESSION_TASKS_STATE_KEY}"`);
diff --git a/packages/eve/src/tasks/session-index.ts b/packages/eve/src/tasks/session-index.ts
index 77de570c8..e863db6ae 100644
--- a/packages/eve/src/tasks/session-index.ts
+++ b/packages/eve/src/tasks/session-index.ts
@@ -19,17 +19,17 @@ export const SESSION_TASKS_STATE_KEY = "eve.tasks";
* One task owned by this session. Immutable model-safe metadata keeps the
* task-to-agent join available before the task run publishes its first view.
*
- * `continuationToken` is the private routing credential for the task run's
+ * `taskInboxToken` is the private routing credential for the task run's
* inbound hook. It must never render into model context, history, task
- * snapshots, or compaction summaries — the model addresses tasks by
+ * views, or compaction summaries — the model addresses tasks by
* `taskId` only, and lookup verifies ownership through this index.
*/
export interface SessionTaskIndexEntry {
readonly taskId: string;
readonly taskRunId: string;
/** Immutable fallback once the owning workflow run expires. */
- readonly terminalSnapshot?: TaskView;
- readonly continuationToken: string;
+ readonly terminalView?: TaskView;
+ readonly taskInboxToken: string;
readonly createdByStepIndex?: number;
readonly createdByTurnId: string;
readonly metadata: TaskMetadata;
@@ -64,7 +64,7 @@ const taskViewBaseShape = {
};
/**
- * Terminal snapshots only, on purpose: the index caches a snapshot solely as
+ * Terminal views only, on purpose: the index caches a view solely as
* the expired-run fallback, and the discriminated arms encode the terminal
* status/output invariants structurally (strict objects reject
* `inputRequests` and mismatched outputs).
@@ -84,14 +84,14 @@ const taskViewSchema: z.ZodType<TaskView> = z.discriminatedUnion("status", [
]);
const sessionTaskIndexEntrySchema: z.ZodType<SessionTaskIndexEntry> = z.strictObject({
- continuationToken: z.string().min(1),
+ taskInboxToken: z.string().min(1),
createdByStepIndex: z.number().int().nonnegative().optional(),
createdByTurnId: z.string().min(1),
metadata: taskMetadataSchema,
operationId: z.string().min(1),
taskId: z.string().min(1),
taskRunId: z.string().min(1),
- terminalSnapshot: taskViewSchema.optional(),
+ terminalView: taskViewSchema.optional(),
});
const sessionTaskIndexSchema = z
@@ -108,11 +108,11 @@ const sessionTaskIndexSchema = z
(index) =>
index.tasks.every(
(entry) =>
- entry.terminalSnapshot === undefined ||
- (entry.terminalSnapshot.taskId === entry.taskId &&
- sameTaskMetadata(entry.terminalSnapshot.metadata, entry.metadata)),
+ entry.terminalView === undefined ||
+ (entry.terminalView.taskId === entry.taskId &&
+ sameTaskMetadata(entry.terminalView.metadata, entry.metadata)),
),
- { message: "Cached terminal snapshots must match their task index entry." },
+ { message: "Cached terminal views must match their task index entry." },
);
interface SessionTaskIndex {
@@ -141,26 +141,26 @@ export function getSessionTaskIndex(
return parsed.data.tasks;
}
-/** Caches one terminal snapshot beside its task-run address. */
-export function cacheTerminalTaskSnapshot(
+/** Caches one terminal view beside its task-run address. */
+export function cacheTerminalTaskView(
state: SessionStateMap | undefined,
- snapshot: TaskView,
+ view: TaskView,
): SessionStateMap | undefined {
- if (!isValidTerminalSnapshot(snapshot)) {
- throw new Error(`Cannot cache invalid terminal task "${snapshot.taskId}".`);
+ if (!isValidTerminalView(view)) {
+ throw new Error(`Cannot cache invalid terminal task "${view.taskId}".`);
}
const entries = getSessionTaskIndex(state);
- const index = entries.findIndex((entry) => entry.taskId === snapshot.taskId);
+ const index = entries.findIndex((entry) => entry.taskId === view.taskId);
if (index < 0) return state;
- if (!sameTaskMetadata(entries[index]!.metadata, snapshot.metadata)) {
- throw new Error(`Task snapshot metadata does not match index entry "${snapshot.taskId}".`);
+ if (!sameTaskMetadata(entries[index]!.metadata, view.metadata)) {
+ throw new Error(`Task view metadata does not match index entry "${view.taskId}".`);
}
const tasks = [...entries];
- tasks[index] = { ...tasks[index]!, terminalSnapshot: snapshot };
+ tasks[index] = { ...tasks[index]!, terminalView: view };
return { ...state, [SESSION_TASKS_STATE_KEY]: { tasks } };
}
-function isValidTerminalSnapshot(view: TaskView): boolean {
+function isValidTerminalView(view: TaskView): boolean {
if (view.inputRequests !== undefined) return false;
switch (view.status) {
case "completed":
diff --git a/packages/eve/src/tasks/task-id.ts b/packages/eve/src/tasks/task-id.ts
index eda19f5bb..8496fe4d9 100644
--- a/packages/eve/src/tasks/task-id.ts
+++ b/packages/eve/src/tasks/task-id.ts
@@ -24,7 +24,7 @@ export function deriveTaskId(input: {
}
/**
- * Derives the task run's private continuation token.
+ * Derives the task run's private inbox token.
*
* Deterministic on purpose: a durable replay of the dispatch step must
* re-derive the same token so the duplicate task run loses the hook
@@ -33,7 +33,7 @@ export function deriveTaskId(input: {
* itself a private capability, and the derived token never renders to
* the model.
*/
-export function deriveTaskContinuationToken(input: {
+export function deriveTaskInboxToken(input: {
readonly parentContinuationToken: string;
readonly taskId: string;
}): string {
@@ -43,8 +43,8 @@ export function deriveTaskContinuationToken(input: {
.slice(0, 32)}`;
}
-/** Reads the non-secret task id embedded in a private task continuation token. */
-export function readTaskIdFromContinuationToken(token: string): string | undefined {
+/** Reads the non-secret task id embedded in a private task inbox token. */
+export function readTaskIdFromInboxToken(token: string): string | undefined {
const match = /^task:(task_[^:]+):[a-f0-9]{32}$/.exec(token);
return match?.[1];
}
diff --git a/packages/eve/src/tasks/transitions.test.ts b/packages/eve/src/tasks/transitions.test.ts
index 7a92f5151..b43493dda 100644
--- a/packages/eve/src/tasks/transitions.test.ts
+++ b/packages/eve/src/tasks/transitions.test.ts
@@ -23,7 +23,9 @@ const TERMINAL_STATUSES: readonly TaskStatus[] = ["completed", "failed", "cancel
const ALL_COMMANDS: readonly TaskCommand[] = [
{ data: { answer: 42 }, kind: "complete" },
{ data: { message: "boom" }, kind: "fail" },
+ { data: { message: "unindexed" }, kind: "reject-dispatch" },
{ kind: "cancel" },
+ { kind: "require-authorization", requestId: "auth-1" },
{ inputRequests: [{ question: "which?" }], kind: "require-input" },
{ kind: "ready" },
{ kind: "answered", requestIds: ["req-1"] },
@@ -41,7 +43,7 @@ describe("applyTaskTransition", () => {
expect(result.view.lastOutput).toEqual({ data: { answer: 42 }, type: "result" });
});
- it("retains reported child usage on the terminal snapshot only", () => {
+ it("retains reported child usage on the terminal view only", () => {
const usage = { cacheReadTokens: 1, cacheWriteTokens: 2, inputTokens: 300, outputTokens: 40 };
for (const command of [
{ data: "done", kind: "complete", usage },
@@ -155,6 +157,33 @@ describe("applyTaskTransition", () => {
expect(stale.view.inputRequests).toEqual([{ question: "second", requestId: "req-2" }]);
});
+ it("keeps independent authorization attempts blocked until each completes", () => {
+ const first = applyTaskTransition(createView("working"), {
+ kind: "require-authorization",
+ requestId: "auth-1",
+ });
+ const second = applyTaskTransition(first.view, {
+ kind: "require-authorization",
+ requestId: "auth-2",
+ });
+ const completedFirst = applyTaskTransition(second.view, {
+ kind: "answered",
+ requestIds: ["auth-1"],
+ });
+
+ expect(second.view).toMatchObject({
+ inputRequests: [
+ { blockedOn: "authorization", requestId: "auth-1" },
+ { blockedOn: "authorization", requestId: "auth-2" },
+ ],
+ status: "input_required",
+ });
+ expect(completedFirst.view).toMatchObject({
+ inputRequests: [{ blockedOn: "authorization", requestId: "auth-2" }],
+ status: "input_required",
+ });
+ });
+
it("replaces the outstanding batch on repeated require-input", () => {
const first = applyTaskTransition(createView("working"), {
inputRequests: [{ question: "first", requestId: "req-1" }],
diff --git a/packages/eve/src/tasks/transitions.ts b/packages/eve/src/tasks/transitions.ts
index c8bcac98b..9a61c13a3 100644
--- a/packages/eve/src/tasks/transitions.ts
+++ b/packages/eve/src/tasks/transitions.ts
@@ -8,7 +8,7 @@ import type {
import { isTerminalTaskStatus, readTaskInputRequestId } from "#tasks/types.js";
/**
- * Outcome of applying one command to a task snapshot.
+ * Outcome of applying one command to a task view.
*
* - `accepted`: the state changed; the new view must be appended.
* - `noop`: the command is recognized and benign (idempotent cancel,
@@ -16,7 +16,7 @@ import { isTerminalTaskStatus, readTaskInputRequestId } from "#tasks/types.js";
* - `rejected`: the command is invalid for the current status; the
* reason is diagnostic only.
*/
-export type TaskTransitionResult =
+type TaskTransitionResult =
| { readonly outcome: "accepted"; readonly view: TaskView }
| { readonly outcome: "noop"; readonly view: TaskView }
| { readonly outcome: "rejected"; readonly view: TaskView; readonly reason: string };
@@ -39,13 +39,13 @@ export type TaskTransitionResult =
* transitions.
*/
/**
- * Builds the settled snapshot for one terminal command, carrying the
+ * Builds the settled view for one terminal command, carrying the
* child's lifecycle verdict and reported usage when present. Usage is
* retention-only: nothing folds it into parent budgets yet.
*/
function terminalView(
view: TaskView,
- command: Extract<TaskCommand, { kind: "complete" | "fail" | "cancel" }>,
+ command: Extract<TaskCommand, { kind: "complete" | "fail" | "reject-dispatch" | "cancel" }>,
settled:
| {
readonly lastOutput: Extract<TaskOutput, { type: "result" }>;
@@ -107,6 +107,7 @@ export function applyTaskTransition(view: TaskView, command: TaskCommand): TaskT
}),
};
case "fail":
+ case "reject-dispatch":
return {
outcome: "accepted",
view: terminalView(view, command, {
@@ -125,6 +126,32 @@ export function applyTaskTransition(view: TaskView, command: TaskCommand): TaskT
reason: `Task "${view.taskId}" is not terminal; usage settles with its terminal command.`,
view,
};
+ case "require-authorization": {
+ const blocker = { blockedOn: "authorization", requestId: command.requestId };
+ if (view.status === "input_required") {
+ if (
+ view.inputRequests.some(
+ (request) => readTaskInputRequestId(request) === command.requestId,
+ )
+ ) {
+ return { outcome: "noop", view };
+ }
+ return {
+ outcome: "accepted",
+ view: { ...view, inputRequests: [...view.inputRequests, blocker] },
+ };
+ }
+ return {
+ outcome: "accepted",
+ view: {
+ inputRequests: [blocker],
+ executor: view.executor,
+ metadata: view.metadata,
+ status: "input_required",
+ taskId: view.taskId,
+ },
+ };
+ }
case "require-input":
if (!isValidInputRequestBatch(command.inputRequests)) {
return {
@@ -153,7 +180,7 @@ export function applyTaskTransition(view: TaskView, command: TaskCommand): TaskT
}
const answered = new Set(command.requestIds);
- const outstanding = view.inputRequests ?? [];
+ const outstanding = view.inputRequests;
const remaining = outstanding.filter((request) => {
const requestId = readTaskInputRequestId(request);
return requestId === undefined || !answered.has(requestId);
diff --git a/packages/eve/src/tasks/types.ts b/packages/eve/src/tasks/types.ts
index f765ea3ac..5ad2adb2c 100644
--- a/packages/eve/src/tasks/types.ts
+++ b/packages/eve/src/tasks/types.ts
@@ -6,8 +6,8 @@ import type { SubagentAuthorizationEvent } from "#channel/types.js";
*
* A task is one durable unit of delegated work owned by a parent session.
* The durable task run is the single writer for lifecycle transitions
- * (see `#execution/tasks/run-task-workflow.js`); every other path submits
- * commands and reads snapshots. This module is dependency-free on
+ * (see `#execution/tasks/child/workflow.js`); every other path submits
+ * commands and reads views. This module is dependency-free on
* purpose: it is bundled into workflow bodies, which reject Node.js
* builtins and heavyweight validators.
*/
@@ -117,7 +117,15 @@ export interface TaskInputResponse {
* bound to the same entry, so completing authorization can never clear
* an unrelated request batch the child raised in the meantime.
*/
-export const TASK_AUTHORIZATION_REQUEST_ID = "task:authorization";
+const TASK_AUTHORIZATION_REQUEST_ID_PREFIX = "task:authorization";
+
+/** Stable task blocker id shared by one authorization attempt's events. */
+export function taskAuthorizationRequestId(event: SubagentAuthorizationEvent): string {
+ if (event.type === "approval.candidate" || event.type === "approval.settled") {
+ return `${TASK_AUTHORIZATION_REQUEST_ID_PREFIX}:${event.data.requestId}`;
+ }
+ return `${TASK_AUTHORIZATION_REQUEST_ID_PREFIX}:${event.data.attemptId ?? event.data.name}`;
+}
/** Reads the `requestId` of one opaque outstanding request. */
export function readTaskInputRequestId(request: TaskInputRequest): string | undefined {
@@ -126,7 +134,7 @@ export function readTaskInputRequestId(request: TaskInputRequest): string | unde
return typeof requestId === "string" ? requestId : undefined;
}
-/** Fields shared by every durable task snapshot. */
+/** Fields shared by every durable task view. */
interface TaskViewBase {
readonly taskId: string;
readonly metadata: TaskMetadata;
@@ -142,10 +150,10 @@ interface TaskViewBase {
}
/**
- * Full durable task snapshot discriminated by lifecycle status.
+ * Full durable task view discriminated by lifecycle status.
*
* The task run appends one per accepted command; readers always observe a
- * complete view, never a delta. A snapshot never contains routing credentials,
+ * complete view, never a delta. A view never contains routing credentials,
* continuation tokens, or authorization capabilities.
*
* Completed and failed tasks carry their corresponding output, cancelled
@@ -194,6 +202,13 @@ export type TaskCommand =
readonly lifecycle?: "parked" | "terminal";
readonly usage?: TaskUsage;
}
+ /** Terminal dispatch rejection for a task that was never indexed by its parent. */
+ | {
+ readonly kind: "reject-dispatch";
+ readonly data: JsonValue;
+ readonly lifecycle?: never;
+ readonly usage?: never;
+ }
| {
readonly kind: "cancel";
readonly lifecycle?: "parked" | "terminal";
@@ -201,6 +216,7 @@ export type TaskCommand =
}
/** Retains a late executor settlement without changing task terminal status. */
| { readonly kind: "settle-executor"; readonly usage?: TaskUsage }
+ | { readonly kind: "require-authorization"; readonly requestId: string }
| { readonly kind: "require-input"; readonly inputRequests: readonly TaskInputRequest[] }
| { readonly kind: "ready" }
/**
@@ -244,7 +260,7 @@ export interface TaskInboundChildResult {
| { readonly kind: "cancelled" };
/**
* Provider usage this turn added. Retained on the terminal task
- * snapshot ({@link TaskView.usage}); folding it into parent
+ * view ({@link TaskView.usage}); folding it into parent
* budgets is deferred until a reservation model lands.
*/
readonly usageDelta?: unknown;
@@ -256,7 +272,7 @@ export interface TaskInboundChildResult {
/**
* Arrives when the delegated child emits `input.requested`. After dispatch is
* acknowledged, the task run exposes the batch in an `input_required`
- * snapshot and forwards the request to the parent session.
+ * view and forwards the request to the parent session.
*/
export interface TaskInboundInputRequest {
readonly callId: string;
@@ -287,8 +303,8 @@ export interface TaskInboundTurnStarted {
/**
* Arrives when the delegated child emits `authorization.required` or
* `authorization.completed`. The former exposes an authorization blocker in
- * the task snapshot; the latter clears it. The event is forwarded separately
- * to the parent and is never copied into the snapshot.
+ * the task view; the latter clears it. The event is forwarded separately
+ * to the parent and is never copied into the view.
*/
export interface TaskInboundAuthorizationEvent {
readonly callId: string;
@@ -322,8 +338,8 @@ export type TaskRunInboundPayload =
| TaskInboundAuthorizationEvent
| TaskInboundAnswerInput;
-/** Namespaced run stream carrying `TaskView` snapshots. */
-export const TASK_SNAPSHOT_STREAM_NAMESPACE = "eve.task";
+/** Namespaced run stream carrying appended `TaskView` records. */
+export const TASK_VIEW_STREAM_NAMESPACE = "eve.task";
/** True when the status can never change again. */
export function isTerminalTaskStatus(status: TaskStatus): boolean {
diff --git a/packages/eve/src/tasks/wire.test.ts b/packages/eve/src/tasks/wire.test.ts
index 2f104069b..6461e61f3 100644
--- a/packages/eve/src/tasks/wire.test.ts
+++ b/packages/eve/src/tasks/wire.test.ts
@@ -1,6 +1,5 @@
import { describe, expect, it } from "vitest";
-import { TASK_AUTHORIZATION_REQUEST_ID } from "#tasks/types.js";
import { translateTaskInboundPayload } from "#tasks/wire.js";
const ZERO_USAGE = { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 0, outputTokens: 0 };
@@ -144,12 +143,14 @@ describe("translateTaskInboundPayload", () => {
});
it("blocks authorization under a reserved id that only its completion clears", () => {
+ const requestId = "task:authorization:attempt-1";
expect(
translateTaskInboundPayload({
callId: "call-1",
childSessionId: "child-session",
event: {
data: {
+ attemptId: "attempt-1",
description: "Authorize GitHub",
name: "github",
sequence: 1,
@@ -162,8 +163,8 @@ describe("translateTaskInboundPayload", () => {
subagentName: "research",
}),
).toEqual({
- inputRequests: [{ blockedOn: "authorization", requestId: TASK_AUTHORIZATION_REQUEST_ID }],
- kind: "require-input",
+ kind: "require-authorization",
+ requestId,
});
expect(
translateTaskInboundPayload({
@@ -171,6 +172,7 @@ describe("translateTaskInboundPayload", () => {
childSessionId: "child-session",
event: {
data: {
+ attemptId: "attempt-1",
name: "github",
outcome: "authorized",
sequence: 2,
@@ -182,7 +184,7 @@ describe("translateTaskInboundPayload", () => {
kind: "authorization-event",
subagentName: "research",
}),
- ).toEqual({ kind: "answered", requestIds: [TASK_AUTHORIZATION_REQUEST_ID] });
+ ).toEqual({ kind: "answered", requestIds: [requestId] });
});
it("leaves answered input to the run, which must deliver before recording it", () => {
diff --git a/packages/eve/src/tasks/wire.ts b/packages/eve/src/tasks/wire.ts
index b26238b8a..933e0871a 100644
--- a/packages/eve/src/tasks/wire.ts
+++ b/packages/eve/src/tasks/wire.ts
@@ -1,5 +1,5 @@
import type { TaskCommand, TaskRunInboundPayload, TaskUsage } from "#tasks/types.js";
-import { TASK_AUTHORIZATION_REQUEST_ID, readTaskUsage } from "#tasks/types.js";
+import { readTaskUsage, taskAuthorizationRequestId } from "#tasks/types.js";
/**
* Translates one inbound hook payload into a lifecycle command.
@@ -16,7 +16,7 @@ import { TASK_AUTHORIZATION_REQUEST_ID, readTaskUsage } from "#tasks/types.js";
* - `authorization.required` also blocks the task (the child cannot
* proceed without the parent's user) under a reserved request id, and
* `authorization.completed` clears exactly that id. Authorization
- * payloads never enter the snapshot — only the fact that the child is
+ * payloads never enter the view — only the fact that the child is
* blocked does.
*
* `input-response` is deliberately absent: the run must forward the
@@ -36,7 +36,7 @@ export function translateTaskInboundPayload(
if (result === undefined) return undefined;
if (result.outcome !== undefined) {
// Usage retention: the settled outcome's `usageDelta` survives into
- // the terminal command so the snapshot keeps the child's spend.
+ // the terminal command so the view keeps the child's spend.
const usage = readTaskUsage(result.outcome.usageDelta);
switch (result.outcome.result.kind) {
case "succeeded":
@@ -64,15 +64,12 @@ export function translateTaskInboundPayload(
kind: "start-turn",
taskId: payload.taskId,
};
- case "authorization-event":
+ case "authorization-event": {
+ const requestId = taskAuthorizationRequestId(payload.event);
return payload.event.type === "authorization.required"
- ? {
- inputRequests: [
- { blockedOn: "authorization", requestId: TASK_AUTHORIZATION_REQUEST_ID },
- ],
- kind: "require-input",
- }
- : { kind: "answered", requestIds: [TASK_AUTHORIZATION_REQUEST_ID] };
+ ? { kind: "require-authorization", requestId }
+ : { kind: "answered", requestIds: [requestId] };
+ }
default:
return undefined;
}
diff --git a/packages/eve/test/runtime-agent-framework-tools.test.ts b/packages/eve/test/runtime-agent-framework-tools.test.ts
index d9ad5e544..c8007fa46 100644
--- a/packages/eve/test/runtime-agent-framework-tools.test.ts
+++ b/packages/eve/test/runtime-agent-framework-tools.test.ts
@@ -114,6 +114,6 @@ describe("runtime agent framework tools", () => {
{ kind: "subagent" },
]);
const runtimeAction = createNodeHarnessTools({ node: graph.root }).get("agent")?.runtimeAction;
- expect(runtimeAction?.subagentName).toBe("agent");
+ expect(runtimeAction).toMatchObject({ kind: "subagent-call", subagentName: "agent" });
});
});