The Open Framework for Building Agents
feat(eve): run subagents as background tools when tasks are enabled (#2323)
Rui99de09116c20
diff --git a/.changeset/subagent-background-tool-adoption.md b/.changeset/subagent-background-tool-adoption.mdnew file mode 100644index 000000000..77639e8fd--- /dev/null+++ b/.changeset/subagent-background-tool-adoption.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Run local and remote subagents through generic background `defineTool` execution when `experimental.tasks` is enabled, preserving durable task receipts, HITL, cancellation, and child stream events.diff --git a/docs/tools/overview.mdx b/docs/tools/overview.mdxindex a7fd4f612..21399831d 100644--- a/docs/tools/overview.mdx+++ b/docs/tools/overview.mdx@@ -65,9 +65,9 @@ The root agent must enable `experimental.tasks`; eve rejects background tools atThis contract currently supports framework-owned task executors, including local and remotesubagents when `experimental.tasks` is enabled. After delegating, an in-process executor reports-the terminal result with `task.send({ kind: "complete", data })` (or `"fail"` / `"cancel"`). Note-that `task.send` is not restart-safe — an in-memory callback dies with the process — so the-cross-process executor wire remains framework-owned.+the terminal result with `task.send({ kind: "complete", data })` (or `fail` / `cancel`). `send` is+not restart-safe — an in-memory callback dies with the process — so the cross-process executor+wire remains framework-owned and is not yet a stable authored-tool API.### The `ctx` parameterdiff --git a/e2e/fixtures/fixture-tasks/evals/shared.ts b/e2e/fixtures/fixture-tasks/evals/shared.tsindex a3fae096a..488cb89bb 100644--- a/e2e/fixtures/fixture-tasks/evals/shared.ts+++ b/e2e/fixtures/fixture-tasks/evals/shared.ts@@ -87,6 +87,15 @@ export function requireBackgroundTaskId(turn: EveEvalTurn): string {throw new Error("Turn completed without a background task receipt.");}+export function parseToolErrorOutput(output: unknown): unknown {+ if (typeof output !== "string") return output;+ try {+ return JSON.parse(output);+ } catch {+ return output;+ }+}+/** Returns the exact model-visible task view from a task-control result. */export function requireTaskView(output: unknown, taskId: string): Record<string, unknown> {if (output === null || typeof output !== "object") {diff --git a/e2e/fixtures/fixture-tasks/evals/task.agent.continue.rejected-agent-busy.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.agent.continue.rejected-agent-busy.eval.tsindex 37bbb1790..d9ea0583a 100644--- a/e2e/fixtures/fixture-tasks/evals/task.agent.continue.rejected-agent-busy.eval.ts+++ b/e2e/fixtures/fixture-tasks/evals/task.agent.continue.rejected-agent-busy.eval.ts@@ -1,6 +1,7 @@import { defineTaskEval } from "./task-transition.js";import {requireBackgroundTaskId,+ parseToolErrorOutput,sendAndFollowQueuedTurn,waitForCompletedTask,} from "./shared.js";@@ -44,13 +45,13 @@ export default defineTaskEval({const admittedTaskId = requireBackgroundTaskId(raced);raced.event("action.result", {count: 2,- data: { result: { kind: "subagent-result", subagentName: "busy-worker" } },+ data: { result: { kind: "tool-result", toolName: "busy-worker" } },});raced.calledSubagent("busy-worker", {count: 1,status: "completed",});- raced.calledSubagent("busy-worker", {+ raced.calledTool("busy-worker", {count: 1,output: (output) => isBusyRejection(output, admittedTaskId),status: "failed",@@ -62,7 +63,7 @@ export default defineTaskEval({race.session,{ allowFailedActions: true },);- later.turn.calledSubagent("busy-worker", {+ later.turn.calledTool("busy-worker", {count: 1,output: (output) => isBusyRejection(output, admittedTaskId),status: "failed",@@ -88,6 +89,7 @@ function agentIdFromTaskView(output: unknown, taskId: string): string {}function isBusyRejection(output: unknown, activeTaskId?: string): boolean {+ output = parseToolErrorOutput(output);if (output === null || typeof output !== "object") return false;const message = Reflect.get(output, "message");return (diff --git a/e2e/fixtures/fixture-tasks/evals/task.dispatch-batch.start.accepted-partial-failure.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.dispatch-batch.start.accepted-partial-failure.eval.tsindex ac1d5783d..2379082de 100644--- a/e2e/fixtures/fixture-tasks/evals/task.dispatch-batch.start.accepted-partial-failure.eval.ts+++ b/e2e/fixtures/fixture-tasks/evals/task.dispatch-batch.start.accepted-partial-failure.eval.ts@@ -1,7 +1,7 @@import { type EveEvalTurn } from "eve/evals";import { satisfies } from "eve/evals/expect";-import { requireTaskView, waitForCompletedTask } from "./shared.js";+import { parseToolErrorOutput, requireTaskView, waitForCompletedTask } from "./shared.js";import { defineTaskEval } from "./task-transition.js";const FIRST_CALL_ID = "task-d6-success-first";@@ -20,13 +20,20 @@ export default defineTaskEval({const started = await t.send("TASK-D6-PARTIAL-FANOUT-FAILURE");started.expectOk();started.messageIncludes("TASK-D6-PARTIAL-FANOUT-STARTED");- started.eventsSatisfy("dispatch results preserve success/failure/success order", (events) => {+ started.eventsSatisfy("dispatch results cover every sibling", (events) => {const callIds = events.flatMap((event) =>- event.type === "action.result" && event.data.result.kind === "subagent-result"+ event.type === "action.result" &&+ event.data.result.kind === "tool-result" &&+ (event.data.result.toolName === "busy-worker" ||+ event.data.result.toolName === "unstartable-worker")? [event.data.result.callId]: [],);- return callIds.join(",") === [FIRST_CALL_ID, FAILED_CALL_ID, THIRD_CALL_ID].join(",");+ return (+ callIds.length === 3 &&+ new Set(callIds).size === 3 &&+ [FIRST_CALL_ID, FAILED_CALL_ID, THIRD_CALL_ID].every((callId) => callIds.includes(callId))+ );});const receipts = backgroundReceipts(started);@@ -35,9 +42,9 @@ export default defineTaskEval({satisfies((values: readonly BackgroundReceipt[]) =>values.length === 2 &&- values[0]?.callId === FIRST_CALL_ID &&- values[1]?.callId === THIRD_CALL_ID &&- values[0].taskId !== values[1].taskId,+ values.some(({ callId }) => callId === FIRST_CALL_ID) &&+ values.some(({ callId }) => callId === THIRD_CALL_ID) &&+ new Set(values.map(({ taskId }) => taskId)).size === 2,"first and third entries return distinct working task receipts",),);@@ -49,18 +56,18 @@ export default defineTaskEval({const failed = events.filter((event) =>event.type === "action.result" &&- event.data.result.kind === "subagent-result" &&+ event.data.result.kind === "tool-result" &&event.data.result.callId === FAILED_CALL_ID,);const event = failed[0];if (event?.type !== "action.result") return false;const result = event.data.result;- if (result.kind !== "subagent-result") return false;- const output = result.output;+ if (result.kind !== "tool-result") return false;+ const output = parseToolErrorOutput(result.output);return (failed.length === 1 &&event.data.status === "failed" &&- result.origin === "dispatch" &&+ result.isError === true &&output !== null &&typeof output === "object" &&Reflect.get(output, "code") === "REMOTE_AGENT_START_FAILED" &&diff --git a/e2e/fixtures/fixture-tasks/evals/task.dispatch.start.rejected-unreachable.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.dispatch.start.rejected-unreachable.eval.tsindex ba9e43ecc..2582bf40d 100644--- a/e2e/fixtures/fixture-tasks/evals/task.dispatch.start.rejected-unreachable.eval.ts+++ b/e2e/fixtures/fixture-tasks/evals/task.dispatch.start.rejected-unreachable.eval.ts@@ -1,4 +1,5 @@import { defineTaskEval } from "./task-transition.js";+import { parseToolErrorOutput } from "./shared.js";const CALL_ID = "task-a3-unstartable-worker";@@ -14,11 +15,9 @@ export default defineTaskEval({const started = await t.send("TASK-A3-DISPATCH-START-FAILURE");started.expectOk();started.messageIncludes("TASK-A3-PARENT-SURVIVED");- started.calledSubagent("unstartable-worker", {- callId: CALL_ID,- childSessionId: undefined,+ started.calledTool("unstartable-worker", {count: 1,- output: { code: "REMOTE_AGENT_START_FAILED" },+ output: isStartFailureWithoutTaskId,status: "failed",});started.eventsSatisfy(@@ -26,7 +25,7 @@ export default defineTaskEval({(events) => {const failed = events.flatMap((event) =>event.type === "action.result" &&- event.data.result.kind === "subagent-result" &&+ event.data.result.kind === "tool-result" &&event.data.result.callId === CALL_ID? [event]: [],@@ -35,8 +34,8 @@ export default defineTaskEval({return (failed.length === 1 &&failed[0]?.data.status === "failed" &&- result?.kind === "subagent-result" &&- result.origin === "dispatch" &&+ result?.kind === "tool-result" &&+ result.isError === true &&isStartFailureWithoutTaskId(result.output) &&!events.some((event) =>@@ -52,6 +51,7 @@ export default defineTaskEval({});function isStartFailureWithoutTaskId(output: unknown): boolean {+ output = parseToolErrorOutput(output);return (output !== null &&typeof output === "object" &&diff --git a/packages/eve/src/context/dynamic-subagent-lifecycle.ts b/packages/eve/src/context/dynamic-subagent-lifecycle.tsindex 415630f77..30d6682e0 100644--- a/packages/eve/src/context/dynamic-subagent-lifecycle.ts+++ b/packages/eve/src/context/dynamic-subagent-lifecycle.ts@@ -6,10 +6,14 @@ import type { ContextReader } from "#context/key.js";import {SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicSubagentSelectionsKey,+ TasksEnabledKey,TurnDynamicSubagentSelectionsKey,type DurableDynamicSubagentSelection,} from "#context/keys.js";-import { createHarnessDelegationToolDefinition } from "#execution/delegation-tool.js";+import {+ createBackgroundSubagentHarnessDefinition,+ createHarnessDelegationToolDefinition,+} from "#execution/delegation-tool.js";import type { HarnessToolDefinition } from "#harness/execute-tool.js";import { createLogger } from "#internal/logging.js";import type { SessionStartedStreamEvent, UnstampedMessageStreamEvent } from "#protocol/message.js";@@ -182,7 +186,11 @@ export function buildDynamicSubagentTools(input: ContextReader): readonly Harnes);}names.add(selection.prepared.name);- tools.push(createHarnessDelegationToolDefinition(selection.prepared));+ tools.push(+ input.get(TasksEnabledKey) === true+ ? createBackgroundSubagentHarnessDefinition(selection.prepared)+ : createHarnessDelegationToolDefinition(selection.prepared),+ );}return tools;diff --git a/packages/eve/src/execution/delegation-tool.ts b/packages/eve/src/execution/delegation-tool.tsindex f593ff89e..5e68b7ed5 100644--- a/packages/eve/src/execution/delegation-tool.ts+++ b/packages/eve/src/execution/delegation-tool.ts@@ -1,4 +1,10 @@import type { HarnessToolDefinition } from "#harness/execute-tool.js";+import { createToolExecuteWithAuth } from "#execution/tool-auth.js";+import {+ defineSubagent,+ registerLocalSubagentExecutor,+} from "#runtime/framework-tools/subagent/local.js";+import { defineRemoteSubagent } from "#runtime/framework-tools/subagent/remote.js";import type { PreparedRuntimeDelegationTool } from "#runtime/sessions/turn.js";import {UNSPECIFIED_INPUT_SCHEMA,@@ -43,3 +49,36 @@ export function createHarnessDelegationToolDefinition(workflowCallable: true,};}++export function createBackgroundSubagentHarnessDefinition(+ tool: HarnessDelegationTool,+): HarnessToolDefinition {+ const definition =+ tool.kind === "remote"+ ? defineRemoteSubagent({+ description: tool.description ?? "",+ name: tool.name,+ nodeId: tool.nodeId,+ })+ : defineSubagent({+ description: tool.description ?? "",+ name: tool.name,+ nodeId: tool.nodeId,+ });+ const execute = createToolExecuteWithAuth({+ execute: definition.execute,+ execution: definition.execution,+ scope: tool.name,+ });+ if (tool.kind !== "remote") registerLocalSubagentExecutor(execute);+ return {+ description: definition.description,+ execute,+ execution: definition.execution,+ inputSchema: toInputSchema(definition.inputSchema) ?? UNSPECIFIED_INPUT_SCHEMA,+ name: tool.name,+ outputSchema: toOutputSchema(definition.outputSchema) ?? undefined,+ rootOnly: tool.rootOnly,+ workflowCallable: true,+ };+}diff --git a/packages/eve/src/execution/dispatch-runtime-actions-shared.ts b/packages/eve/src/execution/dispatch-runtime-actions-shared.tsindex 90aec89c2..0cdb3095d 100644--- a/packages/eve/src/execution/dispatch-runtime-actions-shared.ts+++ b/packages/eve/src/execution/dispatch-runtime-actions-shared.ts@@ -20,6 +20,7 @@ import {InitiatorAuthKey,SandboxKey,} from "#context/keys.js";+import { type AlsContext, ContextContainer } from "#context/container.js";import { withContextScope } from "#context/run-step.js";import {BundleKey,@@ -181,8 +182,10 @@ export async function prepareRuntimeActionDispatch(input: {const batch = getPendingRuntimeActionBatch(durableSession.state);if (batch === undefined || batch.actions.length === 0) return undefined;+ const ctx = await deserializeContext(input.serializedContext);return await prepareActionDispatch({batch,+ ctx,durableSession,serializedContext: input.serializedContext,taskControls: input.taskControls,@@ -191,6 +194,7 @@ export async function prepareRuntimeActionDispatch(input: {export async function prepareAgentActionDispatch(input: {readonly action: RuntimeActionRequest;+ readonly ctx: AlsContext;readonly event: {readonly sequence: number;readonly stepIndex: number;@@ -203,6 +207,7 @@ export async function prepareAgentActionDispatch(input: {const durableSession = await readDurableSession(input.sessionState);return await prepareActionDispatch({batch: { actions: [input.action], event: input.event, responseMessages: [] },+ ctx: copyDurableContext(input.ctx),durableSession,fanoutSize: input.localFanoutSize,serializedContext: input.serializedContext,@@ -210,8 +215,15 @@ export async function prepareAgentActionDispatch(input: {});}+function copyDurableContext(ctx: AlsContext): ContextContainer {+ const copy = new ContextContainer();+ for (const [key, value] of ctx.entries()) copy.set(key, value);+ return copy;+}+async function prepareActionDispatch(input: {readonly batch: NonNullable<ReturnType<typeof getPendingRuntimeActionBatch>>;+ readonly ctx: ContextContainer;readonly durableSession: Awaited<ReturnType<typeof readDurableSession>>;readonly fanoutSize?: number;readonly serializedContext: Record<string, unknown>;@@ -220,7 +232,7 @@ async function prepareActionDispatch(input: {const { batch, durableSession } = input;assertUniqueRuntimeActionCallIds(batch.actions);- const ctx = await deserializeContext(input.serializedContext);+ const ctx = input.ctx;const bundle = ctx.require(BundleKey);const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);let session = hydrateDurableSession({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.tsindex 9072747c1..aba14dc28 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@@ -7,6 +7,7 @@ import { RemoteAgentContinueRequestError } from "#execution/remote-agent-dispatcimport { 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 { prepareAgentActionDispatch } from "#execution/dispatch-runtime-actions-shared.js";import { dispatchTaskStep } from "#execution/tasks/parent/dispatch-task-step.js";import {resolvePendingRuntimeActions,@@ -183,6 +184,56 @@ describe("dispatchRuntimeActionsStep child starts", () => {parentTurnId: "turn-1",});+ it("plans an in-step agent call from the live context", async () => {+ const session = createBaseSession();+ const ctx = new ContextContainer();+ ctx.set(AuthKey, null);+ ctx.set(ChannelKey, ADAPTER);+ ctx.set(BundleKey, {+ compiledArtifactsSource: {},+ resolvedAgent: { config: { experimental: { tasks: true } } },+ subagentRegistry: {+ subagentsByNodeId: new Map([+ ["remote/research", { definition: REMOTE_REGISTRY_DEFINITION }],+ ]),+ },+ turnAgent: session.agent,+ } as never);+ mocks.readDurableSession.mockResolvedValue(session);+ mocks.deserializeContext.mockRejectedValue(+ new Error(+ "A development Workflow generation selector was resumed outside a generation-bound delivery.",+ ),+ );++ const prepared = await prepareAgentActionDispatch({+ action: {+ callId: "call-1",+ description: "Research",+ input: { message: "research this" },+ kind: "remote-agent-call",+ name: "research",+ nodeId: "remote/research",+ remoteAgentName: "research",+ },+ ctx,+ event: { sequence: 1, stepIndex: 2, turnId: "turn-1" },+ localFanoutSize: 0,+ serializedContext: {+ [BundleKey.name]: { source: { kind: "development" } },+ },+ sessionState: BASE_STATE,+ });++ expect(prepared.plan).toEqual([+ expect.objectContaining({+ kind: "start",+ target: expect.objectContaining({ kind: "remote" }),+ }),+ ]);+ expect(mocks.deserializeContext).not.toHaveBeenCalled();+ });+it("owns a local child before the start effect and confirms its running address", async () => {const session = createStartSession({ kind: "local" });installContext(session, {diff --git a/packages/eve/src/execution/node-step.test.ts b/packages/eve/src/execution/node-step.test.tsindex 056f90948..5cfb11595 100644--- a/packages/eve/src/execution/node-step.test.ts+++ b/packages/eve/src/execution/node-step.test.ts@@ -13,6 +13,7 @@ import { createEmptyHookRegistry } from "#runtime/hooks/registry.js";import type { RuntimeToolRegistry } from "#runtime/tools/registry.js";import { createRuntimeToolRegistry } from "#runtime/tools/registry.js";import { createExecutionNodeStep, createNodeHarnessTools } from "#execution/node-step.js";+import { countLocalSubagentCalls } from "#runtime/framework-tools/subagent/local.js";import { createSession } from "#execution/session.js";import { createStubSandboxRegistry } from "#internal/testing/stub-sandbox-registry.js";import { toInputSchema } from "#shared/tool-schema.js";@@ -302,6 +303,65 @@ describe("createNodeHarnessTools", () => {expect(tools.has("task_sleep")).toBe(false);});+ it("executes local and remote subagents as background tools only with experimental.tasks", () => {+ const delegationTools: StaticRuntimeTurnAgent["tools"] = [+ {+ description: "Delegate local research.",+ inputSchema: { type: "object" },+ kind: "subagent",+ logicalPath: "subagents/research",+ name: "research",+ nodeId: "subagents/research",+ sourceId: "subagents/research",+ },+ {+ description: "Delegate remote review.",+ inputSchema: { type: "object" },+ kind: "remote",+ logicalPath: "remote-agents/reviewer",+ name: "reviewer",+ nodeId: "remote-agents/reviewer",+ sourceId: "remote-agents/reviewer",+ },+ ];+ const createNode = (tasks: boolean) => {+ const node = createTestNode(createTestTurnAgent({ tools: delegationTools }));+ return {+ ...node,+ agent: {+ ...node.agent,+ config: {+ experimental: { tasks },+ model: { id: "test-model" },+ name: "test",+ },+ },+ };+ };++ const legacy = createNodeHarnessTools({ node: createNode(false) });+ expect(legacy.get("research")?.runtimeAction?.kind).toBe("subagent-call");+ expect(legacy.get("reviewer")?.runtimeAction?.kind).toBe("remote-agent-call");+ expect(legacy.get("research")?.execution).toBeUndefined();+ expect(legacy.get("reviewer")?.execution).toBeUndefined();++ const background = createNodeHarnessTools({ node: createNode(true) });+ for (const name of ["agent", "research", "reviewer"]) {+ expect(background.get(name)?.execution).toBe("background");+ expect(background.get(name)?.execute).toBeDefined();+ expect(background.get(name)?.runtimeAction).toBeUndefined();+ }+ expect(+ countLocalSubagentCalls(+ ["agent", "research", "reviewer"].map((name) => {+ const execute = background.get(name)?.execute;+ if (execute === undefined) throw new Error(`Missing background executor for ${name}.`);+ return { definition: { execute } };+ }),+ ),+ ).toBe(2);+ });+it("respects disableTool for individual task tools", () => {const node = createTestNode();const tools = createNodeHarnessTools({diff --git a/packages/eve/src/execution/node-step.ts b/packages/eve/src/execution/node-step.tsindex 537e61cb3..eb40d0cee 100644--- a/packages/eve/src/execution/node-step.ts+++ b/packages/eve/src/execution/node-step.ts@@ -2,7 +2,10 @@ import type { LanguageModel } from "ai";import type { Runtime, SessionCapabilities } from "#channel/types.js";import { dispatchDynamicModelEvent } from "#context/dynamic-model-lifecycle.js";-import { createHarnessDelegationToolDefinition } from "#execution/delegation-tool.js";+import {+ createBackgroundSubagentHarnessDefinition,+ createHarnessDelegationToolDefinition,+} from "#execution/delegation-tool.js";import type { HarnessToolDefinition } from "#harness/execute-tool.js";import { LOAD_SKILL_TOOL_NAME } from "#runtime/skills/fragment-context.js";import { createToolLoopHarness } from "#harness/tool-loop.js";@@ -190,18 +193,20 @@ function createRuntimeDynamicModelEventDispatcher(* Resolves unified {@link HarnessToolDefinition}s from the node's registries.** For authored tools: copies all lifecycle fields from the resolved definition.- * For subagent tools: surfaces runtime-owned subagent-call metadata and leaves- * execution to the runtime layer.+ * For subagent tools: selects the existing runtime-action definition or the+ * background `defineTool` definition from the node's `experimental.tasks` setting.* Tools without `execute` (provider-managed) get entries with schema but no execute.*/export function createNodeHarnessTools(input: {readonly node: ResolvedRuntimeAgentNode;}): HarnessToolMap {const tools = new Map<string, HarnessToolDefinition>();+ const tasksEnabled = input.node.agent.config?.experimental?.tasks === true;for (const tool of input.node.turnAgent.tools) {const definition = resolveHarnessToolDefinition({node: input.node,+ tasksEnabled,tool,});@@ -217,24 +222,25 @@ export function createNodeHarnessTools(input: {nodeId: input.node.nodeId,})) {+ const implicitAgent = {+ description: AGENT_TOOL_DESCRIPTION,+ inputSchema:+ tasksEnabled || input.node.agent.config?.experimental?.subagentPersistentSessions === true+ ? PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA+ : SUBAGENT_TOOL_INPUT_SCHEMA,+ kind: "subagent" as const,+ name: AGENT_TOOL_NAME,+ nodeId: input.node.nodeId,+ rootOnly: true,+ };tools.set(AGENT_TOOL_NAME,- createHarnessDelegationToolDefinition({- 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,- kind: "subagent",- name: AGENT_TOOL_NAME,- nodeId: input.node.nodeId,- rootOnly: true,- }),+ tasksEnabled+ ? createBackgroundSubagentHarnessDefinition(implicitAgent)+ : createHarnessDelegationToolDefinition(implicitAgent),);}- const tasksEnabled = input.node.agent.config?.experimental?.tasks === true;for (const definition of createTaskToolHarnessDefinitions()) {if (isTaskToolAvailable({@@ -253,10 +259,13 @@ export function createNodeHarnessTools(input: {function resolveHarnessToolDefinition(input: {readonly node: ResolvedRuntimeAgentNode;+ readonly tasksEnabled: boolean;readonly tool: PreparedRuntimeTool;}): HarnessToolDefinition | null {if (input.tool.kind === "subagent" || input.tool.kind === "remote") {- return createHarnessDelegationToolDefinition(input.tool);+ return input.tasksEnabled+ ? createBackgroundSubagentHarnessDefinition(input.tool)+ : createHarnessDelegationToolDefinition(input.tool);}const registeredTool = findRegisteredRuntimeTool(input.node.toolRegistry, input.tool.name);diff --git a/packages/eve/src/execution/tasks/parent/continuation-dispatch.ts b/packages/eve/src/execution/tasks/parent/continuation-dispatch.tsindex 0eae970ab..8904577b8 100644--- a/packages/eve/src/execution/tasks/parent/continuation-dispatch.ts+++ b/packages/eve/src/execution/tasks/parent/continuation-dispatch.ts@@ -55,13 +55,27 @@ export async function checkTaskContinuationAvailability(input: {);return active === undefined? undefined- : createAgentErrorResult({+ : createTaskContinuationBusyResult({action: input.action,- code: AGENT_BUSY,- message: `Agent "${input.agentId}" is busy with task "${active.view.taskId}" (${active.view.status}).`,+ agentId: input.agentId,+ status: active.view.status,+ taskId: active.view.taskId,});}+export function createTaskContinuationBusyResult(input: {+ readonly action: RuntimeAgentHandleAction;+ readonly agentId: string;+ readonly status: string;+ readonly taskId: string;+}): RuntimeSubagentDispatchFailure {+ return createAgentErrorResult({+ action: input.action,+ code: AGENT_BUSY,+ message: `Agent "${input.agentId}" is busy with task "${input.taskId}" (${input.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.diff --git a/packages/eve/src/execution/tasks/parent/dispatch.ts b/packages/eve/src/execution/tasks/parent/dispatch.tsindex be078b0e1..f39db9b99 100644--- a/packages/eve/src/execution/tasks/parent/dispatch.ts+++ b/packages/eve/src/execution/tasks/parent/dispatch.ts@@ -29,7 +29,13 @@ import {TASK_UPDATE_TOOL_NAME,} from "#runtime/framework-tools/tasks.js";import type { SessionTaskIndexEntry } from "#tasks/session-index.js";-import { isTerminalTaskStatus, readSubagentTaskMetadata, type TaskView } from "#tasks/types.js";+import {+ isTerminalTaskStatus,+ readSubagentExecutor,+ readSubagentTaskMetadata,+ type SubagentExecutorData,+ type TaskView,+} from "#tasks/types.js";const log = createLogger("execution.tasks.dispatch");@@ -141,9 +147,11 @@ export async function cancelOwnedTask(input: {}/**- * 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.+ * Best-effort cooperative abort of the cancelled task's child turn. The+ * child address comes from the task's durable executor binding when one+ * was written at delegation, falling back to the agent handle in session+ * state for tasks delegated before an executor binding existed. A task+ * with neither has nothing left to abort.*/async function propagateTaskCancel(input: {readonly bundle: CompiledBundle;@@ -152,22 +160,48 @@ async function propagateTaskCancel(input: {}): Promise<void> {const metadata = readSubagentTaskMetadata(input.view);if (metadata === undefined) return;- const handle = findTaskAgentAddress(input.session, metadata.agentId);- if (handle === undefined) return;- const childSessionId = handle.address.sessionId;- const childTurnId = input.view.executor?.childTurnId;+ const executor =+ readSubagentExecutor(input.view.executor) ??+ findTaskAgentAddress(input.session, metadata.agentId);+ if (executor === undefined) return;if (input.view.executor?.childSessionId !== undefined &&- input.view.executor.childSessionId !== childSessionId+ input.view.executor.childSessionId !== executor.address.sessionId) {return;}+ await propagateSubagentExecutorCancel({+ bundle: input.bundle,+ childTurnId: input.view.executor?.childTurnId,+ executor,+ taskId: input.view.taskId,+ });+}++/**+ * Sends the cooperative abort to the child identified by a subagent+ * executor binding. Failures are logged, never thrown: the task is already+ * terminal when this runs, so the worst outcome is a child that runs to+ * completion and has its callback refused.+ */+export async function propagateSubagentExecutorCancel(input: {+ readonly bundle: CompiledBundle | undefined;+ readonly childTurnId?: string;+ readonly executor: SubagentExecutorData;+ readonly taskId: string;+}): Promise<void> {+ const { address, identity } = input.executor;+ const childSessionId = address.sessionId;+ const childTurnId = input.childTurnId;try {- if (handle.address.kind === "agent/remote") {+ if (address.kind === "agent/remote") {+ if (input.bundle === undefined) {+ throw new Error("No compiled bundle is available to resolve the remote agent.");+ }const resolved = resolveRemoteAgentForAction({- nodeId: handle.identity.nodeId,- remoteAgentName: handle.identity.name,+ nodeId: identity.nodeId,+ remoteAgentName: identity.name,registry: input.bundle.subagentRegistry.subagentsByNodeId,});const cancelInput: {@@ -176,17 +210,17 @@ async function propagateTaskCancel(input: {readonly taskId: string;turnId?: string;} = {- remote: { ...resolved, url: handle.address.url },+ remote: { ...resolved, url: address.url },sessionId: childSessionId,- taskId: input.view.taskId,+ taskId: input.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 },+ remote: { ...resolved, url: address.url },sessionId: childSessionId,- taskId: input.view.taskId,+ taskId: input.taskId,});}return;@@ -197,20 +231,20 @@ async function propagateTaskCancel(input: {turnId?: string;} = {sessionId: childSessionId,- taskId: input.view.taskId,+ taskId: input.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,+ taskId: input.taskId,});}} catch (error) {logError(log, "task cancel propagation failed; the child may run to completion", error, {childSessionId,- taskId: input.view.taskId,+ taskId: input.taskId,});}}diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts b/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.tsnew file mode 100644index 000000000..f3518605c--- /dev/null+++ b/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts@@ -0,0 +1,314 @@+import { generateText } from "ai";+import { MockLanguageModelV4 } from "ai/test";+import { afterEach, describe, expect, it, vi } from "vitest";++import { ContextContainer } from "#context/container.js";+import {+ AuthKey,+ ContinuationTokenKey,+ HandleEventKey,+ InitiatorAuthKey,+ SessionIdKey,+} from "#context/keys.js";+import { runStep } from "#context/run-step.js";+import { createBackgroundSubagentHarnessDefinition } from "#execution/delegation-tool.js";+import { acknowledgeDelegatedTasksStep } from "#execution/tasks/parent/delegate.js";+import { readLatestTaskView } from "#execution/tasks/parent/run-parent.js";+import { backgroundToolExecutionProvider } from "#execution/tasks/parent/tool-execution.js";+import { CallbackBaseUrlKey } from "#harness/authorization.js";+import { setHarnessEmissionState } from "#harness/emission.js";+import { getAgentHandleStore } from "#harness/handles/store.js";+import { buildToolSet } from "#harness/tools.js";+import type { HarnessSession } from "#harness/types.js";+import { createTestRuntime } from "#internal/testing/app-harness.js";+import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";+import { getRun } from "#internal/workflow/runtime.js";+import type {+ SandboxBackend,+ SandboxBackendCreateInput,+} from "#public/definitions/sandbox-backend.js";+import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";+import { ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";+import { ROOT_RUNTIME_AGENT_NODE_ID } from "#runtime/graph.js";+import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";+import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";+import { readSubagentTaskMetadata } from "#tasks/types.js";++const usage = {+ inputTokens: { cacheRead: undefined, cacheWrite: undefined, noCache: 1, total: 1 },+ outputTokens: { reasoning: undefined, text: 1, total: 1 },+};++describe("background subagent tool execution", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("runs concurrent local and remote defineTool calls as independent durable tasks", async () => {+ const runtime = createTestRuntime({ agent: { name: "background-subagent" } });++ await runtime.run(async () => {+ const remoteNode = {+ description: "Remote reviewer",+ entryPath: "/virtual/eve-memory-app/agent/subagents/reviewer.ts",+ logicalPath: "subagents/reviewer.ts",+ name: "reviewer",+ nodeId: "remote/reviewer",+ path: "/eve/v1/session",+ rootPath: "/virtual/eve-memory-app/agent",+ sourceId: "subagents/reviewer.ts",+ sourceKind: "module",+ url: "https://remote.example.com",+ } as const;+ runtime.session.compiledArtifacts = {+ manifest: { ...runtime.manifest, remoteAgents: [remoteNode] },+ moduleMap: {+ nodes: {+ ...runtime.moduleMap.nodes,+ [ROOT_COMPILED_AGENT_NODE_ID]: {+ modules: {+ ...runtime.moduleMap.nodes[ROOT_COMPILED_AGENT_NODE_ID]?.modules,+ [remoteNode.sourceId]: { default: { url: remoteNode.url } },+ },+ },+ },+ },+ };+ const bundle = await getCompiledRuntimeAgentBundle({+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),+ });+ const sandbox = mockSandbox({ id: "background-subagent-sandbox" });+ const backend: SandboxBackend = {+ create: async (input: SandboxBackendCreateInput) => ({+ captureState: async () => ({+ backendName: "test",+ metadata: {},+ sessionKey: input.sessionKey,+ }),+ session: sandbox.session,+ shutdown: async () => {},+ stop: async () => {},+ useSessionFn: async () => sandbox.session,+ }),+ name: "test",+ prewarm: async () => ({ reused: false }),+ };+ (+ bundle.graph.root.sandboxRegistry.sandbox.definition as {+ backend: SandboxBackend;+ }+ ).backend = backend;+ const fetchMock = vi+ .fn()+ .mockResolvedValue(+ Response.json(+ { ok: true, sessionId: "remote-child", status: "accepted" },+ { headers: { "x-eve-session-id": "remote-child" }, status: 202 },+ ),+ );+ vi.stubGlobal("fetch", fetchMock);+ const ctx = new ContextContainer();+ ctx.set(AuthKey, null);+ ctx.set(BundleKey, bundle);+ ctx.set(CallbackBaseUrlKey, "https://caller.example.com");+ ctx.set(ChannelKey, { kind: "http", state: {} });+ ctx.set(ContinuationTokenKey, "http:background-subagent");+ ctx.set(InitiatorAuthKey, null);+ ctx.set(SessionIdKey, "parent-background-subagent");++ const session: HarnessSession = setHarnessEmissionState(+ {+ agent: { modelReference: { id: "openai/gpt-5.4" }, system: "", tools: [] },+ compaction: { recentWindowSize: 10, threshold: 100_000 },+ continuationToken: "http:background-subagent",+ history: [],+ sessionId: "parent-background-subagent",+ },+ { sequence: 1, sessionStarted: true, stepIndex: 0, turnId: "turn-background" },+ );+ const localTool = createBackgroundSubagentHarnessDefinition({+ description: "General-purpose agent",+ kind: "subagent",+ name: "agent",+ nodeId: ROOT_RUNTIME_AGENT_NODE_ID,+ });+ const remoteTool = createBackgroundSubagentHarnessDefinition({+ description: remoteNode.description,+ kind: "remote",+ name: remoteNode.name,+ nodeId: remoteNode.nodeId,+ });+ const model = new MockLanguageModelV4({+ doGenerate: {+ content: [+ {+ input: JSON.stringify({ message: "Reply with exactly `background-child-a`." }),+ toolCallId: "call-background-child-a",+ toolName: "agent",+ type: "tool-call",+ },+ {+ input: JSON.stringify({ message: "Reply with exactly `background-child-b`." }),+ toolCallId: "call-background-child-b",+ toolName: "agent",+ type: "tool-call",+ },+ {+ input: JSON.stringify({ message: "Review the result." }),+ toolCallId: "call-background-remote",+ toolName: "reviewer",+ type: "tool-call",+ },+ ],+ finishReason: { raw: undefined, unified: "tool-calls" },+ usage,+ warnings: [],+ },+ });++ let generated: Awaited<ReturnType<typeof generateText>> | undefined;+ const calledEvents: unknown[] = [];+ const result = await runStep(+ ctx,+ session,+ async (current) => {+ ctx.setVirtualContext(HandleEventKey, async (event) => {+ calledEvents.push(event);+ });+ generated = await generateText({+ model,+ prompt: "Delegate the work.",+ tools: buildToolSet({+ tools: new Map([+ [localTool.name, localTool],+ [remoteTool.name, remoteTool],+ ]),+ }),+ });+ return { next: null, session: current };+ },+ [backgroundToolExecutionProvider],+ );++ const pendingTasks = result.backgroundTasks ?? [];+ const handles = getAgentHandleStore(result.session.state)?.handles ?? [];+ if (pendingTasks.length !== 3) throw new Error("Three durable tasks were not committed.");+ if (handles.some((handle) => handle.phase !== "addressed") || handles.length !== 3) {+ throw new Error("Three child addresses were not committed.");+ }++ try {+ expect(generated?.toolResults).toHaveLength(3);+ expect(generated?.toolResults.map((toolResult) => toolResult.output)).toEqual(+ expect.arrayContaining(+ pendingTasks.map((task) =>+ expect.objectContaining({ status: "working", taskId: task.taskId }),+ ),+ ),+ );+ expect(new Set(handles.map((handle) => handle.identity.id)).size).toBe(3);+ expect(calledEvents).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ data: expect.objectContaining({ name: "agent" }),+ type: "subagent.called",+ }),+ expect.objectContaining({+ data: expect.objectContaining({+ childSessionId: "remote-child",+ name: "reviewer",+ remote: {+ resolverId: remoteNode.nodeId,+ url: remoteNode.url,+ },+ }),+ type: "subagent.called",+ }),+ ...pendingTasks.map((task) =>+ expect.objectContaining({+ data: expect.objectContaining({+ backgroundTask: { status: "working", taskId: task.taskId },+ }),+ type: "subagent.completed",+ }),+ ),+ ]),+ );+ expect(calledEvents).toHaveLength(6);+ expect(handles).toContainEqual(+ expect.objectContaining({+ address: expect.objectContaining({ kind: "agent/remote", sessionId: "remote-child" }),+ }),+ );+ const remoteReceipt = generated?.toolResults.find(+ (toolResult) => toolResult.toolName === "reviewer",+ )?.output;+ const remoteTaskId =+ typeof remoteReceipt === "object" &&+ remoteReceipt !== null &&+ "taskId" in remoteReceipt &&+ typeof remoteReceipt.taskId === "string"+ ? remoteReceipt.taskId+ : undefined;+ const remoteTaskIndex = pendingTasks.findIndex((task) => task.taskId === remoteTaskId);+ expect(remoteTaskIndex).toBeGreaterThanOrEqual(0);++ await acknowledgeDelegatedTasksStep({ tasks: pendingTasks });+ const localTasks = pendingTasks.filter((_task, index) => index !== remoteTaskIndex);+ await Promise.all(localTasks.map((task) => getRun(task.taskRunId).returnValue));+ const views = await Promise.all(+ pendingTasks.map((task) => readLatestTaskView({ taskRunId: task.taskRunId })),+ );+ expect(views).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ lastOutput: {+ data: expect.stringContaining("background-child-a"),+ type: "result",+ },+ status: "completed",+ }),+ expect.objectContaining({+ lastOutput: {+ data: expect.stringContaining("background-child-b"),+ type: "result",+ },+ status: "completed",+ }),+ expect.objectContaining({+ status: "working",+ }),+ ]),+ );+ const remoteTask = pendingTasks[remoteTaskIndex];+ const remoteView = views[remoteTaskIndex];+ expect(remoteTask).toBeDefined();+ expect(+ remoteView === undefined ? undefined : readSubagentTaskMetadata(remoteView),+ ).toMatchObject({ mode: "remote", name: "reviewer" });+ expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string)).toMatchObject({+ callback: { token: remoteTask?.taskInboxToken },+ });+ } finally {+ await Promise.all(+ handles.flatMap((handle) =>+ handle.phase === "addressed"+ ? [+ getRun(handle.address.sessionId)+ .cancel()+ .catch(() => {}),+ ]+ : [],+ ),+ );+ await Promise.all(+ pendingTasks.map((task) =>+ getRun(task.taskRunId)+ .cancel()+ .catch(() => {}),+ ),+ );+ }+ });+ }, 60_000);+});diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.test.ts b/packages/eve/src/execution/tasks/parent/tool-execution.test.tsindex 1eecc8f54..cbee8c551 100644--- a/packages/eve/src/execution/tasks/parent/tool-execution.test.ts+++ b/packages/eve/src/execution/tasks/parent/tool-execution.test.ts@@ -13,12 +13,19 @@ import { isAuthorizationPendingModelOutput, requestAuthorization } from "#harnesimport type { HarnessToolDefinition } from "#harness/execute-tool.js";import { buildToolSet } from "#harness/tools.js";import type { HarnessSession } from "#harness/types.js";+import {+ getAgentHandleStore,+ type AgentAddress,+ type AgentIdentity,+} from "#harness/handles/store.js";import { defineTool, type TaskExec, type ToolContext } from "#public/definitions/tool.js";import { toInputSchema } from "#shared/tool-schema.js";import { getSessionTaskIndex } from "#tasks/session-index.js";+import { createSubagentExecutorBinding } from "#tasks/types.js";const mocks = vi.hoisted(() => ({beginBackgroundTask: vi.fn(),+ propagateSubagentExecutorCancel: vi.fn(),rejectDelegatedDispatch: vi.fn(),sendTaskCommand: vi.fn(),}));@@ -28,6 +35,10 @@ vi.mock("#execution/tasks/parent/delegate.js", async (importOriginal) => ({beginBackgroundTask: mocks.beginBackgroundTask,rejectDelegatedDispatch: mocks.rejectDelegatedDispatch,}));+vi.mock("#execution/tasks/parent/dispatch.js", async (importOriginal) => ({+ ...(await importOriginal<typeof import("#execution/tasks/parent/dispatch.js")>()),+ propagateSubagentExecutorCancel: mocks.propagateSubagentExecutorCancel,+}));vi.mock("#execution/tasks/parent/run-parent.js", async (importOriginal) => ({...(await importOriginal<typeof import("#execution/tasks/parent/run-parent.js")>()),sendTaskCommand: mocks.sendTaskCommand,@@ -38,9 +49,79 @@ const usage = {outputTokens: { reasoning: undefined, text: 1, total: 1 },};+const childIdentity: AgentIdentity = {+ id: "ag_research:operation1",+ name: "research",+ nodeId: "node_research",+};+const childAddress: AgentAddress = {+ continuationToken: "continuation_child",+ kind: "agent/local",+ sessionId: "session_child",+};++function createParentSession(): HarnessSession {+ return setHarnessEmissionState(+ {+ agent: { modelReference: { id: "mock" }, system: "", tools: [] },+ compaction: { recentWindowSize: 10, threshold: 100_000 },+ continuationToken: "parent-token",+ history: [],+ sessionId: "parent-session",+ },+ { sequence: 1, sessionStarted: true, stepIndex: 0, turnId: "turn-1" },+ );+}++function createSubagentTool(): HarnessToolDefinition {+ const definition = defineTool({+ description: "Spawn a research subagent.",+ execution: "background",+ inputSchema: z.strictObject({}),+ execute(_input: Record<string, never>, _ctx: ToolContext, background: TaskExec) {+ return background.delegated({+ executor: createSubagentExecutorBinding({+ address: childAddress,+ identity: childIdentity,+ }),+ receipt: { agentId: childIdentity.id },+ });+ },+ });+ return {+ description: definition.description,+ execute: createToolExecuteWithAuth({+ execute: definition.execute,+ execution: definition.execution,+ scope: "research",+ }),+ execution: definition.execution,+ inputSchema: toInputSchema(definition.inputSchema),+ name: "research",+ };+}++const subagentToolCallModel = () =>+ new MockLanguageModelV4({+ doGenerate: {+ content: [+ {+ input: "{}",+ toolCallId: "call-research",+ toolName: "research",+ type: "tool-call",+ },+ ],+ finishReason: { raw: undefined, unified: "tool-calls" },+ usage,+ warnings: [],+ },+ });+describe("background tool execution", () => {beforeEach(() => {mocks.beginBackgroundTask.mockReset();+ mocks.propagateSubagentExecutorCancel.mockReset();mocks.rejectDelegatedDispatch.mockReset();mocks.sendTaskCommand.mockReset();});@@ -285,7 +366,7 @@ describe("background tool execution", () => {);});- it("compensates a delegated task when the parent step fails", async () => {+ it("rejects a delegated generic executor without cancel propagation when the parent step fails", async () => {const task = {createdByStepIndex: 0,createdByTurnId: "turn-1",@@ -333,16 +414,7 @@ describe("background tool execution", () => {warnings: [],},});- const session: HarnessSession = setHarnessEmissionState(- {- agent: { modelReference: { id: "mock" }, system: "", tools: [] },- compaction: { recentWindowSize: 10, threshold: 100_000 },- continuationToken: "parent-token",- history: [],- sessionId: "parent-session",- },- { sequence: 1, sessionStarted: true, stepIndex: 0, turnId: "turn-1" },- );+ const session = createParentSession();const ctx = new ContextContainer();ctx.set(AuthKey, null);ctx.set(SessionIdKey, session.sessionId);@@ -370,6 +442,110 @@ describe("background tool execution", () => {executor: { data: { exportId: "customers" }, kind: "export" },},});+ expect(mocks.propagateSubagentExecutorCancel).not.toHaveBeenCalled();+ expect(getSessionTaskIndex(session.state)).toEqual([]);+ });++ it("commits the subagent executor's addressed handle with the step", async () => {+ const task = {+ createdByStepIndex: 0,+ createdByTurnId: "turn-1",+ metadata: { kind: "tool", name: "research" },+ taskId: "task-research",+ taskInboxToken: "inbox-research",+ taskRunId: "run-research",+ } as const;+ mocks.beginBackgroundTask.mockResolvedValue(task);+ mocks.sendTaskCommand.mockResolvedValue("delivered");+ const tool = createSubagentTool();+ const session = createParentSession();+ const ctx = new ContextContainer();+ ctx.set(AuthKey, null);+ ctx.set(SessionIdKey, session.sessionId);++ const result = await runStep(+ ctx,+ session,+ async (current) => {+ await generateText({+ model: subagentToolCallModel(),+ prompt: "Spawn the researcher.",+ tools: buildToolSet({ tools: new Map([[tool.name, tool]]) }),+ });+ return { next: null, session: current };+ },+ [backgroundToolExecutionProvider],+ );++ expect(getAgentHandleStore(result.session.state)?.handles).toEqual([+ { address: childAddress, identity: childIdentity, phase: "addressed" },+ ]);+ expect(getSessionTaskIndex(result.session.state)).toEqual([+ expect.objectContaining({+ executor: createSubagentExecutorBinding({+ address: childAddress,+ identity: childIdentity,+ }),+ taskId: task.taskId,+ }),+ ]);+ expect(mocks.rejectDelegatedDispatch).not.toHaveBeenCalled();+ expect(mocks.propagateSubagentExecutorCancel).not.toHaveBeenCalled();+ });++ it("rejects the task first and then cancels the dispatched subagent child when the parent step fails", async () => {+ const task = {+ createdByStepIndex: 0,+ createdByTurnId: "turn-1",+ metadata: { kind: "tool", name: "research" },+ taskId: "task-research",+ taskInboxToken: "inbox-research",+ taskRunId: "run-research",+ } as const;+ mocks.beginBackgroundTask.mockResolvedValue(task);+ mocks.sendTaskCommand.mockResolvedValue("delivered");+ mocks.rejectDelegatedDispatch.mockResolvedValue(undefined);+ mocks.propagateSubagentExecutorCancel.mockResolvedValue(undefined);+ const tool = createSubagentTool();+ const session = createParentSession();+ const ctx = new ContextContainer();+ ctx.set(AuthKey, null);+ ctx.set(SessionIdKey, session.sessionId);++ await expect(+ runStep(+ ctx,+ session,+ async () => {+ await generateText({+ model: subagentToolCallModel(),+ prompt: "Spawn the researcher.",+ tools: buildToolSet({ tools: new Map([[tool.name, tool]]) }),+ });+ throw new Error("parent step failed");+ },+ [backgroundToolExecutionProvider],+ ),+ ).rejects.toThrow("parent step failed");++ const executor = createSubagentExecutorBinding({+ address: childAddress,+ identity: childIdentity,+ });+ expect(mocks.rejectDelegatedDispatch).toHaveBeenCalledWith({+ error: { code: "PARENT_STEP_FAILED", message: "parent step failed" },+ task: { ...task, executor },+ });+ expect(mocks.propagateSubagentExecutorCancel).toHaveBeenCalledWith({+ bundle: undefined,+ executor: { address: childAddress, identity: childIdentity },+ taskId: task.taskId,+ });+ // The task must be terminal before the child learns anything: a late+ // child result then bounces instead of reviving the rejected task.+ expect(mocks.rejectDelegatedDispatch.mock.invocationCallOrder[0]).toBeLessThan(+ mocks.propagateSubagentExecutorCancel.mock.invocationCallOrder[0] ?? 0,+ );expect(getSessionTaskIndex(session.state)).toEqual([]);});diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.ts b/packages/eve/src/execution/tasks/parent/tool-execution.tsindex 994bc1858..f6f2c2893 100644--- a/packages/eve/src/execution/tasks/parent/tool-execution.ts+++ b/packages/eve/src/execution/tasks/parent/tool-execution.ts@@ -19,13 +19,17 @@ import { isAsyncIterable } from "#shared/async-iterable.js";import { parseJsonValue } from "#shared/json.js";import type { ToolExecuteOptions } from "#shared/tool-definition.js";import { createTaskDelegated, isTaskDelegated, type TaskExec } from "#shared/tool-task.js";+import { recordTaskAgentAddress } from "#harness/handles/transitions.js";+import { BundleKey, type CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";import { recordSessionTask } from "#tasks/session-index.js";+import { readSubagentExecutor } from "#tasks/types.js";import { createWorkflowCallbackUrl } from "#execution/workflow-callback-url.js";import {beginBackgroundTask,rejectDelegatedDispatch,type BackgroundTask,} from "#execution/tasks/parent/delegate.js";+import { propagateSubagentExecutorCancel } from "#execution/tasks/parent/dispatch.js";import { sendTaskCommand } from "#execution/tasks/parent/run-parent.js";interface BackgroundToolExecutionRecord {@@ -62,7 +66,8 @@ export function runBackgroundStep(** - `commit` — step succeeded. Compensates executions that never settled* (the tool neither delegated nor completed its task), then records the- * spawned task handles onto the session being persisted.+ * task entries and executor-owned session writes onto the session being+ * persisted.* - `rollback` — step failed. Compensates incomplete executions, and settled* ones too — unless the cause is turn cancellation: those tasks are already* running, so they are retained for {@link readRetainedBackgroundToolResult}@@ -73,8 +78,8 @@ export function runBackgroundStep(*/export const backgroundToolExecutionProvider: FrameworkContextProvider<BackgroundToolExecutor> = {key: BackgroundToolExecutorKey,- create(_ctx, session) {- return { value: new BackgroundToolExecutionScope(session) };+ create(ctx, session) {+ return { value: new BackgroundToolExecutionScope(session, ctx.get(BundleKey)) };},async commit(executor, session) {return await requireExecutionScope(executor).commit(session);@@ -88,9 +93,9 @@ export const backgroundToolExecutionProvider: FrameworkContextProvider<Backgroun};/**- * Returns what a successful commit would have produced (session with spawned- * task handles recorded) when turn cancellation raced a- * successfully delegated task. `rollback` deliberately does not compensate+ * Returns what a successful commit would have produced (session with task+ * entries and executor session writes applied) when turn cancellation raced+ * a successfully delegated task. `rollback` deliberately does not compensate* settled records on cancellation — that would kill already-running tasks —* so the cancellation epilogue reads this instead to keep those tasks tracked* in durable state rather than orphaned. `undefined` when nothing was retained.@@ -103,13 +108,15 @@ export function readRetainedBackgroundToolResult(}class BackgroundToolExecutionScope implements BackgroundToolExecutor {+ private readonly bundle: CompiledBundle | undefined;private readonly executions = new Map<string, Promise<unknown>>();private readonly records: BackgroundToolExecutionRecord[] = [];private retained = false;private readonly initialSession: HarnessSession;- constructor(initialSession: HarnessSession) {+ constructor(initialSession: HarnessSession, bundle: CompiledBundle | undefined) {+ this.bundle = bundle;this.initialSession = initialSession;}@@ -137,6 +144,7 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {await compensateBackgroundToolExecution(incomplete,new Error("Background tool execution did not delegate or complete its task."),+ this.bundle,);}return this.apply(session);@@ -151,7 +159,7 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {const settled = this.records.filter((record) => record.settled);const incomplete = this.records.filter((record) => !record.settled);if (incomplete.length > 0) {- await compensateBackgroundToolExecution(incomplete, cause);+ await compensateBackgroundToolExecution(incomplete, cause, this.bundle);}if (settled.length === 0) return;// Cancellation must not compensate settled records: their tasks are@@ -160,7 +168,7 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {this.retained = true;return;}- await compensateBackgroundToolExecution(settled, cause);+ await compensateBackgroundToolExecution(settled, cause, this.bundle);}retainedResult(): BackgroundToolStepResult | undefined {@@ -171,6 +179,12 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {let next = session;for (const record of this.records) {if (!record.settled || record.task === undefined) continue;+ // Framework-owned executor commits, matched by executor kind. The+ // subagent binding is the durable copy of the child's addressed+ // handle; committing the task also commits that address into the+ // parent's handle store.+ const subagent = readSubagentExecutor(record.task.executor);+ if (subagent !== undefined) next = recordTaskAgentAddress(next, subagent);next = recordSessionTask(next, record.task);}return next;@@ -274,6 +288,7 @@ async function deliverTaskCommand(async function compensateBackgroundToolExecution(records: readonly BackgroundToolExecutionRecord[],cause: unknown,+ bundle: CompiledBundle | undefined,): Promise<void> {const failures: unknown[] = [];for (const record of records.toReversed()) {@@ -289,11 +304,22 @@ async function compensateBackgroundToolExecution(} catch (error) {failures.push(error);}+ // Reject first so the task is terminal and a late child result cannot+ // revive it, then best-effort abort the already-dispatched child using+ // the address carried on its durable executor binding.+ const subagent = readSubagentExecutor(record.task.executor);+ if (subagent !== undefined) {+ await propagateSubagentExecutorCancel({+ bundle,+ executor: subagent,+ taskId: record.task.taskId,+ });+ }}if (failures.length > 0) {throw new AggregateError([cause, ...failures],- "Background tool execution failed and its tasks could not all be compensated.",+ "Background tool execution failed and its tasks could not all be rejected.",{ cause },);}diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.tsindex 6756c70d3..83a929ab8 100644--- a/packages/eve/src/execution/workflow-steps.test.ts+++ b/packages/eve/src/execution/workflow-steps.test.ts@@ -564,10 +564,12 @@ describe("recordTaskInputRequestStep", () => {createdByTurnId: "turn-parent",executor: {data: {- agentId: "agent-1",- childSessionId: "child-session",- mode: "local",- name: "research",+ address: {+ continuationToken: "child-token",+ kind: "agent/local",+ sessionId: "child-session",+ },+ identity: { id: "agent-1", name: "research", nodeId: "node-1" },},kind: "subagent",},@@ -586,10 +588,12 @@ describe("recordTaskInputRequestStep", () => {executor: {binding: {data: {- agentId: "agent-1",- childSessionId: "child-session",- mode: "local",- name: "research",+ address: {+ continuationToken: "child-token",+ kind: "agent/local",+ sessionId: "child-session",+ },+ identity: { id: "agent-1", name: "research", nodeId: "node-1" },},kind: "subagent",},diff --git a/packages/eve/src/harness/handles/transitions.test.ts b/packages/eve/src/harness/handles/transitions.test.tsindex 604948846..06b2fd4ad 100644--- a/packages/eve/src/harness/handles/transitions.test.ts+++ b/packages/eve/src/harness/handles/transitions.test.ts@@ -18,6 +18,7 @@ import {prepareAgentContinuation,prepareAgentStart,rebaseAgentHandles,+ recordTaskAgentAddress,rejectAgentEffect,removeTaskAgentAddress,settleAgentTurn,@@ -167,6 +168,28 @@ describe("task agent addresses", () => {});});+describe("recordTaskAgentAddress", () => {+ it("appends an addressed handle from a delegated task's executor binding", () => {+ const recorded = recordTaskAgentAddress(createSession(), { address, identity });+ expect(handlesOf(recorded)).toEqual([{ address, identity, phase: "addressed" }]);+ });++ it("is a replay no-op when the identical handle is already stored", () => {+ const recorded = recordTaskAgentAddress(createSession(), { address, identity });+ expect(recordTaskAgentAddress(recorded, { address, identity })).toBe(recorded);+ });++ it("throws when the id already exists with different content", () => {+ const recorded = recordTaskAgentAddress(createSession(), { address, identity });+ expect(() =>+ recordTaskAgentAddress(recorded, {+ address: { ...address, continuationToken: "continuation_divergent" },+ identity,+ }),+ ).toThrow(identity.id);+ });+});+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.tsindex f07cf4fe3..2e60e883a 100644--- a/packages/eve/src/harness/handles/transitions.ts+++ b/packages/eve/src/harness/handles/transitions.ts@@ -201,6 +201,36 @@ export function confirmTaskAgentAddress();}+/**+ * Records a task-mode child's persistent address from its durable executor+ * binding, applied when the parent step that delegated the task commits.+ *+ * Replay-idempotent: a record identical to the stored handle is a no-op+ * (a resumed child, or a replayed commit). A different record under the+ * same id throws — ids derive from unique operations, so a collision+ * means corrupted derivation, not a replay.+ */+export function recordTaskAgentAddress(+ session: HarnessSession,+ input: {+ readonly address: AgentAddress;+ readonly identity: AgentIdentity;+ },+): HarnessSession {+ const handles = getAgentHandleStore(session.state)?.handles ?? [];+ const record: AgentHandle = {+ address: input.address,+ identity: input.identity,+ phase: "addressed",+ };+ const existing = handles.find((handle) => handle.identity.id === input.identity.id);+ if (existing !== undefined) {+ if (jsonValuesEqual(existing, record)) return session;+ throw new Error(`Agent handle "${input.identity.id}" already exists with different content.`);+ }+ return writeHandles(session, [...handles, record]);+}+/** Removes a task-mode address after permanent delivery failure. */export function removeTaskAgentAddress(session: HarnessSession, agentId: string): HarnessSession {return { ...session, state: removeTaskAgentAddressFromState(session.state, agentId) };diff --git a/packages/eve/src/runtime/framework-tools/subagent/local.ts b/packages/eve/src/runtime/framework-tools/subagent/local.tsnew file mode 100644index 000000000..607bb1613--- /dev/null+++ b/packages/eve/src/runtime/framework-tools/subagent/local.ts@@ -0,0 +1,355 @@+import { type AlsContext, loadContext } from "#context/container.js";+import { HandleEventKey } from "#context/keys.js";+import { serializeContext } from "#context/serialize.js";+import {+ dispatchToTaskAgentAddress,+ type DispatchOutcome,+ type RuntimeSession,+} from "#execution/agent-handle-dispatch.js";+import { createAgentContinuationBundle } from "#execution/agent-continuation-bundle.js";+import {+ prepareAgentActionDispatch,+ startSubagent,+} from "#execution/dispatch-runtime-actions-shared.js";+import { createDurableSessionState } from "#execution/durable-session-store.js";+import {+ checkTaskContinuationAvailability,+ createTaskContinuationBusyResult,+ describeTaskDispatch,+} from "#execution/tasks/parent/continuation-dispatch.js";+import { findTaskAgentAddress } from "#execution/tasks/parent/control-shared.js";+import type { BackgroundTask } from "#execution/tasks/parent/delegate.js";+import { CallbackBaseUrlKey } from "#harness/authorization.js";+import { getHarnessEmissionState } from "#harness/emission.js";+import { defineTool, type TaskExec, type ToolContext } from "#public/definitions/tool.js";+import type {+ RuntimeRemoteAgentCallActionRequest,+ RuntimeSubagentCallActionRequest,+} from "#runtime/actions/types.js";+import { SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA } from "#runtime/framework-tools/tasks.js";+import { PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA } from "#runtime/subagents/registry.js";+import { parseJsonObject } from "#shared/json.js";+import { createSubagentExecutorBinding } from "#tasks/types.js";+import { activeTurnId } from "#harness/active-turn-id.js";+import { createSubagentCalledEvent } from "#protocol/message.js";+import { workflowEntryReference } from "#execution/workflow-runtime.js";+import { createLogger, logError } from "#internal/logging.js";++type SubagentCallAction = RuntimeRemoteAgentCallActionRequest | RuntimeSubagentCallActionRequest;++interface SubagentDefinitionInput {+ readonly description: string;+ readonly name: string;+ readonly nodeId: string;+}++interface SubagentDispatchInput {+ readonly action: SubagentCallAction;+ readonly batch: TaskExec["batch"];+ readonly callbackBaseUrl?: string;+ readonly ctx: AlsContext;+ readonly event: {+ readonly sequence: number;+ readonly stepIndex: number;+ readonly turnId: string;+ };+ readonly localFanoutSize: number;+ readonly serializedContext: Record<string, unknown>;+ readonly sessionState: ReturnType<typeof createDurableSessionState>;+ readonly task: BackgroundTask;+}++interface SubagentDispatchResult {+ readonly address: Extract<DispatchOutcome, { readonly kind: "called" }>["address"];+ readonly agentId: string;+ readonly mode: "local" | "remote";+ readonly name: string;+ readonly remote?: { readonly resolverId: string; readonly url: string };+ readonly session: RuntimeSession;+}++const localSubagentExecutors = new WeakSet<object>();+const batchAgentClaims = new WeakMap<TaskExec["batch"], Map<string, string>>();+const log = createLogger("runtime.framework-tools.subagent");++export function defineSubagent(input: SubagentDefinitionInput) {+ const definition = defineTool({+ description: input.description,+ execution: "background",+ inputSchema: PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA,+ outputSchema: SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA,+ execute: (toolInput, ctx, task) =>+ executeSubagentTool({ definition: input, kind: "local", task, toolContext: ctx, toolInput }),+ });+ return definition;+}++export function registerLocalSubagentExecutor(execute: object): void {+ localSubagentExecutors.add(execute);+}++export function countLocalSubagentCalls(+ calls: readonly { readonly definition: { readonly execute: object } }[],+): number {+ return calls.filter((call) => localSubagentExecutors.has(call.definition.execute)).length;+}++export async function executeSubagentTool(input: {+ readonly definition: SubagentDefinitionInput;+ readonly kind: "local" | "remote";+ readonly task: TaskExec;+ readonly toolContext: ToolContext;+ readonly toolInput: unknown;+}) {+ const ctx = loadContext();+ const { batch, session, task } = input.task;+ const emission = getHarnessEmissionState(session.state);+ const commonAction = {+ callId: input.toolContext.callId,+ description: input.definition.description,+ input: parseJsonObject(PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA.parse(input.toolInput)),+ name: input.definition.name,+ nodeId: input.definition.nodeId,+ };+ const action: SubagentCallAction =+ input.kind === "remote"+ ? {+ ...commonAction,+ kind: "remote-agent-call",+ remoteAgentName: input.definition.name,+ }+ : {+ ...commonAction,+ kind: "subagent-call",+ subagentName: input.definition.name,+ };+ const dispatched = await dispatchSubagent({+ action,+ batch,+ callbackBaseUrl: ctx.get(CallbackBaseUrlKey),+ ctx,+ event: { ...emission, turnId: activeTurnId(emission) },+ localFanoutSize: countLocalSubagentCalls(batch),+ serializedContext: serializeContext(ctx),+ sessionState: createDurableSessionState({ session }),+ task,+ });+ // The executor binding is the durable copy of the child's addressed+ // handle, read back from the post-dispatch session so it is exactly what+ // the handle store recorded (fresh start) or already held (resume). It is+ // deep-equal on replay — identity and address derive from the originating+ // call — and it is the only channel the task layer needs: commit writes+ // the address into the parent handle store, and compensation or a later+ // turn cancels the child through it.+ const record = findTaskAgentAddress(dispatched.session, dispatched.agentId);+ if (record === undefined) {+ throw new Error(+ `Subagent dispatch for "${dispatched.agentId}" recorded no task agent address.`,+ );+ }+ const executor = createSubagentExecutorBinding({+ address: record.address,+ identity: record.identity,+ });+ await emitSubagentCalled({+ callId: input.toolContext.callId,+ childSessionId: dispatched.address.sessionId,+ event: { ...emission, turnId: activeTurnId(emission) },+ name: dispatched.name,+ remote: dispatched.remote,+ sessionId: session.sessionId,+ toolName: input.definition.name,+ });++ const delegated = input.task.delegated({+ executor,+ receipt: { agentId: dispatched.agentId },+ });+ await emitSubagentCompleted({+ callId: input.toolContext.callId,+ output: JSON.stringify(delegated.receipt),+ subagentName: dispatched.name,+ taskId: delegated.receipt.taskId,+ });+ return delegated;+}++async function dispatchSubagent(input: SubagentDispatchInput): Promise<SubagentDispatchResult> {+ const prepared = await prepareAgentActionDispatch({+ action: input.action,+ ctx: input.ctx,+ event: input.event,+ localFanoutSize: input.localFanoutSize,+ serializedContext: input.serializedContext,+ sessionState: input.sessionState,+ });+ const entry = prepared.plan[0];+ if (entry === undefined || entry.kind === "task-control") {+ throw new Error("Subagent tool dispatch produced no executable plan entry.");+ }+ if (entry.kind === "reject") {+ throw new Error(JSON.stringify(entry.result.output));+ }++ if (entry.kind === "resume") {+ const busy = await checkTaskContinuationAvailability({+ action: entry.action,+ agentId: entry.agentId,+ parentStepIndex: input.event.stepIndex,+ parentTurnId: input.event.turnId,+ session: prepared.session,+ });+ if (busy !== undefined) throw new Error(JSON.stringify(busy.output));++ const claimedTaskId = claimBatchAgent(input.batch, entry.agentId, input.task.taskId);+ if (claimedTaskId !== undefined) {+ const busy = createTaskContinuationBusyResult({+ action: entry.action,+ agentId: entry.agentId,+ status: "working",+ taskId: claimedTaskId,+ });+ throw new Error(JSON.stringify(busy.output));+ }+ }++ const outcome =+ entry.kind === "resume"+ ? await dispatchToTaskAgentAddress({+ action: entry.action,+ agentId: entry.agentId,+ auth: prepared.auth,+ bundle: createAgentContinuationBundle({+ action: entry.action,+ bundle: prepared.bundle,+ dynamicRemoteAgent: entry.dynamicRemoteAgent,+ }),+ currentSession: prepared.session,+ parentToken: input.task.taskInboxToken,+ })+ : await startSubagent({+ auth: prepared.auth,+ batchEvent: input.event,+ bundle: prepared.bundle,+ callbackBaseUrl: input.callbackBaseUrl,+ capabilities: prepared.capabilities,+ channelMetadata: prepared.channelMetadata,+ currentSession: prepared.session,+ fanoutSize: prepared.fanoutSize,+ initiatorAuth: prepared.initiatorAuth,+ parentContinuationToken: input.task.taskInboxToken,+ parentTraceContext: prepared.parentTraceContext,+ persistentSessions: true,+ sandboxSessionId: prepared.sandboxSessionId,+ serializedContext: prepared.serializedContext,+ session: prepared.session,+ taskOwned: true,+ target: entry.target,+ });+ if (outcome.kind === "error") throw new Error(JSON.stringify(outcome.result.output));++ const described = describeTaskDispatch({+ action: input.action,+ agentId: entry.kind === "resume" ? entry.agentId : undefined,+ parentSessionId: prepared.session.sessionId,+ parentTurnId: input.event.turnId,+ session: outcome.session,+ });+ const dynamicRemoteAgent =+ entry.kind === "resume"+ ? entry.dynamicRemoteAgent+ : entry.target.kind === "remote"+ ? entry.target.dynamicRemoteAgent+ : undefined;+ return {+ address: outcome.address,+ agentId: described.agentId,+ mode: described.mode,+ name: described.name,+ ...(outcome.address.kind === "agent/remote"+ ? {+ remote: {+ resolverId: dynamicRemoteAgent?.credentialsStepId ?? input.action.nodeId,+ url: outcome.address.url,+ },+ }+ : {}),+ session: outcome.session,+ };+}++function claimBatchAgent(+ batch: TaskExec["batch"],+ agentId: string,+ taskId: string,+): string | undefined {+ let claims = batchAgentClaims.get(batch);+ if (claims === undefined) {+ claims = new Map();+ batchAgentClaims.set(batch, claims);+ }+ const claimedTaskId = claims.get(agentId);+ if (claimedTaskId !== undefined) return claimedTaskId;+ claims.set(agentId, taskId);+ return undefined;+}++async function emitSubagentCalled(input: {+ readonly callId: string;+ readonly childSessionId: string;+ readonly event: { readonly sequence: number; readonly turnId: string };+ readonly name: string;+ readonly remote?: { readonly resolverId: string; readonly url: string };+ readonly sessionId: string;+ readonly toolName: string;+}): Promise<void> {+ const handleEvent = loadContext().get(HandleEventKey);+ if (handleEvent === undefined) return;+ try {+ await handleEvent(+ createSubagentCalledEvent({+ callId: input.callId,+ childSessionId: input.childSessionId,+ name: input.name,+ remote: input.remote,+ sequence: input.event.sequence,+ sessionId: input.sessionId,+ toolName: input.toolName,+ turnId: input.event.turnId,+ workflowId: workflowEntryReference.workflowId,+ }),+ );+ } catch (error) {+ logError(log, "subagent.called emission failed", error, {+ callId: input.callId,+ childSessionId: input.childSessionId,+ toolName: input.toolName,+ });+ }+}++async function emitSubagentCompleted(input: {+ readonly callId: string;+ readonly output: string;+ readonly subagentName: string;+ readonly taskId: string;+}): Promise<void> {+ const handleEvent = loadContext().get(HandleEventKey);+ if (handleEvent === undefined) return;+ try {+ await handleEvent({+ data: {+ backgroundTask: { status: "working", taskId: input.taskId },+ callId: input.callId,+ output: input.output,+ subagentName: input.subagentName,+ },+ type: "subagent.completed",+ });+ } catch (error) {+ logError(log, "subagent.completed emission failed", error, {+ callId: input.callId,+ taskId: input.taskId,+ });+ }+}diff --git a/packages/eve/src/runtime/framework-tools/subagent/remote.ts b/packages/eve/src/runtime/framework-tools/subagent/remote.tsnew file mode 100644index 000000000..dff8f7269--- /dev/null+++ b/packages/eve/src/runtime/framework-tools/subagent/remote.ts@@ -0,0 +1,19 @@+import { defineTool } from "#public/definitions/tool.js";+import { SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA } from "#runtime/framework-tools/tasks.js";+import { PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA } from "#runtime/subagents/registry.js";+import { executeSubagentTool } from "#runtime/framework-tools/subagent/local.js";++export function defineRemoteSubagent(input: {+ readonly description: string;+ readonly name: string;+ readonly nodeId: string;+}) {+ return defineTool({+ description: input.description,+ execution: "background",+ inputSchema: PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA,+ outputSchema: SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA,+ execute: (toolInput, ctx, task) =>+ executeSubagentTool({ definition: input, kind: "remote", task, toolContext: ctx, toolInput }),+ });+}diff --git a/packages/eve/src/runtime/framework-tools/tasks.ts b/packages/eve/src/runtime/framework-tools/tasks.tsindex 9bd26165e..d06e741da 100644--- a/packages/eve/src/runtime/framework-tools/tasks.ts+++ b/packages/eve/src/runtime/framework-tools/tasks.ts@@ -68,6 +68,12 @@ export const TASK_VIEWS_OUTPUT_SCHEMA = z.object({tasks: z.array(TASK_VIEW_SCHEMA),});+export const SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA = z.strictObject({+ agentId: z.string(),+ status: z.literal("working"),+ taskId: z.string(),+});+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.";diff --git a/packages/eve/src/shared/tool-task.ts b/packages/eve/src/shared/tool-task.tsindex d08ea44f6..a8fa3c368 100644--- a/packages/eve/src/shared/tool-task.ts+++ b/packages/eve/src/shared/tool-task.ts@@ -68,21 +68,23 @@ export interface TaskExec {* directly instead of through the (already finished) tool call.*/readonly binding: TaskBinding;- /**- * Reports this task's terminal result from in-process code (e.g. a callback- * that outlives `execute`). Call it only after `execute` returned- * `delegated(...)` — the runtime settles non-delegated returns itself, and- * a second terminal command is refused. Throws once the task is terminal.- * Not restart-safe: an in-memory callback dies with the process; the- * persisted executor binding remains the durable cancellation path.- */- readonly send: (command: TaskSendCommand) => Promise<void>;/*** Snapshot of the harness session at step start, for reading context.- * Mutating it changes nothing durable — session writes at commit are- * provider-owned (the task index entry for this call).+ * Mutating it changes nothing durable: session writes belong to the+ * runtime, keyed off the executor binding at step commit.*/readonly session: HarnessSession;+ /**+ * Delivers a terminal command to this task's inbox from the same process,+ * for executors that outlive `execute` in-memory (e.g. a callback firing+ * after delegation). Call it only after `execute` returned `delegated(...)`+ * — the runtime settles non-delegated returns itself, and a second terminal+ * command is refused. Not restart-safe: an in-process callback dies with+ * the process; the persisted executor binding remains the durable+ * cancellation path. Throws when the task no longer accepts commands+ * (already terminal).+ */+ readonly send: (command: TaskSendCommand) => Promise<void>;/** The durable task backing this call; its identity outlives `execute`. */readonly task: BackgroundTask;diff --git a/packages/eve/src/tasks/types.test.ts b/packages/eve/src/tasks/types.test.tsnew file mode 100644index 000000000..450b67c26--- /dev/null+++ b/packages/eve/src/tasks/types.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from "vitest";++import type { AgentAddress, AgentIdentity } from "#harness/handles/store.js";+import {+ createSubagentExecutorBinding,+ readSubagentExecutor,+ readSubagentTaskMetadata,+} from "#tasks/types.js";++const identity: AgentIdentity = {+ id: "ag_research:operation1",+ name: "research",+ nodeId: "node_research",+};++const localAddress: AgentAddress = {+ continuationToken: "continuation_child",+ kind: "agent/local",+ sessionId: "session_child",+};++const remoteAddress: AgentAddress = {+ callbackBaseUrl: "https://parent.example",+ kind: "agent/remote",+ sessionId: "session_child",+ url: "https://child.example",+};++describe("subagent executor binding", () => {+ it("round-trips a local child through the durable binding", () => {+ const binding = createSubagentExecutorBinding({ address: localAddress, identity });+ expect(binding.kind).toBe("subagent");+ expect(readSubagentExecutor(binding)).toEqual({ address: localAddress, identity });+ });++ it("round-trips a remote child through the durable binding", () => {+ const binding = createSubagentExecutorBinding({ address: remoteAddress, identity });+ expect(readSubagentExecutor(binding)).toEqual({ address: remoteAddress, identity });+ });++ it("reads the binding recorded on task executor state", () => {+ const binding = createSubagentExecutorBinding({ address: localAddress, identity });+ expect(readSubagentExecutor({ binding })).toEqual({ address: localAddress, identity });+ });++ it("derives subagent task metadata from the binding of a generic tool task", () => {+ const executor = createSubagentExecutorBinding({ address: remoteAddress, identity });+ expect(+ readSubagentTaskMetadata({ executor, metadata: { kind: "tool", name: "research" } }),+ ).toEqual({ agentId: identity.id, kind: "subagent", mode: "remote", name: identity.name });+ });++ it("returns undefined for other executor kinds and incomplete addresses", () => {+ expect(readSubagentExecutor(undefined)).toBeUndefined();+ expect(readSubagentExecutor({ data: { exportId: "x" }, kind: "export" })).toBeUndefined();+ expect(+ readSubagentExecutor({+ // A local address without its continuation token cannot route a+ // cancel; the reader rejects it instead of returning a partial value.+ data: {+ address: { kind: "agent/local", sessionId: "session_child" },+ identity: { id: identity.id, name: identity.name, nodeId: identity.nodeId },+ },+ kind: "subagent",+ }),+ ).toBeUndefined();+ });+});diff --git a/packages/eve/src/tasks/types.ts b/packages/eve/src/tasks/types.tsindex 3b0951fc4..23aa54fe3 100644--- a/packages/eve/src/tasks/types.ts+++ b/packages/eve/src/tasks/types.ts@@ -1,4 +1,5 @@-import type { JsonValue } from "#shared/json.js";+import type { AgentAddress, AgentIdentity } from "#harness/handles/store.js";+import { isJsonObjectValue, type JsonValue } from "#shared/json.js";import type { TaskExecutorBinding } from "#shared/tool-task.js";import type { SubagentAuthorizationEvent } from "#channel/types.js";@@ -61,19 +62,75 @@ export function readSubagentTaskMetadata(task: {if (task.metadata.kind === "subagent" && "agentId" in task.metadata) {return task.metadata;}- const executor = task.executor;+ const executor = readSubagentExecutor(task.executor);+ if (executor === undefined) return undefined;+ return {+ agentId: executor.identity.id,+ kind: "subagent",+ mode: executor.address.kind === "agent/remote" ? "remote" : "local",+ name: executor.identity.name,+ };+}++/**+ * Durable subagent executor binding payload: the child's stable identity and+ * private delivery address, copied from the parent's agent handle store at+ * delegation time. Every field derives deterministically from the+ * originating call (operation-hashed id, dispatch-chosen continuation+ * token), so a replayed delegation produces a deep-equal binding — the+ * equality the task run's `bind` replay check compares.+ */+export interface SubagentExecutorData {+ readonly address: AgentAddress;+ readonly identity: AgentIdentity;+}++export function createSubagentExecutorBinding(executor: SubagentExecutorData): TaskExecutorBinding {+ const { address, identity } = executor;+ return {+ data: {+ address: { ...address },+ identity: { id: identity.id, name: identity.name, nodeId: identity.nodeId },+ },+ kind: "subagent",+ };+}++export function readSubagentExecutor(+ executor: TaskExecutorBinding | TaskExecutorState | undefined,+): SubagentExecutorData | undefined {const binding = executor !== undefined && "kind" in executor ? executor : executor?.binding;if (binding?.kind !== "subagent") return undefined;- const agentId = binding.data.agentId;- const mode = binding.data.mode;- const name = binding.data.name;- return typeof agentId === "string" &&- (mode === "local" || mode === "remote") &&- typeof name === "string"- ? { agentId, kind: "subagent", mode, name }+ const identity = readAgentIdentity(binding.data.identity);+ const address = readAgentAddress(binding.data.address);+ return identity === undefined || address === undefined ? undefined : { address, identity };+}++function readAgentIdentity(value: JsonValue | undefined): AgentIdentity | undefined {+ if (value === undefined || !isJsonObjectValue(value)) return undefined;+ const { id, name, nodeId } = value;+ return typeof id === "string" && typeof name === "string" && typeof nodeId === "string"+ ? { id, name, nodeId }: undefined;}+function readAgentAddress(value: JsonValue | undefined): AgentAddress | undefined {+ if (value === undefined || !isJsonObjectValue(value)) return undefined;+ const { callbackBaseUrl, continuationToken, kind, sessionId, url } = value;+ if (typeof sessionId !== "string") return undefined;+ if (kind === "agent/local" || kind === "agent/self") {+ return typeof continuationToken === "string"+ ? { continuationToken, kind, sessionId }+ : undefined;+ }+ if (kind === "agent/remote") {+ return typeof url === "string" && typeof callbackBaseUrl === "string"+ ? { callbackBaseUrl, kind, sessionId, url }+ : undefined;+ }+ return undefined;+}+export function sameTaskMetadata(left: DurableTaskMetadata, right: DurableTaskMetadata): boolean {if (left.kind !== right.kind || left.name !== right.name) return false;const leftSubagent = "agentId" in left;diff --git a/research/subagents-as-tasks-implementation.md b/research/subagents-as-tasks-implementation.mdindex e9dd57e66..bddf37f40 100644--- a/research/subagents-as-tasks-implementation.md+++ b/research/subagents-as-tasks-implementation.md@@ -178,6 +178,11 @@ definitions, then make tasks the default subagent execution and retire the flagacceptance criteria hold. Both are behavior changes, not additive, and are sequenced lastdeliberately; they get their own plans if anything nontrivial surfaces.+Retiring `RuntimeAction` also requires defining `task_cancel` and `task_update` in terms of+`defineTool`, then deleting the `task-control` metadata and dispatch path. Before that migration,+settle the smallest generic `defineTool` execution capability that gives framework tools access to+their durable session and task ownership state; the harness must not branch on either tool by name.+## Settled decisions1. **Lifecycle ownership.** In tasks mode, the task run is the sole execution-lifecycle writer.