The Open Framework for Building Agents
feat(eve): generic background tool execution foundation (#2322)
Rui13906757319b
diff --git a/.changeset/background-tool-task-send.md b/.changeset/background-tool-task-send.mdnew file mode 100644index 000000000..7d1d775d1--- /dev/null+++ b/.changeset/background-tool-task-send.md@@ -0,0 +1,5 @@+---+"eve": minor+---++Background tools can now report a delegated task's terminal result in-process via `task.send({ kind: "complete" | "fail" | "cancel", ... })`, without minting a callback URL.diff --git a/.changeset/generic-background-tool-execution.md b/.changeset/generic-background-tool-execution.mdnew file mode 100644index 000000000..a8cbfae33--- /dev/null+++ b/.changeset/generic-background-tool-execution.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Add generic background `defineTool` execution so authored tools can return `task.delegated()` receipts and run through the durable task lifecycle without subagent-specific harness branches.diff --git a/docs/tools/overview.mdx b/docs/tools/overview.mdxindex fc6b7c66d..a7fd4f612 100644--- a/docs/tools/overview.mdx+++ b/docs/tools/overview.mdx@@ -56,6 +56,19 @@ history or `toModelOutput`; only the final yield does. Treat snapshots aslast-write-wins by tool call id, not append-only progress. The durable runtimecan retry a step and replay overlapping snapshots.+### Experimental background execution++`defineTool({ execution: "background" })` receives a third `task` argument. Returning a normal+value completes the durable task with that value. Returning `task.delegated({ executor, receipt })`+returns a `working` receipt immediately while an external executor continues the task.+The root agent must enable `experimental.tasks`; eve rejects background tools at build time otherwise.++This contract currently supports framework-owned task executors, including local and remote+subagents 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 `ctx` parameter`execute` gets a `ctx` carrying the runtime accessors:diff --git a/packages/eve/extension-contracts/compatibility/channel/v5.ts b/packages/eve/extension-contracts/compatibility/channel/v5.tsnew file mode 100644index 000000000..33186ad0c--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/channel/v5.ts@@ -0,0 +1,13 @@+import { defineChannel, POST } from "#public/channels/index.js";++export default defineChannel({+ routes: [+ POST("/input", async (_request, { attachSession, from }) => {+ const inputResponses = [{ optionId: "approve", requestId: "approval-1" }];+ await from("thread-1").respond(inputResponses, { auth: null });+ await attachSession("session-1").respond(inputResponses, { auth: null });+ return new Response("ok");+ }),+ ],+ turnPolicy: "queue",+});diff --git a/packages/eve/extension-contracts/compatibility/tool/v13.ts b/packages/eve/extension-contracts/compatibility/tool/v13.tsnew file mode 100644index 000000000..eae0f5b7e--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/tool/v13.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/compatibility/tool/v14.ts b/packages/eve/extension-contracts/compatibility/tool/v14.tsnew file mode 100644index 000000000..24a84e826--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/tool/v14.ts@@ -0,0 +1,15 @@+import { z as z3 } from "zod/v3";++import { defineTool } from "#public/tools/index.js";++export default defineTool({+ description: "Start a report.",+ execution: "background",+ inputSchema: z3.object({ reportId: z3.string() }),+ execute(input, _ctx, task) {+ return task.delegated({+ executor: { data: { reportId: input.reportId }, kind: "report" },+ receipt: { reportId: input.reportId },+ });+ },+});diff --git a/packages/eve/extension-contracts/reports/channel/v6.json b/packages/eve/extension-contracts/reports/channel/v6.jsonnew file mode 100644index 000000000..a18920a12--- /dev/null+++ b/packages/eve/extension-contracts/reports/channel/v6.json@@ -0,0 +1,17 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "channel",+ "epoch": 6,+ "sha256": "9ce8b280f49aa0cbef63bfdb58f792878cf142b67182b7d9fbc854a93488febc",+ "exports": [+ "DELETE",+ "GET",+ "PATCH",+ "POST",+ "PUT",+ "WS",+ "createWebSocketUpgradeServer",+ "defineChannel",+ "isChannel"+ ]+}diff --git a/packages/eve/extension-contracts/reports/tool/v14.json b/packages/eve/extension-contracts/reports/tool/v14.jsonnew file mode 100644index 000000000..7f532aa9f--- /dev/null+++ b/packages/eve/extension-contracts/reports/tool/v14.json@@ -0,0 +1,22 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "tool",+ "epoch": 14,+ "sha256": "8c5da497d653a4f237c972b3281b6586d4378936ba6870993ad5ecaaf3feb95d",+ "exports": [+ "defineBashTool",+ "defineGlobTool",+ "defineGrepTool",+ "defineReadFileTool",+ "defineTool",+ "defineWriteFileTool",+ "disableTool",+ "experimental_workflow",+ "isDisabledToolSentinel",+ "isExperimentalWorkflowToolDefinition",+ "toolOutput",+ "toolOutputPart",+ "toolResultFrom",+ "webSearch"+ ]+}diff --git a/packages/eve/extension-contracts/reports/tool/v15.json b/packages/eve/extension-contracts/reports/tool/v15.jsonnew file mode 100644index 000000000..33e0274b2--- /dev/null+++ b/packages/eve/extension-contracts/reports/tool/v15.json@@ -0,0 +1,22 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "tool",+ "epoch": 15,+ "sha256": "7a41eb74008b606d6b9141f9125ba75a8cc034274adaa92173bc3e9b9ceafdcc",+ "exports": [+ "defineBashTool",+ "defineGlobTool",+ "defineGrepTool",+ "defineReadFileTool",+ "defineTool",+ "defineWriteFileTool",+ "disableTool",+ "experimental_workflow",+ "isDisabledToolSentinel",+ "isExperimentalWorkflowToolDefinition",+ "toolOutput",+ "toolOutputPart",+ "toolResultFrom",+ "webSearch"+ ]+}diff --git a/packages/eve/extension-contracts/reports/tool/v16.json b/packages/eve/extension-contracts/reports/tool/v16.jsonnew file mode 100644index 000000000..3d0e3c277--- /dev/null+++ b/packages/eve/extension-contracts/reports/tool/v16.json@@ -0,0 +1,22 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "tool",+ "epoch": 16,+ "sha256": "0ac29852f4967945a2e12c38839d362f874bf40863d622d8107e4fbb65f1fc71",+ "exports": [+ "defineBashTool",+ "defineGlobTool",+ "defineGrepTool",+ "defineReadFileTool",+ "defineTool",+ "defineWriteFileTool",+ "disableTool",+ "experimental_workflow",+ "isDisabledToolSentinel",+ "isExperimentalWorkflowToolDefinition",+ "toolOutput",+ "toolOutputPart",+ "toolResultFrom",+ "webSearch"+ ]+}diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.tsindex 1f449c2aa..b403693a4 100644--- a/packages/eve/src/compiler/extension-compatibility.ts+++ b/packages/eve/src/compiler/extension-compatibility.ts@@ -21,13 +21,17 @@ interface ExtensionCapabilityContract {const EXTENSION_CAPABILITY_CONTRACTS = {extension: { current: 1, supported: [1], dropped: {} },- tool: { current: 13, supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], dropped: {} },+ tool: {+ current: 16,+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16],+ dropped: { 15: "TaskExec replaces stageEffect with send" },+ },dynamicTool: {current: 18,supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],dropped: {},},- channel: { current: 5, supported: [1, 2, 3, 4, 5], dropped: {} },+ channel: { current: 6, supported: [1, 2, 3, 4, 5, 6], dropped: {} },schedule: { current: 3, supported: [1, 2, 3], dropped: {} },subagent: { current: 2, supported: [1, 2], dropped: {} },connection: { current: 5, supported: [1, 2, 3, 4, 5], dropped: {} },diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.tsindex 6dd820114..e6d32d2de 100644--- a/packages/eve/src/compiler/manifest.ts+++ b/packages/eve/src/compiler/manifest.ts@@ -614,6 +614,7 @@ const compiledConnectionDefinitionSchema = zconst compiledToolDefinitionSchema = z.object({description: z.string(),+ execution: z.literal("background").optional(),exportName: z.string().optional(),inputSchema: jsonObjectSchema.nullable(),logicalPath: z.string(),diff --git a/packages/eve/src/compiler/normalize-manifest.test.ts b/packages/eve/src/compiler/normalize-manifest.test.tsindex 5783c7538..67ca2912b 100644--- a/packages/eve/src/compiler/normalize-manifest.test.ts+++ b/packages/eve/src/compiler/normalize-manifest.test.ts@@ -1,5 +1,6 @@import { beforeEach, describe, expect, it, vi } from "vitest";+import { z } from "#compiled/zod/index.js";import type { AgentSourceManifest } from "#discover/manifest.js";import {createAgentSourceManifest,@@ -12,7 +13,7 @@ import { compileAgentManifest } from "#compiler/normalize-manifest.js";import { collectModuleRefsForManifest } from "#compiler/module-map.js";import { defineAgent, defineDynamic } from "#public/definitions/agent.js";import { defineInstructions } from "#public/definitions/instructions.js";-import { experimental_workflow } from "#public/definitions/tool.js";+import { defineTool, experimental_workflow } from "#public/definitions/tool.js";import { webSearch } from "#public/tools/web-search.js";const mocks = vi.hoisted(() => ({@@ -241,6 +242,35 @@ describe("compileAgentManifest", () => {);});+ it("requires experimental.tasks for background tools", async () => {+ const manifest = createAgentSourceManifest({+ agentId: "root",+ agentRoot: "/app/agent",+ appRoot: "/app",+ tools: [createModuleSourceRef({ logicalPath: "tools/export.ts" })],+ });+ mocks.loadModuleBackedDefinition.mockResolvedValue(+ defineTool({+ description: "Starts an export.",+ execution: "background",+ inputSchema: z.object({}),+ execute: () => ({ ok: true }),+ }),+ );+ mocks.compileAgentConfig.mockResolvedValue(createConfig({ name: "root" }));++ await expect(compileAgentManifest(manifest)).rejects.toThrow(+ 'Background tool "export" requires experimental.tasks: true in the root agent config.',+ );++ mocks.compileAgentConfig.mockResolvedValue(+ createConfig({ experimental: { tasks: true }, name: "root" }),+ );+ await expect(compileAgentManifest(manifest)).resolves.toMatchObject({+ tools: [expect.objectContaining({ execution: "background", name: "export" })],+ });+ });+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.tsindex 8bed87ce0..30f7e57a7 100644--- a/packages/eve/src/compiler/normalize-manifest.ts+++ b/packages/eve/src/compiler/normalize-manifest.ts@@ -56,6 +56,15 @@ export async function compileAgentManifest(subagents: composeAgentSubagentSources(manifest),});+ const backgroundTool = [compiledNode, ...subagentGraph.nodes.map((node) => node.agent)]+ .flatMap((node) => node.tools)+ .find((tool) => tool.execution === "background");+ if (backgroundTool !== undefined && compiledNode.config.experimental?.tasks !== true) {+ throw new Error(+ `Background tool "${backgroundTool.name}" requires experimental.tasks: true in the root agent config.`,+ );+ }+return createCompiledAgentManifest({...compiledNode,extensionMounts: compiledNode.extensionMounts,diff --git a/packages/eve/src/compiler/normalize-tool.ts b/packages/eve/src/compiler/normalize-tool.tsindex 9116fef4e..7b6a5e3d2 100644--- a/packages/eve/src/compiler/normalize-tool.ts+++ b/packages/eve/src/compiler/normalize-tool.ts@@ -86,6 +86,7 @@ export async function compileToolEntry(kind: "tool",definition: {description: entry.definition.description,+ execution: entry.definition.execution,exportName: source.exportName,inputSchema: entry.definition.inputSchema ?? null,logicalPath: source.logicalPath,diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.tsindex e91a5d410..b33f2d9e7 100644--- a/packages/eve/src/context/keys.ts+++ b/packages/eve/src/context/keys.ts@@ -19,6 +19,7 @@ import type {} from "#channel/types.js";import { ContextKey } from "#context/key.js";import type { InstrumentationChannelDeliveryRef } from "#harness/instrumentation/lifecycle.js";+import type { HandleEventFn } from "#harness/types.js";import type { DurableDynamicToolCallbacks } from "#shared/durable-dynamic-tool-callbacks.js";import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";import type { DynamicRemoteAgentConfig } from "#runtime/subagents/dynamic-remote-agent-config.js";@@ -110,6 +111,7 @@ export const SessionCallbackKey = new ContextKey<SessionCallback>("eve.sessionCaexport const SessionKey = new ContextKey<Session>("eve.session");export const SandboxKey = new ContextKey<SandboxAccess>("eve.sandbox");+export const HandleEventKey = new ContextKey<HandleEventFn>("eve.internal.handleEvent");// ---------------------------------------------------------------------------// Dynamic model keys@@ -191,6 +193,9 @@ export const StepDynamicToolMetadataKey = new ContextKey<readonly DurableDynamic"eve.stepDynamicToolMetadata",);+/** Whether this turn executes subagent definitions as durable background tools. */+export const TasksEnabledKey = new ContextKey<boolean>("eve.tasksEnabled");+export type DurableDynamicSubagentSelection =| {readonly agentConfig: DynamicSubagentAgentConfig;diff --git a/packages/eve/src/context/provider.ts b/packages/eve/src/context/provider.tsindex adc7741c9..651096544 100644--- a/packages/eve/src/context/provider.ts+++ b/packages/eve/src/context/provider.ts@@ -1,4 +1,4 @@-import type { HarnessSession } from "#harness/types.js";+import type { HarnessSession, StepResult } from "#harness/types.js";import type { ContextContainer } from "#context/container.js";import type { ContextKey } from "#context/key.js";@@ -32,4 +32,10 @@ export interface FrameworkContextProvider<T> {): ProviderResult<T> | undefined | Promise<ProviderResult<T> | undefined>;commit?(value: T, session: HarnessSession): HarnessSession | Promise<HarnessSession>;++ /** Rolls back provider-owned effects when the callback or a later commit fails. */+ rollback?(value: T, cause: unknown): void | Promise<void>;++ /** Adds provider-owned durable effects to a successfully committed harness step. */+ decorateStepResult?(value: T, result: StepResult): StepResult | Promise<StepResult>;}diff --git a/packages/eve/src/context/run-step.ts b/packages/eve/src/context/run-step.tsindex 2efa7df72..efaeac6c9 100644--- a/packages/eve/src/context/run-step.ts+++ b/packages/eve/src/context/run-step.ts@@ -34,35 +34,59 @@ export async function withContextScope<T>(ctx: ContextContainer,harnessSession: HarnessSession,callback: (session: HarnessSession) => Promise<ContextScopeResult<T>>,+ additionalProviders: readonly FrameworkContextProvider<any>[] = [],): Promise<ContextScopeResult<T>> {let session = harnessSession;+ const providers = [...frameworkProviders, ...additionalProviders];+ const createdProviders: FrameworkContextProvider<any>[] = [];ctx.clearVirtualContext();- for (const provider of frameworkProviders) {- const result = await provider.create(ctx, session);- if (result !== undefined) {- ctx.setVirtualContext(provider.key, result.value);- if (result.session !== undefined) {- session = result.session;+ try {+ for (const provider of providers) {+ const result = await provider.create(ctx, session);+ if (result !== undefined) {+ ctx.setVirtualContext(provider.key, result.value);+ createdProviders.push(provider);+ if (result.session !== undefined) {+ session = result.session;+ }}}- }- const scopeResult = await contextStorage.run(ctx, () => callback(session));+ const scopeResult = await contextStorage.run(ctx, () => callback(session));- let committed = scopeResult.session;- for (const provider of frameworkProviders) {- if (provider.commit && ctx.has(provider.key)) {- committed = await provider.commit(ctx.require(provider.key), committed);+ let committed = scopeResult.session;+ for (const provider of createdProviders) {+ if (provider.commit !== undefined) {+ committed = await provider.commit(ctx.require(provider.key), committed);+ }}- }- if (committed === scopeResult.session) {- return scopeResult;- }+ if (committed === scopeResult.session) {+ return scopeResult;+ }- return { result: scopeResult.result, session: committed };+ return { result: scopeResult.result, session: committed };+ } catch (error) {+ const rollbackErrors: unknown[] = [];+ for (const provider of createdProviders.toReversed()) {+ if (provider.rollback === undefined) continue;+ try {+ await provider.rollback(ctx.require(provider.key), error);+ } catch (rollbackError) {+ rollbackErrors.push(rollbackError);+ }+ }+ if (rollbackErrors.length > 0) {+ throw new AggregateError(+ [error, ...rollbackErrors],+ "Framework context rollback did not complete.",+ { cause: error },+ );+ }+ throw error;+ }}/**@@ -75,11 +99,23 @@ export async function runStep(ctx: ContextContainer,harnessSession: HarnessSession,callback: (session: HarnessSession) => Promise<StepResult>,+ additionalProviders: readonly FrameworkContextProvider<any>[] = [],): Promise<StepResult> {- const { result, session } = await withContextScope(ctx, harnessSession, async (enriched) => {- const result = await callback(enriched);- return { result, session: result.session };- });+ const scoped = await withContextScope(+ ctx,+ harnessSession,+ async (enriched) => {+ const result = await callback(enriched);+ return { result, session: result.session };+ },+ additionalProviders,+ );- return { ...result, session };+ let result = { ...scoped.result, session: scoped.session };+ for (const provider of [...frameworkProviders, ...additionalProviders]) {+ if (provider.decorateStepResult !== undefined && ctx.has(provider.key)) {+ result = await provider.decorateStepResult(ctx.require(provider.key), result);+ }+ }+ return result;}diff --git a/packages/eve/src/execution/delegation-tool.ts b/packages/eve/src/execution/delegation-tool.tsindex e1cd806e2..f593ff89e 100644--- a/packages/eve/src/execution/delegation-tool.ts+++ b/packages/eve/src/execution/delegation-tool.ts@@ -1,9 +1,23 @@import type { HarnessToolDefinition } from "#harness/execute-tool.js";import type { PreparedRuntimeDelegationTool } from "#runtime/sessions/turn.js";-import { UNSPECIFIED_INPUT_SCHEMA, toInputSchema, toOutputSchema } from "#shared/tool-schema.js";+import {+ UNSPECIFIED_INPUT_SCHEMA,+ toInputSchema,+ toOutputSchema,+ type ToolSchemaSource,+} from "#shared/tool-schema.js";++type HarnessDelegationTool = Pick<+ PreparedRuntimeDelegationTool,+ "description" | "kind" | "name" | "nodeId"+> & {+ readonly inputSchema?: ToolSchemaSource | null;+ readonly outputSchema?: ToolSchemaSource | null;+ readonly rootOnly?: boolean;+};export function createHarnessDelegationToolDefinition(- tool: PreparedRuntimeDelegationTool,+ tool: HarnessDelegationTool,): HarnessToolDefinition {const runtimeAction: HarnessToolDefinition["runtimeAction"] =tool.kind === "remote"@@ -23,7 +37,9 @@ export function createHarnessDelegationToolDefinition(description: tool.description ?? "",inputSchema: toInputSchema(tool.inputSchema) ?? UNSPECIFIED_INPUT_SCHEMA,name: tool.name,- outputSchema: toOutputSchema(tool.outputSchema),+ outputSchema: toOutputSchema(tool.outputSchema) ?? undefined,+ rootOnly: tool.rootOnly,runtimeAction,+ workflowCallable: true,};}diff --git a/packages/eve/src/execution/dispatch-runtime-actions-shared.ts b/packages/eve/src/execution/dispatch-runtime-actions-shared.tsindex bc77f7a79..90aec89c2 100644--- a/packages/eve/src/execution/dispatch-runtime-actions-shared.ts+++ b/packages/eve/src/execution/dispatch-runtime-actions-shared.ts@@ -181,6 +181,43 @@ export async function prepareRuntimeActionDispatch(input: {const batch = getPendingRuntimeActionBatch(durableSession.state);if (batch === undefined || batch.actions.length === 0) return undefined;+ return await prepareActionDispatch({+ batch,+ durableSession,+ serializedContext: input.serializedContext,+ taskControls: input.taskControls,+ });+}++export async function prepareAgentActionDispatch(input: {+ readonly action: RuntimeActionRequest;+ readonly event: {+ readonly sequence: number;+ readonly stepIndex: number;+ readonly turnId: string;+ };+ readonly localFanoutSize: number;+ readonly serializedContext: Record<string, unknown>;+ readonly sessionState: DurableSessionState;+}): Promise<PreparedRuntimeActionDispatch> {+ const durableSession = await readDurableSession(input.sessionState);+ return await prepareActionDispatch({+ batch: { actions: [input.action], event: input.event, responseMessages: [] },+ durableSession,+ fanoutSize: input.localFanoutSize,+ serializedContext: input.serializedContext,+ taskControls: false,+ });+}++async function prepareActionDispatch(input: {+ readonly batch: NonNullable<ReturnType<typeof getPendingRuntimeActionBatch>>;+ readonly durableSession: Awaited<ReturnType<typeof readDurableSession>>;+ readonly fanoutSize?: number;+ readonly serializedContext: Record<string, unknown>;+ readonly taskControls: boolean;+}): Promise<PreparedRuntimeActionDispatch> {+ const { batch, durableSession } = input;assertUniqueRuntimeActionCallIds(batch.actions);const ctx = await deserializeContext(input.serializedContext);@@ -227,8 +264,9 @@ export async function prepareRuntimeActionDispatch(input: {bundle,capabilities: ctx.get(CapabilitiesKey),channelMetadata: ctx.get(ChannelInstrumentationKey),- fanoutSize: plan.filter((entry) => entry.kind === "start" && entry.target.kind === "local")- .length,+ fanoutSize:+ input.fanoutSize ??+ plan.filter((entry) => entry.kind === "start" && entry.target.kind === "local").length,initiatorAuth: ctx.get(InitiatorAuthKey) ?? null,parentTraceContext: readSessionTraceContext(input.serializedContext, session.sessionId),plan,diff --git a/packages/eve/src/execution/next-driver-action.ts b/packages/eve/src/execution/next-driver-action.tsindex 5671ceca3..3ccdb0cf4 100644--- a/packages/eve/src/execution/next-driver-action.ts+++ b/packages/eve/src/execution/next-driver-action.ts@@ -12,9 +12,46 @@* strips unknown fields.*/import type { DurableSessionState } from "#execution/durable-session-store.js";-import type { SettledTurn } from "#harness/types.js";+import type { SettledTurn, StepResult } from "#harness/types.js";import type { TokenUsage } from "#shared/token-usage.js";+interface DurableStepResultFields {+ readonly backgroundTaskState?: DurableSessionState;+ readonly backgroundTasks?: StepResult["backgroundTasks"];+ readonly serializedContext: Record<string, unknown>;+ readonly sessionState: DurableSessionState;+}++/** Result returned by the latest turn step to its durable driver workflow. */+export type DurableStepResult = (+ | {+ readonly action: "continue" | "done";+ readonly output?: unknown;+ readonly isError?: boolean;+ readonly sleepDurationMs?: number;+ readonly usage?: TokenUsage;+ readonly usageDelta?: TokenUsage;+ }+ | { readonly action: "cancelled" }+ | {+ readonly action: "park";+ readonly authorizationAttemptIds?: readonly string[];+ readonly authorizationNames?: readonly string[];+ readonly hasPendingAuthorization: boolean;+ readonly hasPendingInputBatch: boolean;+ readonly pendingRuntimeActionKeys?: readonly string[];+ readonly tasksEnabled?: boolean;+ readonly sleepDurationMs?: number;+ readonly settled?: SettledTurn;+ }+ | {+ readonly action: "dispatch-workflow-runtime-actions";+ readonly pendingRuntimeActionKeys: readonly string[];+ readonly sleepDurationMs?: number;+ }+) &+ DurableStepResultFields;+/** Discriminated union the driver workflow body dispatches on. */export type NextDriverAction =| {diff --git a/packages/eve/src/execution/node-step.ts b/packages/eve/src/execution/node-step.tsindex 473e3e18f..537e61cb3 100644--- a/packages/eve/src/execution/node-step.ts+++ b/packages/eve/src/execution/node-step.ts@@ -217,20 +217,21 @@ export function createNodeHarnessTools(input: {nodeId: input.node.nodeId,})) {- 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,- name: AGENT_TOOL_NAME,- runtimeAction: {- kind: "subagent-call",+ 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,- subagentName: AGENT_TOOL_NAME,- },- });+ rootOnly: true,+ }),+ );}const tasksEnabled = input.node.agent.config?.experimental?.tasks === true;@@ -276,6 +277,7 @@ function resolveHarnessToolDefinition(input: {return {approvalKey: def.approvalKey,description: def.description,+ execution: def.execution,execute: resolveAuthoredExecute({isFrameworkTool,rawExecute,@@ -314,6 +316,10 @@ function resolveAuthoredExecute(input: {if (isFrameworkTool) {return rawExecute;}- const authored = rawExecute as (toolInput: unknown, ctx: unknown) => unknown;+ const authored = rawExecute as (+ toolInput: unknown,+ ctx: unknown,+ task?: Parameters<NonNullable<HarnessToolDefinition["execute"]>>[2],+ ) => unknown;return createToolExecuteWithAuth({ execute: authored, scope });}diff --git a/packages/eve/src/execution/tasks/child/workflow.ts b/packages/eve/src/execution/tasks/child/workflow.tsindex d039e6f5f..93c1510a9 100644--- a/packages/eve/src/execution/tasks/child/workflow.ts+++ b/packages/eve/src/execution/tasks/child/workflow.ts@@ -166,7 +166,7 @@ export async function taskRunWorkflow(input: TaskRunWorkflowInput): Promise<voidcontinue;}const result = applyTaskTransition(view, command);- if (result.outcome !== "accepted") continue;+ if (result.action !== "accepted") continue;const becameTerminal =!isTerminalTaskStatus(view.status) && isTerminalTaskStatus(result.view.status);const becameReady = !isReadyTaskStatus(view.status) && isReadyTaskStatus(result.view.status);diff --git a/packages/eve/src/execution/tasks/parent/agent-views.ts b/packages/eve/src/execution/tasks/parent/agent-views.tsindex 1e52f069e..61f1cc606 100644--- a/packages/eve/src/execution/tasks/parent/agent-views.ts+++ b/packages/eve/src/execution/tasks/parent/agent-views.ts@@ -5,6 +5,7 @@ import { resolveAgentsAnnouncement, type AgentView } from "#harness/handles/promimport { formatAgentStatus, getAgentHandleStore } from "#harness/handles/store.js";import { readTaskViews } from "#execution/tasks/parent/control-shared.js";import { getSessionTaskIndex } from "#tasks/session-index.js";+import { readSubagentTaskMetadata } from "#tasks/types.js";/** Derives model-visible task-agent availability from authoritative task views. */export async function readTaskAgentViews(session: HarnessSession): Promise<readonly AgentView[]> {@@ -17,8 +18,10 @@ export async function readTaskAgentViews(session: HarnessSession): Promise<readoconst 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]);+ const metadata = readSubagentTaskMetadata(view);+ if (metadata === undefined) continue;+ const current = byAgent.get(metadata.agentId) ?? [];+ byAgent.set(metadata.agentId, [...current, view]);}return addresses.map((address) => {diff --git a/packages/eve/src/execution/tasks/parent/control-shared.ts b/packages/eve/src/execution/tasks/parent/control-shared.tsindex be1e7b6fb..ad475e3e7 100644--- a/packages/eve/src/execution/tasks/parent/control-shared.ts+++ b/packages/eve/src/execution/tasks/parent/control-shared.ts@@ -9,7 +9,7 @@ import {getSessionTaskIndex,type SessionTaskIndexEntry,} from "#tasks/session-index.js";-import type { TaskView } from "#tasks/types.js";+import { readSubagentTaskMetadata, type TaskView } from "#tasks/types.js";/*** Result and lookup helpers shared by the task-control executors@@ -59,11 +59,17 @@ export async function readTaskView(entry: SessionTaskIndexEntry): Promise<TaskVi/** The placeholder view for a run that has not published anything yet. */function createPendingTaskView(entry: SessionTaskIndexEntry): TaskView {- return {+ const view: TaskView = {metadata: entry.metadata,status: "working",taskId: entry.taskId,};++ if (entry.executor === undefined) {+ return view;+ }++ return { ...view, executor: { binding: entry.executor } };}/** Finds the persistent address record for one task-owned agent. */@@ -86,7 +92,7 @@ export async function findActiveTaskForAgent(parentStepIndex?: number,): Promise<{ readonly entry: SessionTaskIndexEntry; readonly view: TaskView } | undefined> {const entries = getSessionTaskIndex(session.state).filter(- (entry) => entry.metadata.agentId === agentId,+ (entry) => readSubagentTaskMetadata(entry)?.agentId === agentId,);const views = await readTaskViews(entries);const active = entries.flatMap((entry, index) => {diff --git a/packages/eve/src/execution/tasks/parent/delegate.ts b/packages/eve/src/execution/tasks/parent/delegate.tsindex 45485e90a..1fd92a727 100644--- a/packages/eve/src/execution/tasks/parent/delegate.ts+++ b/packages/eve/src/execution/tasks/parent/delegate.ts@@ -17,21 +17,32 @@ 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 type { TaskExecutorBinding } from "#shared/tool-task.js";import { recordSessionTask } from "#tasks/session-index.js";import { deriveTaskInboxToken, deriveTaskId } from "#tasks/task-id.js";-import { isTerminalTaskStatus, type TaskMetadata } from "#tasks/types.js";+import {+ createSubagentTaskMetadata,+ isTerminalTaskStatus,+ readSubagentTaskMetadata,+ type DurableTaskMetadata,+} from "#tasks/types.js";-/** A prepared delegated task: identity plus its started durable run. */-export interface DelegatedTask {+/** A prepared background task: identity plus its started durable run. */+export interface BackgroundTask {readonly taskInboxToken: string;readonly createdByStepIndex?: number;readonly createdByTurnId: string;- readonly metadata: TaskMetadata;- readonly operationId: string;+ readonly executor?: TaskExecutorBinding;+ readonly metadata: DurableTaskMetadata;readonly taskId: string;readonly taskRunId: string;}+/** A subagent task also carries its deterministic agent-handle operation. */+export interface DelegatedTask extends BackgroundTask {+ readonly operationId: string;+}+/*** Creates the durable task record for one delegated subagent call,* before the child dispatch side effect. The task must exist first so@@ -48,6 +59,37 @@ export async function beginDelegatedTask(input: {readonly parentTurnId: string;readonly session: RuntimeSession;}): Promise<DelegatedTask> {+ const task = await beginBackgroundTask({+ callId: input.callId,+ metadata: createSubagentTaskMetadata({+ agentId: input.agentId,+ mode: input.mode,+ name: input.name,+ }),+ parentSessionId: input.parentSessionId,+ parentStepIndex: input.parentStepIndex,+ parentTurnId: input.parentTurnId,+ session: input.session,+ });+ return {+ ...task,+ operationId: deriveAgentOperationId({+ callId: input.callId,+ parentSessionId: input.parentSessionId,+ parentTurnId: input.parentTurnId,+ }),+ };+}++/** Creates a replay-stable task run before a background tool starts external work. */+export async function beginBackgroundTask(input: {+ readonly callId: string;+ readonly metadata: DurableTaskMetadata;+ readonly parentSessionId: string;+ readonly parentStepIndex?: number;+ readonly parentTurnId: string;+ readonly session: RuntimeSession;+}): Promise<BackgroundTask> {const taskId = deriveTaskId({callId: input.callId,parentSessionId: input.parentSessionId,@@ -57,21 +99,10 @@ export async function beginDelegatedTask(input: {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,+ metadata: input.metadata,status: "working",taskId,},@@ -82,8 +113,7 @@ export async function beginDelegatedTask(input: {taskInboxToken,createdByStepIndex: input.parentStepIndex ?? 0,createdByTurnId: input.parentTurnId,- metadata,- operationId,+ metadata: input.metadata,taskId,taskRunId: owner.runId,};@@ -101,8 +131,12 @@ export async function settleDelegatedDispatch(input: {readonly subagentName: string;readonly task: DelegatedTask;}): Promise<{ readonly receipt: RuntimeSubagentChildResult; readonly session: RuntimeSession }> {+ const metadata = readSubagentTaskMetadata(input.task);+ if (metadata === undefined) {+ throw new Error(`Task "${input.task.taskId}" is not a subagent task.`);+ }const receiptOutput = {- agentId: input.task.metadata.agentId,+ agentId: metadata.agentId,status: "working" as const,taskId: input.task.taskId,};@@ -173,7 +207,7 @@ export async function failDelegatedDispatch(input: {/** Silently terminates a task whose child dispatch failed before parent indexing. */export async function rejectDelegatedDispatch(input: {readonly error: JsonValue;- readonly task: DelegatedTask;+ readonly task: BackgroundTask;}): Promise<void> {await sendTaskCommand({command: { data: input.error, kind: "reject-dispatch" },diff --git a/packages/eve/src/execution/tasks/parent/dispatch.ts b/packages/eve/src/execution/tasks/parent/dispatch.tsindex 1874dcd94..be078b0e1 100644--- a/packages/eve/src/execution/tasks/parent/dispatch.ts+++ b/packages/eve/src/execution/tasks/parent/dispatch.ts@@ -29,7 +29,7 @@ import {TASK_UPDATE_TOOL_NAME,} from "#runtime/framework-tools/tasks.js";import type { SessionTaskIndexEntry } from "#tasks/session-index.js";-import { isTerminalTaskStatus, type TaskView } from "#tasks/types.js";+import { isTerminalTaskStatus, readSubagentTaskMetadata, type TaskView } from "#tasks/types.js";const log = createLogger("execution.tasks.dispatch");@@ -150,7 +150,9 @@ async function propagateTaskCancel(input: {readonly session: RuntimeSession;readonly view: TaskView;}): Promise<void> {- const handle = findTaskAgentAddress(input.session, input.view.metadata.agentId);+ 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;diff --git a/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts b/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.tsindex 16057d797..3c96e3ba4 100644--- a/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts+++ b/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts@@ -14,7 +14,7 @@ import { removeTaskAgentAddressFromState } from "#harness/handles/transitions.jsimport { 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";+import { isTerminalTaskStatus, readSubagentTaskMetadata, type TaskView } from "#tasks/types.js";/** Validates and durably records one task-owned child HITL route batch. */export async function recordTaskInputRequestStep(input: {@@ -34,9 +34,10 @@ export async function recordTaskInputRequestStep(input: {const durableSession = await readDurableSession(input.sessionState);const entry = findSessionTaskEntry(durableSession.state, input.taskId);+ const entryMetadata = entry === undefined ? undefined : readSubagentTaskMetadata(entry);const handle = (getAgentHandleStore(durableSession.state)?.handles ?? []).find((candidate) =>- candidate.phase === "addressed" && candidate.identity.id === entry?.metadata.agentId,+ candidate.phase === "addressed" && candidate.identity.id === entryMetadata?.agentId,);if (entry === undefined ||@@ -50,6 +51,7 @@ export async function recordTaskInputRequestStep(input: {// 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 viewMetadata = view === undefined ? undefined : readSubagentTaskMetadata(view);const eventRequestIds = input.hookPayload.event.requests.map((request) => request.requestId);const viewRequestIds =view?.inputRequests?.map((request) =>@@ -60,8 +62,8 @@ export async function recordTaskInputRequestStep(input: {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 ||+ viewMetadata?.mode !== (handle.address.kind === "agent/remote" ? "remote" : "local") ||+ viewMetadata.agentId !== entryMetadata?.agentId ||view.executor?.childSessionId !== input.hookPayload.childSessionId ||new Set(eventRequestIds).size !== eventRequestIds.length ||eventRequestIds.length !== viewRequestIds.length ||@@ -140,9 +142,11 @@ export async function acceptTaskAuthorizationEventStep(input: {const durableSession = await readDurableSession(input.sessionState);const entry = findSessionTaskEntry(durableSession.state, input.taskId);if (entry === undefined) return false;+ const entryMetadata = readSubagentTaskMetadata(entry);+ if (entryMetadata === undefined) return false;const handle = (getAgentHandleStore(durableSession.state)?.handles ?? []).find((candidate) =>- candidate.phase === "addressed" && candidate.identity.id === entry.metadata.agentId,+ candidate.phase === "addressed" && candidate.identity.id === entryMetadata.agentId,);if (handle?.phase !== "addressed" ||@@ -151,11 +155,12 @@ export async function acceptTaskAuthorizationEventStep(input: {return false;}const view = await readLatestTaskView({ taskRunId: entry.taskRunId });+ const viewMetadata = view === undefined ? undefined : readSubagentTaskMetadata(view);return (view !== undefined &&!isTerminalTaskStatus(view.status) &&view.executor?.childSessionId === input.hookPayload.childSessionId &&- view.metadata.agentId === entry.metadata.agentId+ viewMetadata?.agentId === entryMetadata.agentId);}@@ -171,7 +176,10 @@ export async function recordTerminalTaskViewsStep(input: {for (const view of input.views) {state = cacheTerminalTaskView(state, view);if (view.executor?.lifecycle === "terminal") {- state = removeTaskAgentAddressFromState(state, view.metadata.agentId);+ const metadata = readSubagentTaskMetadata(view);+ if (metadata !== undefined) {+ state = removeTaskAgentAddressFromState(state, metadata.agentId);+ }}}if (state === durableSession.state) return input.sessionState;diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.test.ts b/packages/eve/src/execution/tasks/parent/tool-execution.test.tsnew file mode 100644index 000000000..1eecc8f54--- /dev/null+++ b/packages/eve/src/execution/tasks/parent/tool-execution.test.ts@@ -0,0 +1,458 @@+import { generateText } from "ai";+import { MockLanguageModelV4 } from "ai/test";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { z } from "#compiled/zod/index.js";+import { ContextContainer } from "#context/container.js";+import { AuthKey, SessionIdKey } from "#context/keys.js";+import { runStep } from "#context/run-step.js";+import { createToolExecuteWithAuth } from "#execution/tool-auth.js";+import { backgroundToolExecutionProvider } from "#execution/tasks/parent/tool-execution.js";+import { setHarnessEmissionState } from "#harness/emission.js";+import { isAuthorizationPendingModelOutput, requestAuthorization } from "#harness/authorization.js";+import type { HarnessToolDefinition } from "#harness/execute-tool.js";+import { buildToolSet } from "#harness/tools.js";+import type { HarnessSession } from "#harness/types.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";++const mocks = vi.hoisted(() => ({+ beginBackgroundTask: vi.fn(),+ rejectDelegatedDispatch: vi.fn(),+ sendTaskCommand: vi.fn(),+}));++vi.mock("#execution/tasks/parent/delegate.js", async (importOriginal) => ({+ ...(await importOriginal<typeof import("#execution/tasks/parent/delegate.js")>()),+ beginBackgroundTask: mocks.beginBackgroundTask,+ rejectDelegatedDispatch: mocks.rejectDelegatedDispatch,+}));+vi.mock("#execution/tasks/parent/run-parent.js", async (importOriginal) => ({+ ...(await importOriginal<typeof import("#execution/tasks/parent/run-parent.js")>()),+ sendTaskCommand: mocks.sendTaskCommand,+}));++const usage = {+ inputTokens: { cacheRead: undefined, cacheWrite: undefined, noCache: 1, total: 1 },+ outputTokens: { reasoning: undefined, text: 1, total: 1 },+};++describe("background tool execution", () => {+ beforeEach(() => {+ mocks.beginBackgroundTask.mockReset();+ mocks.rejectDelegatedDispatch.mockReset();+ mocks.sendTaskCommand.mockReset();+ });++ it("runs a non-subagent defineTool through the generic durable task lifecycle", async () => {+ mocks.beginBackgroundTask.mockImplementation(+ async ({ callId }: { readonly callId: string }) => ({+ createdByStepIndex: 0,+ createdByTurnId: "turn-1",+ metadata: { kind: "tool", name: "export" },+ taskId: `task-${callId}`,+ taskInboxToken: `inbox-${callId}`,+ taskRunId: `run-${callId}`,+ }),+ );+ mocks.sendTaskCommand.mockResolvedValue("delivered");+ let releaseSiblingExecutors: (() => void) | undefined;+ const siblingExecutorsStarted = new Promise<void>((resolve) => {+ releaseSiblingExecutors = resolve;+ });+ const startedQueries: string[] = [];+ const observedBatchSizes: number[] = [];++ const definition = defineTool({+ description: "Start an external export.",+ execution: "background",+ inputSchema: z.strictObject({ query: z.string() }),+ async execute(input: { readonly query: string }, _ctx: ToolContext, background: TaskExec) {+ startedQueries.push(input.query);+ observedBatchSizes.push(background.batch.length);+ if (startedQueries.length === 2) releaseSiblingExecutors?.();+ await siblingExecutorsStarted;+ return background.delegated({+ executor: { data: { exportId: input.query }, kind: "export" },+ receipt: { exportId: input.query },+ });+ },+ });+ const tool: HarnessToolDefinition = {+ description: definition.description,+ execute: createToolExecuteWithAuth({+ execute: definition.execute,+ execution: definition.execution,+ scope: "export",+ }),+ execution: definition.execution,+ inputSchema: toInputSchema(definition.inputSchema),+ name: "export",+ };+ const model = new MockLanguageModelV4({+ doGenerate: [+ {+ content: [+ {+ input: JSON.stringify({ query: "export-1" }),+ toolCallId: "call-export-1",+ toolName: "export",+ type: "tool-call",+ },+ {+ input: JSON.stringify({ query: "export-2" }),+ toolCallId: "call-export-2",+ toolName: "export",+ type: "tool-call",+ },+ ],+ finishReason: { raw: undefined, unified: "tool-calls" },+ usage,+ warnings: [],+ },+ {+ content: [+ {+ input: JSON.stringify({ query: "export-3" }),+ toolCallId: "call-export-3",+ toolName: "export",+ type: "tool-call",+ },+ ],+ finishReason: { raw: undefined, unified: "tool-calls" },+ usage,+ 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 ctx = new ContextContainer();+ ctx.set(AuthKey, null);+ ctx.set(SessionIdKey, session.sessionId);++ const generated: Awaited<ReturnType<typeof generateText>>[] = [];+ const result = await runStep(+ ctx,+ session,+ async (current) => {+ generated.push(+ await generateText({+ model,+ prompt: "Start two exports.",+ tools: buildToolSet({ tools: new Map([[tool.name, tool]]) }),+ }),+ await generateText({+ model,+ prompt: "Start one more export.",+ tools: buildToolSet({ tools: new Map([[tool.name, tool]]) }),+ }),+ );+ return { next: null, session: current };+ },+ [backgroundToolExecutionProvider],+ );++ expect(startedQueries).toEqual(["export-1", "export-2", "export-3"]);+ expect(observedBatchSizes).toEqual([2, 2, 1]);+ expect(generated.flatMap((result) => result.toolResults)).toEqual(+ expect.arrayContaining(+ ["export-1", "export-2", "export-3"].map((exportId, index) =>+ expect.objectContaining({+ output: {+ exportId,+ status: "working",+ taskId: `task-call-export-${index + 1}`,+ },+ toolName: "export",+ }),+ ),+ ),+ );+ expect(result.backgroundTasks).toHaveLength(3);+ expect(getSessionTaskIndex(result.session.state)).toEqual(+ expect.arrayContaining(+ ["export-1", "export-2", "export-3"].map((exportId, index) =>+ expect.objectContaining({+ executor: { data: { exportId }, kind: "export" },+ metadata: { kind: "tool", name: "export" },+ taskId: `task-call-export-${index + 1}`,+ }),+ ),+ ),+ );+ expect(mocks.sendTaskCommand).toHaveBeenCalledTimes(3);+ expect(mocks.rejectDelegatedDispatch).not.toHaveBeenCalled();+ });++ it("send delivers terminal commands after delegation and rejects once the task is terminal", async () => {+ const task = {+ createdByStepIndex: 0,+ createdByTurnId: "turn-1",+ metadata: { kind: "tool", name: "export" },+ taskId: "task-export",+ taskInboxToken: "inbox-export",+ taskRunId: "run-export",+ } as const;+ mocks.beginBackgroundTask.mockResolvedValue(task);+ mocks.sendTaskCommand.mockResolvedValue("delivered");+ let background: TaskExec | undefined;+ const definition = defineTool({+ description: "Start an external export.",+ execution: "background",+ inputSchema: z.strictObject({ query: z.string() }),+ execute(input: { readonly query: string }, _ctx: ToolContext, taskExec: TaskExec) {+ background = taskExec;+ return taskExec.delegated({+ executor: { data: { exportId: input.query }, kind: "export" },+ receipt: { exportId: input.query },+ });+ },+ });+ const tool: HarnessToolDefinition = {+ description: definition.description,+ execute: createToolExecuteWithAuth({+ execute: definition.execute,+ execution: definition.execution,+ scope: "export",+ }),+ execution: definition.execution,+ inputSchema: toInputSchema(definition.inputSchema),+ name: "export",+ };+ const model = new MockLanguageModelV4({+ doGenerate: {+ content: [+ {+ input: JSON.stringify({ query: "customers" }),+ toolCallId: "call-export",+ toolName: "export",+ type: "tool-call",+ },+ ],+ finishReason: { raw: undefined, unified: "tool-calls" },+ usage,+ 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 ctx = new ContextContainer();+ ctx.set(AuthKey, null);+ ctx.set(SessionIdKey, session.sessionId);++ await runStep(+ ctx,+ session,+ async (current) => {+ await generateText({+ model,+ prompt: "Start the export.",+ tools: buildToolSet({ tools: new Map([[tool.name, tool]]) }),+ });+ return { next: null, session: current };+ },+ [backgroundToolExecutionProvider],+ );++ expect(background).toBeDefined();+ await background!.send({ data: { rows: 10 }, kind: "complete" });+ expect(mocks.sendTaskCommand).toHaveBeenLastCalledWith({+ command: { data: { rows: 10 }, kind: "complete" },+ taskInboxToken: "inbox-export",+ });++ mocks.sendTaskCommand.mockResolvedValue("unreachable");+ await expect(background!.send({ kind: "cancel" })).rejects.toThrow(+ 'Task run "task-export" did not accept "cancel".',+ );+ });++ it("compensates a delegated task when the parent step fails", async () => {+ const task = {+ createdByStepIndex: 0,+ createdByTurnId: "turn-1",+ metadata: { kind: "tool", name: "export" },+ taskId: "task-export",+ taskInboxToken: "inbox-export",+ taskRunId: "run-export",+ } as const;+ mocks.beginBackgroundTask.mockResolvedValue(task);+ mocks.sendTaskCommand.mockResolvedValue("delivered");+ const definition = defineTool({+ description: "Start an external export.",+ execution: "background",+ inputSchema: z.strictObject({ query: z.string() }),+ execute(input: { readonly query: string }, _ctx: ToolContext, background: TaskExec) {+ return background.delegated({+ executor: { data: { exportId: input.query }, kind: "export" },+ receipt: { exportId: input.query },+ });+ },+ });+ const tool: HarnessToolDefinition = {+ description: definition.description,+ execute: createToolExecuteWithAuth({+ execute: definition.execute,+ execution: definition.execution,+ scope: "export",+ }),+ execution: definition.execution,+ inputSchema: toInputSchema(definition.inputSchema),+ name: "export",+ };+ const model = new MockLanguageModelV4({+ doGenerate: {+ content: [+ {+ input: JSON.stringify({ query: "customers" }),+ toolCallId: "call-export",+ toolName: "export",+ type: "tool-call",+ },+ ],+ finishReason: { raw: undefined, unified: "tool-calls" },+ usage,+ 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 ctx = new ContextContainer();+ ctx.set(AuthKey, null);+ ctx.set(SessionIdKey, session.sessionId);++ await expect(+ runStep(+ ctx,+ session,+ async () => {+ await generateText({+ model,+ prompt: "Start the export.",+ tools: buildToolSet({ tools: new Map([[tool.name, tool]]) }),+ });+ throw new Error("parent step failed");+ },+ [backgroundToolExecutionProvider],+ ),+ ).rejects.toThrow("parent step failed");++ expect(mocks.rejectDelegatedDispatch).toHaveBeenCalledWith({+ error: { code: "PARENT_STEP_FAILED", message: "parent step failed" },+ task: {+ ...task,+ executor: { data: { exportId: "customers" }, kind: "export" },+ },+ });+ expect(getSessionTaskIndex(session.state)).toEqual([]);+ });++ it("parks authorization without committing the provisional task", async () => {+ const task = {+ createdByStepIndex: 0,+ createdByTurnId: "turn-1",+ metadata: { kind: "tool", name: "export" },+ taskId: "task-export",+ taskInboxToken: "inbox-export",+ taskRunId: "run-export",+ } as const;+ mocks.beginBackgroundTask.mockResolvedValue(task);+ mocks.rejectDelegatedDispatch.mockResolvedValue(undefined);+ const signal = requestAuthorization([+ {+ challenge: { url: "https://idp.example/authorize" },+ hookUrl: "https://app.example/callback",+ name: "exports",+ },+ ]);+ const tool: HarnessToolDefinition = {+ description: "Start an authorized export.",+ execute: async () => signal,+ execution: "background",+ inputSchema: z.strictObject({}),+ name: "export",+ };+ const model = new MockLanguageModelV4({+ doGenerate: {+ content: [+ {+ input: "{}",+ toolCallId: "call-export",+ toolName: "export",+ type: "tool-call",+ },+ ],+ finishReason: { raw: undefined, unified: "tool-calls" },+ usage,+ 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 ctx = new ContextContainer();+ ctx.set(AuthKey, null);+ ctx.set(SessionIdKey, session.sessionId);+ let output: unknown;++ const result = await runStep(+ ctx,+ session,+ async (current) => {+ const generated = await generateText({+ model,+ prompt: "Start the export.",+ tools: buildToolSet({ tools: new Map([[tool.name, tool]]) }),+ });+ output = generated.toolResults[0]?.output;+ return { next: null, session: current };+ },+ [backgroundToolExecutionProvider],+ );++ expect(isAuthorizationPendingModelOutput(output)).toBe(true);+ expect(result.backgroundTasks).toBeUndefined();+ expect(getSessionTaskIndex(result.session.state)).toEqual([]);+ expect(mocks.sendTaskCommand).not.toHaveBeenCalled();+ expect(mocks.rejectDelegatedDispatch).toHaveBeenCalledWith({+ error: {+ code: "PARENT_STEP_FAILED",+ message: "Background tool execution did not delegate or complete its task.",+ },+ task,+ });+ });+});diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.ts b/packages/eve/src/execution/tasks/parent/tool-execution.tsnew file mode 100644index 000000000..994bc1858--- /dev/null+++ b/packages/eve/src/execution/tasks/parent/tool-execution.ts@@ -0,0 +1,300 @@+import type { ContextContainer } from "#context/container.js";+import { loadContext } from "#context/container.js";+import type { FrameworkContextProvider } from "#context/provider.js";+import { runStep } from "#context/run-step.js";+import { CallbackBaseUrlKey } from "#harness/authorization.js";+import { isAuthorizationSignal } from "#harness/authorization.js";+import { activeTurnId } from "#harness/active-turn-id.js";+import { getHarnessEmissionState } from "#harness/emission.js";+import { isTurnCancellation } from "#harness/turn-cancellation.js";+import type { HarnessSession, StepResult } from "#harness/types.js";+import {+ BackgroundToolExecutorKey,+ type BackgroundExecutableTool,+ type BackgroundToolCallBatch,+ type BackgroundToolExecutor,+} from "#harness/background-tools.js";+import { createEveCallbackRoutePath } from "#protocol/routes.js";+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 { recordSessionTask } from "#tasks/session-index.js";+import { createWorkflowCallbackUrl } from "#execution/workflow-callback-url.js";+import {+ beginBackgroundTask,+ rejectDelegatedDispatch,+ type BackgroundTask,+} from "#execution/tasks/parent/delegate.js";+import { sendTaskCommand } from "#execution/tasks/parent/run-parent.js";++interface BackgroundToolExecutionRecord {+ settled: boolean;+ task?: BackgroundTask;+}++interface BackgroundToolStepResult {+ readonly backgroundTaskSession: HarnessSession;+ readonly backgroundTasks: NonNullable<StepResult["backgroundTasks"]>;+}++export function runBackgroundStep(+ ctx: ContextContainer,+ session: HarnessSession,+ callback: (session: HarnessSession) => Promise<StepResult>,+): Promise<StepResult> {+ return runStep(ctx, session, callback, [backgroundToolExecutionProvider]);+}++/**+ * Makes background tool work transactional with the harness step.+ *+ * Concretely: when the model calls a background tool (e.g. a subagent spawn),+ * the tool does real external work mid-step — it creates a task run and+ * delivers commands to its inbox — while the step itself can still fail. This+ * provider scopes that work to the step so it either lands with the step or+ * is compensated with it.+ *+ * Lifetime: one {@link BackgroundToolExecutionScope} per step. `create` runs+ * before the authored callback; exactly one of `commit` or `rollback` settles+ * the scope afterwards; `decorateStepResult` runs last, only after a+ * successful commit. Nothing survives the step except retained tasks (below).+ *+ * - `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.+ * - `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}+ * instead of killed.+ * - `decorateStepResult` — attaches `backgroundTasks` and+ * `backgroundTaskSession` to the {@link StepResult} so the turn loop keeps+ * tracking the spawned tasks after the step returns.+ */+export const backgroundToolExecutionProvider: FrameworkContextProvider<BackgroundToolExecutor> = {+ key: BackgroundToolExecutorKey,+ create(_ctx, session) {+ return { value: new BackgroundToolExecutionScope(session) };+ },+ async commit(executor, session) {+ return await requireExecutionScope(executor).commit(session);+ },+ async rollback(executor, cause) {+ await requireExecutionScope(executor).rollback(cause);+ },+ decorateStepResult(executor, result) {+ return requireExecutionScope(executor).decorate(result);+ },+};++/**+ * 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+ * 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.+ */+export function readRetainedBackgroundToolResult(+ ctx: ContextContainer,+): BackgroundToolStepResult | undefined {+ const executor = ctx.get(BackgroundToolExecutorKey);+ return executor instanceof BackgroundToolExecutionScope ? executor.retainedResult() : undefined;+}++class BackgroundToolExecutionScope implements BackgroundToolExecutor {+ private readonly executions = new Map<string, Promise<unknown>>();+ private readonly records: BackgroundToolExecutionRecord[] = [];+ private retained = false;++ private readonly initialSession: HarnessSession;++ constructor(initialSession: HarnessSession) {+ this.initialSession = initialSession;+ }++ execute(input: {+ readonly batch: BackgroundToolCallBatch;+ readonly definition: BackgroundExecutableTool;+ readonly options: ToolExecuteOptions;+ readonly toolInput: unknown;+ }): Promise<unknown> {+ const existing = this.executions.get(input.options.toolCallId);+ if (existing !== undefined) return existing;+ if (!input.batch.calls.some((call) => call.callId === input.options.toolCallId)) {+ throw new Error(+ `Background tool call "${input.options.toolCallId}" was not registered before execution.`,+ );+ }+ const execution = this.start(input);+ this.executions.set(input.options.toolCallId, execution);+ return execution;+ }++ async commit(session: HarnessSession): Promise<HarnessSession> {+ const incomplete = this.records.filter((record) => !record.settled);+ if (incomplete.length > 0) {+ await compensateBackgroundToolExecution(+ incomplete,+ new Error("Background tool execution did not delegate or complete its task."),+ );+ }+ return this.apply(session);+ }++ decorate(result: StepResult): StepResult {+ const fields = this.resultFields();+ return fields === undefined ? result : { ...result, ...fields };+ }++ async rollback(cause: unknown): Promise<void> {+ const settled = this.records.filter((record) => record.settled);+ const incomplete = this.records.filter((record) => !record.settled);+ if (incomplete.length > 0) {+ await compensateBackgroundToolExecution(incomplete, cause);+ }+ if (settled.length === 0) return;+ // Cancellation must not compensate settled records: their tasks are+ // already running. Retain them for readRetainedBackgroundToolResult.+ if (isTurnCancellation(cause)) {+ this.retained = true;+ return;+ }+ await compensateBackgroundToolExecution(settled, cause);+ }++ retainedResult(): BackgroundToolStepResult | undefined {+ return this.retained ? this.resultFields() : undefined;+ }++ private apply(session: HarnessSession): HarnessSession {+ let next = session;+ for (const record of this.records) {+ if (!record.settled || record.task === undefined) continue;+ next = recordSessionTask(next, record.task);+ }+ return next;+ }++ private resultFields(): BackgroundToolStepResult | undefined {+ const tasks = this.records.flatMap((record) =>+ record.settled && record.task !== undefined ? [record.task] : [],+ );+ if (tasks.length === 0) return undefined;+ return {+ backgroundTaskSession: this.apply(this.initialSession),+ backgroundTasks: tasks.map(({ taskInboxToken, taskId, taskRunId }) => ({+ taskInboxToken,+ taskId,+ taskRunId,+ })),+ };+ }++ private async start(input: {+ readonly batch: BackgroundToolCallBatch;+ readonly definition: BackgroundExecutableTool;+ readonly options: ToolExecuteOptions;+ readonly toolInput: unknown;+ }): Promise<unknown> {+ const record: BackgroundToolExecutionRecord = { settled: false };+ this.records.push(record);+ const emission = getHarnessEmissionState(this.initialSession.state);+ const task = await beginBackgroundTask({+ callId: input.options.toolCallId,+ metadata: { kind: "tool", name: input.definition.name },+ parentSessionId: this.initialSession.sessionId,+ parentStepIndex: emission.stepIndex,+ parentTurnId: activeTurnId(emission),+ session: this.initialSession,+ });+ record.task = task;++ const callbackBaseUrl = loadContext().get(CallbackBaseUrlKey);+ const binding = {+ taskId: task.taskId,+ token: task.taskInboxToken,+ ...(callbackBaseUrl === undefined+ ? {}+ : {+ url: createWorkflowCallbackUrl(+ callbackBaseUrl,+ createEveCallbackRoutePath(task.taskInboxToken),+ ),+ }),+ };+ const taskExec: TaskExec = {+ batch: input.batch.calls,+ binding,+ delegated: ({ executor, receipt }) => createTaskDelegated({ binding, executor, receipt }),+ send: (command) => deliverTaskCommand(task, command),+ session: this.initialSession,+ task,+ };++ const output = input.definition.execute(input.toolInput, input.options, taskExec);+ if (isAsyncIterable(output)) {+ throw new Error("Background tools cannot return AsyncIterable output.");+ }+ const settled = await output;+ if (isAuthorizationSignal(settled)) return settled;+ if (isTaskDelegated(settled)) {+ await deliverTaskCommand(task, {+ executor: settled.executor,+ kind: "bind",+ });+ record.task = { ...task, executor: settled.executor };+ record.settled = true;+ return settled.receipt;+ }++ await deliverTaskCommand(task, { data: parseJsonValue(settled), kind: "complete" });+ record.settled = true;+ return settled;+ }+}++function requireExecutionScope(executor: BackgroundToolExecutor): BackgroundToolExecutionScope {+ if (!(executor instanceof BackgroundToolExecutionScope)) {+ throw new Error("The background tool executor is not owned by the task runtime.");+ }+ return executor;+}++async function deliverTaskCommand(+ task: BackgroundTask,+ command: Parameters<typeof sendTaskCommand>[0]["command"],+): Promise<void> {+ const outcome = await sendTaskCommand({ command, taskInboxToken: task.taskInboxToken });+ if (outcome !== "delivered") {+ throw new Error(`Task run "${task.taskId}" did not accept "${command.kind}".`);+ }+}++async function compensateBackgroundToolExecution(+ records: readonly BackgroundToolExecutionRecord[],+ cause: unknown,+): Promise<void> {+ const failures: unknown[] = [];+ for (const record of records.toReversed()) {+ if (record.task === undefined) continue;+ try {+ await rejectDelegatedDispatch({+ error: {+ code: "PARENT_STEP_FAILED",+ message: cause instanceof Error ? cause.message : String(cause),+ },+ task: record.task,+ });+ } catch (error) {+ failures.push(error);+ }+ }+ if (failures.length > 0) {+ throw new AggregateError(+ [cause, ...failures],+ "Background tool execution failed and its tasks could not all be compensated.",+ { cause },+ );+ }+}diff --git a/packages/eve/src/execution/tool-auth.ts b/packages/eve/src/execution/tool-auth.tsindex 52428fa14..877e4184f 100644--- a/packages/eve/src/execution/tool-auth.ts+++ b/packages/eve/src/execution/tool-auth.ts@@ -37,6 +37,7 @@ import {type ScopedAuthorization,} from "#runtime/connections/scoped-authorization.js";import type { ToolExecuteOptions } from "#shared/tool-definition.js";+import type { TaskExec } from "#shared/tool-task.js";import { isAsyncIterable } from "#shared/async-iterable.js";/**@@ -54,17 +55,34 @@ import { isAsyncIterable } from "#shared/async-iterable.js";* strategies rethrow the original error because they have no consent flow to* park on.*/-export function createToolExecuteWithAuth(input: {+type ToolExecuteWithAuthInput<TInput> = {readonly scope: string;- readonly execute: (toolInput: unknown, ctx: unknown) => unknown;-}): (toolInput: unknown, options: ToolExecuteOptions) => Promise<unknown> | AsyncIterable<unknown> {- const { scope, execute } = input;+} & (+ | {+ readonly execution: "background";+ readonly execute: (toolInput: TInput, ctx: ToolContext, task: TaskExec) => unknown;+ }+ | {+ readonly execution?: never;+ readonly execute: (toolInput: TInput, ctx: ToolContext, task?: TaskExec) => unknown;+ }+);++export function createToolExecuteWithAuth<TInput>(+ input: ToolExecuteWithAuthInput<TInput>,+): (+ toolInput: TInput,+ options: ToolExecuteOptions,+ task?: TaskExec,+) => Promise<unknown> | AsyncIterable<unknown> {+ const { scope } = input;// An async wrapper would turn an async generator into Promise<AsyncIterable>,// which the AI SDK treats as one non-serializable terminal output.return (- toolInput: unknown,+ toolInput: TInput,options: ToolExecuteOptions,+ task?: TaskExec,): Promise<unknown> | AsyncIterable<unknown> => {const justAuthorizedScopes = new Set<string>();const ctx = buildToolContext({@@ -75,7 +93,15 @@ export function createToolExecuteWithAuth(input: {});try {- const output = execute(toolInput, ctx);+ let output: unknown;+ if (input.execution === "background") {+ if (task === undefined) {+ throw new Error("Background tool execution requires a task runtime.");+ }+ output = input.execute(toolInput, ctx, task);+ } else {+ output = input.execute(toolInput, ctx, task);+ }if (isAsyncIterable(output)) {return handleToolIterableErrors(output);}diff --git a/packages/eve/src/execution/turn-workflow.test.ts b/packages/eve/src/execution/turn-workflow.test.tsindex 81c842d58..95d811704 100644--- a/packages/eve/src/execution/turn-workflow.test.ts+++ b/packages/eve/src/execution/turn-workflow.test.ts@@ -6,6 +6,7 @@ import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-stimport { dispatchRuntimeActionsStep } from "#execution/dispatch-runtime-actions-step.js";import { dispatchWorkflowRuntimeActionsStep } from "#execution/dispatch-workflow-runtime-actions-step.js";import type { DurableSessionState } from "#execution/durable-session-store.js";+import { acknowledgeDelegatedTasksStep } from "#execution/tasks/parent/delegate.js";import { runProxySubagentEventStep } from "#execution/subagent-event-proxy-step.js";import { turnWorkflow } from "#execution/turn-workflow.js";import {@@ -54,6 +55,10 @@ vi.mock("./cancel-descendant-turns-step.js", () => ({cancelDescendantTurnsStep: vi.fn(),}));+vi.mock("./tasks/parent/delegate.js", () => ({+ acknowledgeDelegatedTasksStep: vi.fn(),+}));+vi.mock("./workflow-callback-url.js", () => ({resolveWorkflowCallbackBaseUrl: vi.fn((metadataUrl: string) => metadataUrl),}));@@ -354,6 +359,39 @@ describe("turnWorkflow", () => {expect(resumeHookMock.mock.calls.filter((call) => call[1]?.kind === "turn-error")).toEqual([]);});+ it("commits and releases background tasks before settling a cancelled turn", async () => {+ const initialState = createSessionState({ continuationToken: "http:parent" });+ const backgroundState = createSessionState({ continuationToken: "http:parent:background" });+ const backgroundTasks = [+ {+ taskId: "task-1",+ taskInboxToken: "task-inbox-1",+ taskRunId: "task-run-1",+ },+ ];+ installInbox([]);+ vi.mocked(turnStep).mockResolvedValueOnce({+ action: "cancelled",+ backgroundTaskState: backgroundState,+ backgroundTasks,+ serializedContext: { state: "cancelled" },+ sessionState: initialState,+ });++ const { input } = createInput({+ driverCapabilities: { cancelledTurnSettle: true, turnInbox: true },+ mode: "task",+ sessionState: initialState,+ });+ await turnWorkflow(input);++ expect(acknowledgeDelegatedTasksStep).toHaveBeenCalledWith({ tasks: backgroundTasks });+ expect(cancelDescendantTurnsStep).toHaveBeenCalledWith({+ serializedContext: { state: "cancelled" },+ sessionState: backgroundState,+ });+ });+it("honors cancellation observed while a durable turn step returns", async () => {const sessionState = createSessionState();const sessionModel = {diff --git a/packages/eve/src/execution/turn-workflow.ts b/packages/eve/src/execution/turn-workflow.tsindex 928e2b7bf..05cf2986a 100644--- a/packages/eve/src/execution/turn-workflow.ts+++ b/packages/eve/src/execution/turn-workflow.ts@@ -101,11 +101,27 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {}while (true) {+ const beforeStep = {+ serializedContext: cursor.serializedContext,+ sessionState: cursor.sessionState,+ };const result = await turnStep(cursor.createStepInput(nextStepInput, cancellation?.signal));const pendingActionKeys =result.action === "dispatch-workflow-runtime-actions" || result.action === "park"? result.pendingRuntimeActionKeys: undefined;+ const hasBackgroundTasks = (result.backgroundTasks?.length ?? 0) > 0;++ if (hasBackgroundTasks) {+ if (result.backgroundTaskState === undefined) {+ throw new Error("Background tasks were returned without their committed session state.");+ }+ await cursor.adopt({+ serializedContext: beforeStep.serializedContext,+ sessionState: result.backgroundTaskState,+ });+ await acknowledgeDelegatedTasksStep({ tasks: result.backgroundTasks ?? [] });+ }// A cancel observed while the step was returning must still win: the// step may have missed the abort and completed normally. Pending@@ -113,18 +129,24 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {if (result.action === "cancelled") {// The cancelled step returns only the context carve-outs required by// the driver epilogue and later turns; adopt those before settling.- await cursor.adopt(result);+ await cursor.adopt({+ serializedContext: result.serializedContext,+ sessionState: cursor.sessionState,+ });await finishCancelledTurn({ bufferedDeliveries, cancellation, cursor });return;}- if (cancellation?.signal.aborted === true && pendingActionKeys === undefined) {+ if (+ cancellation?.signal.aborted === true &&+ (pendingActionKeys === undefined || hasBackgroundTasks)+ ) {// Some worlds cannot interrupt a running step, so it can complete// normally after the workflow observes cancellation. Roll that result// back except for a session model selected by its one-time preamble.await cursor.adopt({serializedContext: preserveSerializedSessionDynamicModelSelection(- cursor.serializedContext,+ beforeStep.serializedContext,result.serializedContext,),sessionState: cursor.sessionState,diff --git a/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v1.test.ts.snap b/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v1.test.ts.snapindex 696870747..a21ccccaa 100644--- a/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v1.test.ts.snap+++ b/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v1.test.ts.snap@@ -1,3 +1,3 @@// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html-exports[`session inbox wire v1 > pins the complete schema byte for byte 1`] = `"{"$schema":"https://json-schema.org/draft/2020-12/schema","oneOf":[{"additionalProperties":false,"properties":{"auth":{"anyOf":[{"additionalProperties":false,"properties":{"attributes":{"additionalProperties":{"anyOf":[{"type":"string"},{"items":{"type":"string"},"type":"array"}]},"propertyNames":{"type":"string"},"type":"object"},"authenticator":{"type":"string"},"issuer":{"type":"string"},"principalId":{"type":"string"},"principalType":{"type":"string"},"subject":{"type":"string"}},"required":["attributes","authenticator","principalId","principalType"],"type":"object"},{"type":"null"}]},"caller":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"replyTo":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"hook","type":"string"},"token":{"type":"string"}},"required":["kind","token"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"callback","type":"string"},"token":{"type":"string"},"url":{"type":"string"}},"required":["kind","token","url"],"type":"object"}]},"subagentName":{"type":"string"},"taskId":{"type":"string"}},"required":["callId","replyTo","subagentName"],"type":"object"},"deliveryMetadata":{"items":{"additionalProperties":false,"properties":{"channelKind":{"type":"string"},"channelName":{"type":"string"},"deliveryId":{"type":"string"},"payloadIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"requestId":{"type":"string"},"requestTraceContext":{"additionalProperties":false,"properties":{"spanId":{"type":"string"},"traceFlags":{"type":"number"},"traceId":{"type":"string"}},"required":["spanId","traceFlags","traceId"],"type":"object"}},"required":["channelKind","channelName","deliveryId","payloadIndex"],"type":"object"},"type":"array"},"kind":{"const":"deliver","type":"string"},"payload":{"additionalProperties":{},"properties":{"context":{"items":{"type":"string"},"type":"array"},"inputResponses":{"items":{"additionalProperties":false,"properties":{"optionId":{"type":"string"},"requestId":{"type":"string"},"text":{"type":"string"}},"required":["requestId"],"type":"object"},"type":"array"},"message":{"anyOf":[{"type":"string"},{"items":{"oneOf":[{"additionalProperties":false,"properties":{"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"text":{"type":"string"},"type":{"const":"text","type":"string"}},"required":["text","type"],"type":"object"},{"additionalProperties":false,"properties":{"image":{},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"image","type":"string"}},"required":["image","type"],"type":"object"},{"additionalProperties":false,"properties":{"data":{},"filename":{"type":"string"},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"file","type":"string"}},"required":["data","mediaType","type"],"type":"object"}]},"type":"array"}]},"outputSchema":{},"task":{"additionalProperties":false,"properties":{"authorizationEvents":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childSessionId":{"type":"string"},"event":{},"kind":{"const":"subagent-authorization-event","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"inputRequests":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childContinuationToken":{"type":"string"},"childSessionId":{"type":"string"},"event":{"additionalProperties":false,"properties":{"requests":{"items":{"additionalProperties":false,"properties":{"action":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"input":{},"kind":{"const":"tool-call","type":"string"},"toolName":{"type":"string"}},"required":["callId","input","kind","toolName"],"type":"object"},"allowFreeform":{"description":"Whether the user may answer with freeform text instead of selecting one of the provided options.","type":"boolean"},"display":{"description":"Rendering hint: the channel uses this to pick a UX treatment.","enum":["confirmation","select","text"],"type":"string"},"kind":{"description":"Framework-owned request source used to resolve, route, and render the response.","enum":["question","session-limit","tool-approval"],"type":"string"},"options":{"description":"Selectable answer options to present to the user.","items":{"additionalProperties":false,"properties":{"description":{"description":"Optional additional context for this option.","type":"string"},"id":{"description":"Stable identifier for the option.","type":"string"},"label":{"description":"User-facing label for the option.","type":"string"},"style":{"description":"Visual treatment hint for the option.","enum":["primary","danger","default"],"type":"string"}},"required":["id","label"],"type":"object"},"type":"array"},"prompt":{"description":"The prompt to present to the user.","type":"string"},"requestId":{"description":"Stable identifier for this request.","type":"string"}},"required":["action","kind","prompt","requestId"],"type":"object"},"type":"array"},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"turnId":{"type":"string"}},"required":["requests","sequence","stepIndex","turnId"],"type":"object"},"kind":{"const":"subagent-input-request","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childContinuationToken","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"views":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},"status":{"const":"working","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"inputRequests":{"items":{},"type":"array"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},"status":{"const":"input_required","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","inputRequests","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"result","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},"status":{"const":"completed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"error","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},"status":{"const":"failed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},"status":{"const":"cancelled","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"}]},"type":"array"}},"type":"object"}},"type":"object"},"payloads":{"items":{"additionalProperties":{},"properties":{"context":{"items":{"type":"string"},"type":"array"},"inputResponses":{"items":{"additionalProperties":false,"properties":{"optionId":{"type":"string"},"requestId":{"type":"string"},"text":{"type":"string"}},"required":["requestId"],"type":"object"},"type":"array"},"message":{"anyOf":[{"type":"string"},{"items":{"oneOf":[{"additionalProperties":false,"properties":{"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"text":{"type":"string"},"type":{"const":"text","type":"string"}},"required":["text","type"],"type":"object"},{"additionalProperties":false,"properties":{"image":{},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"image","type":"string"}},"required":["image","type"],"type":"object"},{"additionalProperties":false,"properties":{"data":{},"filename":{"type":"string"},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"file","type":"string"}},"required":["data","mediaType","type"],"type":"object"}]},"type":"array"}]},"outputSchema":{},"task":{"additionalProperties":false,"properties":{"authorizationEvents":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childSessionId":{"type":"string"},"event":{},"kind":{"const":"subagent-authorization-event","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"inputRequests":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childContinuationToken":{"type":"string"},"childSessionId":{"type":"string"},"event":{"additionalProperties":false,"properties":{"requests":{"items":{"additionalProperties":false,"properties":{"action":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"input":{},"kind":{"const":"tool-call","type":"string"},"toolName":{"type":"string"}},"required":["callId","input","kind","toolName"],"type":"object"},"allowFreeform":{"description":"Whether the user may answer with freeform text instead of selecting one of the provided options.","type":"boolean"},"display":{"description":"Rendering hint: the channel uses this to pick a UX treatment.","enum":["confirmation","select","text"],"type":"string"},"kind":{"description":"Framework-owned request source used to resolve, route, and render the response.","enum":["question","session-limit","tool-approval"],"type":"string"},"options":{"description":"Selectable answer options to present to the user.","items":{"additionalProperties":false,"properties":{"description":{"description":"Optional additional context for this option.","type":"string"},"id":{"description":"Stable identifier for the option.","type":"string"},"label":{"description":"User-facing label for the option.","type":"string"},"style":{"description":"Visual treatment hint for the option.","enum":["primary","danger","default"],"type":"string"}},"required":["id","label"],"type":"object"},"type":"array"},"prompt":{"description":"The prompt to present to the user.","type":"string"},"requestId":{"description":"Stable identifier for this request.","type":"string"}},"required":["action","kind","prompt","requestId"],"type":"object"},"type":"array"},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"turnId":{"type":"string"}},"required":["requests","sequence","stepIndex","turnId"],"type":"object"},"kind":{"const":"subagent-input-request","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childContinuationToken","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"views":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},"status":{"const":"working","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"inputRequests":{"items":{},"type":"array"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},"status":{"const":"input_required","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","inputRequests","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"result","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},"status":{"const":"completed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"error","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},"status":{"const":"failed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},"status":{"const":"cancelled","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"}]},"type":"array"}},"type":"object"}},"type":"object"},"type":"array"},"requestId":{"type":"string"},"taskDeliveryId":{"type":"string"},"turnPolicy":{"enum":["queue","steer"],"type":"string"},"version":{"const":1,"type":"number"}},"required":["kind","payloads","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"session-timeout","type":"string"},"version":{"const":1,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"clear","type":"string"},"version":{"const":1,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"compact","type":"string"},"version":{"const":1,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"reset","type":"string"},"reason":{"type":"string"},"version":{"const":1,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"cancel","type":"string"},"taskId":{"type":"string"},"turnId":{"type":"string"},"version":{"const":1,"type":"number"}},"required":["kind","version"],"type":"object"}]}"`;+exports[`session inbox wire v1 > pins the complete schema byte for byte 1`] = `"{"$schema":"https://json-schema.org/draft/2020-12/schema","oneOf":[{"additionalProperties":false,"properties":{"auth":{"anyOf":[{"additionalProperties":false,"properties":{"attributes":{"additionalProperties":{"anyOf":[{"type":"string"},{"items":{"type":"string"},"type":"array"}]},"propertyNames":{"type":"string"},"type":"object"},"authenticator":{"type":"string"},"issuer":{"type":"string"},"principalId":{"type":"string"},"principalType":{"type":"string"},"subject":{"type":"string"}},"required":["attributes","authenticator","principalId","principalType"],"type":"object"},{"type":"null"}]},"caller":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"replyTo":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"hook","type":"string"},"token":{"type":"string"}},"required":["kind","token"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"callback","type":"string"},"token":{"type":"string"},"url":{"type":"string"}},"required":["kind","token","url"],"type":"object"}]},"subagentName":{"type":"string"},"taskId":{"type":"string"}},"required":["callId","replyTo","subagentName"],"type":"object"},"deliveryMetadata":{"items":{"additionalProperties":false,"properties":{"channelKind":{"type":"string"},"channelName":{"type":"string"},"deliveryId":{"type":"string"},"payloadIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"requestId":{"type":"string"},"requestTraceContext":{"additionalProperties":false,"properties":{"spanId":{"type":"string"},"traceFlags":{"type":"number"},"traceId":{"type":"string"}},"required":["spanId","traceFlags","traceId"],"type":"object"}},"required":["channelKind","channelName","deliveryId","payloadIndex"],"type":"object"},"type":"array"},"kind":{"const":"deliver","type":"string"},"payload":{"additionalProperties":{},"properties":{"context":{"items":{"type":"string"},"type":"array"},"inputResponses":{"items":{"additionalProperties":false,"properties":{"optionId":{"type":"string"},"requestId":{"type":"string"},"text":{"type":"string"}},"required":["requestId"],"type":"object"},"type":"array"},"message":{"anyOf":[{"type":"string"},{"items":{"oneOf":[{"additionalProperties":false,"properties":{"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"text":{"type":"string"},"type":{"const":"text","type":"string"}},"required":["text","type"],"type":"object"},{"additionalProperties":false,"properties":{"image":{},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"image","type":"string"}},"required":["image","type"],"type":"object"},{"additionalProperties":false,"properties":{"data":{},"filename":{"type":"string"},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"file","type":"string"}},"required":["data","mediaType","type"],"type":"object"}]},"type":"array"}]},"outputSchema":{},"task":{"additionalProperties":false,"properties":{"authorizationEvents":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childSessionId":{"type":"string"},"event":{},"kind":{"const":"subagent-authorization-event","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"inputRequests":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childContinuationToken":{"type":"string"},"childSessionId":{"type":"string"},"event":{"additionalProperties":false,"properties":{"requests":{"items":{"additionalProperties":false,"properties":{"action":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"input":{},"kind":{"const":"tool-call","type":"string"},"toolName":{"type":"string"}},"required":["callId","input","kind","toolName"],"type":"object"},"allowFreeform":{"description":"Whether the user may answer with freeform text instead of selecting one of the provided options.","type":"boolean"},"display":{"description":"Rendering hint: the channel uses this to pick a UX treatment.","enum":["confirmation","select","text"],"type":"string"},"kind":{"description":"Framework-owned request source used to resolve, route, and render the response.","enum":["question","session-limit","tool-approval"],"type":"string"},"options":{"description":"Selectable answer options to present to the user.","items":{"additionalProperties":false,"properties":{"description":{"description":"Optional additional context for this option.","type":"string"},"id":{"description":"Stable identifier for the option.","type":"string"},"label":{"description":"User-facing label for the option.","type":"string"},"style":{"description":"Visual treatment hint for the option.","enum":["primary","danger","default"],"type":"string"}},"required":["id","label"],"type":"object"},"type":"array"},"prompt":{"description":"The prompt to present to the user.","type":"string"},"requestId":{"description":"Stable identifier for this request.","type":"string"}},"required":["action","kind","prompt","requestId"],"type":"object"},"type":"array"},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"turnId":{"type":"string"}},"required":["requests","sequence","stepIndex","turnId"],"type":"object"},"kind":{"const":"subagent-input-request","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childContinuationToken","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"views":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"working","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"inputRequests":{"items":{},"type":"array"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"input_required","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","inputRequests","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"result","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"completed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"error","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"failed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"cancelled","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"}]},"type":"array"}},"type":"object"}},"type":"object"},"payloads":{"items":{"additionalProperties":{},"properties":{"context":{"items":{"type":"string"},"type":"array"},"inputResponses":{"items":{"additionalProperties":false,"properties":{"optionId":{"type":"string"},"requestId":{"type":"string"},"text":{"type":"string"}},"required":["requestId"],"type":"object"},"type":"array"},"message":{"anyOf":[{"type":"string"},{"items":{"oneOf":[{"additionalProperties":false,"properties":{"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"text":{"type":"string"},"type":{"const":"text","type":"string"}},"required":["text","type"],"type":"object"},{"additionalProperties":false,"properties":{"image":{},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"image","type":"string"}},"required":["image","type"],"type":"object"},{"additionalProperties":false,"properties":{"data":{},"filename":{"type":"string"},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"file","type":"string"}},"required":["data","mediaType","type"],"type":"object"}]},"type":"array"}]},"outputSchema":{},"task":{"additionalProperties":false,"properties":{"authorizationEvents":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childSessionId":{"type":"string"},"event":{},"kind":{"const":"subagent-authorization-event","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"inputRequests":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childContinuationToken":{"type":"string"},"childSessionId":{"type":"string"},"event":{"additionalProperties":false,"properties":{"requests":{"items":{"additionalProperties":false,"properties":{"action":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"input":{},"kind":{"const":"tool-call","type":"string"},"toolName":{"type":"string"}},"required":["callId","input","kind","toolName"],"type":"object"},"allowFreeform":{"description":"Whether the user may answer with freeform text instead of selecting one of the provided options.","type":"boolean"},"display":{"description":"Rendering hint: the channel uses this to pick a UX treatment.","enum":["confirmation","select","text"],"type":"string"},"kind":{"description":"Framework-owned request source used to resolve, route, and render the response.","enum":["question","session-limit","tool-approval"],"type":"string"},"options":{"description":"Selectable answer options to present to the user.","items":{"additionalProperties":false,"properties":{"description":{"description":"Optional additional context for this option.","type":"string"},"id":{"description":"Stable identifier for the option.","type":"string"},"label":{"description":"User-facing label for the option.","type":"string"},"style":{"description":"Visual treatment hint for the option.","enum":["primary","danger","default"],"type":"string"}},"required":["id","label"],"type":"object"},"type":"array"},"prompt":{"description":"The prompt to present to the user.","type":"string"},"requestId":{"description":"Stable identifier for this request.","type":"string"}},"required":["action","kind","prompt","requestId"],"type":"object"},"type":"array"},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"turnId":{"type":"string"}},"required":["requests","sequence","stepIndex","turnId"],"type":"object"},"kind":{"const":"subagent-input-request","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childContinuationToken","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"views":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"working","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"inputRequests":{"items":{},"type":"array"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"input_required","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","inputRequests","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"result","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"completed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"error","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"failed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"cancelled","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"}]},"type":"array"}},"type":"object"}},"type":"object"},"type":"array"},"requestId":{"type":"string"},"taskDeliveryId":{"type":"string"},"turnPolicy":{"enum":["queue","steer"],"type":"string"},"version":{"const":1,"type":"number"}},"required":["kind","payloads","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"session-timeout","type":"string"},"version":{"const":1,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"clear","type":"string"},"version":{"const":1,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"compact","type":"string"},"version":{"const":1,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"reset","type":"string"},"reason":{"type":"string"},"version":{"const":1,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"cancel","type":"string"},"taskId":{"type":"string"},"turnId":{"type":"string"},"version":{"const":1,"type":"number"}},"required":["kind","version"],"type":"object"}]}"`;diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v1.test.ts b/packages/eve/src/execution/wire/session-inbox-wire.v1.test.tsindex c2349d610..d444e974b 100644--- a/packages/eve/src/execution/wire/session-inbox-wire.v1.test.ts+++ b/packages/eve/src/execution/wire/session-inbox-wire.v1.test.ts@@ -91,6 +91,18 @@ describe("session inbox wire v1", () => {status: "working" as const,taskId: "task-1",},+ {+ executor: {+ binding: {+ data: { agentId: "agent-2", mode: "local", name: "worker" },+ kind: "subagent",+ },+ },+ lastOutput: { data: "done", type: "result" as const },+ metadata: { kind: "tool", name: "worker" },+ status: "completed" as const,+ taskId: "task-2",+ },],};const wire = sessionInboxWireEncoder.encode(diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v1.ts b/packages/eve/src/execution/wire/session-inbox-wire.v1.tsindex e40f62ec4..e2b376c75 100644--- a/packages/eve/src/execution/wire/session-inbox-wire.v1.ts+++ b/packages/eve/src/execution/wire/session-inbox-wire.v1.ts@@ -83,16 +83,26 @@ const subagentAuthorizationEventHookPayloadSchema = zsubagentName: z.string(),}).strict();-const taskMetadataSchema = z- .object({- agentId: z.string(),- kind: z.literal("subagent"),- mode: z.enum(["local", "remote"]),- name: z.string(),- })- .strict();+const taskMetadataSchema = z.union([+ z+ .object({+ agentId: z.string(),+ kind: z.literal("subagent"),+ mode: z.enum(["local", "remote"]),+ name: z.string(),+ })+ .strict(),+ z.object({ kind: z.string(), name: z.string() }).strict(),+]);const taskExecutorSchema = z.object({+ binding: z+ .object({+ data: z.record(z.string(), jsonValueSchema),+ kind: z.string(),+ })+ .strict()+ .optional(),childSessionId: z.string().optional(),childTurnId: z.string().optional(),lifecycle: z.enum(["parked", "terminal"]).optional(),diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.tsindex bfb6f9dcc..6756c70d3 100644--- a/packages/eve/src/execution/workflow-steps.test.ts+++ b/packages/eve/src/execution/workflow-steps.test.ts@@ -562,12 +562,16 @@ describe("recordTaskInputRequestStep", () => {{taskInboxToken: "task-token",createdByTurnId: "turn-parent",- metadata: {- agentId: "agent-1",+ executor: {+ data: {+ agentId: "agent-1",+ childSessionId: "child-session",+ mode: "local",+ name: "research",+ },kind: "subagent",- mode: "local",- name: "research",},+ metadata: { kind: "tool", name: "research" },operationId: "operation-1",taskId: "task-1",taskRunId: "run-1",@@ -578,13 +582,19 @@ describe("recordTaskInputRequestStep", () => {});installSessionStoreMocks([session]);vi.mocked(readLatestTaskView).mockResolvedValue({- metadata: {- agentId: "agent-1",- kind: "subagent",- mode: "local",- name: "research",+ metadata: { kind: "tool", name: "research" },+ executor: {+ binding: {+ data: {+ agentId: "agent-1",+ childSessionId: "child-session",+ mode: "local",+ name: "research",+ },+ kind: "subagent",+ },+ childSessionId: "child-session",},- executor: { childSessionId: "child-session" },inputRequests: hookPayload.event.requests,status: "input_required",taskId: "task-1",diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.tsindex 41b32c8a5..bb49ff2d0 100644--- a/packages/eve/src/execution/workflow-steps.ts+++ b/packages/eve/src/execution/workflow-steps.ts@@ -22,13 +22,14 @@ import {import {AuthKey,CapabilitiesKey,+ HandleEventKey,ModeKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey,+ TasksEnabledKey,TurnTaskDeliveryKey,} from "#context/keys.js";import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";-import { runStep } from "#context/run-step.js";import { deserializeContext, serializeContext } from "#context/serialize.js";import {emitTurnPreamble,@@ -57,9 +58,9 @@ import {} from "#harness/workflow-runtime-action-state.js";import { getPendingWorkflowInterrupt } from "#harness/workflow-interrupt-state.js";import { getPendingRuntimeActionBatch } from "#harness/runtime-actions.js";-import type { HarnessSession, SettledTurn, StepInput, StepResult } from "#harness/types.js";+import type { HarnessSession, 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 { DurableStepResult } from "#execution/next-driver-action.js";import { getRuntimeActionRequestKey } from "#runtime/actions/keys.js";import {createAuthorizationCompletedEvent,@@ -78,14 +79,14 @@ import {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,- readDurableSession,-} from "#execution/durable-session-store.js";+import { createDurableSessionState, readDurableSession } 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 {+ readRetainedBackgroundToolResult,+ runBackgroundStep,+} from "#execution/tasks/parent/tool-execution.js";import {isTaskOwnedSerializedContext,TASK_UPDATE_SESSION_INSTRUCTION,@@ -103,62 +104,6 @@ import { isTaskToolAvailable, TASK_UPDATE_TOOL_NAME } from "#runtime/framework-tconst TASK_DONE_WITH_PENDING_INPUT_ERROR_MESSAGE ="Task mode cannot complete while input requests remain pending.";-/**- * Result of one durable harness step. `cancelled` is returned so workflow-core- * does not retry it; `park` carries the pending state needed by the next action.- */-export type DurableStepResult =- | {- readonly action: "continue" | "done";- readonly output?: unknown;- readonly isError?: boolean;- /**- * Optional durable pause for the turn workflow to fulfill before- * dispatching this result's next action.- */- readonly sleepDurationMs?: number;- readonly serializedContext: Record<string, unknown>;- readonly sessionState: DurableSessionState;- /** Session-total token usage; set on `done` when the session spent any. */- readonly usage?: TokenUsage;- /**- * Usage the final turn added beyond what earlier settled turns already- * reported; feeds the terminal `AgentTurnOutcome` for conversation- * children. Task sessions settle once, so their callers read `usage`.- */- readonly usageDelta?: TokenUsage;- }- | {- readonly action: "cancelled";- readonly serializedContext: Record<string, unknown>;- readonly sessionState: DurableSessionState;- }- | {- readonly action: "park";- readonly authorizationAttemptIds?: readonly string[];- readonly authorizationNames?: readonly string[];- 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;- readonly settled?: SettledTurn;- }- | {- readonly action: "dispatch-workflow-runtime-actions";- readonly pendingRuntimeActionKeys: readonly string[];- readonly sleepDurationMs?: number;- readonly serializedContext: Record<string, unknown>;- readonly sessionState: DurableSessionState;- };-export type { TurnStepInput };/**@@ -177,6 +122,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResuconst adapter = ctx.require(ChannelKey);const bundle = ctx.require(BundleKey);const tasksEnabled = bundle.resolvedAgent.config?.experimental?.tasks === true;+ ctx.set(TasksEnabledKey, tasksEnabled);const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);const taskUpdatesEnabled =isTaskOwnedSerializedContext(input.serializedContext) &&@@ -451,7 +397,8 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu// runtime-action wait) must settle before the park-resume stages run,// or the pending batch would re-park and later re-dispatch.throwIfTurnAborted(input.abortSignal);- stepResult = await runStep(ctx, initialSession, async (enrichedSession) => {+ stepResult = await runBackgroundStep(ctx, initialSession, async (enrichedSession) => {+ ctx.setVirtualContext(HandleEventKey, handleEvent);let schemaSession = resolveEffectiveOutputSchema({agentOutputSchema: effectiveAgent.turnAgent.outputSchema,input: resolved,@@ -556,8 +503,17 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu// The session model is also kept because `session.started` is not emitted// again after this cancellation settles.const interrupted = serializeContext(ctx);+ const retained = readRetainedBackgroundToolResult(ctx);return {action: "cancelled",+ ...(retained === undefined+ ? {}+ : {+ backgroundTaskState: createDurableSessionState({+ session: retained.backgroundTaskSession,+ }),+ backgroundTasks: retained.backgroundTasks,+ }),serializedContext: preserveSerializedInstrumentationState(preserveSerializedAgentTraceState(preserveSerializedSessionDynamicModelSelection(input.serializedContext, interrupted),@@ -577,6 +533,15 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResuconst nextState = createDurableSessionState({ session: stepResult.session });const sleepDurationMs = readTurnSleepDurationMs(ctx);const sleepTransition = sleepDurationMs === undefined ? {} : { sleepDurationMs };+ const backgroundTransition =+ stepResult.backgroundTasks === undefined || stepResult.backgroundTaskSession === undefined+ ? {}+ : {+ backgroundTaskState: createDurableSessionState({+ session: stepResult.backgroundTaskSession,+ }),+ backgroundTasks: stepResult.backgroundTasks,+ };if (stepResult.next !== null &&@@ -591,6 +556,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResuconst sessionTotals = getTurnUsageState(stepResult.session.state)?.session;return {action: "done",+ ...backgroundTransition,output: stepResult.next.output,isError: stepResult.next.isError,...sleepTransition,@@ -611,6 +577,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu) {return {action: "dispatch-workflow-runtime-actions",+ ...backgroundTransition,pendingRuntimeActionKeys: getRuntimeActionKeysFromWorkflowInterrupt(workflowInterrupt.interrupt,),@@ -630,6 +597,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResuconst { delta, session: reportedSession } = takeSessionUsageDelta(stepResult.session);return {action: "park",+ ...backgroundTransition,...pending,...sleepTransition,serializedContext: nextSerializedContext,@@ -645,6 +613,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResureturn {action: "park",+ ...backgroundTransition,...pending,...sleepTransition,serializedContext: nextSerializedContext,@@ -656,6 +625,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResuwriter.releaseLock();return {action: "continue",+ ...backgroundTransition,...sleepTransition,serializedContext: nextSerializedContext,sessionState: nextState,diff --git a/packages/eve/src/harness/advertised-tools.test.ts b/packages/eve/src/harness/advertised-tools.test.tsindex b9446276e..1752f4c98 100644--- a/packages/eve/src/harness/advertised-tools.test.ts+++ b/packages/eve/src/harness/advertised-tools.test.ts@@ -191,6 +191,7 @@ function createSubagentTool(name: string): HarnessToolDefinition {nodeId: "workers",subagentName: name,},+ workflowCallable: true,};}diff --git a/packages/eve/src/harness/advertised-tools.ts b/packages/eve/src/harness/advertised-tools.tsindex 08c43ed85..630d9ea0f 100644--- a/packages/eve/src/harness/advertised-tools.ts+++ b/packages/eve/src/harness/advertised-tools.ts@@ -160,18 +160,13 @@ function filterWorkflowHostToolsForRootSession(}for (const [name, tool] of tools) {- if (isDelegatedRuntimeActionTool(tool)) {+ if (tool.workflowCallable === true) {filteredTools.set(name, tool);}}return filteredTools;}-function isDelegatedRuntimeActionTool(definition: HarnessToolDefinition): boolean {- const runtimeAction = definition.runtimeAction;- return runtimeAction?.kind === "subagent-call" || runtimeAction?.kind === "remote-agent-call";-}-function shouldHideDelegationTool(definition: HarnessToolDefinition,session: AdvertisedToolSession,@@ -192,6 +187,7 @@ function shouldHideDelegationTool(* the only signal that separates the root from its children.*/function isRootOnlyFrameworkTool(definition: HarnessToolDefinition): boolean {+ if (definition.rootOnly === true) return true;if (definition.name === AGENT_TOOL_NAME &&definition.runtimeAction?.kind === "subagent-call" &&diff --git a/packages/eve/src/harness/background-tools.ts b/packages/eve/src/harness/background-tools.tsnew file mode 100644index 000000000..f37c63ba5--- /dev/null+++ b/packages/eve/src/harness/background-tools.ts@@ -0,0 +1,87 @@+import { loadContext } from "#context/container.js";+import { ContextKey } from "#context/key.js";+import type { ToolExecuteOptions } from "#shared/tool-definition.js";+import type { TaskExec } from "#shared/tool-task.js";++export interface BackgroundExecutableTool {+ readonly execute: (input: unknown, options: ToolExecuteOptions, task: TaskExec) => unknown;+ readonly name: string;+}++export interface BackgroundToolCall {+ readonly callId: string;+ readonly definition: BackgroundExecutableTool;+ readonly input: unknown;+}++export interface BackgroundToolCallBatch {+ readonly calls: readonly BackgroundToolCall[];+ register(call: {+ readonly callId: string;+ readonly input: unknown;+ readonly toolName: string;+ }): void;+ setTool(name: string, definition?: BackgroundExecutableTool): void;+}++export interface BackgroundToolExecutor {+ execute(input: {+ readonly batch: BackgroundToolCallBatch;+ readonly definition: BackgroundExecutableTool;+ readonly options: ToolExecuteOptions;+ readonly toolInput: unknown;+ }): Promise<unknown>;+}++// A ContextKey rather than a direct import of the task runtime, for three reasons:+// 1. The executor is per-step state, not a module export — each task-runtime step+// installs a fresh instance whose commit/rollback rides that step's transaction,+// so the correct instance can only be resolved at call time.+// 2. Importing the implementation from `execution/` would make the harness ↔+// execution dependency bidirectional; the key keeps it one-way (harness declares+// the contract, execution installs it).+// 3. "No task runtime active" stays a runtime condition instead of a link-time one:+// tool sets can be built anywhere, and `require()` only throws if a background+// call actually fires outside a task step.+export const BackgroundToolExecutorKey = new ContextKey<BackgroundToolExecutor>(+ "eve.internal.backgroundToolExecution",+);++export function createBackgroundToolCallBatch(): BackgroundToolCallBatch {+ const calls: BackgroundToolCall[] = [];+ const callsById = new Map<string, BackgroundToolCall>();+ const tools = new Map<string, BackgroundExecutableTool>();+ return {+ calls,+ register(call) {+ const definition = tools.get(call.toolName);+ if (definition === undefined) return;++ const existing = callsById.get(call.callId);+ if (existing?.definition === definition) return;+ if (existing !== undefined) {+ throw new Error(`Background tool call "${call.callId}" was registered more than once.`);+ }++ const registeredCall = { callId: call.callId, definition, input: call.input };+ callsById.set(call.callId, registeredCall);+ calls.push(registeredCall);+ },+ setTool(name, definition) {+ if (definition === undefined) {+ tools.delete(name);+ } else {+ tools.set(name, definition);+ }+ },+ };+}++export async function executeBackgroundToolCall(input: {+ readonly batch: BackgroundToolCallBatch;+ readonly definition: BackgroundExecutableTool;+ readonly options: ToolExecuteOptions;+ readonly toolInput: unknown;+}): Promise<unknown> {+ return await loadContext().require(BackgroundToolExecutorKey).execute(input);+}diff --git a/packages/eve/src/harness/execute-tool.ts b/packages/eve/src/harness/execute-tool.tsindex 0c2177c68..580109296 100644--- a/packages/eve/src/harness/execute-tool.ts+++ b/packages/eve/src/harness/execute-tool.ts@@ -2,6 +2,7 @@ import type { FlexibleSchema } from "ai";import type { Approval } from "#public/definitions/approval.js";import type { ToolExecuteOptions } from "#shared/tool-definition.js";+import type { TaskExec } from "#shared/tool-task.js";/*** Runtime-owned action metadata attached to one harness-visible tool.@@ -29,12 +30,20 @@ export type HarnessRuntimeActionDefinition =export interface HarnessToolDefinition {readonly approvalKey?: (toolInput: Readonly<Record<string, unknown>>) => string;readonly description: string;- readonly execute?: (input: any, options: ToolExecuteOptions) => any;+ readonly execute?: (input: any, options: ToolExecuteOptions, task?: TaskExec) => any;+ readonly execution?: "background";readonly frameworkAction?: "load-skill";readonly inputSchema: FlexibleSchema;readonly name: string;readonly approval?: Approval;readonly outputSchema?: FlexibleSchema;+ /**+ * Advertise this tool only to the root session, hiding it from subagent+ * sessions. Set on the injected `agent` self-delegation tool so children+ * cannot delegate recursively. Absent means visible everywhere.+ */+ readonly rootOnly?: boolean;readonly runtimeAction?: HarnessRuntimeActionDefinition;readonly toModelOutput?: (output: unknown) => unknown;+ readonly workflowCallable?: boolean;}diff --git a/packages/eve/src/harness/handles/transitions.test.ts b/packages/eve/src/harness/handles/transitions.test.tsindex 7221d1ffd..604948846 100644--- a/packages/eve/src/harness/handles/transitions.test.ts+++ b/packages/eve/src/harness/handles/transitions.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";import { deriveAgentOperationId } from "#harness/handles/operation-id.js";import {+ AGENT_HANDLES_STATE_KEY,deriveAgentId,getAgentHandleStore,type AgentAddress,@@ -16,6 +17,7 @@ import {confirmTaskAgentAddress,prepareAgentContinuation,prepareAgentStart,+ rebaseAgentHandles,rejectAgentEffect,removeTaskAgentAddress,settleAgentTurn,@@ -310,6 +312,104 @@ describe("abandonRunningAgentTurns", () => {});});+describe("rebaseAgentHandles", () => {+ const otherHandle: AgentHandle = {+ address: {+ continuationToken: "continuation_other",+ kind: "agent/local",+ sessionId: "session_other",+ },+ identity: { id: "ag_writer:aaaaaaaaaaaa", name: "writer", nodeId: "node_writer" },+ lastStatus: "",+ phase: "parked",+ };+ const continueOperation: ContinueOperation = {+ callId: "call_2",+ id: "op_continue",+ kind: "continue",+ parentTurnId: "turn_2",+ previousStatus: "",+ };++ function withHandles(handles: readonly AgentHandle[]): HarnessSession {+ return createSession({ [AGENT_HANDLES_STATE_KEY]: { handles } });+ }++ function inPlaceChange(): { base: HarnessSession; next: HarnessSession } {+ const base = parkedSession();+ const prepared = prepareAgentContinuation(base, {+ agentId: identity.id,+ invokedName: "research",+ operation: continueOperation,+ });+ if (prepared.kind !== "ready") {+ throw new Error("expected ready");+ }+ return { base, next: prepared.session };+ }++ it("appends a handle the dispatch added onto a diverged working session", () => {+ const next = preparedSession();+ const current = withHandles([otherHandle]);+ const rebased = rebaseAgentHandles(current, {+ base: createSession().state,+ next: next.state,+ });+ expect(handlesOf(rebased)).toEqual([otherHandle, ...handlesOf(next)]);+ });++ it("applies a removal the dispatch made", () => {+ const base = confirmTaskAgentAddress(preparedSession(), {+ address,+ operationId: startOperation.id,+ });+ const current = withHandles([...handlesOf(base), otherHandle]);+ const rebased = rebaseAgentHandles(current, {+ base: base.state,+ next: removeTaskAgentAddress(base, identity.id).state,+ });+ expect(handlesOf(rebased)).toEqual([otherHandle]);+ });++ it("applies an in-place change the dispatch made", () => {+ const { base, next } = inPlaceChange();+ const current = withHandles([...handlesOf(base), otherHandle]);+ const rebased = rebaseAgentHandles(current, { base: base.state, next: next.state });+ expect(handlesOf(rebased)).toEqual([...handlesOf(next), otherHandle]);+ });++ it("throws when the dispatch and another effect changed the same handle differently", () => {+ const { base, next } = inPlaceChange();+ const current = withHandles([{ address, identity, lastStatus: "diverged", phase: "parked" }]);+ expect(() => rebaseAgentHandles(current, { base: base.state, next: next.state })).toThrow(+ identity.id,+ );+ });++ it("throws when an added id already exists with different content", () => {+ const current = withHandles([+ {+ identity,+ operation: startOperation,+ phase: "starting",+ target: { continuationToken: "continuation_divergent", kind: "agent/local" },+ },+ ]);+ expect(() =>+ rebaseAgentHandles(current, {+ base: createSession().state,+ next: preparedSession().state,+ }),+ ).toThrow(identity.id);+ });++ it("returns the working session unchanged when it already contains the delta", () => {+ const { base, next } = inPlaceChange();+ const current = withHandles(handlesOf(next));+ expect(rebaseAgentHandles(current, { base: base.state, next: next.state })).toBe(current);+ });+});+describe("settleAgentTurn", () => {it("parks the handle with a truncated status on a parked outcome", () => {const settled = settleAgentTurn(runningSession(), {diff --git a/packages/eve/src/harness/handles/transitions.ts b/packages/eve/src/harness/handles/transitions.tsindex f53eb17c4..f07cf4fe3 100644--- a/packages/eve/src/harness/handles/transitions.ts+++ b/packages/eve/src/harness/handles/transitions.ts@@ -11,6 +11,7 @@ import {} from "#harness/handles/store.js";import type { HarnessSession, SessionStateMap } from "#harness/types.js";import type { AgentTurnOutcome } from "#shared/agent-turn-outcome.js";+import { jsonValuesEqual } from "#shared/json.js";/*** Records intent to start a fresh child. Must be applied to the step's@@ -368,6 +369,80 @@ export function settleAgentTurn(};}+/**+ * Rebases the handle delta one dispatch produced (`base` → `next`) onto a+ * working session that other concurrently staged effects may have advanced+ * past `base`.+ *+ * Per handle id:+ *+ * - deleted by the dispatch → deleted from the working session.+ * - added by the dispatch → appended. If the working session already holds+ * the id with different content, throws: ids derive from unique+ * operations, so a collision means corrupted derivation.+ * - changed in place by the dispatch → the dispatched copy replaces the+ * working copy while that copy still matches `base`. A working copy that+ * diverged from both throws instead of silently dropping either change.+ * - untouched by the dispatch → the working copy is kept.+ *+ * A delta the working session already contains is a no-op, so replaying an+ * effect is safe.+ */+export function rebaseAgentHandles(+ session: HarnessSession,+ input: {+ readonly base: SessionStateMap | undefined;+ readonly next: SessionStateMap | undefined;+ },+): HarnessSession {+ const baseById = handlesById(input.base);+ const nextById = handlesById(input.next);+ const currentHandles = getAgentHandleStore(session.state)?.handles ?? [];+ const currentIds = new Set(currentHandles.map((handle) => handle.identity.id));++ let changed = false;+ const rebased: AgentHandle[] = [];+ for (const current of currentHandles) {+ const id = current.identity.id;+ const base = baseById.get(id);+ const next = nextById.get(id);+ if (base !== undefined && next === undefined) {+ changed = true;+ continue;+ }+ if (base === undefined && next !== undefined && !jsonValuesEqual(current, next)) {+ throw new Error(+ `Agent handle "${id}" added by a dispatch already exists with different content.`,+ );+ }+ if (base !== undefined && next !== undefined && !jsonValuesEqual(base, next)) {+ if (jsonValuesEqual(current, base)) {+ rebased.push(next);+ changed = true;+ continue;+ }+ if (!jsonValuesEqual(current, next)) {+ throw new Error(+ `Agent handle "${id}" was changed by a dispatch and concurrently by another effect.`,+ );+ }+ }+ rebased.push(current);+ }+ const added = [...nextById.values()].filter(+ (handle) => !baseById.has(handle.identity.id) && !currentIds.has(handle.identity.id),+ );+ if (!changed && added.length === 0) {+ return session;+ }+ return writeHandles(session, [...rebased, ...added]);+}++function handlesById(state: SessionStateMap | undefined): ReadonlyMap<string, AgentHandle> {+ const handles = getAgentHandleStore(state)?.handles ?? [];+ return new Map(handles.map((handle) => [handle.identity.id, handle]));+}+/*** Persists the handle store, validating it against the strict store schema* first. This write-time check is what lets the schema-free driver-sidediff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.tsindex 636e90e44..1c0ae009e 100644--- a/packages/eve/src/harness/tool-loop.test.ts+++ b/packages/eve/src/harness/tool-loop.test.ts@@ -2,6 +2,7 @@ import { context as otelContext, trace } from "#compiled/@opentelemetry/api/indeimport {type FilePart,jsonSchema,+ type LanguageModelCallEndEvent,type LanguageModel,type ModelMessage,ToolLoopAgent,@@ -52,6 +53,7 @@ import {} from "#harness/input-requests.js";import { getPendingRuntimeActionBatch } from "#harness/runtime-actions.js";import { AGENT_HANDLES_STATE_KEY } from "#harness/handles/store.js";+import { BackgroundToolExecutorKey } from "#harness/background-tools.js";import { stashToolInterrupt } from "#harness/tool-interrupts.js";import { appendMissingToolResultMessages, createToolLoopHarness } from "#harness/tool-loop.js";import { isSessionLimitDecline, TurnCancelledError } from "#harness/turn-cancellation.js";@@ -873,6 +875,81 @@ describe("createToolLoopHarness", () => {expect(agentCall!.tools).not.toHaveProperty("Workflow");});+ it("registers atomic background tool calls before AI SDK execution", async () => {+ setupMockAgent({+ finishReason: "stop",+ response: { messages: [{ content: "Hello!", role: "assistant" }] },+ text: "Hello!",+ toolCalls: [],+ toolResults: [],+ });++ const runStep = createToolLoopHarness(+ createTestConfig("conversation", undefined, {+ tools: new Map([+ [+ "background_work",+ {+ description: "Start background work.",+ execute: vi.fn(),+ execution: "background" as const,+ inputSchema: jsonSchema({ type: "object" }),+ name: "background_work",+ },+ ],+ ]),+ }),+ );+ await runStep(createTestSession(), { message: "Hi" });++ const agentCall = vi.mocked(ToolLoopAgent).mock.calls[0]?.[0] as+ | (ConstructorParameters<typeof ToolLoopAgent>[0] & {+ onLanguageModelCallEnd?: (event: LanguageModelCallEndEvent) => Promise<void> | void;+ })+ | undefined;+ const backgroundTool = agentCall?.tools?.background_work as+ | {+ execute?: (input: unknown, options: { toolCallId: string }) => Promise<unknown>;+ onInputAvailable?: (input: {+ input: unknown;+ toolCallId: string;+ }) => Promise<void> | void;+ }+ | undefined;+ expect(agentCall?.onLanguageModelCallEnd).toBeTypeOf("function");+ expect(backgroundTool?.onInputAvailable).toBeTypeOf("function");++ await backgroundTool!.onInputAvailable!({ input: { value: 1 }, toolCallId: "call-a" });+ await agentCall!.onLanguageModelCallEnd!({+ content: [+ {+ input: { value: 1 },+ toolCallId: "call-a",+ toolName: "background_work",+ type: "tool-call",+ },+ {+ input: { value: 2 },+ toolCallId: "call-b",+ toolName: "background_work",+ type: "tool-call",+ },+ ],+ } as never);++ let registeredCallIds: string[] = [];+ const ctx = new ContextContainer();+ ctx.set(BackgroundToolExecutorKey, {+ async execute({ batch }) {+ registeredCallIds = batch.calls.map((call) => call.callId);+ return { ok: true };+ },+ });+ await contextStorage.run(ctx, () => backgroundTool!.execute!({}, { toolCallId: "call-a" }));++ expect(registeredCallIds).toEqual(["call-a", "call-b"]);+ });+it("announces parked agents as user-role content before the user message, outside the system prompt", async () => {setupMockAgent({finishReason: "stop",diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.tsindex f52adfaa2..c5a357caf 100644--- a/packages/eve/src/harness/tool-loop.ts+++ b/packages/eve/src/harness/tool-loop.ts@@ -6,6 +6,7 @@ import {} from "#compiled/@opentelemetry/api/index.js";import {isStepCount,+ type LanguageModelCallEndEvent,type LanguageModel,type ModelMessage,type ProviderMetadata,@@ -208,6 +209,7 @@ import {getRegisteredTelemetryIntegrations,} from "#harness/ai-sdk-telemetry.js";import { getAdvertisedTools } from "#harness/advertised-tools.js";+import { createBackgroundToolCallBatch } from "#harness/background-tools.js";import {applyLastToolCacheBreakpoint,applySystemCacheBreakpoint,@@ -1399,6 +1401,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {? [...modelMessages, { role: "user" as const, content: opts.trailingUserNote }]: modelMessages;const harnessTools = buildHarnessToolsWithDynamicSubagents(config.tools, ctx);+ const backgroundBatch = createBackgroundToolCallBatch();const advertisedHarnessTools = getAdvertisedTools({delegatedCaller: taskUpdatesEnabled,session,@@ -1408,6 +1411,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {const flatTools = await buildToolSetWithProviderTools({approvedTools,+ backgroundBatch,capabilities: config.capabilities,disabledProviderTools: opts.disabledProviderTools,modelReference: requireSessionModelReference(session),@@ -1423,6 +1427,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {});const dynamicToolSet = buildToolSetFromDefinitions({approvedTools,+ backgroundBatch,capabilities: config.capabilities,disabledProviderTools: opts.disabledProviderTools,tools: dynamicTools,@@ -1504,6 +1509,22 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {headers: attributionHeaders,instructions,model,+ onLanguageModelCallEnd(event: LanguageModelCallEndEvent) {+ for (const part of event.content) {+ if (+ part.type !== "tool-call" ||+ part.providerExecuted === true ||+ isInvalidToolCall(part)+ ) {+ continue;+ }+ backgroundBatch.register({+ callId: part.toolCallId,+ input: part.input,+ toolName: part.toolName,+ });+ }+ },onToolExecutionEnd: logToolExecutionError,// Replaces the AI SDK's default `console.error`; the harness still// emits stream events, this just keeps the raw error from being silent.diff --git a/packages/eve/src/harness/tools.ts b/packages/eve/src/harness/tools.tsindex 8611f7557..5b371cfda 100644--- a/packages/eve/src/harness/tools.ts+++ b/packages/eve/src/harness/tools.ts@@ -22,6 +22,12 @@ import { stashToolInterrupt } from "#harness/tool-interrupts.js";import { normalizeToolJsonOutput, normalizeToolModelOutput } from "#harness/tool-model-output.js";import type { ToolExecuteOptions } from "#shared/tool-definition.js";import { isAsyncIterable } from "#shared/async-iterable.js";+import {+ createBackgroundToolCallBatch,+ executeBackgroundToolCall,+ type BackgroundExecutableTool,+ type BackgroundToolCallBatch,+} from "#harness/background-tools.js";type NativeApprovalStatus = Exclude<ApprovalStatus, boolean>;@@ -48,11 +54,13 @@ const toolApprovals = new WeakMap<*/export function buildToolSet(input: {readonly approvedTools?: ReadonlySet<string>;+ readonly backgroundBatch?: BackgroundToolCallBatch;readonly capabilities?: SessionCapabilities;readonly disabledProviderTools?: ReadonlySet<string>;readonly tools: HarnessToolMap;}): ToolSet {const tools: Record<string, ToolSet[string]> = {};+ const backgroundBatch = input.backgroundBatch ?? createBackgroundToolCallBatch();const canRequestInput = input.capabilities?.requestInput === true;const disabled = input.disabledProviderTools;@@ -65,12 +73,38 @@ export function buildToolSet(input: {continue;}+ backgroundBatch.setTool(+ definition.name,+ definition.execution === "background" && definition.execute !== undefined+ ? (definition as BackgroundExecutableTool)+ : undefined,+ );const authorToModelOutput = definition.toModelOutput;const approval = buildApprovalFn(definition, input);const aiTool = tool({description: definition.description,- execute: wrapToolExecute(definition),+ execute: wrapToolExecute(definition, backgroundBatch),inputSchema: definition.inputSchema,+ ...(definition.execution === "background"+ ? {+ onInputAvailable: ({+ input: toolInput,+ toolCallId,+ }: {+ readonly input: unknown;+ readonly toolCallId: string;+ }) => {+ if (definition.execute === undefined) {+ throw new Error(`Background tool "${definition.name}" has no execute function.`);+ }+ backgroundBatch.register({+ callId: toolCallId,+ input: toolInput,+ toolName: definition.name,+ });+ },+ }+ : {}),outputSchema: definition.outputSchema,...(definition.execute !== undefined? {@@ -138,6 +172,7 @@ export function buildToolSet(input: {*/export function buildToolSetFromDefinitions(input: {readonly approvedTools?: ReadonlySet<string>;+ readonly backgroundBatch?: BackgroundToolCallBatch;readonly capabilities?: SessionCapabilities;readonly disabledProviderTools?: ReadonlySet<string>;readonly tools: readonly HarnessToolDefinition[];@@ -150,6 +185,7 @@ export function buildToolSetFromDefinitions(input: {}return buildToolSet({approvedTools: input.approvedTools,+ backgroundBatch: input.backgroundBatch,capabilities: input.capabilities,disabledProviderTools: input.disabledProviderTools,tools,@@ -165,6 +201,7 @@ export function buildToolSetFromDefinitions(input: {*/export function wrapToolExecute(definition: HarnessToolDefinition,+ backgroundBatch: BackgroundToolCallBatch = createBackgroundToolCallBatch(),): ((input: any, options: ToolExecuteOptions) => Promise<any> | AsyncIterable<any>) | undefined {const execute = definition.execute;if (execute === undefined) return undefined;@@ -172,7 +209,15 @@ export function wrapToolExecute(return (input, options) => {let output: unknown;try {- output = execute(input, options);+ output =+ definition.execution === "background"+ ? executeBackgroundToolCall({+ batch: backgroundBatch,+ definition: definition as BackgroundExecutableTool,+ options,+ toolInput: input,+ })+ : execute(input, options);} catch (error) {return Promise.reject(error);}@@ -235,6 +280,7 @@ function normalizeToolExecuteOutput(*/export async function buildToolSetWithProviderTools(input: {readonly approvedTools?: ReadonlySet<string>;+ readonly backgroundBatch?: BackgroundToolCallBatch;readonly capabilities?: SessionCapabilities;readonly disabledProviderTools?: ReadonlySet<string>;readonly modelReference: RuntimeModelReference;@@ -245,6 +291,7 @@ export async function buildToolSetWithProviderTools(input: {const tools: ToolSet = {...buildToolSet({approvedTools: input.approvedTools,+ backgroundBatch: input.backgroundBatch,capabilities: input.capabilities,disabledProviderTools: disabled,tools: input.tools,diff --git a/packages/eve/src/harness/types.ts b/packages/eve/src/harness/types.tsindex 8c5c5d3a6..437ae624a 100644--- a/packages/eve/src/harness/types.ts+++ b/packages/eve/src/harness/types.ts@@ -212,6 +212,14 @@ export interface SettledTurn {* Result returned by one harness step invocation.*/export interface StepResult {+ /** Background-tool effects projected onto the session that entered this step. */+ readonly backgroundTaskSession?: HarnessSession;+ /** Durable tasks started by background tools and awaiting the parent commit barrier. */+ readonly backgroundTasks?: readonly {+ readonly taskInboxToken: string;+ readonly taskId: string;+ readonly taskRunId: string;+ }[];readonly next: StepNext;readonly session: HarnessSession;/**diff --git a/packages/eve/src/internal/authored-definition/schema-backed.test.ts b/packages/eve/src/internal/authored-definition/schema-backed.test.tsindex 4b6db15f7..36f19d91a 100644--- a/packages/eve/src/internal/authored-definition/schema-backed.test.ts+++ b/packages/eve/src/internal/authored-definition/schema-backed.test.ts@@ -34,6 +34,26 @@ describe("normalizeToolDefinition", () => {expect(typeof entry.definition.execute).toBe("function");});+ it("preserves the background execution discriminator", () => {+ const tool = defineTool({+ description: "Starts an export.",+ execution: "background",+ inputSchema: z.object({ exportId: z.string() }),+ execute(input, _ctx, task) {+ return task.delegated({+ executor: { data: { exportId: input.exportId }, kind: "export" },+ receipt: { exportId: input.exportId },+ });+ },+ });++ const entry = normalizeToolDefinition(tool, FAILURE_MESSAGE);++ expect(entry.kind).toBe("tool");+ if (entry.kind !== "tool") throw new Error("expected tool kind");+ expect(entry.definition.execution).toBe("background");+ });+it("normalizes a tool with a Zod 3 input schema", () => {const tool = defineTool({description: "Gets weather for a city.",diff --git a/packages/eve/src/internal/authored-definition/schema-backed.ts b/packages/eve/src/internal/authored-definition/schema-backed.tsindex dab814cec..5b311ca2f 100644--- a/packages/eve/src/internal/authored-definition/schema-backed.ts+++ b/packages/eve/src/internal/authored-definition/schema-backed.ts@@ -93,7 +93,16 @@ export function normalizeToolDefinition(value: unknown, message: string): Normalconst record = expectObjectRecord(value, message);expectOnlyKnownKeys(record,- ["auth", "description", "execute", "inputSchema", "approval", "outputSchema", "toModelOutput"],+ [+ "auth",+ "description",+ "execute",+ "execution",+ "inputSchema",+ "approval",+ "outputSchema",+ "toModelOutput",+ ],message,);const inputSchema =@@ -106,6 +115,13 @@ export function normalizeToolDefinition(value: unknown, message: string): Normalexecute: expectFunction(record.execute, message),inputSchema,};+ if (record.execution !== undefined) {+ const execution = expectString(record.execution, message);+ if (execution !== "background") {+ throw new Error(`${message} Expected "execution" to be "background".`);+ }+ definition.execution = execution;+ }if (outputSchema !== undefined) {definition.outputSchema = outputSchema;}diff --git a/packages/eve/src/public/definitions/exact.test.ts b/packages/eve/src/public/definitions/exact.test.tsindex 542af3898..08e6bd13e 100644--- a/packages/eve/src/public/definitions/exact.test.ts+++ b/packages/eve/src/public/definitions/exact.test.ts@@ -25,6 +25,8 @@ import { defineSkill } from "#public/definitions/skill.js";import {defineTool,experimental_workflow,+ type TaskReceipt,+ type TaskExec,type ToolDefinition,} from "#public/definitions/tool.js";@@ -85,6 +87,28 @@ describe("definition helper exact inputs", () => {>();});+ it("types background tools in terms of the durable task capability", () => {+ const backgroundTool = defineTool({+ description: "Start a durable export.",+ execution: "background",+ inputSchema: z.object({ jobId: z.string() }),+ execute(input, _ctx, task) {+ expectTypeOf(task).toEqualTypeOf<TaskExec>();+ expectTypeOf(task.binding.taskId).toEqualTypeOf<string>();+ return task.delegated({+ executor: { data: { jobId: input.jobId }, kind: "export" },+ receipt: { jobId: input.jobId },+ });+ },+ });++ expectTypeOf(backgroundTool.execution).toEqualTypeOf<"background">();+ expectTypeOf<Parameters<NonNullable<typeof backgroundTool.toModelOutput>>[0]>().toEqualTypeOf<+ TaskReceipt<{ jobId: string }>+ >();+ expect(backgroundTool.execution).toBe("background");+ });+it("infers tool input from Zod 3 schemas", () => {const tool = defineTool({description: "Fetch current weather for a city.",@@ -104,6 +128,16 @@ describe("definition helper exact inputs", () => {});function typeOnlyFixtures(): void {+ defineTool({+ description: "Invalid streaming background tool.",+ // @ts-expect-error Background executors settle once; streamed output is unsupported.+ execution: "background",+ inputSchema: { type: "object" },+ async *execute() {+ yield { status: "working" };+ },+ });+defineDynamic({// @ts-expect-error defineDynamic is resolver-only.fallback: "anthropic/claude-sonnet-5",diff --git a/packages/eve/src/public/definitions/tool.ts b/packages/eve/src/public/definitions/tool.tsindex 64ef73598..9b56184a1 100644--- a/packages/eve/src/public/definitions/tool.ts+++ b/packages/eve/src/public/definitions/tool.ts@@ -8,6 +8,7 @@ import type { PublicToolDefinition, ToolModelOutput } from "#shared/tool-definitimport type { SessionContext } from "#public/definitions/callback-context.js";import type { Approval } from "#public/definitions/approval.js";import type { JsonObject } from "#shared/json.js";+import type { TaskDelegated, TaskExec, TaskReceipt } from "#shared/tool-task.js";import type {AuthorizationDefinition,ConnectionAuthorizationContext,@@ -35,6 +36,14 @@ type DynamicEventMapResult<TEvents extends DynamicEvents> = Awaited<>;export type { ToolModelOutput, ToolModelOutputPart } from "#shared/tool-definition.js";+export type {+ TaskBinding,+ TaskDelegated,+ TaskExec,+ TaskExecutorBinding,+ TaskReceipt,+ TaskSendCommand,+} from "#shared/tool-task.js";/*** Authorization provider passed to {@link ToolContext.getToken} or@@ -124,6 +133,7 @@ export interface ToolDefinition<TInput = unknown, TOutput = unknown> extends PubTInput,TOutput> {+ readonly execution?: never;execute(input: TInput, ctx: ToolContext): Promise<TOutput> | TOutput | AsyncIterable<TOutput>;/*** Optional per-tool approval gate. The return value determines whether@@ -147,6 +157,21 @@ export interface ToolDefinition<TInput = unknown, TOutput = unknown> extends PubtoModelOutput?: (output: TOutput) => ToolModelOutput | Promise<ToolModelOutput>;}+/** A tool whose executor can outlive the model tool-call phase as a durable task. */+export interface BackgroundToolDefinition<+ TInput = unknown,+ TOutput = unknown,+> extends PublicToolDefinition<TInput, TOutput> {+ readonly execution: "background";+ execute(+ input: TInput,+ ctx: ToolContext,+ task: TaskExec,+ ): Promise<TaskDelegated | TOutput> | TaskDelegated | TOutput;+ approval?: Approval<ApprovalContextInput<TInput>>;+ toModelOutput?: (output: TOutput) => ToolModelOutput | Promise<ToolModelOutput>;+}+type ToolOutputFromExecuteReturn<TReturn> =TReturn extends Promise<infer TOutput>? TOutput@@ -154,10 +179,24 @@ type ToolOutputFromExecuteReturn<TReturn> =? TOutput: TReturn;+type BackgroundToolOutputFromExecuteReturn<TReturn> =+ ToolOutputFromExecuteReturn<TReturn> extends infer TOutput+ ? TOutput extends TaskDelegated<infer TData>+ ? TaskReceipt<TData>+ : TOutput+ : never;+type ToolDefinitionWithExecuteReturn<TInput, TOutput, TReturn> = ToolDefinition<TInput, TOutput> & {execute(input: TInput, ctx: ToolContext): TReturn;};+type BackgroundToolDefinitionWithExecuteReturn<TInput, TOutput, TReturn> = BackgroundToolDefinition<+ TInput,+ TOutput+> & {+ execute(input: TInput, ctx: ToolContext, task: TaskExec): TReturn;+};+/*** Defines a tool configuration, used both for static tools (default export* from `agent/tools/*.ts`) and as the entry wrapper inside `defineDynamic`@@ -166,6 +205,32 @@ type ToolDefinitionWithExecuteReturn<TInput, TOutput, TReturn> = ToolDefinition<* For static tools, the runtime tool name is the filename slug. `defineTool`* stamps a brand that lifecycle code validates; it rejects raw object literals.*/+export function defineTool<+ TSchema extends StandardSchemaV1<unknown, unknown> | StandardJSONSchemaV1<unknown, unknown>,+ TReturn,+>(definition: {+ description: BackgroundToolDefinition<unknown, unknown>["description"];+ execution: "background";+ inputSchema: TSchema;+ outputSchema?: PublicToolDefinition<+ unknown,+ BackgroundToolOutputFromExecuteReturn<TReturn>+ >["outputSchema"];+ execute(+ input: StandardSchemaV1.InferOutput<TSchema>,+ ctx: ToolContext,+ task: TaskExec,+ ): TReturn extends AsyncIterable<unknown> ? never : TReturn;+ approval?: BackgroundToolDefinition<StandardSchemaV1.InferOutput<TSchema>, unknown>["approval"];+ toModelOutput?: BackgroundToolDefinition<+ unknown,+ BackgroundToolOutputFromExecuteReturn<TReturn>+ >["toModelOutput"];+}): BackgroundToolDefinitionWithExecuteReturn<+ StandardSchemaV1.InferOutput<TSchema>,+ BackgroundToolOutputFromExecuteReturn<TReturn>,+ TReturn+>;export function defineTool<TInputSchema extends StandardSchemaV1<unknown, unknown> | StandardJSONSchemaV1<unknown, unknown>,TOutputSchema extends StandardJSONSchemaV1<unknown, unknown>,@@ -240,8 +305,8 @@ export function defineTool<TInput = unknown, TOutput = unknown>(definition: ToolDefinition<TInput, TOutput>,): ToolDefinition<TInput, TOutput>;export function defineTool<TInput = unknown, TOutput = unknown>(- definition: ToolDefinition<TInput, TOutput>,-): ToolDefinition<TInput, TOutput> {+ definition: ToolDefinition<TInput, TOutput> | BackgroundToolDefinition<TInput, TOutput>,+): ToolDefinition<TInput, TOutput> | BackgroundToolDefinition<TInput, TOutput> {if ((definition as { readonly auth?: unknown }).auth !== undefined) {throw new Error(`defineTool: The "auth" field is no longer supported. ` +diff --git a/packages/eve/src/runtime/framework-tools/tasks.ts b/packages/eve/src/runtime/framework-tools/tasks.tsindex c29d4d354..9bd26165e 100644--- a/packages/eve/src/runtime/framework-tools/tasks.ts+++ b/packages/eve/src/runtime/framework-tools/tasks.ts@@ -47,12 +47,19 @@ const TASK_VIEW_SCHEMA = z.object({type: z.enum(["result", "error"]),}).optional(),- metadata: z.object({- agentId: z.string(),- kind: z.literal("subagent"),- mode: z.enum(["local", "remote"]),- name: z.string(),- }),+ metadata: z.union([+ z.object({+ agentId: z.string(),+ kind: z.literal("subagent"),+ mode: z.enum(["local", "remote"]),+ name: z.string(),+ }),+ z.object({+ data: z.record(z.string(), z.unknown()).optional(),+ kind: z.string(),+ name: z.string(),+ }),+ ]),status: z.enum(["working", "input_required", "completed", "failed", "cancelled"]),taskId: z.string(),});diff --git a/packages/eve/src/runtime/resolve-tool.ts b/packages/eve/src/runtime/resolve-tool.tsindex cd5775299..29bfc4826 100644--- a/packages/eve/src/runtime/resolve-tool.ts+++ b/packages/eve/src/runtime/resolve-tool.ts@@ -59,6 +59,7 @@ export async function resolveToolDefinition(return {description: definition.description,execute,+ execution: definition.execution,exportName: definition.exportName,inputSchema,logicalPath: definition.logicalPath,diff --git a/packages/eve/src/shared/json.test.ts b/packages/eve/src/shared/json.test.tsindex 1f37ea4a7..fa766f52a 100644--- a/packages/eve/src/shared/json.test.ts+++ b/packages/eve/src/shared/json.test.ts@@ -1,8 +1,24 @@import { describe, expect, it } from "vitest";-import { parseJsonObject, parseJsonValue } from "#shared/json.js";+import { jsonValuesEqual, parseJsonObject, parseJsonValue } from "#shared/json.js";import { jsonObjectSchema, jsonValueSchema } from "#shared/json-schemas.js";+describe("jsonValuesEqual", () => {+ it("compares nested JSON values independent of object key order", () => {+ expect(+ jsonValuesEqual(+ { filters: { city: "Brooklyn" }, rows: [1, null] },+ {+ rows: [1, null],+ filters: { city: "Brooklyn" },+ },+ ),+ ).toBe(true);+ expect(jsonValuesEqual({ rows: [1, null] }, { rows: [null, 1] })).toBe(false);+ expect(jsonValuesEqual({ inherited: true }, Object.create({ inherited: true }))).toBe(false);+ });+});+describe("parseJsonValue", () => {it("preserves JSON primitives", () => {expect(parseJsonValue("hello")).toBe("hello");diff --git a/packages/eve/src/shared/json.ts b/packages/eve/src/shared/json.tsindex 1239c9e0a..37a2c707e 100644--- a/packages/eve/src/shared/json.ts+++ b/packages/eve/src/shared/json.ts@@ -20,6 +20,30 @@ export interface JsonObject {*/export type JsonValue = JsonArray | JsonObject | JsonPrimitive;+/** Compares two already-validated JSON structures by value. */+export function jsonValuesEqual(left: unknown, right: unknown): boolean {+ if (left === right) return true;+ if (Array.isArray(left) || Array.isArray(right)) {+ return (+ Array.isArray(left) &&+ Array.isArray(right) &&+ left.length === right.length &&+ left.every((value, index) => jsonValuesEqual(value, right[index]))+ );+ }+ if (left === null || right === null || typeof left !== "object" || typeof right !== "object") {+ return false;+ }+ const leftEntries = Object.entries(left);+ const rightRecord = right as Record<string, unknown>;+ return (+ leftEntries.length === Object.keys(rightRecord).length &&+ leftEntries.every(+ ([key, value]) => Object.hasOwn(rightRecord, key) && jsonValuesEqual(value, rightRecord[key]),+ )+ );+}+const INVALID_JSON_VALUE_CANDIDATE = Symbol("invalid-json-value-candidate");const JSON_VALUE_ERROR_MESSAGE = "Expected a JSON-serializable value.";const JSON_OBJECT_ERROR_MESSAGE = "Expected a JSON-serializable object.";diff --git a/packages/eve/src/shared/tool-definition.ts b/packages/eve/src/shared/tool-definition.tsindex 53d171c3a..caf78e02e 100644--- a/packages/eve/src/shared/tool-definition.ts+++ b/packages/eve/src/shared/tool-definition.ts@@ -4,6 +4,7 @@ import type {StandardSchemaV1,} from "#compiled/@standard-schema/spec/index.js";import type { JsonObject } from "#shared/json.js";+import type { TaskExec } from "#shared/tool-task.js";/*** Options forwarded from the AI SDK to the tool's {@link ToolDefinition.execute}@@ -14,10 +15,14 @@ export type ToolExecuteOptions = Omit<ToolExecutionOptions<unknown>, "context">;export type ToolExecuteFn<TInput = unknown, TOutput = unknown> = (input: TInput,options: ToolExecuteOptions,+ task?: TaskExec,) => Promise<TOutput> | TOutput | AsyncIterable<TOutput>;+export type ToolExecution = "background";+interface ToolDefinitionBase {readonly description: string;+ readonly execution?: ToolExecution;}/**diff --git a/packages/eve/src/shared/tool-task.ts b/packages/eve/src/shared/tool-task.tsnew file mode 100644index 000000000..d08ea44f6--- /dev/null+++ b/packages/eve/src/shared/tool-task.ts@@ -0,0 +1,119 @@+import type { BackgroundTask } from "#execution/tasks/parent/delegate.js";+import type { BackgroundToolCall } from "#harness/background-tools.js";+import type { HarnessSession } from "#harness/types.js";+import type { JsonObject, JsonValue } from "#shared/json.js";++const TASK_DELEGATED_KIND = "eve:task-delegated";++/** Private address an executor uses to report lifecycle changes to its owning task. */+export interface TaskBinding {+ readonly taskId: string;+ readonly token: string;+ readonly url?: string;+}++/**+ * Opaque, task-private address used to control an external executor. `data`+ * means nothing to the task layer beyond deep equality (replay idempotency);+ * only the executor `kind` that wrote it may parse it (e.g. cancel routing).+ */+export interface TaskExecutorBinding {+ readonly kind: string;+ readonly data: JsonObject;+}++/**+ * What the model sees as this call's tool output when work is delegated: the+ * author-supplied data plus `status: "working"` and the `taskId` it can poll+ * or cancel. It acknowledges delegation — it is not the task's result, which+ * arrives later through task completion.+ */+export type TaskReceipt<TData extends JsonObject = JsonObject> = TData & {+ readonly status: "working";+ readonly taskId: string;+};++/**+ * Sentinel returned by a background tool after an external executor accepts+ * responsibility for the task. Returning it ends `execute`; it does not+ * complete the durable task.+ */+export interface TaskDelegated<TData extends JsonObject = JsonObject> {+ readonly kind: typeof TASK_DELEGATED_KIND;+ readonly executor: TaskExecutorBinding;+ readonly receipt: TaskReceipt<TData>;+}++/**+ * Terminal commands an in-process executor may report to its task via+ * {@link TaskExec.send}. Deliberately narrower than the task run's full+ * command surface — bind, ready, and input routing stay runtime-owned.+ */+export type TaskSendCommand =+ | { readonly kind: "complete"; readonly data: JsonValue }+ | { readonly kind: "fail"; readonly data: JsonValue }+ | { readonly kind: "cancel" };++/** Task capability passed only to tools declared with `execution: "background"`. */+export interface TaskExec {+ /**+ * The sibling background calls admitted in the same step. The only view a+ * tool has of what launched alongside it, for enforcing batch-wide+ * invariants before delegating.+ */+ readonly batch: readonly BackgroundToolCall[];+ /**+ * The task-private address for reporting lifecycle changes back to this+ * task. Hand it to the external executor so completion routes to the task+ * 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).+ */+ readonly session: HarnessSession;+ /** The durable task backing this call; its identity outlives `execute`. */+ readonly task: BackgroundTask;++ /**+ * Builds the `TaskDelegated` sentinel to return from `execute`. Centralizes+ * receipt stamping so every receipt carries this task's `taskId` and+ * `status: "working"` — tools cannot mint receipts for tasks they don't own.+ */+ delegated<TData extends JsonObject>(input: {+ readonly executor: TaskExecutorBinding;+ readonly receipt: TData;+ }): TaskDelegated<TData>;+}++export function createTaskDelegated<TData extends JsonObject>(input: {+ readonly binding: TaskBinding;+ readonly executor: TaskExecutorBinding;+ readonly receipt: TData;+}): TaskDelegated<TData> {+ return {+ executor: input.executor,+ kind: TASK_DELEGATED_KIND,+ receipt: { ...input.receipt, status: "working", taskId: input.binding.taskId },+ };+}++export function isTaskDelegated(value: unknown): value is TaskDelegated {+ return (+ typeof value === "object" &&+ value !== null &&+ "kind" in value &&+ value.kind === TASK_DELEGATED_KIND+ );+}diff --git a/packages/eve/src/tasks/json.ts b/packages/eve/src/tasks/json.tsindex 557d2f842..84fe4c1bd 100644--- a/packages/eve/src/tasks/json.ts+++ b/packages/eve/src/tasks/json.ts@@ -3,13 +3,20 @@ import { z } from "#compiled/zod/index.js";import { jsonValueSchema } from "#shared/json-schemas.js";import type { JsonValue } from "#shared/json.js";import type { TaskView } from "#tasks/types.js";+import { readSubagentTaskMetadata } from "#tasks/types.js";-const taskMetadataJsonSchema = z.object({- agentId: z.string(),- kind: z.literal("subagent"),- mode: z.enum(["local", "remote"]),- name: z.string(),-});+const taskMetadataJsonSchema = z.union([+ z.object({+ agentId: z.string(),+ kind: z.literal("subagent"),+ mode: z.enum(["local", "remote"]),+ name: z.string(),+ }),+ z.object({+ kind: z.string(),+ name: z.string(),+ }),+]);const taskOutputJsonSchema = z.object({data: jsonValueSchema,@@ -54,9 +61,19 @@ type TaskViewJson = z.infer<typeof taskViewJsonSchema>;/** Projects a task view into the JSON value carried by tool results. */export function taskViewToJson(view: TaskView): TaskViewJson {+ const subagent = readSubagentTaskMetadata(view);+ const metadata =+ subagent === undefined+ ? view.metadata+ : {+ agentId: subagent.agentId,+ kind: subagent.kind,+ mode: subagent.mode,+ name: subagent.name,+ };// `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);+ return taskViewJsonSchema.parse({ ...view, metadata });}/** Projects many views into one `{ tasks }` tool output. */diff --git a/packages/eve/src/tasks/session-index.ts b/packages/eve/src/tasks/session-index.tsindex e863db6ae..0ab645dd4 100644--- a/packages/eve/src/tasks/session-index.ts+++ b/packages/eve/src/tasks/session-index.ts@@ -2,7 +2,8 @@ import { z } from "#compiled/zod/index.js";import type { HarnessSession, SessionStateMap } from "#harness/types.js";import type { JsonValue } from "#shared/json.js";-import type { TaskMetadata, TaskView } from "#tasks/types.js";+import type { TaskExecutorBinding } from "#shared/tool-task.js";+import { sameTaskMetadata, type DurableTaskMetadata, type TaskView } from "#tasks/types.js";/*** Session-state key for the parent's live-task index.@@ -32,20 +33,33 @@ export interface SessionTaskIndexEntry {readonly taskInboxToken: string;readonly createdByStepIndex?: number;readonly createdByTurnId: string;- readonly metadata: TaskMetadata;- readonly operationId: string;+ readonly executor?: TaskExecutorBinding;+ readonly metadata: DurableTaskMetadata;+ readonly operationId?: string;}-const taskMetadataSchema: z.ZodType<TaskMetadata> = z.strictObject({- agentId: z.string().min(1),- kind: z.literal("subagent"),- mode: z.enum(["local", "remote"]),- name: z.string().min(1),-});+const taskMetadataSchema: z.ZodType<DurableTaskMetadata> = z.union([+ z.strictObject({+ agentId: z.string().min(1),+ kind: z.literal("subagent"),+ mode: z.enum(["local", "remote"]),+ name: z.string().min(1),+ }),+ z.strictObject({+ kind: z.string().min(1),+ name: z.string().min(1),+ }),+]);const taskViewBaseShape = {executor: z.strictObject({+ binding: z+ .strictObject({+ data: z.record(z.string(), z.custom<JsonValue>()),+ kind: z.string().min(1),+ })+ .optional(),childSessionId: z.string().min(1).optional(),childTurnId: z.string().min(1).optional(),lifecycle: z.enum(["parked", "terminal"]).optional(),@@ -87,8 +101,14 @@ const sessionTaskIndexEntrySchema: z.ZodType<SessionTaskIndexEntry> = z.strictObtaskInboxToken: z.string().min(1),createdByStepIndex: z.number().int().nonnegative().optional(),createdByTurnId: z.string().min(1),+ executor: z+ .strictObject({+ data: z.record(z.string(), z.custom<JsonValue>()),+ kind: z.string().min(1),+ })+ .optional(),metadata: taskMetadataSchema,- operationId: z.string().min(1),+ operationId: z.string().min(1).optional(),taskId: z.string().min(1),taskRunId: z.string().min(1),terminalView: taskViewSchema.optional(),@@ -175,15 +195,6 @@ function isValidTerminalView(view: TaskView): boolean {}}-function sameTaskMetadata(left: TaskMetadata, right: TaskMetadata): boolean {- return (- left.agentId === right.agentId &&- left.kind === right.kind &&- left.mode === right.mode &&- left.name === right.name- );-}-/** Finds one owned task; `undefined` enforces parent-session ownership. */export function findSessionTaskEntry(state: SessionStateMap | undefined,diff --git a/packages/eve/src/tasks/transitions.test.ts b/packages/eve/src/tasks/transitions.test.tsindex b43493dda..7bdd06a44 100644--- a/packages/eve/src/tasks/transitions.test.ts+++ b/packages/eve/src/tasks/transitions.test.ts@@ -21,6 +21,10 @@ function createView(status: TaskStatus, overrides: Partial<TaskView> = {}): Taskconst TERMINAL_STATUSES: readonly TaskStatus[] = ["completed", "failed", "cancelled"];const ALL_COMMANDS: readonly TaskCommand[] = [+ {+ executor: { data: { operationId: "operation-1" }, kind: "export" },+ kind: "bind",+ },{ data: { answer: 42 }, kind: "complete" },{ data: { message: "boom" }, kind: "fail" },{ data: { message: "unindexed" }, kind: "reject-dispatch" },@@ -32,13 +36,59 @@ const ALL_COMMANDS: readonly TaskCommand[] = [];describe("applyTaskTransition", () => {+ it("binds an opaque executor binding idempotently", () => {+ const command = {+ executor: { data: { operationId: "operation-1" }, kind: "export" },+ kind: "bind",+ } as const;++ const bound = applyTaskTransition(createView("working"), command);+ expect(bound).toMatchObject({+ action: "accepted",+ view: {+ executor: { binding: command.executor },+ metadata: createView("working").metadata,+ status: "working",+ },+ });+ expect(applyTaskTransition(bound.view, command)).toEqual({+ action: "noop",+ view: bound.view,+ });+ expect(+ applyTaskTransition(bound.view, {+ executor: { data: { operationId: "operation-2" }, kind: "export" },+ kind: "bind",+ }),+ ).toMatchObject({ action: "rejected", view: bound.view });+ });++ it("retains a late executor binding after fast task completion", () => {+ const completed = applyTaskTransition(createView("working"), {+ data: { answer: 42 },+ kind: "complete",+ });+ const executor = { data: { operationId: "operation-1" }, kind: "export" };++ const bound = applyTaskTransition(completed.view, { executor, kind: "bind" });++ expect(bound).toMatchObject({+ action: "accepted",+ view: {+ executor: { binding: executor },+ lastOutput: { data: { answer: 42 }, type: "result" },+ status: "completed",+ },+ });+ });+it("completes a working task with a result output", () => {const result = applyTaskTransition(createView("working"), {data: { answer: 42 },kind: "complete",});- expect(result.outcome).toBe("accepted");+ expect(result.action).toBe("accepted");expect(result.view.status).toBe("completed");expect(result.view.lastOutput).toEqual({ data: { answer: 42 }, type: "result" });});@@ -51,7 +101,7 @@ describe("applyTaskTransition", () => {{ kind: "cancel", usage },] as const) {const result = applyTaskTransition(createView("working"), command);- expect(result.outcome).toBe("accepted");+ expect(result.action).toBe("accepted");expect(result.view.usage).toEqual(usage);}@@ -74,7 +124,7 @@ describe("applyTaskTransition", () => {kind: "fail",});- expect(result.outcome).toBe("accepted");+ expect(result.action).toBe("accepted");expect(result.view.status).toBe("failed");expect(result.view.lastOutput).toEqual({ data: { message: "boom" }, type: "error" });});@@ -85,7 +135,7 @@ describe("applyTaskTransition", () => {kind: "require-input",});- expect(result.outcome).toBe("accepted");+ expect(result.action).toBe("accepted");expect(result.view.status).toBe("input_required");expect(result.view.inputRequests).toEqual([{ question: "which region?", requestId: "req-1" }]);});@@ -103,7 +153,7 @@ describe("applyTaskTransition", () => {inputRequests,kind: "require-input",});- expect(result.outcome).toBe("rejected");+ expect(result.action).toBe("rejected");expect(result.view.status).toBe("working");}});@@ -113,11 +163,11 @@ describe("applyTaskTransition", () => {inputRequests: [{ question: "which region?", requestId: "req-1" }],kind: "require-input",});- expect(blocked.outcome).toBe("accepted");+ expect(blocked.action).toBe("accepted");const result = applyTaskTransition(blocked.view, { kind: "answered", requestIds: ["req-1"] });- expect(result.outcome).toBe("accepted");+ expect(result.action).toBe("accepted");expect(result.view.status).toBe("working");expect(result.view.inputRequests).toBeUndefined();});@@ -130,11 +180,11 @@ describe("applyTaskTransition", () => {],kind: "require-input",});- expect(blocked.outcome).toBe("accepted");+ expect(blocked.action).toBe("accepted");const result = applyTaskTransition(blocked.view, { kind: "answered", requestIds: ["req-1"] });- expect(result.outcome).toBe("accepted");+ expect(result.action).toBe("accepted");expect(result.view.status).toBe("input_required");expect(result.view.inputRequests).toEqual([{ question: "which size?", requestId: "req-2" }]);});@@ -148,11 +198,11 @@ describe("applyTaskTransition", () => {inputRequests: [{ question: "second", requestId: "req-2" }],kind: "require-input",});- expect(second.outcome).toBe("accepted");+ expect(second.action).toBe("accepted");const stale = applyTaskTransition(second.view, { kind: "answered", requestIds: ["req-1"] });- expect(stale.outcome).toBe("noop");+ expect(stale.action).toBe("noop");expect(stale.view.status).toBe("input_required");expect(stale.view.inputRequests).toEqual([{ question: "second", requestId: "req-2" }]);});@@ -189,14 +239,14 @@ describe("applyTaskTransition", () => {inputRequests: [{ question: "first", requestId: "req-1" }],kind: "require-input",});- expect(first.outcome).toBe("accepted");+ expect(first.action).toBe("accepted");const second = applyTaskTransition(first.view, {inputRequests: [{ question: "second", requestId: "req-2" }],kind: "require-input",});- expect(second.outcome).toBe("accepted");+ expect(second.action).toBe("accepted");expect(second.view.inputRequests).toEqual([{ question: "second", requestId: "req-2" }]);});@@ -205,14 +255,14 @@ describe("applyTaskTransition", () => {inputRequests: [{ question: "which?", requestId: "req-1" }],kind: "require-input",});- expect(blocked.outcome).toBe("accepted");+ expect(blocked.action).toBe("accepted");const completed = applyTaskTransition(blocked.view, { data: "done", kind: "complete" });- expect(completed.outcome).toBe("accepted");+ expect(completed.action).toBe("accepted");expect(completed.view.status).toBe("completed");const cancelled = applyTaskTransition(blocked.view, { kind: "cancel" });- expect(cancelled.outcome).toBe("accepted");+ expect(cancelled.action).toBe("accepted");expect(cancelled.view.status).toBe("cancelled");});@@ -222,37 +272,38 @@ describe("applyTaskTransition", () => {requestIds: ["req-1"],});- expect(result.outcome).toBe("noop");+ expect(result.action).toBe("noop");expect(result.view.status).toBe("working");});it("rejects a late completion after cancellation", () => {const cancelled = applyTaskTransition(createView("working"), { kind: "cancel" });- expect(cancelled.outcome).toBe("accepted");+ expect(cancelled.action).toBe("accepted");const late = applyTaskTransition(cancelled.view, { data: "too late", kind: "complete" });- expect(late.outcome).toBe("rejected");+ expect(late.action).toBe("rejected");expect(late.view.status).toBe("cancelled");expect(late.view.lastOutput).toBeUndefined();});it("treats repeated cancellation as an idempotent noop", () => {const cancelled = applyTaskTransition(createView("working"), { kind: "cancel" });- expect(cancelled.outcome).toBe("accepted");+ expect(cancelled.action).toBe("accepted");const again = applyTaskTransition(cancelled.view, { kind: "cancel" });- expect(again.outcome).toBe("noop");+ expect(again.action).toBe("noop");expect(again.view.status).toBe("cancelled");});- it.each(TERMINAL_STATUSES)("keeps %s final against every non-cancel command", (status) => {+ it.each(TERMINAL_STATUSES)("keeps %s final against every lifecycle command", (status) => {const view = createView(status);for (const command of ALL_COMMANDS) {+ if (command.kind === "bind") continue;if (command.kind === "cancel" && status === "cancelled") continue;const result = applyTaskTransition(view, command);- expect(result.outcome).toBe("rejected");+ expect(result.action).toBe("rejected");expect(result.view).toBe(view);}});@@ -260,7 +311,7 @@ describe("applyTaskTransition", () => {it("rejects cancel on completed and failed tasks", () => {for (const status of ["completed", "failed"] as const) {const result = applyTaskTransition(createView(status), { kind: "cancel" });- expect(result.outcome).toBe("rejected");+ expect(result.action).toBe("rejected");}});@@ -293,19 +344,19 @@ describe("applyTaskTransition", () => {},);- expect(result.outcome).toBe("rejected");+ expect(result.action).toBe("rejected");expect(result.view.executor?.childSessionId).toBe("child-session-1");});it("retains late usage on a terminal task without reviving it", () => {const usage = { cacheReadTokens: 1, cacheWriteTokens: 2, inputTokens: 300, outputTokens: 40 };const cancelled = applyTaskTransition(createView("working"), { kind: "cancel" });- if (cancelled.outcome !== "accepted") throw new Error("Expected cancellation to commit.");+ if (cancelled.action !== "accepted") throw new Error("Expected cancellation to commit.");const result = applyTaskTransition(cancelled.view, { kind: "settle-executor", usage });expect(result).toEqual({- outcome: "accepted",+ action: "accepted",view: { ...cancelled.view, executor: { lifecycle: "terminal" }, usage },});});diff --git a/packages/eve/src/tasks/transitions.ts b/packages/eve/src/tasks/transitions.tsindex 9a61c13a3..460f4ff55 100644--- a/packages/eve/src/tasks/transitions.ts+++ b/packages/eve/src/tasks/transitions.ts@@ -6,38 +6,22 @@ import type {TaskView,} from "#tasks/types.js";import { isTerminalTaskStatus, readTaskInputRequestId } from "#tasks/types.js";+import { jsonValuesEqual } from "#shared/json.js";/**- * Outcome of applying one command to a task view.+ * Action taken on one command applied to a task view.*- * - `accepted`: the state changed; the new view must be appended.+ * - `accepted`: the view changed; the new view must be appended.* - `noop`: the command is recognized and benign (idempotent cancel,* stale answer); nothing changed and nothing is appended.* - `rejected`: the command is invalid for the current status; the* reason is diagnostic only.*/type TaskTransitionResult =- | { readonly outcome: "accepted"; readonly view: TaskView }- | { readonly outcome: "noop"; readonly view: TaskView }- | { readonly outcome: "rejected"; readonly view: TaskView; readonly reason: string };+ | { readonly action: "accepted"; readonly view: TaskView }+ | { readonly action: "noop"; readonly view: TaskView }+ | { readonly action: "rejected"; readonly view: TaskView; readonly reason: string };-/**- * Pure transition function for the task lifecycle:- *- * ```text- * working <-> input_required- * | |- * +-----> completed- * +-----> failed- * +-----> cancelled- * ```- *- * Terminal states are final: a late child result can never revive a- * cancelled task, and repeated cancellation is idempotent. The durable- * task run is the only caller that persists accepted views, which is- * what serializes competing completion, cancellation, and input- * transitions.- *//*** Builds the settled view for one terminal command, carrying the* child's lifecycle verdict and reported usage when present. Usage is@@ -73,25 +57,82 @@ function terminalView(}}+/**+ * Pure transition function for the task lifecycle:+ *+ * ```text+ * working <-> input_required+ * | |+ * +-----> completed+ * +-----> failed+ * +-----> cancelled+ * ```+ *+ * Terminal states are final: a late child result can never revive a+ * cancelled task, and repeated cancellation is idempotent. The durable+ * task run is the only caller that persists accepted views, which is+ * what serializes competing completion, cancellation, and input+ * transitions.+ *+ * Orthogonal to the status, the view carries private executor state+ * (`TaskExecutorState`) with its own lifecycle. These commands move+ * executor fields, never the status above:+ *+ * ```text+ * binding: unset --bind-------> bound (replay noop, conflict rejected)+ * address: unset --start-turn-> session pinned (turn id updated per delivery)+ * verdict: unset --complete/fail/cancel/settle-executor-> parked | terminal+ * ```+ *+ * - `bind` writes the executor binding exactly once: replaying the+ * same binding is a noop, a different one is rejected.+ * - `start-turn` records the child session/turn ids used to address+ * the executor, rejecting a child-session mismatch.+ * - Terminal commands and a late `settle-executor` record the child's+ * lifecycle verdict: `parked` means the child session survived and+ * can take another delivery, `terminal` means it ended with the turn.+ */export function applyTaskTransition(view: TaskView, command: TaskCommand): TaskTransitionResult {+ if (command.kind === "bind") {+ const binding = view.executor?.binding;+ if (+ binding !== undefined &&+ binding.kind === command.executor.kind &&+ jsonValuesEqual(binding.data, command.executor.data)+ ) {+ return { action: "noop", view };+ }+ if (binding !== undefined) {+ return {+ action: "rejected",+ reason: `Task "${view.taskId}" already has an executor binding.`,+ view,+ };+ }+ return {+ action: "accepted",+ view: { ...view, executor: { ...view.executor, binding: command.executor } },+ };+ }+if (isTerminalTaskStatus(view.status)) {if (command.kind === "settle-executor") {const executor = { ...view.executor, lifecycle: "terminal" as const };if (sameUsage(view.usage, command.usage) && view.executor?.lifecycle === "terminal") {- return { outcome: "noop", view };+ return { action: "noop", view };}const next = { ...view, executor };return {- outcome: "accepted",+ action: "accepted",view: command.usage === undefined ? next : { ...next, usage: command.usage },};}if (command.kind === "cancel" && view.status === "cancelled") {- return { outcome: "noop", view };+ return { action: "noop", view };}return {- outcome: "rejected",+ action: "rejected",reason: `Task "${view.taskId}" is already ${view.status}; "${command.kind}" cannot change a terminal task.`,view,};@@ -100,7 +141,7 @@ export function applyTaskTransition(view: TaskView, command: TaskCommand): TaskTswitch (command.kind) {case "complete":return {- outcome: "accepted",+ action: "accepted",view: terminalView(view, command, {lastOutput: { data: command.data, type: "result" },status: "completed",@@ -109,7 +150,7 @@ export function applyTaskTransition(view: TaskView, command: TaskCommand): TaskTcase "fail":case "reject-dispatch":return {- outcome: "accepted",+ action: "accepted",view: terminalView(view, command, {lastOutput: { data: command.data, type: "error" },status: "failed",@@ -117,12 +158,12 @@ export function applyTaskTransition(view: TaskView, command: TaskCommand): TaskT};case "cancel":return {- outcome: "accepted",+ action: "accepted",view: terminalView(view, command, { status: "cancelled" }),};case "settle-executor":return {- outcome: "rejected",+ action: "rejected",reason: `Task "${view.taskId}" is not terminal; usage settles with its terminal command.`,view,};@@ -134,15 +175,15 @@ export function applyTaskTransition(view: TaskView, command: TaskCommand): TaskT(request) => readTaskInputRequestId(request) === command.requestId,)) {- return { outcome: "noop", view };+ return { action: "noop", view };}return {- outcome: "accepted",+ action: "accepted",view: { ...view, inputRequests: [...view.inputRequests, blocker] },};}return {- outcome: "accepted",+ action: "accepted",view: {inputRequests: [blocker],executor: view.executor,@@ -155,13 +196,13 @@ export function applyTaskTransition(view: TaskView, command: TaskCommand): TaskTcase "require-input":if (!isValidInputRequestBatch(command.inputRequests)) {return {- outcome: "rejected",+ action: "rejected",reason: `Task "${view.taskId}" received an invalid input request batch.`,view,};}return {- outcome: "accepted",+ action: "accepted",view: {inputRequests: command.inputRequests,executor: view.executor,@@ -173,10 +214,10 @@ export function applyTaskTransition(view: TaskView, command: TaskCommand): TaskTcase "ready":// The readiness command is also the barrier that releases a fast,// pre-acknowledgement HITL batch, so the workflow must observe it.- return { outcome: "accepted", view };+ return { action: "accepted", view };case "answered": {if (view.status !== "input_required") {- return { outcome: "noop", view };+ return { action: "noop", view };}const answered = new Set(command.requestIds);@@ -190,11 +231,11 @@ export function applyTaskTransition(view: TaskView, command: TaskCommand): TaskT// the current batch intact is what stops it from unblocking a// question the human never saw.if (remaining.length === outstanding.length) {- return { outcome: "noop", view };+ return { action: "noop", view };}if (remaining.length > 0) {return {- outcome: "accepted",+ action: "accepted",view: {inputRequests: remaining,executor: view.executor,@@ -206,7 +247,7 @@ export function applyTaskTransition(view: TaskView, command: TaskCommand): TaskT}return {- outcome: "accepted",+ action: "accepted",view: {executor: view.executor,metadata: view.metadata,@@ -218,7 +259,7 @@ export function applyTaskTransition(view: TaskView, command: TaskCommand): TaskTcase "start-turn": {if (command.taskId !== view.taskId) {return {- outcome: "rejected",+ action: "rejected",reason: `Task turn identity "${command.taskId}" does not match "${view.taskId}".`,view,};@@ -228,7 +269,7 @@ export function applyTaskTransition(view: TaskView, command: TaskCommand): TaskTview.executor.childSessionId !== command.childSessionId) {return {- outcome: "rejected",+ action: "rejected",reason: `Task child session "${command.childSessionId}" does not match "${view.executor.childSessionId}".`,view,};@@ -237,10 +278,10 @@ export function applyTaskTransition(view: TaskView, command: TaskCommand): TaskTview.executor?.childSessionId === command.childSessionId &&view.executor.childTurnId === command.childTurnId) {- return { outcome: "noop", view };+ return { action: "noop", view };}return {- outcome: "accepted",+ action: "accepted",view: {...view,executor: {diff --git a/packages/eve/src/tasks/types.ts b/packages/eve/src/tasks/types.tsindex 78aaea7ed..3b0951fc4 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 { TaskExecutorBinding } from "#shared/tool-task.js";import type { SubagentAuthorizationEvent } from "#channel/types.js";/**@@ -37,10 +38,64 @@ export interface TaskMetadata {readonly name: string;}+export type SubagentTaskMetadata = TaskMetadata;++/** Executor-neutral metadata retained by a non-subagent durable task. */+export interface BackgroundTaskMetadata {+ readonly kind: string;+ readonly name: string;+}++export type DurableTaskMetadata = BackgroundTaskMetadata | TaskMetadata;++export function createSubagentTaskMetadata(+ metadata: Omit<SubagentTaskMetadata, "kind" | "name"> & { readonly name: string },+): SubagentTaskMetadata {+ return { ...metadata, kind: "subagent" };+}++export function readSubagentTaskMetadata(task: {+ readonly executor?: TaskExecutorBinding | TaskExecutorState;+ readonly metadata: DurableTaskMetadata;+}): SubagentTaskMetadata | undefined {+ if (task.metadata.kind === "subagent" && "agentId" in task.metadata) {+ return task.metadata;+ }+ const executor = task.executor;+ 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 }+ : 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;+ const rightSubagent = "agentId" in right;+ return (+ leftSubagent === rightSubagent &&+ (!leftSubagent ||+ !rightSubagent ||+ (left.agentId === right.agentId && left.mode === right.mode))+ );+}+/** Private executor state retained for cancellation and address reconciliation. */export interface TaskExecutorState {+ /** Write-once executor address recorded by the `bind` command. */+ readonly binding?: TaskExecutorBinding;readonly childSessionId?: string;readonly childTurnId?: string;+ /**+ * Child-session verdict from the last settled turn: `parked` survived+ * and can take another delivery, `terminal` ended with the turn.+ */readonly lifecycle?: "parked" | "terminal";}@@ -137,7 +192,7 @@ export function readTaskInputRequestId(request: TaskInputRequest): string | unde/** Fields shared by every durable task view. */interface TaskViewBase {readonly taskId: string;- readonly metadata: TaskMetadata;+ readonly metadata: DurableTaskMetadata;/** Private executor state; deliberately excluded from model-visible JSON. */readonly executor?: TaskExecutorState;/**@@ -190,6 +245,10 @@ export type TaskView = TaskViewBase &/** Commands accepted by the durable task run's transition function. */export type TaskCommand =+ | {+ readonly executor: TaskExecutorBinding;+ readonly kind: "bind";+ }| {readonly kind: "complete";readonly data: JsonValue;diff --git a/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts b/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.tsindex d7f4f8ad5..c7f0d3e74 100644--- a/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts+++ b/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts@@ -249,7 +249,7 @@ describe("mounted extension installed under node_modules", () => {);expect(JSON.parse(extensionFiles[`node_modules/${PACKAGE_NAME}/dist/extension/_manifest.json`]!),- ).toMatchObject({ requires: { channel: 5, schedule: 3, subagent: 2 } });+ ).toMatchObject({ requires: { channel: 6, schedule: 3, subagent: 2 } });const app = await scenarioApp({name: "mounted-extension-installed",installDependencies: true,diff --git a/research/subagents-as-tasks-implementation.md b/research/subagents-as-tasks-implementation.mdindex e5e2b8751..e9dd57e66 100644--- a/research/subagents-as-tasks-implementation.md+++ b/research/subagents-as-tasks-implementation.md@@ -119,18 +119,29 @@ In the runtime-action dispatch step, add a delegated mode alongside the existing1. create the durable `working` task run and record it in the session task index;2. dispatch the child with a task binding in its adapter state, reusing the handle-storestart/continue planning for identity and addressing;-3. persist the child acknowledgement (`childSessionId`) on the handle, as agent-messaging- already does at dispatch;+3. return `task.delegated({ executor, receipt })` with a new `"subagent"` executor kind whose+ `data` carries the child acknowledgement (`{ agentId, childSessionId }`). The ack rides the+ task-private executor binding, never the model-visible receipt, so dispatch must yield+ `childSessionId` before `delegated()` is called;4. resolve the originating tool call **immediately** with the task receipt`{ taskId, status: "working" }`.+The handle ack is written at step commit, not by the tool: the background tool provider's+commit path matches `executor.kind === "subagent"` next to its unconditional session task+index write and persists the acknowledgement on the agent handle. There is no author-facing+effect API — framework-owned session writes stay in the provider, and compensation of the+dispatch on parent-step failure is already unconditional (`rejectDelegatedDispatch`).+Step 4 is what keeps the parent turn moving and history provider-valid: the receipt is the oneresult the existing key-based batch matching consumes, so the turn continues without a secondresult path. A task notification starts or nudges a parent turn and carries its ready result orerror directly. Nothing selects this mode yet.Verification: integration tests invoking the mode directly; replay tests proving the same-originating call returns the same task and never dispatches twice.+originating call returns the same task, byte-identical `executor.data`, and never dispatches+twice; commit writes the handle ack; parent-step failure compensates through+`rejectDelegatedDispatch` alone; turn cancellation retains the delegation result for the+restarted step.### Stage 4 — the task wire, and the flag selects the modediff --git a/research/tools-as-tasks.md b/research/tools-as-tasks.mdindex 90a405350..6ff0c581c 100644--- a/research/tools-as-tasks.md+++ b/research/tools-as-tasks.md@@ -15,7 +15,8 @@ finishes. The parent receives result-bearing lifecycle notifications and can cana framework-owned tool. The child can intentionally report progress to its parent with oneframework-owned tool.-Without the flag, current tool and subagent behavior must remain unchanged.+Without the flag, current subagent behavior must remain unchanged. The implementation uses a+generic background `defineTool` execution contract so the harness does not classify subagents.This draft is based on the [Tools as Tasks proposal], the earlier background-task plan in[PR #1085], and the storage-boundary findings from the closed [PR #1190] implementation spike.@@ -67,8 +68,8 @@ cancel paths.## Non-goals- Exposing an MCP Tasks server or client endpoint in this work.-- Changing authored tools, built-in tools, connections, skills, or dynamic workflows.-- Replacing `runtimeAction` lowering with a new public `defineTool` API.+- Stabilizing the experimental background `defineTool` contract for general authored tools.+- Changing connections, skills, or dynamic workflows.- Rolling back external side effects after cancellation.- Retrying failed subagent work automatically.- Streaming every progress event into model context.@@ -98,9 +99,9 @@ Tasks own execution lifecycle and availability; agent addresses do not duplicate`input_required`. At most one nonterminal task may target one child session. The model-visible`<agents>` projection keeps an occupied agent visible as busy and names its active task.-**Delegated execution** is a runtime execution mode, not a tool-authoring surface. A delegated-dispatch returns once the executor acknowledges the work; the task stays `working`, and every-later transition arrives over the task wire.+**Delegated execution** is the outcome of a background tool handing lifecycle ownership to an+external executor. The tool's `execute` returns once that executor acknowledges the work; the task+stays `working`, and every later transition arrives over the task wire.`completed`, `failed`, and `cancelled` are terminal statuses. `input_required` is not terminal,but it is ready for parent action. Entering either condition wakes the parent so it never@@ -118,8 +119,28 @@ export default defineAgent({});```-The flag changes only local and remote subagent calls. Every such call runs in background mode.-All other tools keep their current behavior.+The flag changes only local and remote subagent calls. Every such call is registered as a+background `defineTool` definition and runs in the AI SDK tool loop. Without the flag, the same+subagent tools retain their existing `runtimeAction` path.++The generic execution contract is:++```ts+defineTool({+ execution: "background",+ async execute(input, ctx, task) {+ const executor = await startExternalWork(input, task.binding);+ return task.delegated({+ executor: executor.binding,+ receipt: executor.receipt,+ });+ },+});+```++An ordinary `execute` return completes the task with that value. `task.delegated(...)` ends the+tool call with a `working` receipt while the external executor retains lifecycle ownership. The+task runtime adds `taskId` and `status` to the tool-owned receipt.The parent receives these framework-owned tools:@@ -157,9 +178,7 @@ interface TaskView {}interface TaskMetadata {- readonly agentId: string;- readonly kind: "subagent";- readonly mode: "local" | "remote";+ readonly kind: string;readonly name: string;}@@ -237,10 +256,10 @@ completed, failed, and cancelled are final## Delegated execution-Today the runtime parks subagent tool calls, dispatches them serially as a batch after the-synchronous calls, and holds the turn until every action in the batch resolves (the-[runtime-action park path], [serial dispatch loop], and [turn-level wait]). Delegated execution-replaces the park-and-wait mechanism in the same dispatch codepath:+Today, without `experimental.tasks`, the runtime parks subagent tool calls, dispatches them as a+batch after synchronous calls, and holds the turn until every action in the batch resolves (the+[runtime-action park path], [serial dispatch loop], and [turn-level wait]). With the experiment,+the AI SDK executes subagent definitions through the generic background-tool path:1. The harness creates a durable `working` task for the subagent call.2. It dispatches the child with the task binding.@@ -248,10 +267,24 @@ replaces the park-and-wait mechanism in the same dispatch codepath:4. The originating call receives its receipt and the turn continues.Everything after acknowledgement — progress, input requests, authorization, terminal outcome —-arrives over the task wire instead of resolving the dispatch. Delegated execution is an agent-runtime change, not a `defineTool` change: authored tool contracts and the `runtimeAction`-lowering stay as they are, and the mode lands inert until the experiment selects the two subagent-kinds into it. A later phase can expose delegation to authored tools on top of the same mode.+arrives over the task wire instead of resolving the dispatch. Task creation, parent indexing, the+commit barrier, readiness delivery, and compensation are generic background-tool mechanisms.+Local and remote definitions own only child dispatch, agent-handle effects, and mapping the task+wire onto their executor.++### Workflow host++The dynamic-workflow sandbox drives subagent calls through the same harness tool definitions,+but its host (`createWorkflowHostTools`) still executes only `runtimeAction` tools. With+`experimental.tasks` enabled, the background subagent definitions pass the `workflowCallable`+advertising filter and are then dropped by the host, so no host tools remain and the workflow+tool is not advertised. This is an accepted scope cut: workflows are unavailable under the+experiment.++Graduating the experiment removes the `runtimeAction` dispatch path rather than extending it.+The workflow host then executes background `defineTool` definitions through the same+task-creating `execute` path the model loop uses, and `execution: "background"` becomes the+workflow-callable contract, retiring the manual `workflowCallable` flag.## Parent and executor wire contract@@ -378,6 +411,8 @@ than MCP compatibility.subagent blocking behavior do not change.- With it enabled, a slow subagent returns a task receipt and the parent can take another modelstep before the child completes.+- With it enabled, the workflow tool is not advertised to the root session until graduation adds+ background-tool execution to the workflow host.- The original tool call has exactly one result in durable history. Later task output cannot beattached to that call a second time.- Local and remote subagents support the same five parent-child flows.@@ -407,6 +442,12 @@ than MCP compatibility.4. How are repeated progress messages coalesced before they start parent model turns?5. How are child token usage and remaining parent budgets accounted after a background childcompletes on a later turn?+6. Should background tool inputs be constrained to `JsonValue`? Today they cross the+ harness ↔ executor boundary as `unknown`: schema parsing can transform (a standard schema+ may emit e.g. a `Date`), so JSON-ness is not guaranteed by construction, and annotating the+ boundary alone would verify nothing. An honest constraint must land at the authoring layer+ (`TInput extends JsonValue` for background-capable tools) or as per-call runtime validation;+ deferred until background tools need durable/serializable inputs.Two former open questions are settled and recorded in the [delivery plan]: failure taxonomy(`failed` carries the error output) and wake policy (terminal and `input_required` wake a