The Open Framework for Building Agents
chore(eve): tools - establish typed handling boundary (#2778)
Andrew Barbab0799b3d323c
diff --git a/.changeset/calm-tool-boundaries.md b/.changeset/calm-tool-boundaries.mdnew file mode 100644index 000000000..60e3e01f1--- /dev/null+++ b/.changeset/calm-tool-boundaries.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Preserve built-in tool behavior through compiled and runtime descriptors, so authored replacements, delegation, task controls, request input, and provider tools use the selected source instead of name-based runtime inference. Replacing bundled artifacts now invalidates resolved-agent caches so redeploys expose newly compiled skills consistently.diff --git a/packages/eve/extension-contracts/compatibility/tool/v22.ts b/packages/eve/extension-contracts/compatibility/tool/v22.tsnew file mode 100644index 000000000..f3e0e8878--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/tool/v22.ts@@ -0,0 +1,9 @@+import { defineTool } from "#public/tools/index.js";++export default defineTool({+ description: "Return the active tool identity.",+ inputSchema: { type: "object", properties: {} },+ execute(_input, ctx) {+ return { callId: ctx.callId, toolName: ctx.toolName };+ },+});diff --git a/packages/eve/extension-contracts/reports/tool/v23.json b/packages/eve/extension-contracts/reports/tool/v23.jsonnew file mode 100644index 000000000..f3ef47bd0--- /dev/null+++ b/packages/eve/extension-contracts/reports/tool/v23.json@@ -0,0 +1,19 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "tool",+ "epoch": 23,+ "sha256": "cb409b8ac67a397fc363f03d4d33db13de566d7d676be8ef5549768378337b6c",+ "exports": [+ "defaultWebSearch",+ "defineTool",+ "disableTool",+ "experimental_workflow",+ "isDisabledToolSentinel",+ "isExperimentalWorkflowToolDefinition",+ "isWebSearchToolDefinition",+ "toolOutput",+ "toolOutputPart",+ "toolResultFrom",+ "webSearch"+ ]+}diff --git a/packages/eve/src/client/agent-info-schema.ts b/packages/eve/src/client/agent-info-schema.tsindex 1de5d6700..12dc1a46a 100644--- a/packages/eve/src/client/agent-info-schema.ts+++ b/packages/eve/src/client/agent-info-schema.ts@@ -260,7 +260,6 @@ const kernelEffect = z"root-session","delegated-task-child","requires-request-input",- "requires-loadable-skill","below-subagent-depth",]),),diff --git a/packages/eve/src/compiler/compile-from-memory.test.ts b/packages/eve/src/compiler/compile-from-memory.test.tsindex a14eb672b..47420464f 100644--- a/packages/eve/src/compiler/compile-from-memory.test.ts+++ b/packages/eve/src/compiler/compile-from-memory.test.ts@@ -89,7 +89,7 @@ describe("compileFromMemory", () => {expect(manifest.bindings[skill!.sourceId]?.owner).toEqual({ kind: "application" });});- it("preserves roots and passes the serialized v44 schema", async () => {+ it("preserves roots and passes the current serialized manifest schema", async () => {const { manifest } = await compileFromMemory({agentRoot: "/app/agent",appRoot: "/app",diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.tsindex f8510f450..8aa57a978 100644--- a/packages/eve/src/compiler/extension-compatibility.ts+++ b/packages/eve/src/compiler/extension-compatibility.ts@@ -22,8 +22,8 @@ interface ExtensionCapabilityContract {const EXTENSION_CAPABILITY_CONTRACTS = {extension: { current: 1, supported: [1], dropped: {} },tool: {- current: 22,- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22],+ current: 23,+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23],dropped: { 15: "TaskExec replaces stageEffect with send" },},dynamicTool: {diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.tsindex 4e83f14be..e1e43ebfd 100644--- a/packages/eve/src/compiler/manifest.ts+++ b/packages/eve/src/compiler/manifest.ts@@ -28,7 +28,7 @@ import type {ModelRouting,} from "#shared/agent-definition.js";import type { InternalToolDefinition } from "#tools/definition.js";-import type { WebSearchProvider } from "#shared/web-search.js";+import type { CompiledToolBehavior } from "#tools/behavior.js";import type {AgentModuleBacking,AgentSourceComposition,@@ -54,7 +54,7 @@ export const ROOT_COMPILED_AGENT_NODE_ID = "__root__";/*** Current compiled manifest schema version.*/-export const COMPILED_AGENT_MANIFEST_VERSION = 45;+export const COMPILED_AGENT_MANIFEST_VERSION = 46;/*** Compiled channel entry preserved in the compiled manifest.@@ -233,6 +233,7 @@ export interface CompiledDynamicConnectionDefinition extends ModuleSourceRef {*/export type CompiledToolDefinition = InternalToolDefinition &ModuleSourceRef & {+ readonly behavior?: CompiledToolBehavior;readonly hasExecute: boolean;readonly hasModelOutputProjection: boolean;readonly requiresApproval: boolean;@@ -818,8 +819,40 @@ const compiledDynamicConnectionDefinitionSchema: z.ZodType<CompiledDynamicConnec}).strict();+const compiledToolBehaviorSchema: z.ZodType<CompiledToolBehavior> = z+ .object({+ availability: z+ .array(z.enum(["delegated-task-child", "requires-request-input", "root-session"]))+ .readonly(),+ handling: z+ .discriminatedUnion("kind", [+ z+ .object({+ action: z.enum(["self-agent", "task-cancel", "task-update"]),+ kind: z.literal("dispatch"),+ })+ .strict(),+ z+ .object({+ kind: z.literal("provider-tool"),+ provider: z.enum(["exa", "parallel"]),+ })+ .strict(),+ z+ .object({+ kind: z.literal("request-input"),+ request: z.literal("question"),+ })+ .strict(),+ ])+ .optional(),+ presentation: z.literal("load-skill").optional(),+ })+ .strict();+const compiledToolDefinitionSchema = z.object({+ behavior: compiledToolBehaviorSchema.optional(),description: z.string(),execution: z.literal("background").optional(),exportName: z.string().optional(),@@ -920,7 +953,6 @@ const compiledAgentResourceFields = {diagnosticsSummary: discoverDiagnosticsSummarySchema,sourceComposition: agentSourceCompositionSchema,workflowTool: compiledWorkflowToolDefinitionSchema.optional(),- webSearchProvider: z.enum(["exa", "parallel"]).optional(),dynamicInstructions: z.array(compiledDynamicInstructionsDefinitionSchema).default([]),dynamicSkills: z.array(compiledDynamicSkillDefinitionSchema).default([]),dynamicTools: z.array(compiledDynamicToolDefinitionSchema).default([]),@@ -1030,7 +1062,6 @@ export const compiledAgentManifestSchema = zdiagnosticsSummary: discoverDiagnosticsSummarySchema,sourceComposition: agentSourceCompositionSchema,workflowTool: compiledWorkflowToolDefinitionSchema.optional(),- webSearchProvider: z.enum(["exa", "parallel"]).optional(),dynamicInstructions: z.array(compiledDynamicInstructionsDefinitionSchema).default([]),dynamicSkills: z.array(compiledDynamicSkillDefinitionSchema).default([]),dynamicTools: z.array(compiledDynamicToolDefinitionSchema).default([]),@@ -1061,7 +1092,6 @@ export interface CreateCompiledAgentResourcesInput {readonly diagnosticsSummary?: DiscoverDiagnosticsSummary;readonly sourceComposition: AgentSourceComposition;readonly workflowTool?: CompiledWorkflowToolDefinition;- readonly webSearchProvider?: WebSearchProvider;readonly dynamicInstructions?: readonly CompiledDynamicInstructionsDefinition[];readonly dynamicSkills?: readonly CompiledDynamicSkillDefinition[];readonly dynamicTools?: readonly CompiledDynamicToolDefinition[];@@ -1102,7 +1132,6 @@ export function createCompiledAgentResources(entries: [...input.sourceComposition.entries],},workflowTool: input.workflowTool === undefined ? undefined : { ...input.workflowTool },- webSearchProvider: input.webSearchProvider,dynamicInstructions: [...(input.dynamicInstructions ?? [])],dynamicSkills: [...(input.dynamicSkills ?? [])],dynamicTools: [...(input.dynamicTools ?? [])],@@ -1249,7 +1278,6 @@ export function createCompiledAgentManifest(input: {readonly diagnosticsSummary?: DiscoverDiagnosticsSummary;readonly sourceComposition: AgentSourceComposition;readonly workflowTool?: CompiledWorkflowToolDefinition;- readonly webSearchProvider?: WebSearchProvider;readonly dynamicInstructions?: readonly CompiledDynamicInstructionsDefinition[];readonly dynamicSkills?: readonly CompiledDynamicSkillDefinition[];readonly dynamicTools?: readonly CompiledDynamicToolDefinition[];diff --git a/packages/eve/src/compiler/normalize-manifest.test.ts b/packages/eve/src/compiler/normalize-manifest.test.tsindex 8c9fba1a9..0e010e5c0 100644--- a/packages/eve/src/compiler/normalize-manifest.test.ts+++ b/packages/eve/src/compiler/normalize-manifest.test.ts@@ -23,6 +23,8 @@ import { defineInstructions } from "#public/definitions/instructions.js";import { defineSchedule } from "#public/definitions/schedule.js";import { defineSkill } from "#public/definitions/skill.js";import { resolveAgent } from "#runtime/resolve-agent.js";+import { resolveRuntimeAgentGraph } from "#runtime/resolve-agent-graph.js";+import { compiledAgentManifestSchema } from "#compiler/manifest.js";import { defineTool, disableTool } from "#tools/definition.js";import { defineMemory } from "#public/memory/index.js";import { defineDynamic } from "#dynamic/definition.js";@@ -112,6 +114,87 @@ describe("compileAgentManifest source graph", () => {expect(() => validateCompiledModuleMap(compiled, moduleMap)).not.toThrow();});+ it("preserves selected native behavior through serialization and runtime preparation", async () => {+ const sourceRegistry = registry([+ {+ logicalPath: "tools/web_search.ts",+ loadNamespace: async () => ({ default: webSearch({ provider: "parallel" }) }),+ },+ ]);+ const compiled = await compileAgentManifest(manifest(), {+ sourceRegistries: [sourceRegistry],+ });+ const serialized = compiledAgentManifestSchema.parse(JSON.parse(JSON.stringify(compiled)));+ const moduleMap = await createProgrammaticCompiledModuleMap(serialized, [+ frameworkAgentSourceRegistry,+ sourceRegistry,+ ]);+ const graph = await resolveRuntimeAgentGraph({ manifest: serialized, moduleMap });++ expect(serialized.tools.find((tool) => tool.name === "agent")).toMatchObject({+ behavior: {+ availability: ["root-session"],+ handling: { action: "self-agent", kind: "dispatch" },+ },+ hasExecute: false,+ });+ expect(serialized.tools.find((tool) => tool.name === "ask_question")).toMatchObject({+ behavior: {+ availability: ["requires-request-input"],+ handling: { kind: "request-input", request: "question" },+ },+ hasExecute: false,+ });+ expect(serialized.tools.find((tool) => tool.name === "web_search")).toMatchObject({+ behavior: {+ availability: [],+ handling: { kind: "provider-tool", provider: "parallel" },+ },+ hasExecute: false,+ });+ expect(graph.root.turnAgent.tools.find((tool) => tool.name === "agent")).toMatchObject({+ behavior: {+ handling: {+ kind: "dispatch",+ target: { kind: "self-agent-call", nodeId: "__root__", subagentName: "agent" },+ },+ },+ });+ expect(graph.root.turnAgent.tools.find((tool) => tool.name === "web_search")).toMatchObject({+ behavior: {+ handling: { kind: "provider-tool", provider: "parallel" },+ },+ });+ });++ it("keeps an authored framework-slot replacement as an ordinary executable tool", async () => {+ const execute = vi.fn(() => ({ ordinary: true }));+ const sourceRegistry = registry([+ {+ logicalPath: "tools/agent.ts",+ loadNamespace: async () => ({+ default: defineTool({ description: "Application agent tool.", execute, inputSchema: {} }),+ }),+ },+ ]);+ const compiled = await compileAgentManifest(manifest(), {+ sourceRegistries: [sourceRegistry],+ });+ const selected = compiled.tools.find((tool) => tool.name === "agent");+ expect(selected).toMatchObject({ hasExecute: true, logicalPath: "tools/agent.ts" });+ expect(selected?.behavior).toBeUndefined();++ const moduleMap = await createProgrammaticCompiledModuleMap(compiled, [+ frameworkAgentSourceRegistry,+ sourceRegistry,+ ]);+ const graph = await resolveRuntimeAgentGraph({ manifest: compiled, moduleMap });+ const resolved = graph.root.toolRegistry.toolsByName.get("agent")?.definition;+ expect(resolved?.behavior).toBeUndefined();+ expect(await resolved?.execute?.({}, {} as never)).toEqual({ ordinary: true });+ expect(execute).toHaveBeenCalledOnce();+ });+it("loads the selected config before any non-config definition", async () => {const order: string[] = [];const sourceRegistry = registry([diff --git a/packages/eve/src/compiler/normalize-manifest.ts b/packages/eve/src/compiler/normalize-manifest.tsindex 0e5533566..b41313982 100644--- a/packages/eve/src/compiler/normalize-manifest.ts+++ b/packages/eve/src/compiler/normalize-manifest.ts@@ -1,6 +1,5 @@import type { AgentSourceManifest } from "#discover/manifest.js";import type { ModuleSourceRef } from "#shared/source-ref.js";-import type { WebSearchProvider } from "#shared/web-search.js";import {type CompiledAgentDefinition,type CompiledAgentManifest,@@ -502,7 +501,6 @@ class AgentGraphCompiler {let sandbox: CompiledSandboxDefinition | undefined;let instrumentation: ModuleSourceRef | undefined;let workflowTool: CompiledWorkflowToolDefinition | undefined;- let webSearchProvider: WebSearchProvider | undefined;const selectedSourceIds = collectSelectedSourceIds(state.composed);const loadNamespace = state.evaluation.loadNamespace;@@ -620,7 +618,9 @@ class AgentGraphCompiler {selectedSourceIds.delete(candidate.sourceId);} else if (result.kind === "tool") {tools.push(result.definition);- state.evaluation.requireRuntimeEntry(candidate.sourceId);+ if (result.definition.hasExecute) {+ state.evaluation.requireRuntimeEntry(candidate.sourceId);+ }} else if (result.kind === "dynamic-tool") {dynamicTools.push(withExtensionNamespace(result.definition, candidate.owner));state.evaluation.requireRuntimeEntry(candidate.sourceId);@@ -630,7 +630,6 @@ class AgentGraphCompiler {} else {assertNonExtensionSpecialTool(candidate as AgentModuleCandidate, "Web search");tools.push(result.definition);- webSearchProvider = result.provider;}break;}@@ -693,7 +692,6 @@ class AgentGraphCompiler {skills,sourceComposition: state.composed.composition,tools,- webSearchProvider,workflowTool,});}diff --git a/packages/eve/src/compiler/normalize-tool.ts b/packages/eve/src/compiler/normalize-tool.tsindex 83e110060..e9e3a6a00 100644--- a/packages/eve/src/compiler/normalize-tool.ts+++ b/packages/eve/src/compiler/normalize-tool.ts@@ -21,7 +21,6 @@ export type CompiledToolEntry =| {readonly definition: CompiledToolDefinition;readonly kind: "web-search-tool";- readonly provider: "exa" | "parallel";}| { readonly kind: "dynamic-tool"; readonly definition: CompiledDynamicToolDefinition };@@ -71,6 +70,10 @@ export async function compileToolEntry(}return {definition: {+ behavior: {+ availability: [],+ handling: { kind: "provider-tool", provider: entry.provider },+ },description:"Search the web for real-time information. Use this to find up-to-date information about current events, recent developments, or topics that may have changed since the knowledge cutoff.",exportName: source.exportName,@@ -84,7 +87,6 @@ export async function compileToolEntry(requiresApproval: false,},kind: "web-search-tool",- provider: entry.provider,};}@@ -106,10 +108,11 @@ export async function compileToolEntry(return {kind: "tool",definition: {+ behavior: entry.definition.behavior,description: entry.definition.description,execution: entry.definition.execution,exportName: source.exportName,- hasExecute: true,+ hasExecute: entry.definition.hasExecute,hasModelOutputProjection: entry.definition.hasModelOutputProjection,inputSchema: entry.definition.inputSchema ?? null,logicalPath: source.logicalPath,diff --git a/packages/eve/src/context/dynamic-subagent-lifecycle.test.ts b/packages/eve/src/context/dynamic-subagent-lifecycle.test.tsindex 6ed80ef53..df7057543 100644--- a/packages/eve/src/context/dynamic-subagent-lifecycle.test.ts+++ b/packages/eve/src/context/dynamic-subagent-lifecycle.test.ts@@ -46,13 +46,18 @@ describe("dynamic subagent lifecycle", () => {expect(buildDynamicSubagentTools(ctx)).toMatchObject([{+ behavior: {+ handling: {+ kind: "dispatch",+ target: {+ kind: "subagent-call",+ nodeId: "subagents/researcher",+ subagentName: "researcher",+ },+ },+ },description: "Research the request.",name: "researcher",- runtimeAction: {- kind: "subagent-call",- nodeId: "subagents/researcher",- subagentName: "researcher",- },},]);expect(getDynamicSubagentSelection(ctx, resolver.nodeId)).toBeDefined();@@ -174,13 +179,18 @@ describe("dynamic subagent lifecycle", () => {expect(buildDynamicSubagentTools(ctx)).toMatchObject([{+ behavior: {+ handling: {+ kind: "dispatch",+ target: {+ kind: "remote-agent-call",+ nodeId: "subagents/researcher",+ remoteAgentName: "researcher",+ },+ },+ },description: "Research on the remote deployment.",name: "researcher",- runtimeAction: {- kind: "remote-agent-call",- nodeId: "subagents/researcher",- remoteAgentName: "researcher",- },},]);expect(getDynamicSubagentSelection(ctx, resolver.nodeId)).toMatchObject({diff --git a/packages/eve/src/execution/create-session-step.test.ts b/packages/eve/src/execution/create-session-step.test.tsindex b5c9de415..0a67d068a 100644--- a/packages/eve/src/execution/create-session-step.test.ts+++ b/packages/eve/src/execution/create-session-step.test.ts@@ -28,6 +28,10 @@ describe("createSessionStep", () => {...TestTurnAgent,tools: [{+ behavior: {+ availability: ["delegated-task-child"],+ handling: { kind: "dispatch", target: { kind: "task-update" } },+ },description: "Report task progress.",inputSchema: null,kind: "authored-tool",diff --git a/packages/eve/src/execution/create-session-step.ts b/packages/eve/src/execution/create-session-step.tsindex fe4c3ac95..b95f555bf 100644--- a/packages/eve/src/execution/create-session-step.ts+++ b/packages/eve/src/execution/create-session-step.ts@@ -14,7 +14,6 @@ import type { JsonObject } from "#shared/json.js";import { resolveEffectiveAgentRuntimeFromConfig } from "#execution/effective-agent-config.js";import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";import { TASK_UPDATE_SESSION_INSTRUCTION } from "#execution/tasks/child/instructions.js";-import { TASK_UPDATE_TOOL_NAME } from "#tools/framework/task-contract.js";/*** Result returned by {@link createSessionStep}.@@ -60,8 +59,8 @@ export async function createSessionStep(input: {effectiveAgent.turnAgent.tools.some((tool) =>tool.kind === "authored-tool" &&- tool.owner.kind === "framework" &&- tool.name === TASK_UPDATE_TOOL_NAME,+ tool.behavior?.handling?.kind === "dispatch" &&+ tool.behavior.handling.target.kind === "task-update",);// Both token axes resolve tighter-wins against the cap inherited from thediff --git a/packages/eve/src/execution/delegation-tool.ts b/packages/eve/src/execution/delegation-tool.tsindex 61b89f9f1..ba4ab9b31 100644--- a/packages/eve/src/execution/delegation-tool.ts+++ b/packages/eve/src/execution/delegation-tool.ts@@ -1,8 +1,9 @@import type { HarnessToolDefinition } from "#harness/execute-tool.js";import { createToolExecuteWithAuth } from "#execution/tool-auth.js";-import { defineSubagent, registerLocalSubagentExecutor } from "#execution/tools/subagent/local.js";+import { defineSubagent } from "#execution/tools/subagent/local.js";import { defineRemoteSubagent } from "#execution/tools/subagent/remote.js";import type { PreparedRuntimeDelegationTool } from "#runtime/sessions/turn.js";+import type { PreparedDispatchTarget } from "#tools/behavior.js";import {UNSPECIFIED_INPUT_SCHEMA,toInputSchema,@@ -12,70 +13,82 @@ import {type HarnessDelegationTool = Pick<PreparedRuntimeDelegationTool,- "description" | "kind" | "name" | "nodeId"+ "behavior" | "description" | "name"> & {readonly inputSchema?: ToolSchemaSource | null;readonly outputSchema?: ToolSchemaSource | null;- readonly rootOnly?: boolean;};+type AgentDispatchTarget = Extract<+ PreparedDispatchTarget,+ {+ readonly kind: "remote-agent-call" | "self-agent-call" | "subagent-call";+ }+>;+export function createHarnessDelegationToolDefinition(tool: HarnessDelegationTool,): HarnessToolDefinition {- const runtimeAction: HarnessToolDefinition["runtimeAction"] =- tool.kind === "remote"- ? {- kind: "remote-agent-call",- nodeId: tool.nodeId,- remoteAgentName: tool.name,- subagentName: tool.name,- }- : {- kind: "subagent-call",- nodeId: tool.nodeId,- subagentName: tool.name,- };-return {+ behavior: tool.behavior,description: tool.description ?? "",inputSchema: toInputSchema(tool.inputSchema) ?? UNSPECIFIED_INPUT_SCHEMA,name: tool.name,outputSchema: toOutputSchema(tool.outputSchema) ?? undefined,- rootOnly: tool.rootOnly,- runtimeAction,- workflowCallable: true,};}export function createBackgroundSubagentHarnessDefinition(tool: HarnessDelegationTool,): HarnessToolDefinition {- const definition =- tool.kind === "remote"- ? defineRemoteSubagent({- description: tool.description ?? "",- name: tool.name,- nodeId: tool.nodeId,- })- : defineSubagent({- description: tool.description ?? "",- name: tool.name,- nodeId: tool.nodeId,- });+ const target = tool.behavior?.handling;+ if (target?.kind !== "dispatch") {+ throw new Error(`Background subagent tool "${tool.name}" has no prepared dispatch target.`);+ }+ if (target.target.kind === "task-cancel" || target.target.kind === "task-update") {+ throw new Error(+ `Background subagent tool "${tool.name}" cannot dispatch ${target.target.kind}.`,+ );+ }+ const definition = createBackgroundSubagentDefinition({+ description: tool.description ?? "",+ name: tool.name,+ target: target.target,+ });const execute = createToolExecuteWithAuth({execute: definition.execute,execution: definition.execution,scope: tool.name,});- if (tool.kind !== "remote") registerLocalSubagentExecutor(execute);return {+ behavior: tool.behavior,description: definition.description,execute,execution: definition.execution,inputSchema: toInputSchema(definition.inputSchema) ?? UNSPECIFIED_INPUT_SCHEMA,name: tool.name,outputSchema: toOutputSchema(definition.outputSchema) ?? undefined,- rootOnly: tool.rootOnly,- workflowCallable: true,};}++function createBackgroundSubagentDefinition(input: {+ readonly description: string;+ readonly name: string;+ readonly target: AgentDispatchTarget;+}) {+ switch (input.target.kind) {+ case "remote-agent-call":+ return defineRemoteSubagent({+ description: input.description,+ name: input.name,+ target: input.target,+ });+ case "self-agent-call":+ case "subagent-call":+ return defineSubagent({+ description: input.description,+ name: input.name,+ target: input.target,+ });+ }+}diff --git a/packages/eve/src/execution/dispatch-runtime-actions-shared.ts b/packages/eve/src/execution/dispatch-runtime-actions-shared.tsindex 55fdac894..79d6c3502 100644--- a/packages/eve/src/execution/dispatch-runtime-actions-shared.ts+++ b/packages/eve/src/execution/dispatch-runtime-actions-shared.ts@@ -33,7 +33,6 @@ import {import { deserializeContext } from "#context/serialize.js";import {type DispatchOutcome,- isAgentHandleAction,type RuntimeAgentHandleAction,type RuntimeSession,} from "#execution/agent-handle-dispatch.js";@@ -51,13 +50,16 @@ import {} from "#protocol/message.js";import type { ActivityWorkIdentityV1 } from "#protocol/activity.js";import type {- RuntimeActionRequest,RuntimeActionResult,RuntimeRemoteAgentCallActionRequest,RuntimeSubagentCallActionRequest,RuntimeSubagentDispatchFailure,- RuntimeToolCallActionRequest,} from "#shared/action-types.js";+import type {+ PendingAgentDispatchAction,+ PendingDispatchAction,+ PendingTaskControlAction,+} from "#shared/dispatch-action.js";import { type DurableSessionState, readDurableSession } from "#execution/durable-session-store.js";import {createRecursiveAgentRootOnlyResult,@@ -75,6 +77,8 @@ import { resolveSubagentDepth } from "#harness/subagent-depth.js";import { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";import { isTaskControlAction } from "#execution/tasks/parent/dispatch.js";+import { isSubagentDelegationAction } from "#harness/subagent-depth.js";+import { resolvePreparedAgentAction } from "#execution/prepared-agent-action.js";const log = createLogger("execution.dispatch-runtime-actions");@@ -101,13 +105,14 @@ export type DispatchPlanEntry =}| { readonly kind: "reject"; readonly result: RuntimeSubagentDispatchFailure }| { readonly kind: "start"; readonly target: DispatchStartTarget }- | { readonly kind: "task-control"; readonly action: RuntimeToolCallActionRequest };+ | { readonly kind: "task-control"; readonly action: PendingTaskControlAction };export type DispatchStartTarget =| {readonly kind: "local";readonly action: RuntimeSubagentCallActionRequest;readonly dynamicSubagentAgentConfig?: DynamicSubagentAgentConfig;+ readonly selfAgent: boolean;readonly source: SubagentInputSource;}| {@@ -202,7 +207,7 @@ export async function prepareRuntimeActionDispatch(input: {}export async function prepareAgentActionDispatch(input: {- readonly action: RuntimeActionRequest;+ readonly action: PendingAgentDispatchAction;readonly ctx: AlsContext;readonly event: {readonly sequence: number;@@ -329,14 +334,10 @@ function planSharesSandbox(input: {const graph = (input.bundle as Partial<CompiledBundle>).graph;return input.plan.some((entry) => {if (entry.kind !== "start" || entry.target.kind !== "local") return false;- const action = entry.target.action;- const isSelfDelegation =- action.subagentName === "agent" &&- !input.bundle.subagentRegistry.subagentsByNodeId.has(action.nodeId);return (- isSelfDelegation ||- graph?.nodesByNodeId.get(action.nodeId)?.sandboxRegistry.sandbox.definition.inheritsParent ===- true+ entry.target.selfAgent ||+ graph?.nodesByNodeId.get(entry.target.action.nodeId)?.sandboxRegistry.sandbox.definition+ .inheritsParent === true);});}@@ -426,7 +427,7 @@ export async function emitSubagentCalled(input: {* resolves to a stored handle becomes a resume.*/function planDispatch(input: {- readonly actions: readonly RuntimeActionRequest[];+ readonly actions: readonly PendingDispatchAction[];readonly bundle: CompiledBundle;readonly ctx: Parameters<typeof getDynamicSubagentSelection>[0];readonly session: RuntimeSession;@@ -439,24 +440,32 @@ function planDispatch(input: {return { action, kind: "task-control" };}+ if (!isSubagentDelegationAction(action)) {+ throw new Error(+ `Unsupported prepared dispatch target "${action.target.kind}" in workflow runtime.`,+ );+ }+ const resolved = resolvePreparedAgentAction(action);+const rawAgentId = action.input.agentId;const agentId =typeof rawAgentId === "string" && rawAgentId.trim() !== "" ? rawAgentId : undefined;- if (agentId !== undefined && isAgentHandleAction(action)) {+ if (agentId !== undefined) {// Resume classification runs before the recursion guard: an agentId// continuation resumes an already-adopted child rather than starting// a new one. Unknown ids go through classifyFreshStart below, which// re-applies the guard the resume path bypasses.if (handles.some((handle) => handle.identity.id === agentId)) {const dynamicSubagentSelection =- input.bundle.subagentRegistry.dynamicNodeIds?.has(action.nodeId) === true- ? getDynamicSubagentSelection(input.ctx, action.nodeId)+ input.bundle.subagentRegistry.dynamicNodeIds?.has(resolved.action.nodeId) === true+ ? getDynamicSubagentSelection(input.ctx, resolved.action.nodeId): undefined;return {- action,+ action: resolved.action,agentId,dynamicRemoteAgent:- action.kind === "remote-agent-call" && dynamicSubagentSelection?.kind === "remote"+ resolved.action.kind === "remote-agent-call" &&+ dynamicSubagentSelection?.kind === "remote"? dynamicSubagentSelection.remoteAgent: undefined,kind: "resume",@@ -469,9 +478,10 @@ function planDispatch(input: {}return classifyFreshStart({- action,+ action: resolved.action,bundle: input.bundle,ctx: input.ctx,+ selfAgent: resolved.selfAgent,session: input.session,});});@@ -483,15 +493,17 @@ function planDispatch(input: {* unknown-agentId fallback, so both paths enforce the same guard.*/function classifyFreshStart(input: {- readonly action: RuntimeActionRequest;+ readonly action: RuntimeAgentHandleAction;readonly bundle: CompiledBundle;readonly ctx: Parameters<typeof getDynamicSubagentSelection>[0];+ readonly selfAgent: boolean;readonly session: RuntimeSession;}): Extract<DispatchPlanEntry, { kind: "reject" | "start" }> {const { action } = input;const registry = input.bundle.subagentRegistry.subagentsByNodeId;const subagentDepth = resolveSubagentDepth(input.session);- const rootOnly = input.session.rootSessionId !== undefined || subagentDepth.currentDepth > 0;+ const outsideRootSession =+ input.session.rootSessionId !== undefined || subagentDepth.currentDepth > 0;const isDynamicSubagent =(action.kind === "subagent-call" || action.kind === "remote-agent-call") &&@@ -514,7 +526,10 @@ function classifyFreshStart(input: {return { kind: "reject", result: createUnavailableDynamicSubagentResult(action) };}- if (isRecursiveAgentAction(action, registry) && rootOnly) {+ if (input.selfAgent && action.kind !== "subagent-call") {+ throw new Error("A self-agent dispatch target must resolve to a local subagent action.");+ }+ if (input.selfAgent && outsideRootSession && action.kind === "subagent-call") {log.warn("recursive agent call blocked outside the root session", {callId: action.callId,currentDepth: subagentDepth.currentDepth,@@ -552,6 +567,7 @@ function classifyFreshStart(input: {action,dynamicSubagentAgentConfig: dynamicAgentConfig,kind: "local",+ selfAgent: input.selfAgent,source,},};@@ -568,8 +584,10 @@ function classifyFreshStart(input: {kind: "remote",},};- default:- throw new Error(`Unsupported runtime action kind "${action.kind}" in workflow runtime.`);+ default: {+ const _exhaustive: never = action;+ return _exhaustive;+ }}}@@ -622,6 +640,7 @@ export async function startSubagent(input: {parentTraceContext,activityObserver: input.activityObserver,sandboxSessionId: input.sandboxSessionId,+ selfAgent: input.target.selfAgent,session: input.session,source: input.target.source,taskOwned: input.taskOwned,@@ -648,14 +667,3 @@ export async function startSubagent(input: {}}}--function isRecursiveAgentAction(- action: RuntimeActionRequest,- subagentsByNodeId: ReadonlyMap<string, unknown>,-): action is RuntimeSubagentCallActionRequest {- return (- action.kind === "subagent-call" &&- action.subagentName === "agent" &&- !subagentsByNodeId.has(action.nodeId)- );-}diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.tsindex 499c073f2..5143bce9d 100644--- a/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts@@ -222,10 +222,12 @@ describe("dispatchRuntimeActionsStep child starts", () => {callId: "call-1",description: "Research",input: { message: "research this" },- kind: "remote-agent-call",- name: "research",- nodeId: "remote/research",- remoteAgentName: "research",+ target: {+ kind: "remote-agent-call",+ nodeId: "remote/research",+ remoteAgentName: "research",+ },+ toolName: "research",},ctx,event: { sequence: 1, stepIndex: 2, turnId: "turn-1" },@@ -434,12 +436,16 @@ describe("dispatchRuntimeActionsStep child starts", () => {expect(create).not.toHaveBeenCalled();expect(mocks.createSession).toHaveBeenCalledTimes(1);+ const childInput = mocks.createSession.mock.calls[0]?.[0];+ expect(childInput?.adapter.state).not.toHaveProperty("parentSandboxState");+ expect(childInput?.adapter.state).not.toHaveProperty("sandboxSessionId");});it("rejects recursive self-delegation before opening the parent sandbox", async () => {const session = createNamedStartSession({name: "agent",nodeId: "__root__",+ selfAgent: true,session: { rootSessionId: "root-session", subagentDepth: 1 },});const { backend, create } = createSandboxBackend();@@ -1051,10 +1057,12 @@ describe("dispatchRuntimeActionsStep agent delivery", () => {callId: `call-${n}`,description: "Research",input: { agentId: LOCAL_PARKED_HANDLE.identity.id, message: `continue ${n}` },- kind: "subagent-call" as const,- name: "research",- nodeId: "subagents/research",- subagentName: "research",+ target: {+ kind: "subagent-call" as const,+ nodeId: "subagents/research",+ subagentName: "research",+ },+ toolName: "research",})),event: { sequence: 1, stepIndex: 2, turnId: "turn-1" },responseMessages: [],@@ -1240,19 +1248,23 @@ function createStartSession(input: {callId: "call-1",description: "Research",input: { message: "research this" },- kind: "subagent-call",- name: "research",- nodeId: "subagents/research",- subagentName: "research",+ target: {+ kind: "subagent-call",+ nodeId: "subagents/research",+ subagentName: "research",+ },+ toolName: "research",}: {callId: "call-1",description: "Research",input: { message: "research this" },- kind: "remote-agent-call",- name: "research",- nodeId: "remote/research",- remoteAgentName: "research",+ target: {+ kind: "remote-agent-call",+ nodeId: "remote/research",+ remoteAgentName: "research",+ },+ toolName: "research",},],event: input.event ?? { sequence: 1, stepIndex: 2, turnId: "turn-1" },@@ -1264,6 +1276,7 @@ function createStartSession(input: {function createNamedStartSession(input: {readonly name: string;readonly nodeId: string;+ readonly selfAgent?: boolean;readonly session?: Partial<HarnessSession>;}): HarnessSession {return setPendingRuntimeActionBatch({@@ -1272,10 +1285,18 @@ function createNamedStartSession(input: {callId: "call-1",description: `Delegate to ${input.name}`,input: { message: "research this" },- kind: "subagent-call",- name: input.name,- nodeId: input.nodeId,- subagentName: input.name,+ target: input.selfAgent+ ? {+ kind: "self-agent-call",+ nodeId: input.nodeId,+ subagentName: input.name,+ }+ : {+ kind: "subagent-call",+ nodeId: input.nodeId,+ subagentName: input.name,+ },+ toolName: input.name,},],event: { sequence: 1, stepIndex: 2, turnId: "turn-1" },@@ -1294,10 +1315,12 @@ function createPendingSession(input: {callId: "call-1",description: "Research",input: { agentId: input.agentId, message: "continue with raw input" },- kind: "subagent-call",- name: "research",- nodeId: "subagents/research",- subagentName: "research",+ target: {+ kind: "subagent-call",+ nodeId: "subagents/research",+ subagentName: "research",+ },+ toolName: "research",},],event: { sequence: 1, stepIndex: 2, turnId: "turn-1" },diff --git a/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.tsindex dfb8f18d2..aa7ab5236 100644--- a/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts+++ b/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts@@ -20,11 +20,8 @@ import {import { getSubagentDelegationName, isSubagentDelegationAction } from "#harness/subagent-depth.js";import { createLogger } from "#internal/logging.js";import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";-import type {- RuntimeActionRequest,- RuntimeSubagentDispatchFailure,- RuntimeActionResult,-} from "#shared/action-types.js";+import type { RuntimeSubagentDispatchFailure, RuntimeActionResult } from "#shared/action-types.js";+import type { PendingDispatchAction } from "#shared/dispatch-action.js";import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";const log = createLogger("execution.dispatch-workflow-runtime-actions");@@ -74,7 +71,7 @@ export async function dispatchWorkflowRuntimeActionsStep(input: {maxSubagents: plan.maxSubagents,subagentName: isSubagentDelegationAction(action)? getSubagentDelegationName(action)- : action.kind,+ : action.target.kind,usedCalls: plan.usedCalls,});return createWorkflowSubagentLimitResult({ action, plan });@@ -129,12 +126,12 @@ export async function dispatchWorkflowRuntimeActionsStep(input: {}function createWorkflowSubagentLimitResult(input: {- readonly action: RuntimeActionRequest;+ readonly action: PendingDispatchAction;readonly plan: WorkflowSubagentDispatchPlan;}): RuntimeSubagentDispatchFailure {const subagentName = isSubagentDelegationAction(input.action)? getSubagentDelegationName(input.action)- : input.action.kind;+ : input.action.target.kind;return {callId: input.action.callId,diff --git a/packages/eve/src/execution/node-step.test.ts b/packages/eve/src/execution/node-step.test.tsindex f907e1d17..336f9c7ce 100644--- a/packages/eve/src/execution/node-step.test.ts+++ b/packages/eve/src/execution/node-step.test.ts@@ -32,6 +32,7 @@ import { createStubSandboxRegistry } from "#internal/testing/stub-sandbox-registimport { defineTool } from "#tools/definition.js";import { stampDurableDynamicCallback } from "#tools/durable-callbacks.js";import { toInputSchema } from "#tools/schema.js";+import { AGENT_TOOL_DESCRIPTION } from "#tools/framework/agent-contract.js";vi.mock("ai", () => ({ToolLoopAgent: vi.fn(),@@ -210,14 +211,35 @@ function createTestNode(turnAgent?: RuntimeTurnAgent,overrides: Partial<ResolvedRuntimeAgentNode> = {},): ResolvedRuntimeAgentNode {- const agent = {} as ResolvedRuntimeAgentNode["agent"];+ const sandboxRegistry = createStubSandboxRegistry();+ const agent: ResolvedRuntimeAgentNode["agent"] = {+ channels: [],+ connections: [],+ dynamicConnectionResolvers: [],+ dynamicInstructionsResolvers: [],+ dynamicSkillResolvers: [],+ dynamicToolResolvers: [],+ hooks: [],+ instructions: [],+ memories: [],+ metadata: {+ agentRoot: "",+ appRoot: "",+ diagnosticsSummary: { errors: 0, warnings: 0 },+ },+ sandbox: sandboxRegistry.sandbox.definition,+ skills: [],+ tools: [],+ workspaceResourceRoot: sandboxRegistry.sandbox.workspaceResourceRoot,+ workspaceSpec: { rootEntries: [] },+ };return {agent,channels: [],hookRegistry: createEmptyHookRegistry(),nodeId: ROOT_RUNTIME_AGENT_NODE_ID,- sandboxRegistry: createStubSandboxRegistry(),+ sandboxRegistry,subagentRegistry: {dynamicNodeIds: new Set(),dynamicResolvers: [],@@ -236,18 +258,40 @@ async function createNodeWithSourceOwnedTools(input: {readonly tasks?: boolean;readonly turnTools?: StaticRuntimeTurnAgent["tools"];}): Promise<ResolvedRuntimeAgentNode> {- const toolRegistry = await createRuntimeToolRegistry({- tools: input.names.map((name) => ({- description: `${name} programmatic tool.`,- execute: async () => `${name}-sentinel`,- inputSchema: null,- logicalPath: `tools/${name}.ts`,- name,- owner: { feature: "test", kind: "framework" },- sourceId: `framework:tools/${name}.ts`,- sourceKind: "module",- })),- });+ const toolRegistry = await createRuntimeToolRegistry(+ {+ tools: input.names.map((name) => ({+ behavior:+ name === "agent"+ ? {+ availability: ["root-session"],+ handling: { action: "self-agent", kind: "dispatch" },+ }+ : name === "ask_question"+ ? {+ availability: ["requires-request-input"],+ handling: { kind: "request-input", request: "question" },+ }+ : name === "task_cancel"+ ? {+ availability: ["root-session"],+ handling: { action: "task-cancel", kind: "dispatch" },+ }+ : {+ availability: ["delegated-task-child"],+ handling: { action: "task-update", kind: "dispatch" },+ },+ description: name === "agent" ? AGENT_TOOL_DESCRIPTION : `${name} programmatic tool.`,+ inputSchema: null,+ logicalPath: `tools/${name}.ts`,+ name,+ owner: { feature: "test", kind: "framework" },+ sourceId: `framework:tools/${name}.ts`,+ sourceKind: "module",+ })),+ },+ { nodeId: ROOT_RUNTIME_AGENT_NODE_ID },+ );const node = createTestNode(createTestTurnAgent({tools: [...toolRegistry.preparedTools, ...(input.turnTools ?? [])],@@ -301,10 +345,13 @@ describe("createNodeHarnessTools", () => {expect(agentTool?.description).toContain("include essential context");expect(agentTool?.description).toContain("non-overlapping scopes");expect(agentTool?.description).not.toContain("eve");- expect(agentTool?.runtimeAction).toEqual({- kind: "subagent-call",- nodeId: ROOT_RUNTIME_AGENT_NODE_ID,- subagentName: "agent",+ expect(agentTool?.behavior?.handling).toEqual({+ kind: "dispatch",+ target: {+ kind: "self-agent-call",+ nodeId: ROOT_RUNTIME_AGENT_NODE_ID,+ subagentName: "agent",+ },});});@@ -328,7 +375,10 @@ describe("createNodeHarnessTools", () => {});for (const name of ["task_cancel", "task_update"]) {- expect(tools.get(name)?.runtimeAction).toEqual({ kind: "task-control" });+ expect(tools.get(name)?.behavior?.handling).toEqual({+ kind: "dispatch",+ target: { kind: name === "task_cancel" ? "task-cancel" : "task-update" },+ });expect(tools.get(name)?.execute).toBeUndefined();}expect(tools.has("task_sleep")).toBe(false);@@ -337,6 +387,17 @@ describe("createNodeHarnessTools", () => {it("executes compiled local and remote delegation tools in the selected task mode", async () => {const delegationTools: StaticRuntimeTurnAgent["tools"] = [{+ behavior: {+ availability: [],+ handling: {+ kind: "dispatch",+ target: {+ kind: "subagent-call",+ nodeId: "subagents/research",+ subagentName: "research",+ },+ },+ },description: "Delegate local research.",inputSchema: { type: "object" },kind: "subagent",@@ -346,6 +407,17 @@ describe("createNodeHarnessTools", () => {sourceId: "subagents/research",},{+ behavior: {+ availability: [],+ handling: {+ kind: "dispatch",+ target: {+ kind: "remote-agent-call",+ nodeId: "remote-agents/reviewer",+ remoteAgentName: "reviewer",+ },+ },+ },description: "Delegate remote review.",inputSchema: { type: "object" },kind: "remote",@@ -361,8 +433,14 @@ describe("createNodeHarnessTools", () => {turnTools: delegationTools,}),});- expect(legacy.get("research")?.runtimeAction?.kind).toBe("subagent-call");- expect(legacy.get("reviewer")?.runtimeAction?.kind).toBe("remote-agent-call");+ expect(legacy.get("research")?.behavior?.handling).toMatchObject({+ kind: "dispatch",+ target: { kind: "subagent-call" },+ });+ expect(legacy.get("reviewer")?.behavior?.handling).toMatchObject({+ kind: "dispatch",+ target: { kind: "remote-agent-call" },+ });expect(legacy.get("research")?.execution).toBeUndefined();expect(legacy.get("reviewer")?.execution).toBeUndefined();@@ -376,14 +454,16 @@ describe("createNodeHarnessTools", () => {for (const name of ["agent", "research", "reviewer"]) {expect(background.get(name)?.execution).toBe("background");expect(background.get(name)?.execute).toBeDefined();- expect(background.get(name)?.runtimeAction).toBeUndefined();+ expect(background.get(name)?.behavior?.handling?.kind).toBe("dispatch");}expect(countLocalSubagentCalls(["agent", "research", "reviewer"].map((name) => {- const execute = background.get(name)?.execute;- if (execute === undefined) throw new Error(`Missing background executor for ${name}.`);- return { definition: { execute } };+ const definition = background.get(name);+ if (definition?.execute === undefined) {+ throw new Error(`Missing background executor for ${name}.`);+ }+ return { definition };}),),).toBe(2);@@ -643,6 +723,65 @@ describe("createExecutionNodeStep", () => {);});+ it("always advertises load_skill when the node has no compiled skills", async () => {+ setupMockAgentForToolExecution("load_skill", { skill: "deploy-note" });+ const toolRegistry = await createRuntimeToolRegistry({+ tools: [+ {+ behavior: {+ availability: [],+ presentation: "load-skill",+ },+ description: "Load one skill.",+ execute: async () => "deploy-note instructions",+ inputSchema: toInputSchema({ type: "object" }),+ logicalPath: "tools/load_skill.ts",+ name: "load_skill",+ owner: { feature: "load-skill", kind: "framework" },+ sourceId: "framework:tools/load_skill.ts",+ sourceKind: "module",+ },+ ],+ });+ const rootNode = createTestNode(createTestTurnAgent({ tools: toolRegistry.preparedTools }), {+ toolRegistry,+ });+ expect(rootNode.agent.skills).toEqual([]);+ const step = createExecutionNodeStep({+ createRuntime: () => createNoopRuntime(),+ instrumentation: undefined,+ mode: "task",+ modelResolutionScope: { moduleMap: { nodes: {} }, nodeId: undefined },+ node: rootNode,+ });+ const ctx = new ContextContainer();+ ctx.set(AuthKey, null);+ ctx.set(InitiatorAuthKey, null);+ ctx.set(BundleKey, {+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),+ } as never);+ ctx.set(ChannelKey, { kind: "http" });+ ctx.set(SessionIdKey, "sess-root");+ ctx.set(SessionKey, {+ auth: { current: null, initiator: null },+ sessionId: "sess-root",+ turn: { id: "root-turn", sequence: 0 },+ });++ const result = await contextStorage.run(ctx, () =>+ step(+ createSession({+ continuationToken: "test-root",+ sessionId: "sess-root",+ turnAgent: rootNode.turnAgent,+ }),+ { message: "Load the deploy note skill." },+ ),+ );++ expect(result.next).toEqual({ done: true, output: "deploy-note instructions" });+ });+it("records visible subagent tools as pending runtime actions", async () => {setupMockAgentForToolCall("child-agent", { task: "Delegate this." });@@ -653,6 +792,17 @@ describe("createExecutionNodeStep", () => {createTestTurnAgent({tools: [{+ behavior: {+ availability: [],+ handling: {+ kind: "dispatch",+ target: {+ kind: "subagent-call",+ nodeId: "child-node",+ subagentName: "child-agent",+ },+ },+ },description: "Delegate work to the child agent.",inputSchema: { type: "object" },kind: "subagent",@@ -708,10 +858,12 @@ describe("createExecutionNodeStep", () => {callId: "call-subagent-1",description: "Delegate work to the child agent.",input: { task: "Delegate this." },- kind: "subagent-call",- name: "child-agent",- nodeId: "child-node",- subagentName: "child-agent",+ target: {+ kind: "subagent-call",+ nodeId: "child-node",+ subagentName: "child-agent",+ },+ toolName: "child-agent",},],event: {diff --git a/packages/eve/src/execution/node-step.ts b/packages/eve/src/execution/node-step.tsindex 478305758..4e06ce413 100644--- a/packages/eve/src/execution/node-step.ts+++ b/packages/eve/src/execution/node-step.ts@@ -9,7 +9,6 @@ import {} from "#execution/delegation-tool.js";import type { HarnessToolDefinition } from "#harness/execute-tool.js";import type { ExecutionInstrumentation } from "#instrumentation/runtime.js";-import { LOAD_SKILL_TOOL_NAME } from "#runtime/skills/fragment-context.js";import { createToolLoopHarness } from "#harness/tool-loop.js";import type { HandleEventFn, HarnessToolMap, StepFn } from "#harness/types.js";import { resolveInstalledPackageInfo } from "#internal/application/package.js";@@ -22,12 +21,6 @@ import {type RuntimeModelResolutionScope,} from "#runtime/agent/resolve-model.js";import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";-import {- AGENT_TOOL_DESCRIPTION,- AGENT_TOOL_NAME,- SUBAGENT_TOOL_INPUT_SCHEMA,-} from "#tools/framework/agent-contract.js";-import { createTaskToolHarnessDefinitions } from "#execution/tools/tasks.js";import type { ResolvedRuntimeAgentNode } from "#runtime/graph.js";import type { HistoryViewProjector, PreparedHistoryView } from "#shared/history-view.js";import type { PreparedRuntimeTool } from "#runtime/sessions/turn.js";@@ -35,7 +28,6 @@ import { findRegisteredRuntimeTool } from "#runtime/tools/registry.js";import type { ResolvedToolDefinition } from "#runtime/types.js";import { preserveFrameworkStateOnCompaction } from "#execution/compaction.js";import { createToolExecuteWithAuth } from "#execution/tool-auth.js";-import { ASK_QUESTION_TOOL_NAME } from "#harness/request-input-tool.js";const log = createLogger("execution.node-step");@@ -109,12 +101,12 @@ export function createExecutionNodeStep(input: CreateExecutionNodeStepInput): StcompactOnly: input.compactOnly,workflow: input.node.agent.workflowTool !== undefined,workflowMaxSubagents: input.workflowMaxSubagents,- webSearchProvider: input.node.agent.webSearchProvider,handleEvent: input.handleEvent,historyProjector: input.historyProjector,historyView: input.historyView,instrumentation: sessionInstrumentation,mode: input.mode,+ tasksEnabled: input.node.agent.config?.experimental?.tasks === true,onCompaction: preserveFrameworkStateOnCompaction,prepareStepDynamicTools: (prepareInput) =>preparePersistedStepDynamicToolMetadata({@@ -239,45 +231,40 @@ function resolveHarnessToolDefinition(input: {}const def = registeredTool.definition;- if (def.owner.kind === "framework" && def.name === AGENT_TOOL_NAME) {- const delegation = {- description: AGENT_TOOL_DESCRIPTION,- inputSchema: SUBAGENT_TOOL_INPUT_SCHEMA,- kind: "subagent" as const,- name: AGENT_TOOL_NAME,- nodeId: input.node.nodeId,- rootOnly: true,- };- return input.tasksEnabled- ? createBackgroundSubagentHarnessDefinition(delegation)- : createHarnessDelegationToolDefinition(delegation);+ const dispatchTarget =+ input.tool.behavior?.handling?.kind === "dispatch"+ ? input.tool.behavior.handling.target+ : undefined;+ if (+ !input.tasksEnabled &&+ (dispatchTarget?.kind === "task-cancel" || dispatchTarget?.kind === "task-update")+ ) {+ return null;}- if (def.owner.kind === "framework") {- const taskDefinition = createTaskToolHarnessDefinitions().find(- (definition) => definition.name === def.name,- );- if (taskDefinition !== undefined) {- return input.tasksEnabled ? taskDefinition : null;+ if (dispatchTarget?.kind === "self-agent-call" && input.tasksEnabled) {+ const behavior = input.tool.behavior;+ if (behavior === undefined) {+ throw new Error(`Self-agent tool "${input.tool.name}" has no prepared behavior.`);}+ return createBackgroundSubagentHarnessDefinition({+ behavior,+ description: input.tool.description,+ inputSchema: input.tool.inputSchema,+ name: input.tool.name,+ outputSchema: input.tool.outputSchema,+ });}const rawExecute = def.execute;- const isFrameworkRequestInput =- def.owner.kind === "framework" && def.name === ASK_QUESTION_TOOL_NAME;return {+ behavior: input.tool.behavior,approvalKey: def.approvalKey,description: def.description,execution: def.execution,- execute: isFrameworkRequestInput- ? undefined- : resolveAuthoredExecute({- rawExecute,- scope: def.name,- }),- frameworkAction:- def.owner.kind === "framework" && def.name === LOAD_SKILL_TOOL_NAME- ? "load-skill"- : undefined,+ execute: resolveAuthoredExecute({+ rawExecute,+ scope: def.name,+ }),inputSchema: def.inputSchema ?? UNSPECIFIED_INPUT_SCHEMA,name: def.name,approval: def.approval,diff --git a/packages/eve/src/execution/pending-turn-state.ts b/packages/eve/src/execution/pending-turn-state.tsindex 6c2a4d02b..538b83229 100644--- a/packages/eve/src/execution/pending-turn-state.ts+++ b/packages/eve/src/execution/pending-turn-state.ts@@ -2,7 +2,7 @@ import { getPendingAuthorization } from "#harness/authorization.js";import { hasPendingInputBatch } from "#harness/input-requests.js";import { getPendingRuntimeActionBatch } from "#harness/runtime-actions.js";import type { HarnessSession } from "#harness/types.js";-import { getRuntimeActionRequestKey } from "#runtime/actions/keys.js";+import { getPendingDispatchActionKey } from "#runtime/actions/keys.js";/** Derives the workflow fields used to select the next action at the park boundary. */export function derivePendingState(session: HarnessSession): {@@ -25,6 +25,6 @@ export function derivePendingState(session: HarnessSession): {if (batch === undefined) return base;return {...base,- pendingRuntimeActionKeys: batch.actions.map((action) => getRuntimeActionRequestKey(action)),+ pendingRuntimeActionKeys: batch.actions.map((action) => getPendingDispatchActionKey(action)),};}diff --git a/packages/eve/src/execution/prepared-agent-action.ts b/packages/eve/src/execution/prepared-agent-action.tsnew file mode 100644index 000000000..a4ad6e765--- /dev/null+++ b/packages/eve/src/execution/prepared-agent-action.ts@@ -0,0 +1,45 @@+import type { RuntimeAgentHandleAction } from "#execution/agent-handle-dispatch.js";+import type { PendingAgentDispatchAction } from "#shared/dispatch-action.js";++/** Converts a prepared dispatch identity into the existing agent transport contract. */+export function resolvePreparedAgentAction(action: PendingAgentDispatchAction): {+ readonly action: RuntimeAgentHandleAction;+ readonly selfAgent: boolean;+} {+ const common = {+ callId: action.callId,+ description: action.description,+ input: action.input,+ name: action.toolName,+ nodeId: action.target.nodeId,+ };+ switch (action.target.kind) {+ case "remote-agent-call":+ return {+ action: {+ ...common,+ kind: "remote-agent-call",+ remoteAgentName: action.target.remoteAgentName,+ },+ selfAgent: false,+ };+ case "self-agent-call":+ return {+ action: {+ ...common,+ kind: "subagent-call",+ subagentName: action.target.subagentName,+ },+ selfAgent: true,+ };+ case "subagent-call":+ return {+ action: {+ ...common,+ kind: "subagent-call",+ subagentName: action.target.subagentName,+ },+ selfAgent: false,+ };+ }+}diff --git a/packages/eve/src/execution/subagent-start-local.ts b/packages/eve/src/execution/subagent-start-local.tsindex ca03b2619..797601201 100644--- a/packages/eve/src/execution/subagent-start-local.ts+++ b/packages/eve/src/execution/subagent-start-local.ts@@ -41,6 +41,7 @@ export async function startLocalSubagent(input: {readonly parentTraceContext: Parameters<typeof buildSubagentRunInput>[0]["parentTraceContext"];readonly activityObserver?: Parameters<typeof buildSubagentRunInput>[0]["activityObserver"];readonly sandboxSessionId: string;+ readonly selfAgent: boolean;readonly session: RuntimeSession;readonly source: SubagentInputSource;readonly taskOwned: boolean;@@ -72,6 +73,7 @@ export async function startLocalSubagent(input: {parentTraceContext: input.parentTraceContext,activityObserver,sandboxSessionId: input.sandboxSessionId,+ selfAgent: input.selfAgent,session: input.session,source,});diff --git a/packages/eve/src/execution/subagent-tool.test.ts b/packages/eve/src/execution/subagent-tool.test.tsindex d90881ba3..98e63814b 100644--- a/packages/eve/src/execution/subagent-tool.test.ts+++ b/packages/eve/src/execution/subagent-tool.test.ts@@ -34,9 +34,13 @@ function makeAction(): RuntimeSubagentCallActionRequest {}function buildRuntimeSubagentRunInput(- input: Omit<BuildSubagentRunInput, "source">,+ input: Omit<BuildSubagentRunInput, "selfAgent" | "source"> & { readonly selfAgent?: boolean },): ReturnType<typeof buildSubagentRunInput> {- return buildSubagentRunInput({ ...input, source: { type: "runtime" } });+ return buildSubagentRunInput({+ ...input,+ selfAgent: input.selfAgent ?? false,+ source: { type: "runtime" },+ });}function makeInheritingGraph(nodeId: string) {@@ -225,6 +229,7 @@ describe("buildSubagentRunInput", () => {auth: null,batchEvent: { sequence: 0, turnId: "turn-0" },initiatorAuth: null,+ selfAgent: false,session: makeSession(),source: { description: "Research the request.", outputSchema: schema, type: "local" },});@@ -241,6 +246,7 @@ describe("buildSubagentRunInput", () => {auth: null,batchEvent: { sequence: 0, turnId: "turn-0" },initiatorAuth: null,+ selfAgent: false,session: makeSession(),source: { description: "Research the request.", outputSchema: declared, type: "local" },});@@ -279,6 +285,7 @@ describe("buildSubagentRunInput", () => {auth: null,batchEvent: { sequence: 0, turnId: "turn-0" },initiatorAuth: null,+ selfAgent: false,session: makeSession(),source: { description: "Local delegate subagent description.", type: "local" },});@@ -333,6 +340,7 @@ describe("buildSubagentRunInput", () => {auth: null,batchEvent: { sequence: 0, turnId: "turn-0" },initiatorAuth: null,+ selfAgent: true,session: makeSession(),source: { outputSchema: schema, type: "runtime" },});@@ -381,6 +389,7 @@ describe("buildSubagentRunInput", () => {auth: null,batchEvent: { sequence: 0, turnId: "turn-0" },initiatorAuth: null,+ selfAgent: true,session,});diff --git a/packages/eve/src/execution/subagent-tool.ts b/packages/eve/src/execution/subagent-tool.tsindex fc50e1a7d..824347248 100644--- a/packages/eve/src/execution/subagent-tool.ts+++ b/packages/eve/src/execution/subagent-tool.ts@@ -96,6 +96,7 @@ export function buildSubagentRunInput(input: {readonly graph?: SubagentSandboxGraph;/** Durable session identity of the sandbox currently used by the parent. */readonly sandboxSessionId?: string;+ readonly selfAgent: boolean;/** Hook token owned by the workflow currently waiting for this child. */readonly parentContinuationToken?: string;readonly parentTraceContext?: SessionTraceContext;@@ -139,7 +140,7 @@ export function buildSubagentRunInput(input: {};const sharesSandbox =input.graph?.nodesByNodeId.get(action.nodeId)?.sandboxRegistry.sandbox?.definition- .inheritsParent === true || action.subagentName === "agent";+ .inheritsParent === true || input.selfAgent;if (sharesSandbox) {if (session.sandboxState !== undefined) {adapterState.parentSandboxState = session.sandboxState;diff --git a/packages/eve/src/execution/tasks/child/update.ts b/packages/eve/src/execution/tasks/child/update.tsindex 79f0f3294..07a5f0b2d 100644--- a/packages/eve/src/execution/tasks/child/update.ts+++ b/packages/eve/src/execution/tasks/child/update.ts@@ -7,13 +7,14 @@ import {} from "#execution/subagent-adapter-state.js";import { createTaskControlError } from "#execution/tasks/parent/control-shared.js";import { resumeHook } from "#internal/workflow/runtime.js";-import type { RuntimeActionResult, RuntimeToolCallActionRequest } from "#shared/action-types.js";+import type { RuntimeActionResult } from "#shared/action-types.js";+import type { TaskControlInvocation } from "#shared/dispatch-action.js";import { readTaskIdFromInboxToken } from "#tasks/task-inbox-token.js";import type { TaskInboundUpdate } from "#tasks/types.js";/** Sends one child-authored progress update over its existing parent transport. */export async function executeTaskUpdate(input: {- readonly action: RuntimeToolCallActionRequest;+ readonly action: TaskControlInvocation;readonly adapter: ChannelAdapter | undefined;readonly updateIndex: number;readonly updateEpoch: string;@@ -66,7 +67,7 @@ function readUpdateMessage(input: Record<string, unknown>): string | undefined {}function createTaskUpdateResult(- action: RuntimeToolCallActionRequest,+ action: TaskControlInvocation,taskId: string,): RuntimeActionResult {return {diff --git a/packages/eve/src/execution/tasks/parent/control-shared.ts b/packages/eve/src/execution/tasks/parent/control-shared.tsindex d9eca1042..9bd407105 100644--- a/packages/eve/src/execution/tasks/parent/control-shared.ts+++ b/packages/eve/src/execution/tasks/parent/control-shared.ts@@ -2,7 +2,8 @@ import type { RuntimeSession } from "#execution/agent-handle-dispatch.js";import { readLatestTaskView } from "#execution/tasks/parent/run-parent.js";import { isTaskWorkflowTargetGone } from "#execution/tasks/workflow-target.js";import { getAgentHandleStore, type AgentHandle } from "#harness/handles/store.js";-import type { RuntimeActionResult, RuntimeToolCallActionRequest } from "#shared/action-types.js";+import type { RuntimeActionResult } from "#shared/action-types.js";+import type { TaskControlInvocation } from "#shared/dispatch-action.js";import { taskViewsToJson } from "#tasks/json.js";import {findSessionTaskEntry,@@ -109,7 +110,7 @@ export async function findActiveTaskForAgent(/** One successful task-control result carrying full task views. */export function createTaskViewsResult(- action: RuntimeToolCallActionRequest,+ action: TaskControlInvocation,views: readonly TaskView[],): RuntimeActionResult {return {@@ -122,7 +123,7 @@ export function createTaskViewsResult(/** One task-control error the model can act on. */export function createTaskControlError(- action: RuntimeToolCallActionRequest,+ action: TaskControlInvocation,message: string,): RuntimeActionResult {return {@@ -136,7 +137,7 @@ export function createTaskControlError(/** The ownership error for ids outside this session's task index. */export function createUnknownTasksError(- action: RuntimeToolCallActionRequest,+ action: TaskControlInvocation,unknown: readonly string[],): RuntimeActionResult {return createTaskControlError(diff --git a/packages/eve/src/execution/tasks/parent/dispatch.test.ts b/packages/eve/src/execution/tasks/parent/dispatch.test.tsindex 14c04cd70..a5e28056b 100644--- a/packages/eve/src/execution/tasks/parent/dispatch.test.ts+++ b/packages/eve/src/execution/tasks/parent/dispatch.test.ts@@ -12,7 +12,7 @@ import { executeTaskControlAction } from "#execution/tasks/parent/dispatch.js";import { readLatestTaskView, sendTaskCommand } from "#execution/tasks/parent/run-parent.js";import { requestWorkflowTurnCancellation } from "#execution/workflow-runtime.js";import { AGENT_HANDLES_STATE_KEY } from "#harness/handles/store.js";-import type { RuntimeToolCallActionRequest } from "#shared/action-types.js";+import type { PendingTaskControlAction } from "#shared/dispatch-action.js";import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";import { SESSION_TASKS_STATE_KEY } from "#tasks/session-index.js";@@ -35,10 +35,11 @@ vi.mock("#execution/remote-agent-dispatch.js", async (importOriginal) => ({resolveRemoteAgentStreamHeaders: vi.fn(),}));-const action: RuntimeToolCallActionRequest = {+const action: PendingTaskControlAction = {callId: "call-cancel",+ description: "Cancel tasks.",input: { taskIds: ["task-1"] },- kind: "tool-call",+ target: { kind: "task-cancel" },toolName: "task_cancel",};diff --git a/packages/eve/src/execution/tasks/parent/dispatch.ts b/packages/eve/src/execution/tasks/parent/dispatch.tsindex ea91b4d27..f503048df 100644--- a/packages/eve/src/execution/tasks/parent/dispatch.ts+++ b/packages/eve/src/execution/tasks/parent/dispatch.ts@@ -20,17 +20,9 @@ import type { DelegatedTask } from "#execution/tasks/parent/delegate.js";import { sendTaskCommand } from "#execution/tasks/parent/run-parent.js";import { requestWorkflowTurnCancellation } from "#execution/workflow-runtime.js";import { createLogger, logError } from "#internal/logging.js";-import type {- RuntimeActionRequest,- RuntimeActionResult,- RuntimeToolCallActionRequest,-} from "#shared/action-types.js";+import type { RuntimeActionResult } from "#shared/action-types.js";+import type { PendingDispatchAction, PendingTaskControlAction } from "#shared/dispatch-action.js";import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";-import {- TASK_CANCEL_TOOL_NAME,- TASK_TOOL_NAMES,- TASK_UPDATE_TOOL_NAME,-} from "#tools/framework/task-contract.js";import type { SessionTaskIndexEntry } from "#tasks/session-index.js";import {isTerminalTaskStatus,@@ -47,9 +39,9 @@ const CANCEL_COMMIT_POLL_DELAY_MS = 250;/** True for task-control calls dispatched outside the model loop. */export function isTaskControlAction(- action: RuntimeActionRequest,-): action is RuntimeToolCallActionRequest {- return action.kind === "tool-call" && TASK_TOOL_NAMES.has(action.toolName);+ action: PendingDispatchAction,+): action is PendingTaskControlAction {+ return action.target.kind === "task-cancel" || action.target.kind === "task-update";}/**@@ -60,7 +52,7 @@ export function isTaskControlAction(* Returns the current session alongside the action result.*/export async function executeTaskControlAction(input: {- readonly action: RuntimeToolCallActionRequest;+ readonly action: PendingTaskControlAction;readonly adapter?: ChannelAdapter;readonly bundle: CompiledBundle;readonly parentStepIndex?: number;@@ -74,7 +66,7 @@ export async function executeTaskControlAction(input: {}> {const { action, session } = input;- if (action.toolName === TASK_UPDATE_TOOL_NAME) {+ if (action.target.kind === "task-update") {return {result: await executeTaskUpdate({action,@@ -101,13 +93,6 @@ export async function executeTaskControlAction(input: {}const entries = lookup.entries;- if (action.toolName !== TASK_CANCEL_TOOL_NAME) {- return {- result: createTaskControlError(action, `Unsupported task control "${action.toolName}".`),- session,- };- }-const views: TaskView[] = [];for (const entry of entries) {views.push(diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts b/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.tsindex eb0bd136f..e1acaed1b 100644--- a/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts+++ b/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts@@ -95,19 +95,20 @@ describe("background subagent tool execution", () => {compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),});const sandbox = mockSandbox({ id: "background-subagent-sandbox" });- const backend: SandboxBackend = {- create: async (input: SandboxBackendCreateInput) => ({- captureState: async () => ({- backendName: "test",- metadata: {},- sessionKey: input.sessionKey,- }),- delete: async () => {},- session: sandbox.session,- shutdown: async () => {},- stop: async () => {},- useSessionFn: async () => sandbox.session,+ const createSandbox = vi.fn(async (input: SandboxBackendCreateInput) => ({+ captureState: async () => ({+ backendName: "test",+ metadata: {},+ sessionKey: input.sessionKey,}),+ delete: async () => {},+ session: sandbox.session,+ shutdown: async () => {},+ stop: async () => {},+ useSessionFn: async () => sandbox.session,+ }));+ const backend: SandboxBackend = {+ create: createSandbox,name: "test",prewarm: async () => ({ reused: false }),};@@ -145,16 +146,34 @@ describe("background subagent tool execution", () => {{ sequence: 1, sessionStarted: true, stepIndex: 0, turnId: "turn-background" },);const localTool = createBackgroundSubagentHarnessDefinition({+ behavior: {+ availability: ["root-session"],+ handling: {+ kind: "dispatch",+ target: {+ kind: "self-agent-call",+ nodeId: ROOT_RUNTIME_AGENT_NODE_ID,+ subagentName: "agent",+ },+ },+ },description: "General-purpose agent",- kind: "subagent",name: "agent",- nodeId: ROOT_RUNTIME_AGENT_NODE_ID,});const remoteTool = createBackgroundSubagentHarnessDefinition({+ behavior: {+ availability: [],+ handling: {+ kind: "dispatch",+ target: {+ kind: "remote-agent-call",+ nodeId: remoteNode.nodeId,+ remoteAgentName: remoteNode.name,+ },+ },+ },description: remoteNode.description,- kind: "remote",name: remoteNode.name,- nodeId: remoteNode.nodeId,});const model = new MockLanguageModelV4({doGenerate: {@@ -210,6 +229,14 @@ describe("background subagent tool execution", () => {const pendingTasks = result.backgroundTasks ?? [];const handles = getAgentHandleStore(result.session.state)?.handles ?? [];+ expect(createSandbox).toHaveBeenCalledTimes(2);+ for (const [input] of createSandbox.mock.calls) {+ expect(input).toEqual(+ expect.objectContaining({+ tags: expect.objectContaining({ sessionId: "parent-background-subagent" }),+ }),+ );+ }if (pendingTasks.length !== 3) throw new Error("Three durable tasks were not committed.");if (handles.some((handle) => handle.phase !== "addressed") || handles.length !== 3) {throw new Error("Three child addresses were not committed.");diff --git a/packages/eve/src/execution/tools/load-skill.test.ts b/packages/eve/src/execution/tools/load-skill.test.tsindex 0607d1095..2c4b7d9eb 100644--- a/packages/eve/src/execution/tools/load-skill.test.ts+++ b/packages/eve/src/execution/tools/load-skill.test.ts@@ -5,10 +5,11 @@ import { DynamicSkillManifestKey, SandboxKey } from "#context/keys.js";import { ConnectionRegistryKey } from "#context/providers/connection-key.js";import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";import type { ConnectionRegistry } from "#runtime/connections/registry-types.js";-import { loadSkill } from "#tools/provided/load-skill.js";import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";import { createSandboxSkillHandle } from "#runtime/skills/sandbox-access.js";import type { ResolvedSkillDefinition } from "#runtime/types.js";+import { readToolBehavior } from "#tools/behavior.js";+import { loadSkill } from "#tools/provided/load-skill.js";function skillToolExecutor(ctx: ContextContainer, skills: readonly ResolvedSkillDefinition[] = []) {ctx.set(BundleKey, {@@ -20,6 +21,13 @@ function skillToolExecutor(ctx: ContextContainer, skills: readonly ResolvedSkill}describe("loadSkill", () => {+ it("is always advertised", () => {+ expect(readToolBehavior(loadSkill)).toEqual({+ availability: [],+ presentation: "load-skill",+ });+ });+it("describes when skill loading should be used", () => {expect(loadSkill.description).toContain("request clearly matches a listed skill description");expect(loadSkill.description).toContain(diff --git a/packages/eve/src/execution/tools/subagent/local.ts b/packages/eve/src/execution/tools/subagent/local.tsindex 82edccc0f..d3ed746d7 100644--- a/packages/eve/src/execution/tools/subagent/local.ts+++ b/packages/eve/src/execution/tools/subagent/local.ts@@ -27,6 +27,8 @@ import type {RuntimeRemoteAgentCallActionRequest,RuntimeSubagentCallActionRequest,} from "#shared/action-types.js";+import type { PendingAgentDispatchAction } from "#shared/dispatch-action.js";+import { resolvePreparedAgentAction } from "#execution/prepared-agent-action.js";import { SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA } from "#tools/framework/task-contract.js";import { SUBAGENT_TOOL_INPUT_SCHEMA } from "#tools/framework/agent-contract.js";import { parseJsonObject } from "#shared/json.js";@@ -41,11 +43,12 @@ type SubagentCallAction = RuntimeRemoteAgentCallActionRequest | RuntimeSubagentCinterface SubagentDefinitionInput {readonly description: string;readonly name: string;- readonly nodeId: string;+ readonly target: PendingAgentDispatchAction["target"];}interface SubagentDispatchInput {readonly action: SubagentCallAction;+ readonly dispatchAction: PendingAgentDispatchAction;readonly batch: TaskExec["batch"];readonly callbackBaseUrl?: string;readonly ctx: AlsContext;@@ -69,8 +72,6 @@ interface SubagentDispatchResult {readonly session: RuntimeSession;}-/** Transitional PR 1 classifier, replaced by declared dispatch effects in PR 2. */-const localSubagentExecutors = new WeakSet<object>();const batchAgentClaims = new WeakMap<TaskExec["batch"], Map<string, string>>();const log = createLogger("runtime.framework-tools.subagent");@@ -81,24 +82,27 @@ export function defineSubagent(input: SubagentDefinitionInput) {inputSchema: SUBAGENT_TOOL_INPUT_SCHEMA,outputSchema: SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA,execute: (toolInput, ctx, task) =>- executeSubagentTool({ definition: input, kind: "local", task, toolContext: ctx, toolInput }),+ executeSubagentTool({ definition: input, task, toolContext: ctx, toolInput }),});return definition;}-export function registerLocalSubagentExecutor(execute: object): void {- localSubagentExecutors.add(execute);-}-export function countLocalSubagentCalls(- calls: readonly { readonly definition: { readonly execute: object } }[],+ calls: readonly {+ readonly definition: { readonly behavior?: import("#tools/behavior.js").PreparedToolBehavior };+ }[],): number {- return calls.filter((call) => localSubagentExecutors.has(call.definition.execute)).length;+ return calls.filter((call) => {+ const handling = call.definition.behavior?.handling;+ return (+ handling?.kind === "dispatch" &&+ (handling.target.kind === "self-agent-call" || handling.target.kind === "subagent-call")+ );+ }).length;}export async function executeSubagentTool(input: {readonly definition: SubagentDefinitionInput;- readonly kind: "local" | "remote";readonly task: TaskExec;readonly toolContext: ToolContext;readonly toolInput: unknown;@@ -106,30 +110,20 @@ export async function executeSubagentTool(input: {const ctx = loadContext();const { batch, session, task } = input.task;const emission = getHarnessEmissionState(session.state);- const commonAction = {+ const dispatchAction: PendingAgentDispatchAction = {callId: input.toolContext.callId,description: input.definition.description,input: parseJsonObject(SUBAGENT_TOOL_INPUT_SCHEMA.parse(input.toolInput)),- name: input.definition.name,- nodeId: input.definition.nodeId,+ target: input.definition.target,+ toolName: input.definition.name,};- const action: SubagentCallAction =- input.kind === "remote"- ? {- ...commonAction,- kind: "remote-agent-call",- remoteAgentName: input.definition.name,- }- : {- ...commonAction,- kind: "subagent-call",- subagentName: input.definition.name,- };+ const action: SubagentCallAction = resolvePreparedAgentAction(dispatchAction).action;const dispatched = await dispatchSubagent({action,batch,callbackBaseUrl: ctx.get(CallbackBaseUrlKey),ctx,+ dispatchAction,event: { ...emission, turnId: activeTurnId(emission) },localFanoutSize: countLocalSubagentCalls(batch),serializedContext: serializeContext(ctx),@@ -178,7 +172,7 @@ export async function executeSubagentTool(input: {async function dispatchSubagent(input: SubagentDispatchInput): Promise<SubagentDispatchResult> {const prepared = await prepareAgentActionDispatch({- action: input.action,+ action: input.dispatchAction,ctx: input.ctx,event: input.event,localFanoutSize: input.localFanoutSize,diff --git a/packages/eve/src/execution/tools/subagent/remote.ts b/packages/eve/src/execution/tools/subagent/remote.tsindex f6e73a1a7..b53274190 100644--- a/packages/eve/src/execution/tools/subagent/remote.ts+++ b/packages/eve/src/execution/tools/subagent/remote.ts@@ -2,11 +2,15 @@ import { defineTool } from "#tools/definition.js";import { SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA } from "#tools/framework/task-contract.js";import { SUBAGENT_TOOL_INPUT_SCHEMA } from "#tools/framework/agent-contract.js";import { executeSubagentTool } from "#execution/tools/subagent/local.js";+import type { PendingAgentDispatchAction } from "#shared/dispatch-action.js";export function defineRemoteSubagent(input: {readonly description: string;readonly name: string;- readonly nodeId: string;+ readonly target: Extract<+ PendingAgentDispatchAction["target"],+ { readonly kind: "remote-agent-call" }+ >;}) {return defineTool({description: input.description,@@ -14,6 +18,6 @@ export function defineRemoteSubagent(input: {inputSchema: SUBAGENT_TOOL_INPUT_SCHEMA,outputSchema: SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA,execute: (toolInput, ctx, task) =>- executeSubagentTool({ definition: input, kind: "remote", task, toolContext: ctx, toolInput }),+ executeSubagentTool({ definition: input, task, toolContext: ctx, toolInput }),});}diff --git a/packages/eve/src/execution/tools/tasks.ts b/packages/eve/src/execution/tools/tasks.tsdeleted file mode 100644index 2e573dee2..000000000--- a/packages/eve/src/execution/tools/tasks.ts+++ /dev/null@@ -1,61 +0,0 @@-import type { HarnessToolDefinition } from "#harness/execute-tool.js";-import {- TASK_CANCEL_INPUT_SCHEMA,- TASK_CANCEL_TOOL_NAME,- TASK_UPDATE_INPUT_SCHEMA,- TASK_UPDATE_TOOL_NAME,- TASK_VIEWS_OUTPUT_SCHEMA,-} from "#tools/framework/task-contract.js";--/**- * Framework task tools for `experimental.tasks`.- *- * With the flag on, subagent calls return a task receipt instead of- * blocking the parent turn; these tools coordinate that delegated work.- * `task_cancel` and `task_update` are execute-less runtime actions —- * they need durable session state and world access, so the runtime-action- * dispatch step executes them.- */--const TASK_CANCEL_DESCRIPTION =- "Request cooperative cancellation of one or more background tasks. " +- "Cancellation is final: a task that finishes after you cancel it stays cancelled. Cancelling an already-finished task changes nothing.";--const TASK_UPDATE_DESCRIPTION =- "Briefly tell the parent agent what this background task is currently doing. " +- "Report activity, not preliminary findings or results.";--/**- * Builds the harness definitions injected when the root agent enables- * `experimental.tasks`. Follows the implicit `agent` tool pattern:- * inline definitions, no registry entry, session-shape hiding in- * advertised-tools, and re-validation at dispatch.- */-export function createTaskToolHarnessDefinitions(): readonly HarnessToolDefinition[] {- return [- {- description: TASK_CANCEL_DESCRIPTION,- inputSchema: TASK_CANCEL_INPUT_SCHEMA,- name: TASK_CANCEL_TOOL_NAME,- outputSchema: TASK_VIEWS_OUTPUT_SCHEMA,- runtimeAction: { kind: "task-control" },- },- {- description: TASK_UPDATE_DESCRIPTION,- inputSchema: TASK_UPDATE_INPUT_SCHEMA,- name: TASK_UPDATE_TOOL_NAME,- runtimeAction: { kind: "task-control" },- },- ];-}--/**- * Whether one node's sessions receive the task tools.- *- * Mirrors `isImplicitAgentToolAvailable`: the compile step already- * rejects `experimental.tasks` on subagents, authored tools with the- * same name shadow the framework tool, and `disableTool(name)` removes- * individual tools. Root-node self-delegated children share this node's- * config, so advertised-tools uses caller/session shape to expose only- * `task_update` to delegated task children.- */diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.tsindex 6278b50b2..ae38a72b9 100644--- a/packages/eve/src/execution/workflow-steps.test.ts+++ b/packages/eve/src/execution/workflow-steps.test.ts@@ -832,19 +832,15 @@ describe("dispatchRuntimeActionsStep", () => {callId: "call-1",description: "Runtime action event description.",input: { message: "investigate latest routing" },- kind: "subagent-call",- name: "agent",- nodeId: "subagents/agent",- subagentName: "agent",+ target: { kind: "subagent-call", nodeId: "subagents/agent", subagentName: "agent" },+ toolName: "agent",},{callId: "call-2",description: "Second runtime action event description.",input: { message: "investigate fallback routing" },- kind: "subagent-call",- name: "agent",- nodeId: "subagents/agent",- subagentName: "agent",+ target: { kind: "subagent-call", nodeId: "subagents/agent", subagentName: "agent" },+ toolName: "agent",},],event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },@@ -997,10 +993,12 @@ describe("dispatchRuntimeActionsStep", () => {callId: "call-1",description: "Delegate the work.",input: { message: "investigate latest routing" },- kind: "remote-agent-call",- name: "research",- nodeId: "remote/research",- remoteAgentName: "research",+ target: {+ kind: "remote-agent-call",+ nodeId: "remote/research",+ remoteAgentName: "research",+ },+ toolName: "research",},],event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },@@ -1101,10 +1099,12 @@ describe("dispatchRuntimeActionsStep", () => {callId: "call-remote",description: "Delegate the work.",input: { message: "investigate latest routing" },- kind: "remote-agent-call",- name: "research",- nodeId: "remote/research",- remoteAgentName: "research",+ target: {+ kind: "remote-agent-call",+ nodeId: "remote/research",+ remoteAgentName: "research",+ },+ toolName: "research",},],event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },@@ -1204,10 +1204,8 @@ describe("dispatchRuntimeActionsStep", () => {callId: "call-dynamic-remote",description: "Delegate the work.",input: { message: "investigate latest routing" },- kind: "remote-agent-call",- name: "research",- nodeId,- remoteAgentName: "research",+ target: { kind: "remote-agent-call", nodeId, remoteAgentName: "research" },+ toolName: "research",},],event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },@@ -1285,10 +1283,8 @@ describe("dispatchRuntimeActionsStep", () => {callId: "call-1",description: "Delegate the work.",input: { message: "try to recurse" },- kind: "subagent-call",- name: "agent",- nodeId: "__root__",- subagentName: "agent",+ target: { kind: "self-agent-call", nodeId: "__root__", subagentName: "agent" },+ toolName: "agent",},],event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },@@ -1386,10 +1382,8 @@ describe("dispatchRuntimeActionsStep", () => {callId: "call-dynamic",description: "Research the request.",input: { message: "investigate" },- kind: "subagent-call",- name: "researcher",- nodeId,- subagentName: "researcher",+ target: { kind: "subagent-call", nodeId, subagentName: "researcher" },+ toolName: "researcher",},],event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },@@ -2287,8 +2281,13 @@ describe("turnStep", () => {actions: [{callId: "call-runtime",+ description: "Delegate work.",input: {},- kind: "tool-call",+ target: {+ kind: "subagent-call",+ nodeId: "subagents/runtime-tool",+ subagentName: "runtime-tool",+ },toolName: "runtime-tool",},],diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.tsindex 0ad164d8c..7d294775f 100644--- a/packages/eve/src/execution/workflow-steps.ts+++ b/packages/eve/src/execution/workflow-steps.ts@@ -104,7 +104,6 @@ import { resolveRuntimeCompiledArtifactsVersionedCacheKey } from "#runtime/cacheimport { createWorkflowRuntime } from "#execution/workflow-runtime.js";import { bindDynamicConnections } from "#execution/dynamic-connections.js";import { preserveCancelledTurnMessage } from "#execution/cancelled-turn-message.js";-import { TASK_UPDATE_TOOL_NAME } from "#tools/framework/task-contract.js";const TASK_DONE_WITH_PENDING_INPUT_ERROR_MESSAGE ="Task mode cannot complete while input requests remain pending.";@@ -142,8 +141,8 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResueffectiveAgent.turnAgent.tools.some((tool) =>tool.kind === "authored-tool" &&- tool.owner.kind === "framework" &&- tool.name === TASK_UPDATE_TOOL_NAME,+ tool.behavior?.handling?.kind === "dispatch" &&+ tool.behavior.handling.target.kind === "task-update",);// Populate the callback base URL so getHookUrl() works during tooldiff --git a/packages/eve/src/framework/sources/registry.ts b/packages/eve/src/framework/sources/registry.tsindex 8cc16aef9..159a8a623 100644--- a/packages/eve/src/framework/sources/registry.ts+++ b/packages/eve/src/framework/sources/registry.ts@@ -9,7 +9,7 @@ import {type ProgrammaticModuleNamespace,} from "#compiler/source-graph.js";-const revision = `eve@${resolveInstalledPackageInfo().version}:compiled-manifest-v44`;+const revision = `eve@${resolveInstalledPackageInfo().version}:compiled-manifest-v46`;const localDefaults = defineProgrammaticAgentSource({id: "eve:defaults",diff --git a/packages/eve/src/harness/advertised-tools.test.ts b/packages/eve/src/harness/advertised-tools.test.tsindex 1752f4c98..ca26f83f3 100644--- a/packages/eve/src/harness/advertised-tools.test.ts+++ b/packages/eve/src/harness/advertised-tools.test.ts@@ -186,22 +186,29 @@ function createTool(name: string): HarnessToolDefinition {function createSubagentTool(name: string): HarnessToolDefinition {return {...createTool(name),- runtimeAction: {- kind: "subagent-call",- nodeId: "workers",- subagentName: name,+ behavior: {+ availability: [],+ handling: {+ kind: "dispatch",+ target: { kind: "subagent-call", nodeId: "workers", subagentName: name },+ },},- workflowCallable: true,};}function createBuiltInAgentTool(): HarnessToolDefinition {return {...createSubagentTool("agent"),- runtimeAction: {- kind: "subagent-call",- nodeId: ROOT_RUNTIME_AGENT_NODE_ID,- subagentName: "agent",+ behavior: {+ availability: ["root-session"],+ handling: {+ kind: "dispatch",+ target: {+ kind: "self-agent-call",+ nodeId: ROOT_RUNTIME_AGENT_NODE_ID,+ subagentName: "agent",+ },+ },},};}@@ -209,7 +216,13 @@ function createBuiltInAgentTool(): HarnessToolDefinition {function createTaskControlTool(name: string): HarnessToolDefinition {return {...createTool(name),- runtimeAction: { kind: "task-control" },+ behavior: {+ availability: [name === "task_update" ? "delegated-task-child" : "root-session"],+ handling: {+ kind: "dispatch",+ target: { kind: name === "task_update" ? "task-update" : "task-cancel" },+ },+ },};}diff --git a/packages/eve/src/harness/advertised-tools.ts b/packages/eve/src/harness/advertised-tools.tsindex d1d7e64bf..80ba182b8 100644--- a/packages/eve/src/harness/advertised-tools.ts+++ b/packages/eve/src/harness/advertised-tools.ts@@ -1,9 +1,6 @@import type { ToolSet } from "ai";import type { HarnessToolDefinition } from "#harness/execute-tool.js";import { resolveSubagentDepth } from "#harness/subagent-depth.js";-import { AGENT_TOOL_NAME } from "#tools/framework/agent-contract.js";-import { TASK_TOOL_NAMES, TASK_UPDATE_TOOL_NAME } from "#tools/framework/task-contract.js";-import { ROOT_RUNTIME_AGENT_NODE_ID } from "#runtime/graph.js";import {ensureWorkflowContinuationSecurity,getWorkflowContinuationSecurity,@@ -14,18 +11,21 @@ import type { HarnessSession, HarnessToolMap } from "#harness/types.js";type AdvertisedToolSession = Pick<HarnessSession, "rootSessionId" | "subagentDepth">;type AdvertisedToolMapInput = {+ readonly canRequestInput?: boolean;readonly delegatedCaller?: boolean;readonly session: AdvertisedToolSession;readonly tools: HarnessToolMap;};type AdvertisedToolDefinitionsInput = {+ readonly canRequestInput?: boolean;readonly delegatedCaller?: boolean;readonly session: AdvertisedToolSession;readonly tools: readonly HarnessToolDefinition[];};type AdvertisedModelToolsInput = {+ readonly canRequestInput?: boolean;readonly delegatedCaller?: boolean;readonly modelTools: ToolSet;readonly session: HarnessSession;@@ -60,24 +60,16 @@ export function getAdvertisedTools(}if (isToolDefinitionList(input.tools)) {- return filterUnavailableDelegationToolDefinitions(- input.tools,- input.session,- input.delegatedCaller,- );+ return filterUnavailableDelegationToolDefinitions(input.tools, input.session, input);}- return filterUnavailableDelegationToolMap(input.tools, input.session, input.delegatedCaller);+ return filterUnavailableToolMap(input.tools, input.session, input);}async function getAdvertisedModelTools(input: AdvertisedModelToolsInput,): Promise<AdvertisedModelTools> {- const tools = filterUnavailableDelegationToolMap(- input.tools,- input.session,- input.delegatedCaller,- );+ const tools = filterUnavailableToolMap(input.tools, input.session, input);if (input.workflow === undefined) {return {harnessTools: tools,@@ -113,12 +105,12 @@ async function getAdvertisedModelTools(function filterUnavailableDelegationToolDefinitions(tools: readonly HarnessToolDefinition[],session: AdvertisedToolSession,- delegatedCaller: boolean | undefined,+ availability: Pick<AdvertisedToolDefinitionsInput, "canRequestInput" | "delegatedCaller">,): readonly HarnessToolDefinition[] {const filteredTools: HarnessToolDefinition[] = [];for (const tool of tools) {- if (shouldHideDelegationTool(tool, session, delegatedCaller)) {+ if (!isToolAvailable(tool, session, availability)) {continue;}filteredTools.push(tool);@@ -126,15 +118,15 @@ function filterUnavailableDelegationToolDefinitions(return filteredTools;}-function filterUnavailableDelegationToolMap(+function filterUnavailableToolMap(tools: HarnessToolMap,session: AdvertisedToolSession,- delegatedCaller: boolean | undefined,+ availability: Pick<AdvertisedToolMapInput, "canRequestInput" | "delegatedCaller">,): HarnessToolMap {const filteredTools = new Map<string, HarnessToolDefinition>();for (const [name, tool] of tools) {- if (shouldHideDelegationTool(tool, session, delegatedCaller)) {+ if (!isToolAvailable(tool, session, availability)) {continue;}filteredTools.set(name, tool);@@ -154,43 +146,47 @@ function filterWorkflowHostToolsForRootSession(}for (const [name, tool] of tools) {- if (tool.workflowCallable === true) {+ const target =+ tool.behavior?.handling?.kind === "dispatch" ? tool.behavior.handling.target : undefined;+ if (+ target?.kind === "self-agent-call" ||+ target?.kind === "subagent-call" ||+ target?.kind === "remote-agent-call"+ ) {filteredTools.set(name, tool);}}return filteredTools;}-function shouldHideDelegationTool(+function isToolAvailable(definition: HarnessToolDefinition,session: AdvertisedToolSession,- delegatedCaller: boolean | undefined,+ availability: {+ readonly canRequestInput?: boolean;+ readonly delegatedCaller?: boolean;+ },): boolean {- if (definition.name === TASK_UPDATE_TOOL_NAME) return delegatedCaller !== true;- if (isRootOnlyTransitionalTool(definition)) {- return session.rootSessionId !== undefined || resolveSubagentDepth(session).currentDepth > 0;- }-- return false;-}--/**- * Tools that only a root session may see. The `agent` self-delegation- * tool and parent-side `experimental.tasks` controls are injected from the root- * node's config, which self-delegated children share — session shape is- * the only signal that separates the root from its children.- */-function isRootOnlyTransitionalTool(definition: HarnessToolDefinition): boolean {- if (definition.rootOnly === true) return true;- if (- definition.name === AGENT_TOOL_NAME &&- definition.runtimeAction?.kind === "subagent-call" &&- definition.runtimeAction.nodeId === ROOT_RUNTIME_AGENT_NODE_ID- ) {- return true;+ for (const condition of definition.behavior?.availability ?? []) {+ switch (condition) {+ case "delegated-task-child":+ if (availability.delegatedCaller !== true) return false;+ break;+ case "requires-request-input":+ if (availability.canRequestInput !== true) return false;+ break;+ case "root-session":+ if (session.rootSessionId !== undefined || resolveSubagentDepth(session).currentDepth > 0) {+ return false;+ }+ break;+ default: {+ const _exhaustive: never = condition;+ return _exhaustive;+ }+ }}-- return definition.name !== TASK_UPDATE_TOOL_NAME && TASK_TOOL_NAMES.has(definition.name);+ return true;}function isToolDefinitionList(diff --git a/packages/eve/src/harness/background-tools.ts b/packages/eve/src/harness/background-tools.tsindex ffd0e3e84..ce0dec43d 100644--- a/packages/eve/src/harness/background-tools.ts+++ b/packages/eve/src/harness/background-tools.ts@@ -2,8 +2,10 @@ import { loadContext } from "#context/container.js";import { ContextKey } from "#context/key.js";import type { ToolExecuteOptions } from "#tools/definition.js";import type { TaskExec } from "#tools/task.js";+import type { PreparedToolBehavior } from "#tools/behavior.js";export interface BackgroundExecutableTool {+ readonly behavior?: PreparedToolBehavior;readonly execute: (input: unknown, options: ToolExecuteOptions, task: TaskExec) => unknown;readonly name: string;}diff --git a/packages/eve/src/harness/emission.test.ts b/packages/eve/src/harness/emission.test.tsindex 3650b3dbf..526fd367a 100644--- a/packages/eve/src/harness/emission.test.ts+++ b/packages/eve/src/harness/emission.test.ts@@ -481,14 +481,20 @@ describe("emitStreamContent action requests", () => {["delegate",{+ behavior: {+ availability: [],+ handling: {+ kind: "dispatch",+ target: {+ kind: "subagent-call",+ nodeId: "subagents/researcher",+ subagentName: "researcher",+ },+ },+ },description: "Delegate work to a subagent.",inputSchema: jsonSchema({ type: "object" }),name: "delegate",- runtimeAction: {- kind: "subagent-call",- nodeId: "subagents/researcher",- subagentName: "researcher",- },},],]);diff --git a/packages/eve/src/harness/execute-tool.ts b/packages/eve/src/harness/execute-tool.tsindex de8327f5b..1d955b483 100644--- a/packages/eve/src/harness/execute-tool.ts+++ b/packages/eve/src/harness/execute-tool.ts@@ -3,47 +3,20 @@ import type { FlexibleSchema } from "ai";import type { Approval } from "#approval/definition.js";import type { ToolExecuteOptions } from "#tools/definition.js";import type { TaskExec } from "#tools/task.js";--/**- * Runtime-owned action metadata attached to one harness-visible tool.- *- * These tools are surfaced to the model without a local `execute` function.- * The harness records the tool call and the runtime executes it later.- *- * `task-control` marks the `experimental.tasks` parent tools- * (`task_cancel`, `task_update`): they carry no child- * address of their own — the dispatch step resolves targets through the- * session task index by tool name.- */-export type HarnessRuntimeActionDefinition =- | {- readonly kind: "remote-agent-call" | "subagent-call";- readonly nodeId: string;- readonly remoteAgentName?: string;- readonly subagentName: string;- }- | { readonly kind: "task-control" };+import type { PreparedToolBehavior } from "#tools/behavior.js";/*** Unified harness-owned tool definition.*/export interface HarnessToolDefinition {readonly approvalKey?: (toolInput: Readonly<Record<string, unknown>>) => string;+ readonly behavior?: PreparedToolBehavior;readonly description: string;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/input-extraction.test.ts b/packages/eve/src/harness/input-extraction.test.tsindex 2dde16370..a57c885fd 100644--- a/packages/eve/src/harness/input-extraction.test.ts+++ b/packages/eve/src/harness/input-extraction.test.ts@@ -5,6 +5,21 @@ import {extractToolApprovalInputRequests,} from "#harness/input-extraction.js";+const QUESTION_TOOLS = new Map([+ [+ "ask_question",+ {+ behavior: {+ availability: ["requires-request-input" as const],+ handling: { kind: "request-input" as const, request: "question" as const },+ },+ description: "Ask a question.",+ inputSchema: {} as never,+ name: "ask_question",+ },+ ],+]);+describe("extractQuestionInputRequests", () => {it("extracts a question request from an ask_question tool call", () => {const result = extractQuestionInputRequests({@@ -20,6 +35,7 @@ describe("extractQuestionInputRequests", () => {type: "tool-call",},],+ tools: QUESTION_TOOLS,});expect(result).toEqual([@@ -53,6 +69,7 @@ describe("extractQuestionInputRequests", () => {type: "tool-call",},],+ tools: QUESTION_TOOLS,});expect(result[0]?.allowFreeform).toBe(true);@@ -69,6 +86,7 @@ describe("extractQuestionInputRequests", () => {type: "tool-call",},],+ tools: QUESTION_TOOLS,});expect(result).toEqual([]);@@ -85,6 +103,7 @@ describe("extractQuestionInputRequests", () => {type: "tool-call",},],+ tools: QUESTION_TOOLS,});expect(result).toEqual([]);diff --git a/packages/eve/src/harness/input-extraction.ts b/packages/eve/src/harness/input-extraction.tsindex 09b4b2933..1cb7ae2a7 100644--- a/packages/eve/src/harness/input-extraction.ts+++ b/packages/eve/src/harness/input-extraction.ts@@ -1,7 +1,7 @@import type { ContentPart, ModelMessage, ToolSet, TypedToolCall } from "ai";import { z } from "zod";-import { ASK_QUESTION_TOOL_NAME } from "#harness/request-input-tool.js";+import type { HarnessToolMap } from "#harness/types.js";import type { InputRequest } from "#shared/input.js";import { createRuntimeToolCallActionFromToolCall } from "#harness/tool-call-action.js";@@ -38,6 +38,7 @@ const ToolApprovalRequestSchema = z.object({export function extractQuestionInputRequests(input: {readonly excludedCallIds: ReadonlySet<string>;readonly toolCalls: readonly TypedToolCall<ToolSet>[];+ readonly tools: HarnessToolMap;}): InputRequest[] {return extractQuestionRequests(input);}@@ -45,11 +46,13 @@ export function extractQuestionInputRequests(input: {function extractQuestionRequests(input: {readonly excludedCallIds: ReadonlySet<string>;readonly toolCalls: readonly ToolCallDescriptor[];+ readonly tools: HarnessToolMap;}): InputRequest[] {const requests: InputRequest[] = [];for (const toolCall of input.toolCalls) {- if (toolCall.toolName !== ASK_QUESTION_TOOL_NAME) {+ const handling = input.tools.get(toolCall.toolName)?.behavior?.handling;+ if (handling?.kind !== "request-input" || handling.request !== "question") {continue;}@@ -179,6 +182,7 @@ function extractApprovalRequests(input: {export function extractHistoricalInputRequests(input: {readonly history: readonly ModelMessage[];readonly requestIds: ReadonlySet<string>;+ readonly tools: HarnessToolMap;}): ReadonlyMap<string, InputRequest> {const requests = new Map<string, InputRequest>();@@ -195,7 +199,7 @@ export function extractHistoricalInputRequests(input: {: [];});const candidates = [- ...extractQuestionRequests({ excludedCallIds: new Set(), toolCalls }),+ ...extractQuestionRequests({ excludedCallIds: new Set(), toolCalls, tools: input.tools }),...extractApprovalRequests({content: message.content,includedRequestIds: input.requestIds,diff --git a/packages/eve/src/harness/runtime-actions.test.ts b/packages/eve/src/harness/runtime-actions.test.tsindex abbb839dc..34993a90b 100644--- a/packages/eve/src/harness/runtime-actions.test.ts+++ b/packages/eve/src/harness/runtime-actions.test.ts@@ -54,8 +54,8 @@ describe("createRuntimeActionRequestFromToolCall", () => {["load_skill",{+ behavior: { availability: [], presentation: "load-skill" as const },description: "Load a skill.",- frameworkAction: "load-skill" as const,inputSchema: jsonSchema({ type: "object" }),name: "load_skill",},@@ -113,10 +113,12 @@ function createParkedSession(): HarnessSession {callId: "call-1",description: "research subagent",input: { description: "Research the topic", message: "go" },- kind: "subagent-call",- name: "researcher",- nodeId: "subagents/researcher",- subagentName: "researcher",+ target: {+ kind: "subagent-call",+ nodeId: "subagents/researcher",+ subagentName: "researcher",+ },+ toolName: "researcher",},],event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },@@ -131,15 +133,20 @@ describe("runtime action batch identity", () => {callId: "duplicate-call",description: "research subagent",input: { message: "go" },- kind: "subagent-call" as const,- name: "researcher",- nodeId: "subagents/researcher",- subagentName: "researcher",+ target: {+ kind: "subagent-call" as const,+ nodeId: "subagents/researcher",+ subagentName: "researcher",+ },+ toolName: "researcher",};expect(() =>setPendingRuntimeActionBatch({- actions: [action, { ...action, name: "other", subagentName: "other" }],+ actions: [+ action,+ { ...action, target: { ...action.target, subagentName: "other" }, toolName: "other" },+ ],event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },responseMessages: [],session: createParkedSession(),@@ -459,10 +466,12 @@ describe("resolvePendingRuntimeActions", () => {callId: "call-2",description: "research subagent",input: { agentId, message: "continue" },- kind: "subagent-call",- name: "researcher",- nodeId: "subagents/researcher",- subagentName: "researcher",+ target: {+ kind: "subagent-call",+ nodeId: "subagents/researcher",+ subagentName: "researcher",+ },+ toolName: "researcher",},],event: { sequence: 1, stepIndex: 0, turnId: "turn_1" },@@ -566,10 +575,12 @@ describe("resolvePendingRuntimeActions", () => {callId: "call-2",description: "research subagent",input: { agentId, message: "continue" },- kind: "subagent-call",- name: "researcher",- nodeId: "subagents/researcher",- subagentName: "researcher",+ target: {+ kind: "subagent-call",+ nodeId: "subagents/researcher",+ subagentName: "researcher",+ },+ toolName: "researcher",},],event: { sequence: 1, stepIndex: 0, turnId: "turn_1" },diff --git a/packages/eve/src/harness/runtime-actions.ts b/packages/eve/src/harness/runtime-actions.tsindex 7757f8833..8759d99d2 100644--- a/packages/eve/src/harness/runtime-actions.ts+++ b/packages/eve/src/harness/runtime-actions.ts@@ -1,9 +1,10 @@import type { ModelMessage, ToolSet, TypedToolCall } from "ai";import { createActionResultEvent, type UnstampedMessageStreamEvent } from "#protocol/message.js";-import { getRuntimeActionRequestKey } from "#runtime/actions/keys.js";+import { getPendingDispatchActionKey } from "#runtime/actions/keys.js";import { resolveRuntimeActionResultsForKeys } from "#runtime/actions/results.js";import type { RuntimeActionRequest, RuntimeActionResult } from "#shared/action-types.js";+import type { PendingDispatchAction } from "#shared/dispatch-action.js";import { parseJsonObject, type JsonObject } from "#shared/json.js";import type { AgentTurnOutcome } from "#shared/agent-turn-outcome.js";import { findRunningAgentHandle, isResultBoundToRunningHandle } from "#harness/handles/query.js";@@ -57,7 +58,7 @@ interface PendingRuntimeActionEventMetadata {* authority for continuing, settling, and cancelling children.*/export interface PendingRuntimeActionBatch {- readonly actions: readonly RuntimeActionRequest[];+ readonly actions: readonly PendingDispatchAction[];readonly event: PendingRuntimeActionEventMetadata;readonly responseMessages: readonly ModelMessage[];}@@ -115,7 +116,7 @@ export function clearPendingRuntimeActionBatch(session: HarnessSession): Harness* Stores one pending runtime-action batch on the session.*/export function setPendingRuntimeActionBatch(input: {- readonly actions: readonly RuntimeActionRequest[];+ readonly actions: readonly PendingDispatchAction[];readonly event: PendingRuntimeActionEventMetadata;readonly responseMessages: readonly ModelMessage[];readonly session: HarnessSession;@@ -132,7 +133,7 @@ export function setPendingRuntimeActionBatch(input: {}/** Rejects an ambiguous action batch before any result or side effect can bind by call id. */-export function assertUniqueRuntimeActionCallIds(actions: readonly RuntimeActionRequest[]): void {+export function assertUniqueRuntimeActionCallIds(actions: readonly PendingDispatchAction[]): void {const seen = new Set<string>();for (const action of actions) {if (seen.has(action.callId)) {@@ -170,7 +171,7 @@ function resolveRuntimeActionResultsForBatch(input: {readonly state: SessionStateMap | undefined;}): RuntimeActionResult[] | undefined {return resolveRuntimeActionResultsForKeys({- pendingKeys: input.batch.actions.map((action) => getRuntimeActionRequestKey(action)),+ pendingKeys: input.batch.actions.map((action) => getPendingDispatchActionKey(action)),results: input.results.filter((result) => isResultBoundToRunningHandle(input.state, result)),});}@@ -363,56 +364,80 @@ export function createRuntimeActionRequestFromToolCall(input: {readonly tools: HarnessToolMap;}): RuntimeActionRequest {const definition = input.tools.get(input.toolCall.toolName);+ const toolInput = resolveToolCallInputObject(input.toolCall.input, {+ callId: input.toolCall.toolCallId,+ toolName: input.toolCall.toolName,+ });- if (definition?.frameworkAction === "load-skill") {+ if (definition?.behavior?.presentation === "load-skill") {return {callId: input.toolCall.toolCallId,- input: resolveToolCallInputObject(input.toolCall.input, {- callId: input.toolCall.toolCallId,- toolName: input.toolCall.toolName,- }),+ input: toolInput,kind: "load-skill",};}- if (definition?.runtimeAction?.kind === "subagent-call") {+ const target =+ definition?.execution === "background" || definition?.behavior?.handling?.kind !== "dispatch"+ ? undefined+ : definition.behavior.handling.target;+ if (+ definition !== undefined &&+ (target?.kind === "self-agent-call" || target?.kind === "subagent-call")+ ) {return {callId: input.toolCall.toolCallId,description: definition.description,- input: resolveToolCallInputObject(input.toolCall.input, {- callId: input.toolCall.toolCallId,- toolName: input.toolCall.toolName,- }),+ input: toolInput,kind: "subagent-call",name: definition.name,- nodeId: definition.runtimeAction.nodeId,- subagentName: definition.runtimeAction.subagentName,+ nodeId: target.nodeId,+ subagentName: target.subagentName,};}- if (definition?.runtimeAction?.kind === "remote-agent-call") {+ if (definition !== undefined && target?.kind === "remote-agent-call") {return {callId: input.toolCall.toolCallId,description: definition.description,- input: resolveToolCallInputObject(input.toolCall.input, {- callId: input.toolCall.toolCallId,- toolName: input.toolCall.toolName,- }),+ input: toolInput,kind: "remote-agent-call",name: definition.name,- nodeId: definition.runtimeAction.nodeId,- remoteAgentName: definition.runtimeAction.remoteAgentName ?? definition.name,+ nodeId: target.nodeId,+ remoteAgentName: target.remoteAgentName,};}return {callId: input.toolCall.toolCallId,+ input: toolInput,+ kind: "tool-call",+ toolName: input.toolCall.toolName,+ };+}++/** Projects one execute-less dispatch tool call into the durable pending contract. */+export function createPendingDispatchActionFromToolCall(input: {+ readonly toolCall: TypedToolCall<ToolSet>;+ readonly tools: HarnessToolMap;+}): PendingDispatchAction {+ const definition = input.tools.get(input.toolCall.toolName);+ if (definition === undefined) {+ throw new Error(`Unknown tool "${input.toolCall.toolName}" in dispatch projection.`);+ }+ const handling = definition.behavior?.handling;+ if (handling?.kind !== "dispatch" || definition.execution === "background") {+ throw new Error(`Tool "${input.toolCall.toolName}" is not a durable dispatch tool.`);+ }+ return {+ callId: input.toolCall.toolCallId,+ description: definition.description,input: resolveToolCallInputObject(input.toolCall.input, {callId: input.toolCall.toolCallId,toolName: input.toolCall.toolName,}),- kind: "tool-call",- toolName: input.toolCall.toolName,+ target: handling.target,+ toolName: definition.name,};}diff --git a/packages/eve/src/harness/stale-input-responses.test.ts b/packages/eve/src/harness/stale-input-responses.test.tsindex 0f1b333e3..45893f36b 100644--- a/packages/eve/src/harness/stale-input-responses.test.ts+++ b/packages/eve/src/harness/stale-input-responses.test.ts@@ -7,6 +7,21 @@ import {dropStaleSessionLimitContinuationResponses,} from "#harness/stale-input-responses.js";+const QUESTION_TOOLS = new Map([+ [+ "ask_question",+ {+ behavior: {+ availability: ["requires-request-input" as const],+ handling: { kind: "request-input" as const, request: "question" as const },+ },+ description: "Ask a question.",+ inputSchema: {} as never,+ name: "ask_question",+ },+ ],+]);+const approvalHistory: ModelMessage[] = [{content: [@@ -54,6 +69,7 @@ it("converts a stale approval into a non-authorizing user message", () => {stepInput: {inputResponses: [{ optionId: "approve", requestId: "approval-1" }],},+ tools: QUESTION_TOOLS,});expect(result.kind).toBe("converted");@@ -87,6 +103,7 @@ it("converts an attributed stale question selection using its option label", ()},],},+ tools: QUESTION_TOOLS,});expect(result.kind).toBe("converted");@@ -112,6 +129,7 @@ it("keeps responses for pending requests structured while converting stale ones"{ optionId: "candidate", requestId: "question-1" },],},+ tools: QUESTION_TOOLS,});expect(result.kind).toBe("converted");@@ -131,6 +149,7 @@ it("keeps the non-authorization notice when request metadata is missing", () =>stepInput: {inputResponses: [{ optionId: "approve", requestId: "approval-gone" }],},+ tools: QUESTION_TOOLS,});expect(result.kind).toBe("converted");@@ -153,6 +172,7 @@ it("returns unchanged when every response matches the pending batch", () => {history: approvalHistory,pendingRequestIds: new Set(["approval-1"]),stepInput,+ tools: QUESTION_TOOLS,});expect(result.kind).toBe("unchanged");@@ -222,6 +242,7 @@ it("converts remaining stale responses after the drop pass", () => {history: questionHistory,pendingRequestIds,stepInput,+ tools: QUESTION_TOOLS,});expect(result.kind).toBe("converted");diff --git a/packages/eve/src/harness/stale-input-responses.ts b/packages/eve/src/harness/stale-input-responses.tsindex 6fdab5cd6..db032daf6 100644--- a/packages/eve/src/harness/stale-input-responses.ts+++ b/packages/eve/src/harness/stale-input-responses.ts@@ -4,7 +4,7 @@ import { extractHistoricalInputRequests } from "#harness/input-extraction.js";import { isApprovalRequest } from "#harness/input-request-class.js";import { appendUserContent, normalizeUserContent } from "#harness/messages.js";import { isSessionLimitContinuationRequestId } from "#harness/session-limit-continuation.js";-import type { StepInput } from "#harness/types.js";+import type { HarnessToolMap, StepInput } from "#harness/types.js";import type { InputRequest, InputResponse } from "#shared/input.js";type StaleResponseConversion =@@ -72,6 +72,7 @@ export function convertStaleResponsesToUserMessage(input: {readonly history: readonly ModelMessage[];readonly pendingRequestIds: ReadonlySet<string>;readonly stepInput?: StepInput;+ readonly tools: HarnessToolMap;}): StaleResponseConversion {if (input.stepInput === undefined) return { kind: "unchanged" };const responses = input.stepInput.inputResponses ?? [];@@ -103,6 +104,7 @@ export function convertStaleResponsesToUserMessage(input: {const requests = extractHistoricalInputRequests({history: input.history,requestIds: new Set(staleResponses.map((response) => response.requestId)),+ tools: input.tools,});const modelMessage = appendOptionalUserContent(input.stepInput.message,diff --git a/packages/eve/src/harness/subagent-depth.ts b/packages/eve/src/harness/subagent-depth.tsindex 70e6da792..c73fde1c8 100644--- a/packages/eve/src/harness/subagent-depth.ts+++ b/packages/eve/src/harness/subagent-depth.ts@@ -1,14 +1,6 @@import { SubagentDepthKey } from "#context/keys.js";import type { HarnessSession } from "#harness/types.js";-import type {- RuntimeActionRequest,- RuntimeRemoteAgentCallActionRequest,- RuntimeSubagentCallActionRequest,-} from "#shared/action-types.js";--export type DelegatedRuntimeActionRequest =- | RuntimeRemoteAgentCallActionRequest- | RuntimeSubagentCallActionRequest;+import type { PendingAgentDispatchAction, PendingDispatchAction } from "#shared/dispatch-action.js";export type ResolvedSubagentDepth = {readonly currentDepth: number;@@ -33,19 +25,24 @@ export function readSerializedSubagentDepth(}export function isSubagentDelegationAction(- action: RuntimeActionRequest,-): action is DelegatedRuntimeActionRequest {- return action.kind === "subagent-call" || action.kind === "remote-agent-call";+ action: PendingDispatchAction,+): action is PendingAgentDispatchAction {+ return (+ action.target.kind === "self-agent-call" ||+ action.target.kind === "subagent-call" ||+ action.target.kind === "remote-agent-call"+ );}-export function getSubagentDelegationName(action: DelegatedRuntimeActionRequest): string {- switch (action.kind) {+export function getSubagentDelegationName(action: PendingAgentDispatchAction): string {+ switch (action.target.kind) {case "remote-agent-call":- return action.remoteAgentName;+ return action.target.remoteAgentName;+ case "self-agent-call":case "subagent-call":- return action.subagentName;+ return action.target.subagentName;default: {- const _exhaustive: never = action;+ const _exhaustive: never = action.target;return _exhaustive;}}diff --git a/packages/eve/src/harness/tool-input-validation.integration.test.ts b/packages/eve/src/harness/tool-input-validation.integration.test.tsindex c9119e930..7e14868f4 100644--- a/packages/eve/src/harness/tool-input-validation.integration.test.ts+++ b/packages/eve/src/harness/tool-input-validation.integration.test.ts@@ -87,6 +87,10 @@ describe("framework tool input validation (real AI SDK)", () => {["ask_question",{+ behavior: {+ availability: ["requires-request-input"],+ handling: { kind: "request-input", request: "question" },+ },description: askQuestion.description,inputSchema: ASK_QUESTION_INPUT_SCHEMA,name: "ask_question",diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.tsindex 1452f723b..eaec6e15c 100644--- a/packages/eve/src/harness/tool-loop.test.ts+++ b/packages/eve/src/harness/tool-loop.test.ts@@ -67,6 +67,7 @@ import {appendPendingInputBatch,} from "#harness/input-requests.js";import { getPendingRuntimeActionBatch } from "#harness/runtime-actions.js";+import type { HarnessToolDefinition } from "#harness/execute-tool.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";@@ -306,19 +307,35 @@ function createDelegationToolMap(): ToolLoopHarnessConfig["tools"] {["delegate",{+ behavior: {+ availability: [],+ handling: {+ kind: "dispatch",+ target: { kind: "subagent-call", nodeId: "workers", subagentName: "worker" },+ },+ },description: "Delegate to a subagent.",inputSchema: jsonSchema({ type: "object" }),name: "delegate",- runtimeAction: {- kind: "subagent-call",- nodeId: "workers",- subagentName: "worker",- },},],]);}+const QUESTION_BEHAVIOR = {+ availability: ["requires-request-input"],+ handling: { kind: "request-input", request: "question" },+} as const;++function createQuestionHarnessTool() {+ return {+ behavior: QUESTION_BEHAVIOR,+ description: "Ask the user a question.",+ inputSchema: jsonSchema({ type: "object" }),+ name: "ask_question",+ };+}+function createScheduleContext(): ContextContainer {const ctx = new ContextContainer();ctx.set(AuthKey, SCHEDULE_APP_AUTH);@@ -1608,10 +1625,8 @@ describe("createToolLoopHarness", () => {callId: "call-1",description: "Delegate to a subagent.",input: { message: "delegate at depth 2" },- kind: "subagent-call",- name: "delegate",- nodeId: "workers",- subagentName: "worker",+ target: { kind: "subagent-call", nodeId: "workers", subagentName: "worker" },+ toolName: "delegate",},]);});@@ -1654,6 +1669,17 @@ describe("createToolLoopHarness", () => {},kind: "subagent",prepared: {+ behavior: {+ availability: [],+ handling: {+ kind: "dispatch",+ target: {+ kind: "subagent-call",+ nodeId: "subagents/researcher",+ subagentName: "researcher",+ },+ },+ },description: "Research the request.",inputSchema: { type: "object" },kind: "subagent",@@ -1682,8 +1708,10 @@ describe("createToolLoopHarness", () => {expect(getPendingRuntimeActionBatch(result.session.state)?.actions).toEqual([expect.objectContaining({callId: "call-dynamic",- kind: "subagent-call",- nodeId: "subagents/researcher",+ target: expect.objectContaining({+ kind: "subagent-call",+ nodeId: "subagents/researcher",+ }),}),]);});@@ -1757,7 +1785,10 @@ describe("createToolLoopHarness", () => {expect(parked.next).toBeNull();expect(getPendingRuntimeActionBatch(parked.session.state)?.actions).toEqual([- expect.objectContaining({ callId: "delegate-1", kind: "subagent-call" }),+ expect.objectContaining({+ callId: "delegate-1",+ target: expect.objectContaining({ kind: "subagent-call" }),+ }),]);expect(hasPendingInputBatch(parked.session.state)).toBe(true);expect(events.filter((event) => event.type === "input.requested")).toHaveLength(1);@@ -1895,14 +1926,16 @@ describe("createToolLoopHarness", () => {["delegate",{+ behavior: {+ availability: [],+ handling: {+ kind: "dispatch",+ target: { kind: "subagent-call", nodeId: "workers", subagentName: "worker" },+ },+ },description: "Delegate to a subagent.",inputSchema: jsonSchema({ type: "object" }),name: "delegate",- runtimeAction: {- kind: "subagent-call",- nodeId: "workers",- subagentName: "worker",- },},],]),@@ -3572,16 +3605,7 @@ describe("createToolLoopHarness", () => {const runStep = createToolLoopHarness(createTestConfig("conversation", emit, {capabilities: { requestInput: true },- tools: new Map([- [- "ask_question",- {- description: "Ask the user a question.",- inputSchema: jsonSchema({ type: "object" }),- name: "ask_question",- },- ],- ]),+ tools: new Map([["ask_question", createQuestionHarnessTool()]]),}),);const session = createTestSession({@@ -3809,14 +3833,16 @@ describe("createToolLoopHarness", () => {["delegate",{+ behavior: {+ availability: [],+ handling: {+ kind: "dispatch",+ target: { kind: "subagent-call", nodeId: "workers", subagentName: "worker" },+ },+ },description: "Delegate to a subagent.",inputSchema: jsonSchema({ type: "object" }),name: "delegate",- runtimeAction: {- kind: "subagent-call",- nodeId: "workers",- subagentName: "worker",- },},],]),@@ -3869,10 +3895,16 @@ describe("createToolLoopHarness", () => {["delegate",{+ behavior: {+ availability: [],+ handling: {+ kind: "dispatch",+ target: { kind: "subagent-call", nodeId: "workers", subagentName: "worker" },+ },+ },description: "Delegate to a subagent.",inputSchema: jsonSchema({ type: "object" }),name: "delegate",- runtimeAction: { kind: "subagent-call", nodeId: "workers", subagentName: "worker" },},],]),@@ -4914,7 +4946,7 @@ describe("createToolLoopHarness", () => {const config: ToolLoopHarnessConfig = {mode: "conversation",resolveModel: vi.fn().mockResolvedValue("anthropic/claude-opus-4.7"),- tools: new Map([+ tools: new Map<string, HarnessToolDefinition>([["add",{@@ -5692,7 +5724,7 @@ describe("createToolLoopHarness", () => {const config: ToolLoopHarnessConfig = {mode: "conversation",resolveModel: vi.fn().mockResolvedValue("anthropic/claude-opus-4.7"),- tools: new Map([+ tools: new Map<string, HarnessToolDefinition>([["web_search",{@@ -6849,7 +6881,24 @@ describe("createToolLoopHarness", () => {});const harness = createToolLoopHarness(- createTestConfig("conversation", undefined, { tools: new Map() }),+ createTestConfig("conversation", undefined, {+ capabilities: { requestInput: true },+ tools: new Map<string, HarnessToolDefinition>([+ [+ "web_search",+ {+ behavior: {+ availability: [],+ handling: { kind: "provider-tool", provider: "exa" },+ },+ description: "Search the web",+ inputSchema: jsonSchema({}),+ name: "web_search",+ },+ ],+ ["ask_question", createQuestionHarnessTool()],+ ]),+ }),);const result = await harness(createTestSession({@@ -6977,7 +7026,24 @@ describe("createToolLoopHarness", () => {});const harness = createToolLoopHarness(- createTestConfig("conversation", undefined, { tools: new Map() }),+ createTestConfig("conversation", undefined, {+ capabilities: { requestInput: true },+ tools: new Map<string, HarnessToolDefinition>([+ [+ "web_search",+ {+ behavior: {+ availability: [],+ handling: { kind: "provider-tool", provider: "exa" },+ },+ description: "Search the web",+ inputSchema: jsonSchema({}),+ name: "web_search",+ },+ ],+ ["ask_question", createQuestionHarnessTool()],+ ]),+ }),);const result = await harness(createTestSession({@@ -8188,7 +8254,8 @@ describe("createToolLoopHarness", () => {},};const config = createTestConfig("conversation", undefined, {- tools: new Map([+ capabilities: { requestInput: true },+ tools: new Map<string, HarnessToolDefinition>([["bash",{@@ -8363,7 +8430,8 @@ describe("createToolLoopHarness", () => {}),});const config = createTestConfig("conversation", undefined, {- tools: new Map([+ capabilities: { requestInput: true },+ tools: new Map<string, HarnessToolDefinition>([["bash",{@@ -8373,6 +8441,7 @@ describe("createToolLoopHarness", () => {name: "bash",},],+ ["ask_question", createQuestionHarnessTool()],]),});@@ -8603,7 +8672,7 @@ describe("createToolLoopHarness", () => {});const config = createTestConfig("conversation", undefined, {- tools: new Map([+ tools: new Map<string, HarnessToolDefinition>([["guarded_echo",{@@ -9092,7 +9161,8 @@ describe("createToolLoopHarness", () => {},};const config = createTestConfig("conversation", undefined, {- tools: new Map([+ capabilities: { requestInput: true },+ tools: new Map<string, HarnessToolDefinition>([["bash",{@@ -9102,14 +9172,7 @@ describe("createToolLoopHarness", () => {name: "bash",},],- [- "ask_question",- {- description: "Ask the user a question.",- inputSchema: jsonSchema({ type: "object" }),- name: "ask_question",- },- ],+ ["ask_question", createQuestionHarnessTool()],]),});const runStep = createToolLoopHarness(config);@@ -9171,7 +9234,12 @@ describe("createToolLoopHarness", () => {});const { emit, events } = createEventCollector();- const runStep = createToolLoopHarness(createTestConfig("conversation", emit));+ const runStep = createToolLoopHarness(+ createTestConfig("conversation", emit, {+ capabilities: { requestInput: true },+ tools: new Map([["ask_question", createQuestionHarnessTool()]]),+ }),+ );const session = createTestSession({agent: {modelReference: { id: "test-model" },@@ -9218,6 +9286,78 @@ describe("createToolLoopHarness", () => {});});+ it("uses dynamic override metadata when ask_question becomes an ordinary tool", async () => {+ const toolCall = {+ input: { prompt: "Handled inline." },+ toolCallId: "dynamic-question-1",+ toolName: "ask_question",+ type: "tool-call" as const,+ };+ const toolResult = {+ input: toolCall.input,+ output: { handled: true },+ toolCallId: toolCall.toolCallId,+ toolName: toolCall.toolName,+ type: "tool-result" as const,+ };+ setupMockAgent({+ content: [toolCall, toolResult],+ finishReason: "tool-calls",+ response: {+ messages: [+ { content: [toolCall], role: "assistant" },+ {+ content: [+ {+ output: { type: "json", value: toolResult.output },+ toolCallId: toolCall.toolCallId,+ toolName: toolCall.toolName,+ type: "tool-result",+ },+ ],+ role: "tool",+ },+ ],+ },+ text: "",+ toolCalls: [toolCall],+ toolResults: [toolResult],+ });++ registerDurableDynamicCallback({+ callback: () => ({ handled: true }),+ phase: "execute",+ toolName: "ask_question",+ });+ const ctx = new ContextContainer();+ ctx.set(StepDynamicToolMetadataKey, [+ {+ callbacks: { execute: { closure: {} } },+ description: "Handle a question inline.",+ entryKey: "ask_question",+ inputSchema: { type: "object" },+ name: "ask_question",+ resolverSlug: "question-override",+ },+ ]);+ const { emit, events } = createEventCollector();+ const runStep = createToolLoopHarness(+ createTestConfig("conversation", emit, {+ capabilities: { requestInput: true },+ tools: new Map([["ask_question", createQuestionHarnessTool()]]),+ }),+ );+ const result = await contextStorage.run(ctx, () =>+ runStep(createTestSession(), { message: "Handle this inline." }),+ );++ expect(typeof result.next).toBe("function");+ expect(hasPendingInputBatch(result.session.state)).toBe(false);+ expect(events.filter((event) => event.type === "input.requested")).toEqual([]);+ expect(events.filter((event) => event.type === "actions.requested")).toHaveLength(1);+ expect(events.filter((event) => event.type === "action.result")).toHaveLength(1);+ });+it("delivers a stale ask_question selection as a new user turn while another question is pending", async () => {const nextQuestionInput = {allowFreeform: false,@@ -9267,7 +9407,12 @@ describe("createToolLoopHarness", () => {vi.mocked(ToolLoopAgent).mockImplementationOnce(nextQuestionImplementation!);const { emit, events } = createEventCollector();- const runStep = createToolLoopHarness(createTestConfig("conversation", emit));+ const runStep = createToolLoopHarness(+ createTestConfig("conversation", emit, {+ capabilities: { requestInput: true },+ tools: new Map([["ask_question", createQuestionHarnessTool()]]),+ }),+ );const questionInput = {allowFreeform: true,options: [@@ -9362,7 +9507,11 @@ describe("createToolLoopHarness", () => {});const { emit, events } = createEventCollector();- const runStep = createToolLoopHarness(createTestConfig("conversation", emit));+ const runStep = createToolLoopHarness(+ createTestConfig("conversation", emit, {+ tools: new Map([["ask_question", createQuestionHarnessTool()]]),+ }),+ );const questionInput = {allowFreeform: true,options: [diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.tsindex e22a66634..ec56d02d1 100644--- a/packages/eve/src/harness/tool-loop.ts+++ b/packages/eve/src/harness/tool-loop.ts@@ -62,7 +62,6 @@ import {type UnstampedMessageStreamEvent,} from "#protocol/message.js";import type { RuntimeTraceContext } from "#protocol/message.js";-import { ASK_QUESTION_TOOL_NAME } from "#harness/request-input-tool.js";import { resolveAgentsAnnouncement } from "#harness/handles/prompt.js";import { getAgentHandleStore } from "#harness/handles/store.js";import {@@ -143,7 +142,6 @@ import {} from "#harness/approval-delivery-coordinator.js";import type { InstrumentationAttempt, InstrumentationStepScope } from "#instrumentation/runtime.js";import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";-import { TASK_UPDATE_TOOL_NAME } from "#tools/framework/task-contract.js";import { readTaskIdFromInboxToken } from "#tasks/task-inbox-token.js";import {consumeDeferredStepInput,@@ -189,6 +187,7 @@ import {import { summarizeKnownError, type SemanticErrorSummary } from "#harness/semantic-errors/index.js";import { throwIfTurnAborted } from "#harness/turn-cancellation.js";import type { JsonObject, JsonValue } from "#shared/json.js";+import type { PreparedDispatchTarget } from "#tools/behavior.js";import { EMPTY_DELIVERY_SENTINEL, hasEmptyDeliverySentinel } from "#shared/empty-delivery.js";import { resolveDeliveryPolicy } from "#tasks/delivery-policy.js";import { extractWorkflowStreamWriteErrorDetails } from "#harness/workflow-stream-error.js";@@ -202,7 +201,7 @@ import {} from "#harness/prompt-cache.js";import { resolveFrameworkToolFromUpstreamType } from "#harness/provider-tools.js";import {- createRuntimeActionRequestFromToolCall,+ createPendingDispatchActionFromToolCall,resolvePendingRuntimeActions,setPendingRuntimeActionBatch,} from "#harness/runtime-actions.js";@@ -224,6 +223,7 @@ import {unwrapWorkflowSandboxResult,} from "#shared/workflow-sandbox.js";import { buildFinalOutputTool, FINAL_OUTPUT_TOOL_NAME } from "#harness/final-output.js";+import type { HarnessToolDefinition } from "#harness/execute-tool.js";import type { RuntimeModelReference } from "#runtime/agent/bootstrap.js";import type { RunMode } from "#shared/run-mode.js";import { createHistoryViewPreparer, type HistoryViewProjector } from "#shared/history-view.js";@@ -449,6 +449,13 @@ function buildHarnessToolsWithDynamicSubagents(return effectiveTools;}+function hasDispatchTarget(tools: HarnessToolMap, kind: PreparedDispatchTarget["kind"]): boolean {+ return [...tools.values()].some(+ (tool) =>+ tool.behavior?.handling?.kind === "dispatch" && tool.behavior.handling.target.kind === kind,+ );+}+export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {const baseEmit = config.handleEvent;@@ -496,7 +503,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {const taskOwned =callback?.taskId !== undefined ||readTaskIdFromInboxToken(String(channel?.state?.parentContinuationToken ?? "")) !== undefined;- const taskUpdatesEnabled = taskOwned && config.tools.has(TASK_UPDATE_TOOL_NAME);+ const taskUpdatesEnabled = taskOwned && hasDispatchTarget(config.tools, "task-update");let activeAttemptScope: InstrumentationAttempt | undefined;const emit =stepInstrumentation?.createHandleEvent({@@ -646,6 +653,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {pendingRequestIds,stepInput: stepInput.input,}),+ tools: config.tools,});const effectiveStepInput = staleConversion.stepInput;const preambleStepInput =@@ -1262,11 +1270,12 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {const harnessTools = buildHarnessToolsWithDynamicSubagents(config.tools, ctx);const backgroundBatch = createBackgroundToolCallBatch();const advertisedHarnessTools = getAdvertisedTools({+ canRequestInput: config.capabilities?.requestInput === true,delegatedCaller: taskUpdatesEnabled,session,tools: harnessTools,});- modelCallRuntimeActionTools = advertisedHarnessTools;+ const effectiveHarnessTools = new Map(advertisedHarnessTools);const flatTools = await buildToolSetWithProviderTools({approvedTools,@@ -1275,11 +1284,11 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {disabledProviderTools: opts.disabledProviderTools,modelReference: requireSessionModelReference(session),tools: advertisedHarnessTools,- webSearchProvider: config.webSearchProvider,});if (ctx !== undefined) {const dynamicTools = getAdvertisedTools({+ canRequestInput: config.capabilities?.requestInput === true,delegatedCaller: taskUpdatesEnabled,session,tools: buildDynamicTools(ctx),@@ -1291,11 +1300,22 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {disabledProviderTools: opts.disabledProviderTools,tools: dynamicTools,});+ const dynamicToolsByName = new Map<string, HarnessToolDefinition>();+ for (const definition of dynamicTools) {+ if (!dynamicToolsByName.has(definition.name)) {+ dynamicToolsByName.set(definition.name, definition);+ }+ }// Dynamic tools override a same-named authored tool.for (const [name, toolDefinition] of Object.entries(dynamicToolSet)) {- if (advertisedHarnessTools.get(name)?.runtimeAction !== undefined) {+ if (advertisedHarnessTools.get(name)?.behavior?.handling?.kind === "dispatch") {throw new Error(`Dynamic tool "${name}" collides with a runtime-visible subagent.`);}+ const dynamicDefinition = dynamicToolsByName.get(name);+ if (dynamicDefinition === undefined) {+ throw new Error(`Dynamic tool "${name}" has no effective harness definition.`);+ }+ effectiveHarnessTools.set(name, dynamicDefinition);flatTools[name] = toolDefinition;}}@@ -1308,13 +1328,15 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {config.workflow === true ? { maxSubagents: config.workflowMaxSubagents } : undefined;const advertisedModelTools = await getAdvertisedTools({+ canRequestInput: config.capabilities?.requestInput === true,delegatedCaller: taskUpdatesEnabled,modelTools: flatTools,session,- tools: advertisedHarnessTools,+ tools: effectiveHarnessTools,workflow: workflowConfig,});session = advertisedModelTools.session;+ modelCallRuntimeActionTools = advertisedModelTools.harnessTools;const modelTools = advertisedModelTools.modelTools;const effectiveTools = marker ? applyLastToolCacheBreakpoint(modelTools, marker) : modelTools;@@ -1387,13 +1409,17 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {const hiddenRuntimeActionToolNames = [...config.tools].filter(([name, tool]) =>- tool.runtimeAction !== undefined && advertisedHarnessTools.get(name) === undefined,+ tool.behavior?.handling?.kind === "dispatch" &&+ effectiveHarnessTools.get(name) === undefined,).map(([name]) => name);+ const requestInputToolNames = [...effectiveHarnessTools.values()]+ .filter((tool) => tool.behavior?.handling?.kind === "request-input")+ .map((tool) => tool.name);const excludedActionToolNames = new Set([- ASK_QUESTION_TOOL_NAME,FINAL_OUTPUT_TOOL_NAME,...hiddenRuntimeActionToolNames,+ ...requestInputToolNames,]);const streamResult = await agent.stream({abortSignal: config.abortSignal,@@ -1407,7 +1433,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {trailingInlineToolResultParts,} = await emitStreamContent(emit, emissionState, streamResult.fullStream, {excludedActionToolNames,- tools: advertisedHarnessTools,+ tools: effectiveHarnessTools,});throwIfTurnAborted(config.abortSignal);const [stepResult, accumulatedResponseMessages] = await Promise.all([@@ -1427,7 +1453,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {excludedActionCallIds: invalidInputToolCallIds,excludedActionToolNames,handledInlineToolResultCallIds,- tools: advertisedHarnessTools,+ tools: effectiveHarnessTools,});const existingToolResults = stepResult.toolResults as TypedToolResult<ToolSet>[];const toolResultsByCallId = new Map(@@ -2413,6 +2439,7 @@ async function handleStepResult(input: {const approvalRequestCallIds = new Set(approvalRequests.map((request) => request.action.callId));const questionRequests = extractQuestionInputRequests({toolCalls: result.toolCalls,+ tools: input.runtimeActionTools,excludedCallIds: new Set([...invalidInputToolCallIds, ...approvalRequestCallIds]),});const inputRequests: InputRequest[] = [...approvalRequests, ...questionRequests];@@ -2433,6 +2460,7 @@ async function handleStepResult(input: {: [{ content: pendingApprovals, role: "user" as const }]),];const advertisedRuntimeActionTools = getAdvertisedTools({+ canRequestInput: input.config.capabilities?.requestInput === true,delegatedCaller: input.delegatedCaller,session: baseSession,tools: input.runtimeActionTools,@@ -2440,10 +2468,16 @@ async function handleStepResult(input: {const pendingRuntimeActions = ((result.toolCalls ?? []) as TypedToolCall<ToolSet>[]).filter((toolCall) => !invalidInputToolCallIds.has(toolCall.toolCallId)).filter(- (toolCall) => input.runtimeActionTools.get(toolCall.toolName)?.runtimeAction !== undefined,+ (toolCall) =>+ input.runtimeActionTools.get(toolCall.toolName)?.behavior?.handling?.kind === "dispatch" &&+ input.runtimeActionTools.get(toolCall.toolName)?.execution !== "background",).filter((toolCall) => {- if (advertisedRuntimeActionTools.get(toolCall.toolName)?.runtimeAction !== undefined) {+ if (+ advertisedRuntimeActionTools.get(toolCall.toolName)?.behavior?.handling?.kind ===+ "dispatch" &&+ advertisedRuntimeActionTools.get(toolCall.toolName)?.execution !== "background"+ ) {return true;}log.warn("runtime action tool call blocked because tool is not advertised", {@@ -2454,7 +2488,7 @@ async function handleStepResult(input: {return false;}).map((toolCall) =>- createRuntimeActionRequestFromToolCall({+ createPendingDispatchActionFromToolCall({toolCall,tools: advertisedRuntimeActionTools,}),diff --git a/packages/eve/src/harness/tools.test.ts b/packages/eve/src/harness/tools.test.tsindex ef4bc6f87..2c8c3e30c 100644--- a/packages/eve/src/harness/tools.test.ts+++ b/packages/eve/src/harness/tools.test.ts@@ -361,6 +361,10 @@ describe("buildToolSet", () => {["web_search",{+ behavior: {+ availability: [],+ handling: { kind: "provider-tool", provider: "parallel" },+ },description: "Web search.",inputSchema: jsonSchema({}),name: "web_search",@@ -433,6 +437,10 @@ describe("buildToolSet", () => {["web_search",{+ behavior: {+ availability: [],+ handling: { kind: "provider-tool", provider: "exa" },+ },description: "Web search.",inputSchema: jsonSchema({}),name: "web_search",@@ -454,6 +462,10 @@ describe("buildToolSet", () => {["web_search",{+ behavior: {+ availability: [],+ handling: { kind: "provider-tool", provider: "parallel" },+ },description: "Web search.",inputSchema: jsonSchema({}),name: "web_search",@@ -464,7 +476,6 @@ describe("buildToolSet", () => {const result = await buildToolSetWithProviderTools({modelReference: { id: "openai/gpt-5.4" },tools,- webSearchProvider: "parallel",});expect(getOutputJsonSchema(result.web_search)).toEqual(WEB_SEARCH_PARALLEL_OUTPUT_SCHEMA);@@ -475,6 +486,10 @@ describe("buildToolSet", () => {["web_search",{+ behavior: {+ availability: [],+ handling: { kind: "provider-tool", provider: "exa" },+ },description: "Web search.",inputSchema: jsonSchema({}),name: "web_search",@@ -503,6 +518,10 @@ describe("buildToolSet", () => {["ask_question",{+ behavior: {+ availability: ["requires-request-input"],+ handling: { kind: "request-input", request: "question" },+ },description: "Ask the user a question.",inputSchema: jsonSchema({}),name: "ask_question",diff --git a/packages/eve/src/harness/tools.ts b/packages/eve/src/harness/tools.tsindex fb8798733..d821284d5 100644--- a/packages/eve/src/harness/tools.ts+++ b/packages/eve/src/harness/tools.ts@@ -2,9 +2,6 @@ import { type ToolApprovalConfiguration, type ToolApprovalStatus, type ToolSet,import type { SessionCapabilities } from "#channel/types.js";import type { RuntimeModelReference } from "#runtime/agent/bootstrap.js";-import type { WebSearchProvider } from "#shared/web-search.js";-import { ASK_QUESTION_TOOL_NAME } from "#harness/request-input-tool.js";-import { WEB_SEARCH_TOOL_NAME } from "#harness/provider-tool-schemas.js";import { isObject } from "#shared/guards.js";import type { HarnessToolDefinition } from "#harness/execute-tool.js";import { resolveApprovalPolicy, type ApprovalStatus } from "#approval/definition.js";@@ -65,7 +62,10 @@ export function buildToolSet(input: {const disabled = input.disabledProviderTools;for (const definition of input.tools.values()) {- if (definition.name === ASK_QUESTION_TOOL_NAME && !canRequestInput) {+ if (+ definition.behavior?.availability.includes("requires-request-input") === true &&+ !canRequestInput+ ) {continue;}@@ -285,7 +285,6 @@ export async function buildToolSetWithProviderTools(input: {readonly disabledProviderTools?: ReadonlySet<string>;readonly modelReference: RuntimeModelReference;readonly tools: HarnessToolMap;- readonly webSearchProvider?: WebSearchProvider;}): Promise<ToolSet> {const disabled = input.disabledProviderTools;const tools: ToolSet = {@@ -298,16 +297,18 @@ export async function buildToolSetWithProviderTools(input: {}),};- // Inject the real provider tool for web_search when the definition has- // no local execute (i.e. the framework definition uses the provider sentinel).- if (!disabled?.has(WEB_SEARCH_TOOL_NAME)) {- const webSearchTool = input.tools.get(WEB_SEARCH_TOOL_NAME);- if (webSearchTool !== undefined && webSearchTool.execute === undefined) {- const backend = resolveWebSearchBackend(input.modelReference, input.webSearchProvider);+ for (const definition of input.tools.values()) {+ const handling = definition.behavior?.handling;+ if (+ handling?.kind === "provider-tool" &&+ definition.execute === undefined &&+ !disabled?.has(definition.name)+ ) {+ const backend = resolveWebSearchBackend(input.modelReference, handling.provider);if (backend === null) {- delete tools[WEB_SEARCH_TOOL_NAME];+ delete tools[definition.name];} else {- tools[WEB_SEARCH_TOOL_NAME] = await resolveWebSearchProviderTool(backend);+ tools[definition.name] = await resolveWebSearchProviderTool(backend);}}}diff --git a/packages/eve/src/harness/types.ts b/packages/eve/src/harness/types.tsindex 21ab01143..6866910e6 100644--- a/packages/eve/src/harness/types.ts+++ b/packages/eve/src/harness/types.ts@@ -15,7 +15,6 @@ import type { SandboxState } from "#sandbox/state.js";import type { JsonObject } from "#shared/json.js";import type { TokenUsage } from "#shared/token-usage.js";import type { InternalToolDefinition } from "#tools/definition.js";-import type { WebSearchProvider } from "#shared/web-search.js";import type { AgentReasoningDefinition } from "#shared/agent-definition.js";import type { HarnessToolDefinition } from "#harness/execute-tool.js";import type { SessionInstrumentation } from "#instrumentation/runtime.js";@@ -303,8 +302,6 @@ export interface ToolLoopHarnessConfig {* {@link import("#harness/workflow-subagent-limit.js").DEFAULT_WORKFLOW_MAX_SUBAGENTS}.*/readonly workflowMaxSubagents?: number;- /** AI Gateway provider selected for the framework `web_search` tool. */- readonly webSearchProvider?: WebSearchProvider;readonly handleEvent?: HandleEventFn;/** Projects raw durable history before it crosses a message-bearing boundary. */readonly historyProjector?: HistoryViewProjector;@@ -323,6 +320,8 @@ export interface ToolLoopHarnessConfig {* for terminal assistant text inside the current invocation.*/readonly mode: RunMode;+ /** Whether this node enables framework background-task behavior. */+ readonly tasksEnabled?: boolean;/*** Called after compaction to let the execution layer re-apply* framework-owned state preservation (read-before-write reset, tododiff --git a/packages/eve/src/harness/workflow-lifecycle.test.ts b/packages/eve/src/harness/workflow-lifecycle.test.tsindex 114b68deb..bedaa770e 100644--- a/packages/eve/src/harness/workflow-lifecycle.test.ts+++ b/packages/eve/src/harness/workflow-lifecycle.test.ts@@ -25,14 +25,20 @@ function createTools(): HarnessToolMap {["researcher",{+ behavior: {+ availability: [],+ handling: {+ kind: "dispatch",+ target: {+ kind: "subagent-call",+ nodeId: "subagents/researcher",+ subagentName: "researcher",+ },+ },+ },description: "Delegate to the researcher.",inputSchema: jsonSchema({ type: "object" }),name: "researcher",- runtimeAction: {- kind: "subagent-call",- nodeId: "subagents/researcher",- subagentName: "researcher",- },},],]);diff --git a/packages/eve/src/harness/workflow-runtime-action-state.test.ts b/packages/eve/src/harness/workflow-runtime-action-state.test.tsindex d649b6113..ea0bdeef9 100644--- a/packages/eve/src/harness/workflow-runtime-action-state.test.ts+++ b/packages/eve/src/harness/workflow-runtime-action-state.test.ts@@ -15,12 +15,12 @@ function concurrentWorkflowInterrupt(): WorkflowSandboxInterrupt {input: { message },interruptId: `${toolCallId}:interrupt`,payload: {- kind: WORKFLOW_RUNTIME_ACTION_INTERRUPT_KIND,- runtimeAction: {+ dispatchTarget: {kind: "subagent-call" as const,nodeId: "subagents/echo-marker",subagentName: "echo-marker",},+ kind: WORKFLOW_RUNTIME_ACTION_INTERRUPT_KIND,toolInput: { message },toolName: "echo-marker",},@@ -77,14 +77,12 @@ describe("workflow runtime action state", () => {{callId: "echo-marker_workflow-call_tool-1_interrupt",input: { message: "alpha" },- kind: "subagent-call",- subagentName: "echo-marker",+ target: { kind: "subagent-call", subagentName: "echo-marker" },},{callId: "echo-marker_workflow-call_tool-2_interrupt",input: { message: "beta" },- kind: "subagent-call",- subagentName: "echo-marker",+ target: { kind: "subagent-call", subagentName: "echo-marker" },},]);expect(getRuntimeActionKeysFromWorkflowInterrupt(interrupt)).toEqual([diff --git a/packages/eve/src/harness/workflow-runtime-action-state.ts b/packages/eve/src/harness/workflow-runtime-action-state.tsindex 19d71f2c8..337b98f12 100644--- a/packages/eve/src/harness/workflow-runtime-action-state.ts+++ b/packages/eve/src/harness/workflow-runtime-action-state.ts@@ -1,11 +1,11 @@-import type { HarnessRuntimeActionDefinition } from "#harness/execute-tool.js";-import { getRuntimeActionRequestKey } from "#runtime/actions/keys.js";-import type { RuntimeActionRequest } from "#shared/action-types.js";+import { getPendingDispatchActionKey } from "#runtime/actions/keys.js";+import type { PendingDispatchAction } from "#shared/dispatch-action.js";import type { JsonObject } from "#shared/json.js";import {getWorkflowSandboxPendingInterrupts,type WorkflowSandboxInterrupt,} from "#shared/workflow-sandbox.js";+import type { PreparedDispatchTarget } from "#tools/behavior.js";export const WORKFLOW_RUNTIME_ACTION_INTERRUPT_KIND = "eve.workflow-runtime-action";@@ -19,41 +19,31 @@ export function isWorkflowRuntimeActionInterrupt(interrupt: unknown): boolean {export function buildRuntimeActionFromWorkflowInterrupt(interrupt: WorkflowSandboxInterrupt,-): RuntimeActionRequest {+): PendingDispatchAction {const raw = interrupt.payload as Record<string, unknown>;- const runtimeAction = raw.runtimeAction as HarnessRuntimeActionDefinition;+ const dispatchTarget = raw.dispatchTarget as PreparedDispatchTarget;const toolInput = raw.toolInput as JsonObject;const toolName = raw.toolName as string;const interruptId = "interruptId" in interrupt ? String(interrupt.interruptId) : "";const callId = sanitizeCallId(`${toolName}_${interruptId}`);- if (runtimeAction.kind === "remote-agent-call") {+ if (+ dispatchTarget.kind === "self-agent-call" ||+ dispatchTarget.kind === "subagent-call" ||+ dispatchTarget.kind === "remote-agent-call"+ ) {return {callId,description: "",input: toolInput,- kind: "remote-agent-call",- name: toolName,- nodeId: runtimeAction.nodeId,- remoteAgentName: runtimeAction.remoteAgentName ?? toolName,- };- }-- if (runtimeAction.kind === "subagent-call") {- return {- callId,- description: "",- input: toolInput,- kind: "subagent-call",- name: toolName,- nodeId: runtimeAction.nodeId,- subagentName: runtimeAction.subagentName,+ target: dispatchTarget,+ toolName,};}// Dynamic workflows only interrupt on delegation tools; task controls// never enter a workflow sandbox.- throw new Error(`Workflow runtime actions cannot carry "${runtimeAction.kind}" tools.`);+ throw new Error(`Workflow runtime actions cannot carry "${dispatchTarget.kind}" tools.`);}/** Returns every pending runtime-action interrupt in deterministic request order. */@@ -65,7 +55,7 @@ export function getWorkflowRuntimeActionInterrupts(export function buildRuntimeActionsFromWorkflowInterrupt(interrupt: WorkflowSandboxInterrupt,-): RuntimeActionRequest[] {+): PendingDispatchAction[] {return getWorkflowRuntimeActionInterrupts(interrupt).map((pending) =>buildRuntimeActionFromWorkflowInterrupt(pending),);@@ -74,7 +64,7 @@ export function buildRuntimeActionsFromWorkflowInterrupt(export function getRuntimeActionKeysFromWorkflowInterrupt(interrupt: WorkflowSandboxInterrupt,): string[] {- return buildRuntimeActionsFromWorkflowInterrupt(interrupt).map(getRuntimeActionRequestKey);+ return buildRuntimeActionsFromWorkflowInterrupt(interrupt).map(getPendingDispatchActionKey);}function sanitizeCallId(id: string): string {diff --git a/packages/eve/src/harness/workflow-sandbox.scenario.test.ts b/packages/eve/src/harness/workflow-sandbox.scenario.test.tsindex 59521e57c..59e49e0cf 100644--- a/packages/eve/src/harness/workflow-sandbox.scenario.test.ts+++ b/packages/eve/src/harness/workflow-sandbox.scenario.test.ts@@ -20,6 +20,17 @@ function orchestrationTools(): HarnessToolMap {["echo-marker",{+ behavior: {+ availability: [],+ handling: {+ kind: "dispatch",+ target: {+ kind: "subagent-call",+ nodeId: "subagents/echo-marker",+ subagentName: "echo-marker",+ },+ },+ },description: "Echo one marker.",inputSchema: jsonSchema({properties: { message: { type: "string" } },@@ -27,11 +38,6 @@ function orchestrationTools(): HarnessToolMap {type: "object",}),name: "echo-marker",- runtimeAction: {- kind: "subagent-call",- nodeId: "subagents/echo-marker",- subagentName: "echo-marker",- },},],]);diff --git a/packages/eve/src/harness/workflow-sandbox.test.ts b/packages/eve/src/harness/workflow-sandbox.test.tsindex 15d643c5f..c31c6740a 100644--- a/packages/eve/src/harness/workflow-sandbox.test.ts+++ b/packages/eve/src/harness/workflow-sandbox.test.ts@@ -17,28 +17,39 @@ function orchestrationTools(): HarnessToolMap {["researcher",{+ behavior: {+ availability: [],+ handling: {+ kind: "dispatch",+ target: {+ kind: "subagent-call",+ nodeId: "subagents/researcher",+ subagentName: "researcher",+ },+ },+ },description: "Delegate to the researcher subagent.",inputSchema: jsonSchema({ type: "object" }),name: "researcher",- runtimeAction: {- kind: "subagent-call",- nodeId: "subagents/researcher",- subagentName: "researcher",- },},],["remote_reviewer",{+ behavior: {+ availability: [],+ handling: {+ kind: "dispatch",+ target: {+ kind: "remote-agent-call",+ nodeId: "subagents/remote-reviewer.ts",+ remoteAgentName: "remote_reviewer",+ },+ },+ },description: "Delegate to the remote reviewer.",inputSchema: jsonSchema({ type: "object" }),name: "remote_reviewer",- runtimeAction: {- kind: "remote-agent-call",- nodeId: "subagents/remote-reviewer.ts",- remoteAgentName: "remote_reviewer",- subagentName: "remote_reviewer",- },},],[diff --git a/packages/eve/src/harness/workflow-sandbox.ts b/packages/eve/src/harness/workflow-sandbox.tsindex dc742a4b4..99247231f 100644--- a/packages/eve/src/harness/workflow-sandbox.ts+++ b/packages/eve/src/harness/workflow-sandbox.ts@@ -95,7 +95,14 @@ function createWorkflowHostTools(tools: HarnessToolMap, names: Iterable<string>)for (const name of names) {const tool = tools.get(name);- if (tool?.runtimeAction !== undefined) {+ if (tool === undefined) continue;+ const target =+ tool.behavior?.handling?.kind === "dispatch" ? tool.behavior.handling.target : undefined;+ if (+ target?.kind === "self-agent-call" ||+ target?.kind === "subagent-call" ||+ target?.kind === "remote-agent-call"+ ) {hostTools[name] = createWorkflowRuntimeActionHostTool(tool);}}@@ -112,8 +119,11 @@ function createWorkflowRuntimeActionHostTool(harnessTool: HarnessToolDefinition)if (resolution !== undefined) return resolution;return requestWorkflowSandboxInterrupt({+ dispatchTarget:+ harnessTool.behavior?.handling?.kind === "dispatch"+ ? harnessTool.behavior.handling.target+ : undefined,kind: WORKFLOW_RUNTIME_ACTION_INTERRUPT_KIND,- runtimeAction: harnessTool.runtimeAction,toolInput,toolName: harnessTool.name,});diff --git a/packages/eve/src/harness/workflow-subagent-limit.test.ts b/packages/eve/src/harness/workflow-subagent-limit.test.tsindex e34d27345..fa882b679 100644--- a/packages/eve/src/harness/workflow-subagent-limit.test.ts+++ b/packages/eve/src/harness/workflow-subagent-limit.test.ts@@ -4,17 +4,19 @@ import {DEFAULT_WORKFLOW_MAX_SUBAGENTS,planWorkflowSubagentDispatch,} from "#harness/workflow-subagent-limit.js";-import type { RuntimeActionRequest } from "#shared/action-types.js";+import type { PendingDispatchAction } from "#shared/dispatch-action.js";-function createAction(index: number): RuntimeActionRequest {+function createAction(index: number): PendingDispatchAction {return {callId: `call-${index}`,description: "",input: {},- kind: "subagent-call",- name: "echo-marker",- nodeId: "subagents/echo-marker",- subagentName: "echo-marker",+ target: {+ kind: "subagent-call",+ nodeId: "subagents/echo-marker",+ subagentName: "echo-marker",+ },+ toolName: "echo-marker",};}diff --git a/packages/eve/src/harness/workflow-subagent-limit.ts b/packages/eve/src/harness/workflow-subagent-limit.tsindex 2e323c35c..3dead1965 100644--- a/packages/eve/src/harness/workflow-subagent-limit.ts+++ b/packages/eve/src/harness/workflow-subagent-limit.ts@@ -1,4 +1,4 @@-import type { RuntimeActionRequest } from "#shared/action-types.js";+import type { PendingDispatchAction } from "#shared/dispatch-action.js";/*** Default maximum number of subagent (and remote-agent) calls one `Workflow`@@ -12,8 +12,8 @@ export const DEFAULT_WORKFLOW_MAX_SUBAGENTS = 100;* actions must resolve with an error result instead of starting a child.*/export type WorkflowSubagentDispatchPlan = {- readonly allowed: readonly RuntimeActionRequest[];- readonly blocked: readonly RuntimeActionRequest[];+ readonly allowed: readonly PendingDispatchAction[];+ readonly blocked: readonly PendingDispatchAction[];readonly maxSubagents: number;readonly usedCalls: number;};@@ -25,7 +25,7 @@ export type WorkflowSubagentDispatchPlan = {* program's call order.*/export function planWorkflowSubagentDispatch(input: {- readonly actions: readonly RuntimeActionRequest[];+ readonly actions: readonly PendingDispatchAction[];readonly maxSubagents?: number;readonly usedCalls: number;}): WorkflowSubagentDispatchPlan {diff --git a/packages/eve/src/internal/authored-definition/schema-backed.ts b/packages/eve/src/internal/authored-definition/schema-backed.tsindex 24e71d4c9..2197da6f8 100644--- a/packages/eve/src/internal/authored-definition/schema-backed.ts+++ b/packages/eve/src/internal/authored-definition/schema-backed.ts@@ -8,7 +8,8 @@ import {expectPositiveInteger,expectString,} from "#internal/authored-module.js";-import type { InternalToolDefinitionWithExecuteFn } from "#tools/definition.js";+import type { InternalToolDefinition, ToolExecuteFn } from "#tools/definition.js";+import { readToolBehavior, type CompiledToolBehavior } from "#tools/behavior.js";import {serializeInputSchema,serializeOutputSchema,@@ -29,8 +30,11 @@ import {* the compiled entry. This shape never carries an authored `name`.*/type NormalizedAuthoredTool = Readonly<- Omit<InternalToolDefinitionWithExecuteFn, "name"> & {+ Omit<InternalToolDefinition, "name"> & {+ readonly behavior?: CompiledToolBehavior;+ readonly execute?: ToolExecuteFn;readonly hasApproval: boolean;+ readonly hasExecute: boolean;readonly hasModelOutputProjection: boolean;}>;@@ -116,14 +120,32 @@ export function normalizeToolDefinition(value: unknown, message: string): Normal? null: serializeInputSchema(record.inputSchema as ToolSchemaSource);const outputSchema = serializeOutputSchema(record.outputSchema as ToolSchemaSource | undefined);+ const behavior = readToolBehavior(value);+ const hasExecute = record.execute !== undefined;+ if (+ !hasExecute &&+ behavior?.handling?.kind !== "dispatch" &&+ behavior?.handling?.kind !== "request-input"+ ) {+ expectFunction(record.execute, message);+ }const definition: MutableNormalizedAuthoredTool = {description: expectString(record.description, message),- execute: expectFunction(record.execute, message),hasApproval: record.approval !== undefined,+ hasExecute,hasModelOutputProjection: record.toModelOutput !== undefined,inputSchema,};+ if (behavior !== undefined) {+ definition.behavior = behavior;+ }+ if (hasExecute) {+ definition.execute = expectFunction(record.execute, message) as ToolExecuteFn;+ }if (record.execution !== undefined) {+ if (!hasExecute) {+ throw new Error(`${message} Execute-less native tools cannot use background execution.`);+ }const execution = expectString(record.execution, message);if (execution !== "background") {throw new Error(`${message} Expected "execution" to be "background".`);diff --git a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.tsindex c7fbe4b25..8dd6af88d 100644--- a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts+++ b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts@@ -370,29 +370,43 @@ function collectCompositionDiagnostics(manifest: CompiledAgentManifest) {};}-const KERNEL_EFFECT_BY_SLOT = {- "tools/agent": { action: "subagent-call", audience: ["root-session"], kind: "dispatch" },- "tools/ask_question": {- audience: ["requires-request-input"],- kind: "request-input",- },- "tools/task_cancel": { action: "task-cancel", audience: ["root-session"], kind: "dispatch" },- "tools/task_update": {- action: "task-update",- audience: ["delegated-task-child"],- kind: "dispatch",- },- "tools/web_search": { audience: [], kind: "provider-tool" },-} as const;+function projectPreparedKernelEffects(+ manifest: CompiledAgentManifest,+): AgentInfoResponse["kernelEffects"] {+ const effects: AgentInfoResponse["kernelEffects"][number][] = [];+ for (const tool of manifest.tools) {+ const behavior = tool.behavior;+ const handling = behavior?.handling;+ if (behavior === undefined || handling === undefined) continue;-function projectPreparedKernelEffects(manifest: CompiledAgentManifest) {- return manifest.tools.flatMap((tool) => {- const binding = manifest.bindings[tool.sourceId];- const slot = tool.logicalPath.replace(/\.(?:[cm]?[jt]sx?)$/, "");- const effect = KERNEL_EFFECT_BY_SLOT[slot as keyof typeof KERNEL_EFFECT_BY_SLOT];- const isAuthoredWebSearch =- slot === "tools/web_search" && manifest.webSearchProvider !== undefined;- if (binding?.owner.kind !== "framework" && !isAuthoredWebSearch) return [];- return effect === undefined ? [] : [{ ...effect, sourceId: tool.sourceId }];- });+ switch (handling.kind) {+ case "dispatch":+ effects.push({+ action: handling.action === "self-agent" ? "subagent-call" : handling.action,+ audience: [...behavior.availability],+ kind: "dispatch",+ sourceId: tool.sourceId,+ });+ break;+ case "provider-tool":+ effects.push({+ audience: [...behavior.availability],+ kind: "provider-tool",+ sourceId: tool.sourceId,+ });+ break;+ case "request-input":+ effects.push({+ audience: [...behavior.availability],+ kind: "request-input",+ sourceId: tool.sourceId,+ });+ break;+ default: {+ const _exhaustive: never = handling;+ throw new Error(`Unsupported compiled tool handling: ${String(_exhaustive)}`);+ }+ }+ }+ return effects;}diff --git a/packages/eve/src/runtime/actions/keys.ts b/packages/eve/src/runtime/actions/keys.tsindex 0e593b3e1..01410e6e9 100644--- a/packages/eve/src/runtime/actions/keys.ts+++ b/packages/eve/src/runtime/actions/keys.ts@@ -1,4 +1,5 @@import type { RuntimeActionRequest, RuntimeActionResult } from "#shared/action-types.js";+import type { PendingDispatchAction } from "#shared/dispatch-action.js";/*** Returns the stable match key used to pair one pending runtime action request@@ -17,6 +18,24 @@ export function getRuntimeActionRequestKey(action: RuntimeActionRequest): string}}+/** Returns the stable match key for one durable dispatch request. */+export function getPendingDispatchActionKey(action: PendingDispatchAction): string {+ switch (action.target.kind) {+ case "remote-agent-call":+ return `subagent-call:${action.target.remoteAgentName}:${action.callId}`;+ case "self-agent-call":+ case "subagent-call":+ return `subagent-call:${action.target.subagentName}:${action.callId}`;+ case "task-cancel":+ case "task-update":+ return `tool-call:${action.toolName}:${action.callId}`;+ default: {+ const _exhaustive: never = action.target;+ return _exhaustive;+ }+ }+}+/*** Returns the stable match key used to pair one runtime action result with its* originating request.diff --git a/packages/eve/src/runtime/agent/bootstrap.test.ts b/packages/eve/src/runtime/agent/bootstrap.test.tsindex cd9324b2a..2942c0b56 100644--- a/packages/eve/src/runtime/agent/bootstrap.test.ts+++ b/packages/eve/src/runtime/agent/bootstrap.test.ts@@ -10,6 +10,17 @@ const APPLICATION_OWNER = { kind: "application" } as const;function createFrameworkAgentTool(): PreparedRuntimeTool {return {+ behavior: {+ availability: ["root-session"],+ handling: {+ kind: "dispatch",+ target: {+ kind: "self-agent-call",+ nodeId: ROOT_RUNTIME_AGENT_NODE_ID,+ subagentName: AGENT_TOOL_NAME,+ },+ },+ },description: "Message a persistent agent.",inputSchema: null,kind: "authored-tool",diff --git a/packages/eve/src/runtime/agent/bootstrap.ts b/packages/eve/src/runtime/agent/bootstrap.tsindex c3323cc1b..63542ad14 100644--- a/packages/eve/src/runtime/agent/bootstrap.ts+++ b/packages/eve/src/runtime/agent/bootstrap.ts@@ -1,6 +1,5 @@import type { ModelMessage } from "ai";-import { AGENT_TOOL_NAME } from "#tools/framework/agent-contract.js";import { composeRuntimeBasePrompt } from "#runtime/prompt/compose.js";import type { PreparedRuntimeTool } from "#runtime/sessions/turn.js";import type { ResolvedAgent, ResolvedAgentDefinition } from "#runtime/types.js";@@ -96,9 +95,8 @@ export function createResolvedRuntimeTurnAgent(input: {);const subagentFrameworkRootTool = input.tools.some((tool) =>- tool.kind === "authored-tool" &&- tool.owner.kind === "framework" &&- tool.name === AGENT_TOOL_NAME,+ tool.behavior?.handling?.kind === "dispatch" &&+ tool.behavior.handling.target.kind === "self-agent-call",);const base: RuntimeTurnAgentBase = {availableSkills: agent.skills.map((skill) => ({diff --git a/packages/eve/src/runtime/loaders/bundled-artifacts.test.ts b/packages/eve/src/runtime/loaders/bundled-artifacts.test.tsindex 5a43647a5..ec96d7d55 100644--- a/packages/eve/src/runtime/loaders/bundled-artifacts.test.ts+++ b/packages/eve/src/runtime/loaders/bundled-artifacts.test.ts@@ -1,13 +1,17 @@import { describe, expect, it } from "vitest";+import { createCompileMetadata, resolveCompilerArtifactPaths } from "#compiler/artifacts.js";import { compileFromMemory } from "#compiler/compile-from-memory.js";import {readBundledCompiledArtifacts,withBundledCompiledArtifacts,} from "#runtime/loaders/bundled-artifacts.js";+import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";+import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";import {createRuntimeSession,getActiveRuntimeSession,+ setRuntimeSessionCompiledArtifacts,withRuntimeSession,} from "#runtime/sessions/runtime-session.js";@@ -40,4 +44,123 @@ describe("withBundledCompiledArtifacts", () => {expect(readBundledCompiledArtifacts()).toBeNull();});});++ it("invalidates resolved bundles when the installed snapshot changes", async () => {+ const initial = await compileFromMemory({+ agentRoot: "/tmp/app/agent",+ appRoot: "/tmp/app",+ model: "openai/gpt-5.4",+ name: "test-agent",+ });+ const updated = await compileFromMemory({+ agentRoot: "/tmp/app/agent",+ appRoot: "/tmp/app",+ model: "openai/gpt-5.4",+ name: "test-agent",+ skills: [+ {+ description: "Use for deployment notes",+ markdown: "# Deployment note\n",+ name: "deploy-note",+ },+ ],+ });+ const source = createBundledRuntimeCompiledArtifactsSource();+ const initialSnapshot = {+ manifest: initial.manifest,+ metadata: createTestCompileMetadata(initial.manifest, "initial"),+ moduleMap: initial.moduleMap,+ };+ const updatedSnapshot = {+ manifest: {+ ...updated.manifest,+ skills: updated.manifest.skills.map(({ files: _files, ...skill }) => skill),+ },+ metadata: createTestCompileMetadata(updated.manifest, "updated"),+ moduleMap: updated.moduleMap,+ };++ const session = createRuntimeSession("redeploy");+ await withRuntimeSession(session, async () => {+ setRuntimeSessionCompiledArtifacts(session, initialSnapshot);+ await expect(+ getCompiledRuntimeAgentBundle({ compiledArtifactsSource: source }),+ ).resolves.toMatchObject({ resolvedAgent: { skills: [] } });++ setRuntimeSessionCompiledArtifacts(session, updatedSnapshot);+ await expect(+ getCompiledRuntimeAgentBundle({ compiledArtifactsSource: source }),+ ).resolves.toMatchObject({ resolvedAgent: { skills: [{ name: "deploy-note" }] } });+ });+ });++ it("keeps resolved bundles for equivalent compiled artifact snapshots", async () => {+ const compiled = await compileFromMemory({+ agentRoot: "/tmp/app/agent",+ appRoot: "/tmp/app",+ model: "openai/gpt-5.4",+ name: "test-agent",+ });+ const source = createBundledRuntimeCompiledArtifactsSource();+ const session = createRuntimeSession("workflow-steps");++ await withRuntimeSession(session, async () => {+ setRuntimeSessionCompiledArtifacts(session, {+ ...compiled,+ metadata: createTestCompileMetadata(compiled.manifest, "stable"),+ });+ const firstBundle = await getCompiledRuntimeAgentBundle({+ compiledArtifactsSource: source,+ });++ setRuntimeSessionCompiledArtifacts(session, {+ manifest: { ...compiled.manifest },+ metadata: createTestCompileMetadata(compiled.manifest, "stable"),+ moduleMap: { ...compiled.moduleMap },+ });++ await expect(+ getCompiledRuntimeAgentBundle({ compiledArtifactsSource: source }),+ ).resolves.toBe(firstBundle);+ });+ });++ it("invalidates metadata-less compiled artifact replacements", async () => {+ const compiled = await compileFromMemory({+ agentRoot: "/tmp/app/agent",+ appRoot: "/tmp/app",+ model: "openai/gpt-5.4",+ name: "test-agent",+ });+ const source = createBundledRuntimeCompiledArtifactsSource();+ const session = createRuntimeSession("metadata-less");++ await withRuntimeSession(session, async () => {+ setRuntimeSessionCompiledArtifacts(session, compiled);+ const firstBundle = await getCompiledRuntimeAgentBundle({+ compiledArtifactsSource: source,+ });++ setRuntimeSessionCompiledArtifacts(session, {+ manifest: { ...compiled.manifest },+ moduleMap: { ...compiled.moduleMap },+ });++ await expect(+ getCompiledRuntimeAgentBundle({ compiledArtifactsSource: source }),+ ).resolves.not.toBe(firstBundle);+ });+ });});++function createTestCompileMetadata(manifest: unknown, moduleMapSource: string) {+ return createCompileMetadata({+ appRoot: "/tmp/app",+ compiledManifestJson: JSON.stringify(manifest),+ diagnosticsArtifactJson: "{}",+ diagnosticsSummary: { errors: 0, warnings: 0 },+ discoveryManifestJson: "{}",+ moduleMapSource,+ paths: resolveCompilerArtifactPaths("/tmp/app"),+ });+}diff --git a/packages/eve/src/runtime/loaders/bundled-artifacts.ts b/packages/eve/src/runtime/loaders/bundled-artifacts.tsindex 6f7c771ae..1d45e0f70 100644--- a/packages/eve/src/runtime/loaders/bundled-artifacts.ts+++ b/packages/eve/src/runtime/loaders/bundled-artifacts.ts@@ -4,6 +4,7 @@ import type { CompiledModuleMap } from "#compiler/module-map.js";import {createRuntimeSession,getActiveRuntimeSession,+ setRuntimeSessionCompiledArtifacts,withRuntimeSession,} from "#runtime/sessions/runtime-session.js";@@ -32,11 +33,11 @@ export interface WithBundledCompiledArtifactsInput extends BundledCompiledArtifa* scoped session so tests cannot leak installations across each other.*/export function installBundledCompiledArtifacts(input: BundledCompiledArtifacts): void {- getActiveRuntimeSession().compiledArtifacts = {+ setRuntimeSessionCompiledArtifacts(getActiveRuntimeSession(), {manifest: input.manifest,metadata: input.metadata,moduleMap: input.moduleMap,- };+ });}/**diff --git a/packages/eve/src/runtime/resolve-agent-graph.ts b/packages/eve/src/runtime/resolve-agent-graph.tsindex 05389427e..03ecacdba 100644--- a/packages/eve/src/runtime/resolve-agent-graph.ts+++ b/packages/eve/src/runtime/resolve-agent-graph.ts@@ -138,6 +138,7 @@ async function resolveRuntimeAgentNode(const toolRegistry = await createRuntimeToolRegistry({ tools: agent.tools },{+ nodeId,reservedToolNames: [WORKFLOW_TOOL_NAME],},);diff --git a/packages/eve/src/runtime/resolve-agent.ts b/packages/eve/src/runtime/resolve-agent.tsindex 6e69ae57b..90a0ea697 100644--- a/packages/eve/src/runtime/resolve-agent.ts+++ b/packages/eve/src/runtime/resolve-agent.ts@@ -122,7 +122,6 @@ export async function resolveAgent(input: ResolveAgentInput): Promise<ResolvedAginput.manifest.workflowTool === undefined? undefined: { maxSubagents: input.manifest.workflowTool.maxSubagents },- webSearchProvider: input.manifest.webSearchProvider,dynamicInstructionsResolvers: resolvedDynamicInstructionsResolvers,dynamicSkillResolvers: resolvedDynamicSkillResolvers,dynamicToolResolvers: resolvedDynamicToolResolvers,diff --git a/packages/eve/src/runtime/resolve-tool.ts b/packages/eve/src/runtime/resolve-tool.tsindex 33f36c0d4..b44014644 100644--- a/packages/eve/src/runtime/resolve-tool.ts+++ b/packages/eve/src/runtime/resolve-tool.ts@@ -29,6 +29,7 @@ export async function resolveToolDefinition(): Promise<ResolvedToolDefinition> {if (!definition.hasExecute) {return {+ behavior: definition.behavior,description: definition.description,inputSchema: toInputSchema(definition.inputSchema),logicalPath: definition.logicalPath,@@ -75,6 +76,7 @@ export async function resolveToolDefinition(: toOutputSchema(definition.outputSchema);return {+ behavior: definition.behavior,description: definition.description,execute,execution: definition.execution,diff --git a/packages/eve/src/runtime/sessions/runtime-session.ts b/packages/eve/src/runtime/sessions/runtime-session.tsindex 344356cf4..abdfc960c 100644--- a/packages/eve/src/runtime/sessions/runtime-session.ts+++ b/packages/eve/src/runtime/sessions/runtime-session.ts@@ -47,6 +47,43 @@ export function createRuntimeSession(id: string = "test-session"): RuntimeSessio};}+export function setRuntimeSessionCompiledArtifacts(+ session: RuntimeSession,+ input: BundledCompiledArtifacts,+): void {+ const installed = session.compiledArtifacts;+ const snapshotChanged = installed === null || !isSameCompiledArtifactSnapshot(installed, input);++ // Resolved bundles retain references into the installed snapshot, so a+ // replacement must not inherit caches populated by the prior deployment.+ if (snapshotChanged) {+ session.bundleCache.clear();+ session.bundleCacheKeyBySourceKey.clear();+ }++ session.compiledArtifacts = input;+}++function isSameCompiledArtifactSnapshot(+ installed: BundledCompiledArtifacts,+ input: BundledCompiledArtifacts,+): boolean {+ const installedSourceGraphHash = installed.metadata?.discovery.sourceGraphHash;+ const inputSourceGraphHash = input.metadata?.discovery.sourceGraphHash;++ // Equivalent bootstrap modules do not share object identity, but the+ // compiler fingerprint is stable across their copies.+ if (installedSourceGraphHash && inputSourceGraphHash) {+ return installedSourceGraphHash === inputSourceGraphHash;+ }++ return (+ installed.manifest === input.manifest &&+ installed.moduleMap === input.moduleMap &&+ installed.metadata === input.metadata+ );+}+/*** Process-global storage for the current `RuntimeSession`.*diff --git a/packages/eve/src/runtime/sessions/turn.ts b/packages/eve/src/runtime/sessions/turn.tsindex 31ef5d235..81286fed3 100644--- a/packages/eve/src/runtime/sessions/turn.ts+++ b/packages/eve/src/runtime/sessions/turn.ts@@ -2,6 +2,7 @@ import type { Node } from "#shared/node.js";import type { SourceRef } from "#shared/source-ref.js";import type { InternalToolDefinition } from "#tools/definition.js";import type { AgentSourceOwner } from "#compiler/source-graph.js";+import type { PreparedToolBehavior } from "#tools/behavior.js";/*** Serializable authored tool descriptor prepared by the runtime for one@@ -10,6 +11,7 @@ import type { AgentSourceOwner } from "#compiler/source-graph.js";export type PreparedRuntimeAuthoredTool = Readonly<InternalToolDefinition &SourceRef & {+ behavior?: PreparedToolBehavior;kind: "authored-tool";owner: AgentSourceOwner;}@@ -19,6 +21,7 @@ type PreparedRuntimeDelegationToolBase<TKind extends "remote" | "subagent"> = ReInternalToolDefinition &SourceRef &Node & {+ behavior: PreparedToolBehavior;kind: TKind;}>;diff --git a/packages/eve/src/runtime/subagents/registry.ts b/packages/eve/src/runtime/subagents/registry.tsindex 3508d5b89..d19959178 100644--- a/packages/eve/src/runtime/subagents/registry.ts+++ b/packages/eve/src/runtime/subagents/registry.ts@@ -119,6 +119,24 @@ export function createPreparedRuntimeSubagentTool(throw new Error(`Static subagent "${definition.name}" is missing a description.`);}return {+ behavior: {+ availability: [],+ handling: {+ kind: "dispatch",+ target:+ definition.kind === "remote"+ ? {+ kind: "remote-agent-call",+ nodeId: definition.nodeId,+ remoteAgentName: definition.name,+ }+ : {+ kind: "subagent-call",+ nodeId: definition.nodeId,+ subagentName: definition.name,+ },+ },+ },description: definition.description,inputSchema,kind: definition.kind,diff --git a/packages/eve/src/runtime/tools/registry.ts b/packages/eve/src/runtime/tools/registry.tsindex 19c845b06..2af15f983 100644--- a/packages/eve/src/runtime/tools/registry.ts+++ b/packages/eve/src/runtime/tools/registry.ts@@ -2,6 +2,7 @@ import { RuntimeRegistry } from "#internal/runtime-registry.js";import type { PreparedRuntimeAuthoredTool } from "#runtime/sessions/turn.js";import type { ResolvedToolDefinition } from "#runtime/types.js";import { serializeInputSchema, serializeOutputSchema } from "#tools/schema.js";+import type { CompiledToolBehavior, PreparedToolBehavior } from "#tools/behavior.js";/*** One executable authored tool tracked by the runtime-owned registry.@@ -28,6 +29,7 @@ export async function createRuntimeToolRegistry(readonly tools: readonly ResolvedToolDefinition[];},input: {+ readonly nodeId?: string;readonly reservedToolNames?: readonly string[];} = {},): Promise<RuntimeToolRegistry> {@@ -38,7 +40,7 @@ export async function createRuntimeToolRegistry();for (const toolDefinition of definitions.tools) {- const prepared = await createPreparedRuntimeTool(toolDefinition);+ const prepared = await createPreparedRuntimeTool(toolDefinition, input.nodeId);registry.register(toolDefinition.name,{ definition: toolDefinition, prepared },@@ -72,8 +74,10 @@ export function findRegisteredRuntimeTool(async function createPreparedRuntimeTool(definition: ResolvedToolDefinition,+ nodeId: string | undefined,): Promise<PreparedRuntimeAuthoredTool> {return {+ behavior: prepareToolBehavior(definition.behavior, nodeId),description: definition.description,inputSchema: serializeInputSchema(definition.inputSchema),kind: "authored-tool",@@ -84,3 +88,48 @@ async function createPreparedRuntimeTool(sourceId: definition.sourceId,};}++function prepareToolBehavior(+ behavior: CompiledToolBehavior | undefined,+ nodeId: string | undefined,+): PreparedToolBehavior | undefined {+ if (behavior === undefined) {+ return undefined;+ }+ if (behavior.handling === undefined) {+ return {+ availability: behavior.availability,+ presentation: behavior.presentation,+ };+ }+ if (behavior.handling.kind !== "dispatch") {+ return { ...behavior, handling: behavior.handling };+ }++ let target: Extract<PreparedToolBehavior["handling"], { readonly kind: "dispatch" }>["target"];+ switch (behavior.handling.action) {+ case "self-agent":+ if (nodeId === undefined) {+ throw new Error("The self-agent tool requires a concrete runtime node id.");+ }+ target = { kind: "self-agent-call", nodeId, subagentName: "agent" };+ break;+ case "task-cancel":+ target = { kind: "task-cancel" };+ break;+ case "task-update":+ target = { kind: "task-update" };+ break;+ default: {+ const _exhaustive: never = behavior.handling.action;+ return _exhaustive;+ }+ }+ return {+ ...behavior,+ handling: {+ kind: "dispatch",+ target,+ },+ };+}diff --git a/packages/eve/src/runtime/types.ts b/packages/eve/src/runtime/types.tsindex 6a7eccd8b..f83c67f48 100644--- a/packages/eve/src/runtime/types.ts+++ b/packages/eve/src/runtime/types.ts@@ -34,7 +34,7 @@ import type { NamedSkillDefinition } from "#shared/skill-definition.js";import type { InternalAgentDefinition } from "#shared/agent-definition.js";import type { RuntimeDynamicModelReference } from "#runtime/agent/bootstrap.js";import type { InternalToolDefinitionWithExecuteFn } from "#tools/definition.js";-import type { WebSearchProvider } from "#shared/web-search.js";+import type { CompiledToolBehavior } from "#tools/behavior.js";import type { SandboxBackend } from "#shared/sandbox-backend.js";import type { SandboxBootstrapContext, SandboxSessionContext } from "#shared/sandbox-definition.js";import type { ToolSchema } from "#tools/schema.js";@@ -165,6 +165,7 @@ export type ResolvedToolDefinition = Readonly<>> &ResolvedModuleSourceRef & {+ readonly behavior?: CompiledToolBehavior;readonly owner: AgentSourceOwner;/*** Validated runtime input schema. Compiled and durable JSON Schemas are@@ -441,7 +442,6 @@ export interface ResolvedAgent {readonly maxSubagents?: number;};/** AI Gateway provider selected for the framework `web_search` tool. */- readonly webSearchProvider?: WebSearchProvider;readonly dynamicInstructionsResolvers: readonly ResolvedDynamicInstructionsResolver[];readonly dynamicSkillResolvers: readonly ResolvedDynamicSkillResolver[];readonly dynamicToolResolvers: readonly ResolvedDynamicToolResolver[];diff --git a/packages/eve/src/shared/dispatch-action.ts b/packages/eve/src/shared/dispatch-action.tsnew file mode 100644index 000000000..3039d8d67--- /dev/null+++ b/packages/eve/src/shared/dispatch-action.ts@@ -0,0 +1,30 @@+import type { JsonObject } from "#shared/json.js";+import type { PreparedDispatchTarget } from "#tools/behavior.js";++/** One model tool call selected for durable execution outside the harness. */+export interface PendingDispatchAction {+ readonly callId: string;+ readonly description: string;+ readonly input: JsonObject;+ readonly target: PreparedDispatchTarget;+ readonly toolName: string;+}++/** Pending action that delegates work to a prepared agent identity. */+export type PendingAgentDispatchAction = PendingDispatchAction & {+ readonly target: Extract<+ PreparedDispatchTarget,+ { readonly kind: "remote-agent-call" | "self-agent-call" | "subagent-call" }+ >;+};++/** Pending action that mutates the durable task lifecycle. */+export type PendingTaskControlAction = PendingDispatchAction & {+ readonly target: Extract<+ PreparedDispatchTarget,+ { readonly kind: "task-cancel" | "task-update" }+ >;+};++/** Fields common to task-control dispatch and its result projection helpers. */+export type TaskControlInvocation = Pick<PendingDispatchAction, "callId" | "input" | "toolName">;diff --git a/packages/eve/src/shared/workflow-sandbox.ts b/packages/eve/src/shared/workflow-sandbox.tsindex 9da5c7b6d..ec1659de5 100644--- a/packages/eve/src/shared/workflow-sandbox.ts+++ b/packages/eve/src/shared/workflow-sandbox.ts@@ -44,8 +44,8 @@ export async function createWorkflowSandboxTool(input: {}export async function requestWorkflowSandboxInterrupt(input: {+ readonly dispatchTarget: unknown;readonly kind: string;- readonly runtimeAction: unknown;readonly toolInput: unknown;readonly toolName: string;}): Promise<unknown> {diff --git a/packages/eve/src/tools/behavior.ts b/packages/eve/src/tools/behavior.tsnew file mode 100644index 000000000..5c9ebdfe7--- /dev/null+++ b/packages/eve/src/tools/behavior.ts@@ -0,0 +1,79 @@+import type { WebSearchProvider } from "#shared/web-search.js";++/** Session facts that can hide a selected tool without changing source composition. */+export type ToolAvailabilityCondition =+ | "delegated-task-child"+ | "requires-request-input"+ | "root-session";++/** Native behavior declared by a selected compiled tool. */+export type CompiledToolHandling =+ | { readonly kind: "dispatch"; readonly action: "self-agent" | "task-cancel" | "task-update" }+ | { readonly kind: "provider-tool"; readonly provider: WebSearchProvider }+ | { readonly kind: "request-input"; readonly request: "question" };++/** Closed, serializable behavior carried by one selected compiled tool. */+export interface CompiledToolBehavior {+ readonly availability: readonly ToolAvailabilityCondition[];+ readonly handling?: CompiledToolHandling;+ readonly presentation?: "load-skill";+}++/** Concrete dispatch identity prepared before a tool reaches the harness. */+export type PreparedDispatchTarget =+ | {+ readonly kind: "remote-agent-call";+ readonly nodeId: string;+ readonly remoteAgentName: string;+ }+ | {+ readonly kind: "self-agent-call";+ readonly nodeId: string;+ readonly subagentName: string;+ }+ | {+ readonly kind: "subagent-call";+ readonly nodeId: string;+ readonly subagentName: string;+ }+ | { readonly kind: "task-cancel" }+ | { readonly kind: "task-update" };++/** Runtime-prepared handling consumed by the harness and execution boundary. */+export type PreparedToolHandling =+ | { readonly kind: "dispatch"; readonly target: PreparedDispatchTarget }+ | Extract<CompiledToolHandling, { readonly kind: "provider-tool" | "request-input" }>;++/** Runtime-prepared behavior carried by one harness-visible tool. */+export interface PreparedToolBehavior {+ readonly availability: readonly ToolAvailabilityCondition[];+ readonly handling?: PreparedToolHandling;+ readonly presentation?: CompiledToolBehavior["presentation"];+}++// Framework definitions and the compiler may come from different bundled copies.+const TOOL_BEHAVIOR = Symbol.for("eve.tool-behavior");++type ToolBehaviorCarrier = {+ readonly [TOOL_BEHAVIOR]: CompiledToolBehavior;+};++/** Attaches internal behavior without adding a public string-keyed definition field. */+export function attachToolBehavior<TDefinition extends object>(+ definition: TDefinition,+ behavior: CompiledToolBehavior,+): TDefinition {+ Object.defineProperty(definition, TOOL_BEHAVIOR, {+ configurable: false,+ enumerable: false,+ value: behavior,+ writable: false,+ });+ return definition;+}++/** Reads internal behavior from a framework-owned definition. */+export function readToolBehavior(value: unknown): CompiledToolBehavior | undefined {+ if (typeof value !== "object" || value === null) return undefined;+ return (value as Partial<ToolBehaviorCarrier>)[TOOL_BEHAVIOR];+}diff --git a/packages/eve/src/tools/framework/agent.ts b/packages/eve/src/tools/framework/agent.tsindex 23e9328da..cadc69485 100644--- a/packages/eve/src/tools/framework/agent.ts+++ b/packages/eve/src/tools/framework/agent.ts@@ -1,16 +1,18 @@-import { defineTool } from "#tools/definition.js";import {AGENT_TOOL_DESCRIPTION,SUBAGENT_TOOL_INPUT_SCHEMA,} from "#tools/framework/agent-contract.js";+import { defineNativeTool } from "#tools/native-definition.js";-/** The harness intercepts this tool before its durable dispatch step executes. */-export const agent = defineTool({- description: AGENT_TOOL_DESCRIPTION,- inputSchema: SUBAGENT_TOOL_INPUT_SCHEMA,- execute() {- throw new Error("agent is handled by eve's durable dispatch step.");+export const agent = defineNativeTool(+ {+ description: AGENT_TOOL_DESCRIPTION,+ inputSchema: SUBAGENT_TOOL_INPUT_SCHEMA,},-});+ {+ availability: ["root-session"],+ handling: { action: "self-agent", kind: "dispatch" },+ },+);export default agent;diff --git a/packages/eve/src/tools/framework/ask-question.ts b/packages/eve/src/tools/framework/ask-question.tsindex f17e54308..a5a2f2251 100644--- a/packages/eve/src/tools/framework/ask-question.ts+++ b/packages/eve/src/tools/framework/ask-question.ts@@ -1,6 +1,6 @@import { z } from "#compiled/zod/index.js";-import { defineTool } from "#tools/definition.js";import { inputRequestSchema } from "#shared/input.js";+import { defineNativeTool } from "#tools/native-definition.js";export const ASK_QUESTION_INPUT_SCHEMA = inputRequestSchema.omit({action: true,@@ -16,15 +16,17 @@ export const ASK_QUESTION_OUTPUT_SCHEMA = z}).strict();-/** The harness intercepts this tool before its durable input step executes. */-export const askQuestion = defineTool({- description:- "Ask the user a question and wait for their response before continuing. Use this when you need clarification or a choice from the user.",- inputSchema: ASK_QUESTION_INPUT_SCHEMA,- outputSchema: ASK_QUESTION_OUTPUT_SCHEMA,- execute() {- throw new Error("ask_question is handled by eve's durable input dispatcher.");+export const askQuestion = defineNativeTool(+ {+ description:+ "Ask the user a question and wait for their response before continuing. Use this when you need clarification or a choice from the user.",+ inputSchema: ASK_QUESTION_INPUT_SCHEMA,+ outputSchema: ASK_QUESTION_OUTPUT_SCHEMA,},-});+ {+ availability: ["requires-request-input"],+ handling: { kind: "request-input", request: "question" },+ },+);export default askQuestion;diff --git a/packages/eve/src/tools/framework/task-cancel.ts b/packages/eve/src/tools/framework/task-cancel.tsindex dd34e3a3c..3a678c627 100644--- a/packages/eve/src/tools/framework/task-cancel.ts+++ b/packages/eve/src/tools/framework/task-cancel.ts@@ -1,18 +1,20 @@-import { defineTool } from "#tools/definition.js";import {TASK_CANCEL_INPUT_SCHEMA,TASK_VIEWS_OUTPUT_SCHEMA,} from "#tools/framework/task-contract.js";+import { defineNativeTool } from "#tools/native-definition.js";-/** The harness intercepts this tool before its durable dispatch step executes. */-export const taskCancel = defineTool({- description:- "Request cooperative cancellation of one or more background tasks. Cancellation is final: a task that finishes after you cancel it stays cancelled. Cancelling an already-finished task changes nothing.",- inputSchema: TASK_CANCEL_INPUT_SCHEMA,- outputSchema: TASK_VIEWS_OUTPUT_SCHEMA,- execute() {- throw new Error("task_cancel is handled by eve's durable dispatch step.");+export const taskCancel = defineNativeTool(+ {+ description:+ "Request cooperative cancellation of one or more background tasks. Cancellation is final: a task that finishes after you cancel it stays cancelled. Cancelling an already-finished task changes nothing.",+ inputSchema: TASK_CANCEL_INPUT_SCHEMA,+ outputSchema: TASK_VIEWS_OUTPUT_SCHEMA,},-});+ {+ availability: ["root-session"],+ handling: { action: "task-cancel", kind: "dispatch" },+ },+);export default taskCancel;diff --git a/packages/eve/src/tools/framework/task-contract.ts b/packages/eve/src/tools/framework/task-contract.tsindex 1240a7441..e59e10dcd 100644--- a/packages/eve/src/tools/framework/task-contract.ts+++ b/packages/eve/src/tools/framework/task-contract.ts@@ -4,12 +4,6 @@ import { jsonValueSchema } from "#shared/json-schemas.js";export const TASK_CANCEL_TOOL_NAME = "task_cancel";export const TASK_UPDATE_TOOL_NAME = "task_update";-/** Transitional PR 1 task-tool names used by the existing dispatch mechanics. */-export const TASK_TOOL_NAMES: ReadonlySet<string> = new Set([- TASK_CANCEL_TOOL_NAME,- TASK_UPDATE_TOOL_NAME,-]);-const TASK_IDS_SCHEMA = z.array(z.string().min(1)).min(1)diff --git a/packages/eve/src/tools/framework/task-update.ts b/packages/eve/src/tools/framework/task-update.tsindex 6aa0adecf..affdc9efa 100644--- a/packages/eve/src/tools/framework/task-update.ts+++ b/packages/eve/src/tools/framework/task-update.ts@@ -1,14 +1,16 @@-import { defineTool } from "#tools/definition.js";import { TASK_UPDATE_INPUT_SCHEMA } from "#tools/framework/task-contract.js";+import { defineNativeTool } from "#tools/native-definition.js";-/** The harness intercepts this tool before its durable dispatch step executes. */-export const taskUpdate = defineTool({- description:- "Briefly tell the parent agent what this background task is currently doing. Report activity, not preliminary findings or results.",- inputSchema: TASK_UPDATE_INPUT_SCHEMA,- execute() {- throw new Error("task_update is handled by eve's durable dispatch step.");+export const taskUpdate = defineNativeTool(+ {+ description:+ "Briefly tell the parent agent what this background task is currently doing. Report activity, not preliminary findings or results.",+ inputSchema: TASK_UPDATE_INPUT_SCHEMA,},-});+ {+ availability: ["delegated-task-child"],+ handling: { action: "task-update", kind: "dispatch" },+ },+);export default taskUpdate;diff --git a/packages/eve/src/tools/native-definition.ts b/packages/eve/src/tools/native-definition.tsnew file mode 100644index 000000000..e3c2de599--- /dev/null+++ b/packages/eve/src/tools/native-definition.ts@@ -0,0 +1,16 @@+import type { PublicToolDefinition } from "#tools/definition.js";+import { attachToolBehavior, type CompiledToolBehavior } from "#tools/behavior.js";++/** Framework-only tool definition whose implementation is owned outside an executor. */+export type NativeToolDefinition<TInput = unknown, TOutput = unknown> = PublicToolDefinition<+ TInput,+ TOutput+>;++/** Defines an execute-less framework tool with closed internal behavior. */+export function defineNativeTool<TInput = unknown, TOutput = unknown>(+ definition: NativeToolDefinition<TInput, TOutput>,+ behavior: CompiledToolBehavior,+): NativeToolDefinition<TInput, TOutput> {+ return attachToolBehavior(definition, behavior);+}diff --git a/packages/eve/src/tools/provided/load-skill.ts b/packages/eve/src/tools/provided/load-skill.tsindex 50a38a9bc..a8c0c4c70 100644--- a/packages/eve/src/tools/provided/load-skill.ts+++ b/packages/eve/src/tools/provided/load-skill.ts@@ -4,17 +4,24 @@ import {SKILL_OUTPUT_SCHEMA,} from "#execution/tools/load-skill.js";import { defineTool } from "#tools/definition.js";+import { attachToolBehavior } from "#tools/behavior.js";-export const loadSkill = defineTool({- description: [- "Load the full instructions for one available skill by name or id.",- "Use this tool when the request clearly matches a listed skill description or when the user explicitly asks for that skill.",- "Loading adds the skill instructions to the current turn.",- 'Choose the "skill" value from the Available skills block.',- ].join(" "),- execute: executeLoadSkill,- inputSchema: SKILL_INPUT_SCHEMA,- outputSchema: SKILL_OUTPUT_SCHEMA,-});+export const loadSkill = attachToolBehavior(+ defineTool({+ description: [+ "Load the full instructions for one available skill by name or id.",+ "Use this tool when the request clearly matches a listed skill description or when the user explicitly asks for that skill.",+ "Loading adds the skill instructions to the current turn.",+ 'Choose the "skill" value from the Available skills block.',+ ].join(" "),+ execute: executeLoadSkill,+ inputSchema: SKILL_INPUT_SCHEMA,+ outputSchema: SKILL_OUTPUT_SCHEMA,+ }),+ {+ availability: [],+ presentation: "load-skill",+ },+);export default loadSkill;diff --git a/research/programmatic-agent-sources.md b/research/programmatic-agent-sources.mdindex 0880f0b70..5d1a13ed3 100644--- a/research/programmatic-agent-sources.md+++ b/research/programmatic-agent-sources.md@@ -1,7 +1,7 @@---issue: https://github.com/vercel/eve/issues/2347-status: in-progress-last_updated: "2026-08-25"+status: implemented+last_updated: "2026-08-31"---# Programmatic agent sources@@ -37,37 +37,57 @@ programmatic module exists on disk.The framework API is internal. Programmatic modules export ordinary public evedefinitions: `defineTool`, `defineDynamic`, `defineChannel`, `defineSandbox`,`defineAgent`, `defineInstrumentation`, and the existing connection, hook,-schedule, instruction, and skill factories. They never construct `Compiled*` or `Resolved*` records.+schedule, instruction, and skill factories. Framework-only native tools use a+closed internal definition variant so they do not carry fake throwing+executors. Neither form constructs `Compiled*` or `Resolved*` records.Production runtime behavior continues to live in the `eve` package; generatedmodule maps only bind statically reachable module namespaces.The compiled manifest, required bindings, persisted composition report,-compiler-owned channel route plan, and closed kernel effect and host-capability plans are the only downstream authority. An active module-backed-source is owned by its binding. An active non-module source is owned by its-explicit compiled source record. A losing or disabled source is owned by its-self-contained composition entry. No second winner-owner index or out-of-band-origin table may exist.+compiler-owned channel route plan, selected tools' handling descriptors, and+closed host inventory are the only downstream authority. An active+module-backed source is owned by its binding. An active non-module source is+owned by its explicit compiled source record. A losing or disabled source is+owned by its self-contained composition entry. No second winner-owner index,+kernel plan, or out-of-band origin table may exist.Every ordinary framework default is a first-class eve primitive at a canonicallogical path, including the default `agent.ts`, sandbox, home page, and theeve channel carrying the public health and info endpoints. Native executionmay implement a selected primitive, but it may not create that primitive'spresence independently of the source graph.-Model-visible kernel behavior is keyed by a closed set of typed effect kinds —-never by tool name — and host registrations that cannot be ordinary sources-live in a separate, typed, exhaustive inventory.+Model-visible native behavior is keyed by a closed handling descriptor carried+by the selected tool — never inferred from its tool name, source ID, owner, or+logical path. Host registrations that cannot be ordinary sources live in a+separate, typed, exhaustive inventory.This supersedes the runtime-tool contribution seam in #2347. Runtimecontribution is too late for channels, schedules, sandboxes, host routes,bundling, and inspection, and would create another collision, durability, anddispatch system for tools.+## Current state++The source-graph phase landed in [#2516](https://github.com/vercel/eve/pull/2516).+Derived slot composition landed in+[#2539](https://github.com/vercel/eve/pull/2539), and first-class memory now+uses that boundary through [#2534](https://github.com/vercel/eve/pull/2534).+Manifest v45 and agent-info v4 are current on `main`.++Those changes completed source selection, binding, loading, route planning,+ownership, and memory integration. They deliberately preserved the dispatch+seam for a second phase. The remaining work is narrower than the original+kernel-effects proposal: make each selected tool carry its own handling and+availability metadata through compilation and runtime preparation, then delete+the harness and execution code that infers those facts from names, owners,+paths, markers, or function identity.+## Problem-The compiler already tracks `logicalPath` and `sourceId`, but module loading-still assumes every source lives at `agentRoot + logicalPath`. Framework and-extension features work around that assumption at different layers:+Before #2516, the compiler tracked `logicalPath` and `sourceId`, but module+loading still assumed every source lived at `agentRoot + logicalPath`.+Framework and extension features worked around that assumption at different+layers:- framework tools and channels fabricate resolved definitions and merge themafter compilation;@@ -91,13 +111,25 @@ extension features work around that assumption at different layers:- native harness tools are represented by metadata stubs that are not thedefinitions the harness advertises or executes.-Native dispatch itself is a layer of magic strings. Execution branches on-`sourceId.startsWith("eve:")` to decide how a tool executor is called; the-harness recognizes `ask_question` and `final_output` by tool-name comparison;-task control is classified through the `TASK_TOOL_NAMES` name set;-`load_skill` carries a `frameworkAction` marker even though it runs an-ordinary inline executor; and advertisement rules such as root-only and-delegated-caller-only visibility are name checks inside the harness.+The source graph removed those parallel composition paths, but native dispatch+still infers semantics after resolution:++- `createExecutionNodeStep` recognizes framework `agent`, `ask_question`, task+ controls, and `load_skill` through owner-and-name checks;+- the harness recognizes `ask_question` and `web_search` by model-visible name;+- task control is classified through `TASK_TOOL_NAMES` and dispatched by name;+- `load_skill` retains a `frameworkAction` marker to classify action events+ even though it executes inline;+- task-mode local subagent fanout uses a module-global `WeakSet` of executor+ function identities;+- root-only, delegated-caller-only, Workflow-callable, and request-input+ availability are separate booleans and name checks; and+- agent-info reconstructs `kernelEffects` from a hard-coded logical-slot table+ instead of the selected compiled tool.++`final_output` is different: eve creates it for one model call from that+turn's output schema, so it has no selected source to carry metadata. Its+terminal interception stays explicit and localized outside the source graph.The result is duplicate machinery with inconsistent identity. Replacement,disablement, route order, source provenance, cold-start loading, and inspection@@ -106,7 +138,7 @@ those parallel paths are deleted, not hidden behind a new registry.## Scope-This work will:+The complete work includes:- introduce source-neutral candidate, composition, and loading boundaries;- require complete module bindings at artifact construction, compilation, and@@ -116,24 +148,24 @@ This work will:once, including local subagent source nodes;- compile one effective manifest consumed by runtime, Nitro, bundling, andinspection;-- migrate ordinary and effectful framework tools, `connection_search`, the+- migrate ordinary and native-handled framework tools, `connection_search`, theeve channel (carrying the callbacks, health, and info), the home channel,the default sandbox, and the default `agent.ts` to programmatic evemodules;- separate public primitive definitions, execution implementations, and native- kernel code so each ordinary default has one definition value;-- replace scattered native-tool knowledge — name checks, source-ID prefixes,- and marker fields — with a closed inventory of typed kernel effect kinds- covering preparation, advertisement, materialization, dispatch, prompt- flags, and inspection;+ handling metadata so each ordinary default has one definition value;+- carry a closed internal handling descriptor on each selected native-handled+ tool and each graph-derived delegation tool, covering availability,+ materialization, dispatch, and inspection without a parallel plan;- limit non-source host behavior to an explicit closed host inventory and moveprocess readiness away from the replaceable public health route;-- replace agent-info v2 with a truthful v3 projection;+- keep agent-info projected from the effective graph and selected tool+ descriptors rather than reconstructing framework behavior from paths;- remove each superseded framework, extension-composition, fallback, andinspection path in the delivery PR that supersedes it.-The implementation does not expose a public registration API or public effect-constructors, serialize functions, mutate a compiled graph, create+The implementation does not expose a public registration API or public+handling constructors, serialize functions, mutate a compiled graph, createprogrammatic subagent nodes, or virtualize markdown and skill asset files.Programmatic modules may be applied to already-discovered local nodes. Theframework registry receives a narrow exception to provide the default config@@ -512,12 +544,13 @@ happens once in path space; normalization happens once after selection.### The effective manifest is authoritativeThe result is one effective compiled graph containing node manifests, required-bindings, the composition report, a compiler-owned channel route plan, and the-prepared kernel effect plan. Those are the only named plan artifacts.-Instrumentation, the Workflow world, sandbox workspace assets, and external-dependencies are per-binding data, ordinary slot content, or existing config —-introducing any new named plan artifact requires amending this document-first. Every downstream consumer reads the effective graph:+bindings, the composition report, and a compiler-owned channel route plan.+Native handling is a field on each selected compiled tool, not a second plan.+Instrumentation, the Workflow world, sandbox workspace assets, external+dependencies, and prepared tool handling are per-binding data, ordinary slot+content, existing config, or runtime projections. Introducing another named+plan artifact requires amending this document first. Every downstream consumer+reads the effective graph:- graph resolution registers only compiled resources;- Nitro registers only the compiled ordered channel routes;@@ -553,12 +586,12 @@ through source composition:| `tools/write_file.ts` | `defineTool` | every local node | ordinary executor || `tools/todo.ts` | `defineTool` | every local node | ordinary executor || `tools/web_fetch.ts` | `defineTool` | every local node | ordinary executor |-| `tools/load_skill.ts` | `defineTool` | every local node | visibility: `requires-loadable-skill` |+| `tools/load_skill.ts` | `defineTool` | every local node | ordinary executor || `tools/connection_search.ts` | `defineDynamic` | every local node | discovers and qualifies connection tools |-| `tools/ask_question.ts` | `defineTool` + `request-input` | every local node | visibility: `requires-request-input` |-| `tools/agent.ts` | `defineTool` + `dispatch` | root node | action: `subagent-call`; visibility: `root-session` |-| `tools/task_update.ts` | `defineTool` + `dispatch` | root node | action: `task-update`; tasks mode; visibility: `delegated-task-child` |-| `tools/task_cancel.ts` | `defineTool` + `dispatch` | root node | action: `task-cancel`; tasks mode; visibility: `root-session` |+| `tools/ask_question.ts` | internal native tool + `request-input` | every local node | visibility: `requires-request-input` |+| `tools/agent.ts` | internal native tool + `dispatch` | root node | action: `subagent-call`; visibility: `root-session` |+| `tools/task_update.ts` | internal native tool + `dispatch` | root node | action: `task-update`; tasks mode; visibility: `delegated-task-child` |+| `tools/task_cancel.ts` | internal native tool + `dispatch` | root node | action: `task-cancel`; tasks mode; visibility: `root-session` || `tools/web_search.ts` | `webSearch` sentinel + `provider-tool` | every local node | materialized at eligible model calls || `channels/eve.ts` | `eveChannel` factory | root node | complete `/eve/v1` surface: protocol, callbacks, health, info || `channels/home.ts` | `defineChannel` | root node | `GET` and `HEAD` at `/` |@@ -574,11 +607,11 @@ these identities is limited to `final_output` and the closed host inventory.### Primitive ownership boundaries-Ordinary public definitions and schemas live under `public/tools` or another-primitive-owned shared module. Execution-only implementations and durable-state live under `execution/tools` or an equivalent execution-owned boundary.-Kernel effect handlers live under `kernel/<effect>` or their effect-specific-execution modules.+Canonical tool definitions and contracts live under `tools/`; package-facing+modules under `public/tools/` remain thin adapters. Execution-only+implementations and durable state live under `execution/`, while the harness+continues to own model-loop and pending-input behavior. A native-handling+descriptor does not justify a new `kernel/` subsystem.Each ordinary default has exactly one definition value. Its framework sourcemodule and its public `eve/tools/<name>` subpath export import that same@@ -586,8 +619,8 @@ value; there is no barrel export. Moving modules mustpreserve durable state key identity for todo, read-before-write, skill,connection-search, compaction, and task behavior. These boundaries holdstructurally: public modules do not import `runtime/`, ordinary framework-sources construct only public definitions, and kernel effects are dispatched-only through the closed effect inventory.+sources construct only canonical definitions, and execution code receives+prepared handling metadata instead of rediscovering source identity.The mixed `runtime/framework-tools` subsystem and transitional re-exportwrappers are deleted after legitimate modules move. “Framework tool catalog”@@ -625,77 +658,86 @@ converter, duplicate resolved-definition constants and wrappers, and the`sourceId.startsWith("eve:")` calling convention. Framework ownership comesfrom the binding, not a string prefix.-`load_skill` already has a real executor today; its-`frameworkAction: "load-skill"` classification marker is deleted. Its executor-reads an eve-owned skill-catalog context provider instead of closing over-resolved skills, and its advertisement gate — whether the node can load a-static or dynamic skill — becomes declared visibility data rather than a-fabricated second definition. Dynamic-skill and cold-start behavior use the-same compiled source and selected binding; no special source type or native-fallback remains.--### Effectful tools--`ask_question`, `agent`, `task_update`, and `task_cancel` are ordinary public-`defineTool` values, and `web_search` is the public `webSearch()` sentinel,-all registered at canonical `tools/*.ts` slots. They compose, replace, and-disable through the same source graph as any authored tool. Instead of an-executor that performs work in-process, each declares a typed kernel effect-(described below). The definitions know nothing about Workflow, parking,-pending batches, or the model SDK; the kernel translates a declared effect-into durable park/resume mechanics.--The declaration and its visibility conditions are closed, JSON-serializable-data carried on the definition value:+`load_skill` already has a real executor. Delete its+`frameworkAction: "load-skill"` marker. Its availability gate — whether the+node can load a static or dynamic skill — and its skill-specific action-event+presentation become selected tool metadata rather than a fabricated second+definition. Existing action request/result wire kinds may remain as protocol+presentation; they must not make `load_skill` a durable dispatch action.+Dynamic-skill and cold-start behavior use the same compiled source and selected+binding; no special source type or native fallback remains.++### Native-handled tools++`ask_question`, `agent`, `task_update`, and `task_cancel` are closed internal+native-tool definitions, and `web_search` is the `webSearch()` sentinel. They+compose, replace, and disable in ordinary tool slots. Each framework definition+carries closed, internal behavior metadata; the compiler serializes that+metadata on the selected tool itself:```ts-interface KernelEffectDeclaration {- readonly kind: "request-input" | "dispatch" | "provider-tool";- // per-kind payload stays minimal and JSON-serializable;- // "dispatch" carries one typed action+type CompiledToolHandling =+ | { readonly kind: "request-input"; readonly request: "question" }+ | {+ readonly kind: "dispatch";+ readonly action: "self-agent" | "task-update" | "task-cancel";+ }+ | { readonly kind: "provider-tool"; readonly provider: "web-search" };++interface CompiledToolBehavior {+ readonly availability: readonly ToolAvailabilityCondition[];+ readonly handling?: CompiledToolHandling;+ readonly presentation?: "skill";}-type DispatchAction =- | { readonly kind: "subagent-call"; readonly nodeId: string; readonly subagentName?: string }- | { readonly kind: "remote-agent-call"; readonly nodeId: string }+type PreparedDispatchTarget =+ | { readonly kind: "subagent-call"; readonly nodeId: string; readonly subagentName: string }+ | { readonly kind: "self-agent-call"; readonly nodeId: string; readonly subagentName: string }+ | {+ readonly kind: "remote-agent-call";+ readonly nodeId: string;+ readonly remoteAgentName: string;+ }| { readonly kind: "task-update" }| { readonly kind: "task-cancel" };-type ToolVisibilityCondition =- | "root-session"- | "delegated-task-child"- | "requires-request-input"- | "requires-loadable-skill"- | "below-subagent-depth";+interface PendingDispatchAction {+ readonly callId: string;+ readonly description: string;+ readonly input: JsonObject;+ readonly target: PreparedDispatchTarget;+ readonly toolName: string;+}++type ToolAvailabilityCondition = "root-session" | "delegated-task-child" | "requires-request-input";```-A definition declares zero or more visibility conditions; all declared-conditions must hold for a session or model call to advertise the tool, and-the kernel evaluates them without reading the tool's name. Visibility follows-the same public-shaped, internally constructed rule as effect declarations:-the types live on public definitions, the constructors stay unexported.--An application `defineTool(...)` or `disableTool()` at any of those identities-composes normally. Replacing `tools/web_search.ts` with an application-`webSearch(...)` or ordinary tool follows the same rule; model/provider-materialization remains the `provider-tool` effect described below.--Workflow follows the same pattern with no framework default: the authored-`experimental_workflow()` sentinel at `tools/workflow.ts` composes at that-canonical slot and carries the tool's complete configuration in its-arguments. It mints no new effect kind — the sentinel declares `dispatch` in-program mode, which is code mode over the same effect. The kernel-materializes the model-visible tool as an isolated program sandbox whose-only host functions are the other `dispatch`-declaring tools in the-effective graph. Each host call performs the same `dispatch` effect the-`agent` tool performs, restricted to the agent-call actions — a program-performing a task action is rejected — with results resuming the durable-program instead of the model step. Advertisement (root sessions below the-depth limit) is declared visibility data like any other effectful tool.-Despite the shared name, `defineAgent({ experimental: { workflow } })` is-unrelated to the tool: it selects the durable-runtime world backing the-agent's own execution. That world selection and the workflow transport in-the closed host inventory are not tool identities.+The internal constructor creates a truthful execute-less native definition and+stamps its behavior metadata; no public `defineTool` option exposes this form.+The normalizer reads the declaration only from the selected namespace and+persists it on `CompiledToolDefinition`; cold-start loading never reconstructs+it from the logical path. An application `defineTool(...)` at+`tools/ask_question.ts` therefore becomes an ordinary executor, while an+application `webSearch(...)` retains provider handling because the selected+sentinel declares it. `load_skill` remains an ordinary executable tool whose+behavior carries presentation, an empty availability set, and no native handling.++Runtime preparation expands `self-agent` and graph-derived local or remote+subagents into `PreparedDispatchTarget` values with concrete node identity.+Availability travels beside the prepared tool. The harness evaluates those+conditions and switches on the handling discriminator; it does not inspect the+tool's owner, name, path, executor identity, or a second plan. An absent+handling declaration means ordinary execution. Tasks mode may materialize an+agent-call dispatch as the existing background executor, but the prepared+dispatch kind remains available for Workflow filtering and local fanout.++Workflow remains a source-selected sentinel with no framework default. Its+program sandbox receives only prepared `dispatch` tools whose actions are+local or remote agent calls; task actions remain unavailable. Workflow reuses+the existing runtime-action dispatch and durable continuation paths rather+than minting an effect kind or global capability lifecycle. Despite the shared+name, `defineAgent({ experimental: { workflow } })` still selects the durable+runtime world backing the agent's own execution and is not a tool identity.### `connection_search`@@ -747,8 +789,8 @@ definitions carry truthful HTTP adapter metadata and use the ordinary channelhandler path, eliminating framework-only route construction and fetchdispatch. Data needed by the info handler comes from an eve-owned contextprovider — the effective compiled graph, binding owners, composition-diagnostics, and kernel plan — not a special source kind or build-time native-route.+diagnostics, and selected tool descriptors — not a special source kind or+build-time native route.Add a root framework channel module at `channels/home.ts` using ordinary`defineChannel`, `GET`, and `HEAD` values for the home page at `/`. Its@@ -868,122 +910,82 @@ successful artifact. The discovery-diagnostics artifact (version 1 today)becomes this compiler diagnostic artifact at version 2; loaders reject theearlier serialized shape rather than repairing it.-### Kernel effects--Some framework tools cannot be modeled as plain executors: their behavior is-to durably suspend the turn workflow and resume it with an externally produced-result. Main already proves the mechanics — an authored tool with `approval`-parks the entire durable turn through the pending-input path, and-`requireAuth()` raises a typed signal the harness converts into an-authorization park. What is missing is a typed boundary: today the harness-recognizes these tools by name strings, source-ID prefixes, and marker fields.--Both names are load-bearing. The kernel is eve's privileged core in the-operating-system sense: definitions cannot suspend or resume the durable-workflow themselves, only kernel handlers touch park/resume state, and the-closed effect inventory plays the role of a syscall table. `request-input`-suspends a turn the way a blocking `read()` suspends a process, and the-kernel later resumes it with the result. Effects take their name from-algebraic effects and handlers in programming-language theory: a definition-performs an operation it cannot interpret, and a handler — here, the-kernel — suspends the computation and resumes it with a value. The durable-callback pattern, a stable identity plus a JSON closure rebound to live code-on every run, is that suspended computation's serialized continuation.--The kernel is keyed by a closed set of effect kinds, never by tool name:--| Effect kind | Declared by | Kernel behavior |-| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |-| `request-input` | `tools/ask_question.ts`; tool approvals internally | park the turn on a pending input batch; resume synthesizes the tool result |-| `dispatch` | `tools/agent.ts`; graph-derived subagent and remote-agent tools; `tools/task_update.ts`; `tools/task_cancel.ts`; the `tools/workflow.ts` sentinel (program mode) | park; execute typed actions in the durable dispatch step; resume with results |-| `provider-tool` | the `tools/web_search.ts` provider sentinel | materialize the provider-managed tool at eligible model calls; no suspension |--The two suspension kinds are genuinely distinct — `request-input` resolves-inside the harness when the next channel delivery arrives, while `dispatch`-resolves outside it in a durable step — and `provider-tool` never suspends at-all. Everything narrower is payload, not a new kind. A `dispatch`-declaration either names exactly one typed `DispatchAction` (call mode) or-declares program mode, where the materialized durable program performs-agent-call actions. The dispatch handler switches exhaustively over the-action union: `subagent-call` and `remote-agent-call` start or resume child-sessions; `task-update` and `task-cancel` execute task commands and may not-be performed from a program. Results resume one of two continuations the-pending batch already identifies: the model step, or the durable Workflow-program whose host call performed the effect.--Each effect kind owns its park semantics, dispatch, resume, prompt flags,-advertisement predicate evaluation, and inspection projection through one-exhaustive lifecycle. Adding an effect kind — or a dispatch action kind —-must produce TypeScript failures until every lifecycle stage handles it.-Effects prepare from the effective composed sources that declare them:-replacing or disabling `tools/agent.ts` removes its `dispatch` preparation-because no selected definition declares the effect. The compiled kernel-effect plan serializes, per node, each prepared effect kind with its-declaring source ID, action kind where applicable, and declared visibility-conditions — nothing more. No kernel code fabricates a `Resolved*` record-merely for validation or inspection.--Effect declarations are public-shaped but internally constructed: the types-live on the tool definition, not in harness code, and carry no reference to-Workflow or execution internals. The constructors remain unexported; opening-them to application tools is a separate future proposal. Effect resume state-persists through the same durable callback pattern `defineDynamic` already-uses; effects gain no parallel continuation store.--`final_output` is the sole remaining non-tool native. It is injected per model-call only when a turn requires structured output, its input schema is that-turn's output schema, and calling it terminally intercepts the turn. It has no-honest static source slot, so it stays outside the source graph as an-explicitly typed terminal-output interception in the kernel.--Preparation and advertisement are deliberately separate: a self-delegated or-task child can share the root node while receiving a different model-visible-tool set. Root tasks-mode preparation records whether the canonical-`task_update` source survived composition and propagates that prepared-capability to every task-owned session, including tasks targeting named or-dynamic local subagents; `task_cancel` remains restricted to eligible-parent/root sessions. Build inspection reports prepared potential, never-claims to be the exact tools for every session and model call.--Local and remote subagent tools remain derived from the effective subagent-graph; they declare the `dispatch` effect rather than appearing as kernel-catalog entries. Workflow's sandbox materialization derives its host-functions from exactly those `dispatch`-declaring tools.--The layering is structural, not tooled: no harness or execution code may-branch on a tool name or source ID; only kernel effect handlers touch-park/resume session-state keys; `public/` modules never import `runtime/`,-`harness/`, or `execution/`; and the kernel exposes no lookup by tool name or-logical path — consumers receive prepared effect state instead of querying-the inventory. Native ordinary-resource fabrication or effect dispatch-outside the exhaustive integration points is a design error to correct in-the implementation, not a condition to police with new guards.--This deletes the magic-string dispatch layer: `sourceId.startsWith("eve:")`-execution branching, `toolName === "ask_question"` and-`toolName === "final_output"` harness checks, the `TASK_TOOL_NAMES`-name set, the `frameworkAction: "load-skill"` marker, and name-based-visibility rules in tool advertisement.--## Inspection v3--Replace agent-info v2 instead of preserving fields whose meanings no longer-fit. The `/eve/v1/info` payload becomes version 3 and has one projector from the-effective compiled graph, binding owners, composition diagnostics, and kernel-plan, served as an ordinary route of the framework eve channel at-`channels/eve.ts` rather than a native Nitro route. All in-repository-clients, TUI views, eval targeting, and tests migrate in the same change;-there is no v2 fallback before 1.0.--Version 3 reports:+### Typed tool handling++The durable mechanisms already exist and remain with their current owners.+Pending input, approvals, and authorization are harness concerns. Runtime+action batches, child dispatch, task control, and Workflow continuation are+execution concerns. Provider-tool materialization belongs next to the model+call. Phase 2 does not move those implementations behind a universal kernel+strategy object.++The missing boundary is the typed handoff between those layers:++```text+selected definition ─> CompiledToolDefinition.behavior+ │+ ├─> prepared source-backed tool+subagent graph ─────────────────┴─> prepared delegation tool+ │+ ├─> availability filter+ ├─> model-tool materialization+ ├─> pending input or action request+ └─> agent-info projection+```++Compiler normalization copies the internal declaration from the selected+definition to its `CompiledToolDefinition`. Runtime resolution carries that+compiled behavior into one uniform prepared-tool descriptor; execute-less+native tools do not need to reload a module merely to recover behavior. Local+and remote subagent graph entries join at that prepared boundary with concrete+dispatch targets; they do not need a fabricated source definition or a global+catalog.++The harness evaluates availability before materialization. It handles+`request-input`, `dispatch`, and `provider-tool` through exhaustive switches on+the descriptor, while an ordinary tool follows its executor. The existing+pending-input and pending-dispatch records remain authoritative for resume. The+broad action-event union remains a protocol projection for clients; the pending+batch narrows to `PendingDispatchAction` values. Plain tool calls and+`load-skill` presentation must not enter the durable dispatch planner. Approvals+remain an orthogonal gate on any executable tool and do not become a declared+`request-input` operation.++Task control requests carry `task-update` or `task-cancel` in the typed action+itself. The execution step switches on that action instead of recovering it+from `toolName`. Background subagent batches carry local or remote dispatch+identity in their prepared definitions, which removes+`localSubagentExecutors` without changing task admission, fanout, or durable+child ownership.++`final_output` remains the sole per-turn native tool. It is created only when+a turn has an output schema, and the terminal-output module owns both its+model-visible name and extraction. Other harness and execution modules receive+the typed terminal result; the source graph does not fabricate a static slot.++This boundary is intentionally distributed by ownership. It adds no+`kernelPlan` artifact, capability registry, strategy table, semantic validator,+or guard rule. The closed TypeScript unions make new handling and dispatch+kinds fail at their actual integration switches. Replacing or disabling a+framework source removes its descriptor because no downstream layer can infer+it from the vacated logical path.++## Inspection++Agent-info v3 landed with #2516, and first-class memory advanced the current+payload to v4. Phase 2 does not replace that schema. The `/eve/v1/info` route+continues to project from the effective compiled graph and remains an ordinary+route of `channels/eve.ts`.++Agent-info reports:- the selected default or authored agent config with its binding and owner;- active static definitions in one list per primitive, each with its logicalpath, source ID, and owner (`application`, `extension`, or `framework`);- active dynamic resolvers separately from their session-specific outputs,including exact subscribed events and explicit source provenance;-- prepared kernel effects separately from compiled tool definitions,- including their audience/model conditions;+- prepared native handling as an inspection projection, including its+ availability conditions;- the exact effective ordered channel-route list used by Nitro, including homeand health, plus retained route-composition diagnostics;- every compiled local subagent and its dynamic config resolver with explicit@@ -1016,8 +1018,11 @@ agent state.Every inspectable source must have explicit ownership. Missing ownership is amalformed artifact rejected at construction or load; agent-info never fallsback to application ownership, parses a source ID, or reconstructs an origin.-The kernel projection comes from the exhaustive effect inventory, and channel-entries come directly from `manifest.channelRoutes.effective`.+The native-handling projection comes from each selected compiled tool and+prepared graph-derived delegation descriptor. Delete `KERNEL_EFFECT_BY_SLOT`;+inspection must not parse a logical path or owner to rediscover behavior.+Channel entries continue to come directly from+`manifest.channelRoutes.effective`.Normalizers continue recording safe facts that cannot be reconstructed fromserialized JSON, such as execution presence, approval, schemas, model-output@@ -1027,7 +1032,7 @@ Tool `hasAuth` remains false because arbitrary executor calls to `getToken()` or`eve info --json` and Vercel summaries keep their narrower contracts but usethe same effective compiled resources. They do not grow session-specific-dynamic outputs or pretend prepared kernel potential is a concrete model-call+dynamic outputs or pretend prepared native potential is a concrete model-calltool set.## In-memory compiler parity@@ -1039,9 +1044,10 @@ the ordinary constructors, includes the framework default `agent.ts`, andproves authored config replacement through the same phase-one composer.Filesystem and memory fixtures must produce equivalent source owners, config-provenance, kernel plans, and module-map key sets. Cold-start namespace-reconstruction and durable callback replay use registry/module bindings only;-neither logical paths nor source IDs recover missing backing or provenance.+provenance, tool-handling descriptors, and module-map key sets. Cold-start+namespace reconstruction and durable callback replay use registry/module+bindings only; neither logical paths nor source IDs recover missing backing or+provenance.The app-harness execution helper accepts an installed tool identity or name andresolves it from the compiled runtime bundle. It never builds a new registry@@ -1062,130 +1068,98 @@ than a memory-only registry or runtime contributor seam.## Delivery-The implementation lands as two stacked PRs split at the boundary between-source identity and dispatch behavior. Each PR deletes every path it-supersedes; no compatibility adapter lands in either. The split isolates the-two failure domains: PR 1's risk is compilation, serialization, and loading,-guarded by artifact validators and module-map parity; PR 2's risk is-park/resume semantics inside the harness, reviewed in a small focused diff.-PR #2407 was an earlier atomic attempt at this boundary; it remains open only-as salvage reference and does not gate or define the implementation.--Both PRs are judged by replacement ratio: production deletions from the-ledger meet or exceed new machinery, and the touched subsystems end-materially simpler than they started. A growing `guard-invariants` script,-sibling validator modules, new plan artifacts, or hand-built test factories-signal that the design is failing — the correction is always in the-implementation, never in tooling around it. `guard-invariants` gains no new-rules for this work; its changes are limited to baseline shrinks and-deleted-path references.--### PR 1 — canonical source graph--Everything becomes a source, and dispatch behavior does not change:--1. source-neutral candidates, required bindings, and the one composition pass;-2. ordinary framework tool, config, sandbox, and `connection_search`- migration to programmatic sources;-3. effectful tool definitions registered at their canonical `tools/*.ts`- slots — presence, replacement, disablement, and ownership become source- composition, while the harness continues to supply their behavior through- the existing dispatch mechanics;-4. framework channels, the compiled route plan, and the closed host inventory;-5. inspection v3 and in-memory compiler parity.--`COMPILED_AGENT_MANIFEST_VERSION` moves from 41 to 42 with required total-bindings, persisted composition, the channel route plan, config provenance,-and v3 inspection metadata. The compiler diagnostic artifact moves from-version 1 to version 2 in the same PR. Disk and bundled loaders reject-earlier serialized shapes rather than repairing them. The complete version 42-schema, its single semantic validator, and serialization fixtures land first-inside the PR, and the serialized shape does not change again within it; the-same rule applies to version 44 in PR 2. Kernel preparation-switches from catalog membership to slot survival: a capability prepares only-when its canonical source survived composition, and agent-info v3 derives its-prepared kernel entries from that survival plus the static kind mapping.--PR 1 carries one explicitly inventoried transitional seam: the harness still-recognizes `ask_question`, `agent`, `task_update`, `task_cancel`,-`web_search`, and `final_output` through today's name checks, `runtimeAction`-markers, and the `frameworkAction: "load-skill"` marker. Nothing else on the-magic-string list survives PR 1 — the `sourceId.startsWith("eve:")` calling-convention dies with the catalog — and no new name-based dispatch may be-added.--PR 1 includes the `minor` changeset — it breaks the agent-info schema, moves-the health and info routes into the replaceable eve channel, and replaces the-`eve/tools/defaults` barrel with per-tool `eve/tools/<name>` subpath exports —-and updates tool, config, channel, health, sandbox, and agent-info-documentation.--### Follow-up — derived slot composition--Programmatic templates, derived-vs-direct precedence within a layer, binding-dependencies, serialized parameters, and dependency-aware namespace loading-land as one focused source-graph extension before memory builds on the graph.-`COMPILED_AGENT_MANIFEST_VERSION` moves from 42 to 43. This follow-up carries a-`patch` changeset because it changes only internal compiler capabilities.--### PR 2 — kernel effects--Dispatch becomes declared effects, and the seam is deleted:--1. effect declarations and visibility conditions consumed by the kernel;-2. the exhaustive effect-kind lifecycle, with approvals riding- `request-input`;-3. replacement of `localSubagentExecutors` function-identity classification- with prepared `dispatch` effect state;-4. deletion of the complete magic-string dispatch layer listed in the- deletion ledger's kernel row.--`COMPILED_AGENT_MANIFEST_VERSION` moves from 43 to 44 with the serialized-kernel effect plan. PR 2 is `patch` when externally observable behavior is-preserved, and updates the dynamic capability documentation.--PR 2 depends entirely on PR 1 and starts only after it lands; nothing in PR 1-depends on PR 2. When PR 2 lands, #2347 is closed with a pointer to this doc.-The research status remains `in-progress` until every deletion, validation-item, and required CI suite across both PRs is complete.--## Distributed deletion ledger--The work is incomplete while any listed path or equivalent parallel system-remains:--| Requirement group | Required deletion |-| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Binding authority | Optional bindings; binding reconstruction in compiled constructors; extension scope inferred from source-ID prefixes; fixtures that use physical extension paths as logical identity. |-| Composition and loading | `logicalPath`-based module loading or sandbox hashing; post-normalization binding reconstruction; module normalizers accepting missing bindings; non-config definition loading before the total remaining binding table exists; eager programmatic namespaces or definition imports; parallel active-owner indexes; arbitrary unbound injected definitions in production normalizers. |-| Framework-source graph | Runtime no-source sandbox construction; `PACKAGE_ROUTES` and the native home, health, and info route defaults; host lifecycle probes using the public health route; silent post-compile ordinary route drops; discovery-only diagnostics that lose compiler warnings; module-global subagent executor-identity state and discarded subagent composition; prompt ownership parsed from source IDs; `public/tools/internal.ts` and `toPublicToolDefinition`. |-| Primitive ownership | The mixed `runtime/framework-tools` directory, the `eve/tools/defaults` barrel export, transitional re-export wrappers, public-to-runtime imports, duplicate default definition values, and ordinary “framework tool catalog” terminology. |-| Default config authority | Synthesized default config in `normalize-agent-config.ts`, undefined-config-source inspection conventions, and config loading outside the total binding table. |-| Kernel effects | `sourceId.startsWith("eve:")` execution branching; `ask_question` and `final_output` tool-name checks in the harness; the `TASK_TOOL_NAMES` name set; the `frameworkAction: "load-skill"` marker; name-based advertisement visibility; kernel conditionals, literal name lists, or registries outside the exhaustive integration points; native fabrication of ordinary resources. |-| Inspection and memory parity | Inspection owner fallback or framework-state reconstruction; omitted dynamic-resolver or remote-agent provenance; `createMemorySourceId`, mirrored memory manifest references, and other in-memory descriptor shortcuts; harness execution of caller-owned tool objects; downstream source catalogs, composers, merges, or compatibility readers. |--This ledger also removes the old framework tool and channel catalogs, duplicate-`Resolved*` constants and callback builders, `getAllFramework*Names`, compiled-or runtime `disabledFramework*` state, the connection-search history scanner-and synthetic registry, and the per-primitive extension prefix/rebase and-disable machinery. Helpers may move behind the canonical boundary, but a-renamed second source of truth does not satisfy deletion.+The source-identity half is complete: #2516 landed the canonical graph, #2539+landed derived slots, #2534 moved memory onto them, and #2531 consolidated the+tool source layout. Issue #2347 was closed when the runtime-contribution seam+was superseded. Phase 2 can now be reviewed independently against current+`main`.++The original Phase 2 implementation shape is rejected. The discarded+`barba/exhaustive-kernel-lifecycle` attempt added 4,617 lines while deleting+734, including a separate 476-line kernel-plan semantic validator and 486 lines+of invariant-guard machinery. It reproduced source facts in a capability+strategy table and made no-op lifecycle methods part of the architecture. That+is the inverse of the replacement ratio and self-enforcing boundary required+by this plan.++### Phase 2 — typed tool handling++Phase 2 is one focused, behavior-preserving refactor:++1. Add closed internal handling and availability declarations to the canonical+ framework definitions, and serialize them on the selected+ `CompiledToolDefinition`.+2. Carry those declarations through runtime resolution into prepared tools;+ create the same prepared dispatch shape directly from local and remote+ subagent graph entries.+3. Make harness availability, question extraction, provider materialization,+ runtime-action creation, Workflow host filtering, and agent-info projection+ consume the prepared descriptor.+4. Make task execution consume the typed dispatch action instead of+ `toolName`, and make background subagent fanout consume prepared delegation+ kind instead of executor function identity.+5. Delete every superseded marker, name table, owner-and-name branch,+ logical-slot inspection table, fake native executor, and broad action-event+ type from the pending dispatch boundary.++If the compiled descriptor changes the serialized manifest, increment the+manifest once from the version current when the PR starts. Do not reserve a+version in this research document. Agent-info remains v4 when its wire shape is+unchanged; `kernelEffects` may remain the public projection name while its data+comes from selected descriptors. The PR carries a `patch` changeset when+observable behavior is preserved.++Production deletions must meet or exceed new production machinery. A new+kernel plan, global capability registry, semantic validator, hand-built+artifact factory, or `guard-invariants` rule fails the design review.++The implemented boundary adds 171 lines across four focused behavior and+dispatch modules while deleting 498 lines from existing production modules.+It increments the compiled manifest to v46 and the backward-compatible tool+extension contract to epoch 23. No kernel plan, global registry, semantic+validator, artifact factory, or invariant rule was added.++## Phase 2 deletion ledger++The remaining work is incomplete while any listed path or equivalent parallel+system remains:++| Requirement group | Required deletion |+| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Handling authority | Owner-and-name dispatch in `execution/node-step.ts`; logical-path or owner reconstruction of native handling; `KERNEL_EFFECT_BY_SLOT`; any separate kernel plan, registry, strategy table, or semantic validator. |+| Harness shape | `frameworkAction`, `runtimeAction`, `rootOnly`, and `workflowCallable` as unrelated special fields; `ask_question` and `web_search` name gates outside their owning adapters; name-based hidden-tool and Workflow-host filtering. |+| Dispatch | `TASK_TOOL_NAMES`; task update/cancel selection by `toolName`; `localSubagentExecutors` and executor-identity fanout; the broad action-event union as the pending dispatch contract; any source ID, logical path, owner, or model-visible name used to select a dispatch implementation. |+| Definition truth | Framework definitions whose executors can only throw because a downstream name check is expected to intercept them. Native-handled definitions are execute-less; `load_skill` remains genuinely executable. |+| Presentation | The `frameworkAction: "load-skill"` marker and name-derived action presentation. If the special `load-skill` request/result wire projection remains, it derives from selected behavior metadata and stays separate from durable dispatch. |+| Terminal output | `final_output` name checks spread across the harness. The terminal-output module may own its reserved name, construction, and extraction because no source-backed identity exists. |++Helpers may move behind the typed prepared-tool boundary, but a renamed second+source of truth does not satisfy deletion.## Validation-Tests are replaced, not accumulated. Tests that assert superseded behavior —-catalog merges, fallback construction, name-based dispatch, agent-info v2 —-are deleted with the code they cover and replaced by tight unit and-integration tests for the new boundaries. Test helpers obtain compiled-artifacts only through the real compiler, from filesystem fixtures or-in-memory source registration; no helper constructs `Compiled*` records-field-by-field.--The work adds no new e2e evals and no new scenario suites. Existing-scenario, TUI, and fixture-owned e2e suites are the behavioral regression-net: nearly all of them must continue passing unchanged, with modifications-limited to the named breaking surfaces — agent-info v3 assertions, the-health and info routes, and `eve/tools/<name>` import paths.+Tests are replaced, not accumulated. Tests that assert name-based dispatch,+independent special fields, function-identity classification, or logical-slot+inspection are deleted with the code they cover. Replacement coverage proves:++- framework declarations survive compile, serialization, cold loading, and+ runtime preparation without path inference;+- an authored `defineTool` replacement at a framework slot executes ordinarily,+ while a selected `webSearch()` sentinel retains provider handling;+- request-input and availability semantics remain correct for root,+ self-delegated, scheduled, named, dynamic, and task-owned sessions;+- task controls and local or remote subagent calls reach the same existing+ durable dispatch paths from typed actions; and+- Workflow receives only eligible agent-call dispatch tools.++Test helpers obtain compiled artifacts only through the real compiler, from+filesystem fixtures or in-memory source registration; no helper constructs+`Compiled*` records field-by-field.++Phase 2 adds no new e2e evals or scenario suites. Existing scenario, TUI, and+fixture-owned e2e suites are the behavioral regression net and should remain+unchanged because the refactor preserves the public tool and agent-info+contracts.Run inexpensive checks throughout implementation:@@ -1242,13 +1216,15 @@ The implementation is complete only when:ordinary route or generated preflight absent from the compiled channelroute plan, and route-planning failures use their stable compile errorcodes.-7. Every kernel effect kind, every dispatch action kind, and the- `final_output` interception are covered through preparation, advertisement,- materialization, dispatch, prompts, and inspection for root, self-delegated- root, named and dynamic task children, non-task children,- provider-dependent calls, Workflow depth, and structured output. Named task- children receive `task_update`. No harness or execution code branches on a- tool name or source ID.+7. Every selected native-handled tool carries one compiled handling descriptor,+ every local or remote delegation carries one prepared dispatch descriptor,+ and every handling and dispatch union is switched exhaustively at its owning+ layer. Root, self-delegated root, named and dynamic task children, non-task+ children, provider-dependent calls, Workflow depth, approvals, and+ structured output preserve their current behavior. Named task children+ receive `task_update`. No harness or execution code selects source-backed+ behavior from a tool name, logical path, owner, source ID, or executor+ identity.8. Connection search preserves filtering, auth, approval, failure, long-name,durable callback, and restart behavior without history scanning; home andeve-channel replacement, client payload validation for health and info,@@ -1263,8 +1239,8 @@ The implementation is complete only when:changes module-map identity, while relocating identical filesystem contentwithout changing its logical extension namespace does not.12. The complete implementation lands with all required local and CI- validation passing, existing higher-level suites modified only at the- named breaking surfaces, no new e2e or scenario suites, and no new+ validation passing, existing higher-level suites behaviorally unchanged,+ no new e2e or scenario suites, no new plan artifact, and no new`guard-invariants` rules.## Invariants and rejected alternatives@@ -1292,12 +1268,15 @@ The implementation is complete only when:- `defineDynamic` remains the sole dynamic-definition lifecycle. Framework andfuture memory features do not gain parallel validation, durability,replacement, collision, or callback stores.-- Kernel effects are declared on public definitions and implemented by the- kernel. Tool definitions never import Workflow, harness, or execution- internals, and no effect is keyed by tool name.+- Native handling is internally declared on canonical definitions, serialized+ on selected compiled tools, and consumed through prepared descriptors.+ Public authoring APIs do not expose the declaration, definition modules do+ not import Workflow, harness, or execution internals, and no source-backed+ behavior is keyed by tool name.- Ordinary route dispatch comes only from the compiled route plan. Native- behavior is limited to the closed kernel effect kinds and host inventory; a- universal native-tool, route, or adapter escape hatch is rejected.+ behavior is limited to the closed tool-handling union, the localized+ `final_output` interception, and the host inventory; a universal native-tool,+ route, or adapter escape hatch is rejected.- Pre-1.0 cleanup is a breaking replacement: no legacy manifest reader,agent-info schema, health fallback, history reconstruction, duplicate statusstate, or compatibility path is retained.