The Open Framework for Building Agents
fix(eve): cap recursive subagent delegation (#409)
Ruiafa22f8a49fb
diff --git a/.changeset/cap-recursive-subagent-delegation.md b/.changeset/cap-recursive-subagent-delegation.mdnew file mode 100644index 000000000..92654fbd1--- /dev/null+++ b/.changeset/cap-recursive-subagent-delegation.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Cap recursive subagent delegation at three child-session levels by default, configurable with `defineAgent({ limits: { maxSubagentDepth } })`. At the limit, eve no longer advertises subagent tools and blocks stale delegated calls before starting another child session.diff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.mdindex af9d3c9d9..ebaabd3f1 100644--- a/docs/reference/typescript-api.md+++ b/docs/reference/typescript-api.md@@ -52,7 +52,7 @@ export default defineTool({| `mockModel` | `eve/evals` | Deterministic fixture agent models | [Evals](../evals/overview) || `useEveAgent` | `eve/react`, `eve/vue`, `eve/svelte` | frontend | [Frontend](../guides/frontend/overview) |-A few non-`define*` helpers round out the set: `disableTool` from `eve/tools` (see [Default harness](../concepts/default-harness)), the route verbs `GET`/`POST`/`PUT`/`PATCH`/`DELETE`/`WS` from `eve/channels`, the approval policies `always`/`once`/`never` from `eve/tools/approval`, and the channel auth helpers `localDev`/`vercelOidc`/`placeholderAuth` from `eve/channels/auth`. To wrap a built-in tool, import its default value from `eve/tools/defaults` (`bash`, `readFile`, `writeFile`, `glob`, `grep`, `webFetch`, `webSearch`, `todo`, `loadSkill`). `AgentReasoningDefinition` is exported from `eve` for the top-level `defineAgent({ reasoning })` setting. `AgentWorkflowDefinition` and `AgentWorkflowWorldDefinition` are exported from `eve` for the `defineAgent({ experimental: { workflow } })` config shape.+A few non-`define*` helpers round out the set: `disableTool` from `eve/tools` (see [Default harness](../concepts/default-harness)), the route verbs `GET`/`POST`/`PUT`/`PATCH`/`DELETE`/`WS` from `eve/channels`, the approval policies `always`/`once`/`never` from `eve/tools/approval`, and the channel auth helpers `localDev`/`vercelOidc`/`placeholderAuth` from `eve/channels/auth`. To wrap a built-in tool, import its default value from `eve/tools/defaults` (`bash`, `readFile`, `writeFile`, `glob`, `grep`, `webFetch`, `webSearch`, `todo`, `loadSkill`). `AgentReasoningDefinition` is exported from `eve` for the top-level `defineAgent({ reasoning })` setting. `AgentLimitsDefinition` is exported for `defineAgent({ limits })`. `AgentWorkflowDefinition` and `AgentWorkflowWorldDefinition` are exported from `eve` for the `defineAgent({ experimental: { workflow } })` config shape.## Runtime context (`ctx`)diff --git a/docs/subagents.mdx b/docs/subagents.mdxindex dedc7c124..7cb8cf342 100644--- a/docs/subagents.mdx+++ b/docs/subagents.mdx@@ -77,6 +77,23 @@ The built-in `agent` tool is the exception. Its children share the parent's sandeve lowers every subagent (built-in copy, declared, or [remote](./guides/remote-agents)) into a model-visible tool with the same `{ message, outputSchema? }` shape. The parent packs `message` with everything the child needs, since the child never sees the parent's history. Set `outputSchema` to run the child in task mode, returning structured output as the tool result.+Subagent delegation is capped by default at three child-session levels. Increase+or lower that limit with `limits.maxSubagentDepth`:++```ts title="agent/agent.ts"+export default defineAgent({+ model: "anthropic/claude-sonnet-4.6",+ limits: {+ maxSubagentDepth: 4,+ },+});+```++The root session is depth 0. With `maxSubagentDepth: 4`, eve may create child sessions+at depths 1 through 4; a session already at depth 4 cannot delegate again.++At the configured depth, eve stops advertising subagent tools, including declared local subagents, remote-agent tools, the built-in `agent` tool, and the `Workflow` orchestration tool when it would only expose subagents. If a stale or forced subagent call still reaches execution, eve blocks it and returns an error tool result instead of starting another child session.+A declared subagent's tool name is the bare path-derived name, with no prefix. `agent/subagents/researcher/` registers as the tool `researcher`. Unlike connection tools (`<connection>__<tool>`), it carries no namespace, so the model, approvals, logs, and evals all reference it by that name. Its input schema is:```tsdiff --git a/e2e/fixtures/agent-subagents/agent/agent.ts b/e2e/fixtures/agent-subagents/agent/agent.tsindex bea278ea3..5bad44315 100644--- a/e2e/fixtures/agent-subagents/agent/agent.ts+++ b/e2e/fixtures/agent-subagents/agent/agent.ts@@ -1,6 +1,9 @@import { defineAgent } from "eve";export default defineAgent({+ limits: {+ maxSubagentDepth: 4,+ },model: "openai/gpt-5.5",reasoning: "high",});diff --git a/e2e/fixtures/agent-subagents/evals/recursive-depth-limit.eval.ts b/e2e/fixtures/agent-subagents/evals/recursive-depth-limit.eval.tsnew file mode 100644index 000000000..d5957c8dd--- /dev/null+++ b/e2e/fixtures/agent-subagents/evals/recursive-depth-limit.eval.ts@@ -0,0 +1,30 @@+import { defineEval } from "eve/evals";++const DONE_TOKEN = "RECURSIVE_SUBAGENT_DEPTH_LIMIT_OK";++/**+ * Recursive subagent stress: the prompt asks each built-in `agent` child to+ * delegate again until the configured depth cap removes subagent tools.+ */+export default defineEval({+ description:+ "Recursive subagent stress: repeated built-in agent delegation stops at the depth cap without failed actions.",+ async test(t) {+ await t.send(+ [+ "Stress recursive subagent delegation.",+ "Use the built-in agent subagent as deeply as eve allows.",+ "Root level: call agent once.",+ "The first child must call agent once.",+ "The second child must call agent once.",+ "The third child must call agent once.",+ "The fourth child must not call another subagent; it should report that no deeper delegation tool is available and return the token LEVEL_4_REACHED.",+ `After the recursive chain returns, reply with ${DONE_TOKEN} and no extra status token.`,+ ].join(" "),+ );++ t.calledSubagent("agent");+ t.noFailedActions();+ t.messageIncludes(DONE_TOKEN);+ },+});diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.tsindex 51ae1b143..be60977ba 100644--- a/packages/eve/src/channel/types.ts+++ b/packages/eve/src/channel/types.ts@@ -272,6 +272,17 @@ export interface RunInput {};readonly mode: RunMode;readonly parent?: SessionParent;+ /**+ * Framework-owned depth of delegated local subagent sessions. Root sessions+ * omit this and are treated as depth 0; each local child receives+ * parent depth + 1.+ */+ readonly subagentDepth?: number;+ /**+ * Optional maximum delegated subagent depth inherited by this run. When+ * omitted, the session uses its resolved agent config or eve's default.+ */+ readonly subagentMaxDepth?: number;}export interface DeliverInput {diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.tsindex cb6106c25..343d47277 100644--- a/packages/eve/src/compiler/manifest.ts+++ b/packages/eve/src/compiler/manifest.ts@@ -40,7 +40,7 @@ export const ROOT_COMPILED_AGENT_NODE_ID = "__root__";/*** Current compiled manifest schema version.*/-export const COMPILED_AGENT_MANIFEST_VERSION = 31;+export const COMPILED_AGENT_MANIFEST_VERSION = 32;/*** Compiled channel entry preserved in the compiled manifest.@@ -357,6 +357,12 @@ const compiledAgentCompactionDefinitionSchema: z.ZodType<CompiledAgentCompaction}).strict();+const compiledAgentLimitsDefinitionSchema = z+ .object({+ maxSubagentDepth: z.number().int().positive().optional(),+ })+ .strict();+const compiledAgentConfigSchema: z.ZodType<CompiledAgentDefinition> = z.object({build: compiledAgentBuildDefinitionSchema.optional(),@@ -375,6 +381,7 @@ const compiledAgentConfigSchema: z.ZodType<CompiledAgentDefinition> = z.enum(["provider-default", "none", "minimal", "low", "medium", "high", "xhigh"]).optional(),source: moduleSourceRefSchema.optional(),+ limits: compiledAgentLimitsDefinitionSchema.optional(),}).strict();diff --git a/packages/eve/src/compiler/normalize-agent-config.ts b/packages/eve/src/compiler/normalize-agent-config.tsindex a86b1c36d..a65d89f5e 100644--- a/packages/eve/src/compiler/normalize-agent-config.ts+++ b/packages/eve/src/compiler/normalize-agent-config.ts@@ -71,6 +71,7 @@ export async function compileAgentConfig(outputSchema?: JsonObject;reasoning?: CompiledAgentDefinition["reasoning"];source?: ModuleSourceRef;+ limits?: CompiledAgentDefinition["limits"];} = {compaction,model,@@ -103,6 +104,12 @@ export async function compileAgentConfig(compiledConfig.reasoning = definition.reasoning;}+ if (definition.limits !== undefined) {+ compiledConfig.limits = {+ maxSubagentDepth: definition.limits.maxSubagentDepth,+ };+ }+if (configModule !== undefined) {compiledConfig.source = {exportName: configModule.exportName,diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.tsindex 8e623cbdc..8c46b9bbb 100644--- a/packages/eve/src/context/keys.ts+++ b/packages/eve/src/context/keys.ts@@ -66,6 +66,8 @@ export const ChannelInstrumentationKey = new ContextKey<ChannelInstrumentationPr);export const ModeKey = new ContextKey<RunMode>("eve.mode");export const ParentSessionKey = new ContextKey<SessionParent>("eve.parentSession");+export const SubagentDepthKey = new ContextKey<number>("eve.subagentDepth");+export const SubagentMaxDepthKey = new ContextKey<number>("eve.subagentMaxDepth");/*** Session-level capability flags (see {@link SessionCapabilities}). Setdiff --git a/packages/eve/src/execution/create-session-step.test.ts b/packages/eve/src/execution/create-session-step.test.tsnew file mode 100644index 000000000..8aa539ce0--- /dev/null+++ b/packages/eve/src/execution/create-session-step.test.ts@@ -0,0 +1,58 @@+import { describe, expect, it, vi } from "vitest";++import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";+import { createSessionStep } from "#execution/create-session-step.js";+import type { RuntimeTurnAgent } from "#runtime/agent/bootstrap.js";++vi.mock("#runtime/sessions/compiled-agent-cache.js", () => ({+ getCompiledRuntimeAgentBundle: vi.fn(),+}));++const TestTurnAgent: RuntimeTurnAgent = {+ id: "test-agent",+ instructions: ["You are a test assistant."],+ model: { id: "test-model" },+ tools: [],+ workspaceSpec: { rootEntries: [] },+};++describe("createSessionStep", () => {+ it("seeds subagent max depth from resolved agent config", async () => {+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({+ resolvedAgent: {+ config: {+ limits: { maxSubagentDepth: 4 },+ },+ },+ turnAgent: TestTurnAgent,+ } as never);++ const { state } = await createSessionStep({+ compiledArtifactsSource: { kind: "bundled" },+ continuationToken: "http:test",+ sessionId: "sess-root",+ });++ expect(state.snapshot?.session.subagentMaxDepth).toBe(4);+ });++ it("keeps inherited subagent max depth when one is provided", async () => {+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({+ resolvedAgent: {+ config: {+ limits: { maxSubagentDepth: 2 },+ },+ },+ turnAgent: TestTurnAgent,+ } as never);++ const { state } = await createSessionStep({+ compiledArtifactsSource: { kind: "bundled" },+ continuationToken: "subagent:test",+ sessionId: "sess-child",+ subagentMaxDepth: 4,+ });++ expect(state.snapshot?.session.subagentMaxDepth).toBe(4);+ });+});diff --git a/packages/eve/src/execution/create-session-step.ts b/packages/eve/src/execution/create-session-step.tsindex 18633090e..270c43762 100644--- a/packages/eve/src/execution/create-session-step.ts+++ b/packages/eve/src/execution/create-session-step.ts@@ -30,6 +30,8 @@ export async function createSessionStep(input: {readonly nodeId?: string;readonly rootSessionId?: string;readonly sessionId: string;+ readonly subagentDepth?: number;+ readonly subagentMaxDepth?: number;}): Promise<CreateSessionStepResult> {"use step";@@ -46,6 +48,9 @@ export async function createSessionStep(input: {outputSchema: input.outputSchema,rootSessionId: input.rootSessionId,sessionId: input.sessionId,+ subagentDepth: input.subagentDepth,+ subagentMaxDepth:+ input.subagentMaxDepth ?? bundle.resolvedAgent.config.limits?.maxSubagentDepth,turnAgent: bundle.turnAgent,});diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.tsindex 5f831d4f6..65934014f 100644--- a/packages/eve/src/execution/dispatch-runtime-actions-step.ts+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.ts@@ -44,6 +44,13 @@ import { buildSubagentRunInput, type SubagentInputSource } from "#execution/subaimport { createWorkflowRuntime, workflowEntryReference } from "#execution/workflow-runtime.js";import { createLogger, logError } from "#internal/logging.js";import { toErrorMessage } from "#shared/errors.js";+import {+ type DelegatedRuntimeActionRequest,+ getSubagentDelegationName,+ isSubagentDelegationAction,+ resolveSubagentDelegationLimit,+ type SubagentDelegationLimit,+} from "#harness/subagent-depth.js";const log = createLogger("execution.dispatch-runtime-actions");@@ -84,12 +91,25 @@ export async function dispatchRuntimeActionsStep(input: {const writer = input.parentWritable.getWriter();const adapterCtx = buildAdapterContext(adapter, ctx);+ const delegationLimit = resolveSubagentDelegationLimit(session);let nextSession = session;const results: RuntimeSubagentResultActionResult[] = [];try {for (const action of batch.actions) {+ if (delegationLimit.reached && isSubagentDelegationAction(action)) {+ log.warn("subagent depth limit reached; blocking delegated call", {+ callId: action.callId,+ currentDepth: delegationLimit.currentDepth,+ maxDepth: delegationLimit.maxDepth,+ nodeId: action.nodeId,+ subagentName: getSubagentDelegationName(action),+ });+ results.push(createSubagentDepthLimitResult({ action, delegationLimit }));+ continue;+ }+let childSessionId: string;let name: string;let remote: { readonly url: string } | undefined;@@ -206,3 +226,22 @@ function createRemoteAgentStartFailureResult(input: {subagentName: input.action.remoteAgentName,};}++function createSubagentDepthLimitResult(input: {+ readonly action: DelegatedRuntimeActionRequest;+ readonly delegationLimit: SubagentDelegationLimit;+}): RuntimeSubagentResultActionResult {+ const subagentName = getSubagentDelegationName(input.action);+ return {+ callId: input.action.callId,+ isError: true,+ kind: "subagent-result",+ output: {+ code: "SUBAGENT_DEPTH_LIMIT_REACHED",+ currentDepth: input.delegationLimit.currentDepth,+ maxDepth: input.delegationLimit.maxDepth,+ message: `Subagent depth limit reached (${input.delegationLimit.maxDepth}); "${subagentName}" was not called.`,+ },+ subagentName,+ };+}diff --git a/packages/eve/src/execution/durable-session-store.ts b/packages/eve/src/execution/durable-session-store.tsindex 62d3dd0e4..30e2cd457 100644--- a/packages/eve/src/execution/durable-session-store.ts+++ b/packages/eve/src/execution/durable-session-store.ts@@ -84,6 +84,8 @@ export interface DurableSession {readonly outputSchema?: JsonObject;readonly state?: SessionStateMap;readonly sandboxState?: SandboxState;+ readonly subagentDepth?: number;+ readonly subagentMaxDepth?: number;readonly agent: {readonly system: string;};diff --git a/packages/eve/src/execution/runtime-context.test.ts b/packages/eve/src/execution/runtime-context.test.tsindex aa9abb88d..c9bf8457a 100644--- a/packages/eve/src/execution/runtime-context.test.ts+++ b/packages/eve/src/execution/runtime-context.test.ts@@ -7,6 +7,7 @@ import {type SessionAuthContext,SessionIdKey,SessionKey,+ SubagentMaxDepthKey,} from "#context/keys.js";import { buildRunContext } from "#execution/runtime-context.js";@@ -246,4 +247,20 @@ describe("buildRunContext", () => {expect(projection!.kind).toBe("http");expect(projection!.metadata).toEqual({});});++ it("seeds inherited subagent max depth from the run input", () => {+ const ctx = buildRunContext({+ bundle: createMinimalBundle(),+ run: {+ auth: null,+ adapter: { kind: "subagent" },+ continuationToken: "t",+ input: { message: "hi" },+ mode: "task",+ subagentMaxDepth: 4,+ },+ });++ expect(ctx.require(SubagentMaxDepthKey)).toBe(4);+ });});diff --git a/packages/eve/src/execution/runtime-context.ts b/packages/eve/src/execution/runtime-context.tsindex 78f645db0..f63c9dce3 100644--- a/packages/eve/src/execution/runtime-context.ts+++ b/packages/eve/src/execution/runtime-context.ts@@ -11,6 +11,8 @@ import {ModeKey,ParentSessionKey,SessionCallbackKey,+ SubagentDepthKey,+ SubagentMaxDepthKey,} from "#context/keys.js";import { BundleKey, type CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";@@ -57,5 +59,13 @@ export function buildRunContext(input: {ctx.set(ParentSessionKey, run.parent);}+ if (run.subagentDepth !== undefined) {+ ctx.set(SubagentDepthKey, run.subagentDepth);+ }++ if (run.subagentMaxDepth !== undefined) {+ ctx.set(SubagentMaxDepthKey, run.subagentMaxDepth);+ }+return ctx;}diff --git a/packages/eve/src/execution/session.test.ts b/packages/eve/src/execution/session.test.tsindex bcfa6cb3c..989f6fbe5 100644--- a/packages/eve/src/execution/session.test.ts+++ b/packages/eve/src/execution/session.test.ts@@ -209,6 +209,27 @@ describe("createSession", () => {expect(hydrated.outputSchema).toEqual(runOutputSchema);});+ it("persists subagent depth limits through durable session projection and hydration", () => {+ const session = createSession({+ continuationToken: "root-token",+ sessionId: "sess-root",+ subagentDepth: 2,+ subagentMaxDepth: 4,+ turnAgent: createTestTurnAgent(),+ });++ const durable = projectToDurableSession(session);+ const hydrated = hydrateDurableSession({+ durable,+ turnAgent: createTestTurnAgent(),+ });++ expect(durable.subagentDepth).toBe(2);+ expect(durable.subagentMaxDepth).toBe(4);+ expect(hydrated.subagentDepth).toBe(2);+ expect(hydrated.subagentMaxDepth).toBe(4);+ });+it("restores current reasoning configuration when hydrating a durable session", () => {const session = createSession({continuationToken: "root-token",diff --git a/packages/eve/src/execution/session.ts b/packages/eve/src/execution/session.tsindex 4234d3379..42da983ab 100644--- a/packages/eve/src/execution/session.ts+++ b/packages/eve/src/execution/session.ts@@ -53,6 +53,8 @@ export interface CreateSessionInput {readonly sessionId: string;readonly turnAgent: RuntimeTurnAgent;readonly outputSchema?: HarnessSession["outputSchema"];+ readonly subagentDepth?: number;+ readonly subagentMaxDepth?: number;}/** Creates a fresh {@link HarnessSession} from the current `turnAgent`. */@@ -85,6 +87,12 @@ export function createSession(input: CreateSessionInput): HarnessSession {if (input.outputSchema !== undefined) {session.outputSchema = input.outputSchema;}+ if (input.subagentDepth !== undefined) {+ session.subagentDepth = input.subagentDepth;+ }+ if (input.subagentMaxDepth !== undefined) {+ session.subagentMaxDepth = input.subagentMaxDepth;+ }return session;}@@ -149,6 +157,8 @@ export function projectToDurableSession(session: HarnessSession): DurableSessionsandboxState?: HarnessSession["sandboxState"];sessionId: string;state?: HarnessSession["state"];+ subagentDepth?: number;+ subagentMaxDepth?: number;} = {agent: { system: session.agent.system },continuationToken: session.continuationToken,@@ -177,6 +187,12 @@ export function projectToDurableSession(session: HarnessSession): DurableSessionif (session.state !== undefined) {durable.state = session.state;}+ if (session.subagentDepth !== undefined) {+ durable.subagentDepth = session.subagentDepth;+ }+ if (session.subagentMaxDepth !== undefined) {+ durable.subagentMaxDepth = session.subagentMaxDepth;+ }return durable;}@@ -229,6 +245,12 @@ export function hydrateDurableSession(input: {if (durable.state !== undefined) {session.state = durable.state;}+ if (durable.subagentDepth !== undefined) {+ session.subagentDepth = durable.subagentDepth;+ }+ if (durable.subagentMaxDepth !== undefined) {+ session.subagentMaxDepth = durable.subagentMaxDepth;+ }return session;}diff --git a/packages/eve/src/execution/subagent-tool.test.ts b/packages/eve/src/execution/subagent-tool.test.tsindex f32ce0560..d6cc3b0eb 100644--- a/packages/eve/src/execution/subagent-tool.test.ts+++ b/packages/eve/src/execution/subagent-tool.test.ts@@ -157,6 +157,25 @@ describe("buildSubagentRunInput", () => {});});+ it("increments subagent depth for the child run input", () => {+ const nestedSession: HarnessSession = {+ ...makeSession(),+ sessionId: "intermediate-session",+ subagentDepth: 2,+ subagentMaxDepth: 4,+ };+ const { runInput } = buildRuntimeSubagentRunInput({+ action: makeAction(),+ auth: null,+ batchEvent: { sequence: 1, turnId: "turn-99" },+ initiatorAuth: null,+ session: nestedSession,+ });++ expect(runInput.subagentDepth).toBe(3);+ expect(runInput.subagentMaxDepth).toBe(4);+ });+it("threads outputSchema from action input to RunInput", () => {const schema = { type: "object", properties: { result: { type: "string" } } };const action: RuntimeSubagentCallActionRequest = {diff --git a/packages/eve/src/execution/subagent-tool.ts b/packages/eve/src/execution/subagent-tool.tsindex bf9e4731a..7b5f41d5e 100644--- a/packages/eve/src/execution/subagent-tool.ts+++ b/packages/eve/src/execution/subagent-tool.ts@@ -10,6 +10,7 @@ import type { HarnessSession } from "#harness/types.js";import type { JsonObject } from "#shared/json.js";import type { RuntimeSubagentCallActionRequest } from "#runtime/actions/types.js";import { mintSubagentContinuationToken } from "#execution/session.js";+import { resolveSubagentDelegationLimit } from "#harness/subagent-depth.js";/*** Pending runtime-action batch event metadata needed for child run lineage.@@ -83,6 +84,7 @@ export function buildSubagentRunInput(input: {// explicit root, so its own `sessionId` becomes the root for its// children.const rootSessionId = session.rootSessionId ?? session.sessionId;+ const delegationLimit = resolveSubagentDelegationLimit(session);const runInput: RunInput = {adapter: {@@ -116,6 +118,8 @@ export function buildSubagentRunInput(input: {sequence: batchEvent.sequence,},},+ subagentDepth: delegationLimit.nextChildDepth,+ subagentMaxDepth: session.subagentMaxDepth,};return { childContinuationToken, runInput };diff --git a/packages/eve/src/execution/workflow-entry.test.ts b/packages/eve/src/execution/workflow-entry.test.tsindex 2536ac709..9f8e7cb78 100644--- a/packages/eve/src/execution/workflow-entry.test.ts+++ b/packages/eve/src/execution/workflow-entry.test.ts@@ -3,7 +3,7 @@ import { createHook } from "#compiled/@workflow/core/index.js";import { resumeHook } from "#internal/workflow/runtime.js";import type { HookPayload } from "#channel/types.js";-import { ChannelRequestIdKey } from "#context/keys.js";+import { ChannelRequestIdKey, SubagentDepthKey, SubagentMaxDepthKey } from "#context/keys.js";import { createSessionStep } from "#execution/create-session-step.js";import type { DurableSessionState } from "#execution/durable-session-store.js";import type { TurnControlPayload } from "#execution/turn-control-protocol.js";@@ -229,6 +229,29 @@ describe("workflowEntry", () => {});});+ it("passes delegated subagent depth options to session creation", async () => {+ const sessionState = createBaseSessionState();+ vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));+ installHookMocks({+ turnControls: [turnResult({ action: "done", output: "ok", sessionState })],+ });++ await workflowEntry({+ input: { message: "hello there" },+ serializedContext: createSerializedContext({+ [SubagentDepthKey.name]: 3,+ [SubagentMaxDepthKey.name]: 4,+ }),+ });++ expect(createSessionStep).toHaveBeenCalledWith(+ expect.objectContaining({+ subagentDepth: 3,+ subagentMaxDepth: 4,+ }),+ );+ });+it("passes the resumed channel request id to the next turn", async () => {const sessionState = createBaseSessionState();vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));diff --git a/packages/eve/src/execution/workflow-entry.ts b/packages/eve/src/execution/workflow-entry.tsindex dbc82e2aa..d69aae0d3 100644--- a/packages/eve/src/execution/workflow-entry.ts+++ b/packages/eve/src/execution/workflow-entry.ts@@ -29,6 +29,7 @@ import {createSessionDeliveryHook,type SessionDeliveryHook,} from "#execution/session-delivery-hook.js";+import { readSerializedSubagentSessionDepth } from "#harness/subagent-depth.js";// workflow-entry.ts is the durable workflow body — the bundler rejects// node built-ins here, so `internal/logging.ts` cannot be imported.@@ -86,6 +87,9 @@ export async function workflowEntry(input: WorkflowEntryInput): Promise<Workflow// Derived once and reused for createSession + tag emission so the// chain-root id can never drift between persisted session and tags.const rootSessionIdFromParent = readRootSessionId(input.serializedContext);+ const { subagentDepth, subagentMaxDepth } = readSerializedSubagentSessionDepth(+ input.serializedContext,+ );const { state: sessionState } = await createSessionStep({compiledArtifactsSource: serializedBundle.source,@@ -94,6 +98,8 @@ export async function workflowEntry(input: WorkflowEntryInput): Promise<WorkflowoutputSchema: input.input.outputSchema,rootSessionId: rootSessionIdFromParent,sessionId,+ subagentDepth,+ subagentMaxDepth,});return await runDriverLoop({diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.tsindex 2b01d0faa..a2f639c82 100644--- a/packages/eve/src/execution/workflow-steps.test.ts+++ b/packages/eve/src/execution/workflow-steps.test.ts@@ -8,6 +8,7 @@ import { AuthKey, ContinuationTokenKey, ModeKey, SessionIdKey } from "#context/kimport { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";import { serializeContext } from "#context/serialize.js";import { setPendingRuntimeActionBatch } from "#harness/runtime-actions.js";+import { DEFAULT_SUBAGENT_MAX_DEPTH } from "#harness/subagent-depth.js";import { getPendingAuthorization, setPendingAuthorization } from "#harness/authorization.js";import type { HarnessSession, StepResult } from "#harness/types.js";import { createEmptyHookRegistry } from "#runtime/hooks/registry.js";@@ -499,6 +500,95 @@ describe("dispatchRuntimeActionsStep", () => {);expect(workflowWritesByNamespace.get(DEFAULT_WORKFLOW_STREAM_NAMESPACE)).toBeUndefined();});++ it("blocks pending subagent calls at the subagent depth limit", async () => {+ const compiledBundle = {+ adapterRegistry: {+ adaptersByKind: new Map([[threadContextAdapter.kind, threadContextAdapter]]),+ },+ compiledArtifactsSource: {},+ graph: {+ nodesByNodeId: new Map(),+ root: {+ sandboxRegistry: { sandbox: null },+ turnAgent: TestTurnAgent,+ },+ },+ hookRegistry: createEmptyHookRegistry(),+ resolvedAgent: { config: {} },+ subagentRegistry: {+ subagentsByNodeId: new Map(),+ },+ toolRegistry: {},+ turnAgent: TestTurnAgent,+ } as never;+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(compiledBundle);+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});++ const session = setPendingRuntimeActionBatch({+ actions: [+ {+ callId: "call-1",+ description: "Delegate the work.",+ input: { message: "try to recurse" },+ kind: "subagent-call",+ name: "delegate",+ nodeId: "subagents/delegate",+ subagentName: "delegate",+ },+ ],+ event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },+ responseMessages: [],+ session: createStubSession({+ continuationToken: "http:parent",+ sessionId: "parent-session",+ subagentDepth: DEFAULT_SUBAGENT_MAX_DEPTH + 1,+ subagentMaxDepth: DEFAULT_SUBAGENT_MAX_DEPTH + 1,+ }),+ });+ installSessionStoreMocks([session]);++ const sessionState = createStubSessionState({+ continuationToken: "http:parent",+ sessionId: "parent-session",+ });++ await expect(+ dispatchRuntimeActionsStep({+ parentContinuationToken: "turn-inbox",+ parentWritable: createTestWritable(),+ serializedContext: createSerializedContext(),+ sessionState,+ }),+ ).resolves.toEqual({+ results: [+ {+ callId: "call-1",+ isError: true,+ kind: "subagent-result",+ output: {+ code: "SUBAGENT_DEPTH_LIMIT_REACHED",+ currentDepth: DEFAULT_SUBAGENT_MAX_DEPTH + 1,+ maxDepth: DEFAULT_SUBAGENT_MAX_DEPTH + 1,+ message: `Subagent depth limit reached (${DEFAULT_SUBAGENT_MAX_DEPTH + 1}); "delegate" was not called.`,+ },+ subagentName: "delegate",+ },+ ],+ sessionState,+ });+ expect(startMock).not.toHaveBeenCalled();+ expect(warn).toHaveBeenCalledWith(+ "[eve:execution.dispatch-runtime-actions] subagent depth limit reached; blocking delegated call",+ expect.objectContaining({+ callId: "call-1",+ currentDepth: DEFAULT_SUBAGENT_MAX_DEPTH + 1,+ maxDepth: DEFAULT_SUBAGENT_MAX_DEPTH + 1,+ subagentName: "delegate",+ }),+ );+ expect(workflowWritesByNamespace.get(DEFAULT_WORKFLOW_STREAM_NAMESPACE)).toBeUndefined();+ });});describe("turnStep", () => {diff --git a/packages/eve/src/harness/advertised-tools.test.ts b/packages/eve/src/harness/advertised-tools.test.tsnew file mode 100644index 000000000..50c98bbff--- /dev/null+++ b/packages/eve/src/harness/advertised-tools.test.ts@@ -0,0 +1,101 @@+import { jsonSchema } from "ai";+import { describe, expect, it } from "vitest";++import { getAdvertisedTools } from "#harness/advertised-tools.js";+import { DEFAULT_SUBAGENT_MAX_DEPTH } from "#harness/subagent-depth.js";+import type { HarnessToolDefinition } from "#harness/execute-tool.js";+import type { HarnessToolMap } from "#harness/types.js";++describe("getAdvertisedTools", () => {+ it("keeps subagent tools below the subagent depth limit", () => {+ const tools = new Map([+ ["add", createTool("add")],+ ["delegate", createSubagentTool("delegate")],+ ]) satisfies HarnessToolMap;++ const advertisedTools = getAdvertisedTools({+ session: { subagentDepth: DEFAULT_SUBAGENT_MAX_DEPTH - 1 },+ tools,+ });++ expect([...advertisedTools.keys()]).toEqual(["add", "delegate"]);+ });++ it("removes subagent tools at the subagent depth limit", () => {+ const tools = new Map([+ ["add", createTool("add")],+ ["delegate", createSubagentTool("delegate")],+ ]) satisfies HarnessToolMap;++ const advertisedTools = getAdvertisedTools({+ session: { subagentDepth: DEFAULT_SUBAGENT_MAX_DEPTH },+ tools,+ });++ expect([...advertisedTools.keys()]).toEqual(["add"]);+ });++ it("removes the built-in agent tool at the subagent depth limit", () => {+ const tools = new Map([+ ["add", createTool("add")],+ ["agent", createSubagentTool("agent")],+ ]) satisfies HarnessToolMap;++ const advertisedTools = getAdvertisedTools({+ session: { subagentDepth: DEFAULT_SUBAGENT_MAX_DEPTH },+ tools,+ });++ expect([...advertisedTools.keys()]).toEqual(["add"]);+ });++ it("uses the session-specific subagent max depth when configured", () => {+ const tools = new Map([+ ["add", createTool("add")],+ ["delegate", createSubagentTool("delegate")],+ ]) satisfies HarnessToolMap;+ const maxDepth = DEFAULT_SUBAGENT_MAX_DEPTH + 1;++ const belowCustomLimit = getAdvertisedTools({+ session: { subagentDepth: DEFAULT_SUBAGENT_MAX_DEPTH, subagentMaxDepth: maxDepth },+ tools,+ });+ const atCustomLimit = getAdvertisedTools({+ session: { subagentDepth: maxDepth, subagentMaxDepth: maxDepth },+ tools,+ });++ expect([...belowCustomLimit.keys()]).toEqual(["add", "delegate"]);+ expect([...atCustomLimit.keys()]).toEqual(["add"]);+ });+});++describe("getAdvertisedTools for definition arrays", () => {+ it("removes subagent tool definitions at the subagent depth limit", () => {+ const advertisedTools = getAdvertisedTools({+ session: { subagentDepth: DEFAULT_SUBAGENT_MAX_DEPTH },+ tools: [createTool("add"), createSubagentTool("delegate")],+ });++ expect(advertisedTools.map((tool) => tool.name)).toEqual(["add"]);+ });+});++function createTool(name: string): HarnessToolDefinition {+ return {+ description: `${name} description`,+ inputSchema: jsonSchema({ type: "object" }),+ name,+ };+}++function createSubagentTool(name: string): HarnessToolDefinition {+ return {+ ...createTool(name),+ runtimeAction: {+ kind: "subagent-call",+ nodeId: "workers",+ subagentName: name,+ },+ };+}diff --git a/packages/eve/src/harness/advertised-tools.ts b/packages/eve/src/harness/advertised-tools.tsnew file mode 100644index 000000000..6044a0e7b--- /dev/null+++ b/packages/eve/src/harness/advertised-tools.ts@@ -0,0 +1,72 @@+import type { HarnessToolDefinition } from "#harness/execute-tool.js";+import { resolveSubagentDelegationLimit } from "#harness/subagent-depth.js";+import type { HarnessSession, HarnessToolMap } from "#harness/types.js";++type AdvertisedToolMapInput = {+ readonly session: Pick<HarnessSession, "subagentDepth" | "subagentMaxDepth">;+ readonly tools: HarnessToolMap;+};++type AdvertisedToolDefinitionsInput = {+ readonly session: Pick<HarnessSession, "subagentDepth" | "subagentMaxDepth">;+ readonly tools: readonly HarnessToolDefinition[];+};++type AdvertisedToolsInput = AdvertisedToolMapInput | AdvertisedToolDefinitionsInput;++export function getAdvertisedTools(input: AdvertisedToolMapInput): HarnessToolMap;+export function getAdvertisedTools(+ input: AdvertisedToolDefinitionsInput,+): readonly HarnessToolDefinition[];+export function getAdvertisedTools(+ input: AdvertisedToolsInput,+): HarnessToolMap | readonly HarnessToolDefinition[] {+ if (isToolDefinitionList(input.tools)) {+ return filterSubagentToolDefinitionsAtDepthLimit(input.tools, input.session);+ }++ return filterSubagentToolMapAtDepthLimit(input.tools, input.session);+}++function filterSubagentToolDefinitionsAtDepthLimit(+ tools: readonly HarnessToolDefinition[],+ session: Pick<HarnessSession, "subagentDepth" | "subagentMaxDepth">,+): readonly HarnessToolDefinition[] {+ const delegationLimit = resolveSubagentDelegationLimit(session);+ const filteredTools: HarnessToolDefinition[] = [];++ for (const tool of tools) {+ if (delegationLimit.reached && isDelegatedRuntimeActionTool(tool)) {+ continue;+ }+ filteredTools.push(tool);+ }+ return filteredTools;+}++function filterSubagentToolMapAtDepthLimit(+ tools: HarnessToolMap,+ session: Pick<HarnessSession, "subagentDepth" | "subagentMaxDepth">,+): HarnessToolMap {+ const delegationLimit = resolveSubagentDelegationLimit(session);+ const filteredTools = new Map<string, HarnessToolDefinition>();++ for (const [name, tool] of tools) {+ if (delegationLimit.reached && isDelegatedRuntimeActionTool(tool)) {+ continue;+ }+ filteredTools.set(name, tool);+ }+ return filteredTools;+}++function isDelegatedRuntimeActionTool(definition: HarnessToolDefinition): boolean {+ const runtimeAction = definition.runtimeAction;+ return runtimeAction?.kind === "subagent-call" || runtimeAction?.kind === "remote-agent-call";+}++function isToolDefinitionList(+ tools: HarnessToolMap | readonly HarnessToolDefinition[],+): tools is readonly HarnessToolDefinition[] {+ return Array.isArray(tools);+}diff --git a/packages/eve/src/harness/subagent-depth.ts b/packages/eve/src/harness/subagent-depth.tsnew file mode 100644index 000000000..30625f799--- /dev/null+++ b/packages/eve/src/harness/subagent-depth.ts@@ -0,0 +1,74 @@+import { SubagentDepthKey, SubagentMaxDepthKey } from "#context/keys.js";+import type { HarnessSession } from "#harness/types.js";+import type {+ RuntimeActionRequest,+ RuntimeRemoteAgentCallActionRequest,+ RuntimeSubagentCallActionRequest,+} from "#runtime/actions/types.js";++export const DEFAULT_SUBAGENT_MAX_DEPTH = 3;++export type DelegatedRuntimeActionRequest =+ | RuntimeRemoteAgentCallActionRequest+ | RuntimeSubagentCallActionRequest;++export type SubagentDelegationLimit = {+ readonly currentDepth: number;+ readonly maxDepth: number;+ readonly nextChildDepth: number;+ readonly reached: boolean;+};++export function resolveSubagentDelegationLimit(+ session: Pick<HarnessSession, "subagentDepth" | "subagentMaxDepth">,+): SubagentDelegationLimit {+ const currentDepth = parseSubagentDepth(session.subagentDepth);+ const maxDepth = parseSubagentMaxDepth(session.subagentMaxDepth) ?? DEFAULT_SUBAGENT_MAX_DEPTH;+ return {+ currentDepth,+ maxDepth,+ nextChildDepth: currentDepth + 1,+ reached: currentDepth >= maxDepth,+ };+}++export function readSerializedSubagentSessionDepth(+ serializedContext: Readonly<Record<string, unknown>>,+): {+ readonly subagentDepth?: number;+ readonly subagentMaxDepth?: number;+} {+ const subagentDepth = parseSubagentDepth(serializedContext[SubagentDepthKey.name]);+ const subagentMaxDepth = parseSubagentMaxDepth(serializedContext[SubagentMaxDepthKey.name]);+ return {+ subagentDepth: subagentDepth === 0 ? undefined : subagentDepth,+ subagentMaxDepth,+ };+}++export function isSubagentDelegationAction(+ action: RuntimeActionRequest,+): action is DelegatedRuntimeActionRequest {+ return action.kind === "subagent-call" || action.kind === "remote-agent-call";+}++export function getSubagentDelegationName(action: DelegatedRuntimeActionRequest): string {+ switch (action.kind) {+ case "remote-agent-call":+ return action.remoteAgentName;+ case "subagent-call":+ return action.subagentName;+ default: {+ const _exhaustive: never = action;+ return _exhaustive;+ }+ }+}++function parseSubagentDepth(value: unknown): number {+ return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : 0;+}++function parseSubagentMaxDepth(value: unknown): number | undefined {+ return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : undefined;+}diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.tsindex 34e9fb671..cd0f5fa47 100644--- a/packages/eve/src/harness/tool-loop.test.ts+++ b/packages/eve/src/harness/tool-loop.test.ts@@ -34,8 +34,10 @@ import {requestAuthorization,} from "#harness/authorization.js";import { hasDeferredStepInput, setPendingInputBatch } from "#harness/input-requests.js";+import { getPendingRuntimeActionBatch } from "#harness/runtime-actions.js";import { stashToolInterrupt } from "#harness/tool-interrupts.js";import { createToolLoopHarness } from "#harness/tool-loop.js";+import { DEFAULT_SUBAGENT_MAX_DEPTH } from "#harness/subagent-depth.js";import type { HarnessEmitFn, HarnessSession, ToolLoopHarnessConfig } from "#harness/types.js";import {CONDITIONAL_DELIVERY_INSTRUCTION,@@ -132,6 +134,33 @@ function createTestConfig(};}+function createDelegationToolMap(): ToolLoopHarnessConfig["tools"] {+ return new Map([+ [+ "add",+ {+ description: "Adds numbers",+ execute: vi.fn().mockResolvedValue("42"),+ inputSchema: jsonSchema({ type: "object" }),+ name: "add",+ },+ ],+ [+ "delegate",+ {+ description: "Delegate to a subagent.",+ inputSchema: jsonSchema({ type: "object" }),+ name: "delegate",+ runtimeAction: {+ kind: "subagent-call",+ nodeId: "workers",+ subagentName: "worker",+ },+ },+ ],+ ]);+}+function createScheduleContext(): ContextContainer {const ctx = new ContextContainer();ctx.set(AuthKey, SCHEDULE_APP_AUTH);@@ -593,6 +622,187 @@ describe("createToolLoopHarness", () => {expect(agentCall!.tools).not.toHaveProperty("Workflow");});+ it("hides subagent tools from the model after the subagent depth limit", async () => {+ setupMockAgent({+ finishReason: "stop",+ response: { messages: [{ content: "Hello!", role: "assistant" }] },+ text: "Hello!",+ toolCalls: [],+ toolResults: [],+ });++ const config = createTestConfig("conversation", undefined, {+ tools: createDelegationToolMap(),+ });+ const runStep = createToolLoopHarness(config);++ await runStep(createTestSession({ subagentDepth: DEFAULT_SUBAGENT_MAX_DEPTH }), {+ message: "Hi",+ });++ const agentCall = vi.mocked(ToolLoopAgent).mock.calls[0]?.[0];+ expect(agentCall).toBeDefined();+ expect(agentCall!.tools).toHaveProperty("add");+ expect(agentCall!.tools).not.toHaveProperty("delegate");+ });++ it("publishes subagent calls from the current run immediately before the depth limit", async () => {+ setupMockAgent({+ finishReason: "tool-calls",+ response: {+ messages: [+ {+ content: [+ {+ input: { message: "delegate at depth 2" },+ toolCallId: "call-1",+ toolName: "delegate",+ type: "tool-call",+ },+ ],+ role: "assistant",+ },+ ],+ },+ text: "",+ toolCalls: [+ {+ input: { message: "delegate at depth 2" },+ toolCallId: "call-1",+ toolName: "delegate",+ type: "tool-call",+ },+ ],+ toolResults: [],+ });++ const { emit, events } = createEventCollector();+ const runStep = createToolLoopHarness(+ createTestConfig("conversation", emit, { tools: createDelegationToolMap() }),+ );++ const result = await runStep(+ createTestSession({ subagentDepth: DEFAULT_SUBAGENT_MAX_DEPTH - 1 }),+ {+ message: "Hi",+ },+ );++ expect(events.find((event) => event.type === "actions.requested")?.data.actions).toEqual([+ {+ callId: "call-1",+ description: "Delegate to a subagent.",+ input: { message: "delegate at depth 2" },+ kind: "subagent-call",+ name: "delegate",+ nodeId: "workers",+ subagentName: "worker",+ },+ ]);+ expect(getPendingRuntimeActionBatch(result.session.state)?.actions).toEqual([+ {+ callId: "call-1",+ description: "Delegate to a subagent.",+ input: { message: "delegate at depth 2" },+ kind: "subagent-call",+ name: "delegate",+ nodeId: "workers",+ subagentName: "worker",+ },+ ]);+ });++ it("does not publish subagent calls from the current run at the depth limit", async () => {+ setupMockAgent({+ finishReason: "tool-calls",+ response: {+ messages: [+ {+ content: [+ {+ input: { message: "delegate at depth 3" },+ toolCallId: "call-1",+ toolName: "delegate",+ type: "tool-call",+ },+ ],+ role: "assistant",+ },+ ],+ },+ text: "",+ toolCalls: [+ {+ input: { message: "delegate at depth 3" },+ toolCallId: "call-1",+ toolName: "delegate",+ type: "tool-call",+ },+ ],+ toolResults: [],+ });+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});++ const { emit, events } = createEventCollector();+ const runStep = createToolLoopHarness(+ createTestConfig("conversation", emit, { tools: createDelegationToolMap() }),+ );++ const result = await runStep(createTestSession({ subagentDepth: DEFAULT_SUBAGENT_MAX_DEPTH }), {+ message: "Hi",+ });++ expect(events.some((event) => event.type === "actions.requested")).toBe(false);+ expect(getPendingRuntimeActionBatch(result.session.state)).toBeUndefined();+ expect(warn).toHaveBeenCalledWith(+ "[eve:harness.tool-loop] runtime action tool call blocked because tool is not advertised",+ expect.objectContaining({+ callId: "call-1",+ sessionId: "test-session",+ toolName: "delegate",+ }),+ );+ });++ it("omits Workflow when subagent host tools are hidden by the depth limit", async () => {+ setupMockAgent({+ finishReason: "stop",+ response: { messages: [{ content: "Hello!", role: "assistant" }] },+ text: "Hello!",+ toolCalls: [],+ toolResults: [],+ });++ const config = createTestConfig("conversation", undefined, {+ workflow: true,+ tools: new Map([+ [+ "delegate",+ {+ description: "Delegate to a subagent.",+ inputSchema: jsonSchema({ type: "object" }),+ name: "delegate",+ runtimeAction: {+ kind: "subagent-call",+ nodeId: "workers",+ subagentName: "worker",+ },+ },+ ],+ ]),+ });+ const runStep = createToolLoopHarness(config);++ await runStep(createTestSession({ subagentDepth: DEFAULT_SUBAGENT_MAX_DEPTH }), {+ message: "Hi",+ });++ const agentCall = vi.mocked(ToolLoopAgent).mock.calls[0]?.[0];+ expect(agentCall).toBeDefined();+ expect(agentCall!.tools).not.toHaveProperty("delegate");+ expect(agentCall!.tools).not.toHaveProperty("Workflow");+ });+it("forwards the agent reasoning effort to the model call", async () => {setupMockAgent({finishReason: "stop",diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.tsindex a93310076..9f6aa37fd 100644--- a/packages/eve/src/harness/tool-loop.ts+++ b/packages/eve/src/harness/tool-loop.ts@@ -124,6 +124,7 @@ import {} from "#shared/empty-delivery.js";import { extractWorkflowStreamWriteErrorDetails } from "#harness/workflow-stream-error.js";import { ensureOtelIntegration } from "#harness/otel-integration.js";+import { getAdvertisedTools } from "#harness/advertised-tools.js";import {applyLastToolCacheBreakpoint,applySystemCacheBreakpoint,@@ -639,17 +640,24 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {const callMessages = opts.trailingUserNote? [...modelMessages, { role: "user" as const, content: opts.trailingUserNote }]: modelMessages;+ const advertisedHarnessTools = getAdvertisedTools({+ session,+ tools: config.tools,+ });const flatTools = await buildToolSetWithProviderTools({approvedTools,capabilities: config.capabilities,disabledProviderTools: opts.disabledProviderTools,modelReference: session.agent.modelReference,- tools: config.tools,+ tools: advertisedHarnessTools,});if (ctx !== undefined) {- const dynamicTools = buildDynamicTools(ctx);+ const dynamicTools = getAdvertisedTools({+ session,+ tools: buildDynamicTools(ctx),+ });const dynamicToolSet = buildToolSetFromDefinitions({approvedTools,capabilities: config.capabilities,@@ -671,13 +679,13 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {? (await applyWorkflowTool({continuationSecurity: getWorkflowContinuationSecurity(session),- harnessTools: config.tools,+ harnessTools: advertisedHarnessTools,lifecycle:emit !== undefined? createWorkflowLifecycle({emit,emissionState,- tools: config.tools,+ tools: advertisedHarnessTools,}): undefined,tools: flatTools,@@ -725,7 +733,17 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {const executeModelCall = async (): Promise<HarnessStepResult> => {if (emit) {- const excludedActionToolNames = new Set([ASK_QUESTION_TOOL_NAME, FINAL_OUTPUT_TOOL_NAME]);+ const hiddenRuntimeActionToolNames = [...config.tools]+ .filter(+ ([name, tool]) =>+ tool.runtimeAction !== undefined && advertisedHarnessTools.get(name) === undefined,+ )+ .map(([name]) => name);+ const excludedActionToolNames = new Set([+ ASK_QUESTION_TOOL_NAME,+ FINAL_OUTPUT_TOOL_NAME,+ ...hiddenRuntimeActionToolNames,+ ]);const streamResult = await agent.stream({ messages: callMessages });const {emittedActionCallIds,@@ -748,7 +766,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {emittedActionCallIds,excludedActionToolNames,handledInlineToolResultCallIds,- tools: config.tools,+ tools: advertisedHarnessTools,});if (inlineToolResultParts.length > 0 || inlineAuthorizationResults.length > 0) {const existingToolResults = stepResult.toolResults as TypedToolResult<ToolSet>[];@@ -1463,13 +1481,28 @@ async function handleStepResult(input: {excludedCallIds: approvalRequestCallIds,});const inputRequests: InputRequest[] = [...approvalRequests, ...questionRequests];+ const advertisedRuntimeActionTools = getAdvertisedTools({+ session: baseSession,+ tools: config.tools,+ });const pendingRuntimeActions = ((result.toolCalls ?? []) as TypedToolCall<ToolSet>[]).filter((toolCall) => !isInvalidToolCall(toolCall)).filter((toolCall) => config.tools.get(toolCall.toolName)?.runtimeAction !== undefined)+ .filter((toolCall) => {+ if (advertisedRuntimeActionTools.get(toolCall.toolName)?.runtimeAction !== undefined) {+ return true;+ }+ log.warn("runtime action tool call blocked because tool is not advertised", {+ callId: toolCall.toolCallId,+ sessionId: baseSession.sessionId,+ toolName: toolCall.toolName,+ });+ return false;+ }).map((toolCall) =>createRuntimeActionRequestFromToolCall({toolCall,- tools: config.tools,+ tools: advertisedRuntimeActionTools,}),);diff --git a/packages/eve/src/harness/types.ts b/packages/eve/src/harness/types.tsindex 4cc81f903..46eee04a7 100644--- a/packages/eve/src/harness/types.ts+++ b/packages/eve/src/harness/types.ts@@ -73,6 +73,17 @@ export interface HarnessSession {readonly sessionId: string;readonly sandboxState?: SandboxState;readonly state?: SessionStateMap;+ /**+ * Number of local delegated subagent hops from the root session to this+ * session. Root sessions are depth 0. Used by the harness to cap recursive+ * subagent delegation.+ */+ readonly subagentDepth?: number;+ /**+ * Maximum delegated child-session depth for this session. When omitted, the+ * harness uses the framework default.+ */+ readonly subagentMaxDepth?: number;}/**diff --git a/packages/eve/src/internal/authored-definition/core.test.ts b/packages/eve/src/internal/authored-definition/core.test.tsindex bb75270e5..1217e6560 100644--- a/packages/eve/src/internal/authored-definition/core.test.ts+++ b/packages/eve/src/internal/authored-definition/core.test.ts@@ -32,6 +32,42 @@ describe("normalizeAgentDefinition", () => {).toThrow(FAILURE_MESSAGE);});+ it("accepts a positive subagent max depth", () => {+ const definition = normalizeAgentDefinition(+ {+ model: "openai/gpt-5.5",+ limits: { maxSubagentDepth: 4 },+ },+ FAILURE_MESSAGE,+ );++ expect(definition.limits).toEqual({ maxSubagentDepth: 4 });+ });++ it.each([0, 1.5, -1, "4"])("rejects invalid subagent max depth %j", (maxSubagentDepth) => {+ expect(() =>+ normalizeAgentDefinition(+ {+ model: "openai/gpt-5.5",+ limits: { maxSubagentDepth },+ },+ FAILURE_MESSAGE,+ ),+ ).toThrow(FAILURE_MESSAGE);+ });++ it("rejects the old subagents maxDepth config", () => {+ expect(() =>+ normalizeAgentDefinition(+ {+ model: "openai/gpt-5.5",+ subagents: { maxDepth: 4 },+ },+ FAILURE_MESSAGE,+ ),+ ).toThrow(FAILURE_MESSAGE);+ });+it("accepts a workflow world package name", () => {const definition = normalizeAgentDefinition({diff --git a/packages/eve/src/internal/authored-definition/core.ts b/packages/eve/src/internal/authored-definition/core.tsindex c4e9990cf..6001ea5da 100644--- a/packages/eve/src/internal/authored-definition/core.ts+++ b/packages/eve/src/internal/authored-definition/core.ts@@ -41,6 +41,7 @@ export function normalizeAgentDefinition("compaction","description","experimental",+ "limits","model","modelContextWindowTokens","modelOptions",@@ -92,6 +93,10 @@ export function normalizeAgentDefinition(definition.reasoning = normalizeAgentReasoningDefinition(record.reasoning, message);}+ if (record.limits !== undefined) {+ definition.limits = normalizeAgentLimitsDefinition(record.limits, message);+ }+return definition as Readonly<NormalizedAgentDefinition>;}@@ -123,6 +128,21 @@ function expectPositiveInteger(value: unknown, message: string): number {return value;}+function normalizeAgentLimitsDefinition(+ value: unknown,+ message: string,+): NonNullable<NormalizedAgentDefinition["limits"]> {+ const record = expectObjectRecord(value, message);+ expectOnlyKnownKeys(record, ["maxSubagentDepth"], message);+ const normalizedDefinition: Mutable<NonNullable<NormalizedAgentDefinition["limits"]>> = {};++ if (record.maxSubagentDepth !== undefined) {+ normalizedDefinition.maxSubagentDepth = expectPositiveInteger(record.maxSubagentDepth, message);+ }++ return normalizedDefinition;+}+function normalizeAgentBuildDefinition(value: unknown,message: string,diff --git a/packages/eve/src/public/definitions/agent.ts b/packages/eve/src/public/definitions/agent.tsindex 49c0b5d1b..eede780c9 100644--- a/packages/eve/src/public/definitions/agent.ts+++ b/packages/eve/src/public/definitions/agent.ts@@ -6,6 +6,7 @@ export type {AgentReasoningDefinition,AgentBuildDefinition,AgentExperimentalDefinition,+ AgentLimitsDefinition,AgentWorkflowDefinition,AgentWorkflowWorldDefinition,PublicAgentModelDefinition as AgentModelDefinition,diff --git a/packages/eve/src/public/definitions/exact.test.ts b/packages/eve/src/public/definitions/exact.test.tsindex 77359ee4e..4577e1b87 100644--- a/packages/eve/src/public/definitions/exact.test.ts+++ b/packages/eve/src/public/definitions/exact.test.ts@@ -16,6 +16,7 @@ describe("definition helper exact inputs", () => {it("preserves literal inference for valid definitions", () => {const agent = defineAgent({description: "type-test",+ limits: { maxSubagentDepth: 4 },model: "anthropic/claude-sonnet-4.6",});@@ -25,6 +26,7 @@ describe("definition helper exact inputs", () => {});expect(agent.description).toBe("type-test");+ expect(agent.limits.maxSubagentDepth).toBe(4);expect(schedule.cron).toBe("0 9 * * *");});});diff --git a/packages/eve/src/public/index.ts b/packages/eve/src/public/index.tsindex d86813242..e32fedae6 100644--- a/packages/eve/src/public/index.ts+++ b/packages/eve/src/public/index.ts@@ -6,6 +6,7 @@ export {type AgentCompactionDefinition,type AgentDefinition,type AgentExperimentalDefinition,+ type AgentLimitsDefinition,type AgentModelDefinition,type AgentModelOptionsDefinition,type AgentReasoningDefinition,diff --git a/packages/eve/src/runtime/resolve-agent.ts b/packages/eve/src/runtime/resolve-agent.tsindex 78477776d..c8491c053 100644--- a/packages/eve/src/runtime/resolve-agent.ts+++ b/packages/eve/src/runtime/resolve-agent.ts@@ -153,6 +153,7 @@ function createResolvedAgentConfig(manifest: CompiledAgentNodeManifest): ResolveoutputSchema?: ResolvedAgent["config"]["outputSchema"];reasoning?: ResolvedAgent["config"]["reasoning"];source?: ResolvedAgent["config"]["source"];+ limits?: ResolvedAgent["config"]["limits"];} = {model:manifest.config.model.source === undefined@@ -230,5 +231,11 @@ function createResolvedAgentConfig(manifest: CompiledAgentNodeManifest): Resolveconfig.source = createResolvedModuleSourceRef(manifest.config.source);}+ if (manifest.config.limits !== undefined) {+ config.limits = {+ maxSubagentDepth: manifest.config.limits.maxSubagentDepth,+ };+ }+return config;}diff --git a/packages/eve/src/shared/agent-definition.ts b/packages/eve/src/shared/agent-definition.tsindex d2a7e4fdb..f1c65c9d4 100644--- a/packages/eve/src/shared/agent-definition.ts+++ b/packages/eve/src/shared/agent-definition.ts@@ -96,6 +96,21 @@ export interface PublicAgentCompactionDefinition {readonly thresholdPercent?: number;}+/**+ * Configures framework-owned runtime limits for this agent's runs.+ */+export interface AgentLimitsDefinition {+ /**+ * Maximum number of delegated child-session levels from the root session.+ *+ * Root sessions are depth 0. A `maxSubagentDepth` of 3 allows child sessions at+ * depths 1, 2, and 3; sessions already at depth 3 cannot delegate again.+ *+ * @default 3+ */+ readonly maxSubagentDepth?: number;+}+/*** Experimental, opt-in agent capabilities authored in `agent.ts`.*@@ -162,6 +177,7 @@ export type InternalAgentDefinition = {outputSchema?: JsonObject;reasoning?: AgentReasoningDefinition;source?: ModuleSourceRef;+ limits?: AgentLimitsDefinition;};/**@@ -205,6 +221,10 @@ export type PublicAgentDefinition = {* Support for individual levels depends on the selected model and provider.*/readonly reasoning?: AgentReasoningDefinition;+ /**+ * Framework-owned runtime limits for this agent's runs.+ */+ readonly limits?: AgentLimitsDefinition;/*** Optional structured return type used when this agent runs in task mode* (for example as a subagent, schedule, or remote job). Interactive