Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): subagent sessions inherit the parent's remaining token quota (#555)

Ruida2ec6c5972b
diff --git a/.changeset/subagent-quota-inheritance.md b/.changeset/subagent-quota-inheritance.md
new file mode 100644
index 000000000..ca29ea89c
--- /dev/null
+++ b/.changeset/subagent-quota-inheritance.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Delegated subagent sessions now receive a share of the parent's remaining token quota at dispatch time — the remainder split across the batch's delegated calls — instead of a fixed 5M input-token cap, and a completed child's usage counts against the parent's quota, so a delegation tree can never outspend the budget configured at its root. Session token limits also accept `false` to uncap a session explicitly. Delegated children likewise inherit the parent's delegation caps (`limits.maxSubagentDepth` and `limits.maxSubagents`); on every inherited axis the tighter of the configured and inherited value wins.
diff --git a/docs/agent-config.md b/docs/agent-config.md
index 386551271..ac79bcb34 100644
--- a/docs/agent-config.md
+++ b/docs/agent-config.md
@@ -96,10 +96,18 @@ either limit is allowed to finish because providers only report exact token
usage after a call completes. Follow-up model calls in the same session fail
with `SESSION_TOKEN_LIMIT_REACHED`.
-When `maxInputTokensPerSession` is omitted, eve applies a default input budget:
-`40_000_000` provider-reported input tokens for root sessions and `5_000_000`
-for delegated subagent sessions. `maxOutputTokensPerSession` is unset unless
-configured.
+When `maxInputTokensPerSession` is omitted, root sessions apply a default
+input budget of `40_000_000` provider-reported input tokens.
+`maxOutputTokensPerSession` is unset unless configured. Setting either limit
+to `false` uncaps that axis — the session never stops on it.
+
+Delegated subagent sessions have no fixed default. Each child receives a
+share of the delegating parent's remaining quota at dispatch time — the
+remainder (limit minus accumulated usage) split evenly across the batch's
+local subagent calls — and a completed child's usage counts against the
+parent's quota, so a delegation tree can never outspend the budget configured
+at its root. An authored child limit applies only when it is tighter than the
+parent's grant; an uncapped parent delegates uncapped children.
## Workflow world
@@ -142,14 +150,14 @@ installed package must stay external in hosted output, list it in
`defineAgent` takes a few more fields, all optional. For the exported types, see the [TypeScript API](./reference/typescript-api).
-| Field | Type | Default | Description |
-| -------------- | --------------------------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `reasoning` | `AgentReasoningDefinition` | provider default | Provider-agnostic reasoning effort forwarded to the agent's turn model calls. |
-| `modelOptions` | `AgentModelOptionsDefinition` | none | Provider option overrides forwarded to the model call. |
-| `limits` | `AgentLimitsDefinition` | field-specific | Framework-owned runtime limits. `maxSubagentDepth` defaults to `3`; `maxInputTokensPerSession` defaults to `40_000_000` for root sessions and `5_000_000` for delegated subagent sessions; `maxOutputTokensPerSession` is unset unless configured. |
-| `experimental` | `{ workflow?: { world?: string } }` | unset | Opt-in settings that can change or disappear in any release. Treat them as unstable. `workflow.world` selects the Workflow world package backing session state, queues, hooks, and streams on the root agent. |
-| `outputSchema` | Standard Schema or a JSON Schema object | none | Structured return type for task-mode runs (a subagent, schedule, or remote job). Interactive conversation turns ignore it unless the client supplies a per-message schema. |
-| `build` | `{ externalDependencies?: string[] }` | none | Hosted-build packaging controls. `externalDependencies` keeps listed packages external while eve compiles authored modules such as tools and channels, and traces those packages into the hosted output. |
+| Field | Type | Default | Description |
+| -------------- | --------------------------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `reasoning` | `AgentReasoningDefinition` | provider default | Provider-agnostic reasoning effort forwarded to the agent's turn model calls. |
+| `modelOptions` | `AgentModelOptionsDefinition` | none | Provider option overrides forwarded to the model call. |
+| `limits` | `AgentLimitsDefinition` | field-specific | Framework-owned runtime limits. `maxSubagentDepth` defaults to `3`; `maxInputTokensPerSession` defaults to `40_000_000` for root sessions, and delegated subagent sessions inherit the parent's remaining quota; `maxOutputTokensPerSession` is unset unless configured; `false` uncaps a session token limit. |
+| `experimental` | `{ workflow?: { world?: string } }` | unset | Opt-in settings that can change or disappear in any release. Treat them as unstable. `workflow.world` selects the Workflow world package backing session state, queues, hooks, and streams on the root agent. |
+| `outputSchema` | Standard Schema or a JSON Schema object | none | Structured return type for task-mode runs (a subagent, schedule, or remote job). Interactive conversation turns ignore it unless the client supplies a per-message schema. |
+| `build` | `{ externalDependencies?: string[] }` | none | Hosted-build packaging controls. `externalDependencies` keeps listed packages external while eve compiles authored modules such as tools and channels, and traces those packages into the hosted output. |
`externalDependencies` is a packaging control only. It keeps selected packages as runtime dependencies in the hosted output; it does not authorize, configure, or review any third-party service those packages may call.
diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.ts
index be60977ba..43f87ac1f 100644
--- a/packages/eve/src/channel/types.ts
+++ b/packages/eve/src/channel/types.ts
@@ -5,6 +5,7 @@ import type { RunMode } from "#shared/run-mode.js";
import type { RuntimeActionResult } from "#runtime/actions/types.js";
import type { InputRequest, InputResponse } from "#runtime/input/types.js";
import type { ChannelAdapter } from "#channel/adapter.js";
+import type { AgentLimitsDefinition } from "#shared/agent-definition.js";
import type { JsonObject } from "#shared/json.js";
export type { ContextAccessor } from "#context/key.js";
@@ -12,6 +13,11 @@ export type { ChannelInstrumentationProjection } from "#channel/instrumentation.
import type { ChannelInstrumentationProjection } from "#channel/instrumentation.js";
+export type RunSessionLimits = Pick<
+ AgentLimitsDefinition,
+ "maxInputTokensPerSession" | "maxOutputTokensPerSession" | "maxSubagentDepth" | "maxSubagents"
+>;
+
// ---------------------------------------------------------------------------
// Lineage
// ---------------------------------------------------------------------------
@@ -272,17 +278,19 @@ export interface RunInput {
};
readonly mode: RunMode;
readonly parent?: SessionParent;
+ /**
+ * Runtime-supplied session limits. Delegated local subagents use this to
+ * carry the parent's remaining quota and delegation caps with the same limit
+ * fields authors configure on agents; `false` means no inherited token cap
+ * for that axis.
+ */
+ readonly limits?: RunSessionLimits;
/**
* 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.test.ts b/packages/eve/src/compiler/manifest.test.ts
index ab76d2446..757edc585 100644
--- a/packages/eve/src/compiler/manifest.test.ts
+++ b/packages/eve/src/compiler/manifest.test.ts
@@ -44,6 +44,28 @@ describe("compiledAgentManifestSchema", () => {
});
});
+ it("preserves uncapped (false) session token limits", () => {
+ const manifest = createCompiledAgentManifest({
+ agentRoot: "/app/agent",
+ appRoot: "/app",
+ config: {
+ limits: {
+ maxInputTokensPerSession: false,
+ maxOutputTokensPerSession: false,
+ },
+ model: { id: "openai/gpt-5.5", routing: classifyModelRouting("openai/gpt-5.5") },
+ name: "app",
+ },
+ });
+
+ const parsed = compiledAgentManifestSchema.parse(manifest);
+
+ expect(parsed.config.limits).toEqual({
+ maxInputTokensPerSession: false,
+ maxOutputTokensPerSession: false,
+ });
+ });
+
it("accepts compiled workflow world configuration", () => {
const manifest = createCompiledAgentManifest({
agentRoot: "/app/agent",
diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.ts
index 317df7ba8..344c88ad7 100644
--- a/packages/eve/src/compiler/manifest.ts
+++ b/packages/eve/src/compiler/manifest.ts
@@ -357,12 +357,14 @@ const compiledAgentCompactionDefinitionSchema: z.ZodType<CompiledAgentCompaction
})
.strict();
+const sessionTokenLimitSchema = z.union([z.number().int().positive(), z.literal(false)]);
+
const compiledAgentLimitsDefinitionSchema = z
.object({
maxSubagentDepth: z.number().int().positive().optional(),
maxSubagents: z.number().int().positive().optional(),
- maxInputTokensPerSession: z.number().int().positive().optional(),
- maxOutputTokensPerSession: z.number().int().positive().optional(),
+ maxInputTokensPerSession: sessionTokenLimitSchema.optional(),
+ maxOutputTokensPerSession: sessionTokenLimitSchema.optional(),
})
.strict();
diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.ts
index 8c46b9bbb..691fc24df 100644
--- a/packages/eve/src/context/keys.ts
+++ b/packages/eve/src/context/keys.ts
@@ -67,7 +67,6 @@ 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}). Set
diff --git a/packages/eve/src/execution/create-session-step.test.ts b/packages/eve/src/execution/create-session-step.test.ts
index c9eb0b090..d71026697 100644
--- a/packages/eve/src/execution/create-session-step.test.ts
+++ b/packages/eve/src/execution/create-session-step.test.ts
@@ -1,10 +1,7 @@
import { describe, expect, it, vi } from "vitest";
import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
-import {
- DEFAULT_ROOT_MAX_INPUT_TOKENS_PER_SESSION,
- DEFAULT_SUBAGENT_MAX_INPUT_TOKENS_PER_SESSION,
-} from "#execution/session.js";
+import { DEFAULT_ROOT_MAX_INPUT_TOKENS_PER_SESSION } from "#execution/session.js";
import { createSessionStep } from "#execution/create-session-step.js";
import type { RuntimeTurnAgent } from "#runtime/agent/bootstrap.js";
@@ -40,7 +37,7 @@ describe("createSessionStep", () => {
);
});
- it("defaults delegated subagent sessions to the subagent input token budget", async () => {
+ it("limits delegated subagent sessions to the inherited token budget", async () => {
vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({
resolvedAgent: {
config: {},
@@ -51,13 +48,96 @@ describe("createSessionStep", () => {
const { state } = await createSessionStep({
compiledArtifactsSource: { kind: "bundled" },
continuationToken: "subagent:test",
+ inheritedLimits: { maxInputTokensPerSession: 3_000_000, maxOutputTokensPerSession: false },
sessionId: "sess-child",
subagentDepth: 1,
});
- expect(state.snapshot?.session.limits?.maxInputTokensPerSession).toBe(
- DEFAULT_SUBAGENT_MAX_INPUT_TOKENS_PER_SESSION,
- );
+ expect(state.snapshot?.session.limits).toEqual({
+ maxInputTokensPerSession: 3_000_000,
+ });
+ });
+
+ it("leaves delegated subagent sessions uncapped with uncapped inherited axes", async () => {
+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({
+ resolvedAgent: {
+ config: {},
+ },
+ turnAgent: TestTurnAgent,
+ } as never);
+
+ const { state } = await createSessionStep({
+ compiledArtifactsSource: { kind: "bundled" },
+ continuationToken: "subagent:test",
+ inheritedLimits: { maxInputTokensPerSession: false, maxOutputTokensPerSession: false },
+ sessionId: "sess-child",
+ subagentDepth: 1,
+ });
+
+ expect(state.snapshot?.session.limits).toEqual({});
+ });
+
+ it("caps configured child token limits at the inherited token budget", async () => {
+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({
+ resolvedAgent: {
+ config: {
+ limits: { maxInputTokensPerSession: 10_000_000 },
+ },
+ },
+ turnAgent: TestTurnAgent,
+ } as never);
+
+ const { state } = await createSessionStep({
+ compiledArtifactsSource: { kind: "bundled" },
+ continuationToken: "subagent:test",
+ inheritedLimits: { maxInputTokensPerSession: 2_000_000, maxOutputTokensPerSession: false },
+ sessionId: "sess-child",
+ subagentDepth: 1,
+ });
+
+ expect(state.snapshot?.session.limits?.maxInputTokensPerSession).toBe(2_000_000);
+ });
+
+ it("keeps tighter configured child token limits under inherited token budget", async () => {
+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({
+ resolvedAgent: {
+ config: {
+ limits: { maxInputTokensPerSession: 1_000_000 },
+ },
+ },
+ turnAgent: TestTurnAgent,
+ } as never);
+
+ const { state } = await createSessionStep({
+ compiledArtifactsSource: { kind: "bundled" },
+ continuationToken: "subagent:test",
+ inheritedLimits: { maxInputTokensPerSession: 2_000_000, maxOutputTokensPerSession: false },
+ sessionId: "sess-child",
+ subagentDepth: 1,
+ });
+
+ expect(state.snapshot?.session.limits?.maxInputTokensPerSession).toBe(1_000_000);
+ });
+
+ it("still applies inherited token budget when configured child limit is false", async () => {
+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({
+ resolvedAgent: {
+ config: {
+ limits: { maxInputTokensPerSession: false },
+ },
+ },
+ turnAgent: TestTurnAgent,
+ } as never);
+
+ const { state } = await createSessionStep({
+ compiledArtifactsSource: { kind: "bundled" },
+ continuationToken: "subagent:test",
+ inheritedLimits: { maxInputTokensPerSession: 500_000, maxOutputTokensPerSession: false },
+ sessionId: "sess-child",
+ subagentDepth: 1,
+ });
+
+ expect(state.snapshot?.session.limits?.maxInputTokensPerSession).toBe(500_000);
});
it("seeds session token limits from resolved agent config", async () => {
@@ -104,7 +184,7 @@ describe("createSessionStep", () => {
expect(state.snapshot?.session.subagentMaxDepth).toBe(4);
});
- it("keeps inherited subagent max depth when one is provided", async () => {
+ it("keeps a tighter configured subagent max depth under the inherited cap", async () => {
vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({
resolvedAgent: {
config: {
@@ -117,10 +197,89 @@ describe("createSessionStep", () => {
const { state } = await createSessionStep({
compiledArtifactsSource: { kind: "bundled" },
continuationToken: "subagent:test",
+ inheritedLimits: { maxSubagentDepth: 4 },
+ sessionId: "sess-child",
+ });
+
+ expect(state.snapshot?.session.subagentMaxDepth).toBe(2);
+ });
+
+ it("caps configured subagent max depth at the inherited cap", async () => {
+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({
+ resolvedAgent: {
+ config: {
+ limits: { maxSubagentDepth: 6 },
+ },
+ },
+ turnAgent: TestTurnAgent,
+ } as never);
+
+ const { state } = await createSessionStep({
+ compiledArtifactsSource: { kind: "bundled" },
+ continuationToken: "subagent:test",
+ inheritedLimits: { maxSubagentDepth: 4 },
sessionId: "sess-child",
- subagentMaxDepth: 4,
});
expect(state.snapshot?.session.subagentMaxDepth).toBe(4);
});
+
+ it("keeps a tighter configured workflow max subagents under the inherited cap", async () => {
+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({
+ resolvedAgent: {
+ config: {
+ limits: { maxSubagents: 5 },
+ },
+ },
+ turnAgent: TestTurnAgent,
+ } as never);
+
+ const { state } = await createSessionStep({
+ compiledArtifactsSource: { kind: "bundled" },
+ continuationToken: "subagent:test",
+ inheritedLimits: { maxSubagents: 12 },
+ sessionId: "sess-child",
+ });
+
+ expect(state.snapshot?.session.workflowMaxSubagents).toBe(5);
+ });
+
+ it("seeds workflow max subagents from resolved agent config", async () => {
+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({
+ resolvedAgent: {
+ config: {
+ limits: { maxSubagents: 12 },
+ },
+ },
+ turnAgent: TestTurnAgent,
+ } as never);
+
+ const { state } = await createSessionStep({
+ compiledArtifactsSource: { kind: "bundled" },
+ continuationToken: "http:test",
+ sessionId: "sess-root",
+ });
+
+ expect(state.snapshot?.session.workflowMaxSubagents).toBe(12);
+ });
+
+ it("caps configured workflow max subagents at the inherited cap", async () => {
+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({
+ resolvedAgent: {
+ config: {
+ limits: { maxSubagents: 12 },
+ },
+ },
+ turnAgent: TestTurnAgent,
+ } as never);
+
+ const { state } = await createSessionStep({
+ compiledArtifactsSource: { kind: "bundled" },
+ continuationToken: "subagent:test",
+ inheritedLimits: { maxSubagents: 5 },
+ sessionId: "sess-child",
+ });
+
+ expect(state.snapshot?.session.workflowMaxSubagents).toBe(5);
+ });
});
diff --git a/packages/eve/src/execution/create-session-step.ts b/packages/eve/src/execution/create-session-step.ts
index de734e219..ecd6a61c2 100644
--- a/packages/eve/src/execution/create-session-step.ts
+++ b/packages/eve/src/execution/create-session-step.ts
@@ -5,6 +5,11 @@ import {
type DurableSessionState,
} from "#execution/durable-session-store.js";
import { createSession } from "#execution/session.js";
+import {
+ resolveInheritedCountLimit,
+ resolveInheritedTokenLimit,
+} from "#execution/run-session-limits.js";
+import type { RunSessionLimits } from "#channel/types.js";
import type { JsonObject } from "#shared/json.js";
/**
@@ -26,12 +31,12 @@ export interface CreateSessionStepResult {
export async function createSessionStep(input: {
readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;
readonly continuationToken: string;
+ readonly inheritedLimits?: RunSessionLimits;
readonly outputSchema?: JsonObject;
readonly nodeId?: string;
readonly rootSessionId?: string;
readonly sessionId: string;
readonly subagentDepth?: number;
- readonly subagentMaxDepth?: number;
}): Promise<CreateSessionStepResult> {
"use step";
@@ -40,22 +45,43 @@ export async function createSessionStep(input: {
nodeId: input.nodeId,
});
+ // Every axis below resolves tighter-wins against the cap inherited from the
+ // delegating parent: a child may narrow what its parent granted, never widen
+ // it. Root runs have no inherited limits, so their configured values apply.
const session = createSession({
compactionOverrides: {
thresholdPercent: bundle.resolvedAgent.config.compaction?.thresholdPercent,
},
continuationToken: input.continuationToken,
limits: {
- maxInputTokensPerSession: bundle.resolvedAgent.config.limits?.maxInputTokensPerSession,
- maxOutputTokensPerSession: bundle.resolvedAgent.config.limits?.maxOutputTokensPerSession,
+ // Inherited token limits are the parent's remaining quota share at
+ // dispatch time; an authored `false` uncaps only when there is nothing
+ // to inherit.
+ maxInputTokensPerSession: resolveInheritedTokenLimit({
+ configured: bundle.resolvedAgent.config.limits?.maxInputTokensPerSession,
+ inherited: input.inheritedLimits?.maxInputTokensPerSession,
+ }),
+ maxOutputTokensPerSession: resolveInheritedTokenLimit({
+ configured: bundle.resolvedAgent.config.limits?.maxOutputTokensPerSession,
+ inherited: input.inheritedLimits?.maxOutputTokensPerSession,
+ }),
},
outputSchema: input.outputSchema,
rootSessionId: input.rootSessionId,
sessionId: input.sessionId,
subagentDepth: input.subagentDepth,
- subagentMaxDepth:
- input.subagentMaxDepth ?? bundle.resolvedAgent.config.limits?.maxSubagentDepth,
+ // Depth is absolute (root = 0), so the tighter cap lets a child stop
+ // delegation earlier in its subtree but never extend past the root's cap.
+ subagentMaxDepth: resolveInheritedCountLimit({
+ configured: bundle.resolvedAgent.config.limits?.maxSubagentDepth,
+ inherited: input.inheritedLimits?.maxSubagentDepth,
+ }),
turnAgent: bundle.turnAgent,
+ // Caps one Workflow invocation's fan-out anywhere in this session.
+ workflowMaxSubagents: resolveInheritedCountLimit({
+ configured: bundle.resolvedAgent.config.limits?.maxSubagents,
+ inherited: input.inheritedLimits?.maxSubagents,
+ }),
});
return { state: createDurableSessionState({ session }) };
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.ts
index 65934014f..2b6a1c546 100644
--- a/packages/eve/src/execution/dispatch-runtime-actions-step.ts
+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.ts
@@ -92,6 +92,11 @@ export async function dispatchRuntimeActionsStep(input: {
const adapterCtx = buildAdapterContext(adapter, ctx);
const delegationLimit = resolveSubagentDelegationLimit(session);
+ // Split the parent's remaining token quota across the batch's local
+ // subagent calls, the children that actually receive an enforced cap.
+ // Remote agents run on their own deployment under their own limits and
+ // do not dilute the local shares.
+ const fanoutSize = batch.actions.filter((action) => action.kind === "subagent-call").length;
let nextSession = session;
const results: RuntimeSubagentResultActionResult[] = [];
@@ -132,6 +137,7 @@ export async function dispatchRuntimeActionsStep(input: {
batchEvent: batch.event,
capabilities,
channelMetadata,
+ fanoutSize,
initiatorAuth,
parentContinuationToken: input.parentContinuationToken,
session,
diff --git a/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts
index ae9ac7fc8..64b744c44 100644
--- a/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts
+++ b/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts
@@ -49,7 +49,7 @@ export async function dispatchWorkflowRuntimeActionsStep(input: {
const plan = planWorkflowSubagentDispatch({
actions,
interrupt: pending.interrupt,
- maxSubagents: bundle.resolvedAgent.config.limits?.maxSubagents,
+ maxSubagents: durableSession.workflowMaxSubagents,
});
const blockedResults = plan.blocked.map((action) => {
diff --git a/packages/eve/src/execution/durable-session-store.ts b/packages/eve/src/execution/durable-session-store.ts
index f605432da..fe41971f6 100644
--- a/packages/eve/src/execution/durable-session-store.ts
+++ b/packages/eve/src/execution/durable-session-store.ts
@@ -87,6 +87,7 @@ export interface DurableSession {
readonly sandboxState?: SandboxState;
readonly subagentDepth?: number;
readonly subagentMaxDepth?: number;
+ readonly workflowMaxSubagents?: number;
readonly agent: {
readonly system: string;
};
diff --git a/packages/eve/src/execution/node-step.ts b/packages/eve/src/execution/node-step.ts
index 7647f70ff..19a06abdb 100644
--- a/packages/eve/src/execution/node-step.ts
+++ b/packages/eve/src/execution/node-step.ts
@@ -64,6 +64,12 @@ export interface CreateExecutionNodeStepInput {
readonly mode: RunMode;
readonly modelResolutionScope: RuntimeModelResolutionScope;
readonly node: ResolvedRuntimeAgentNode;
+ /**
+ * Effective `limits.maxSubagents` cap for Workflow invocations in this run,
+ * materialized on the session at creation (config resolved against any
+ * inherited parent cap).
+ */
+ readonly workflowMaxSubagents?: number;
}
/**
@@ -77,7 +83,7 @@ export function createExecutionNodeStep(input: CreateExecutionNodeStepInput): St
abortSignal: input.abortSignal,
capabilities: input.capabilities,
workflow: input.node.agent.workflowEnabled === true,
- workflowMaxSubagents: input.node.agent.config?.limits?.maxSubagents,
+ workflowMaxSubagents: input.workflowMaxSubagents,
handleEvent: input.handleEvent,
mode: input.mode,
onCompaction: preserveFrameworkStateOnCompaction,
diff --git a/packages/eve/src/execution/run-session-limits.ts b/packages/eve/src/execution/run-session-limits.ts
new file mode 100644
index 000000000..a19b86d7e
--- /dev/null
+++ b/packages/eve/src/execution/run-session-limits.ts
@@ -0,0 +1,41 @@
+import type { AgentLimitsDefinition } from "#shared/agent-definition.js";
+
+type TokenLimit =
+ | AgentLimitsDefinition["maxInputTokensPerSession"]
+ | AgentLimitsDefinition["maxOutputTokensPerSession"];
+
+/**
+ * Resolves an authored token cap against an inherited parent cap. `false`
+ * only means "uncapped" before inheritance; an actual inherited cap still
+ * bounds the child.
+ */
+export function resolveInheritedTokenLimit(input: {
+ readonly configured: TokenLimit | undefined;
+ readonly inherited: TokenLimit | undefined;
+}): TokenLimit | undefined {
+ if (input.inherited === undefined || input.inherited === false) {
+ return input.configured;
+ }
+ if (input.configured === undefined || input.configured === false) {
+ return input.inherited;
+ }
+ return Math.min(input.configured, input.inherited);
+}
+
+/**
+ * Resolves a positive integer limit against an inherited parent cap: the
+ * tighter value wins; absence means the other side applies. Used for the
+ * delegation-count axes (`maxSubagentDepth`, `maxSubagents`).
+ */
+export function resolveInheritedCountLimit(input: {
+ readonly configured?: number;
+ readonly inherited?: number;
+}): number | undefined {
+ if (input.inherited === undefined) {
+ return input.configured;
+ }
+ if (input.configured === undefined) {
+ return input.inherited;
+ }
+ return Math.min(input.configured, input.inherited);
+}
diff --git a/packages/eve/src/execution/runtime-context.test.ts b/packages/eve/src/execution/runtime-context.test.ts
index c9bf8457a..aa9abb88d 100644
--- a/packages/eve/src/execution/runtime-context.test.ts
+++ b/packages/eve/src/execution/runtime-context.test.ts
@@ -7,7 +7,6 @@ import {
type SessionAuthContext,
SessionIdKey,
SessionKey,
- SubagentMaxDepthKey,
} from "#context/keys.js";
import { buildRunContext } from "#execution/runtime-context.js";
@@ -247,20 +246,4 @@ 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.ts
index f63c9dce3..db18fd854 100644
--- a/packages/eve/src/execution/runtime-context.ts
+++ b/packages/eve/src/execution/runtime-context.ts
@@ -12,7 +12,6 @@ import {
ParentSessionKey,
SessionCallbackKey,
SubagentDepthKey,
- SubagentMaxDepthKey,
} from "#context/keys.js";
import { BundleKey, type CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
@@ -63,9 +62,9 @@ export function buildRunContext(input: {
ctx.set(SubagentDepthKey, run.subagentDepth);
}
- if (run.subagentMaxDepth !== undefined) {
- ctx.set(SubagentMaxDepthKey, run.subagentMaxDepth);
- }
+ // `run.limits` deliberately never enters the context: inherited limits ride
+ // the typed workflow-entry payload into `createSessionStep` and live on the
+ // session from then on.
return ctx;
}
diff --git a/packages/eve/src/execution/session.test.ts b/packages/eve/src/execution/session.test.ts
index 72ad7af1c..f4129fcc2 100644
--- a/packages/eve/src/execution/session.test.ts
+++ b/packages/eve/src/execution/session.test.ts
@@ -5,7 +5,6 @@ import {
createCompactionConfig,
createSession,
DEFAULT_ROOT_MAX_INPUT_TOKENS_PER_SESSION,
- DEFAULT_SUBAGENT_MAX_INPUT_TOKENS_PER_SESSION,
hydrateDurableSession,
mintSubagentContinuationToken,
projectToDurableSession,
@@ -215,7 +214,7 @@ describe("createSession", () => {
);
});
- it("defaults delegated subagent sessions to the subagent input token budget", () => {
+ it("leaves delegated subagent sessions uncapped by default", () => {
const session = createSession({
continuationToken: "subagent-token",
sessionId: "sess-child",
@@ -223,12 +222,33 @@ describe("createSession", () => {
turnAgent: createTestTurnAgent(),
});
- expect(session.limits?.maxInputTokensPerSession).toBe(
- DEFAULT_SUBAGENT_MAX_INPUT_TOKENS_PER_SESSION,
- );
+ expect(session.limits).toEqual({});
+ });
+
+ it("uncaps a root session when the authored limit is false", () => {
+ const session = createSession({
+ continuationToken: "root-token",
+ limits: { maxInputTokensPerSession: false },
+ sessionId: "sess-root",
+ turnAgent: createTestTurnAgent(),
+ });
+
+ expect(session.limits).toEqual({});
+ });
+
+ it("uncaps a delegated subagent session when the authored limit is false", () => {
+ const session = createSession({
+ continuationToken: "subagent-token",
+ limits: { maxInputTokensPerSession: false },
+ sessionId: "sess-child",
+ subagentDepth: 1,
+ turnAgent: createTestTurnAgent(),
+ });
+
+ expect(session.limits).toEqual({});
});
- it("applies the root input token budget when hydrating a durable session without a stored limit", () => {
+ it("treats a durable session without stored limits as uncapped on hydration", () => {
const hydrated = hydrateDurableSession({
durable: {
agent: { system: "You are a helpful assistant." },
@@ -239,26 +259,25 @@ describe("createSession", () => {
turnAgent: createTestTurnAgent(),
});
- expect(hydrated.limits?.maxInputTokensPerSession).toBe(
- DEFAULT_ROOT_MAX_INPUT_TOKENS_PER_SESSION,
- );
+ expect(hydrated.limits).toBeUndefined();
});
- it("applies the subagent input token budget when hydrating a durable child without a stored limit", () => {
+ it("rehydrates persisted limits verbatim without re-applying defaults", () => {
const hydrated = hydrateDurableSession({
durable: {
agent: { system: "You are a helpful assistant." },
continuationToken: "subagent-token",
history: [],
+ limits: {},
sessionId: "sess-child",
subagentDepth: 1,
},
turnAgent: createTestTurnAgent(),
});
- expect(hydrated.limits?.maxInputTokensPerSession).toBe(
- DEFAULT_SUBAGENT_MAX_INPUT_TOKENS_PER_SESSION,
- );
+ // An uncapped session (resolved limits `{}`) must stay uncapped across
+ // rehydration instead of picking up the root default again.
+ expect(hydrated.limits).toEqual({});
});
it("persists run outputSchema through durable session projection and hydration", () => {
diff --git a/packages/eve/src/execution/session.ts b/packages/eve/src/execution/session.ts
index 174691d8f..91b800646 100644
--- a/packages/eve/src/execution/session.ts
+++ b/packages/eve/src/execution/session.ts
@@ -7,7 +7,16 @@ const DEFAULT_COMPACTION_RECENT_WINDOW_SIZE = 10;
const DEFAULT_COMPACTION_THRESHOLD_PERCENT = 0.9;
const FALLBACK_COMPACTION_THRESHOLD = 100_000;
export const DEFAULT_ROOT_MAX_INPUT_TOKENS_PER_SESSION = 40_000_000;
-export const DEFAULT_SUBAGENT_MAX_INPUT_TOKENS_PER_SESSION = 5_000_000;
+
+/**
+ * Authored session token limits before resolution. `false` means the author
+ * explicitly uncapped the axis (skipping the root default). Resolution maps
+ * this shape onto the numeric {@link SessionLimits} the harness checks.
+ */
+export interface AuthoredSessionLimits {
+ readonly maxInputTokensPerSession?: number | false;
+ readonly maxOutputTokensPerSession?: number | false;
+}
/**
* Creates the durable compaction configuration used by one harness session.
@@ -55,11 +64,12 @@ export interface CreateSessionInput {
readonly rootSessionId?: string;
readonly sessionId: string;
readonly turnAgent: RuntimeTurnAgent;
- readonly limits?: SessionLimits;
+ readonly limits?: AuthoredSessionLimits;
readonly outputSchema?: HarnessSession["outputSchema"];
readonly skillRoot?: string;
readonly subagentDepth?: number;
readonly subagentMaxDepth?: number;
+ readonly workflowMaxSubagents?: number;
}
/** Creates a fresh {@link HarnessSession} from the current `turnAgent`. */
@@ -102,6 +112,9 @@ export function createSession(input: CreateSessionInput): HarnessSession {
if (input.subagentMaxDepth !== undefined) {
session.subagentMaxDepth = input.subagentMaxDepth;
}
+ if (input.workflowMaxSubagents !== undefined) {
+ session.workflowMaxSubagents = input.workflowMaxSubagents;
+ }
return session;
}
@@ -187,6 +200,7 @@ export function projectToDurableSession(session: HarnessSession): DurableSession
state?: HarnessSession["state"];
subagentDepth?: number;
subagentMaxDepth?: number;
+ workflowMaxSubagents?: number;
} = {
agent: { system: session.agent.system },
continuationToken: session.continuationToken,
@@ -224,6 +238,9 @@ export function projectToDurableSession(session: HarnessSession): DurableSession
if (session.subagentMaxDepth !== undefined) {
durable.subagentMaxDepth = session.subagentMaxDepth;
}
+ if (session.workflowMaxSubagents !== undefined) {
+ durable.workflowMaxSubagents = session.workflowMaxSubagents;
+ }
return durable;
}
@@ -266,7 +283,12 @@ export function hydrateDurableSession(input: {
if (durable.rootSessionId !== undefined) {
session.rootSessionId = durable.rootSessionId;
}
- session.limits = resolveSessionLimits(durable);
+ // Persisted limits are already resolved (defaults, `false`, and any
+ // inherited parent budget applied at creation). Rehydrating verbatim keeps
+ // an uncapped session uncapped instead of re-applying the root default.
+ if (durable.limits !== undefined) {
+ session.limits = durable.limits;
+ }
if (durable.outputSchema !== undefined) {
session.outputSchema = durable.outputSchema;
}
@@ -282,6 +304,9 @@ export function hydrateDurableSession(input: {
if (durable.subagentMaxDepth !== undefined) {
session.subagentMaxDepth = durable.subagentMaxDepth;
}
+ if (durable.workflowMaxSubagents !== undefined) {
+ session.workflowMaxSubagents = durable.workflowMaxSubagents;
+ }
return session;
}
@@ -295,21 +320,35 @@ function createSessionToolDefinitions(turnAgent: RuntimeTurnAgent): SessionToolD
}
function resolveSessionLimits(input: {
- readonly limits?: SessionLimits;
+ readonly limits?: AuthoredSessionLimits;
readonly subagentDepth?: number;
}): SessionLimits {
- const maxInputTokensPerSession =
- input.limits?.maxInputTokensPerSession ??
- (input.subagentDepth !== undefined && input.subagentDepth > 0
- ? DEFAULT_SUBAGENT_MAX_INPUT_TOKENS_PER_SESSION
- : DEFAULT_ROOT_MAX_INPUT_TOKENS_PER_SESSION);
+ const isSubagent = input.subagentDepth !== undefined && input.subagentDepth > 0;
- if (input.limits?.maxOutputTokensPerSession === undefined) {
- return { maxInputTokensPerSession };
+ const maxInputTokensPerSession = resolveSessionTokenLimit({
+ authored: input.limits?.maxInputTokensPerSession,
+ // Subagents have no fixed default: uncapped parents delegate uncapped
+ // children, capped parents delegate their remaining quota (inherited).
+ fallback: isSubagent ? undefined : DEFAULT_ROOT_MAX_INPUT_TOKENS_PER_SESSION,
+ });
+ const maxOutputTokensPerSession = resolveSessionTokenLimit({
+ authored: input.limits?.maxOutputTokensPerSession,
+ fallback: undefined,
+ });
+
+ const limits: { maxInputTokensPerSession?: number; maxOutputTokensPerSession?: number } = {};
+ if (maxInputTokensPerSession !== undefined) {
+ limits.maxInputTokensPerSession = maxInputTokensPerSession;
+ }
+ if (maxOutputTokensPerSession !== undefined) {
+ limits.maxOutputTokensPerSession = maxOutputTokensPerSession;
}
+ return limits;
+}
- return {
- maxInputTokensPerSession,
- maxOutputTokensPerSession: input.limits.maxOutputTokensPerSession,
- };
+function resolveSessionTokenLimit(input: {
+ readonly authored: number | false | undefined;
+ readonly fallback: number | undefined;
+}): number | undefined {
+ return input.authored === false ? undefined : (input.authored ?? input.fallback);
}
diff --git a/packages/eve/src/execution/subagent-tool.test.ts b/packages/eve/src/execution/subagent-tool.test.ts
index d6cc3b0eb..fff6bd97d 100644
--- a/packages/eve/src/execution/subagent-tool.test.ts
+++ b/packages/eve/src/execution/subagent-tool.test.ts
@@ -173,7 +173,28 @@ describe("buildSubagentRunInput", () => {
});
expect(runInput.subagentDepth).toBe(3);
- expect(runInput.subagentMaxDepth).toBe(4);
+ expect(runInput.limits).toMatchObject({ maxSubagentDepth: 4 });
+ });
+
+ it("threads inherited limits through the child run input", () => {
+ const { runInput } = buildRuntimeSubagentRunInput({
+ action: makeAction(),
+ auth: null,
+ batchEvent: { sequence: 0, turnId: "turn-0" },
+ initiatorAuth: null,
+ session: {
+ ...makeSession(),
+ subagentMaxDepth: 4,
+ workflowMaxSubagents: 7,
+ },
+ });
+
+ expect(runInput.limits).toEqual({
+ maxInputTokensPerSession: false,
+ maxOutputTokensPerSession: false,
+ maxSubagentDepth: 4,
+ maxSubagents: 7,
+ });
});
it("threads outputSchema from action input to RunInput", () => {
diff --git a/packages/eve/src/execution/subagent-tool.ts b/packages/eve/src/execution/subagent-tool.ts
index 7b5f41d5e..083fed779 100644
--- a/packages/eve/src/execution/subagent-tool.ts
+++ b/packages/eve/src/execution/subagent-tool.ts
@@ -3,6 +3,7 @@ import { formatSubagentInput } from "#execution/subagent-invocation.js";
import type {
ChannelInstrumentationProjection,
RunInput,
+ RunSessionLimits,
SessionAuthContext,
SessionCapabilities,
} from "#channel/types.js";
@@ -11,6 +12,7 @@ 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";
+import { resolveRemainingSessionTokenLimits } from "#harness/subagent-token-budget.js";
/**
* Pending runtime-action batch event metadata needed for child run lineage.
@@ -55,6 +57,13 @@ export function buildSubagentRunInput(input: {
*/
readonly capabilities?: SessionCapabilities;
readonly channelMetadata?: ChannelInstrumentationProjection;
+ /**
+ * Number of local subagent calls dispatched in this batch. The parent's
+ * remaining token quota is split evenly across them so parallel children
+ * are collectively, not individually, bounded by it. Remote agents run
+ * under their own deployment's limits and are not counted.
+ */
+ readonly fanoutSize?: number;
readonly initiatorAuth: SessionAuthContext | null;
/** Hook token owned by the workflow currently waiting for this child. */
readonly parentContinuationToken?: string;
@@ -85,8 +94,19 @@ export function buildSubagentRunInput(input: {
// children.
const rootSessionId = session.rootSessionId ?? session.sessionId;
const delegationLimit = resolveSubagentDelegationLimit(session);
+ const inheritedLimits: {
+ -readonly [K in keyof RunSessionLimits]: RunSessionLimits[K];
+ } = resolveRemainingSessionTokenLimits(session, input.fanoutSize);
+ if (session.subagentMaxDepth !== undefined) {
+ inheritedLimits.maxSubagentDepth = session.subagentMaxDepth;
+ }
+ if (session.workflowMaxSubagents !== undefined) {
+ inheritedLimits.maxSubagents = session.workflowMaxSubagents;
+ }
- const runInput: RunInput = {
+ const runInput: {
+ -readonly [K in keyof RunInput]: RunInput[K];
+ } = {
adapter: {
kind: SUBAGENT_ADAPTER_KIND,
state: {
@@ -108,6 +128,7 @@ export function buildSubagentRunInput(input: {
message: formatSubagentCallInputMessage({ action, source }),
outputSchema: action.input.outputSchema as JsonObject | undefined,
},
+ limits: inheritedLimits,
mode: "task",
parent: {
callId: action.callId,
@@ -119,7 +140,6 @@ export function buildSubagentRunInput(input: {
},
},
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.ts
index 9f8e7cb78..25fbe2518 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, SubagentDepthKey, SubagentMaxDepthKey } from "#context/keys.js";
+import { ChannelRequestIdKey, SubagentDepthKey } 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";
@@ -238,16 +238,16 @@ describe("workflowEntry", () => {
await workflowEntry({
input: { message: "hello there" },
+ limits: { maxSubagentDepth: 4 },
serializedContext: createSerializedContext({
[SubagentDepthKey.name]: 3,
- [SubagentMaxDepthKey.name]: 4,
}),
});
expect(createSessionStep).toHaveBeenCalledWith(
expect.objectContaining({
+ inheritedLimits: { maxSubagentDepth: 4 },
subagentDepth: 3,
- subagentMaxDepth: 4,
}),
);
});
diff --git a/packages/eve/src/execution/workflow-entry.ts b/packages/eve/src/execution/workflow-entry.ts
index 9d2ab9ee9..7b10b55e6 100644
--- a/packages/eve/src/execution/workflow-entry.ts
+++ b/packages/eve/src/execution/workflow-entry.ts
@@ -29,7 +29,7 @@ import {
createSessionDeliveryHook,
type SessionDeliveryHook,
} from "#execution/session-delivery-hook.js";
-import { readSerializedSubagentSessionDepth } from "#harness/subagent-depth.js";
+import { readSerializedSubagentDepth } 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.
@@ -42,6 +42,7 @@ import { readSerializedSubagentSessionDepth } from "#harness/subagent-depth.js";
*/
export interface WorkflowEntryInput {
readonly input: RunInput["input"];
+ readonly limits?: RunInput["limits"];
readonly serializedContext: Record<string, unknown>;
}
@@ -87,19 +88,17 @@ 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 subagentDepth = readSerializedSubagentDepth(input.serializedContext);
const { state: sessionState } = await createSessionStep({
compiledArtifactsSource: serializedBundle.source,
continuationToken,
+ inheritedLimits: input.limits,
nodeId: serializedBundle.nodeId,
outputSchema: input.input.outputSchema,
rootSessionId: rootSessionIdFromParent,
sessionId,
subagentDepth,
- subagentMaxDepth,
});
return await runDriverLoop({
diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.ts
index 10d1f3c16..f32f6ddbe 100644
--- a/packages/eve/src/execution/workflow-runtime.ts
+++ b/packages/eve/src/execution/workflow-runtime.ts
@@ -124,6 +124,7 @@ export function createWorkflowRuntime(config: {
[
{
input: input.input,
+ limits: input.limits,
serializedContext,
},
],
diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.ts
index c57832e03..36e53a53a 100644
--- a/packages/eve/src/execution/workflow-steps.test.ts
+++ b/packages/eve/src/execution/workflow-steps.test.ts
@@ -368,6 +368,10 @@ describe("dispatchRuntimeActionsStep", () => {
input: {
message: expect.stringContaining("Description: Local delegate child description."),
},
+ limits: {
+ maxInputTokensPerSession: false,
+ maxOutputTokensPerSession: false,
+ },
serializedContext: expect.objectContaining({
"eve.channel": expect.objectContaining({
kind: "subagent",
diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.ts
index 2eafd2b46..a3e2801a7 100644
--- a/packages/eve/src/execution/workflow-steps.ts
+++ b/packages/eve/src/execution/workflow-steps.ts
@@ -340,6 +340,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
nodeId: bundle.nodeId,
},
node: bundle.graph.root,
+ workflowMaxSubagents: refreshedSession.workflowMaxSubagents,
});
return step(refreshedSession, stepInput);
};
diff --git a/packages/eve/src/harness/runtime-actions.test.ts b/packages/eve/src/harness/runtime-actions.test.ts
new file mode 100644
index 000000000..ae8229a53
--- /dev/null
+++ b/packages/eve/src/harness/runtime-actions.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ resolvePendingRuntimeActions,
+ setPendingRuntimeActionBatch,
+} from "#harness/runtime-actions.js";
+import { getSessionTokenUsage, setTurnUsageState } from "#harness/turn-tag-state.js";
+import type { HarnessSession } from "#harness/types.js";
+
+function createParkedSession(): HarnessSession {
+ const base: HarnessSession = {
+ agent: { modelReference: { id: "test-model" }, system: "", tools: [] },
+ compaction: { recentWindowSize: 10, threshold: 100_000 },
+ continuationToken: "http:test-session",
+ history: [{ content: "delegate this", role: "user" }],
+ sessionId: "test-session",
+ };
+
+ const ownUsage = {
+ cacheReadTokens: 0,
+ cacheWriteTokens: 0,
+ costUsd: 0,
+ inputTokens: 1_000,
+ outputTokens: 100,
+ sawCost: false,
+ };
+ const withUsage = setTurnUsageState(base, {
+ ...ownUsage,
+ session: ownUsage,
+ turnId: "turn_0",
+ });
+
+ return setPendingRuntimeActionBatch({
+ actions: [
+ {
+ callId: "call-1",
+ description: "research subagent",
+ input: { message: "go" },
+ kind: "subagent-call",
+ name: "researcher",
+ nodeId: "subagents/researcher",
+ subagentName: "researcher",
+ },
+ ],
+ event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
+ responseMessages: [],
+ session: withUsage,
+ });
+}
+
+describe("resolvePendingRuntimeActions", () => {
+ it("draws completed child usage down against the parent's session totals", async () => {
+ const session = createParkedSession();
+
+ const resolved = await resolvePendingRuntimeActions({
+ session,
+ stepInput: {
+ runtimeActionResults: [
+ {
+ callId: "call-1",
+ kind: "subagent-result",
+ output: "done",
+ subagentName: "researcher",
+ usage: {
+ cacheReadTokens: 10,
+ cacheWriteTokens: 5,
+ inputTokens: 4_000,
+ outputTokens: 400,
+ },
+ },
+ ],
+ },
+ });
+
+ expect(resolved.outcome).toBe("resolved");
+ expect(getSessionTokenUsage(resolved.session)).toMatchObject({
+ inputTokens: 5_000,
+ outputTokens: 500,
+ });
+ });
+
+ it("leaves the parent's totals untouched when the child reports no usage", async () => {
+ const session = createParkedSession();
+
+ const resolved = await resolvePendingRuntimeActions({
+ session,
+ stepInput: {
+ runtimeActionResults: [
+ {
+ callId: "call-1",
+ kind: "subagent-result",
+ output: "done",
+ subagentName: "researcher",
+ },
+ ],
+ },
+ });
+
+ expect(resolved.outcome).toBe("resolved");
+ expect(getSessionTokenUsage(resolved.session)).toMatchObject({
+ inputTokens: 1_000,
+ outputTokens: 100,
+ });
+ });
+});
diff --git a/packages/eve/src/harness/runtime-actions.ts b/packages/eve/src/harness/runtime-actions.ts
index c43d13df4..90cefd100 100644
--- a/packages/eve/src/harness/runtime-actions.ts
+++ b/packages/eve/src/harness/runtime-actions.ts
@@ -5,6 +5,11 @@ import { getRuntimeActionRequestKey, getRuntimeActionResultKey } from "#runtime/
import type { RuntimeActionRequest, RuntimeActionResult } from "#runtime/actions/types.js";
import { parseJsonObject, type JsonObject } from "#shared/json.js";
import { clearProxyInputRequestsForChild } from "#harness/proxy-input-requests.js";
+import {
+ accumulateSessionUsage,
+ getTurnUsageState,
+ setTurnUsageState,
+} from "#harness/turn-tag-state.js";
import type {
HarnessEmitFn,
HarnessSession,
@@ -286,6 +291,22 @@ export async function resolvePendingRuntimeActions(input: {
}
}
+ // Draw completed child spend down against the parent's session totals so
+ // the session token limits and the remaining-quota budget granted to later
+ // delegations account for what the tree has already spent.
+ for (const result of readyResults) {
+ if (result.kind !== "subagent-result" || result.usage === undefined) {
+ continue;
+ }
+ nextSession = setTurnUsageState(
+ nextSession,
+ accumulateSessionUsage({
+ previous: getTurnUsageState(nextSession.state),
+ usage: result.usage,
+ }),
+ );
+ }
+
const toolResults = readyResults.map((result) => {
switch (result.kind) {
case "load-skill-result":
diff --git a/packages/eve/src/harness/subagent-depth.ts b/packages/eve/src/harness/subagent-depth.ts
index 30625f799..c5d556e57 100644
--- a/packages/eve/src/harness/subagent-depth.ts
+++ b/packages/eve/src/harness/subagent-depth.ts
@@ -1,4 +1,4 @@
-import { SubagentDepthKey, SubagentMaxDepthKey } from "#context/keys.js";
+import { SubagentDepthKey } from "#context/keys.js";
import type { HarnessSession } from "#harness/types.js";
import type {
RuntimeActionRequest,
@@ -32,18 +32,11 @@ export function resolveSubagentDelegationLimit(
};
}
-export function readSerializedSubagentSessionDepth(
+export function readSerializedSubagentDepth(
serializedContext: Readonly<Record<string, unknown>>,
-): {
- readonly subagentDepth?: number;
- readonly subagentMaxDepth?: number;
-} {
+): number | undefined {
const subagentDepth = parseSubagentDepth(serializedContext[SubagentDepthKey.name]);
- const subagentMaxDepth = parseSubagentMaxDepth(serializedContext[SubagentMaxDepthKey.name]);
- return {
- subagentDepth: subagentDepth === 0 ? undefined : subagentDepth,
- subagentMaxDepth,
- };
+ return subagentDepth === 0 ? undefined : subagentDepth;
}
export function isSubagentDelegationAction(
diff --git a/packages/eve/src/harness/subagent-token-budget.test.ts b/packages/eve/src/harness/subagent-token-budget.test.ts
new file mode 100644
index 000000000..8a3a5eb9a
--- /dev/null
+++ b/packages/eve/src/harness/subagent-token-budget.test.ts
@@ -0,0 +1,137 @@
+import { describe, expect, it } from "vitest";
+
+import { resolveRemainingSessionTokenLimits } from "#harness/subagent-token-budget.js";
+import { setTurnUsageState } from "#harness/turn-tag-state.js";
+import type { HarnessSession, SessionLimits } from "#harness/types.js";
+
+function createSessionWithUsage(input: {
+ readonly limits?: SessionLimits;
+ readonly usedInputTokens?: number;
+ readonly usedOutputTokens?: number;
+}): HarnessSession {
+ const base: {
+ -readonly [K in keyof HarnessSession]: HarnessSession[K];
+ } = {
+ agent: { modelReference: { id: "test-model" }, system: "", tools: [] },
+ compaction: { recentWindowSize: 10, threshold: 100_000 },
+ continuationToken: "http:test-session",
+ history: [],
+ sessionId: "test-session",
+ };
+ if (input.limits !== undefined) {
+ base.limits = input.limits;
+ }
+
+ if (input.usedInputTokens === undefined && input.usedOutputTokens === undefined) {
+ return base;
+ }
+
+ const usage = {
+ cacheReadTokens: 0,
+ cacheWriteTokens: 0,
+ costUsd: 0,
+ inputTokens: input.usedInputTokens ?? 0,
+ outputTokens: input.usedOutputTokens ?? 0,
+ sawCost: false,
+ };
+ return setTurnUsageState(base, { ...usage, session: usage, turnId: "turn_0" });
+}
+
+describe("resolveRemainingSessionTokenLimits", () => {
+ it("returns false axes for an uncapped session", () => {
+ expect(resolveRemainingSessionTokenLimits(createSessionWithUsage({}))).toEqual({
+ maxInputTokensPerSession: false,
+ maxOutputTokensPerSession: false,
+ });
+ });
+
+ it("returns the configured limits minus accumulated usage", () => {
+ const session = createSessionWithUsage({
+ limits: { maxInputTokensPerSession: 1_000_000, maxOutputTokensPerSession: 50_000 },
+ usedInputTokens: 300_000,
+ usedOutputTokens: 20_000,
+ });
+
+ expect(resolveRemainingSessionTokenLimits(session)).toEqual({
+ maxInputTokensPerSession: 700_000,
+ maxOutputTokensPerSession: 30_000,
+ });
+ });
+
+ it("returns the full limit when the session has no usage yet", () => {
+ const session = createSessionWithUsage({
+ limits: { maxInputTokensPerSession: 1_000_000 },
+ });
+
+ expect(resolveRemainingSessionTokenLimits(session)).toEqual({
+ maxInputTokensPerSession: 1_000_000,
+ maxOutputTokensPerSession: false,
+ });
+ });
+
+ it("clamps an overspent axis to zero", () => {
+ const session = createSessionWithUsage({
+ limits: { maxInputTokensPerSession: 100_000 },
+ usedInputTokens: 150_000,
+ });
+
+ expect(resolveRemainingSessionTokenLimits(session)).toEqual({
+ maxInputTokensPerSession: 0,
+ maxOutputTokensPerSession: false,
+ });
+ });
+
+ it("splits the remaining quota across the batch's delegated calls", () => {
+ const session = createSessionWithUsage({
+ limits: { maxInputTokensPerSession: 1_000_000, maxOutputTokensPerSession: 50_000 },
+ usedInputTokens: 100_000,
+ usedOutputTokens: 20_000,
+ });
+
+ expect(resolveRemainingSessionTokenLimits(session, 3)).toEqual({
+ maxInputTokensPerSession: 300_000,
+ maxOutputTokensPerSession: 10_000,
+ });
+ });
+
+ it("floors uneven splits so a batch can never exceed the remainder", () => {
+ const session = createSessionWithUsage({
+ limits: { maxInputTokensPerSession: 100 },
+ });
+
+ expect(resolveRemainingSessionTokenLimits(session, 3)).toEqual({
+ maxInputTokensPerSession: 33,
+ maxOutputTokensPerSession: false,
+ });
+ });
+
+ it("treats a non-positive fan-out as a single delegation", () => {
+ const session = createSessionWithUsage({
+ limits: { maxInputTokensPerSession: 100 },
+ });
+
+ expect(resolveRemainingSessionTokenLimits(session, 0)).toEqual({
+ maxInputTokensPerSession: 100,
+ maxOutputTokensPerSession: false,
+ });
+ });
+
+ it("keeps uncapped parents uncapped regardless of fan-out", () => {
+ expect(resolveRemainingSessionTokenLimits(createSessionWithUsage({}), 5)).toEqual({
+ maxInputTokensPerSession: false,
+ maxOutputTokensPerSession: false,
+ });
+ });
+
+ it("marks uncapped axes as false", () => {
+ const session = createSessionWithUsage({
+ limits: { maxOutputTokensPerSession: 50_000 },
+ usedOutputTokens: 10_000,
+ });
+
+ expect(resolveRemainingSessionTokenLimits(session)).toEqual({
+ maxInputTokensPerSession: false,
+ maxOutputTokensPerSession: 40_000,
+ });
+ });
+});
diff --git a/packages/eve/src/harness/subagent-token-budget.ts b/packages/eve/src/harness/subagent-token-budget.ts
new file mode 100644
index 000000000..9f1c87030
--- /dev/null
+++ b/packages/eve/src/harness/subagent-token-budget.ts
@@ -0,0 +1,46 @@
+import type { RunSessionLimits } from "#channel/types.js";
+import { getSessionTokenUsage } from "#harness/turn-tag-state.js";
+import type { HarnessSession } from "#harness/types.js";
+
+/**
+ * Computes the session token limits a delegated child inherits from its parent:
+ * the remaining quota (configured limit minus accumulated usage) split evenly
+ * across the batch's delegated calls, per axis, at dispatch time. `false`
+ * marks an axis with no inherited cap.
+ *
+ * Splitting by `fanoutSize` makes one dispatch batch collectively
+ * bounded by the parent's remainder. N parallel children cannot each spend
+ * the full remainder. Sequential batches see the quota net of completed
+ * children because their usage folds back into the parent's session totals.
+ */
+export function resolveRemainingSessionTokenLimits(
+ session: Pick<HarnessSession, "limits" | "state">,
+ fanoutSize = 1,
+): RunSessionLimits {
+ const normalizedFanoutSize = Math.max(1, Math.floor(fanoutSize));
+ const usage = getSessionTokenUsage(session);
+ const maxInputTokensPerSession = grantShare(
+ remainingQuota(session.limits?.maxInputTokensPerSession, usage.inputTokens),
+ normalizedFanoutSize,
+ );
+ const maxOutputTokensPerSession = grantShare(
+ remainingQuota(session.limits?.maxOutputTokensPerSession, usage.outputTokens),
+ normalizedFanoutSize,
+ );
+
+ return { maxInputTokensPerSession, maxOutputTokensPerSession };
+}
+
+function remainingQuota(limit: number | undefined, used: number): number | false {
+ if (limit === undefined) {
+ return false;
+ }
+ return Math.max(0, limit - used);
+}
+
+function grantShare(remaining: number | false, fanOut: number): number | false {
+ if (remaining === false) {
+ return false;
+ }
+ return Math.floor(remaining / fanOut);
+}
diff --git a/packages/eve/src/harness/turn-tag-state.test.ts b/packages/eve/src/harness/turn-tag-state.test.ts
index f4368d470..0a072c779 100644
--- a/packages/eve/src/harness/turn-tag-state.test.ts
+++ b/packages/eve/src/harness/turn-tag-state.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import {
+ accumulateSessionUsage,
accumulateTurnUsage,
getSessionTokenLimitViolation,
getSessionTokenUsage,
@@ -323,3 +324,40 @@ describe("session token limits", () => {
);
});
});
+
+describe("accumulateSessionUsage", () => {
+ it("folds a child's totals into the session without touching turn totals", () => {
+ const previous = accumulateTurnUsage({
+ previous: undefined,
+ turnId: "turn_1",
+ usage: { inputTokens: 100, outputTokens: 10 },
+ });
+
+ const next = accumulateSessionUsage({
+ previous,
+ usage: { cacheReadTokens: 5, cacheWriteTokens: 2, inputTokens: 400, outputTokens: 40 },
+ });
+
+ // Turn-scoped totals unchanged: the child's spend is not this turn's
+ // own model-call spend.
+ expect(next.turnId).toBe("turn_1");
+ expect(next.inputTokens).toBe(100);
+ expect(next.outputTokens).toBe(10);
+ expect(next.session).toMatchObject({
+ cacheReadTokens: 5,
+ cacheWriteTokens: 2,
+ inputTokens: 500,
+ outputTokens: 50,
+ });
+ });
+
+ it("starts from zero when no usage state exists yet", () => {
+ const next = accumulateSessionUsage({
+ previous: undefined,
+ usage: { inputTokens: 400, outputTokens: 40 },
+ });
+
+ expect(next.inputTokens).toBe(0);
+ expect(next.session).toMatchObject({ inputTokens: 400, outputTokens: 40 });
+ });
+});
diff --git a/packages/eve/src/harness/turn-tag-state.ts b/packages/eve/src/harness/turn-tag-state.ts
index c9a143c8f..14f2f8a04 100644
--- a/packages/eve/src/harness/turn-tag-state.ts
+++ b/packages/eve/src/harness/turn-tag-state.ts
@@ -149,6 +149,30 @@ export function accumulateTurnUsage(input: {
};
}
+/**
+ * Folds a delegated child session's reported totals into the parent's
+ * session totals without touching the in-flight turn totals. Turn tags
+ * attribute only the parent's own model calls (child spend is attributed by
+ * the caller-side `invoke_agent` span); session totals feed the session
+ * token limits and the remaining-quota budget granted to later delegations.
+ */
+export function accumulateSessionUsage(input: {
+ readonly previous: TurnUsageState | undefined;
+ readonly usage: TokenUsageDelta;
+}): TurnUsageState {
+ const delta = toTokenUsageDelta(input.usage);
+ const base = input.previous ?? {
+ ...ZERO_TOKEN_USAGE,
+ session: ZERO_TOKEN_USAGE,
+ turnId: "",
+ };
+
+ return {
+ ...base,
+ session: addTokenUsage(base.session, delta),
+ };
+}
+
function addTokenUsage(base: TokenUsageTotals, delta: TokenUsageTotals): TokenUsageTotals {
return {
cacheReadTokens: base.cacheReadTokens + delta.cacheReadTokens,
diff --git a/packages/eve/src/harness/types.ts b/packages/eve/src/harness/types.ts
index 2f455d6f5..1ee6d4e9d 100644
--- a/packages/eve/src/harness/types.ts
+++ b/packages/eve/src/harness/types.ts
@@ -85,6 +85,13 @@ export interface HarnessSession {
* harness uses the framework default.
*/
readonly subagentMaxDepth?: number;
+ /**
+ * Effective maximum subagent calls one `Workflow` invocation may dispatch
+ * for this session. Resolved at session creation as the tighter of the
+ * agent's `limits.maxSubagents` and any cap inherited from the parent run.
+ * When omitted, the dispatch step applies the framework default.
+ */
+ readonly workflowMaxSubagents?: number;
}
/**
@@ -92,9 +99,11 @@ export interface HarnessSession {
*/
export interface SessionLimits {
/**
- * Maximum provider-reported input tokens this durable session may spend before
- * eve refuses to start another model call. Defaults to 40M for root sessions
- * and 5M for delegated subagent sessions.
+ * Maximum provider-reported input tokens this durable session may spend
+ * before eve refuses to start another model call. Absent when the session
+ * is uncapped. Root sessions default to 40M unless authored otherwise;
+ * delegated subagent sessions receive the parent's remaining quota at
+ * dispatch time.
*/
readonly maxInputTokensPerSession?: number;
/**
diff --git a/packages/eve/src/internal/authored-definition/core.test.ts b/packages/eve/src/internal/authored-definition/core.test.ts
index 4103989c4..2054b1cb2 100644
--- a/packages/eve/src/internal/authored-definition/core.test.ts
+++ b/packages/eve/src/internal/authored-definition/core.test.ts
@@ -54,6 +54,36 @@ describe("normalizeAgentDefinition", () => {
});
});
+ it("accepts false to uncap session token limits", () => {
+ const definition = normalizeAgentDefinition(
+ {
+ model: "openai/gpt-5.5",
+ limits: {
+ maxInputTokensPerSession: false,
+ maxOutputTokensPerSession: false,
+ },
+ },
+ FAILURE_MESSAGE,
+ );
+
+ expect(definition.limits).toEqual({
+ maxInputTokensPerSession: false,
+ maxOutputTokensPerSession: false,
+ });
+ });
+
+ it("rejects false for subagent max depth", () => {
+ expect(() =>
+ normalizeAgentDefinition(
+ {
+ model: "openai/gpt-5.5",
+ limits: { maxSubagentDepth: false },
+ },
+ FAILURE_MESSAGE,
+ ),
+ ).toThrow(FAILURE_MESSAGE);
+ });
+
it.each([0, 1.5, -1, "4"])("rejects invalid subagent max depth %j", (maxSubagentDepth) => {
expect(() =>
normalizeAgentDefinition(
diff --git a/packages/eve/src/internal/authored-definition/core.ts b/packages/eve/src/internal/authored-definition/core.ts
index a325d1773..0739a4789 100644
--- a/packages/eve/src/internal/authored-definition/core.ts
+++ b/packages/eve/src/internal/authored-definition/core.ts
@@ -128,6 +128,15 @@ function expectPositiveInteger(value: unknown, message: string): number {
return value;
}
+/** `false` means "explicitly uncapped" for session token limits. */
+function expectPositiveIntegerOrFalse(value: unknown, message: string): number | false {
+ if (value === false) {
+ return false;
+ }
+
+ return expectPositiveInteger(value, message);
+}
+
function normalizeAgentLimitsDefinition(
value: unknown,
message: string,
@@ -141,13 +150,13 @@ function normalizeAgentLimitsDefinition(
const normalizedDefinition: Mutable<NonNullable<NormalizedAgentDefinition["limits"]>> = {};
if (record.maxInputTokensPerSession !== undefined) {
- normalizedDefinition.maxInputTokensPerSession = expectPositiveInteger(
+ normalizedDefinition.maxInputTokensPerSession = expectPositiveIntegerOrFalse(
record.maxInputTokensPerSession,
message,
);
}
if (record.maxOutputTokensPerSession !== undefined) {
- normalizedDefinition.maxOutputTokensPerSession = expectPositiveInteger(
+ normalizedDefinition.maxOutputTokensPerSession = expectPositiveIntegerOrFalse(
record.maxOutputTokensPerSession,
message,
);
diff --git a/packages/eve/src/shared/agent-definition.ts b/packages/eve/src/shared/agent-definition.ts
index 0c426379e..294cbc0cd 100644
--- a/packages/eve/src/shared/agent-definition.ts
+++ b/packages/eve/src/shared/agent-definition.ts
@@ -106,6 +106,9 @@ export interface AgentLimitsDefinition {
* 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.
*
+ * Delegated subagent sessions resolve this against the cap inherited from
+ * the delegating parent; the tighter value wins.
+ *
* @default 3
*/
readonly maxSubagentDepth?: number;
@@ -119,6 +122,9 @@ export interface AgentLimitsDefinition {
* parallel calls alike). Calls beyond the limit fail with an error result
* instead of starting a child session.
*
+ * Delegated subagent sessions resolve this against the cap inherited from
+ * the delegating parent; the tighter value wins.
+ *
* @default 100
*/
readonly maxSubagents?: number;
@@ -129,17 +135,26 @@ export interface AgentLimitsDefinition {
* the limit is allowed to finish because providers only report exact usage
* after the call completes; later model calls in the same session are blocked.
*
- * @default 40_000_000 for root sessions; 5_000_000 for delegated subagent sessions
+ * `false` disables the limit: the session is uncapped.
+ *
+ * Delegated subagent sessions default to the delegating parent's remaining
+ * quota at dispatch time, and the parent's remaining quota always caps an
+ * authored child limit — a child can never outspend its parent's budget.
+ *
+ * @default 40_000_000 for root sessions; the parent's remaining quota for delegated subagent sessions
*/
- readonly maxInputTokensPerSession?: number;
+ readonly maxInputTokensPerSession?: number | false;
/**
* Maximum provider-reported output tokens accumulated by one durable session.
*
* eve checks this before starting each model call. The model call that crosses
* the limit is allowed to finish because providers only report exact usage
* after the call completes; later model calls in the same session are blocked.
+ *
+ * `false` disables the limit. Unset by default; delegated subagent sessions
+ * inherit the parent's remaining output quota when the parent has one.
*/
- readonly maxOutputTokensPerSession?: number;
+ readonly maxOutputTokensPerSession?: number | false;
}
/**