The Open Framework for Building Agents
feat(eve)!: replace numeric session limits with a limits.sessionUsage function (#5028)
Ruic543585422ca
diff --git a/.changeset/session-usage-limit-function.md b/.changeset/session-usage-limit-function.mdnew file mode 100644index 000000000..991ddb63c--- /dev/null+++ b/.changeset/session-usage-limit-function.md@@ -0,0 +1,5 @@+---+"eve": minor+---++Breaking: replace `limits.maxInputTokensPerSession`, `limits.maxOutputTokensPerSession` and `limits.maxTokenCostUsdPerSession` with one `limits.sessionUsage` function. It receives the session's `total` usage and its `window` since the last approved continuation, and returns `true` when the limit is reached; Continue starts a new window. The default is 40M new input tokens (input minus cache reads) per window. Subagents now check their own window with their own `sessionUsage` or the root agent's instead of receiving a share of the parent's remaining quota. Sessions that can't ask now fail with `SESSION_USAGE_LIMIT_REACHED`, replacing `SESSION_TOKEN_LIMIT_REACHED` and `SESSION_TOKEN_COST_LIMIT_REACHED`.diff --git a/apps/templates/eve-llm-council-template/agent/agent.ts b/apps/templates/eve-llm-council-template/agent/agent.tsindex 0e9529351..30bd5f845 100644--- a/apps/templates/eve-llm-council-template/agent/agent.ts+++ b/apps/templates/eve-llm-council-template/agent/agent.ts@@ -3,6 +3,6 @@ import { defineAgent } from "eve";export default defineAgent({model: "anthropic/claude-opus-5",limits: {- maxOutputTokensPerSession: 4_000,+ sessionUsage: ({ window }) => window.outputTokens >= 4_000,},});diff --git a/docs/agent-config.md b/docs/agent-config.mdindex 62e7b5fb5..783072d0b 100644--- a/docs/agent-config.md+++ b/docs/agent-config.md@@ -137,7 +137,7 @@ export default defineAgent({starting points on Ollama.- **Usage.** `includeUsage: true` lets token usage reach eve's[session limits](#runtime-limits). Local models report no cost, so- `maxTokenCostUsdPerSession` does not apply.+ `costUsd` stays unset in a `sessionUsage` check.- **Other servers.** Change `baseURL`, for example to`http://localhost:1234/v1` for LM Studio. Pass `apiKey` for a remoteOpenAI-compatible server that requires one.@@ -262,17 +262,18 @@ See [Default harness](./concepts/default-harness#compaction) for how the loop ap## Runtime limits-Use `limits` for framework-owned runtime caps. Session usage limits stop the-current durable session from starting another model call after accumulated-provider-reported tokens or model token cost reaches a configured limit:+Use `limits` for framework-owned runtime caps. `sessionUsage` decides when the+current durable session must stop starting model calls. It receives the+session's usage and returns `true` when the limit is reached:```ts title="agent/agent.ts"export default defineAgent({model: "anthropic/claude-opus-5.5",limits: {- maxInputTokensPerSession: 200_000,- maxOutputTokensPerSession: 20_000,- maxTokenCostUsdPerSession: 1.5,+ sessionUsage: ({ window }) =>+ window.inputTokens - window.cacheReadTokens >= 200_000 ||+ window.outputTokens >= 20_000 ||+ (window.costUsd ?? 0) >= 1.5,sessionTimeoutMs: 7 * 24 * 60 * 60 * 1_000,},});@@ -293,23 +294,56 @@ disable the timeout. Session expiration follows[run-data retention](#run-data-retention); a zero-retention session loses itsstored payloads when it ends.-Input tokens, output tokens, and model token cost are checked independently.-The input limit counts only new input: uncached input plus cache writes. Cache-reads, the history a provider replays from its prompt cache on every step, do-not count, so long tool-heavy sessions are not stopped for re-reading their own-context. When a provider reports no cache details, all input counts.-The model call that crosses a limit is allowed to finish because exact usage-arrives after the call completes. Before the next model call, eve pauses the-turn (`turn.waiting`) and sends a deterministic continuation prompt with two options:-**Continue** grants a fresh window of each configured size and resumes the same-turn, and **Stop**-cancels the in-flight turn through the standard cancellation path-(`turn.cancelled` → `session.waiting`) — a user decision, not an error. The session stays resumable; because it is-still over budget after Stop, the next message raises a new prompt. Declining a+`sessionUsage` gets two usage records with `inputTokens`, `outputTokens`,+`cacheReadTokens`, `cacheWriteTokens`, and `costUsd`: `total` is everything+the session has spent, and `window` is what it spent since the last approved+continuation. `inputTokens` includes cache reads and writes. Subtract+`cacheReadTokens` to count only new input; cache reads are the history a+provider replays from its prompt cache on every step. `costUsd` is the model+token cost in US dollars that AI Gateway reports with each step, not tool or+infrastructure spend; it is unset when no step reported a cost.++When `sessionUsage` is omitted, the limit is `40_000_000` new input tokens per+window:++```ts+({ window }) => window.inputTokens - window.cacheReadTokens >= 40_000_000;+```++`sessionUsage` can raise its threshold after each approval. This limit asks+at 20,000 new input tokens, then at 40,000, 80,000, and so on:++```ts title="agent/agent.ts"+export default defineAgent({+ model: "anthropic/claude-opus-5.5",+ limits: {+ sessionUsage: ({ total, window }) => {+ const used = total.inputTokens - total.cacheReadTokens;+ // Usage when the last continuation was approved; 0 before the first.+ const approvedAt = used - (window.inputTokens - window.cacheReadTokens);+ // Double past it, so each approval allows twice the usage before the next prompt.+ let next = 20_000;+ while (next <= approvedAt) next *= 2;+ return used >= next;+ },+ },+});+```++Set `sessionUsage: () => false` to leave sessions uncapped; `sessionUsage:+false` is not accepted. eve calls `sessionUsage` before each model call once+the window has usage. The model call that crosses a limit is allowed to finish+because exact usage arrives after the call completes. Before the next model+call, eve pauses the turn (`turn.waiting`) and sends a deterministic+continuation prompt with two options: **Continue** starts a new window and+resumes the same turn, and **Stop** cancels the in-flight turn through the+standard cancellation path (`turn.cancelled` → `session.waiting`). Stop is a+user decision, not an error. The session stays resumable; because it is still+over budget after Stop, the next message raises a new prompt. Declining adelegated child's prompt cancels the root turn, which cascades to the whole-delegation tree — the delegating parent never receives an error result it-could retry against a fresh quota share. A reply that answers neither option-is queued while the existing prompt stays pending; eve does not raise another+delegation tree, so the delegating parent never receives an error result it+could retry. A reply that answers neither option is queued while the existing+prompt stays pending; eve does not raise anothercopy or start another turn. The reply is received (`message.received`) andprocessed in the held turn once the budget is granted.@@ -321,44 +355,22 @@ turn or duplicate the prompt.Sessions that cannot request input from a human, such as markdown schedules anddelegated runs without input proxying, skip the prompt and fail the next model-call with `SESSION_TOKEN_LIMIT_REACHED` for token budgets or-`SESSION_TOKEN_COST_LIMIT_REACHED` for model token cost. A delegated task with-no inherited quota also fails instead of raising a continuation prompt that-could only grant another zero-value window.--When `maxInputTokensPerSession` is omitted, root sessions apply a default-input budget of `40_000_000` new input tokens.-`maxOutputTokensPerSession` and `maxTokenCostUsdPerSession` are unset by-default. `maxTokenCostUsdPerSession` is a US-dollar limit on model token cost,-not tool or infrastructure spend. It uses the cost reported with each model-step; AI Gateway supplies this value, while model steps without reported cost-do not add to the limit. Set any usage limit to `false` to uncap that axis.--Delegated subagent sessions have no fixed default. Each child receives a share-of the delegating parent's remaining quota when it starts: the remainder in-the current budget window split evenly across the agent tasks that one model-step starts. A session that a workflow tool opens with `ctx.agent` receives-the share of the model step that called the tool, or the whole remainder when-that step starts no agent tasks; eve does not divide that share among several-sessions one call opens. A child keeps its grant for its whole session,-including turns that later calls with `taskId` start. Remote agent tasks count-toward the split but receive no grant: they run under their own deployment's-limits.--A child's usage, including what the child's own subagents spent, counts-against the parent's quota. An agent task's usage counts with each reply it+call with `SESSION_USAGE_LIMIT_REACHED`. Its details carry the `total` and+`window` usage the check saw.++Each subagent session checks its own usage against its own `sessionUsage`, or+the root agent's when it authors none. A dynamic subagent can't select+`sessionUsage` at runtime and always uses the root agent's. Remote agents run+under their own deployment's limits.++A child's usage, including what the child's own subagents spent, also counts+in the parent's usage. An agent task's usage counts with each reply itsends. A turn it doesn't reply to, such as one a cancel stopped, counts withthe next reply, or when the turn ends if no call waits for a reply. Sessionsthat any other `serve` workflow tool opens with `ctx.agent` count the sameway; those of an `execute` or `task` tool count when the tool finishes. Remote-agents' reported usage counts the same way. Later children draw from what-remains, and the parent's own limit and continuation prompt include delegated-spend. Token-cost budgets follow the same rules, including splitting the-remaining US-dollar budget and adding child cost back to the parent. Approving-a continuation opens a fresh parent window for later child grants without-erasing lifetime usage. An authored child limit applies only when it is-tighter than the parent's grant; an uncapped parent delegates uncapped-children.+agents' reported usage counts the same way, cost included. Approving a+continuation starts a new window without erasing `total`.Some delegated usage doesn't count against the parent: a `ctx.agent` turnstill running when its workflow tool finishes or is cancelled; the `ctx.agent`diff --git a/e2e/fixtures/agent-compaction-regressions/agent/agent.ts b/e2e/fixtures/agent-compaction-regressions/agent/agent.tsindex 286508229..5e2b1e4bf 100644--- a/e2e/fixtures/agent-compaction-regressions/agent/agent.ts+++ b/e2e/fixtures/agent-compaction-regressions/agent/agent.ts@@ -233,7 +233,7 @@ export default defineAgent({(TEST_REQUEST_ENVELOPE_TOKENS + TEST_HISTORY_BUDGET_TOKENS) / TEST_CONTEXT_WINDOW_TOKENS,},limits: {- maxInputTokensPerSession: 100_000,+ sessionUsage: ({ window }) => window.inputTokens - window.cacheReadTokens >= 100_000,},});diff --git a/e2e/fixtures/agent-deferred-tools/agent/agent.ts b/e2e/fixtures/agent-deferred-tools/agent/agent.tsindex b6522355c..ea1a25ea1 100644--- a/e2e/fixtures/agent-deferred-tools/agent/agent.ts+++ b/e2e/fixtures/agent-deferred-tools/agent/agent.ts@@ -126,5 +126,5 @@ export default defineAgent({? { modelOptions: { providerOptions: { gateway: { only: ["anthropic"] } } } }: {}),reasoning: "high",- limits: { maxInputTokensPerSession: 300_000 },+ limits: { sessionUsage: ({ window }) => window.inputTokens - window.cacheReadTokens >= 300_000 },});diff --git a/e2e/fixtures/agent-prompt-cache/agent/agent.ts b/e2e/fixtures/agent-prompt-cache/agent/agent.tsindex 8de030968..b0c7ab3c2 100644--- a/e2e/fixtures/agent-prompt-cache/agent/agent.ts+++ b/e2e/fixtures/agent-prompt-cache/agent/agent.ts@@ -14,5 +14,5 @@ export default defineAgent({}: {}),reasoning: "high",- limits: { maxInputTokensPerSession: 300_000 },+ limits: { sessionUsage: ({ window }) => window.inputTokens - window.cacheReadTokens >= 300_000 },});diff --git a/e2e/fixtures/agent-session-limits/agent/agent.ts b/e2e/fixtures/agent-session-limits/agent/agent.tsindex 75eef2a76..b45733fd4 100644--- a/e2e/fixtures/agent-session-limits/agent/agent.ts+++ b/e2e/fixtures/agent-session-limits/agent/agent.ts@@ -7,7 +7,7 @@ export default defineAgent({// the limit, so the next conversation turn deterministically parks on the// session-limit continuation prompt.limits: {- maxInputTokensPerSession: 1,+ sessionUsage: ({ window }) => window.inputTokens >= 1,},// Without the built-in agent tool there are no task tools, so the one-call budget can't go to eve__task_wait.tool: false,diff --git a/e2e/fixtures/agent-subagents-hitl/agent/subagents/budget-child/agent.ts b/e2e/fixtures/agent-subagents-hitl/agent/subagents/budget-child/agent.tsindex 490bc1754..c51c65ba3 100644--- a/e2e/fixtures/agent-subagents-hitl/agent/subagents/budget-child/agent.ts+++ b/e2e/fixtures/agent-subagents-hitl/agent/subagents/budget-child/agent.ts@@ -7,7 +7,7 @@ import { mockModel } from "eve/evals";*/export default defineAgent({description: "Record the release step, then confirm it.",- limits: { maxInputTokensPerSession: 1 },+ limits: { sessionUsage: ({ window }) => window.inputTokens >= 1 },model: mockModel(({ toolResults }) =>toolResults.some((entry) => entry.name === "record_step")? "BUDGET-CHILD-RESULT recorded"diff --git a/e2e/fixtures/agent-subagents/agent/subagents/limited-worker/agent.ts b/e2e/fixtures/agent-subagents/agent/subagents/limited-worker/agent.tsindex b4eb97fe5..fa47fd40e 100644--- a/e2e/fixtures/agent-subagents/agent/subagents/limited-worker/agent.ts+++ b/e2e/fixtures/agent-subagents/agent/subagents/limited-worker/agent.ts@@ -5,7 +5,7 @@ export default defineAgent({description:"Test-only child for session-limit propagation. Call it exactly when the user asks for the limited-worker subagent.",limits: {- maxInputTokensPerSession: 1,+ sessionUsage: ({ window }) => window.inputTokens >= 1,},...e2eSubagentConfig(),reasoning: "high",diff --git a/e2e/fixtures/agent-subagents/evals/delegated-usage-limit.shared.ts b/e2e/fixtures/agent-subagents/evals/delegated-usage-limit.shared.tsindex 8352973a2..f1bc989d2 100644--- a/e2e/fixtures/agent-subagents/evals/delegated-usage-limit.shared.ts+++ b/e2e/fixtures/agent-subagents/evals/delegated-usage-limit.shared.ts@@ -20,12 +20,14 @@ export async function expectSurveyCountedAgainstParent(t: EveEvalContext, messagoptionIds: ["continue", "stop"],toolName: "session_limit_continuation",});- const parentLimitId = new RegExp(`^${session.sessionId ?? ""}:\\d+:limit:input:(\\d+)$`, "u");await t.require(- request.requestId,+ request,satisfies(- (requestId: string) =>- Number(parentLimitId.exec(requestId)?.[1] ?? -1) >= SURVEY_WORKER_INPUT_TOKENS,+ (prompt: typeof request) =>+ prompt.requestId.startsWith(`${session.sessionId ?? ""}:`) &&+ Number(+ (prompt.action.input.total as { inputTokens?: number } | undefined)?.inputTokens ?? -1,+ ) >= SURVEY_WORKER_INPUT_TOKENS,"the parent's input limit prompt counts the worker's tokens",),);diff --git a/e2e/fixtures/agent-tools-hitl/agent/agent.ts b/e2e/fixtures/agent-tools-hitl/agent/agent.tsindex 22effa3fe..dc6371175 100644--- a/e2e/fixtures/agent-tools-hitl/agent/agent.ts+++ b/e2e/fixtures/agent-tools-hitl/agent/agent.ts@@ -99,7 +99,7 @@ export default defineAgent({experimental: base.experimental,reasoning: "high",// Budget evals exhaust this with synthetic usage; ordinary HITL sessions do not.- limits: { maxOutputTokensPerSession: 1_000_000 },+ limits: { sessionUsage: ({ window }) => window.outputTokens >= 1_000_000 },model: defineDynamic({events: {"session.started": () => ({diff --git a/packages/eve/extension-contracts/reports/subagent/v41.json b/packages/eve/extension-contracts/reports/subagent/v41.jsonnew file mode 100644index 000000000..4e84ae3cd--- /dev/null+++ b/packages/eve/extension-contracts/reports/subagent/v41.json@@ -0,0 +1,23 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "subagent",+ "epoch": 41,+ "sha256": "4ce7a59a4f956f06d4cbf9893d33335832d694852ce4294d2b8db050f211f127",+ "exports": [+ "AgentCompactionDefinition",+ "AgentDefinition",+ "AgentModelDefinition",+ "AgentStaticModelDefinition",+ "DefinedAgent",+ "DynamicLocalSubagentDefinition",+ "DynamicSubagentDefinition",+ "RemoteAgentDefinition",+ "RemoteAgentDefinitionInput",+ "WorkspaceAgentDefinition",+ "WorkspaceAgentTransport",+ "defineAgent",+ "defineDynamic",+ "defineRemoteAgent",+ "defineWorkspaceAgent"+ ]+}diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.tsindex 53db8b927..38b37a7cf 100644--- a/packages/eve/src/channel/types.ts+++ b/packages/eve/src/channel/types.ts@@ -11,7 +11,6 @@ import type {} from "#shared/action-types.js";import type { InputRequest, InputResponse } from "#shared/input.js";import type { ChannelAdapter } from "#channel/adapter.js";-import type { AgentLimitsDefinition } from "#shared/agent-definition.js";import type { JsonObject } from "#shared/json.js";import type { SessionHistoryMessage } from "#shared/session-history.js";import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";@@ -24,11 +23,6 @@ export type { ChannelInstrumentationProjection } from "#channel/instrumentation.import type { ChannelInstrumentationProjection } from "#channel/instrumentation.js";-export type RunSessionLimits = Pick<- AgentLimitsDefinition,- "maxInputTokensPerSession" | "maxOutputTokensPerSession" | "maxTokenCostUsdPerSession"->;-/** Identifies the session turn to cancel. */export interface CancelTurnInput {readonly sessionId: string;@@ -545,13 +539,6 @@ export interface RunInput {* because trace state is scoped to one session's context.*/readonly parentTraceContext?: SessionTraceContext;- /**- * 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 metadata for a protocol-neutral external invocation. */readonly externalInvocation?: {readonly continuationToken: string;diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.tsindex 556463373..93018436d 100644--- a/packages/eve/src/compiler/extension-compatibility.ts+++ b/packages/eve/src/compiler/extension-compatibility.ts@@ -172,10 +172,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},},subagent: {- current: 40,+ current: 41,supported: [3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 19, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,- 34, 35, 36, 37, 38, 39, 40,+ 34, 35, 36, 37, 38, 39, 41,],dropped: {1: "Persistent subagent sessions are now the default and the experimental opt-in was removed",@@ -186,6 +186,7 @@ const EXTENSION_CAPABILITY_CONTRACTS = {20: "Run mode was removed and agent definitions no longer declare outputSchema; sessions always park, ConversationContext no longer carries mode, and structured output is requested per turn.",21: 'Background task execution was removed: subagent results no longer carry backgroundTask, message.completed always carries text, and experimental.tasks is gone. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.',22: "Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.",+ 40: "limits.sessionUsage replaces the numeric per-session token and cost limits",},},connection: {diff --git a/packages/eve/src/compiler/manifest.test.ts b/packages/eve/src/compiler/manifest.test.tsindex 9ee7f0785..655ea2de5 100644--- a/packages/eve/src/compiler/manifest.test.ts+++ b/packages/eve/src/compiler/manifest.test.ts@@ -17,7 +17,10 @@ describe("compiled agent manifest v50", () => {const { manifest } = await compileFromMemory({agent: {experimental: { workflow: { modelCallsPerStep: 4, retention: 0 } },- limits: { maxTokenCostUsdPerSession: 1.5 },+ limits: {+ sessionTimeoutMs: 86_400_000,+ sessionUsage: ({ window }) => window.costUsd !== undefined && window.costUsd >= 1.5,+ },model: "openai/gpt-5.4",},model: "openai/gpt-5.4",@@ -29,10 +32,23 @@ describe("compiled agent manifest v50", () => {expect(parsed.config.experimental?.workflow?.modelCallsPerStep).toBe(4);// `0` is falsy: a truthiness-based copy anywhere on the manifest path drops it.expect(parsed.config.experimental?.workflow?.retention).toBe(0);- expect(parsed.config.limits?.maxTokenCostUsdPerSession).toBe(1.5);+ expect(parsed.config.limits?.sessionTimeoutMs).toBe(86_400_000);+ // The manifest is JSON: a `sessionUsage` function compiles to a marker, and the+ // runtime loads the function from the agent module.+ expect(parsed.config.limits?.sessionUsage).toBe(true);expect(() => validateCompiledAgentManifest(parsed)).not.toThrow();});+ it("marks no session usage limit when the agent authors none", async () => {+ const { manifest } = await compileFromMemory({+ agent: { limits: { sessionTimeoutMs: 1_000 }, model: "openai/gpt-5.4" },+ model: "openai/gpt-5.4",+ });+ const parsed = compiledAgentManifestSchema.parse(JSON.parse(JSON.stringify(manifest)));++ expect(parsed.config.limits).toEqual({ sessionTimeoutMs: 1_000 });+ });+it("round-trips agent tool configuration and disabled tool names", async () => {const { manifest } = await compileFromMemory({agent: { model: "openai/gpt-5.4", tool: false },diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.tsindex 5b75bfecd..e0fe7c85b 100644--- a/packages/eve/src/compiler/manifest.ts+++ b/packages/eve/src/compiler/manifest.ts@@ -615,16 +615,12 @@ const compiledAgentCompactionDefinitionSchema: z.ZodType<CompiledAgentCompaction}).strict();-const sessionTokenLimitSchema = z.union([z.number().int().positive(), z.literal(false)]);-const sessionTokenCostLimitSchema = z.union([z.number().finite().positive(), z.literal(false)]);const sessionTimeoutSchema = z.union([z.number().int().positive(), z.literal(false)]);const compiledAgentLimitsDefinitionSchema = z.object({- maxInputTokensPerSession: sessionTokenLimitSchema.optional(),- maxOutputTokensPerSession: sessionTokenLimitSchema.optional(),- maxTokenCostUsdPerSession: sessionTokenCostLimitSchema.optional(),sessionTimeoutMs: sessionTimeoutSchema.optional(),+ sessionUsage: z.literal(true).optional(),}).strict();@@ -1255,10 +1251,8 @@ function cloneCompiledAgentDefinition(config: CompiledAgentDefinition): Compiledconfig.limits === undefined? undefined: {- maxInputTokensPerSession: config.limits.maxInputTokensPerSession,- maxOutputTokensPerSession: config.limits.maxOutputTokensPerSession,- maxTokenCostUsdPerSession: config.limits.maxTokenCostUsdPerSession,sessionTimeoutMs: config.limits.sessionTimeoutMs,+ sessionUsage: config.limits.sessionUsage,},source: { ...config.source },tool: config.tool,diff --git a/packages/eve/src/compiler/module-lifecycle.ts b/packages/eve/src/compiler/module-lifecycle.tsindex 7ca31a5c8..aa7d7718a 100644--- a/packages/eve/src/compiler/module-lifecycle.ts+++ b/packages/eve/src/compiler/module-lifecycle.ts@@ -53,7 +53,13 @@ export function markConfigRuntimeEntries(config: CompiledAgentDefinition,evaluation: NodeModuleEvaluationContext,): void {- const sources = [config.dynamicModel, config.model?.source, config.compaction?.model?.source];+ const sources = [+ config.dynamicModel,+ config.model?.source,+ config.compaction?.model?.source,+ // The runtime loads `limits.sessionUsage` from the agent config module.+ config.limits?.sessionUsage === true ? config.source : undefined,+ ];for (const source of sources) {if (source !== undefined) evaluation.requireRuntimeEntry(source.sourceId);}diff --git a/packages/eve/src/compiler/normalize-agent-config.ts b/packages/eve/src/compiler/normalize-agent-config.tsindex 931cedb2b..e3b6a2184 100644--- a/packages/eve/src/compiler/normalize-agent-config.ts+++ b/packages/eve/src/compiler/normalize-agent-config.ts@@ -144,10 +144,8 @@ export async function compileAgentConfig(if (definition.limits !== undefined) {compiledConfig.limits = {- maxInputTokensPerSession: definition.limits.maxInputTokensPerSession,- maxOutputTokensPerSession: definition.limits.maxOutputTokensPerSession,- maxTokenCostUsdPerSession: definition.limits.maxTokenCostUsdPerSession,sessionTimeoutMs: definition.limits.sessionTimeoutMs,+ sessionUsage: definition.limits.sessionUsage === undefined ? undefined : true,};}diff --git a/packages/eve/src/execution/agent-sessions/context.test.ts b/packages/eve/src/execution/agent-sessions/context.test.tsdeleted file mode 100644index 4cde0bc0f..000000000--- a/packages/eve/src/execution/agent-sessions/context.test.ts+++ /dev/null@@ -1,92 +0,0 @@-import { describe, expect, it } from "vitest";--import { resolveStepAgentLimits } from "#execution/agent-sessions/context.js";-import {- createTask,- readTaskTable,- writeTaskTable,- type TaskTable,-} from "#execution/tasks/table.js";-import { setTurnUsageState } from "#harness/turn-tag-state.js";-import type { HarnessSession } from "#harness/types.js";-import type { RuntimeWorkflowTaskRequest, WorkflowToolCallEntry } from "#shared/action-types.js";--/** Alice's session has spent 400 of 1,000 input tokens and $0.50 of $2.00. */-function aliceSession(table: TaskTable): HarnessSession {- const used = {- cacheReadTokens: 0,- cacheWriteTokens: 0,- costUsd: 0.5,- inputTokens: 400,- outputTokens: 0,- sawCost: true,- };- const session = {- limits: { maxInputTokensPerSession: 1_000, maxTokenCostUsdPerSession: 2 },- sessionId: "alice-session",- } as HarnessSession;- return setTurnUsageState(writeTaskTable(session, table), {- ...used,- session: used,- turnId: "turn_1",- });-}--function call(callId: string, entry: WorkflowToolCallEntry): RuntimeWorkflowTaskRequest {- return { callId, entry, input: {}, kind: "workflow-task", toolName: callId, workflowId: callId };-}--function task(- table: TaskTable,- name: string,- kind: "agent" | "tool",-): { readonly table: TaskTable; readonly taskId: string } {- return createTask(table, { callId: name, kind, name, resumable: true, turnId: "turn_1" });-}--/**- * One model step's calls: the step started a reviewer and a writer agent- * task, an authored `serve` task, and an `execute` call, and sent a message- * to a planner agent task an earlier step started.- */-function stepCalls(input: { readonly startsAgents: boolean }): {- readonly plan: readonly RuntimeWorkflowTaskRequest[];- readonly table: TaskTable;-} {- const planner = task(readTaskTable(undefined), "planner", "agent");- const plan = [- call("research", { entryPoint: "execute" }),- call("planner", { entryPoint: "receive", taskId: planner.taskId }),- ];- if (!input.startsAgents) return { plan, table: planner.table };- const reviewer = task(planner.table, "reviewer", "agent");- const writer = task(reviewer.table, "writer", "agent");- const notes = task(writer.table, "notes", "tool");- return {- plan: [- ...plan,- call("reviewer", { entryPoint: "serve", taskId: reviewer.taskId }),- call("writer", { entryPoint: "serve", taskId: writer.taskId }),- call("notes", { entryPoint: "serve", taskId: notes.taskId }),- ],- table: notes.table,- };-}--describe("resolveStepAgentLimits", () => {- it.each([- { expected: { input: 300, costUsd: 0.75 }, startsAgents: true },- { expected: { input: 600, costUsd: 1.5 }, startsAgents: false },- ])(- "splits the remainder across the agent tasks a step starts (starts agents: $startsAgents)",- ({ expected, startsAgents }) => {- const { plan, table } = stepCalls({ startsAgents });-- expect(resolveStepAgentLimits({ plan, session: aliceSession(table) })).toEqual({- maxInputTokensPerSession: expected.input,- maxOutputTokensPerSession: false,- maxTokenCostUsdPerSession: expected.costUsd,- });- },- );-});diff --git a/packages/eve/src/execution/agent-sessions/context.ts b/packages/eve/src/execution/agent-sessions/context.tsindex 61374842e..cbaa5d99d 100644--- a/packages/eve/src/execution/agent-sessions/context.ts+++ b/packages/eve/src/execution/agent-sessions/context.ts@@ -1,6 +1,5 @@import type {ChannelInstrumentationProjection,- RunSessionLimits,SessionCapabilities,SessionParent,SessionTraceRoot,@@ -15,9 +14,7 @@ import {type DurableCompiledArtifactsSource,} from "#runtime/durable-compiled-artifacts-source.js";import type { SandboxState } from "#sandbox/state.js";-import { findTask, readTaskTable } from "#execution/tasks/table.js";import type { ConversationContext } from "#shared/conversation-context.js";-import { resolveRemainingSessionTokenLimits } from "#subagents/token-budget.js";import type { WorkflowAgentMetadata } from "#tools/workflow-definition.js";import {resolveToolCallAgentTrace,@@ -46,8 +43,6 @@ export interface AgentSessionContext {readonly conversation?: ConversationContext;/** Dynamic agents the calling turn selected, by node id. */readonly dynamicSelections: DynamicSubagentSelections;- /** The token budget each session inherits: its share of the caller's remaining quota. */- readonly limits: RunSessionLimits;readonly localDevRequest?: LocalDevRequestProvenance;/** The calling session, turn, and tool call, recorded as each session's lineage. */readonly parent: SessionParent;@@ -85,29 +80,10 @@ type CallerDispatch = Pick<| "workflowAgents">;-/**- * The token budget every session a model step's calls open inherits: the- * caller's remaining quota split evenly across the agent tasks the step- * starts, local or remote, so those tasks are bounded by the remainder- * together. Sessions a workflow tool opens with `ctx.agent` get the same- * share without dividing it further. A call to a running task starts none,- * so it takes no share.- */-export function resolveStepAgentLimits(- caller: Pick<PreparedCoordinationDispatch, "plan" | "session">,-): RunSessionLimits {- const table = readTaskTable(caller.session.state);- const agentTasksStarted = caller.plan.filter(- ({ entry }) => entry.entryPoint === "serve" && findTask(table, entry.taskId)?.kind === "agent",- ).length;- return resolveRemainingSessionTokenLimits(caller.session, agentTasksStarted);-}-/** Captures the agent session context for one workflow tool call, in the step that admits it. */export function captureAgentSessionContext(caller: CallerDispatch,callId: string,- limits: RunSessionLimits,): AgentSessionContext {const { batch, session } = caller;return {@@ -122,7 +98,6 @@ export function captureAgentSessionContext(channelMetadata: caller.channelMetadata,conversation: caller.inheritedConversation,dynamicSelections: caller.dynamicSubagentSelections,- limits,localDevRequest: caller.localDevRequest,parent: {callId,diff --git a/packages/eve/src/execution/agent-sessions/steps.ts b/packages/eve/src/execution/agent-sessions/steps.tsindex bcc26111c..48eb94481 100644--- a/packages/eve/src/execution/agent-sessions/steps.ts+++ b/packages/eve/src/execution/agent-sessions/steps.ts@@ -328,7 +328,6 @@ async function startLocalSession(graph: bundle.graph,inheritedConversation: context.conversation,initiatorAuth: auth.initiator,- limits: context.limits,parent: createParentContext(context, input.replyTo),sandboxSessionId: context.sandbox.sessionId,selfAgent: target.source.type === "runtime",diff --git a/packages/eve/src/execution/coordination-dispatch-step.ts b/packages/eve/src/execution/coordination-dispatch-step.tsindex 96d0b171a..ac7986247 100644--- a/packages/eve/src/execution/coordination-dispatch-step.ts+++ b/packages/eve/src/execution/coordination-dispatch-step.ts@@ -24,10 +24,7 @@ import {startTaskRun,} from "#execution/tasks/start.js";import { readTaskTable, type TaskTable } from "#execution/tasks/table.js";-import {- captureAgentSessionContext,- resolveStepAgentLimits,-} from "#execution/agent-sessions/context.js";+import { captureAgentSessionContext } from "#execution/agent-sessions/context.js";import type { TaskStartedStreamEvent } from "#protocol/message.js";import { startTask } from "#harness/session-machine/transitions.js";import type { RuntimeActionResult } from "#shared/action-types.js";@@ -85,11 +82,9 @@ async function dispatchCoordination(let nextSession = session;const results: RuntimeActionResult[] = [];const started: TaskStartedStreamEvent["data"][] = [];- const agentLimits = resolveStepAgentLimits(prepared);-const starts = withPrestartedRuns(prepared.plan.map((task) => ({- agentContext: captureAgentSessionContext(prepared, task.callId, agentLimits),+ agentContext: captureAgentSessionContext(prepared, task.callId),auth: {current: prepared.auth,initiator: prepared.initiatorAuth,diff --git a/packages/eve/src/execution/create-session-step.test.ts b/packages/eve/src/execution/create-session-step.test.tsdeleted file mode 100644index 0220dc9b1..000000000--- a/packages/eve/src/execution/create-session-step.test.ts+++ /dev/null@@ -1,188 +0,0 @@-import { describe, expect, it, vi } from "vitest";--import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.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";--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("defaults root sessions to the root input token budget", async () => {- vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({- resolvedAgent: {- config: {},- },- turnAgent: TestTurnAgent,- } as never);-- const { state } = await createSessionStep({- compiledArtifactsSource: { kind: "bundled" },- continuationToken: "http:test",- sessionId: "sess-root",- });-- expect(state.snapshot.session.limits?.maxInputTokensPerSession).toBe(- DEFAULT_ROOT_MAX_INPUT_TOKENS_PER_SESSION,- );- });-- it("limits delegated subagent sessions to the inherited token budget", async () => {- vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({- resolvedAgent: {- config: {},- },- turnAgent: TestTurnAgent,- } as never);-- const { state } = await createSessionStep({- compiledArtifactsSource: { kind: "bundled" },- continuationToken: "subagent:test",- inheritedLimits: { maxInputTokensPerSession: 3_000_000, maxOutputTokensPerSession: false },- rootSessionId: "sess-root",- sessionId: "sess-child",- });-- 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 },- rootSessionId: "sess-root",- sessionId: "sess-child",- });-- 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 },- rootSessionId: "sess-root",- sessionId: "sess-child",- });-- expect(state.snapshot.session.limits?.maxInputTokensPerSession).toBe(2_000_000);- });-- it("caps a configured child token-cost limit at the inherited budget", async () => {- vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({- resolvedAgent: {- config: { limits: { maxTokenCostUsdPerSession: 2 } },- },- turnAgent: TestTurnAgent,- } as never);-- const { state } = await createSessionStep({- compiledArtifactsSource: { kind: "bundled" },- continuationToken: "subagent:test",- inheritedLimits: { maxTokenCostUsdPerSession: 0.75 },- rootSessionId: "sess-root",- sessionId: "sess-child",- });-- expect(state.snapshot.session.limits?.maxTokenCostUsdPerSession).toBe(0.75);- });-- 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 },- rootSessionId: "sess-root",- sessionId: "sess-child",- });-- 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 },- rootSessionId: "sess-root",- sessionId: "sess-child",- });-- expect(state.snapshot.session.limits?.maxInputTokensPerSession).toBe(500_000);- });-- it("seeds session token limits from resolved agent config", async () => {- vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({- resolvedAgent: {- config: {- limits: {- maxInputTokensPerSession: 200_000,- maxOutputTokensPerSession: 20_000,- maxTokenCostUsdPerSession: 1.5,- },- },- },- turnAgent: TestTurnAgent,- } as never);-- const { state } = await createSessionStep({- compiledArtifactsSource: { kind: "bundled" },- continuationToken: "http:test",- sessionId: "sess-root",- });-- expect(state.snapshot.session.limits).toMatchObject({- maxInputTokensPerSession: 200_000,- maxOutputTokensPerSession: 20_000,- maxTokenCostUsdPerSession: 1.5,- });- });-});diff --git a/packages/eve/src/execution/create-session-step.ts b/packages/eve/src/execution/create-session-step.tsindex b70a70d38..7c9e4b0f8 100644--- a/packages/eve/src/execution/create-session-step.ts+++ b/packages/eve/src/execution/create-session-step.ts@@ -9,8 +9,6 @@ import {} from "#execution/durable-session-store.js";import type { HarnessModelMessage } from "#harness/messages.js";import { createSession } from "#execution/session.js";-import { resolveInheritedTokenLimit } from "#execution/run-session-limits.js";-import type { RunSessionLimits } from "#channel/types.js";import type { JsonObject } from "#shared/json.js";import { resolveEffectiveAgentRuntimeFromConfig } from "#execution/effective-agent-config.js";import type { AgentSessionRuntimeOverrides } from "#execution/agent-sessions/runtime-overrides.js";@@ -42,7 +40,6 @@ export async function createSessionStep(input: {readonly dynamicSubagentAgentConfig?: DynamicSubagentAgentConfig;/** History from `create()`, held until the first message's turn adds it. */readonly history?: readonly SessionHistoryMessage[];- readonly inheritedLimits?: RunSessionLimits;readonly outputSchema?: JsonObject;readonly nodeId?: string;readonly rootSessionId?: string;@@ -60,31 +57,11 @@ export async function createSessionStep(input: {input.agentSessionRuntimeOverrides,);- // Both token axes resolve 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: effectiveAgent.thresholdPercent,},continuationToken: input.continuationToken,- limits: {- // 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: effectiveAgent.limits?.maxInputTokensPerSession,- inherited: input.inheritedLimits?.maxInputTokensPerSession,- }),- maxOutputTokensPerSession: resolveInheritedTokenLimit({- configured: effectiveAgent.limits?.maxOutputTokensPerSession,- inherited: input.inheritedLimits?.maxOutputTokensPerSession,- }),- maxTokenCostUsdPerSession: resolveInheritedTokenLimit({- configured: effectiveAgent.limits?.maxTokenCostUsdPerSession,- inherited: input.inheritedLimits?.maxTokenCostUsdPerSession,- }),- },outputSchema: input.outputSchema,rootSessionId: input.rootSessionId,sessionId: input.sessionId,diff --git a/packages/eve/src/execution/durable-session-store.ts b/packages/eve/src/execution/durable-session-store.tsindex 706ee8cf3..ccda446a7 100644--- a/packages/eve/src/execution/durable-session-store.ts+++ b/packages/eve/src/execution/durable-session-store.ts@@ -53,7 +53,6 @@ export interface DurableSession {*/readonly rootSessionId?: string;readonly continuationToken: string;- readonly limits?: HarnessSession["limits"];readonly outputSchema?: JsonObject;readonly state?: SessionStateMap;readonly sandboxState?: SandboxState;diff --git a/packages/eve/src/execution/effective-agent-config.ts b/packages/eve/src/execution/effective-agent-config.tsindex d14c399c1..0b5ab8851 100644--- a/packages/eve/src/execution/effective-agent-config.ts+++ b/packages/eve/src/execution/effective-agent-config.ts@@ -1,8 +1,9 @@import type { ContextReader } from "#context/key.js";import { AgentSessionRuntimeOverridesKey, DynamicSubagentAgentConfigKey } from "#context/keys.js";import type { RuntimeTurnAgent } from "#runtime/agent/bootstrap.js";+import { ROOT_RUNTIME_AGENT_NODE_ID } from "#runtime/graph.js";import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";-import type { AgentLimitsDefinition } from "#shared/agent-definition.js";+import type { AgentLimitsDefinition, SessionUsageLimit } from "#shared/agent-definition.js";import type { AgentSessionRuntimeOverrides } from "#execution/agent-sessions/runtime-overrides.js";import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";@@ -23,6 +24,19 @@ export function resolveEffectiveAgentRuntime();}+/**+ * The session's `limits.sessionUsage`: the agent's own, else the root agent's.+ * A dynamic subagent config can't carry one, so its sessions run the root's.+ */+export function resolveSessionUsageLimit(+ bundle: Pick<CompiledBundle, "graph" | "resolvedAgent">,+): SessionUsageLimit | undefined {+ return (+ bundle.resolvedAgent.config?.limits?.sessionUsage ??+ bundle.graph.nodesByNodeId.get(ROOT_RUNTIME_AGENT_NODE_ID)?.agent.config?.limits?.sessionUsage+ );+}+export function resolveEffectiveAgentRuntimeFromConfig(bundle: Pick<CompiledBundle, "resolvedAgent" | "turnAgent">,config: DynamicSubagentAgentConfig | undefined,diff --git a/packages/eve/src/execution/legacy-session/snapshot.test.ts b/packages/eve/src/execution/legacy-session/snapshot.test.tsindex 14d5570f7..1d01e3cb1 100644--- a/packages/eve/src/execution/legacy-session/snapshot.test.ts+++ b/packages/eve/src/execution/legacy-session/snapshot.test.ts@@ -3,13 +3,12 @@ import { importConversation, normalizeHistory } from "./snapshot.js";import type { LegacySession } from "./snapshot.js";import { nextStepIndex, storedProjection, turnPosition } from "#harness/session-machine/view.js";describe("conversation import", () => {- it("preserves authored state, budget, emission coordinates and storage", () => {+ it("preserves authored state, emission coordinates and storage", () => {const session: LegacySession = {sessionId: "old",continuationToken: "slack:thread",history: [{ role: "user", content: "Alice chose blue." }],agent: { system: "old prompt" },- limits: { maxInputTokensPerSession: 40 },sandboxState: { session: null },state: {"app.color": "blue",@@ -27,7 +26,6 @@ describe("conversation import", () => {const { history, sessionState: result } = importConversation(session);expect(result.snapshot.session).toMatchObject({sessionId: "old",- limits: session.limits,sandboxState: session.sandboxState,state: {"app.color": "blue",diff --git a/packages/eve/src/execution/node-step.ts b/packages/eve/src/execution/node-step.tsindex e89c73a84..fd91bc864 100644--- a/packages/eve/src/execution/node-step.ts+++ b/packages/eve/src/execution/node-step.ts@@ -80,6 +80,7 @@ interface CreateExecutionNodeStepInput {readonly titleAttributeWrite?: ToolLoopHarnessConfig["titleAttributeWrite"];readonly modelResolutionScope: RuntimeModelResolutionScope;readonly node: ResolvedRuntimeAgentNode;+ readonly sessionUsageLimit?: ToolLoopHarnessConfig["sessionUsageLimit"];}/**@@ -119,6 +120,7 @@ export function createExecutionNodeStep(input: CreateExecutionNodeStepInput): StdispatchDynamicModelEvent: dispatchModelEvent,resolveModel,runtimeIdentity: buildRuntimeIdentity(input.node),+ sessionUsageLimit: input.sessionUsageLimit,tools,titleAttributeWrite: input.titleAttributeWrite,});diff --git a/packages/eve/src/execution/run-session-limits.ts b/packages/eve/src/execution/run-session-limits.tsdeleted file mode 100644index 3d99288e3..000000000--- a/packages/eve/src/execution/run-session-limits.ts+++ /dev/null@@ -1,23 +0,0 @@-import type { AgentLimitsDefinition } from "#shared/agent-definition.js";--type UsageLimit =- | AgentLimitsDefinition["maxInputTokensPerSession"]- | AgentLimitsDefinition["maxOutputTokensPerSession"]- | AgentLimitsDefinition["maxTokenCostUsdPerSession"];--/**- * Resolves an authored usage 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: UsageLimit | undefined;- readonly inherited: UsageLimit | undefined;-}): UsageLimit | undefined {- if (input.inherited === undefined) return input.configured;- if (input.inherited === false) return input.configured ?? false;- if (input.configured === undefined || input.configured === false) {- return input.inherited;- }- return Math.min(input.configured, input.inherited);-}diff --git a/packages/eve/src/execution/runtime-context.ts b/packages/eve/src/execution/runtime-context.tsindex e7ba05676..913db3880 100644--- a/packages/eve/src/execution/runtime-context.ts+++ b/packages/eve/src/execution/runtime-context.ts@@ -125,9 +125,5 @@ export function buildRunContext(input: {ctx.set(ParentTraceContextKey, run.parentTraceContext);}- // `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-limit-cancellation.integration.test.ts b/packages/eve/src/execution/session-limit-cancellation.integration.test.tsindex a0cda52ae..8b7870053 100644--- a/packages/eve/src/execution/session-limit-cancellation.integration.test.ts+++ b/packages/eve/src/execution/session-limit-cancellation.integration.test.ts@@ -84,7 +84,10 @@ function requestIdFromPromptTurn(events: readonly UnstampedMessageStreamEvent[])describe("session-limit continuation decline integration", () => {it("cancels the turn and keeps the session resumable when the user declines", async () => {const runtime = await createTestRuntime({- agent: { limits: { maxInputTokensPerSession: 1 }, name: "limit-decline-root" },+ agent: {+ limits: { sessionUsage: ({ window }) => window.inputTokens >= 1 },+ name: "limit-decline-root",+ },});const continuationToken = "http:limit-decline-root";diff --git a/packages/eve/src/execution/session.test.ts b/packages/eve/src/execution/session.test.tsindex 43285bd27..db3c880b0 100644--- a/packages/eve/src/execution/session.test.ts+++ b/packages/eve/src/execution/session.test.ts@@ -4,7 +4,6 @@ import type { RuntimeTurnAgent } from "#runtime/agent/bootstrap.js";import {createCompactionConfig,createSession,- DEFAULT_ROOT_MAX_INPUT_TOKENS_PER_SESSION,hydrateDurableSession,mintSubagentContinuationToken,projectToDurableSession,@@ -233,84 +232,6 @@ describe("createSession", () => {});});- it("defaults root sessions to the root input token budget", () => {- const session = createSession({- continuationToken: "root-token",- sessionId: "sess-root",- turnAgent: createTestTurnAgent(),- });-- expect(session.limits?.maxInputTokensPerSession).toBe(- DEFAULT_ROOT_MAX_INPUT_TOKENS_PER_SESSION,- );- });-- it("keeps the default cap when remote lineage has no inherited budget", () => {- const session = createSession({- continuationToken: "subagent-token",- rootSessionId: "sess-root",- sessionId: "sess-child",- turnAgent: createTestTurnAgent(),- });-- expect(session.limits?.maxInputTokensPerSession).toBe(- DEFAULT_ROOT_MAX_INPUT_TOKENS_PER_SESSION,- );- });-- 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 },- rootSessionId: "sess-root",- sessionId: "sess-child",- turnAgent: createTestTurnAgent(),- });-- expect(session.limits).toEqual({});- });-- it("treats a durable session without stored limits as uncapped on hydration", () => {- const hydrated = hydrateDurableSession({- durable: {- agent: { system: "You are a helpful assistant." },- continuationToken: "root-token",- sessionId: "sess-root",- },- turnAgent: createTestTurnAgent(),- });-- expect(hydrated.limits).toBeUndefined();- });-- it("rehydrates persisted limits verbatim without re-applying defaults", () => {- const hydrated = hydrateDurableSession({- durable: {- agent: { system: "You are a helpful assistant." },- continuationToken: "subagent-token",- limits: {},- rootSessionId: "sess-root",- sessionId: "sess-child",- },- turnAgent: createTestTurnAgent(),- });-- // 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", () => {const runOutputSchema = {properties: { title: { type: "string" } },@@ -352,36 +273,6 @@ describe("createSession", () => {expect(hydrated.rootSessionId).toBe("sess-root");});- it("persists session token limits through durable session projection and hydration", () => {- const session = createSession({- continuationToken: "root-token",- limits: {- maxInputTokensPerSession: 200_000,- maxOutputTokensPerSession: 20_000,- maxTokenCostUsdPerSession: 1.5,- },- sessionId: "sess-root",- turnAgent: createTestTurnAgent(),- });-- const durable = projectToDurableSession(session);- const hydrated = hydrateDurableSession({- durable,- turnAgent: createTestTurnAgent(),- });-- expect(durable.limits).toEqual({- maxInputTokensPerSession: 200_000,- maxOutputTokensPerSession: 20_000,- maxTokenCostUsdPerSession: 1.5,- });- expect(hydrated.limits).toEqual({- maxInputTokensPerSession: 200_000,- maxOutputTokensPerSession: 20_000,- maxTokenCostUsdPerSession: 1.5,- });- });-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 5e3be4894..4c1e14458 100644--- a/packages/eve/src/execution/session.ts+++ b/packages/eve/src/execution/session.ts@@ -4,7 +4,6 @@ import type {HarnessSession,HarnessSessionBase,SessionAgent,- SessionLimits,SessionToolDefinition,} from "#harness/types.js";import type { RuntimeTurnAgent } from "#runtime/agent/bootstrap.js";@@ -12,18 +11,6 @@ import type { RuntimeTurnAgent } from "#runtime/agent/bootstrap.js";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;--/**- * 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.- */-interface AuthoredSessionLimits {- readonly maxInputTokensPerSession?: number | false;- readonly maxOutputTokensPerSession?: number | false;- readonly maxTokenCostUsdPerSession?: number | false;-}/*** Creates the durable compaction configuration used by one harness session.@@ -72,7 +59,6 @@ interface CreateSessionInput {readonly rootSessionId?: string;readonly sessionId: string;readonly turnAgent: RuntimeTurnAgent;- readonly limits?: AuthoredSessionLimits;readonly outputSchema?: HarnessSession["outputSchema"];}@@ -97,7 +83,6 @@ export function createSession(input: CreateSessionInput): HarnessSession {if (input.rootSessionId !== undefined) {session.rootSessionId = input.rootSessionId;}- session.limits = resolveSessionLimits(input);if (input.outputSchema !== undefined) {session.outputSchema = input.outputSchema;}@@ -185,7 +170,6 @@ export function projectToDurableSession(session: HarnessSessionBase): DurableSeslastKnownPromptMessageCount?: number;};continuationToken: string;- limits?: HarnessSession["limits"];outputSchema?: HarnessSession["outputSchema"];rootSessionId?: string;sandboxState?: HarnessSession["sandboxState"];@@ -209,9 +193,6 @@ export function projectToDurableSession(session: HarnessSessionBase): DurableSesif (session.rootSessionId !== undefined) {durable.rootSessionId = session.rootSessionId;}- if (session.limits !== undefined) {- durable.limits = session.limits;- }if (session.outputSchema !== undefined) {durable.outputSchema = session.outputSchema;}@@ -256,12 +237,6 @@ export function hydrateDurableSession(input: {if (durable.rootSessionId !== undefined) {session.rootSessionId = durable.rootSessionId;}- // 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,44 +257,3 @@ function createSessionToolDefinitions(turnAgent: RuntimeTurnAgent): SessionToolDoutputSchema: tool.outputSchema,}));}--function resolveSessionLimits(input: { readonly limits?: AuthoredSessionLimits }): SessionLimits {- const maxInputTokensPerSession = resolveSessionTokenLimit({- authored: input.limits?.maxInputTokensPerSession,- // Local children carry an explicit inherited value, including `false` for- // an uncapped parent. Remote lineage alone must not remove this default.- fallback: DEFAULT_ROOT_MAX_INPUT_TOKENS_PER_SESSION,- });- const maxOutputTokensPerSession = resolveSessionTokenLimit({- authored: input.limits?.maxOutputTokensPerSession,- fallback: undefined,- });-- const maxTokenCostUsdPerSession = resolveSessionTokenLimit({- authored: input.limits?.maxTokenCostUsdPerSession,- fallback: undefined,- });-- const limits: {- maxInputTokensPerSession?: number;- maxOutputTokensPerSession?: number;- maxTokenCostUsdPerSession?: number;- } = {};- if (maxInputTokensPerSession !== undefined) {- limits.maxInputTokensPerSession = maxInputTokensPerSession;- }- if (maxOutputTokensPerSession !== undefined) {- limits.maxOutputTokensPerSession = maxOutputTokensPerSession;- }- if (maxTokenCostUsdPerSession !== undefined) {- limits.maxTokenCostUsdPerSession = maxTokenCostUsdPerSession;- }- return limits;-}--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/session/entry-input.ts b/packages/eve/src/execution/session/entry-input.tsindex 985d20e52..8a0ad2727 100644--- a/packages/eve/src/execution/session/entry-input.ts+++ b/packages/eve/src/execution/session/entry-input.ts@@ -20,7 +20,6 @@ export interface InitialWorkflowEntryInput {readonly continuationConflictCommand?: Extract<SessionCommand, { readonly kind: "send" }>;readonly input: RunInput["input"];readonly kind: "initial";- readonly limits?: RunInput["limits"];readonly ownerDeploymentId: string;readonly retention?: AgentWorkflowRetentionDefinition;readonly sessionTimeoutMs?: number | false;diff --git a/packages/eve/src/execution/session/entry.integration.test.ts b/packages/eve/src/execution/session/entry.integration.test.tsindex d6bcc99a9..dc20b4b3a 100644--- a/packages/eve/src/execution/session/entry.integration.test.ts+++ b/packages/eve/src/execution/session/entry.integration.test.ts@@ -1261,7 +1261,7 @@ describe("workflowEntry integration", () => {await withHeldApprovalRun({agent: {- limits: { maxInputTokensPerSession: 1 },+ limits: { sessionUsage: ({ window }) => window.inputTokens >= 1 },name: "workflow-entry-steer-held-limit",},auth: ALICE,diff --git a/packages/eve/src/execution/session/entry.ts b/packages/eve/src/execution/session/entry.tsindex b591ca7c7..45e90d8ed 100644--- a/packages/eve/src/execution/session/entry.ts+++ b/packages/eve/src/execution/session/entry.ts@@ -188,7 +188,6 @@ export async function bootInitialOwner(| undefined,// With a first message, its delivery carries the history instead.history: input.input.message === undefined ? input.input.history : undefined,- inheritedLimits: input.limits,nodeId: serializedBundle.nodeId,outputSchema: input.input.outputSchema,rootSessionId: readRootSessionId(serializedContext),diff --git a/packages/eve/src/execution/session/turn-step.test.ts b/packages/eve/src/execution/session/turn-step.test.tsindex 74b3b3885..0a072d5d3 100644--- a/packages/eve/src/execution/session/turn-step.test.ts+++ b/packages/eve/src/execution/session/turn-step.test.ts@@ -81,6 +81,7 @@ import {replaceDurableSessionSnapshot,} from "#execution/durable-session-store.js";import { buildRuntimeIdentity, createExecutionNodeStep } from "#execution/node-step.js";+import { ROOT_RUNTIME_AGENT_NODE_ID } from "#runtime/graph.js";import { defineTool } from "#tools/definition.js";import { defineState } from "#public/definitions/state.js";import { stampDurableDynamicCallback } from "#tools/durable-callbacks.js";@@ -1107,6 +1108,56 @@ describe("dispatchCoordinationStep", () => {});describe("turnStep", () => {+ describe("session usage limit", () => {+ const uncappedRoot = () => false;+ const childLimit = () => true;++ async function limitPassedToHarness(childSessionUsage: (() => boolean) | undefined) {+ const bundle = createStubBundle();+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({+ ...bundle,+ graph: {+ ...bundle.graph,+ nodesByNodeId: new Map([+ [+ ROOT_RUNTIME_AGENT_NODE_ID,+ { agent: { config: { limits: { sessionUsage: uncappedRoot } } } },+ ],+ ]),+ },+ resolvedAgent: {+ config:+ childSessionUsage === undefined ? {} : { limits: { sessionUsage: childSessionUsage } },+ },+ } as never);+ installSessionStoreMocks([createStubSession()]);+ let passed: unknown = "unset";+ vi.mocked(createExecutionNodeStep).mockImplementation((input) => {+ passed = input.sessionUsageLimit;+ return async (session: HarnessSession): Promise<StepResult> => ({+ next: { done: true, output: "complete" },+ session,+ });+ });++ await turnStep({+ input: { kind: "deliver", payloads: [{ message: "Survey the pier." }] },+ sessionWritable: createTestWritable(),+ serializedContext: createSerializedContext(),+ sessionState: createStubSessionState(),+ });+ return passed;+ }++ it("runs a subagent's own limit over an uncapped root's", async () => {+ await expect(limitPassedToHarness(childLimit)).resolves.toBe(childLimit);+ });++ it("runs the root agent's limit for a subagent without one", async () => {+ await expect(limitPassedToHarness(undefined)).resolves.toBe(uncappedRoot);+ });+ });+it("starts model work before the title attribute write settles and joins it before returning", async () => {let finishTitle!: () => void;vi.mocked(setEveAttributes)diff --git a/packages/eve/src/execution/session/turn-step.ts b/packages/eve/src/execution/session/turn-step.tsindex 71e6e948a..87c4ee08b 100644--- a/packages/eve/src/execution/session/turn-step.ts+++ b/packages/eve/src/execution/session/turn-step.ts@@ -76,7 +76,10 @@ import {readDurableSession,} from "#execution/durable-session-store.js";import { buildRuntimeIdentity, createExecutionNodeStep } from "#execution/node-step.js";-import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";+import {+ resolveEffectiveAgentRuntime,+ resolveSessionUsageLimit,+} from "#execution/effective-agent-config.js";import { reconcileSessionContinuationToken } from "#execution/reconcile-session-continuation-token.js";import { hydrateDurableSession, refreshSessionFromTurnAgent } from "#execution/session.js";import { createExecutionHistoryView } from "#execution/history-view.js";@@ -296,6 +299,7 @@ async function runSessionStepBody(try {const dynamicConnections = bindDynamicConnections(ctx, bundle.resolvedAgent);const effectiveNode = { ...bundle.graph.root, turnAgent: effectiveAgent.turnAgent };+ const sessionUsageLimit = resolveSessionUsageLimit(bundle);let compacted = false;const emitTurnEvent = createTurnEventHandler({abortSignal,@@ -517,6 +521,7 @@ async function runSessionStepBody(nodeId: bundle.nodeId,},node: effectiveNode,+ sessionUsageLimit,titleAttributeWrite: pendingAttributes.title,});return step(modelSession, stepInput);diff --git a/packages/eve/src/execution/tasks/task-run-usage.test.ts b/packages/eve/src/execution/tasks/task-run-usage.test.tsindex fe9743755..df090ce3e 100644--- a/packages/eve/src/execution/tasks/task-run-usage.test.ts+++ b/packages/eve/src/execution/tasks/task-run-usage.test.ts@@ -13,12 +13,11 @@ import {} from "#execution/tasks/table.js";import type { WorkflowToolRunRef } from "#execution/tools/workflow/messages.js";import {- getSessionTokenUsage,- getSessionUsageLimitViolation,+ getSessionUsage,+ getSessionUsageWindow,+ resetSessionUsageWindow,setTurnUsageState,- toUsage,} from "#harness/turn-tag-state.js";-import type { HarnessSession } from "#harness/types.js";import { createTestSessionState } from "#internal/testing/session-state.js";import type { TokenUsage } from "#shared/token-usage.js";@@ -38,14 +37,10 @@ function usage(inputTokens: number, costUsd?: number): TokenUsage {}/**- * A session that has spent `ownInputTokens` itself, under `limits`, with one- * agent task, `name`, whose run is working on a call.+ * A session that has spent `ownInputTokens` itself (all of it before a usage-window+ * reset), with one agent task, `name`, whose run is working on a call.*/-function sessionWithTask(input: {- readonly limits?: HarnessSession["limits"];- readonly name: string;- readonly ownInputTokens: number;-}): {+function sessionWithTask(input: { readonly name: string; readonly ownInputTokens: number }): {readonly cursor: SessionStateCursor;readonly execution: SessionExecution;readonly from: WorkflowToolRunRef;@@ -65,9 +60,8 @@ function sessionWithTask(input: {runId,});const snapshot = writeTaskTable(- setTurnUsageState(- { ...base.snapshot.session, limits: input.limits },- { ...own, session: own, turnId: "turn_1" },+ resetSessionUsageWindow(+ setTurnUsageState(base.snapshot.session, { ...own, session: own, turnId: "turn_1" }),),table,);@@ -108,13 +102,12 @@ function committed(cursor: SessionStateCursor): DurableSession {}function spent(cursor: SessionStateCursor): TokenUsage {- return toUsage(getSessionTokenUsage(committed(cursor)));+ return getSessionUsage(committed(cursor));}describe("delegated agent usage", () => {- it("counts a task's usage once from its replies, usage reports, and outcome, however often they arrive, against the session's limits", async () => {+ it("counts a task's usage once from its replies, usage reports, and outcome, however often they arrive, in the session's usage window", async () => {const alice = sessionWithTask({- limits: { maxInputTokensPerSession: 1_000 },name: "reviewer",ownInputTokens: 100,});@@ -136,7 +129,8 @@ describe("delegated agent usage", () => {await alice.execution.handleWorkflowMessage({ from, kind: "usage", usage: usage(600, 0.5) });expect(spent(alice.cursor)).toEqual(usage(700, 0.5));- expect(getSessionUsageLimitViolation(committed(alice.cursor))).toBeNull();+ // The window started after Alice's own 100 tokens, so it holds only the reviewer's spend.+ expect(getSessionUsageWindow(committed(alice.cursor))).toEqual(usage(600, 0.5));const outcome = {from,@@ -149,10 +143,6 @@ describe("delegated agent usage", () => {await alice.execution.handleWorkflowMessage(outcome);expect(spent(alice.cursor)).toEqual(usage(1_000, 0.75));- expect(getSessionUsageLimitViolation(committed(alice.cursor))).toEqual({- kind: "input",- limit: 1_000,- usedTokens: 1_000,- });+ expect(getSessionUsageWindow(committed(alice.cursor))).toEqual(usage(900, 0.75));});});diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.tsindex df796db07..e5564e9b6 100644--- a/packages/eve/src/execution/workflow-runtime.ts+++ b/packages/eve/src/execution/workflow-runtime.ts@@ -184,7 +184,6 @@ export function createWorkflowRuntime(config: {ownerDeploymentId: await resolveCurrentWorkflowDeploymentId(),serializedContext,};- if (input.limits !== undefined) workflowInput.limits = input.limits;if (input.continuationConflictCommand !== undefined) {workflowInput.continuationConflictCommand = input.continuationConflictCommand;}diff --git a/packages/eve/src/harness/hitl/budget-request.test.ts b/packages/eve/src/harness/hitl/budget-request.test.tsindex a2a5315da..d46eed4f8 100644--- a/packages/eve/src/harness/hitl/budget-request.test.ts+++ b/packages/eve/src/harness/hitl/budget-request.test.ts@@ -7,26 +7,43 @@ import {resolveSessionLimitContinuation,} from "#harness/hitl/budget-request.js";-const VIOLATION = { kind: "input", limit: 40_000_000, usedTokens: 40_120_500 } as const;+const TOTAL = {+ cacheReadTokens: 500,+ cacheWriteTokens: 0,+ inputTokens: 40_120_000,+ outputTokens: 500,+} as const;+const WINDOW = {+ cacheReadTokens: 500,+ cacheWriteTokens: 0,+ inputTokens: 40_000_500,+ outputTokens: 20,+} as const;++const PROMPT =+ "This session has hit its usage limit. This is a guardrail against defective " ++ "long-running sessions. If session activity looks fine, just approve to keep going.";function createTestRequest() {return createSessionLimitContinuationRequest({sessionId: "sess-test",+ total: TOTAL,turnSequence: 0,- violation: VIOLATION,+ window: WINDOW,+ windowIndex: 0,});}describe("createSessionLimitContinuationRequest", () => {- it("derives a deterministic request from the violation", () => {+ it("derives a deterministic request from the usage", () => {const first = createTestRequest();const second = createTestRequest();expect(first).toEqual(second);expect(first).toEqual({action: {- callId: "sess-test:0:limit:input:40120500",- input: { kind: "input", limit: 40_000_000, usedTokens: 40_120_500 },+ callId: "sess-test:0:limit:usage:0",+ input: { total: TOTAL, window: WINDOW },kind: "tool-call",toolName: "session_limit_continuation",},@@ -35,7 +52,7 @@ describe("createSessionLimitContinuationRequest", () => {kind: "session-limit",options: [{- description: "Grant a fresh token budget",+ description: "Start a new usage window",id: "continue",label: "Approve",style: "primary",@@ -47,67 +64,47 @@ describe("createSessionLimitContinuationRequest", () => {style: "danger",},],- prompt:- "This session has hit the input-token limit (40M) per session. This is a guardrail " +- "against defective long-running sessions. If session activity looks fine, just " +- "approve to keep going.",- requestId: "sess-test:0:limit:input:40120500",+ prompt: PROMPT,+ requestId: "sess-test:0:limit:usage:0",});});- it("creates a token-cost continuation prompt", () => {+ it("carries a reported cost and omits an unreported one", () => {const request = createSessionLimitContinuationRequest({sessionId: "sess-test",+ total: { ...TOTAL, costUsd: 1.5123 },turnSequence: 0,- violation: { kind: "token-cost", limitUsd: 1.5, usedCostUsd: 1.5123 },+ window: WINDOW,+ windowIndex: 0,});- expect(request).toMatchObject({- action: {- callId: "sess-test:0:limit:token-cost:1.5123",- input: { kind: "token-cost", limitUsd: 1.5, usedCostUsd: 1.5123 },- },- prompt:- "This session has hit the $1.5 model token-cost limit per session. This is a guardrail " +- "against defective long-running sessions. If session activity looks fine, just " +- "approve to keep going.",- requestId: "sess-test:0:limit:token-cost:1.5123",- });+ expect(request.action.input).toEqual({ total: { ...TOTAL, costUsd: 1.5123 }, window: WINDOW });+ expect(request.action.input.window).not.toHaveProperty("costUsd");+ expect(request.prompt).toBe(PROMPT);});- it("formats the limit compactly in the prompt copy", () => {- const promptFor = (limit: number): string =>- createSessionLimitContinuationRequest({- sessionId: "sess-test",- turnSequence: 0,- violation: { kind: "input", limit, usedTokens: limit + 1 },- }).prompt;-- expect(promptFor(2_000_000)).toContain("(2M)");- expect(promptFor(1_872_014)).toContain("(1.9M)");- expect(promptFor(200_000)).toContain("(200K)");- expect(promptFor(1_500)).toContain("(1.5K)");- expect(promptFor(999)).toContain("(999)");-- const tinyCost = createSessionLimitContinuationRequest({+ it("gives each usage window its own id at the same usage", () => {+ const later = createSessionLimitContinuationRequest({sessionId: "sess-test",+ total: TOTAL,turnSequence: 0,- violation: { kind: "token-cost", limitUsd: 5e-7, usedCostUsd: 6e-7 },+ window: WINDOW,+ windowIndex: 1,});- expect(tinyCost.prompt).toContain("$5e-7 model token-cost limit");- expect(isSessionLimitContinuationRequestId(tinyCost.requestId)).toBe(true);++ expect(later.requestId).not.toBe(createTestRequest().requestId);});- it("gives each violation instance its own id as the session total grows", () => {- // The absolute total is strictly increasing across grants, so a stale- // response to an earlier prompt never resolves a later one.- const later = createSessionLimitContinuationRequest({+ it("tells the same usage apart across turns", () => {+ const nextTurn = createSessionLimitContinuationRequest({sessionId: "sess-test",- turnSequence: 0,- violation: { ...VIOLATION, usedTokens: 80_500_000 },+ total: TOTAL,+ turnSequence: 1,+ window: WINDOW,+ windowIndex: 0,});- expect(later.requestId).not.toBe(createTestRequest().requestId);+ expect(nextTurn.requestId).toBe("sess-test:1:limit:usage:0");});it("is recognized by isSessionLimitContinuationRequest", () => {@@ -116,10 +113,13 @@ describe("createSessionLimitContinuationRequest", () => {it("mints ids recognized by isSessionLimitContinuationRequestId", () => {expect(isSessionLimitContinuationRequestId(createTestRequest().requestId)).toBe(true);+ expect(isSessionLimitContinuationRequestId("s:0:limit:usage:5")).toBe(true);+ // Ids minted before the usage-window limit still resolve stale answers.+ expect(isSessionLimitContinuationRequestId("sess-test:0:limit:input:40120500")).toBe(true);expect(isSessionLimitContinuationRequestId("sess-test:0:limit:output:12")).toBe(true);expect(isSessionLimitContinuationRequestId("sess-test:0:limit:token-cost:1.5123")).toBe(true);expect(isSessionLimitContinuationRequestId("approval-1")).toBe(false);- expect(isSessionLimitContinuationRequestId("sess-test:0:limit:input:")).toBe(false);+ expect(isSessionLimitContinuationRequestId("sess-test:0:limit:usage:")).toBe(false);});});diff --git a/packages/eve/src/harness/hitl/budget-request.ts b/packages/eve/src/harness/hitl/budget-request.tsindex 53cbab539..c393d9003 100644--- a/packages/eve/src/harness/hitl/budget-request.ts+++ b/packages/eve/src/harness/hitl/budget-request.ts@@ -1,55 +1,46 @@/*** Deterministic HITL continuation prompt for session usage limits.*- * When a durable session reaches its configured token or token-cost budget, the harness+ * When a durable session reaches its usage limit, the harness* parks on a harness-authored input request instead of failing the session.- * The request is derived only from the session, turn, and violation, so+ * The request is derived only from the session, turn, and usage, so* identical session state always produces an identical prompt — no model call* is involved.*/import type { InputRequest, InputResponse } from "#shared/input.js";import type { JsonObject } from "#shared/json.js";-import type { SessionUsageLimitViolation } from "#harness/turn-tag-state.js";+import type { TokenUsage } from "#shared/token-usage.js";/** Synthetic action tool name carried by session-limit continuation requests. */const SESSION_LIMIT_CONTINUATION_TOOL_NAME = "session_limit_continuation";-/** Option id that grants a fresh token budget window. */+/** Option id that starts a new usage window. */const SESSION_LIMIT_CONTINUE_OPTION_ID = "continue";/** Option id that declines continuation and ends the session. */export const SESSION_LIMIT_STOP_OPTION_ID = "stop";/**- * Builds the deterministic continuation prompt for one session usage-limit- * violation.+ * Builds the deterministic continuation prompt for a session that reached its+ * usage limit.*/export function createSessionLimitContinuationRequest(input: {readonly sessionId: string;+ readonly total: TokenUsage;/** The turn's `sequence`, which tells its prompt apart from another turn's at the same usage. */readonly turnSequence: number;- readonly violation: SessionUsageLimitViolation;+ readonly window: TokenUsage;+ /** Which usage window the prompt is for; approving starts the next one. */+ readonly windowIndex: number;}): InputRequest {- const { sessionId, turnSequence, violation } = input;- const used = violation.kind === "token-cost" ? violation.usedCostUsd : violation.usedTokens;- // Re-raising an unanswered prompt within a turn keeps its id. Usage alone- // doesn't separate prompts across turns: after Stop the next turn is over- // budget at the same usage, and clients drop request ids they've seen. The- // sequence rather than the turn id keeps the id short enough for Discord's+ const { sessionId, total, turnSequence, window, windowIndex } = input;+ // Re-raising an unanswered prompt keeps its id; clients drop ids they've+ // seen, so each window and each turn gets its own. Usage can't tell windows+ // apart: a cost-only window leaves token counts unchanged. The sequence+ // rather than the turn id keeps the id short enough for Discord's// 100-character `custom_id`.- const requestId = `${sessionId}:${String(turnSequence)}:limit:${violation.kind}:${String(used)}`;- const actionInput: JsonObject =- violation.kind === "token-cost"- ? {- kind: violation.kind,- limitUsd: violation.limitUsd,- usedCostUsd: violation.usedCostUsd,- }- : {- kind: violation.kind,- limit: violation.limit,- usedTokens: violation.usedTokens,- };+ const requestId = `${sessionId}:${String(turnSequence)}:limit:usage:${String(windowIndex)}`;+ const actionInput: JsonObject = { total: toJsonUsage(total), window: toJsonUsage(window) };return {action: {@@ -63,10 +54,7 @@ export function createSessionLimitContinuationRequest(input: {kind: "session-limit",options: [{- description:- violation.kind === "token-cost"- ? "Grant a fresh model token-cost budget"- : "Grant a fresh token budget",+ description: "Start a new usage window",id: SESSION_LIMIT_CONTINUE_OPTION_ID,label: "Approve",style: "primary",@@ -78,46 +66,20 @@ export function createSessionLimitContinuationRequest(input: {style: "danger",},],- prompt: formatSessionLimitPrompt(violation),+ prompt: SESSION_LIMIT_PROMPT,requestId,};}-/**- * Formats a token count compactly for prompt copy: `2M`, `1.9M`, `200K`;- * exact below 1,000.- */-function formatCompactTokenCount(count: number): string {- if (count >= 1_000_000) {- return `${trimTrailingZero(count / 1_000_000)}M`;- }- if (count >= 1_000) {- return `${trimTrailingZero(count / 1_000)}K`;- }- return String(count);-}--function trimTrailingZero(value: number): string {- const rounded = value.toFixed(1);- return rounded.endsWith(".0") ? rounded.slice(0, -2) : rounded;+/** `usage` as JSON: an unreported cost is left out. */+export function toJsonUsage(usage: TokenUsage): JsonObject {+ const { costUsd, ...tokens } = usage;+ return costUsd === undefined ? tokens : { ...tokens, costUsd };}-function formatSessionLimitPrompt(violation: SessionUsageLimitViolation): string {- const reachedLimit =- violation.kind === "token-cost"- ? `${formatUsd(violation.limitUsd)} model token-cost limit per session`- : `${violation.kind}-token limit (${formatCompactTokenCount(violation.limit)}) per session`;- return (- `This session has hit the ${reachedLimit}. This is a guardrail ` +- `against defective long-running sessions. If session activity looks fine, ` +- `just approve to keep going.`- );-}--function formatUsd(costUsd: number): string {- const value = costUsd < 0.000001 ? String(costUsd) : costUsd.toFixed(6);- return `$${value.replace(/0+$/u, "").replace(/\.$/u, "")}`;-}+const SESSION_LIMIT_PROMPT =+ "This session has hit its usage limit. This is a guardrail against defective " ++ "long-running sessions. If session activity looks fine, just approve to keep going.";/*** Returns true when a request is a harness-authored session-limit@@ -136,7 +98,7 @@ export function isSessionLimitContinuationRequest(request: InputRequest): boolea*/export function isSessionLimitContinuationRequestId(requestId: string): boolean {return (- /:limit:(?:input|output):\d+$/u.test(requestId) ||+ /:limit:(?:usage|input|output):\d+$/u.test(requestId) ||/:limit:token-cost:\d+(?:\.\d+)?(?:e[+-]?\d+)?$/iu.test(requestId));}diff --git a/packages/eve/src/harness/hitl/budget.ts b/packages/eve/src/harness/hitl/budget.tsindex a91078b79..0883b95cc 100644--- a/packages/eve/src/harness/hitl/budget.ts+++ b/packages/eve/src/harness/hitl/budget.ts@@ -1,27 +1,39 @@/**- * Session token and token-cost limit policy for the tool-loop harness.+ * Session usage limit policy for the tool-loop harness.*- * Before each model call, {@link checkSessionUsageLimit} says whether the- * session may call the model. Over budget, a session that can request input- * asks whether to continue (the machine's `requestLimit`); one nobody can- * answer fails with `SESSION_TOKEN_LIMIT_REACHED`. The answer is the- * machine's `answer`: a grant bumps the runtime limits with- * {@link bumpSessionRuntimeUsageLimits}; a decline cancels the turn tree.+ * Before each model call, {@link checkSessionUsageLimit} asks the agent's+ * `limits.sessionUsage` whether the session may call the model. Over the+ * limit, a session that can request input asks whether to continue (the+ * machine's `requestLimit`); one nobody can answer fails with+ * `SESSION_USAGE_LIMIT_REACHED`. The answer is the machine's `answer`: a+ * grant starts a new usage window with `resetSessionUsageWindow`; a+ * decline cancels the turn tree.*/-import { createSessionLimitContinuationRequest } from "#harness/hitl/budget-request.js";import {- getSessionUsageLimitViolation,- getSessionTokenUsage,- type SessionUsageLimitViolation,+ createSessionLimitContinuationRequest,+ toJsonUsage,+} from "#harness/hitl/budget-request.js";+import {+ getSessionUsage,+ getSessionUsageWindow,+ getSessionUsageWindowIndex,} from "#harness/turn-tag-state.js";import type { HarnessSession } from "#harness/types.js";+import type { SessionUsageLimit } from "#shared/agent-definition.js";import type { InputRequest } from "#shared/input.js";import type { JsonObject } from "#shared/json.js";+import type { TokenUsage } from "#shared/token-usage.js";++const DEFAULT_MAX_NEW_INPUT_TOKENS_PER_WINDOW = 40_000_000;-export { bumpSessionRuntimeUsageLimits } from "#harness/turn-tag-state.js";+/**+ * The limit for agents that author none: 40M new input tokens per window. Cache reads are+ * replayed history, not new work, so only uncached input and cache writes count.+ */+export const DEFAULT_SESSION_USAGE_LIMIT: SessionUsageLimit = ({ window }) =>+ window.inputTokens - window.cacheReadTokens >= DEFAULT_MAX_NEW_INPUT_TOKENS_PER_WINDOW;-const SESSION_TOKEN_LIMIT_REACHED_CODE = "SESSION_TOKEN_LIMIT_REACHED";-const SESSION_TOKEN_COST_LIMIT_REACHED_CODE = "SESSION_TOKEN_COST_LIMIT_REACHED";+const SESSION_USAGE_LIMIT_REACHED_CODE = "SESSION_USAGE_LIMIT_REACHED";export type SessionUsageLimitCheck =| { readonly kind: "within" }@@ -36,57 +48,34 @@ export type SessionUsageLimitCheck =/** Whether the session may call the model, may ask to continue, or must fail. */export function checkSessionUsageLimit(input: {readonly canAsk: boolean;+ readonly limit: SessionUsageLimit;readonly session: HarnessSession;readonly turnSequence: number;}): SessionUsageLimitCheck {- const violation = getSessionUsageLimitViolation(input.session);- if (violation === null) return { kind: "within" };- // A zero limit is an exhausted quota inherited by a delegated task.- // Approving would bump the runtime limit by the configured limit -- zero --- // so fail the child and let its parent reach the resumable limit gate.- if (violationWindow(violation) > 0 && input.canAsk) {+ const total = getSessionUsage(input.session);+ const window = getSessionUsageWindow(input.session);+ // An empty window has nothing to judge, and approving could only start another empty one.+ if (isEmptyUsage(window) || !input.limit({ total, window })) return { kind: "within" };+ if (input.canAsk) {return {kind: "ask",request: createSessionLimitContinuationRequest({sessionId: input.session.sessionId,+ total,turnSequence: input.turnSequence,- violation,+ window,+ windowIndex: getSessionUsageWindowIndex(input.session),}),};}- const usage = getSessionTokenUsage(input.session);return {- code:- violation.kind === "token-cost"- ? SESSION_TOKEN_COST_LIMIT_REACHED_CODE- : SESSION_TOKEN_LIMIT_REACHED_CODE,- details:- violation.kind === "token-cost"- ? {- costUsd: usage.costUsd,- kind: violation.kind,- limitUsd: violation.limitUsd,- usedCostUsd: violation.usedCostUsd,- }- : {- cacheReadTokens: usage.cacheReadTokens,- inputTokens: usage.inputTokens,- kind: violation.kind,- limit: violation.limit,- outputTokens: usage.outputTokens,- usedTokens: violation.usedTokens,- },+ code: SESSION_USAGE_LIMIT_REACHED_CODE,+ details: { total: toJsonUsage(total), window: toJsonUsage(window) },kind: "fail",- message: formatSessionLimitMessage(violation.kind),+ message: "The session reached its usage limit.",};}-function violationWindow(violation: SessionUsageLimitViolation): number {- return violation.kind === "token-cost" ? violation.limitUsd : violation.limit;-}--function formatSessionLimitMessage(kind: SessionUsageLimitViolation["kind"]): string {- return kind === "token-cost"- ? "The session reached its configured model token-cost limit."- : `The session reached its configured ${kind} token limit.`;+function isEmptyUsage(usage: TokenUsage): boolean {+ return usage.inputTokens === 0 && usage.outputTokens === 0 && !usage.costUsd;}diff --git a/packages/eve/src/harness/hitl/index.ts b/packages/eve/src/harness/hitl/index.tsindex f2da537eb..8e879cf08 100644--- a/packages/eve/src/harness/hitl/index.ts+++ b/packages/eve/src/harness/hitl/index.ts@@ -24,7 +24,7 @@ import {requestLimit,requireSignIn,} from "./approvals.js";-import { checkSessionUsageLimit } from "./budget.js";+import { checkSessionUsageLimit, DEFAULT_SESSION_USAGE_LIMIT } from "./budget.js";import { retireActiveCandidates } from "./candidates.js";import { isEmptyInput } from "./delivery.js";import { holdForInput } from "./intake.js";@@ -116,6 +116,7 @@ export async function enforceBudget(): Promise<StepResult | undefined> {const limit = checkSessionUsageLimit({canAsk: step.emit !== undefined && step.config.capabilities?.requestInput === true,+ limit: step.config.sessionUsageLimit ?? DEFAULT_SESSION_USAGE_LIMIT,session: step.session,turnSequence: step.position().sequence,});diff --git a/packages/eve/src/harness/hitl/intake.ts b/packages/eve/src/harness/hitl/intake.tsindex 316af353c..653c92004 100644--- a/packages/eve/src/harness/hitl/intake.ts+++ b/packages/eve/src/harness/hitl/intake.ts@@ -14,7 +14,7 @@ import type { SessionView, SuspendedStep } from "#harness/session-machine/view.jimport { signInAttemptKey } from "#harness/hitl/sign-ins.js";import type { Step } from "#harness/step/context.js";import { SessionLimitDeclinedError, throwIfTurnAborted } from "#harness/turn-cancellation.js";-import { bumpSessionRuntimeUsageLimits } from "#harness/turn-tag-state.js";+import { resetSessionUsageWindow } from "#harness/turn-tag-state.js";import type { HarnessToolLookup, StepInput, StepResult } from "#harness/types.js";import type { RuntimeWorkflowTaskRequest } from "#shared/action-types.js";import {@@ -213,13 +213,13 @@ export async function acceptHumanInput(}/**- * Admits what a delivery decided before its turn calls the model: a session-limit answer grants a- * fresh budget or ends the turn tree, and a step its answers completed, as denials do, commits.+ * Admits what a delivery decided before its turn calls the model: a session-limit answer starts a+ * new usage window or ends the turn tree, and a step its answers completed, as denials do, commits.*/export async function admitApprovedWork(step: Step, work: ApprovedWork): Promise<void> {if (work.limit !== undefined) {if (!work.limit.granted) throw new SessionLimitDeclinedError();- step.session = bumpSessionRuntimeUsageLimits(step.session);+ step.session = resetSessionUsageWindow(step.session);}await step.apply(settle(step.view(), { results: [] }));}diff --git a/packages/eve/src/harness/input-request-class.test.ts b/packages/eve/src/harness/input-request-class.test.tsindex 8848dc3a9..c7b5c4897 100644--- a/packages/eve/src/harness/input-request-class.test.ts+++ b/packages/eve/src/harness/input-request-class.test.ts@@ -40,8 +40,10 @@ describe("isApprovalRequest", () => {isApprovalRequest(createSessionLimitContinuationRequest({sessionId: "sess-test",+ total: { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 12, outputTokens: 0 },turnSequence: 0,- violation: { kind: "input", limit: 12, usedTokens: 12 },+ window: { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 12, outputTokens: 0 },+ windowIndex: 0,}),),).toBe(false);diff --git a/packages/eve/src/harness/issue-3494-adversarial.integration.test.ts b/packages/eve/src/harness/issue-3494-adversarial.integration.test.tsindex f6d405da0..86dd3af5b 100644--- a/packages/eve/src/harness/issue-3494-adversarial.integration.test.ts+++ b/packages/eve/src/harness/issue-3494-adversarial.integration.test.ts@@ -60,7 +60,6 @@ function fixture(continuationToken: name,sessionId: name,history: [],- limits: outputLimit === undefined ? undefined : { maxOutputTokensPerSession: outputLimit },outputSchema,};const model = new MockLanguageModelV4({@@ -178,6 +177,8 @@ function fixture(capabilities: { requestInput: true },tools,resolveModel: async () => model,+ sessionUsageLimit:+ outputLimit === undefined ? undefined : ({ window }) => window.outputTokens >= outputLimit,handleEvent: async (event) => {events.push(event);recorder.record(event);@@ -446,7 +447,8 @@ it("reaches the next budget prompt after a grant without an older approval [contawait f.drive(f.respond("session_limit_continuation", "continue"));expect(f.executions).toEqual(["read"]);expect(f.pending().map((r) => r.kind)).toEqual(["session-limit"]);- expect(f.pending()[0]?.requestId).toContain(":output:2");+ // The grant started the second usage window.+ expect(f.pending()[0]?.requestId).toMatch(/:limit:usage:1$/u);});for (const pending of [true, false]) {diff --git a/packages/eve/src/harness/session-machine/machine.test.ts b/packages/eve/src/harness/session-machine/machine.test.tsindex 457d4c127..b8b3fbd36 100644--- a/packages/eve/src/harness/session-machine/machine.test.ts+++ b/packages/eve/src/harness/session-machine/machine.test.ts@@ -681,8 +681,10 @@ describe("answers", () => {describe("the session-limit prompt", () => {const request = createSessionLimitContinuationRequest({sessionId: "session-test",+ total: { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 101, outputTokens: 0 },turnSequence: 1,- violation: { kind: "input", limit: 100, usedTokens: 101 },+ window: { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 101, outputTokens: 0 },+ windowIndex: 0,});async function exhausted() {diff --git a/packages/eve/src/harness/session-usage-limits.test.ts b/packages/eve/src/harness/session-usage-limits.test.tsdeleted file mode 100644index 37bde419a..000000000--- a/packages/eve/src/harness/session-usage-limits.test.ts+++ /dev/null@@ -1,105 +0,0 @@-import { describe, expect, it } from "vitest";--import {- findRuntimeUsageLimitViolation,- grantRuntimeUsageLimits,- remainingRuntimeUsageQuota,- resolveRuntimeUsageLimits,-} from "#harness/session-usage-limits.js";--const CONFIGURED = { costUsd: 1.5, inputTokens: 100, outputTokens: 50 };--describe("session usage-limit transitions", () => {- it.each([- { configured: {}, expected: {}, stored: undefined },- { configured: CONFIGURED, expected: CONFIGURED, stored: undefined },- {- configured: CONFIGURED,- expected: { costUsd: 3, inputTokens: 250, outputTokens: 50 },- stored: { costUsd: 3, inputTokens: 250 },- },- ])("resolves configured and granted ceilings", ({ configured, expected, stored }) => {- expect(resolveRuntimeUsageLimits({ configured, stored })).toEqual(expected);- });-- it.each([- {- configured: CONFIGURED,- expected: { costUsd: 1.5, inputTokens: 100, outputTokens: 50 },- usage: { costUsd: 0, inputTokens: 0, outputTokens: 0 },- },- {- configured: CONFIGURED,- expected: { costUsd: 3.25, inputTokens: 450, outputTokens: 170 },- usage: { costUsd: 1.75, inputTokens: 350, outputTokens: 120 },- },- {- configured: { inputTokens: 100 },- expected: { inputTokens: 140 },- usage: { inputTokens: 40, outputTokens: 999 },- },- ])("grants one full window from current usage", ({ configured, expected, usage }) => {- expect(grantRuntimeUsageLimits({ configured, usage })).toEqual(expected);- });-- it.each([- {- expected: { costUsd: false, inputTokens: false, outputTokens: false },- runtime: {},- usage: { costUsd: 2, inputTokens: 1_000, outputTokens: 1_000 },- },- {- expected: { costUsd: 1, inputTokens: 60, outputTokens: 40 },- runtime: CONFIGURED,- usage: { costUsd: 0.5, inputTokens: 40, outputTokens: 10 },- },- {- expected: { costUsd: 0, inputTokens: 0, outputTokens: 0 },- runtime: CONFIGURED,- usage: { costUsd: 2, inputTokens: 150, outputTokens: 80 },- },- ])("computes remaining quota without negative values", ({ expected, runtime, usage }) => {- expect(remainingRuntimeUsageQuota({ runtime, usage })).toEqual(expected);- });-- it.each([- {- configured: CONFIGURED,- expected: null,- runtime: CONFIGURED,- usage: { costUsd: 1.49, inputTokens: 99, outputTokens: 49 },- },- {- configured: CONFIGURED,- expected: { kind: "input", limit: 100, usedTokens: 100 },- runtime: CONFIGURED,- usage: { costUsd: 1.5, inputTokens: 100, outputTokens: 50 },- },- {- configured: CONFIGURED,- expected: { kind: "output", limit: 50, usedTokens: 50 },- runtime: CONFIGURED,- usage: { costUsd: 1.5, inputTokens: 0, outputTokens: 50 },- },- {- configured: { costUsd: 1.5 },- expected: { kind: "token-cost", limitUsd: 1.5, usedCostUsd: 1.5 },- runtime: { costUsd: 1.5 },- usage: { costUsd: 1.5, inputTokens: 0, outputTokens: 0 },- },- {- configured: { inputTokens: 0 },- expected: { kind: "input", limit: 0, usedTokens: 0 },- runtime: { inputTokens: 0 },- usage: { inputTokens: 0, outputTokens: 0 },- },- {- configured: CONFIGURED,- expected: { kind: "input", limit: 100, usedTokens: 200 },- runtime: { costUsd: 3, inputTokens: 200, outputTokens: 100 },- usage: { costUsd: 2, inputTokens: 200, outputTokens: 0 },- },- ])("finds the first exhausted axis", ({ configured, expected, runtime, usage }) => {- expect(findRuntimeUsageLimitViolation({ configured, runtime, usage })).toEqual(expected);- });-});diff --git a/packages/eve/src/harness/session-usage-limits.ts b/packages/eve/src/harness/session-usage-limits.tsdeleted file mode 100644index 23861b723..000000000--- a/packages/eve/src/harness/session-usage-limits.ts+++ /dev/null@@ -1,128 +0,0 @@-interface SessionUsageAmounts {- readonly costUsd?: number;- readonly inputTokens: number;- readonly outputTokens: number;-}--export interface SessionRuntimeUsageLimits {- readonly costUsd?: number;- readonly inputTokens?: number;- readonly outputTokens?: number;-}--export type SessionUsageLimitViolation =- | {- readonly kind: "input";- readonly limit: number;- readonly usedTokens: number;- }- | {- readonly kind: "output";- readonly limit: number;- readonly usedTokens: number;- }- | {- readonly kind: "token-cost";- readonly limitUsd: number;- readonly usedCostUsd: number;- };--/** Resolves per-axis lifetime ceilings, preferring a previously granted ceiling. */-export function resolveRuntimeUsageLimits(input: {- readonly configured: SessionRuntimeUsageLimits;- readonly stored?: SessionRuntimeUsageLimits;-}): SessionRuntimeUsageLimits {- const limits: { costUsd?: number; inputTokens?: number; outputTokens?: number } = {};- const inputTokens = input.stored?.inputTokens ?? input.configured.inputTokens;- if (inputTokens !== undefined) limits.inputTokens = inputTokens;- const outputTokens = input.stored?.outputTokens ?? input.configured.outputTokens;- if (outputTokens !== undefined) limits.outputTokens = outputTokens;- const costUsd = input.stored?.costUsd ?? input.configured.costUsd;- if (costUsd !== undefined) limits.costUsd = costUsd;- return limits;-}--/** Grants one full configured window from the current lifetime usage. */-export function grantRuntimeUsageLimits(input: {- readonly configured: SessionRuntimeUsageLimits;- readonly usage: SessionUsageAmounts;-}): SessionRuntimeUsageLimits {- const limits: { costUsd?: number; inputTokens?: number; outputTokens?: number } = {};- if (input.configured.inputTokens !== undefined) {- limits.inputTokens = input.usage.inputTokens + input.configured.inputTokens;- }- if (input.configured.outputTokens !== undefined) {- limits.outputTokens = input.usage.outputTokens + input.configured.outputTokens;- }- if (input.configured.costUsd !== undefined) {- limits.costUsd = (input.usage.costUsd ?? 0) + input.configured.costUsd;- }- return limits;-}--/** Returns the unspent quota for each capped axis. */-export function remainingRuntimeUsageQuota(input: {- readonly runtime: SessionRuntimeUsageLimits;- readonly usage: SessionUsageAmounts;-}): {- readonly costUsd: number | false;- readonly inputTokens: number | false;- readonly outputTokens: number | false;-} {- return {- costUsd:- input.runtime.costUsd === undefined- ? false- : Math.max(0, input.runtime.costUsd - (input.usage.costUsd ?? 0)),- inputTokens:- input.runtime.inputTokens === undefined- ? false- : Math.max(0, input.runtime.inputTokens - input.usage.inputTokens),- outputTokens:- input.runtime.outputTokens === undefined- ? false- : Math.max(0, input.runtime.outputTokens - input.usage.outputTokens),- };-}--/** Returns the first exhausted axis: input tokens, output tokens, then token cost. */-export function findRuntimeUsageLimitViolation(input: {- readonly configured: SessionRuntimeUsageLimits;- readonly runtime: SessionRuntimeUsageLimits;- readonly usage: SessionUsageAmounts;-}): SessionUsageLimitViolation | null {- if (- input.runtime.inputTokens !== undefined &&- input.configured.inputTokens !== undefined &&- input.usage.inputTokens >= input.runtime.inputTokens- ) {- return {- kind: "input",- limit: input.configured.inputTokens,- usedTokens: input.usage.inputTokens,- };- }- if (- input.runtime.outputTokens !== undefined &&- input.configured.outputTokens !== undefined &&- input.usage.outputTokens >= input.runtime.outputTokens- ) {- return {- kind: "output",- limit: input.configured.outputTokens,- usedTokens: input.usage.outputTokens,- };- }- if (- input.runtime.costUsd !== undefined &&- input.configured.costUsd !== undefined &&- (input.usage.costUsd ?? 0) >= input.runtime.costUsd- ) {- return {- kind: "token-cost",- limitUsd: input.configured.costUsd,- usedCostUsd: input.usage.costUsd ?? 0,- };- }- return null;-}diff --git a/packages/eve/src/harness/tool-loop-generate-approval-resume.integration.test.ts b/packages/eve/src/harness/tool-loop-generate-approval-resume.integration.test.tsindex 07b712f87..d608ef83f 100644--- a/packages/eve/src/harness/tool-loop-generate-approval-resume.integration.test.ts+++ b/packages/eve/src/harness/tool-loop-generate-approval-resume.integration.test.ts@@ -958,6 +958,7 @@ describe("tool loop generate approval resume (real AI SDK)", () => {...createConfig(model, execute),capabilities: { requestInput: true },handleEvent: async () => {},+ sessionUsageLimit: ({ window }) => window.inputTokens >= 12,} satisfies ToolLoopHarnessConfig;const usageState = {cacheReadTokens: 0,@@ -967,13 +968,11 @@ describe("tool loop generate approval resume (real AI SDK)", () => {outputTokens: 3,sawCost: false,};- const session = setTurnUsageState(- {- ...createPendingApprovalSession(),- limits: { maxInputTokensPerSession: 12 },- },- { ...usageState, session: usageState, turnId: "turn_previous" },- );+ const session = setTurnUsageState(createPendingApprovalSession(), {+ ...usageState,+ session: usageState,+ turnId: "turn_previous",+ });const runStep = createToolLoopHarness(config);const limited = await runStep(session, {diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.tsindex fad0c3a2a..8d8466f63 100644--- a/packages/eve/src/harness/tool-loop.test.ts+++ b/packages/eve/src/harness/tool-loop.test.ts@@ -41,6 +41,7 @@ import { defineInstructions } from "#public/definitions/instructions.js";import type { ResolvedDynamicInstructionsResolver } from "#runtime/types.js";import type { DynamicResolveContext } from "#dynamic/definition.js";import { registerDurableDynamicCallback } from "#tools/durable-callbacks.js";+import type { SessionUsageLimit } from "#shared/agent-definition.js";import type { ChannelAudience } from "#shared/channel-audience.js";import {ConversationContextKey,@@ -77,8 +78,9 @@ import { createToolLoopHarness } from "#harness/tool-loop.js";import { createTask, writeTaskTable } from "#execution/tasks/table.js";import { SessionLimitDeclinedError, TurnCancelledError } from "#harness/turn-cancellation.js";import {- getSessionUsageLimitViolation,getSessionTokenUsage,+ getSessionUsage,+ getSessionUsageWindow,setTurnUsageState,} from "#harness/turn-tag-state.js";import type { HarnessEmitFn, HarnessSession, ToolLoopHarnessConfig } from "#harness/types.js";@@ -1984,112 +1986,99 @@ describe("createToolLoopHarness", () => {});});- it.each([- {- // The limit counts new input (14 minus 2 cache reads); details keep the raw totals.- details: {- cacheReadTokens: 2,- inputTokens: 14,- kind: "input",- limit: 12,- outputTokens: 3,- usedTokens: 12,- },- message: "The session reached its configured input token limit.",- limits: {- maxInputTokensPerSession: 12,- },- usage: {- cacheReadTokens: 2,- cacheWriteTokens: 1,- costUsd: 0,- inputTokens: 14,- outputTokens: 3,- sawCost: false,- },- errorCode: "SESSION_TOKEN_LIMIT_REACHED",- tokenKind: "input",- },- {- details: {- inputTokens: 7,- kind: "output",- limit: 3,- outputTokens: 3,- usedTokens: 3,- },- message: "The session reached its configured output token limit.",- limits: {- maxOutputTokensPerSession: 3,- },- usage: {- cacheReadTokens: 2,- cacheWriteTokens: 1,- costUsd: 0,- inputTokens: 7,- outputTokens: 3,- sawCost: false,- },- errorCode: "SESSION_TOKEN_LIMIT_REACHED",- tokenKind: "output",- },- {- details: {- costUsd: 1.51,- kind: "token-cost",- limitUsd: 1.5,- usedCostUsd: 1.51,- },- message: "The session reached its configured model token-cost limit.",- limits: {- maxTokenCostUsdPerSession: 1.5,- },- usage: {- cacheReadTokens: 2,- cacheWriteTokens: 1,- costUsd: 1.51,- inputTokens: 7,- outputTokens: 3,- sawCost: true,- },- errorCode: "SESSION_TOKEN_COST_LIMIT_REACHED",- tokenKind: "model token-cost",- },- ])(- "fails fast after the $tokenKind limit when the session cannot request input",- async (testCase) => {- const { emit, events } = createEventCollector();- const runStep = createToolLoopHarness(createTestConfig(emit, { capabilities: undefined }));- const session = setTurnUsageState(createTestSession({ limits: testCase.limits }), {- turnId: "turn_previous",- ...testCase.usage,- session: testCase.usage,- });+ // A limit that trips once the window holds 12 new input tokens (cache reads excluded).+ const TWELVE_NEW_INPUT_TOKENS: SessionUsageLimit = ({ window }) =>+ window.inputTokens - window.cacheReadTokens >= 12;- const result = await runStep(session, { message: "Hi again" });+ it("fails fast past the usage limit when the session cannot request input", async () => {+ const { emit, events } = createEventCollector();+ const runStep = createToolLoopHarness(+ createTestConfig(emit, {+ capabilities: undefined,+ sessionUsageLimit: TWELVE_NEW_INPUT_TOKENS,+ }),+ );+ // 14 input tokens of which 2 are cache reads: 12 new input tokens.+ const usage = {+ cacheReadTokens: 2,+ cacheWriteTokens: 1,+ costUsd: 0,+ inputTokens: 14,+ outputTokens: 3,+ sawCost: false,+ };+ const session = setTurnUsageState(createTestSession(), {+ turnId: "turn_previous",+ ...usage,+ session: usage,+ });- expect(vi.mocked(ToolLoopAgent)).not.toHaveBeenCalled();- expect(result.next).toEqual({ done: true, output: "" });- expect(events.map((event) => event.type)).toEqual([- "session.started",- "turn.started",- "message.received",- "step.started",- "step.failed",- "turn.failed",- "session.failed",- ]);- expect(events.find((event) => event.type === "step.failed")?.data).toMatchObject({- code: testCase.errorCode,- details: testCase.details,- message: testCase.message,- });- },- );+ const result = await runStep(session, { message: "Hi again" });++ expect(vi.mocked(ToolLoopAgent)).not.toHaveBeenCalled();+ expect(result.next).toEqual({ done: true, output: "" });+ expect(events.map((event) => event.type)).toEqual([+ "session.started",+ "turn.started",+ "message.received",+ "step.started",+ "step.failed",+ "turn.failed",+ "session.failed",+ ]);+ // Details keep the raw totals; an unreported cost is left out.+ const reported = { cacheReadTokens: 2, cacheWriteTokens: 1, inputTokens: 14, outputTokens: 3 };+ expect(events.find((event) => event.type === "step.failed")?.data).toMatchObject({+ code: "SESSION_USAGE_LIMIT_REACHED",+ details: { total: reported, window: reported },+ message: "The session reached its usage limit.",+ });+ expect(+ events.find((event) => event.type === "step.failed")?.data.details?.total,+ ).not.toHaveProperty("costUsd");+ });++ it("hands the limit the session total and the usage window", async () => {+ const { emit } = createEventCollector();+ const sessionUsageLimit = vi.fn<SessionUsageLimit>(() => false);+ const runStep = createToolLoopHarness(createTestConfig(emit, { sessionUsageLimit }));+ setupMockAgent({+ finishReason: "stop",+ response: { messages: [{ content: "Hello!", role: "assistant" }] },+ text: "Hello!",+ toolCalls: [],+ toolResults: [],+ });+ const usage = {+ cacheReadTokens: 2,+ cacheWriteTokens: 1,+ costUsd: 0.5,+ inputTokens: 14,+ outputTokens: 3,+ sawCost: true,+ };+ const session = setTurnUsageState(createTestSession(), {+ turnId: "turn_previous",+ ...usage,+ session: usage,+ });++ await runStep(session, { message: "Hi again" });++ const expected = {+ cacheReadTokens: 2,+ cacheWriteTokens: 1,+ costUsd: 0.5,+ inputTokens: 14,+ outputTokens: 3,+ };+ expect(sessionUsageLimit).toHaveBeenCalledWith({ total: expected, window: expected });+ expect(vi.mocked(ToolLoopAgent)).toHaveBeenCalledTimes(1);+ });// Session state with 12 input tokens already spent against a 12-token- // budget: the next model call is over the limit. The matching continuation- // request id is `test-session:limit:input:12` (absolute total = 12).+ // window: the next model call is over the limit. The matching continuation+ // request id is `test-session:0:limit:usage:0` (the first usage window).function createLimitReachedSession(): HarnessSession {const usage = {cacheReadTokens: 0,@@ -2099,18 +2088,25 @@ describe("createToolLoopHarness", () => {outputTokens: 3,sawCost: false,};- return setTurnUsageState(createTestSession({ limits: { maxInputTokensPerSession: 12 } }), {+ return setTurnUsageState(createTestSession(), {turnId: "turn_previous",...usage,session: usage,});}- const LIMIT_REQUEST_ID = "test-session:0:limit:input:12";+ function createLimitedConfig(emit?: HarnessEmitFn): ToolLoopHarnessConfig {+ return createTestConfig(emit, { sessionUsageLimit: TWELVE_NEW_INPUT_TOKENS });+ }- it("parks on a deterministic continuation prompt when the session reaches its token limit", async () => {+ const LIMIT_REQUEST_ID = "test-session:0:limit:usage:0";+ const LIMIT_PROMPT =+ "This session has hit its usage limit. This is a guardrail against defective " ++ "long-running sessions. If session activity looks fine, just approve to keep going.";++ it("parks on a deterministic continuation prompt when the session reaches its usage limit", async () => {const { emit, events } = createEventCollector();- const runStep = createToolLoopHarness(createTestConfig(emit));+ const runStep = createToolLoopHarness(createLimitedConfig(emit));const result = await runStep(createLimitReachedSession(), { message: "Hi again" });@@ -2126,12 +2122,13 @@ describe("createToolLoopHarness", () => {"turn.waiting",]);const requested = events.find((event) => event.type === "input.requested");+ const reported = { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 12, outputTokens: 3 };expect(requested?.data).toMatchObject({requests: [{action: {callId: LIMIT_REQUEST_ID,- input: { kind: "input", limit: 12, usedTokens: 12 },+ input: { total: reported, window: reported },kind: "tool-call",toolName: "session_limit_continuation",},@@ -2142,13 +2139,14 @@ describe("createToolLoopHarness", () => {{ id: "continue", label: "Approve", style: "primary" },{ id: "stop", label: "Stop", style: "danger" },],+ prompt: LIMIT_PROMPT,requestId: LIMIT_REQUEST_ID,},],});});- it("parks and grants a fresh model token-cost budget", async () => {+ it("parks on a cost limit and starts a new window on continue", async () => {const usage = {cacheReadTokens: 0,cacheWriteTokens: 0,@@ -2157,22 +2155,25 @@ describe("createToolLoopHarness", () => {outputTokens: 3,sawCost: true,};- const reached = setTurnUsageState(- createTestSession({ limits: { maxTokenCostUsdPerSession: 1.5 } }),- { turnId: "turn_previous", ...usage, session: usage },- );+ const reached = setTurnUsageState(createTestSession(), {+ turnId: "turn_previous",+ ...usage,+ session: usage,+ });const { emit, events } = createEventCollector();- const runStep = createToolLoopHarness(createTestConfig(emit));+ const runStep = createToolLoopHarness(+ createTestConfig(emit, { sessionUsageLimit: ({ window }) => (window.costUsd ?? 0) >= 1.5 }),+ );const parked = await runStep(reached, { message: "Hi again" });expect(events.find((event) => event.type === "input.requested")?.data).toMatchObject({requests: [{action: {- input: { kind: "token-cost", limitUsd: 1.5, usedCostUsd: 1.51 },+ input: { total: { costUsd: 1.51 }, window: { costUsd: 1.51 } },},- prompt: expect.stringContaining("$1.5 model token-cost limit"),- requestId: "test-session:0:limit:token-cost:1.51",+ prompt: LIMIT_PROMPT,+ requestId: LIMIT_REQUEST_ID,},],});@@ -2185,14 +2186,16 @@ describe("createToolLoopHarness", () => {toolResults: [],});const resumed = await runStep(parked.session, {- inputResponses: [{ optionId: "continue", requestId: "test-session:0:limit:token-cost:1.51" }],+ inputResponses: [{ optionId: "continue", requestId: LIMIT_REQUEST_ID }],});expect(vi.mocked(ToolLoopAgent)).toHaveBeenCalledTimes(1);- expect(getSessionUsageLimitViolation(resumed.session)).toBeNull();+ // The total keeps the spend; the window restarted at the grant.+ expect(getSessionUsage(resumed.session)).toMatchObject({ costUsd: 1.51, inputTokens: 12 });+ expect(getSessionUsageWindow(resumed.session)).toMatchObject({ costUsd: 0, inputTokens: 0 });});- it("grants a fresh token budget when the user continues past the limit prompt", async () => {+ it("starts a new usage window when the user continues past the limit prompt", async () => {setupMockAgent({finishReason: "stop",response: { messages: [{ content: "Hello!", role: "assistant" }] },@@ -2202,7 +2205,7 @@ describe("createToolLoopHarness", () => {usage: { inputTokens: 7, outputTokens: 3 },});const { emit, events } = createEventCollector();- const runStep = createToolLoopHarness(createTestConfig(emit));+ const runStep = createToolLoopHarness(createLimitedConfig(emit));const parked = await runStep(createLimitReachedSession(), { message: "Hi again" });expect(vi.mocked(ToolLoopAgent)).not.toHaveBeenCalled();@@ -2213,7 +2216,12 @@ describe("createToolLoopHarness", () => {expect(vi.mocked(ToolLoopAgent)).toHaveBeenCalledTimes(1);expect(resumed.next).toBeNull();- expect(getSessionUsageLimitViolation(resumed.session)).toBeNull();+ // The window holds only the resumed call's spend; the total has both.+ expect(getSessionUsageWindow(resumed.session)).toMatchObject({+ inputTokens: 7,+ outputTokens: 3,+ });+ expect(getSessionUsage(resumed.session)).toMatchObject({ inputTokens: 19, outputTokens: 6 });// The parked user message survives into model history for the resumed call.expect(resumed.session.history).toContainEqual({content: "Hi again",@@ -2240,7 +2248,7 @@ describe("createToolLoopHarness", () => {).toBeGreaterThan(resolutionIndex);});- it("grants the budget when the user types the continue option as plain text", async () => {+ it("starts a new window when the user types the continue option as plain text", async () => {setupMockAgent({finishReason: "stop",response: { messages: [{ content: "Hello!", role: "assistant" }] },@@ -2250,7 +2258,7 @@ describe("createToolLoopHarness", () => {usage: { inputTokens: 7, outputTokens: 3 },});const { emit } = createEventCollector();- const runStep = createToolLoopHarness(createTestConfig(emit));+ const runStep = createToolLoopHarness(createLimitedConfig(emit));const parked = await runStep(createLimitReachedSession(), { message: "Hi again" });@@ -2260,12 +2268,12 @@ describe("createToolLoopHarness", () => {expect(vi.mocked(ToolLoopAgent)).toHaveBeenCalledTimes(1);expect(resumed.next).toBeNull();- expect(getSessionUsageLimitViolation(resumed.session)).toBeNull();+ expect(getSessionUsageWindow(resumed.session)).toMatchObject({ inputTokens: 7 });});it("cancels the turn when the user declines the limit continuation prompt", async () => {const { emit, events } = createEventCollector();- const runStep = createToolLoopHarness(createTestConfig(emit));+ const runStep = createToolLoopHarness(createLimitedConfig(emit));const parked = await runStep(createLimitReachedSession(), { message: "Hi again" });const declined = runStep(parked.session, {@@ -2283,15 +2291,25 @@ describe("createToolLoopHarness", () => {expect(events.some((event) => event.type === "session.completed")).toBe(false);});- it("fails a zero-budget session instead of raising a continuation that cannot grant tokens", async () => {+ it("does not consult the limit before the session spent anything", async () => {+ setupMockAgent({+ finishReason: "stop",+ response: { messages: [{ content: "Hello!", role: "assistant" }] },+ text: "Hello!",+ toolCalls: [],+ toolResults: [],+ usage: { inputTokens: 7, outputTokens: 3 },+ });const { emit, events } = createEventCollector();- const runStep = createToolLoopHarness(createTestConfig(emit));- const session = createTestSession({ limits: { maxInputTokensPerSession: 0 } });+ const sessionUsageLimit = vi.fn<SessionUsageLimit>(() => true);+ const runStep = createToolLoopHarness(createTestConfig(emit, { sessionUsageLimit }));- const result = await runStep(session, { message: "Hi again" });+ // An empty window has nothing to judge, and approving could only start another empty one.+ const result = await runStep(createTestSession(), { message: "Hi again" });- expect(vi.mocked(ToolLoopAgent)).not.toHaveBeenCalled();- expect(result.next).toEqual({ done: true, output: "" });+ expect(sessionUsageLimit).not.toHaveBeenCalled();+ expect(vi.mocked(ToolLoopAgent)).toHaveBeenCalledTimes(1);+ expect(result.next).toBeNull();expect(events.some((event) => event.type === "input.requested")).toBe(false);});@@ -2305,7 +2323,7 @@ describe("createToolLoopHarness", () => {usage: { inputTokens: 7, outputTokens: 3 },});const { emit, events } = createEventCollector();- const runStep = createToolLoopHarness(createTestConfig(emit));+ const runStep = createToolLoopHarness(createLimitedConfig(emit));const parked = await runStep(createLimitReachedSession(), { message: "Hi again" });const beforeQueued = events.length;@@ -2349,7 +2367,7 @@ describe("createToolLoopHarness", () => {usage: { inputTokens: 7, outputTokens: 3 },});const { emit, events } = createEventCollector();- const runStep = createToolLoopHarness(createTestConfig(emit));+ const runStep = createToolLoopHarness(createLimitedConfig(emit));const parked = await runStep(createLimitReachedSession(), { message: "Hi again" });// Before this change requestLimit published input.requested followed by@@ -2389,7 +2407,7 @@ describe("createToolLoopHarness", () => {data: { resolutions: [{ requestId: LIMIT_REQUEST_ID, outcome: "answered" }] },});expect(vi.mocked(ToolLoopAgent)).toHaveBeenCalledTimes(1);- expect(getSessionUsageLimitViolation(resumed.session)).toBeNull();+ expect(getSessionUsageWindow(resumed.session)).toMatchObject({ inputTokens: 7 });expect(resumed.session.history.filter((message) => message.content === "also do this other thing"),).toHaveLength(1);@@ -8358,7 +8376,6 @@ describe("createToolLoopHarness", () => {}),);const state = { retained: "yes" };- const limits = { maxInputTokensPerSession: 1_000 };const outputSchema = { type: "string" };const session = createTestSession({compaction: {@@ -8372,7 +8389,6 @@ describe("createToolLoopHarness", () => {{ content: "Dynamic user instructions.", kind: "user" as const, role: "user" },{ content: "old reply", role: "assistant" },],- limits,outputSchema,state,});@@ -8385,7 +8401,6 @@ describe("createToolLoopHarness", () => {compaction: { recentWindowSize: 10, threshold: 100_000 },continuationToken: session.continuationToken,history: [],- limits,outputSchema,sessionId: session.sessionId,state,diff --git a/packages/eve/src/harness/turn-tag-state.test.ts b/packages/eve/src/harness/turn-tag-state.test.tsindex 243418e6f..698e9d652 100644--- a/packages/eve/src/harness/turn-tag-state.test.ts+++ b/packages/eve/src/harness/turn-tag-state.test.ts@@ -1,20 +1,21 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";+import { checkSessionUsageLimit, DEFAULT_SESSION_USAGE_LIMIT } from "#harness/hitl/budget.js";import { extractTokenUsageDelta } from "#harness/model-call/usage.js";import type { HarnessStepResult } from "#harness/step-hooks.js";import {accumulateSessionUsage,accumulateTurnUsage,addTurnUsage,- bumpSessionRuntimeUsageLimits,- getSessionRemainingUsageQuota,- getSessionRuntimeUsageLimits,- getSessionUsageLimitViolation,getSessionTokenUsage,+ getSessionUsage,+ getSessionUsageWindow,getTurnUsageState,+ resetSessionUsageWindow,setTurnUsageState,} from "#harness/turn-tag-state.js";import type { HarnessSession } from "#harness/types.js";+import type { SessionUsageLimit } from "#shared/agent-definition.js";const ZERO_SESSION_USAGE = {cacheReadTokens: 0,@@ -292,196 +293,212 @@ describe("session state round-trip", () => {});});-describe("session token limits", () => {+describe("session usage limit", () => {it("reads zero session usage before token state exists", () => {expect(getSessionTokenUsage(makeSession())).toEqual(ZERO_SESSION_USAGE);- });-- it.each([- {- expected: { kind: "input", limit: 10, usedTokens: 10 },- limits: { maxInputTokensPerSession: 10 },- },- {- expected: { kind: "output", limit: 3, usedTokens: 3 },- limits: { maxOutputTokensPerSession: 3 },- },- ])("reports the first exhausted $expected.kind limit", (testCase) => {- const session = setTurnUsageState(makeSession(), {- turnId: "turn_0",+ expect(getSessionUsageWindow(makeSession())).toEqual({cacheReadTokens: 0,cacheWriteTokens: 0,- costUsd: 0,- inputTokens: 10,- outputTokens: 3,- sawCost: false,- session: {- cacheReadTokens: 0,- cacheWriteTokens: 0,- costUsd: 0,- inputTokens: 10,- outputTokens: 3,- sawCost: false,- },+ costUsd: undefined,+ inputTokens: 0,+ outputTokens: 0,});+ });- expect(getSessionUsageLimitViolation({ ...session, limits: testCase.limits })).toEqual(- testCase.expected,+ function sessionAfterStep(+ usage: Partial<NonNullable<HarnessStepResult["usage"]>>,+ session: HarnessSession = makeSession(),+ turnId = "turn_0",+ ) {+ return addTurnUsage(+ session,+ turnId,+ extractTokenUsageDelta({+ costUsd: undefined,+ usage: usage as NonNullable<HarnessStepResult["usage"]>,+ }),);- });+ }- it("checks usage against the bumped runtime limit after a grant", () => {- const usage = {- cacheReadTokens: 0,- cacheWriteTokens: 0,- costUsd: 0,- inputTokens: 10,- outputTokens: 3,- sawCost: false,- };- const session = {- ...setTurnUsageState(makeSession(), { turnId: "turn_0", ...usage, session: usage }),- limits: { maxInputTokensPerSession: 10, maxOutputTokensPerSession: 3 },- };+ describe("default limit counts only new input", () => {+ it("excludes cache reads from the window", () => {+ // One model step that replayed 20 cached tokens and sent the rest uncached.+ const session = sessionAfterStep({+ inputTokens: 40_000_010,+ inputTokenDetails: { cacheReadTokens: 20, cacheWriteTokens: 4, noCacheTokens: 39_999_986 },+ outputTokens: 1,+ });- expect(getSessionUsageLimitViolation(session)).toEqual({- kind: "input",- limit: 10,- usedTokens: 10,+ // Telemetry keeps the raw totals.+ expect(getSessionTokenUsage(session)).toMatchObject({+ cacheReadTokens: 20,+ cacheWriteTokens: 4,+ inputTokens: 40_000_010,+ });+ expect(+ checkSessionUsageLimit({+ canAsk: false,+ limit: DEFAULT_SESSION_USAGE_LIMIT,+ session,+ turnSequence: 0,+ }),+ ).toEqual({ kind: "within" });});- const bumped = bumpSessionRuntimeUsageLimits(session);-- // Both axes bump together so a session near two limits gets one prompt.- expect(getSessionRuntimeUsageLimits(bumped)).toEqual({ inputTokens: 20, outputTokens: 6 });- expect(getSessionUsageLimitViolation({ ...bumped, limits: session.limits })).toBeNull();-- const laterUsage = { ...usage, inputTokens: 20, outputTokens: 3 };- const later = setTurnUsageState(bumped, {- turnId: "turn_1",- ...laterUsage,- session: laterUsage,+ it("counts the full input when the provider reports no cache details", () => {+ const session = sessionAfterStep({ inputTokens: 40_000_000, outputTokens: 1 });++ expect(+ checkSessionUsageLimit({+ canAsk: false,+ limit: DEFAULT_SESSION_USAGE_LIMIT,+ session,+ turnSequence: 0,+ }),+ ).toEqual({+ code: "SESSION_USAGE_LIMIT_REACHED",+ details: {+ total: {+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ inputTokens: 40_000_000,+ outputTokens: 1,+ },+ window: {+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ inputTokens: 40_000_000,+ outputTokens: 1,+ },+ },+ kind: "fail",+ message: "The session reached its usage limit.",+ });});+ });- // `limit` reports the configured window size; `usedTokens` the lifetime total.- expect(getSessionUsageLimitViolation({ ...later, limits: session.limits })).toEqual({- kind: "input",- limit: 10,- usedTokens: 20,+ it("starts a new window after a reset while the total keeps accumulating", () => {+ const session = sessionAfterStep({ inputTokens: 10, outputTokens: 3 });+ const limit: SessionUsageLimit = ({ window }) => window.inputTokens >= 10;++ expect(+ checkSessionUsageLimit({ canAsk: false, limit, session, turnSequence: 0 }),+ ).toMatchObject({ kind: "fail" });++ const reset = resetSessionUsageWindow(session);+ expect(getSessionUsage(reset)).toMatchObject({ inputTokens: 10, outputTokens: 3 });+ expect(getSessionUsageWindow(reset)).toMatchObject({ inputTokens: 0, outputTokens: 0 });+ expect(+ checkSessionUsageLimit({ canAsk: false, limit, session: reset, turnSequence: 0 }),+ ).toEqual({ kind: "within" });++ // Later usage only counts its delta since the reset.+ const later = sessionAfterStep({ inputTokens: 4, outputTokens: 2 }, reset, "turn_1");+ expect(getSessionUsage(later)).toMatchObject({ inputTokens: 14, outputTokens: 5 });+ expect(getSessionUsageWindow(later)).toMatchObject({ inputTokens: 4, outputTokens: 2 });+ expect(+ checkSessionUsageLimit({ canAsk: false, limit, session: later, turnSequence: 1 }),+ ).toEqual({ kind: "within" });++ const much = sessionAfterStep({ inputTokens: 6, outputTokens: 0 }, later, "turn_1");+ expect(+ checkSessionUsageLimit({ canAsk: false, limit, session: much, turnSequence: 1 }),+ ).toMatchObject({+ details: { total: { inputTokens: 20 }, window: { inputTokens: 10 } },+ kind: "fail",});});- it("every grant moves the runtime limit, even after a large overshoot", () => {- const usage = {- cacheReadTokens: 0,- cacheWriteTokens: 0,- costUsd: 0,- inputTokens: 35,- outputTokens: 0,- sawCost: false,- };- // A single model call overshot the 10-token window by several windows.- const session = {- ...setTurnUsageState(makeSession(), { turnId: "turn_0", ...usage, session: usage }),- limits: { maxInputTokensPerSession: 10 },- };-- expect(getSessionUsageLimitViolation(session)).toMatchObject({ usedTokens: 35 });-- // One approval always unblocks: the runtime limit re-anchors to- // usage + configured limit rather than incrementing by the limit.- const bumped = bumpSessionRuntimeUsageLimits(session);- expect(getSessionRuntimeUsageLimits(bumped)).toEqual({ inputTokens: 45 });- expect(getSessionUsageLimitViolation({ ...bumped, limits: session.limits })).toBeNull();+ it("passes the total and the window to the limit", () => {+ const limit = vi.fn<SessionUsageLimit>(() => false);+ const session = sessionAfterStep({ inputTokens: 4, outputTokens: 2 }, undefined, "turn_0");+ const later = sessionAfterStep(+ { inputTokens: 5, outputTokens: 1 },+ resetSessionUsageWindow(session),+ "turn_1",+ );- // A second grant cycle moves the ceiling again -- never idempotent.- const laterUsage = { ...usage, inputTokens: 45 };- const later = setTurnUsageState(bumped, {- turnId: "turn_1",- ...laterUsage,- session: laterUsage,+ expect(+ checkSessionUsageLimit({ canAsk: true, limit, session: later, turnSequence: 1 }),+ ).toEqual({ kind: "within" });+ expect(limit).toHaveBeenCalledTimes(1);+ expect(limit).toHaveBeenCalledWith({+ total: {+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ costUsd: undefined,+ inputTokens: 9,+ outputTokens: 3,+ },+ window: {+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ costUsd: undefined,+ inputTokens: 5,+ outputTokens: 1,+ },});- expect(getSessionUsageLimitViolation({ ...later, limits: session.limits })).not.toBeNull();- const bumpedAgain = bumpSessionRuntimeUsageLimits(later);- expect(getSessionRuntimeUsageLimits(bumpedAgain)).toEqual({ inputTokens: 55 });- expect(getSessionUsageLimitViolation({ ...bumpedAgain, limits: session.limits })).toBeNull();});- it("reports remaining quota from the runtime limit", () => {- const usage = {- cacheReadTokens: 0,- cacheWriteTokens: 0,- costUsd: 0,- inputTokens: 4,- outputTokens: 9,- sawCost: false,- };- const session = {- ...setTurnUsageState(makeSession(), { turnId: "turn_0", ...usage, session: usage }),- limits: { maxInputTokensPerSession: 10 },- };+ it("does not consult the limit on an empty window", () => {+ const limit = vi.fn<SessionUsageLimit>(() => true);++ expect(+ checkSessionUsageLimit({ canAsk: false, limit, session: makeSession(), turnSequence: 0 }),+ ).toEqual({ kind: "within" });+ // A fresh window after a grant is empty too, even though the total is not.+ const reset = resetSessionUsageWindow(sessionAfterStep({ inputTokens: 10, outputTokens: 3 }));+ expect(+ checkSessionUsageLimit({ canAsk: false, limit, session: reset, turnSequence: 1 }),+ ).toEqual({ kind: "within" });+ expect(limit).not.toHaveBeenCalled();+ });- expect(getSessionRemainingUsageQuota(session)).toEqual({- costUsd: false,- inputTokens: 6,- outputTokens: false,+ it("asks to continue when the session can take input", () => {+ const session = sessionAfterStep({ inputTokens: 10, outputTokens: 3 });++ const check = checkSessionUsageLimit({+ canAsk: true,+ limit: () => true,+ session,+ turnSequence: 2,});- expect(getSessionRemainingUsageQuota(makeSession())).toEqual({- costUsd: false,- inputTokens: false,- outputTokens: false,++ expect(check.kind).toBe("ask");+ if (check.kind !== "ask") throw new Error("expected ask");+ expect(check.request.requestId).toBe("wrun_test:2:limit:usage:0");+ expect(check.request.kind).toBe("session-limit");+ expect(check.request.action).toMatchObject({+ input: {+ total: { inputTokens: 10, outputTokens: 3 },+ window: { inputTokens: 10, outputTokens: 3 },+ },});});- describe("counts only new input", () => {- // One model step that replayed 90 cached tokens, wrote 4 to the cache and sent 6 uncached.- function sessionAfterStep(usage: Partial<NonNullable<HarnessStepResult["usage"]>>) {- return {- ...addTurnUsage(- makeSession(),- "turn_0",- extractTokenUsageDelta({- costUsd: undefined,- usage: usage as NonNullable<HarnessStepResult["usage"]>,- }),- ),- limits: { maxInputTokensPerSession: 30 },- };- }-- it("excludes cache reads from the limit, the grant and the remaining quota", () => {- const session = sessionAfterStep({- inputTokens: 100,- inputTokenDetails: { cacheReadTokens: 90, cacheWriteTokens: 4, noCacheTokens: 6 },- outputTokens: 1,- });-- // Telemetry keeps the raw totals.- expect(getSessionTokenUsage(session)).toMatchObject({- cacheReadTokens: 90,- cacheWriteTokens: 4,- inputTokens: 100,- });- expect(getSessionUsageLimitViolation(session)).toBeNull();- expect(getSessionRemainingUsageQuota(session)).toMatchObject({ inputTokens: 20 });- expect(getSessionRuntimeUsageLimits(bumpSessionRuntimeUsageLimits(session))).toEqual({- inputTokens: 40,- });- });+ it("gives each approval window its own ask when only cost advances", () => {+ const limit: SessionUsageLimit = ({ window }) => (window.costUsd ?? 0) >= 1;+ const costStep = (session: HarnessSession) =>+ addTurnUsage(session, "turn_0", extractTokenUsageDelta({ costUsd: 1, usage: undefined }));+ const ask = (session: HarnessSession) => {+ const check = checkSessionUsageLimit({ canAsk: true, limit, session, turnSequence: 0 });+ if (check.kind !== "ask") throw new Error(`expected ask, got ${check.kind}`);+ return check.request.requestId;+ };- it("counts the full input when the provider reports no cache details", () => {- const session = sessionAfterStep({ inputTokens: 100, outputTokens: 1 });+ const first = costStep(makeSession());+ const firstId = ask(first);+ expect(ask(first)).toBe(firstId);- expect(getSessionUsageLimitViolation(session)).toEqual({- kind: "input",- limit: 30,- usedTokens: 100,- });- expect(getSessionRemainingUsageQuota(session)).toMatchObject({ inputTokens: 0 });- expect(getSessionRuntimeUsageLimits(bumpSessionRuntimeUsageLimits(session))).toEqual({- inputTokens: 130,- });+ const approved = resetSessionUsageWindow(first);+ expect(+ checkSessionUsageLimit({ canAsk: true, limit, session: approved, turnSequence: 0 }),+ ).toEqual({+ kind: "within",});+ const second = costStep(approved);+ expect(getSessionUsage(second)).toMatchObject({ costUsd: 2, inputTokens: 0, outputTokens: 0 });+ expect(ask(second)).not.toBe(firstId);});});diff --git a/packages/eve/src/harness/turn-tag-state.ts b/packages/eve/src/harness/turn-tag-state.tsindex a1412681b..145747c23 100644--- a/packages/eve/src/harness/turn-tag-state.ts+++ b/packages/eve/src/harness/turn-tag-state.ts@@ -21,21 +21,12 @@* the shared {@link TokenUsage} contract.*/import type { HarnessSession, SessionStateMap } from "#harness/types.js";-import {- findRuntimeUsageLimitViolation,- grantRuntimeUsageLimits,- remainingRuntimeUsageQuota,- resolveRuntimeUsageLimits,- type SessionRuntimeUsageLimits,- type SessionUsageLimitViolation,-} from "#harness/session-usage-limits.js";import type { TokenUsage } from "#shared/token-usage.js";-export type { SessionRuntimeUsageLimits, SessionUsageLimitViolation };-const HARNESS_TURN_USAGE_STATE_KEY = "eve.harness.turnUsage";const REPORTED_SESSION_USAGE_STATE_KEY = "eve.harness.reportedSessionUsage";-const SESSION_RUNTIME_USAGE_LIMIT_KEY = "eve.harness.sessionRuntimeTokenLimit";+const SESSION_USAGE_WINDOW_START_KEY = "eve.harness.sessionUsageWindowStart";+const SESSION_USAGE_WINDOW_INDEX_KEY = "eve.harness.sessionUsageWindowIndex";export interface TokenUsageTotals {readonly cacheReadTokens: number;@@ -95,87 +86,35 @@ export function toUsage(totals: TokenUsageTotals): TokenUsage {}/**- * The lifetime-usage ceilings currently in force, per axis. An axis is- * absent when the configured limit leaves it uncapped. Before any granted- * continuation the runtime limit equals the configured limit; each grant- * re-anchors it to `usage + configured limit` via- * {@link bumpSessionRuntimeUsageLimits}.+ * What the session spent since the last approved continuation, or since it+ * started. This is the `window` the session usage limit sees.*/-export function getSessionRuntimeUsageLimits(- session: Pick<HarnessSession, "limits" | "state">,-): SessionRuntimeUsageLimits {- const stored = session.state?.[SESSION_RUNTIME_USAGE_LIMIT_KEY] as- | SessionRuntimeUsageLimits- | undefined;- return resolveRuntimeUsageLimits({- configured: configuredSessionUsageLimits(session),- stored,- });+export function getSessionUsageWindow(session: Pick<HarnessSession, "state">): TokenUsage {+ return toUsage(subtractTokenUsage(getSessionTokenUsage(session), getWindowStart(session)));}-/**- * Bumps the runtime usage limits after the user grants a continuation. Each- * capped axis is re-anchored to `current budget usage + configured limit`, so one- * approval buys one full configured window even after an overshoot. All axes- * bump together to avoid back-to-back prompts. Configured limits never change.- */-export function bumpSessionRuntimeUsageLimits(session: HarnessSession): HarnessSession {- const bumped = grantRuntimeUsageLimits({- configured: configuredSessionUsageLimits(session),- usage: getSessionBudgetUsage(session),- });+/** Starts a new usage window at the session's current totals, after an approved continuation. */+export function resetSessionUsageWindow<T extends Pick<HarnessSession, "state">>(session: T): T {return {...session,state: {...session.state,- [SESSION_RUNTIME_USAGE_LIMIT_KEY]: bumped satisfies SessionRuntimeUsageLimits,+ [SESSION_USAGE_WINDOW_INDEX_KEY]: getSessionUsageWindowIndex(session) + 1,+ [SESSION_USAGE_WINDOW_START_KEY]: getSessionTokenUsage(session),},};}-/**- * Remaining lifetime usage quota under the runtime limits, per axis.- * `false` marks an uncapped axis. This is the pool a delegated child's- * budget is granted from.- */-export function getSessionRemainingUsageQuota(session: Pick<HarnessSession, "limits" | "state">): {- costUsd: number | false;- inputTokens: number | false;- outputTokens: number | false;-} {- const runtime = getSessionRuntimeUsageLimits(session);- return remainingRuntimeUsageQuota({ runtime, usage: getSessionBudgetUsage(session) });-}--export function getSessionUsageLimitViolation(- session: Pick<HarnessSession, "limits" | "state">,-): SessionUsageLimitViolation | null {- const runtime = getSessionRuntimeUsageLimits(session);- return findRuntimeUsageLimitViolation({- configured: configuredSessionUsageLimits(session),- runtime,- usage: getSessionBudgetUsage(session),- });-}--/**- * The session's usage as the limits count it. Cache reads are replayed history, not new work,- * so the input axis counts only new input: uncached input plus cache writes. A provider that- * reports no cache details counts its full input, as before.- */-function getSessionBudgetUsage(session: Pick<HarnessSession, "state">): TokenUsageTotals {- const usage = getSessionTokenUsage(session);- return { ...usage, inputTokens: Math.max(0, usage.inputTokens - usage.cacheReadTokens) };+/** How many usage windows the session has started before its current one. */+export function getSessionUsageWindowIndex(session: Pick<HarnessSession, "state">): number {+ return (session.state?.[SESSION_USAGE_WINDOW_INDEX_KEY] as number | undefined) ?? 0;}-function configuredSessionUsageLimits(- session: Pick<HarnessSession, "limits">,-): SessionRuntimeUsageLimits {- return {- costUsd: session.limits?.maxTokenCostUsdPerSession,- inputTokens: session.limits?.maxInputTokensPerSession,- outputTokens: session.limits?.maxOutputTokensPerSession,- };+function getWindowStart(session: Pick<HarnessSession, "state">): TokenUsageTotals {+ return (+ (session.state?.[SESSION_USAGE_WINDOW_START_KEY] as TokenUsageTotals | undefined) ??+ ZERO_TOKEN_USAGE+ );}/**@@ -201,13 +140,7 @@ export function takeSessionUsageDelta<T extends Pick<HarnessSession, "state">>((session.state?.[REPORTED_SESSION_USAGE_STATE_KEY] as TokenUsageTotals | undefined) ??ZERO_TOKEN_USAGE;return {- delta: {- cacheReadTokens: totals.cacheReadTokens - reported.cacheReadTokens,- cacheWriteTokens: totals.cacheWriteTokens - reported.cacheWriteTokens,- costUsd: totals.sawCost || reported.sawCost ? totals.costUsd - reported.costUsd : undefined,- inputTokens: totals.inputTokens - reported.inputTokens,- outputTokens: totals.outputTokens - reported.outputTokens,- },+ delta: toUsage(subtractTokenUsage(totals, reported)),session: {...session,state: {@@ -331,6 +264,17 @@ function addTokenUsage(base: TokenUsageTotals, delta: TokenUsageTotals): TokenUs};}+function subtractTokenUsage(total: TokenUsageTotals, base: TokenUsageTotals): TokenUsageTotals {+ return {+ cacheReadTokens: total.cacheReadTokens - base.cacheReadTokens,+ cacheWriteTokens: total.cacheWriteTokens - base.cacheWriteTokens,+ costUsd: total.costUsd - base.costUsd,+ inputTokens: total.inputTokens - base.inputTokens,+ outputTokens: total.outputTokens - base.outputTokens,+ sawCost: total.sawCost || base.sawCost,+ };+}+function toTokenUsageDelta(usage: TokenUsageDelta | undefined): TokenUsageTotals {if (usage === undefined) {return ZERO_TOKEN_USAGE;diff --git a/packages/eve/src/harness/types.ts b/packages/eve/src/harness/types.tsindex dd26de6ca..026843627 100644--- a/packages/eve/src/harness/types.ts+++ b/packages/eve/src/harness/types.ts@@ -15,7 +15,7 @@ import type { SandboxState } from "#sandbox/state.js";import type { JsonObject } from "#shared/json.js";import type { TokenUsage } from "#shared/token-usage.js";import type { InternalToolDefinition } from "#tools/definition.js";-import type { AgentReasoningDefinition } from "#shared/agent-definition.js";+import type { AgentReasoningDefinition, SessionUsageLimit } from "#shared/agent-definition.js";import type { HarnessToolDefinition } from "#harness/execute-tool.js";import type { HarnessModelMessage } from "#harness/messages.js";import type { SessionInstrumentation } from "#instrumentation/runtime.js";@@ -80,7 +80,6 @@ export interface HarnessSessionBase {readonly agent: SessionAgent;readonly compaction: CompactionConfig;readonly continuationToken: string;- readonly limits?: SessionLimits;readonly outputSchema?: JsonObject;/*** Stable identifier of the top user-facing session in the dispatch@@ -114,30 +113,6 @@ export function requireSessionModelReference(session: HarnessSession): RuntimeMoreturn reference;}-/**- * Token limits stored on one durable session.- */-export interface SessionLimits {- /**- * Maximum new input tokens (input minus cache reads) 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;- /**- * Maximum provider-reported output tokens this durable session may spend before- * eve refuses to start another model call.- */- readonly maxOutputTokensPerSession?: number;- /**- * Maximum provider-reported model token cost this durable session may spend,- * in US dollars, before eve refuses to start another model call.- */- readonly maxTokenCostUsdPerSession?: number;-}-/*** Input payload for a harness turn.*@@ -361,6 +336,8 @@ export interface ToolLoopHarnessConfig {* authoritative server-side metadata.*/readonly runtimeIdentity?: RuntimeIdentity;+ /** The agent's `limits.sessionUsage`; the default limit applies when absent. */+ readonly sessionUsageLimit?: SessionUsageLimit;/*** Unified tool definitions for this harness step.*diff --git a/packages/eve/src/harness/workflow-approval-resume.integration.test.ts b/packages/eve/src/harness/workflow-approval-resume.integration.test.tsindex 8d52c238c..b59841f71 100644--- a/packages/eve/src/harness/workflow-approval-resume.integration.test.ts+++ b/packages/eve/src/harness/workflow-approval-resume.integration.test.ts@@ -385,8 +385,10 @@ describe("workflow approval resume (real AI SDK)", () => {clearDurableDynamicCallbacks(initial.session.sessionId);});- it("starts an approved workflow and applies the session budget to the next model call", async () => {- const fixture = setup([workflow("deploy", always())]);+ it("starts an approved workflow and applies the session usage limit to the next model call", async () => {+ const fixture = setup([workflow("deploy", always())], {+ sessionUsageLimit: ({ window }) => window.inputTokens >= 12,+ });const initial = await fixture.step(fixture.session, { message: "Deploy Alice's release." });const totals = {cacheReadTokens: 0,@@ -396,14 +398,11 @@ describe("workflow approval resume (real AI SDK)", () => {outputTokens: 1,sawCost: false,};- const exhausted = setTurnUsageState(- { ...initial.session, limits: { maxInputTokensPerSession: 12 } },- {- ...totals,- session: totals,- turnId: "turn_0",- },- );+ const exhausted = setTurnUsageState(initial.session, {+ ...totals,+ session: totals,+ turnId: "turn_0",+ });const approved = await fixture.step(exhausted, {inputResponses: requests(initial.session).map((request) => ({optionId: "approve",diff --git a/packages/eve/src/internal/authored-definition/core.test.ts b/packages/eve/src/internal/authored-definition/core.test.tsindex cad09575a..139bb5cd5 100644--- a/packages/eve/src/internal/authored-definition/core.test.ts+++ b/packages/eve/src/internal/authored-definition/core.test.ts@@ -129,36 +129,32 @@ describe("normalizeAgentDefinition", () => {).toThrow(FAILURE_MESSAGE);});- it("accepts positive agent limits", () => {+ it("accepts agent limits and keeps the session usage function", () => {+ const sessionUsage = ({ window }: { window: { inputTokens: number } }) =>+ window.inputTokens >= 1_000;const definition = normalizeAgentDefinition({model: "openai/gpt-5.5",limits: {- maxInputTokensPerSession: 200_000,- maxOutputTokensPerSession: 20_000,- maxTokenCostUsdPerSession: 1.5,sessionTimeoutMs: 86_400_000,+ sessionUsage,},},FAILURE_MESSAGE,);expect(definition.limits).toEqual({- maxInputTokensPerSession: 200_000,- maxOutputTokensPerSession: 20_000,- maxTokenCostUsdPerSession: 1.5,sessionTimeoutMs: 86_400_000,+ sessionUsage,});+ expect(definition.limits?.sessionUsage).toBe(sessionUsage);});- it("accepts false to uncap session token limits", () => {+ it("accepts false to disable the session timeout", () => {const definition = normalizeAgentDefinition({model: "openai/gpt-5.5",limits: {- maxInputTokensPerSession: false,- maxOutputTokensPerSession: false,- maxTokenCostUsdPerSession: false,sessionTimeoutMs: false,},},@@ -166,13 +162,27 @@ describe("normalizeAgentDefinition", () => {);expect(definition.limits).toEqual({- maxInputTokensPerSession: false,- maxOutputTokensPerSession: false,- maxTokenCostUsdPerSession: false,sessionTimeoutMs: false,});});+ it.each([+ ["maxInputTokensPerSession", 200_000],+ ["maxOutputTokensPerSession", 20_000],+ ["maxTokenCostUsdPerSession", 1.5],+ ["maxInputTokensPerSession", false],+ ])("rejects the removed numeric session limit %s=%j", (key, value) => {+ expect(() =>+ normalizeAgentDefinition(+ {+ model: "openai/gpt-5.5",+ limits: { [key]: value },+ },+ FAILURE_MESSAGE,+ ),+ ).toThrow(FAILURE_MESSAGE);+ });+it("rejects the removed subagent max depth limit", () => {expect(() =>normalizeAgentDefinition(@@ -198,22 +208,15 @@ describe("normalizeAgentDefinition", () => {});it.each([- ["maxInputTokensPerSession", 0],- ["maxInputTokensPerSession", 1.5],- ["maxInputTokensPerSession", -1],- ["maxInputTokensPerSession", "200000"],- ["maxOutputTokensPerSession", 0],- ["maxOutputTokensPerSession", 1.5],- ["maxOutputTokensPerSession", -1],- ["maxOutputTokensPerSession", "20000"],- ["maxTokenCostUsdPerSession", 0],- ["maxTokenCostUsdPerSession", -0.01],- ["maxTokenCostUsdPerSession", Number.POSITIVE_INFINITY],- ["maxTokenCostUsdPerSession", "1.50"],["sessionTimeoutMs", 0],["sessionTimeoutMs", 1.5],["sessionTimeoutMs", -1],["sessionTimeoutMs", "30d"],+ ["sessionUsage", true],+ ["sessionUsage", false],+ ["sessionUsage", 40_000_000],+ ["sessionUsage", { inputTokens: 40_000_000 }],+ ["sessionUsage", "() => true"],])("rejects invalid session runtime limit %s=%j", (key, value) => {expect(() =>normalizeAgentDefinition(diff --git a/packages/eve/src/internal/authored-definition/core.ts b/packages/eve/src/internal/authored-definition/core.tsindex e69cd6c70..8182d3aec 100644--- a/packages/eve/src/internal/authored-definition/core.ts+++ b/packages/eve/src/internal/authored-definition/core.ts@@ -23,6 +23,7 @@ import {type AgentPromptCacheDefinition,type AnthropicPromptCacheTtl,type PublicAgentStaticModelDefinition,+ type SessionUsageLimit,} from "#shared/agent-definition.js";import {isDynamicSentinel,@@ -174,31 +175,12 @@ function expectPositiveIntegerOrFalse(value: unknown, message: string): number |return expectPositiveInteger(value, message);}-function expectPositiveNumberOrFalse(value: unknown, message: string): number | false {- if (value === false) {- return false;- }- if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {- throw new Error(message);- }- return value;-}-function normalizeAgentLimitsDefinition(value: unknown,message: string,): NonNullable<NormalizedAgentDefinition["limits"]> {const record = expectObjectRecord(value, message);- expectOnlyKnownKeys(- record,- [- "maxInputTokensPerSession",- "maxOutputTokensPerSession",- "maxTokenCostUsdPerSession",- "sessionTimeoutMs",- ],- message,- );+ expectOnlyKnownKeys(record, ["sessionTimeoutMs", "sessionUsage"], message);const normalizedDefinition: Mutable<NonNullable<NormalizedAgentDefinition["limits"]>> = {};if (record.sessionTimeoutMs !== undefined) {@@ -207,21 +189,9 @@ function normalizeAgentLimitsDefinition(message,);}- if (record.maxInputTokensPerSession !== undefined) {- normalizedDefinition.maxInputTokensPerSession = expectPositiveIntegerOrFalse(- record.maxInputTokensPerSession,- message,- );- }- if (record.maxOutputTokensPerSession !== undefined) {- normalizedDefinition.maxOutputTokensPerSession = expectPositiveIntegerOrFalse(- record.maxOutputTokensPerSession,- message,- );- }- if (record.maxTokenCostUsdPerSession !== undefined) {- normalizedDefinition.maxTokenCostUsdPerSession = expectPositiveNumberOrFalse(- record.maxTokenCostUsdPerSession,+ if (record.sessionUsage !== undefined) {+ normalizedDefinition.sessionUsage = expectFunction<SessionUsageLimit>(+ record.sessionUsage,message,);}diff --git a/packages/eve/src/internal/testing/app-harness.ts b/packages/eve/src/internal/testing/app-harness.tsindex dd9c52e07..4fb385af3 100644--- a/packages/eve/src/internal/testing/app-harness.ts+++ b/packages/eve/src/internal/testing/app-harness.ts@@ -44,12 +44,7 @@ interface TestAppDescriptor {readonly agent?: {/** Full agent definition; overrides `model` and `limits`. */readonly definition?: import("#public/definitions/agent.js").AgentDefinition;- readonly limits?: {- readonly maxInputTokensPerSession?: number | false;- readonly maxOutputTokensPerSession?: number | false;- readonly maxTokenCostUsdPerSession?: number | false;- readonly sessionTimeoutMs?: number | false;- };+ readonly limits?: import("#shared/agent-definition.js").AgentLimitsDefinition;readonly model?: string;readonly name?: string;};diff --git a/packages/eve/src/internal/testing/channel-conformance/contract.ts b/packages/eve/src/internal/testing/channel-conformance/contract.tsindex 03df2448a..dcaa7751b 100644--- a/packages/eve/src/internal/testing/channel-conformance/contract.ts+++ b/packages/eve/src/internal/testing/channel-conformance/contract.ts@@ -311,10 +311,12 @@ async function expectFileReachesAgent(conversation: ChannelConversation, file: S).toEqual([{ ...asSeen(file), url: undefined }]);}-const ONE_TOKEN_BUDGET = { limits: { maxInputTokensPerSession: 1 } } as const;+const ONE_TOKEN_BUDGET = {+ limits: { sessionUsage: ({ window }) => window.inputTokens >= 1 },+} as const satisfies Pick<ConversationOptions, "limits">;const BUDGET_PROMPT =- "This session has hit the input-token limit (1) per session. This is a guardrail against " +- "defective long-running sessions. If session activity looks fine, just approve to keep going.";+ "This session has hit its usage limit. This is a guardrail against defective " ++ "long-running sessions. If session activity looks fine, just approve to keep going.";const LOOK_UP_NOTES = `Use ${PLAIN_TOOL} to find Bob's review notes.`;const LATER_MESSAGE = "Carol wants the review by Friday.";diff --git a/packages/eve/src/internal/testing/compile-from-memory.ts b/packages/eve/src/internal/testing/compile-from-memory.tsindex 471e8358a..f8b97d7ae 100644--- a/packages/eve/src/internal/testing/compile-from-memory.ts+++ b/packages/eve/src/internal/testing/compile-from-memory.ts@@ -24,12 +24,7 @@ export interface CompileFromMemoryInput {readonly appRoot?: string;readonly agentRoot?: string;readonly model: string;- readonly limits?: {- readonly maxInputTokensPerSession?: number | false;- readonly maxOutputTokensPerSession?: number | false;- readonly maxTokenCostUsdPerSession?: number | false;- readonly sessionTimeoutMs?: number | false;- };+ readonly limits?: import("#shared/agent-definition.js").AgentLimitsDefinition;readonly revision?: string;readonly modules?: readonly ProgrammaticAgentModule[];readonly tools?: readonly CompileFromMemoryToolInput[];diff --git a/packages/eve/src/public/definitions/agent.ts b/packages/eve/src/public/definitions/agent.tsindex ecc1a2427..fcb0d0df8 100644--- a/packages/eve/src/public/definitions/agent.ts+++ b/packages/eve/src/public/definitions/agent.ts@@ -20,6 +20,7 @@ export type {PublicAgentDynamicModelResult as AgentDynamicModelResult,AgentExperimentalDefinition,AgentLimitsDefinition,+ SessionUsageLimit,PublicAgentModelSelectionDefinition as AgentModelSelectionDefinition,AgentWorkflowDefinition,AgentWorkflowRetentionDefinition,diff --git a/packages/eve/src/public/definitions/exact.test.ts b/packages/eve/src/public/definitions/exact.test.tsindex 7577b5400..ae79e97bc 100644--- a/packages/eve/src/public/definitions/exact.test.ts+++ b/packages/eve/src/public/definitions/exact.test.ts@@ -27,6 +27,8 @@ import { defineTool, type ToolDefinition } from "#public/tools/index.js";describe("definition helper exact inputs", () => {it("preserves literal inference for valid definitions", () => {+ const sessionUsage = ({ window }: { window: { inputTokens: number } }) =>+ window.inputTokens >= 1_000_000;const agent = defineAgent({description: "type-test",experimental: {@@ -36,10 +38,8 @@ describe("definition helper exact inputs", () => {},},limits: {- maxInputTokensPerSession: 200_000,- maxOutputTokensPerSession: 20_000,- maxTokenCostUsdPerSession: 1.5,sessionTimeoutMs: 86_400_000,+ sessionUsage,},model: "anthropic/claude-sonnet-5",});@@ -53,10 +53,8 @@ describe("definition helper exact inputs", () => {expect(defineAgent({ model: "openai/gpt-5.5", tool: false }).tool).toBe(false);expect(agent.experimental.workflow.modelCallsPerStep).toBe(4);expect(agent.experimental.workflow.retention).toBe(0);- expect(agent.limits.maxInputTokensPerSession).toBe(200_000);- expect(agent.limits.maxOutputTokensPerSession).toBe(20_000);- expect(agent.limits.maxTokenCostUsdPerSession).toBe(1.5);expect(agent.limits.sessionTimeoutMs).toBe(86_400_000);+ expect(agent.limits.sessionUsage).toBe(sessionUsage);expect(schedule.cron).toBe("0 9 * * *");});@@ -217,6 +215,22 @@ function typeOnlyFixtures(): void {model: "anthropic/claude-sonnet-5",});+ defineAgent({+ limits: {+ // @ts-expect-error Numeric per-session token limits were replaced by `sessionUsage`.+ maxInputTokensPerSession: 200_000,+ },+ model: "anthropic/claude-sonnet-5",+ });++ defineAgent({+ limits: {+ // @ts-expect-error `sessionUsage` is a function, not a number.+ sessionUsage: 40_000_000,+ },+ model: "anthropic/claude-sonnet-5",+ });+const agentWithName = {model: "anthropic/claude-sonnet-5",name: "agent-name",diff --git a/packages/eve/src/public/index.ts b/packages/eve/src/public/index.tsindex 7eaefc265..78387ef83 100644--- a/packages/eve/src/public/index.ts+++ b/packages/eve/src/public/index.ts@@ -15,6 +15,7 @@ export {type AgentWorkflowRetentionDefinition,type AgentWorkflowWorldDefinition,type DefinedAgent,+ type SessionUsageLimit,type DynamicSubagentDefinition,type DynamicLocalSubagentDefinition,defineAgent,diff --git a/packages/eve/src/runtime/resolve-agent.ts b/packages/eve/src/runtime/resolve-agent.tsindex 2be44552a..c2b545a11 100644--- a/packages/eve/src/runtime/resolve-agent.ts+++ b/packages/eve/src/runtime/resolve-agent.ts@@ -17,13 +17,15 @@ import { resolveDynamicSkillDefinition } from "#runtime/resolve-dynamic-skill.jsimport { resolveDynamicToolDefinition } from "#runtime/resolve-dynamic-tool.js";import { resolveToolDefinition } from "#runtime/resolve-tool.js";import { resolveMemoryDefinition } from "#runtime/resolve-memory.js";+import { normalizeAgentDefinition } from "#internal/authored-definition/core.js";+import { loadResolvedModuleExport } from "#runtime/resolve-helpers.js";import type {ResolvedAgent,ResolvedChannelDefinition,ResolvedSkillDefinition,ResolvedInstructionsDefinition,} from "#runtime/types.js";-import type { AgentToolExposure } from "#shared/agent-definition.js";+import type { AgentToolExposure, SessionUsageLimit } from "#shared/agent-definition.js";/*** Input for resolving one compiled authored agent into a runtime-owned model.@@ -133,10 +135,36 @@ export async function resolveAgent(input: ResolveAgentInput): Promise<ResolvedAg};return "config" in input.manifest- ? { ...resolvedAgent, config: createResolvedAgentConfig(input.manifest) }+ ? {+ ...resolvedAgent,+ config: createResolvedAgentConfig(+ input.manifest,+ await loadSessionUsageLimit(input.manifest, input.moduleMap, input.nodeId),+ ),+ }: resolvedAgent;}+/** Loads the authored `limits.sessionUsage` function, which the manifest can only mark. */+async function loadSessionUsageLimit(+ manifest: CompiledAgentNodeManifest,+ moduleMap: CompiledModuleMap,+ nodeId: string | undefined,+): Promise<SessionUsageLimit | undefined> {+ const source = manifest.config.source;+ if (manifest.config.limits?.sessionUsage !== true || source === undefined) return undefined;+ const definition = await loadResolvedModuleExport({+ definition: source,+ kindLabel: "agent config",+ moduleMap,+ nodeId,+ });+ return normalizeAgentDefinition(+ definition,+ `Expected the authored agent config export "${source.exportName ?? "default"}" from "${source.logicalPath}" to match the public eve shape.`,+ ).limits?.sessionUsage;+}+function requireBindingOwner(manifest: CompiledAgentNodeManifest | CompiledAgentResources,sourceId: string,@@ -177,6 +205,7 @@ function requireCompiledSourceOwner(function createResolvedAgentConfig(manifest: CompiledAgentNodeManifest,+ sessionUsage: SessionUsageLimit | undefined,): NonNullable<ResolvedAgent["config"]> {const config: {compaction?: NonNullable<ResolvedAgent["config"]>["compaction"];@@ -261,12 +290,7 @@ function createResolvedAgentConfig(}if (manifest.config.limits !== undefined) {- config.limits = {- maxInputTokensPerSession: manifest.config.limits.maxInputTokensPerSession,- maxOutputTokensPerSession: manifest.config.limits.maxOutputTokensPerSession,- maxTokenCostUsdPerSession: manifest.config.limits.maxTokenCostUsdPerSession,- sessionTimeoutMs: manifest.config.limits.sessionTimeoutMs,- };+ config.limits = { sessionTimeoutMs: manifest.config.limits.sessionTimeoutMs, sessionUsage };}if (manifest.config.dynamicModel !== undefined) {diff --git a/packages/eve/src/runtime/subagents/dynamic-agent-config.test.ts b/packages/eve/src/runtime/subagents/dynamic-agent-config.test.tsnew file mode 100644index 000000000..655a7c1b0--- /dev/null+++ b/packages/eve/src/runtime/subagents/dynamic-agent-config.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from "vitest";++import { normalizeDynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";++describe("normalizeDynamicSubagentAgentConfig", () => {+ it("rejects a selected limits.sessionUsage", async () => {+ await expect(+ normalizeDynamicSubagentAgentConfig({+ name: "researcher",+ state: {} as never,+ value: {+ description: "Perform deep research.",+ limits: { sessionUsage: () => true },+ model: "openai/gpt-5.5",+ },+ }),+ ).rejects.toThrow(+ 'The "limits.sessionUsage" field cannot be selected at runtime; the root agent\'s `sessionUsage` applies.',+ );+ });+});diff --git a/packages/eve/src/runtime/subagents/dynamic-agent-config.ts b/packages/eve/src/runtime/subagents/dynamic-agent-config.tsindex 8ca35bea5..c4226b00f 100644--- a/packages/eve/src/runtime/subagents/dynamic-agent-config.ts+++ b/packages/eve/src/runtime/subagents/dynamic-agent-config.ts@@ -16,7 +16,8 @@ export interface DynamicSubagentAgentConfig {readonly thresholdPercent?: number;};readonly description: string;- readonly limits?: AgentLimitsDefinition;+ /** Serialized into workflow input, so it can't carry the `sessionUsage` function. */+ readonly limits?: Pick<AgentLimitsDefinition, "sessionTimeoutMs">;readonly model: DynamicSubagentModelReference;readonly reasoning?: AgentReasoningDefinition;readonly tool?: AgentToolExposure;@@ -48,11 +49,16 @@ export async function normalizeDynamicSubagentAgentConfig(input: {if (isDynamicModelDefinition(definition.model)) {throw new Error(`${message} The returned "model" must be static.`);}+ if (definition.limits?.sessionUsage !== undefined) {+ throw new Error(+ `${message} The "limits.sessionUsage" field cannot be selected at runtime; the root agent's \`sessionUsage\` applies.`,+ );+ }const config: {compaction?: DynamicSubagentAgentConfig["compaction"];description: string;- limits?: AgentLimitsDefinition;+ limits?: DynamicSubagentAgentConfig["limits"];model: DynamicSubagentModelReference;reasoning?: AgentReasoningDefinition;tool?: AgentToolExposure;diff --git a/packages/eve/src/runtime/types.ts b/packages/eve/src/runtime/types.tsindex 984bc329a..ad0e308fa 100644--- a/packages/eve/src/runtime/types.ts+++ b/packages/eve/src/runtime/types.ts@@ -33,7 +33,11 @@ import type {MarkdownSourceRef,} from "#shared/source-ref.js";import type { NamedSkillDefinition } from "#shared/skill-definition.js";-import type { InternalAgentDefinition, AgentToolExposure } from "#shared/agent-definition.js";+import type {+ AgentLimitsDefinition,+ InternalAgentDefinition,+ AgentToolExposure,+} from "#shared/agent-definition.js";import type { RuntimeDynamicModelReference } from "#runtime/agent/bootstrap.js";import type { InternalToolDefinitionWithExecuteFn } from "#tools/definition.js";import type { CompiledToolBehavior } from "#tools/behavior.js";@@ -337,7 +341,11 @@ export interface ResolvedDynamicSubagentDefinition extends Readonly<ModuleSource/*** Runtime-owned additive agent configuration resolved from `agent.ts`.*/-type ResolvedAgentDefinitionBase = Omit<InternalAgentDefinition, "build" | "model" | "source"> & {+type ResolvedAgentDefinitionBase = Omit<+ InternalAgentDefinition,+ "build" | "limits" | "model" | "source"+> & {+ limits?: AgentLimitsDefinition;source?: Readonly<NonNullable<InternalAgentDefinition["source"]>>;};diff --git a/packages/eve/src/shared/agent-definition.ts b/packages/eve/src/shared/agent-definition.tsindex 74a3f4c74..27d16a03f 100644--- a/packages/eve/src/shared/agent-definition.ts+++ b/packages/eve/src/shared/agent-definition.ts@@ -1,6 +1,7 @@import type { CallSettings, LanguageModel } from "ai";import type { JsonObject } from "#shared/json.js";import type { ModuleSourceRef } from "#shared/source-ref.js";+import type { TokenUsage } from "#shared/token-usage.js";import {isDynamicSentinel,type DynamicResolveContext,@@ -184,49 +185,29 @@ export interface AgentLimitsDefinition {*/readonly sessionTimeoutMs?: number | false;/**- * Maximum new input tokens accumulated by one durable session: uncached- * input plus cache writes. Cache reads don't count. When the provider- * reports no cache details, all input counts.+ * Decides whether a session has reached its usage limit. eve calls it before+ * each model call; returning `true` pauses the turn on a continuation prompt,+ * or fails it when nobody can answer. Approving starts a new window.*- * 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.+ * Subagent sessions without their own `sessionUsage` use the root agent's.+ * Set `sessionUsage: () => false` to leave sessions uncapped.*- * `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 | 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 | false;- /**- * Maximum provider-reported model token cost accumulated by one durable- * session, in US dollars.- *- * eve checks this before starting each model call. The model call that- * crosses the limit is allowed to finish because providers report cost only- * 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 token-cost quota when the parent has one.+ * @default ({ window }) => window.inputTokens - window.cacheReadTokens >= 40_000_000*/- readonly maxTokenCostUsdPerSession?: number | false;+ readonly sessionUsage?: SessionUsageLimit;}+/**+ * Usage limit check for one session. `inputTokens` includes cache reads and+ * writes. Usage counts what the session's subagents spent once they reply.+ */+export type SessionUsageLimit = (usage: {+ /** Everything the session has spent. */+ readonly total: TokenUsage;+ /** What the session has spent since the last approved continuation. */+ readonly window: TokenUsage;+}) => boolean;+/*** Experimental, opt-in agent capabilities authored in `agent.ts`.*@@ -356,9 +337,18 @@ export type InternalAgentDefinition = {reasoning?: AgentReasoningDefinition;source?: ModuleSourceRef;tool?: AgentToolExposure;- limits?: AgentLimitsDefinition;+ limits?: CompiledAgentLimitsDefinition;};+/**+ * Compiled `limits`. `sessionUsage` is a function, so the manifest only marks that the agent+ * config module authors one; the runtime loads it from `source`.+ */+export interface CompiledAgentLimitsDefinition {+ readonly sessionTimeoutMs?: number | false;+ readonly sessionUsage?: true;+}+/*** Shared public definition for an agent.*diff --git a/packages/eve/src/subagents/event-proxy-step.integration.test.ts b/packages/eve/src/subagents/event-proxy-step.integration.test.tsindex 83654fc49..887a13141 100644--- a/packages/eve/src/subagents/event-proxy-step.integration.test.ts+++ b/packages/eve/src/subagents/event-proxy-step.integration.test.ts@@ -94,8 +94,10 @@ function fixture() {enterSessionProjection(ctx, durableSession.state);const request = createSessionLimitContinuationRequest({sessionId: "child-session",+ total: { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 101, outputTokens: 0 },turnSequence: 0,- violation: { kind: "input", limit: 100, usedTokens: 101 },+ window: { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 101, outputTokens: 0 },+ windowIndex: 0,});const hookPayload: SubagentInputRequestHookPayload = {kind: "subagent-input-request",diff --git a/packages/eve/src/subagents/token-budget.test.ts b/packages/eve/src/subagents/token-budget.test.tsdeleted file mode 100644index 57bdfc50b..000000000--- a/packages/eve/src/subagents/token-budget.test.ts+++ /dev/null@@ -1,140 +0,0 @@-import { describe, expect, it } from "vitest";--import { resolveRemainingSessionTokenLimits } from "#subagents/token-budget.js";-import { bumpSessionRuntimeUsageLimits, setTurnUsageState } from "#harness/turn-tag-state.js";-import type { HarnessSession, SessionLimits } from "#harness/types.js";--function createSessionWithUsage(input: {- readonly limits?: SessionLimits;- readonly usedCostUsd?: number;- 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.usedCostUsd === undefined &&- input.usedInputTokens === undefined &&- input.usedOutputTokens === undefined- ) {- return base;- }-- const usage = {- cacheReadTokens: 0,- cacheWriteTokens: 0,- costUsd: input.usedCostUsd ?? 0,- inputTokens: input.usedInputTokens ?? 0,- outputTokens: input.usedOutputTokens ?? 0,- sawCost: input.usedCostUsd !== undefined,- };- return setTurnUsageState(base, { ...usage, session: usage, turnId: "turn_0" });-}--describe("resolveRemainingSessionTokenLimits", () => {- it("returns false axes for an uncapped session", () => {- expect(resolveRemainingSessionTokenLimits(createSessionWithUsage({}), 1)).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, 1)).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, 1)).toEqual({- maxInputTokensPerSession: 1_000_000,- maxOutputTokensPerSession: false,- });- });-- it("measures a delegated grant from the bumped runtime limit", () => {- const exhausted = createSessionWithUsage({- limits: { maxInputTokensPerSession: 1_000_000, maxOutputTokensPerSession: 100_000 },- usedInputTokens: 1_100_000,- usedOutputTokens: 110_000,- });- const continued = bumpSessionRuntimeUsageLimits(exhausted);-- expect(resolveRemainingSessionTokenLimits(continued, 1)).toEqual({- maxInputTokensPerSession: 1_000_000,- maxOutputTokensPerSession: 100_000,- });- });-- it("clamps an overspent axis to zero", () => {- const session = createSessionWithUsage({- limits: { maxInputTokensPerSession: 100_000 },- usedInputTokens: 150_000,- });-- expect(resolveRemainingSessionTokenLimits(session, 1)).toEqual({- maxInputTokensPerSession: 0,- maxOutputTokensPerSession: false,- });- });-- it("splits the remaining tokens across children started together, flooring each share", () => {- const session = createSessionWithUsage({- limits: { maxInputTokensPerSession: 1_000_000, maxOutputTokensPerSession: 50_000 },- usedInputTokens: 100_001,- usedOutputTokens: 20_000,- });-- expect(resolveRemainingSessionTokenLimits(session, 3)).toEqual({- maxInputTokensPerSession: 299_999,- maxOutputTokensPerSession: 10_000,- });- });-- it("splits the remaining model token-cost budget across children started together", () => {- const session = createSessionWithUsage({- limits: { maxTokenCostUsdPerSession: 1.5 },- usedCostUsd: 0.5,- });-- expect(resolveRemainingSessionTokenLimits(session, 4)).toEqual({- maxInputTokensPerSession: false,- maxOutputTokensPerSession: false,- maxTokenCostUsdPerSession: 0.25,- });- });-- it("marks uncapped axes as false", () => {- const session = createSessionWithUsage({- limits: { maxOutputTokensPerSession: 50_000 },- usedOutputTokens: 10_000,- });-- expect(resolveRemainingSessionTokenLimits(session, 1)).toEqual({- maxInputTokensPerSession: false,- maxOutputTokensPerSession: 40_000,- });- });-});diff --git a/packages/eve/src/subagents/token-budget.ts b/packages/eve/src/subagents/token-budget.tsdeleted file mode 100644index 97bf29960..000000000--- a/packages/eve/src/subagents/token-budget.ts+++ /dev/null@@ -1,40 +0,0 @@-import type { RunSessionLimits } from "#channel/types.js";-import { getSessionRemainingUsageQuota } 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 parent's remaining runtime-limit quota, per axis, split evenly- * across the `fanoutSize` children started together. `false` marks an axis- * with no inherited cap.- *- * The split bounds children started together by the parent's remainder as a- * group, not each by the whole of it. Children started later see the quota- * net of the spend earlier children reported, which counts in the parent's- * session totals. A granted continuation bumps the parent's runtime limit, so- * children started after a grant draw from the fresh window.- */-export function resolveRemainingSessionTokenLimits(- session: Pick<HarnessSession, "limits" | "state">,- fanoutSize: number,-): RunSessionLimits {- const shares = Math.max(1, fanoutSize);- const remaining = getSessionRemainingUsageQuota(session);- const limits: {- maxInputTokensPerSession: number | false;- maxOutputTokensPerSession: number | false;- maxTokenCostUsdPerSession?: number;- } = {- maxInputTokensPerSession: grantTokenShare(remaining.inputTokens, shares),- maxOutputTokensPerSession: grantTokenShare(remaining.outputTokens, shares),- };- if (remaining.costUsd !== false) {- limits.maxTokenCostUsdPerSession = remaining.costUsd / shares;- }- return limits;-}--function grantTokenShare(remaining: number | false, shares: number): number | false {- if (remaining === false) return false;- return Math.floor(remaining / shares);-}diff --git a/packages/eve/src/subagents/tool.test.ts b/packages/eve/src/subagents/tool.test.tsindex 30f305ab8..50851b690 100644--- a/packages/eve/src/subagents/tool.test.ts+++ b/packages/eve/src/subagents/tool.test.ts@@ -51,17 +51,14 @@ function makeParent(};}-const NO_LIMITS = { maxInputTokensPerSession: false, maxOutputTokensPerSession: false } as const;-function buildRuntimeSubagentRunInput(- input: Omit<BuildSubagentRunInput, "continuationKey" | "limits" | "selfAgent" | "source"> & {+ input: Omit<BuildSubagentRunInput, "continuationKey" | "selfAgent" | "source"> & {readonly selfAgent?: boolean;},): ReturnType<typeof buildSubagentRunInput> {return buildSubagentRunInput({...input,continuationKey: `${input.session.sessionId}:${input.action.callId}`,- limits: NO_LIMITS,selfAgent: input.selfAgent ?? false,source: { type: "runtime" },});@@ -272,7 +269,6 @@ describe("buildSubagentRunInput", () => {auth: null,continuationKey: "parent-session:call-1",initiatorAuth: null,- limits: NO_LIMITS,selfAgent: false,session: makeSession(),source: { description: "Local delegate subagent description.", type: "local" },diff --git a/packages/eve/src/subagents/tool.ts b/packages/eve/src/subagents/tool.tsindex d39b0298e..ae1b43c64 100644--- a/packages/eve/src/subagents/tool.ts+++ b/packages/eve/src/subagents/tool.ts@@ -3,7 +3,6 @@ import { formatSubagentInput, type SubagentParentContext } from "#subagents/invoimport type { JsonObject } from "#shared/json.js";import type {ChannelInstrumentationProjection,- RunSessionLimits,SessionAuthContext,SessionCapabilities,RunInput,@@ -78,8 +77,6 @@ export function buildSubagentRunInput(input: {/** Durable session identity of the sandbox currently used by the parent. */readonly sandboxSessionId?: string;readonly selfAgent: boolean;- /** Session token limits the child inherits. */- readonly limits: RunSessionLimits;readonly parent: SubagentParentContext;readonly session: Pick<HarnessSession, "continuationToken" | "sandboxState" | "sessionId">;readonly source: SubagentInputSource;@@ -134,7 +131,6 @@ export function buildSubagentRunInput(input: {// `ctx.agent` already dropped an empty schema, so what arrives is one to honor.outputSchema: action.input.outputSchema as JsonObject | undefined,},- limits: input.limits,conversationId: input.parent.conversationId,parent: input.parent.lineage,parentTraceContext: input.parent.traceContext,diff --git a/packages/eve/test/scenarios/turn-cancellation.scenario.test.ts b/packages/eve/test/scenarios/turn-cancellation.scenario.test.tsindex 945d5305a..2dcfe87f2 100644--- a/packages/eve/test/scenarios/turn-cancellation.scenario.test.ts+++ b/packages/eve/test/scenarios/turn-cancellation.scenario.test.ts@@ -99,7 +99,7 @@ const model = mockModel((request) => {});export default defineAgent({- ${options.sessionInputLimit === undefined ? "" : `limits: { maxInputTokensPerSession: ${String(options.sessionInputLimit)} },`}+ ${options.sessionInputLimit === undefined ? "" : `limits: { sessionUsage: ({ window }) => window.inputTokens >= ${String(options.sessionInputLimit)} },`}model,modelContextWindowTokens: 32_000,});diff --git a/research/session-usage-limit-function.md b/research/session-usage-limit-function.mdnew file mode 100644index 000000000..3c072e972--- /dev/null+++ b/research/session-usage-limit-function.md@@ -0,0 +1,63 @@+---+issue: https://github.com/vercel/eve/pull/5028+status: implemented+last_updated: "2026-10-19"+---++# Session usage limit as a function++Three numeric caps (`maxInputTokensPerSession`, `maxOutputTokensPerSession`,+`maxTokenCostUsdPerSession`) could only express "this one counter crossed this+number". Authors who want to count cache writes, new input plus output, or a+mix of tokens and cost had no way to say so, and every new counting rule needed+another field.++Replace them with one authored function, shaped like a tool's `approval`+policy:++```ts+limits: {+ sessionUsage: ({ total, window }) => boolean, // true = limit reached+}+```++`total` is the session's lifetime usage; `window` is the usage since the last+approved continuation. Both are the shared `TokenUsage` record and include+delegated spend. Approving a continuation starts a new window, which replaces+the old "re-anchor each ceiling to usage + configured limit" bookkeeping with a+single stored snapshot. When omitted, the limit is 40M new input tokens+(`inputTokens - cacheReadTokens`) per window.++## Subagents++A function can't be divided the way a number can, so the per-step split of the+parent's remaining quota goes away. Each subagent session checks its own window+with its own `sessionUsage`, or the root agent's when it authors none. Child+spend still counts in the parent's usage once the child replies. Dynamic+subagent configs are serialized into workflow input, so they can't carry a+function and always use the root agent's.++The cost is a looser bound on fan-out. Parallel children each get a full+window, and their spend reaches the parent only when they reply, so one model+step that starts N children can spend about N times the limit before the+parent's next check asks. The old split capped the whole tree, but a child's+limit depended on how many siblings started with it and on what earlier+children had spent. A tree-wide check, which counts in-flight child usage+before each child model call, would restore the bound and is left for a+follow-up.++## Runtime++The manifest marks `limits.sessionUsage: true`; the agent config module+becomes a runtime entry and the runtime loads the function when it resolves the+agent, the same way tool approval policies are loaded. The harness receives it+through its config, never through durable session state.++## Compatibility++This is a breaking change to `defineAgent`, made before 1.0 without a shim.+Sessions created before the change keep their stored numeric limits in durable+state, which the runtime now ignores; they start on the new limit with a window+covering their whole history. Pending continuation prompts from older+deployments still match the session-limit request id. The two failure codes+collapse into `SESSION_USAGE_LIMIT_REACHED`.