Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): count delegated agent usage against parent session budgets (#3956)

Andrew Barbaa9da46c6a1da
diff --git a/.changeset/delegated-session-budgets.md b/.changeset/delegated-session-budgets.md
new file mode 100644
index 000000000..d3cf67f91
--- /dev/null
+++ b/.changeset/delegated-session-budgets.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Delegated agents again share and count against the parent's session token and cost budgets: agent tasks started in the same model step split the parent's remaining quota, and delegated usage, including remote agents and nested subagents, counts toward the parent's `maxInputTokensPerSession`, `maxOutputTokensPerSession`, and `maxTokenCostUsdPerSession` and the usage the parent reports. An agent task's usage counts with each reply and when a cancelled turn ends; other workflow tools' `ctx.agent` usage counts when the tool replies or finishes.
diff --git a/docs/agent-config.md b/docs/agent-config.md
index daae5b569..cf8afb282 100644
--- a/docs/agent-config.md
+++ b/docs/agent-config.md
@@ -213,16 +213,37 @@ 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 at dispatch time — the
-remainder in the current budget window split evenly across the batch's local
-subagent calls — and a completed child's usage counts against the parent's
-quota. Token-cost budgets follow the same rules, including splitting the
-remaining US-dollar budget across a batch and adding completed 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.
+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
+sends. A turn it doesn't reply to, such as one a cancel stopped, counts with
+the next reply, or when the turn ends if no call waits for a reply. Sessions
+that any other `serve` workflow tool opens with `ctx.agent` count the same
+way; 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.
+
+Some delegated usage doesn't count against the parent: a `ctx.agent` turn
+still running when its workflow tool finishes or is cancelled; the `ctx.agent`
+usage of an `execute` tool whose parent turn is cancelled while it waits; and
+what a cancelled agent task's own subagents spend after the task reports its
+cancelled turn, until the task's next reply.
## Workflow world
diff --git a/e2e/fixtures/agent-subagents/agent/agent.ts b/e2e/fixtures/agent-subagents/agent/agent.ts
index 93bb40be4..eba694b65 100644
--- a/e2e/fixtures/agent-subagents/agent/agent.ts
+++ b/e2e/fixtures/agent-subagents/agent/agent.ts
@@ -9,6 +9,12 @@ import {
respondAsNotebookKeeper,
respondAsNotebookParent,
} from "./lib/notebook.js";
+import {
+ isSurveyDirective,
+ isSurveyToolDirective,
+ respondAsSurveyParent,
+ respondAsSurveyToolParent,
+} from "./lib/survey.js";
if (process.env.EVE_E2E_MODEL === "mock") {
process.env.EVE_MOCK_AUTHORED_MODELS = "1";
@@ -88,6 +94,11 @@ const workspaceDispatcher = mockModel({
},
});
const notebookParent = mockModel({ modelId: "notebook-parent", respond: respondAsNotebookParent });
+const surveyParent = mockModel({ modelId: "survey-parent", respond: respondAsSurveyParent });
+const surveyToolParent = mockModel({
+ modelId: "survey-tool-parent",
+ respond: respondAsSurveyToolParent,
+});
// The remote keeper is a root session of this deployment, reached through remote-loopback.
const notebookKeeper = mockModel({ modelId: "notebook-keeper", respond: respondAsNotebookKeeper });
/** Reads the id of a tool's task from the latest framework-injected `[Tasks]` note. */
@@ -136,6 +147,12 @@ export default defineAgent({
if (messages.some(isNotebookDirective)) {
return { model: notebookParent, modelContextWindowTokens: 1_000_000 };
}
+ if (messages.some(isSurveyDirective)) {
+ return { model: surveyParent, modelContextWindowTokens: 1_000_000 };
+ }
+ if (messages.some(isSurveyToolDirective)) {
+ return { model: surveyToolParent, modelContextWindowTokens: 1_000_000 };
+ }
return { model: defaultModel, modelContextWindowTokens };
},
},
diff --git a/e2e/fixtures/agent-subagents/agent/lib/survey.ts b/e2e/fixtures/agent-subagents/agent/lib/survey.ts
new file mode 100644
index 000000000..4a419d9de
--- /dev/null
+++ b/e2e/fixtures/agent-subagents/agent/lib/survey.ts
@@ -0,0 +1,57 @@
+import { latestTaskResult, outputOf, playScript } from "@eve-e2e/config/mock-script";
+import type { MockModelRequest, MockModelResponse } from "eve/evals";
+
+import {
+ SURVEY_DIRECTIVE,
+ SURVEY_TOOL_DIRECTIVE,
+ SURVEY_WORKER_INPUT_TOKENS,
+} from "../../constants.js";
+
+// The survey scripts: the parent starts one survey-worker task and waits for
+// it, or calls a workflow tool that opens a `ctx.agent` session with
+// survey-worker. The worker's one model call reports more input tokens than
+// the parent's whole session budget, so once the worker's usage counts against
+// the parent, the parent's next model call stops at its own session-limit
+// prompt.
+
+/** Whether a message is Alice's survey request. */
+export function isSurveyDirective(message: string): boolean {
+ return message.startsWith(`${SURVEY_DIRECTIVE} `);
+}
+
+/** Whether a message is Alice's survey request for the workflow tool. */
+export function isSurveyToolDirective(message: string): boolean {
+ return message.startsWith(`${SURVEY_TOOL_DIRECTIVE} `);
+}
+
+/** The parent: starts the survey, waits for it, and reports the worker's answer. */
+export function respondAsSurveyParent(request: MockModelRequest): MockModelResponse | string {
+ return playScript(
+ request,
+ [
+ {
+ id: "survey-start",
+ input: () => ({ message: "Please count the tide survey stations for Alice." }),
+ name: "survey-worker",
+ },
+ { id: "survey-wait", name: "task_wait" },
+ ],
+ (finished) => `SURVEY-REPLY ${latestTaskResult(finished, "survey-worker") ?? "no result"}`,
+ );
+}
+
+/** The parent: runs the survey through the workflow tool and reports the worker's answer. */
+export function respondAsSurveyToolParent(request: MockModelRequest): MockModelResponse | string {
+ return playScript(request, [{ id: "survey-tool", name: "survey-through-tool" }], (finished) => {
+ const { survey } = JSON.parse(outputOf(finished, "survey-tool")) as { survey: string | null };
+ return `SURVEY-REPLY ${survey ?? "no result"}`;
+ });
+}
+
+/** The worker: answers in one model call that reports a large prompt. */
+export function respondAsSurveyWorker(): MockModelResponse {
+ return {
+ text: "Alice's tide survey has 12 stations.",
+ usage: { inputTokens: SURVEY_WORKER_INPUT_TOKENS, outputTokens: 20 },
+ };
+}
diff --git a/e2e/fixtures/agent-subagents/agent/subagents/survey-worker/agent.ts b/e2e/fixtures/agent-subagents/agent/subagents/survey-worker/agent.ts
new file mode 100644
index 000000000..83c9d20bd
--- /dev/null
+++ b/e2e/fixtures/agent-subagents/agent/subagents/survey-worker/agent.ts
@@ -0,0 +1,19 @@
+import { defineAgent, defineDynamic } from "eve";
+import { mockModel } from "eve/evals";
+
+import { respondAsSurveyWorker } from "../../lib/survey.js";
+
+const workerModel = mockModel({ modelId: "survey-worker", respond: respondAsSurveyWorker });
+
+/** Counts Alice's survey stations in one model call whose usage exceeds the parent's budget. */
+export default defineAgent({
+ description:
+ "Test fixture: counts Alice's tide survey stations. Call it only for SURVEY-DELEGATE directives.",
+ // Selected per step: in mock mode this fixture replaces static authored
+ // models with eve's bootstrap mock, which would drop the worker's usage.
+ model: defineDynamic({
+ events: {
+ "step.started": () => ({ model: workerModel, modelContextWindowTokens: 1_000_000 }),
+ },
+ }),
+});
diff --git a/e2e/fixtures/agent-subagents/agent/tools/survey-through-tool.ts b/e2e/fixtures/agent-subagents/agent/tools/survey-through-tool.ts
new file mode 100644
index 000000000..930418e8a
--- /dev/null
+++ b/e2e/fixtures/agent-subagents/agent/tools/survey-through-tool.ts
@@ -0,0 +1,29 @@
+import {
+ defineWorkflowTool,
+ type WorkflowToolContext,
+ type WorkflowToolDefinition,
+} from "eve/tools";
+import { z } from "zod";
+
+type Input = Record<string, never>;
+type Output = { survey: string | null };
+
+async function execute(_input: Input, ctx: WorkflowToolContext) {
+ "use workflow";
+
+ const response = await ctx
+ .agent("survey-worker")
+ .send("Please count the tide survey stations for Alice.");
+ const { message } = await response.result();
+ return { survey: message ?? null };
+}
+
+/** Runs Alice's survey through a `ctx.agent` session with survey-worker and returns its count. */
+const tool: WorkflowToolDefinition<Input, Output> = defineWorkflowTool({
+ description:
+ "Test fixture: counts Alice's tide survey stations through survey-worker. Call it only for SURVEY-TOOL directives.",
+ inputSchema: z.object({}),
+ execute,
+});
+
+export default tool;
diff --git a/e2e/fixtures/agent-subagents/constants.ts b/e2e/fixtures/agent-subagents/constants.ts
index 4014ddeaf..4b7394404 100644
--- a/e2e/fixtures/agent-subagents/constants.ts
+++ b/e2e/fixtures/agent-subagents/constants.ts
@@ -21,3 +21,10 @@ export const NOTEBOOK_NAME = "Harbor Lumen 4482";
export const NOTEBOOK_CORRECTION = `${NOTEBOOK_ENTRY} Correction: Alice meant the south pier, not the north pier.`;
/** What a keeper reports once it measures the pier Alice meant after her correction. */
export const CORRECTED_MEASUREMENT = "NOTEBOOK-DEPTH south pier 4.2 m";
+
+/** Starts Alice's survey request, which the parent delegates to one survey-worker task. */
+export const SURVEY_DIRECTIVE = "SURVEY-DELEGATE";
+/** Starts Alice's survey request, which the parent runs through the survey-through-tool workflow tool. */
+export const SURVEY_TOOL_DIRECTIVE = "SURVEY-TOOL";
+/** What survey-worker reports for its one model call: more than the parent's default 40M input budget. */
+export const SURVEY_WORKER_INPUT_TOKENS = 50_000_000;
diff --git a/e2e/fixtures/agent-subagents/evals/delegated-usage-limit-task.eval.ts b/e2e/fixtures/agent-subagents/evals/delegated-usage-limit-task.eval.ts
new file mode 100644
index 000000000..12e66f36f
--- /dev/null
+++ b/e2e/fixtures/agent-subagents/evals/delegated-usage-limit-task.eval.ts
@@ -0,0 +1,18 @@
+import { defineEval } from "eve/evals";
+
+import { SURVEY_DIRECTIVE } from "../constants";
+import { expectSurveyCountedAgainstParent } from "./delegated-usage-limit.shared";
+
+/** The parent starts one survey-worker task and waits for it; the task's reply carries its usage. */
+export default defineEval({
+ description:
+ "An agent task's token usage counts against the parent's session limit and continuation prompt.",
+ timeoutMs: 90_000,
+ async test(t) {
+ const session = await expectSurveyCountedAgainstParent(
+ t,
+ `${SURVEY_DIRECTIVE} Alice asks for the tide station survey.`,
+ );
+ session.event("task.started", { count: 1, data: { name: "survey-worker" } });
+ },
+});
diff --git a/e2e/fixtures/agent-subagents/evals/delegated-usage-limit-tool.eval.ts b/e2e/fixtures/agent-subagents/evals/delegated-usage-limit-tool.eval.ts
new file mode 100644
index 000000000..245f0d2ca
--- /dev/null
+++ b/e2e/fixtures/agent-subagents/evals/delegated-usage-limit-tool.eval.ts
@@ -0,0 +1,21 @@
+import { defineEval } from "eve/evals";
+
+import { SURVEY_TOOL_DIRECTIVE } from "../constants";
+import { expectSurveyCountedAgainstParent } from "./delegated-usage-limit.shared";
+
+/**
+ * The parent calls a workflow tool that opens a `ctx.agent` session with
+ * survey-worker; the tool's outcome carries the session's usage.
+ */
+export default defineEval({
+ description:
+ "A workflow tool's ctx.agent token usage counts against the parent's session limit and continuation prompt.",
+ timeoutMs: 90_000,
+ async test(t) {
+ const session = await expectSurveyCountedAgainstParent(
+ t,
+ `${SURVEY_TOOL_DIRECTIVE} Alice asks for the tide station survey.`,
+ );
+ session.calledTool("survey-through-tool", { count: 1 });
+ },
+});
diff --git a/e2e/fixtures/agent-subagents/evals/delegated-usage-limit.shared.ts b/e2e/fixtures/agent-subagents/evals/delegated-usage-limit.shared.ts
new file mode 100644
index 000000000..8c2a3f9bf
--- /dev/null
+++ b/e2e/fixtures/agent-subagents/evals/delegated-usage-limit.shared.ts
@@ -0,0 +1,37 @@
+import type { EveEvalContext } from "eve/evals";
+import { satisfies } from "eve/evals/expect";
+
+import { SURVEY_WORKER_INPUT_TOKENS } from "../constants";
+
+/**
+ * A delegated agent's spend counts against the session that delegated to it.
+ * Alice asks for a tide survey, and the parent hands it to survey-worker. The
+ * worker's one model call reports more input tokens than the parent's default
+ * session budget, so the parent's next model call stops at its own
+ * session-limit prompt, whose used figure includes the worker's tokens.
+ * Approving the prompt lets the parent report the survey. Returns the session
+ * for checks on how the parent delegated.
+ */
+export async function expectSurveyCountedAgainstParent(t: EveEvalContext, message: string) {
+ const { session } = await t.send(message);
+ const request = session.requireInputRequest({
+ display: "confirmation",
+ optionIds: ["continue", "stop"],
+ toolName: "session_limit_continuation",
+ });
+ const parentLimitPrefix = `${session.sessionId ?? ""}:limit:input:`;
+ await t.require(
+ request.requestId,
+ satisfies(
+ (requestId: string) =>
+ requestId.startsWith(parentLimitPrefix) &&
+ Number(requestId.slice(parentLimitPrefix.length)) >= SURVEY_WORKER_INPUT_TOKENS,
+ "the parent's input limit prompt counts the worker's tokens",
+ ),
+ );
+
+ const resumed = await session.respond([{ optionId: "continue", requestId: request.requestId }]);
+ resumed.expectOk();
+ resumed.messageIncludes("SURVEY-REPLY Alice's tide survey has 12 stations.");
+ return session;
+}
diff --git a/packages/eve/src/execution/agent-sessions/context.test.ts b/packages/eve/src/execution/agent-sessions/context.test.ts
new file mode 100644
index 000000000..4cde0bc0f
--- /dev/null
+++ b/packages/eve/src/execution/agent-sessions/context.test.ts
@@ -0,0 +1,92 @@
+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.ts
index 58e3d349b..49394a952 100644
--- a/packages/eve/src/execution/agent-sessions/context.ts
+++ b/packages/eve/src/execution/agent-sessions/context.ts
@@ -14,6 +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";
@@ -45,7 +46,7 @@ export interface AgentSessionContext {
readonly conversation?: ConversationContext;
/** Dynamic agents the calling turn selected, by node id. */
readonly dynamicSelections: DynamicSubagentSelections;
- /** The token budget each session inherits: the caller's remaining quota. */
+ /** 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. */
@@ -82,10 +83,29 @@ 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 {
@@ -99,7 +119,7 @@ export function captureAgentSessionContext(
channelMetadata: caller.channelMetadata,
conversation: caller.inheritedConversation,
dynamicSelections: caller.dynamicSubagentSelections,
- limits: resolveRemainingSessionTokenLimits(session),
+ limits,
localDevRequest: caller.localDevRequest,
parent: {
callId,
diff --git a/packages/eve/src/execution/agent-sessions/session.ts b/packages/eve/src/execution/agent-sessions/session.ts
index 3f3f80ba0..29a8b24a6 100644
--- a/packages/eve/src/execution/agent-sessions/session.ts
+++ b/packages/eve/src/execution/agent-sessions/session.ts
@@ -13,6 +13,7 @@ import {
type AgentSessionMessage,
type OpenedAgentSession,
} from "#execution/agent-sessions/steps.js";
+import type { RunUsageTally } from "#execution/agent-sessions/usage.js";
import { disposeHook } from "#execution/hook-ownership.js";
import type { WorkflowToolRunContext } from "#execution/tools/workflow/ask.js";
import type { RuntimeSubagentResult } from "#shared/action-types.js";
@@ -37,7 +38,10 @@ type AgentTurnEnd =
* run names its session, so replay reaches the same one, and `close` ends
* every session the run opened, cancelling any turn still running.
*/
-export function createAgentSessions(run: WorkflowToolRunContext): {
+export function createAgentSessions(
+ run: WorkflowToolRunContext,
+ usage: RunUsageTally,
+): {
readonly close: () => Promise<void>;
readonly open: (name: string) => AgentSession;
} {
@@ -50,7 +54,7 @@ export function createAgentSessions(run: WorkflowToolRunContext): {
}
const key = `${run.from.runId}:${String(handles)}`;
handles += 1;
- return new RunAgentSession({ key, name, run, sessions });
+ return new RunAgentSession({ key, name, run, sessions, usage });
},
close: async () => {
if (sessions.length === 0) return;
@@ -75,6 +79,8 @@ class RunAgentSession implements AgentSession {
readonly #run: WorkflowToolRunContext;
/** Every session the run opened, which it ends when it finishes. */
readonly #sessions: OpenedAgentSession[];
+ /** What the run's sessions spent, which the run reports to its calling session. */
+ readonly #usage: RunUsageTally;
#opened: Promise<OpenedAgentSession> | undefined;
/** Oldest first. */
readonly #awaited: AwaitedReply[] = [];
@@ -84,11 +90,13 @@ class RunAgentSession implements AgentSession {
readonly name: string;
readonly run: WorkflowToolRunContext;
readonly sessions: OpenedAgentSession[];
+ readonly usage: RunUsageTally;
}) {
this.#key = input.key;
this.#name = input.name;
this.#run = input.run;
this.#sessions = input.sessions;
+ this.#usage = input.usage;
}
async send<TOutput = unknown>(
@@ -133,7 +141,11 @@ class RunAgentSession implements AgentSession {
return reply;
}
- /** Forwards the turn's questions up to the session and returns its end. */
+ /**
+ * Forwards the turn's questions up to the session and returns its end. The
+ * turn's usage is tallied before its end settles any reply, so the reply the
+ * body sends with the turn's result carries it.
+ */
async #readTurn(hook: Hook<AgentTurnReply>, expectsData: boolean): Promise<AgentTurnEnd> {
try {
for await (const reply of hook) {
@@ -150,6 +162,7 @@ class RunAgentSession implements AgentSession {
(candidate): candidate is RuntimeSubagentResult => candidate.kind === "subagent-result",
);
if (result !== undefined) {
+ if (result.origin === "child") this.#usage.record(result.outcome.usageDelta);
return { kind: "ended", result: toAgentMessageResult(result, expectsData) };
}
}
diff --git a/packages/eve/src/execution/agent-sessions/usage.ts b/packages/eve/src/execution/agent-sessions/usage.ts
new file mode 100644
index 000000000..0bf0a156b
--- /dev/null
+++ b/packages/eve/src/execution/agent-sessions/usage.ts
@@ -0,0 +1,70 @@
+import {
+ accumulateSessionUsage,
+ getTurnUsageState,
+ setTurnUsageState,
+ toUsage,
+ type TokenUsageDelta,
+ type TurnUsageState,
+} from "#harness/turn-tag-state.js";
+import type { SessionStateMap } from "#harness/types.js";
+import type { TokenUsage } from "#shared/token-usage.js";
+
+// A delegated agent's spend counts against the session that delegated to it.
+// A run tallies what its `ctx.agent` sessions spend, and its replies and
+// outcome carry the running total to its calling session, which counts it in
+// the step that applies them. A `serve` run sends the total on its own only for
+// a turn no reply will carry. A run's messages reach the session in the order
+// it sent them, so each total is at least the last one counted. A child's
+// usage already includes what its own children spent, so a chain of agents
+// adds up at every level.
+
+/** What a run's `ctx.agent` sessions have spent, turn by turn. */
+export interface RunUsageTally {
+ /** Adds one ended turn's usage. */
+ record(turnUsage: TokenUsage): void;
+ /** The running total, or `undefined` before any turn ended. */
+ total(): TokenUsage | undefined;
+}
+
+/** `onRecord` runs after each recorded turn, so the run can send a total no reply will carry. */
+export function createRunUsageTally(onRecord?: () => void): RunUsageTally {
+ let spent: TurnUsageState | undefined;
+ return {
+ record(turnUsage) {
+ spent = accumulateSessionUsage({ previous: spent, usage: turnUsage });
+ onRecord?.();
+ },
+ total() {
+ return spent === undefined ? undefined : toUsage(spent.session);
+ },
+ };
+}
+
+/**
+ * Adds a run's delegated spend to the session's totals: its running `total`,
+ * less the part of it `counted` earlier.
+ */
+export function countRunUsage<T extends { readonly state?: SessionStateMap }>(
+ session: T,
+ total: TokenUsage,
+ counted?: TokenUsage,
+): T {
+ return setTurnUsageState(
+ session,
+ accumulateSessionUsage({
+ previous: getTurnUsageState(session.state),
+ usage: usageSince(total, counted),
+ }),
+ );
+}
+
+function usageSince(total: TokenUsage, counted: TokenUsage | undefined): TokenUsageDelta {
+ if (counted === undefined) return total;
+ return {
+ cacheReadTokens: total.cacheReadTokens - counted.cacheReadTokens,
+ cacheWriteTokens: total.cacheWriteTokens - counted.cacheWriteTokens,
+ costUsd: total.costUsd === undefined ? undefined : total.costUsd - (counted.costUsd ?? 0),
+ inputTokens: total.inputTokens - counted.inputTokens,
+ outputTokens: total.outputTokens - counted.outputTokens,
+ };
+}
diff --git a/packages/eve/src/execution/coordination-dispatch-step.ts b/packages/eve/src/execution/coordination-dispatch-step.ts
index 64fecd947..5d7576c30 100644
--- a/packages/eve/src/execution/coordination-dispatch-step.ts
+++ b/packages/eve/src/execution/coordination-dispatch-step.ts
@@ -9,7 +9,10 @@ import { createDurableSessionState } from "#execution/durable-session-store.js";
import { publishSessionEvents } from "#execution/publish-session-events.js";
import { startWorkflowTask, type StartWorkflowTaskInput } from "#execution/tools/workflow/start.js";
import { sendToTask, startTaskRun } from "#execution/tasks/start.js";
-import { captureAgentSessionContext } from "#execution/agent-sessions/context.js";
+import {
+ captureAgentSessionContext,
+ resolveStepAgentLimits,
+} from "#execution/agent-sessions/context.js";
import type { TaskStartedStreamEvent } from "#protocol/message.js";
import type { RuntimeActionResult } from "#shared/action-types.js";
import type { HarnessSession } from "#harness/types.js";
@@ -39,10 +42,11 @@ export async function dispatchCoordinationStep(
let nextSession = session;
const results: RuntimeActionResult[] = [];
const started: TaskStartedStreamEvent[] = [];
+ const agentLimits = resolveStepAgentLimits(prepared);
for (const task of prepared.plan) {
const start = {
- agentContext: captureAgentSessionContext(prepared, task.callId),
+ agentContext: captureAgentSessionContext(prepared, task.callId, agentLimits),
auth: { current: prepared.auth, initiator: prepared.initiatorAuth },
batchEvent: batch.event,
owner: input.workflowToolRunOwner,
diff --git a/packages/eve/src/execution/legacy-session/interrupt-step.test.ts b/packages/eve/src/execution/legacy-session/interrupt-step.test.ts
index 16fcc7761..fbc6c1bce 100644
--- a/packages/eve/src/execution/legacy-session/interrupt-step.test.ts
+++ b/packages/eve/src/execution/legacy-session/interrupt-step.test.ts
@@ -85,6 +85,7 @@ describe("legacy pending work", () => {
mocks.settle.mockResolvedValue({ sessionState: prepared.sessionState, serializedContext: {} });
await interruptLegacySessionStep(prepared);
expect(mocks.settle).toHaveBeenCalledExactlyOnceWith({
+ reportUsage: false,
sessionWritable: prepared.input.sessionWritable,
sessionState: prepared.sessionState,
serializedContext: {},
diff --git a/packages/eve/src/execution/legacy-session/interrupt-step.ts b/packages/eve/src/execution/legacy-session/interrupt-step.ts
index 92747b804..302c6149d 100644
--- a/packages/eve/src/execution/legacy-session/interrupt-step.ts
+++ b/packages/eve/src/execution/legacy-session/interrupt-step.ts
@@ -82,6 +82,7 @@ export async function interruptLegacySessionStep(prepared: PreparedLegacySession
serializedContext: prepared.serializedContext,
};
return await settleCancelledTurnStep({
+ reportUsage: false,
sessionWritable: prepared.input.sessionWritable,
serializedContext: prepared.serializedContext,
sessionState: prepared.sessionState,
diff --git a/packages/eve/src/execution/session-inbox/inbox.ts b/packages/eve/src/execution/session-inbox/inbox.ts
index c0668daf4..2ae2aef48 100644
--- a/packages/eve/src/execution/session-inbox/inbox.ts
+++ b/packages/eve/src/execution/session-inbox/inbox.ts
@@ -247,6 +247,7 @@ export function isWorkflowMessage(value: SessionInboxPayload): value is Workflow
value.kind === "reply" ||
value.kind === "request" ||
value.kind === "withdraw" ||
+ value.kind === "usage" ||
value.kind === "outcome"
);
}
diff --git a/packages/eve/src/execution/session-workflow-tool-run.ts b/packages/eve/src/execution/session-workflow-tool-run.ts
index c484b8750..1d595c6b3 100644
--- a/packages/eve/src/execution/session-workflow-tool-run.ts
+++ b/packages/eve/src/execution/session-workflow-tool-run.ts
@@ -35,9 +35,10 @@ export async function handleWorkflowToolRunMessage(
): Promise<RuntimeActionResult | undefined> {
const { message } = input;
switch (message.kind) {
- // Only task runs report started or reply, and the session applies those to the task table.
+ // Only task runs report started, reply, or usage, and the session applies those to the task table.
case "started":
case "reply":
+ case "usage":
return undefined;
case "outcome":
return await handleWorkflowToolRunOutcome({ ...input, message });
diff --git a/packages/eve/src/execution/session/program.ts b/packages/eve/src/execution/session/program.ts
index d6a00b99d..b6bb5f035 100644
--- a/packages/eve/src/execution/session/program.ts
+++ b/packages/eve/src/execution/session/program.ts
@@ -258,9 +258,10 @@ async function runSessionLoop(
if (next.delivery.caller !== undefined) progress.caller = next.delivery.caller;
return { action: await runTurn({ delivery: next.delivery }), kind: "action" };
};
- const settleCancelledTurn = async () => {
+ const settleCancelledTurn = async (reportUsage: boolean) => {
const settled = await settleCancelledTurnStep({
...cursor.stepState(),
+ reportUsage,
});
await cursor.apply(settled);
progress.caller = undefined;
@@ -311,7 +312,7 @@ async function runSessionLoop(
if (action.cancelled === true) {
const cancelledCaller = { caller: progress.caller, sessionId: boot.sessionId };
- const settled = await settleCancelledTurn();
+ const settled = await settleCancelledTurn(progress.caller !== undefined);
await notifyCancelledTaskCallerStep(
settled.usage === undefined
? cancelledCaller
@@ -353,7 +354,7 @@ async function runSessionLoop(
sessionState: cursor.sessionState,
});
await cancelWorkingTasks(cursor);
- await settleCancelledTurn();
+ await settleCancelledTurn(false);
// Cancellation consumes any outstanding caller; do not report the prior turn.
action = { ...action, settled: undefined };
continue;
diff --git a/packages/eve/src/execution/session/turn-step-types.ts b/packages/eve/src/execution/session/turn-step-types.ts
index 587e6365f..3d83e18ed 100644
--- a/packages/eve/src/execution/session/turn-step-types.ts
+++ b/packages/eve/src/execution/session/turn-step-types.ts
@@ -8,6 +8,8 @@ import type { TokenUsage } from "#shared/token-usage.js";
/** Trusted runtime-action results collected by the session owner. */
export interface RuntimeActionResultStepInput {
readonly acceptedAtMsByCallId?: Readonly<Record<string, number>>;
+ /** What the `ctx.agent` sessions of the `execute` runs behind these results spent. */
+ readonly delegatedUsage?: readonly TokenUsage[];
readonly results: readonly RuntimeActionResult[];
}
diff --git a/packages/eve/src/execution/session/turn-step.ts b/packages/eve/src/execution/session/turn-step.ts
index dedb8189f..6560fcf36 100644
--- a/packages/eve/src/execution/session/turn-step.ts
+++ b/packages/eve/src/execution/session/turn-step.ts
@@ -67,6 +67,7 @@ import {
PendingAuthorizationResultKey,
} from "#harness/authorization.js";
import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";
+import { countRunUsage } from "#execution/agent-sessions/usage.js";
import { createDurableSessionState, readDurableSession } from "#execution/durable-session-store.js";
import { buildRuntimeIdentity, createExecutionNodeStep } from "#execution/node-step.js";
import { prepareWorkflowPreambleTrace } from "#execution/workflow-trace-context.js";
@@ -106,6 +107,10 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>
const runtimeResults = input.input?.runtimeResults;
let durableSession = readDurableSession(input.sessionState);
+ // An `execute` run's delegated spend counts in the step that hands the model its result.
+ for (const usage of runtimeResults?.delegatedUsage ?? []) {
+ durableSession = countRunUsage(durableSession, usage);
+ }
const ctx = await deserializeContext(input.serializedContext);
const adapter = ctx.require(ChannelKey);
const bundle = ctx.require(BundleKey);
diff --git a/packages/eve/src/execution/session/turn.test.ts b/packages/eve/src/execution/session/turn.test.ts
index 89228af0c..1ac9d6231 100644
--- a/packages/eve/src/execution/session/turn.test.ts
+++ b/packages/eve/src/execution/session/turn.test.ts
@@ -11,7 +11,16 @@ import type { DeliverHookPayload, SessionCapabilities, TurnCaller } from "#chann
import { dispatchCoordinationStep } from "#execution/coordination-dispatch-step.js";
import { routeDeliverToChildren } from "#execution/route-child-delivery.js";
import { publishTurnWaitingStep } from "#execution/session/turn-waiting-step.js";
-import { createTask, readTaskTable, writeTaskTable } from "#execution/tasks/table.js";
+import {
+ createTask,
+ readTaskTable,
+ recordTaskRun,
+ settleTaskCalls,
+ writeTaskTable,
+} from "#execution/tasks/table.js";
+import { getSessionTokenUsage } from "#harness/turn-tag-state.js";
+import { registerWorkflowToolRun } from "#harness/workflow-tool-runs.js";
+import type { TokenUsage } from "#shared/token-usage.js";
vi.mock("#compiled/@workflow/core/index.js", async (importOriginal) => ({
...(await importOriginal()),
@@ -776,6 +785,183 @@ describe("SessionExecution checkpoints", () => {
expect(publishTurnWaitingStep).toHaveBeenCalledWith(expect.objectContaining({ sessionState }));
});
+ it("admits an idle agent task's usage report while the turn waits and counts it", async () => {
+ const base = state("");
+ // Alice's reviewer task answered earlier and is idle; its run is still live.
+ const created = createTask(readTaskTable(undefined), {
+ callId: "review-call",
+ kind: "agent",
+ name: "reviewer",
+ resumable: true,
+ turnId: "turn_0",
+ });
+ const running = recordTaskRun(created.table, created.taskId, {
+ hookToken: "reviewer-control",
+ runId: "reviewer-run",
+ });
+ const idle = settleTaskCalls(running, {
+ callIds: ["review-call"],
+ outcome: { output: "The plan looks ready.", status: "completed" },
+ taskId: created.taskId,
+ }).table;
+ const sessionState: DurableSessionState = {
+ ...base,
+ snapshot: { session: writeTaskTable(base.snapshot.session, idle) },
+ };
+ // A turn of the reviewer that no reply answers ends while Alice's turn waits on a call.
+ const payloads: SessionInboxPayload[] = [
+ {
+ from: {
+ callId: "review-call",
+ input: {},
+ runId: "reviewer-run",
+ sequence: 0,
+ stepIndex: 0,
+ taskId: created.taskId,
+ toolName: "reviewer",
+ turnId: "turn_0",
+ },
+ kind: "usage",
+ usage: { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 250, outputTokens: 25 },
+ },
+ { kind: "cancel" },
+ ];
+ const inbox: SessionInbox = {
+ claimedTokens: [],
+ claimSessionHook: vi.fn(),
+ claimSessionHooks: vi.fn(),
+ drain: vi.fn(() => []),
+ hasPending: vi.fn(() => false),
+ whenPending: () => new Promise<void>(() => {}),
+ next: vi.fn(async () => payloads.shift()),
+ onDelivery: vi.fn(() => () => {}),
+ onAgentStarted: () => () => {},
+ onInterrupt: vi.fn(() => () => {}),
+ restore: vi.fn(),
+ };
+ vi.mocked(turnStep)
+ .mockReset()
+ .mockResolvedValue({
+ action: "park",
+ hasPendingAuthorization: false,
+ hasPendingInputBatch: false,
+ pendingCoordinationCallIds: ["hold-call"],
+ serializedContext: {},
+ sessionState,
+ });
+ vi.mocked(dispatchCoordinationStep)
+ .mockReset()
+ .mockResolvedValue({ results: [], serializedContext: {}, sessionState });
+ const cursor = new SessionStateCursor({
+ inbox,
+ serializedContext: {},
+ sessionState,
+ sessionWritable: new WritableStream<Uint8Array>(),
+ });
+ const execution = new SessionExecution({
+ cursor,
+ inbox,
+ queue: new SessionInputQueue(),
+ sessionId: sessionState.sessionId,
+ });
+
+ await expect(
+ execution.runTurn({
+ delivery: { kind: "deliver", payloads: [{ message: "Hold the release." }] },
+ }),
+ ).resolves.toEqual({ cancelled: true, kind: "park" });
+
+ expect(getSessionTokenUsage(cursor.sessionState.snapshot.session)).toMatchObject({
+ inputTokens: 250,
+ outputTokens: 25,
+ });
+ });
+
+ it("hands the step each workflow run's delegated usage once, even when its outcome arrives twice", async () => {
+ const base = state("");
+ const tools = ["draft", "review"];
+ const sessionState: DurableSessionState = {
+ ...base,
+ snapshot: {
+ session: tools.reduce(
+ (session, name) =>
+ registerWorkflowToolRun(session, {
+ address: { hookToken: `${name}-control`, runId: `${name}-run` },
+ callId: `${name}-call`,
+ origin: { stepIndex: 0, turnId: "turn_0" },
+ toolName: name,
+ }),
+ base.snapshot.session,
+ ),
+ },
+ };
+ const spent = (inputTokens: number): TokenUsage => ({
+ cacheReadTokens: 0,
+ cacheWriteTokens: 0,
+ inputTokens,
+ outputTokens: 0,
+ });
+ const outcome = (name: string, inputTokens: number): SessionInboxPayload => ({
+ from: {
+ callId: `${name}-call`,
+ input: {},
+ runId: `${name}-run`,
+ sequence: 0,
+ stepIndex: 0,
+ toolName: name,
+ turnId: "turn_0",
+ },
+ kind: "outcome",
+ result: { output: `${name} finished`, status: "completed" },
+ usage: spent(inputTokens),
+ });
+ // The draft's outcome is delivered twice before the review finishes.
+ const payloads = [outcome("draft", 300), outcome("draft", 300), outcome("review", 500)];
+ const inbox: SessionInbox = {
+ claimedTokens: [],
+ claimSessionHook: vi.fn(),
+ claimSessionHooks: vi.fn(),
+ drain: vi.fn(() => []),
+ hasPending: vi.fn(() => false),
+ whenPending: () => new Promise<void>(() => {}),
+ next: vi.fn(async () => payloads.shift() ?? new Promise<never>(() => {})),
+ onDelivery: vi.fn(() => () => {}),
+ onAgentStarted: () => () => {},
+ onInterrupt: vi.fn(() => () => {}),
+ restore: vi.fn(),
+ };
+ vi.mocked(turnStep)
+ .mockReset()
+ .mockResolvedValueOnce({
+ action: "park",
+ hasPendingAuthorization: false,
+ hasPendingInputBatch: false,
+ pendingCoordinationCallIds: tools.map((name) => `${name}-call`),
+ serializedContext: {},
+ sessionState,
+ })
+ .mockResolvedValueOnce({
+ action: "done",
+ output: "done",
+ serializedContext: {},
+ sessionState,
+ });
+ vi.mocked(dispatchCoordinationStep)
+ .mockReset()
+ .mockResolvedValue({ results: [], serializedContext: {}, sessionState });
+
+ await expect(
+ createExecution({ inbox, sessionState }).runTurn({
+ delivery: { kind: "deliver", payloads: [{ message: "Draft the plan and review it." }] },
+ }),
+ ).resolves.toMatchObject({ kind: "done" });
+
+ expect(vi.mocked(turnStep).mock.calls[1]?.[0].input?.runtimeResults?.delegatedUsage).toEqual([
+ spent(300),
+ spent(500),
+ ]);
+ });
+
it("does not let steering that woke a wait interrupt the step that reads it", async () => {
const base = state("");
const working = createTask(readTaskTable(undefined), {
diff --git a/packages/eve/src/execution/session/turn.ts b/packages/eve/src/execution/session/turn.ts
index e0a68c242..9649f0863 100644
--- a/packages/eve/src/execution/session/turn.ts
+++ b/packages/eve/src/execution/session/turn.ts
@@ -57,6 +57,7 @@ import {
} from "#harness/workflow-tool-runs.js";
import { resolveRuntimeActionResultsForCallIds } from "#runtime/actions/results.js";
import type { RuntimeActionResult } from "#shared/action-types.js";
+import type { TokenUsage } from "#shared/token-usage.js";
/** True when a delegating parent (local or remote) receives this session's input requests. */
export function hasDelegatedCallerContext(serializedContext: Record<string, unknown>): boolean {
@@ -285,6 +286,8 @@ export class SessionExecution {
const results: RuntimeActionResult[] = [...input.initialResults];
let interrupted = false;
const acceptedAtMsByCallId = new Map<string, number>();
+ // By call id, so an outcome delivered twice counts once.
+ const delegatedUsageByCallId = new Map<string, TokenUsage>();
if (input.initialAcceptedAtMs !== undefined) {
for (const result of results)
acceptedAtMsByCallId.set(result.callId, input.initialAcceptedAtMs);
@@ -302,10 +305,15 @@ export class SessionExecution {
results,
});
if (ready !== undefined) {
+ const delegatedUsage = ready.flatMap((result) => {
+ const usage = delegatedUsageByCallId.get(result.callId);
+ return usage === undefined ? [] : [usage];
+ });
return {
acceptedAtMsByCallId: Object.fromEntries(
ready.map((result) => [result.callId, acceptedAtMsByCallId.get(result.callId)!]),
),
+ ...(delegatedUsage.length > 0 && { delegatedUsage }),
results: ready,
};
}
@@ -341,7 +349,11 @@ export class SessionExecution {
}
const result = await this.handleWorkflowMessage(next.message);
- if (result !== undefined) accept(result);
+ if (result === undefined) continue;
+ accept(result);
+ if (next.message.kind === "outcome" && next.message.usage !== undefined) {
+ delegatedUsageByCallId.set(result.callId, next.message.usage);
+ }
}
}
diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.test.ts b/packages/eve/src/execution/settle-cancelled-turn-step.test.ts
new file mode 100644
index 000000000..97cab8126
--- /dev/null
+++ b/packages/eve/src/execution/settle-cancelled-turn-step.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it, vi } from "vitest";
+
+import type { HarnessSession, SessionStateMap } from "#harness/types.js";
+import { readDurableSession } from "#execution/durable-session-store.js";
+import { settleCancelledTurnStep } from "#execution/settle-cancelled-turn-step.js";
+import {
+ accumulateTurnUsage,
+ getTurnUsageState,
+ setTurnUsageState,
+ takeSessionUsageDelta,
+} from "#harness/turn-tag-state.js";
+import { createTestSessionState } from "#internal/testing/session-state.js";
+
+// The turn's stream events and channel context are not under test; the usage
+// the step reports and the session it persists are.
+vi.mock("#context/serialize.js", () => ({
+ deserializeContext: async () => ({ get: () => undefined }),
+ serializeContext: () => ({}),
+}));
+vi.mock("#execution/publish-session-events.js", () => ({
+ withSessionEventEmitter: async (
+ input: { readonly durableSession: HarnessSession },
+ emitEvents: (
+ emit: () => Promise<void>,
+ session: HarnessSession,
+ ) => Promise<{ readonly result: unknown; readonly session: HarnessSession }>,
+ // Hydration of a session with no compaction history yields empty compaction state.
+ ) =>
+ await emitEvents(async () => {}, { ...input.durableSession, compaction: {} } as HarnessSession),
+}));
+
+function spend<T extends { readonly state?: SessionStateMap }>(
+ session: T,
+ inputTokens: number,
+ turnId: string,
+): T {
+ return setTurnUsageState(
+ session,
+ accumulateTurnUsage({
+ previous: getTurnUsageState(session.state),
+ turnId,
+ usage: { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens, outputTokens: 0 },
+ }),
+ );
+}
+
+describe("settleCancelledTurnStep", () => {
+ it.each([
+ { reportUsage: true, reported: 50, nextSettled: 0 },
+ { reportUsage: false, reported: undefined, nextSettled: 50 },
+ ])(
+ "reports only what the session spent since its caller's last report (reports usage: $reportUsage)",
+ async ({ reportUsage, reported, nextSettled }) => {
+ const base = createTestSessionState({
+ emissionState: { sequence: 1, sessionStarted: true, stepIndex: 0, turnId: "turn_2" },
+ sessionId: "reviewer-session",
+ });
+ // The reviewer's first turn spent 100 tokens and settled, reporting them.
+ const settled = takeSessionUsageDelta(spend(base.snapshot.session, 100, "turn_1")).session;
+ // Its next turn spent 50 more before Alice cancelled it.
+ const cancelling = spend(settled, 50, "turn_2");
+
+ const result = await settleCancelledTurnStep({
+ reportUsage,
+ serializedContext: {},
+ sessionState: { ...base, snapshot: { session: cancelling } },
+ sessionWritable: new WritableStream<Uint8Array>(),
+ });
+
+ expect(result.usage?.inputTokens).toBe(reported);
+ // The next settled turn reports whatever the cancel didn't.
+ expect(takeSessionUsageDelta(readDurableSession(result.sessionState)).delta.inputTokens).toBe(
+ nextSettled,
+ );
+ },
+ );
+});
diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.ts b/packages/eve/src/execution/settle-cancelled-turn-step.ts
index 10f3ff9fb..a9648d777 100644
--- a/packages/eve/src/execution/settle-cancelled-turn-step.ts
+++ b/packages/eve/src/execution/settle-cancelled-turn-step.ts
@@ -15,12 +15,13 @@ import { clearPendingSessionLimitPrompt } from "#harness/input-requests.js";
import { getHarnessEmissionState, setHarnessEmissionState } from "#harness/emission.js";
import { clearAllProxyInputRequests } from "#harness/proxy-input-requests.js";
import { removeBlockingWorkflowToolRuns } from "#harness/workflow-tool-runs.js";
-import { getTurnUsageState, toUsage } from "#harness/turn-tag-state.js";
+import { getTurnUsageState, takeSessionUsageDelta } from "#harness/turn-tag-state.js";
import type { TokenUsage } from "#shared/token-usage.js";
export interface CancelledTurnSettleResult {
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
+ /** What the session spent since its caller's last report, when asked to report it. */
readonly usage?: TokenUsage;
}
@@ -31,6 +32,11 @@ export interface CancelledTurnSettleResult {
* cancel hook, so a queued cancel wake cannot re-dispatch it.
*/
export async function settleCancelledTurnStep(input: {
+ /**
+ * Whether a caller receives the turn's usage. Only then is it marked
+ * reported; otherwise the next settled turn reports it.
+ */
+ readonly reportUsage: boolean;
readonly sessionWritable: WritableStream<Uint8Array>;
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
@@ -71,11 +77,16 @@ export async function settleCancelledTurnStep(input: {
emissionState,
),
);
- const totals = getTurnUsageState(session.state)?.session;
-
- const base = {
- serializedContext: serializeContext(ctx),
- sessionState: createDurableSessionState({ session: cancelledSession }),
+ const base = { serializedContext: serializeContext(ctx) };
+ if (!input.reportUsage || getTurnUsageState(session.state) === undefined) {
+ return { ...base, sessionState: createDurableSessionState({ session: cancelledSession }) };
+ }
+ // Reported like a settled turn, as usage since the last report, so the
+ // caller counts each turn once whether it settled or was cancelled.
+ const reported = takeSessionUsageDelta(cancelledSession);
+ return {
+ ...base,
+ sessionState: createDurableSessionState({ session: reported.session }),
+ usage: reported.delta,
};
- return totals === undefined ? base : { ...base, usage: toUsage(totals) };
}
diff --git a/packages/eve/src/execution/tasks/session.ts b/packages/eve/src/execution/tasks/session.ts
index 74e9d2baf..1ebdde2c9 100644
--- a/packages/eve/src/execution/tasks/session.ts
+++ b/packages/eve/src/execution/tasks/session.ts
@@ -19,7 +19,12 @@ import type { RuntimeActionResult } from "#shared/action-types.js";
/** Whether a run's message changes a task record. */
export function isTaskRunMessage(message: WorkflowToolRunMessage): message is TaskRunMessage {
if (message.from.taskId === undefined) return false;
- return message.kind === "started" || message.kind === "reply" || message.kind === "outcome";
+ return (
+ message.kind === "started" ||
+ message.kind === "reply" ||
+ message.kind === "usage" ||
+ message.kind === "outcome"
+ );
}
/** The session's task table as the workflow body last committed it. */
diff --git a/packages/eve/src/execution/tasks/steps.ts b/packages/eve/src/execution/tasks/steps.ts
index bea49bb21..66ecc517d 100644
--- a/packages/eve/src/execution/tasks/steps.ts
+++ b/packages/eve/src/execution/tasks/steps.ts
@@ -10,6 +10,7 @@ import {
finishTaskRun,
markTaskRunStarted,
readTaskTable,
+ recordTaskRunUsage,
settleRemainingTaskCalls,
settleTaskCalls,
writeTaskTable,
@@ -20,6 +21,7 @@ import {
type TaskTable,
} from "#execution/tasks/table.js";
import { ignoreGoneTarget } from "#execution/tasks/workflow-target.js";
+import { countRunUsage } from "#execution/agent-sessions/usage.js";
import {
publishSessionEvents,
relaySessionEvents,
@@ -40,12 +42,12 @@ import { createTaskSettledEvent, type TaskSettledStreamEvent } from "#protocol/m
/** The messages a task's run sends that change its record. */
export type TaskRunMessage = Extract<
WorkflowToolRunMessage,
- { readonly kind: "outcome" | "reply" | "started" }
+ { readonly kind: "outcome" | "reply" | "started" | "usage" }
>;
const TASK_CANCEL_REASON = "The task was cancelled.";
-/** Applies one message from a task's run: started, a reply, or the run's outcome. */
+/** Applies one message from a task's run: started, a reply, usage no reply carried, or the run's outcome. */
export async function applyTaskRunMessageStep(
input: SessionStepState & { readonly message: TaskRunMessage },
): Promise<PublishedSessionEvents> {
@@ -67,13 +69,18 @@ export async function applyTaskRunMessageStep(
break;
}
case "reply": {
+ ({ session, table } = countTaskRunUsage(session, table, taskId, message));
const outcome: TaskOutcome = { output: message.output, status: "completed" };
const settled = settleTaskCalls(table, { callIds: message.callIds, outcome, taskId });
table = settled.table;
events.push(...settled.settled.map((call) => taskSettledEvent(taskId, call, outcome)));
break;
}
+ case "usage":
+ ({ session, table } = countTaskRunUsage(session, table, taskId, message));
+ break;
case "outcome": {
+ ({ session, table } = countTaskRunUsage(session, table, taskId, message));
const outcome = toOutcome(message);
const settled = settleRemainingTaskCalls(table, taskId, outcome);
events.push(...settled.settled.map((call) => taskSettledEvent(taskId, call, outcome)));
@@ -182,6 +189,26 @@ function failureMessage(message: WorkflowToolRunOutcomeMessage): string {
return typeof described === "string" ? described : JSON.stringify(output);
}
+/**
+ * Counts what the delegated spend a reply, usage report, or outcome carries
+ * adds to what the session counted from its run. Only while that run is the
+ * task's run: a redelivered outcome arrives after the run finished, and adds
+ * nothing.
+ */
+function countTaskRunUsage(
+ session: DurableSession,
+ table: TaskTable,
+ taskId: string,
+ message: Extract<TaskRunMessage, { readonly kind: "outcome" | "reply" | "usage" }>,
+): { readonly session: DurableSession; readonly table: TaskTable } {
+ const run = findTask(table, taskId)?.run;
+ if (message.usage === undefined || run?.runId !== message.from.runId) return { session, table };
+ return {
+ session: countRunUsage(session, message.usage, run.usage),
+ table: recordTaskRunUsage(table, taskId, message.usage),
+ };
+}
+
/** A finished run can no longer take answers, so its unanswered questions are dropped. */
function forgetRunQuestions(session: DurableSession, runId: string): DurableSession {
return clearProxyInputRequestsWhere(session, (route) => route.workflowAsk?.runId === runId);
diff --git a/packages/eve/src/execution/tasks/table.ts b/packages/eve/src/execution/tasks/table.ts
index ddb950d0c..7f6f8be3c 100644
--- a/packages/eve/src/execution/tasks/table.ts
+++ b/packages/eve/src/execution/tasks/table.ts
@@ -3,6 +3,7 @@ import type { WorkflowToolRunCall } from "#execution/tools/workflow/messages.js"
import type { SessionStateMap } from "#harness/types.js";
import { isNonEmptyString, isObject } from "#shared/guards.js";
import type { JsonValue } from "#shared/json.js";
+import type { TokenUsage } from "#shared/token-usage.js";
import type { TaskStartedStreamEvent } from "#protocol/message.js";
import { UNREADABLE_TASK_ERROR } from "#execution/tasks/render.js";
@@ -33,6 +34,8 @@ export interface TaskRunAddress {
/** The workflow run doing a task's work. `started` once its control hook can take commands. */
export interface TaskRun extends TaskRunAddress {
readonly started: boolean;
+ /** The run's delegated spend the session counted so far, which later totals count from. */
+ readonly usage?: TokenUsage;
}
/** A call the task admitted and hasn't settled, with the turn that made it. */
@@ -322,6 +325,13 @@ export function settleRemainingTaskCalls(
return settleTaskCalls(table, { callIds, outcome, taskId });
}
+/** Records the run's delegated spend the session just counted. */
+export function recordTaskRunUsage(table: TaskTable, taskId: string, usage: TokenUsage): TaskTable {
+ return updateTask(table, taskId, (record) =>
+ record.run === undefined ? record : { ...record, run: { ...record.run, usage } },
+ );
+}
+
/** The task's run finished; nothing is left to cancel. */
export function finishTaskRun(table: TaskTable, taskId: string, runId: string): TaskTable {
return updateTask(table, taskId, (record) => {
@@ -494,7 +504,8 @@ function isTaskRun(value: unknown): value is TaskRun {
isObject(value) &&
isNonEmptyString(value.runId) &&
isNonEmptyString(value.hookToken) &&
- typeof value.started === "boolean"
+ typeof value.started === "boolean" &&
+ (value.usage === undefined || isObject(value.usage))
);
}
diff --git a/packages/eve/src/execution/tasks/task-run-usage.test.ts b/packages/eve/src/execution/tasks/task-run-usage.test.ts
new file mode 100644
index 000000000..5bef3a24b
--- /dev/null
+++ b/packages/eve/src/execution/tasks/task-run-usage.test.ts
@@ -0,0 +1,164 @@
+import { describe, expect, it, vi } from "vitest";
+
+import type { DurableSession } from "#execution/durable-session-store.js";
+import type { SessionInbox } from "#execution/session-inbox/inbox.js";
+import { SessionInputQueue } from "#execution/session/input-queue.js";
+import { SessionStateCursor } from "#execution/session/state-cursor.js";
+import { SessionExecution } from "#execution/session/turn.js";
+import {
+ createTask,
+ readTaskTable,
+ recordTaskRun,
+ writeTaskTable,
+} from "#execution/tasks/table.js";
+import type { WorkflowToolRunRef } from "#execution/tools/workflow/messages.js";
+import {
+ getSessionTokenUsage,
+ getSessionUsageLimitViolation,
+ 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";
+
+// The settled calls' stream events are not under test; the committed session is.
+vi.mock("#execution/publish-session-events.js", () => ({
+ publishSessionEvents: async ({
+ serializedContext,
+ sessionState,
+ }: {
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: unknown;
+ }) => ({ serializedContext, sessionState }),
+ relaySessionEvents: async ({
+ serializedContext,
+ sessionState,
+ }: {
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: unknown;
+ }) => ({ serializedContext, sessionState }),
+}));
+
+function usage(inputTokens: number, costUsd?: number): TokenUsage {
+ return { cacheReadTokens: 0, cacheWriteTokens: 0, costUsd, inputTokens, outputTokens: 0 };
+}
+
+/**
+ * A session that has spent `ownInputTokens` itself, under `limits`, 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;
+}): {
+ readonly cursor: SessionStateCursor;
+ readonly execution: SessionExecution;
+ readonly from: WorkflowToolRunRef;
+} {
+ const base = createTestSessionState({ sessionId: `${input.name}-parent` });
+ const own = { ...usage(input.ownInputTokens), costUsd: 0, sawCost: false };
+ const created = createTask(readTaskTable(undefined), {
+ callId: `${input.name}-call`,
+ kind: "agent",
+ name: input.name,
+ resumable: true,
+ turnId: "turn_1",
+ });
+ const runId = `${input.name}-run`;
+ const table = recordTaskRun(created.table, created.taskId, {
+ hookToken: `${runId}-control`,
+ runId,
+ });
+ const snapshot = writeTaskTable(
+ setTurnUsageState(
+ { ...base.snapshot.session, limits: input.limits },
+ { ...own, session: own, turnId: "turn_1" },
+ ),
+ table,
+ );
+ const inbox = {
+ claimSessionHooks: vi.fn(),
+ onAgentStarted: () => () => {},
+ onDelivery: () => () => {},
+ onInterrupt: () => () => {},
+ } as Partial<SessionInbox> as SessionInbox;
+ const cursor = new SessionStateCursor({
+ inbox,
+ serializedContext: {},
+ sessionState: { ...base, snapshot: { session: snapshot } },
+ sessionWritable: new WritableStream<Uint8Array>(),
+ });
+ const execution = new SessionExecution({
+ cursor,
+ inbox,
+ queue: new SessionInputQueue(),
+ sessionId: base.sessionId,
+ });
+ const from: WorkflowToolRunRef = {
+ callId: `${input.name}-call`,
+ input: {},
+ runId,
+ sequence: 1,
+ stepIndex: 0,
+ taskId: created.taskId,
+ toolName: input.name,
+ turnId: "turn_1",
+ };
+ return { cursor, execution, from };
+}
+
+function committed(cursor: SessionStateCursor): DurableSession {
+ return cursor.sessionState.snapshot.session;
+}
+
+function spent(cursor: SessionStateCursor): TokenUsage {
+ return toUsage(getSessionTokenUsage(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 () => {
+ const alice = sessionWithTask({
+ limits: { maxInputTokensPerSession: 1_000 },
+ name: "reviewer",
+ ownInputTokens: 100,
+ });
+ const { from } = alice;
+ const reply = {
+ callIds: [from.callId],
+ from,
+ kind: "reply" as const,
+ output: "The plan looks ready.",
+ usage: usage(300, 0.25),
+ };
+ // The reply is delivered twice.
+ await alice.execution.handleWorkflowMessage(reply);
+ await alice.execution.handleWorkflowMessage(reply);
+
+ expect(spent(alice.cursor)).toEqual(usage(400, 0.25));
+
+ // Alice cancels the reviewer's next turn; no reply carries its 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();
+
+ const outcome = {
+ from,
+ kind: "outcome" as const,
+ result: { output: "Reviewed.", status: "completed" as const },
+ usage: usage(900, 0.75),
+ };
+ // The outcome is delivered twice too; the second arrives after the task's run finished.
+ await alice.execution.handleWorkflowMessage(outcome);
+ 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,
+ });
+ });
+});
diff --git a/packages/eve/src/execution/tools/workflow/body.ts b/packages/eve/src/execution/tools/workflow/body.ts
index 18ff49508..9458a73a0 100644
--- a/packages/eve/src/execution/tools/workflow/body.ts
+++ b/packages/eve/src/execution/tools/workflow/body.ts
@@ -3,6 +3,7 @@ import { getWorkflowMetadata } from "#compiled/@workflow/core/index.js";
import type { SessionContext } from "#context/session-context.js";
import type { AgentSessionContext } from "#execution/agent-sessions/context.js";
import { createAgentSessions } from "#execution/agent-sessions/session.js";
+import { createRunUsageTally, type RunUsageTally } from "#execution/agent-sessions/usage.js";
import type {
AgentSession,
WorkflowSharedContext,
@@ -69,6 +70,8 @@ export interface StartedWorkflowBody {
close(): Promise<void>;
readonly control: WorkflowBodyControl;
readonly outcome: Promise<WorkflowToolRunOutcome>;
+ /** What the body's `ctx.agent` sessions spent, which the run's outcome carries. */
+ readonly usage: RunUsageTally;
}
type WorkflowCallContext = ToolContext & WorkflowToolContext;
@@ -147,7 +150,8 @@ export function startCallBody(input: WorkflowBodyInput): StartedWorkflowBody {
from,
owner: input.owner,
};
- const agentSessions = createAgentSessions(run);
+ const usage = createRunUsageTally();
+ const agentSessions = createAgentSessions(run, usage);
const ctx = createCallContext(input, signals, agentSessions.open);
attachWorkflowToolRunContext(ctx, run);
return {
@@ -155,6 +159,7 @@ export function startCallBody(input: WorkflowBodyInput): StartedWorkflowBody {
close: agentSessions.close,
control: signals,
outcome: executeCallBody(input, ctx, signals, from),
+ usage,
};
}
diff --git a/packages/eve/src/execution/tools/workflow/messages.ts b/packages/eve/src/execution/tools/workflow/messages.ts
index 91ccaf333..e391bec1f 100644
--- a/packages/eve/src/execution/tools/workflow/messages.ts
+++ b/packages/eve/src/execution/tools/workflow/messages.ts
@@ -4,6 +4,7 @@ import type { AgentSessionContext } from "#execution/agent-sessions/context.js";
import type { AgentSessionAddress } from "#execution/agent-sessions/steps.js";
import type { InputRequest } from "#shared/input.js";
import type { JsonObject, JsonValue } from "#shared/json.js";
+import type { TokenUsage } from "#shared/token-usage.js";
import type {
ToolInputRequest,
ToolInputResponse,
@@ -84,6 +85,8 @@ export interface WorkflowToolRunRequestMessage {
export interface WorkflowToolRunOutcomeMessage {
readonly from: WorkflowToolRunRef;
readonly result: WorkflowToolRunOutcome;
+ /** What the run's `ctx.agent` sessions spent in all, once any of their turns ended. */
+ readonly usage?: TokenUsage;
}
/**
@@ -114,6 +117,22 @@ export interface WorkflowToolRunReplyMessage {
/** The latest call the reply settles, which the body serves now. */
readonly from: WorkflowToolRunRef;
readonly output: JsonValue;
+ /**
+ * What the run's `ctx.agent` sessions spent so far, once any of their turns
+ * ended. A running total, so the session counts only what it adds to the
+ * last one it counted, and a redelivered reply adds nothing.
+ */
+ readonly usage?: TokenUsage;
+}
+
+/**
+ * A `serve` body's delegated spend that no reply carries: its `ctx.agent`
+ * sessions ended a turn while no call waited for a reply, such as a turn a
+ * cancel stopped. A running total, like a reply's.
+ */
+export interface WorkflowToolRunUsageMessage {
+ readonly from: WorkflowToolRunRef;
+ readonly usage: TokenUsage;
}
/** A task's run can take commands: its control hook is registered. */
@@ -128,6 +147,7 @@ export type WorkflowToolRunMessage =
| ({ readonly kind: "reply" } & WorkflowToolRunReplyMessage)
| ({ readonly kind: "request" } & WorkflowToolRunRequestMessage)
| ({ readonly kind: "withdraw" } & WorkflowToolRunWithdrawMessage)
+ | ({ readonly kind: "usage" } & WorkflowToolRunUsageMessage)
| ({ readonly kind: "outcome" } & WorkflowToolRunOutcomeMessage);
/**
diff --git a/packages/eve/src/execution/tools/workflow/serve.ts b/packages/eve/src/execution/tools/workflow/serve.ts
index ad465b2fa..a4ef02308 100644
--- a/packages/eve/src/execution/tools/workflow/serve.ts
+++ b/packages/eve/src/execution/tools/workflow/serve.ts
@@ -1,6 +1,7 @@
import type { SessionContext } from "#context/session-context.js";
import type { AgentSessionContext } from "#execution/agent-sessions/context.js";
import { createAgentSessions } from "#execution/agent-sessions/session.js";
+import { createRunUsageTally, type RunUsageTally } from "#execution/agent-sessions/usage.js";
import {
ask,
attachWorkflowToolRunContext,
@@ -26,6 +27,7 @@ import type {
} from "#execution/tools/workflow/messages.js";
import type { WorkflowToolRunInbox } from "#execution/tools/workflow/owner.js";
import type { JsonValue } from "#shared/json.js";
+import type { TokenUsage } from "#shared/token-usage.js";
import type { ToolContext } from "#tools/definition.js";
import type {
AgentSession,
@@ -88,6 +90,14 @@ class WorkflowServeCalls implements WorkflowBodyControl {
private readonly runRef: WorkflowToolRunRef;
private readonly runSession: SessionContext["session"];
private readonly owner: WorkflowToolRunInbox;
+ /**
+ * What the body's `ctx.agent` sessions spent. Each reply carries the total,
+ * and a turn that ends while no call waits for a reply, such as one a cancel
+ * stopped, sends it on its own, since no reply would carry it.
+ */
+ readonly usage: RunUsageTally = createRunUsageTally(() => this.sendUncarriedUsage());
+ /** The latest total a message carried, so a turn that spent nothing sends none. */
+ private carriedUsage: TokenUsage | undefined;
private readonly toolName: string;
private readonly seenCallIds: Set<string>;
private firstReceived = false;
@@ -211,6 +221,18 @@ class WorkflowServeCalls implements WorkflowBodyControl {
await this.replies;
}
+ /** Sends the usage total when no call waits for the reply that would carry it. */
+ private sendUncarriedUsage(): void {
+ if (this.waiting.length > 0 || this.endedBy !== undefined) return;
+ const { from } = this.latest;
+ this.replies = this.replies.then(async () => {
+ const usage = this.usage.total();
+ if (usage === undefined || isSameUsage(usage, this.carriedUsage)) return;
+ this.carriedUsage = usage;
+ await this.owner.send({ from, kind: "usage", usage });
+ });
+ }
+
/** A later call reached the run. Redelivered calls are ignored. */
private accept(call: WorkflowToolRunCall): void {
if (this.endedBy !== undefined || this.seenCallIds.has(call.callId)) return;
@@ -294,10 +316,29 @@ class WorkflowServeCalls implements WorkflowBodyControl {
const latest = calls.at(-1);
if (latest === undefined) return;
const callIds = calls.map((served) => served.from.callId);
- await this.owner.send({ callIds, from: latest.from, kind: "reply", output });
+ const usage = this.usage.total();
+ this.carriedUsage = usage;
+ await this.owner.send({
+ callIds,
+ from: latest.from,
+ kind: "reply",
+ output,
+ ...(usage !== undefined && { usage }),
+ });
}
}
+function isSameUsage(total: TokenUsage, carried: TokenUsage | undefined): boolean {
+ return (
+ carried !== undefined &&
+ total.inputTokens === carried.inputTokens &&
+ total.outputTokens === carried.outputTokens &&
+ total.cacheReadTokens === carried.cacheReadTokens &&
+ total.cacheWriteTokens === carried.cacheWriteTokens &&
+ total.costUsd === carried.costUsd
+ );
+}
+
/** Starts a `serve` body, which runs once for its task and serves every call to it. */
export function startServeBody(input: WorkflowBodyInput): StartedWorkflowBody {
const calls = new WorkflowServeCalls(input);
@@ -315,7 +356,7 @@ export function startServeBody(input: WorkflowBodyInput): StartedWorkflowBody {
},
owner: input.owner,
};
- const agentSessions = createAgentSessions(run);
+ const agentSessions = createAgentSessions(run, calls.usage);
const ctx = createServeContext(input, calls, agentSessions.open);
attachWorkflowToolRunContext(ctx, run);
return {
@@ -323,6 +364,7 @@ export function startServeBody(input: WorkflowBodyInput): StartedWorkflowBody {
close: agentSessions.close,
control: calls,
outcome: executeServeBody(input, calls, ctx),
+ usage: calls.usage,
};
}
diff --git a/packages/eve/src/execution/tools/workflow/workflow.test.ts b/packages/eve/src/execution/tools/workflow/workflow.test.ts
index bc3d93d69..7baefb722 100644
--- a/packages/eve/src/execution/tools/workflow/workflow.test.ts
+++ b/packages/eve/src/execution/tools/workflow/workflow.test.ts
@@ -13,6 +13,7 @@ const mocks = vi.hoisted(() => ({
deliver: vi.fn(),
runBody: vi.fn(),
applyCommand: vi.fn(),
+ usageTotal: vi.fn(),
body: { runSignal: new AbortController().signal },
openWorkflowToolRunOwnerInbox: vi.fn(),
}));
@@ -50,6 +51,7 @@ vi.mock("#execution/tools/workflow/body.js", () => ({
},
},
outcome: mocks.runBody(input),
+ usage: { record: () => {}, total: mocks.usageTotal },
}),
}));
vi.mock("#execution/tools/workflow/owner.js", () => ({
@@ -123,6 +125,28 @@ it("emits every persisted report before the terminal outcome", async () => {
expect(mocks.runBody).toHaveBeenCalledWith(expect.objectContaining({ owner: invocationOwner }));
});
+it("carries what the body's agent sessions spent on the outcome", async () => {
+ const spent = { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 1_500, outputTokens: 150 };
+ mocks.usageTotal.mockReturnValue(spent);
+ mocks.openWorkflowToolRunOwnerInbox.mockReturnValue({
+ owner: { send: vi.fn(), sent: 0 },
+ reader: createChannelReader("workflow", {
+ [Symbol.asyncIterator]: () => ({
+ next: () => new Promise<IteratorResult<never>>(() => {}),
+ }),
+ }),
+ });
+
+ await workflowToolRunWorkflow(input);
+
+ expect(mocks.deliver).toHaveBeenCalledTimes(1);
+ expect(mocks.deliver).toHaveBeenCalledWith(
+ "parent",
+ expect.objectContaining({ kind: "outcome", usage: spent }),
+ { ifPresent: false },
+ );
+});
+
it.each(["completed", "failed", "cancelled", "throw", "blocked"] as const)(
"keeps cancellation final when cleanup is %s",
async (status) => {
diff --git a/packages/eve/src/execution/tools/workflow/workflow.ts b/packages/eve/src/execution/tools/workflow/workflow.ts
index c83dda1b3..f61c73b3c 100644
--- a/packages/eve/src/execution/tools/workflow/workflow.ts
+++ b/packages/eve/src/execution/tools/workflow/workflow.ts
@@ -129,10 +129,12 @@ export async function workflowToolRunWorkflow(input: WorkflowToolRunInput): Prom
};
}
if (outcome !== undefined) {
+ const usage = started.usage.total();
await owner.handleMessage({
from: createWorkflowBodyRef(input),
kind: "outcome",
result: outcome,
+ ...(usage !== undefined && { usage }),
});
}
}
diff --git a/packages/eve/src/harness/turn-tag-state.ts b/packages/eve/src/harness/turn-tag-state.ts
index 3545ac916..0002738f5 100644
--- a/packages/eve/src/harness/turn-tag-state.ts
+++ b/packages/eve/src/harness/turn-tag-state.ts
@@ -246,11 +246,12 @@ export function accumulateTurnUsage(input: {
}
/**
- * Folds a delegated child session's reported totals into the parent's
- * session totals without touching the in-flight turn totals. Turn tags
- * attribute only the parent's own model calls (child spend is attributed by
- * the caller's durable `agent.action` span); session totals feed the session
- * token limits and the remaining-quota budget granted to later delegations.
+ * Adds usage to session totals without touching the in-flight turn totals:
+ * the delegated spend a parent counts, or a run's tally of what its
+ * `ctx.agent` sessions spent. Turn tags attribute only the parent's own model
+ * calls (child spend is attributed by the caller's durable `agent.action`
+ * span); session totals feed the session token limits and the remaining-quota
+ * budget granted to later delegations.
*/
export function accumulateSessionUsage(input: {
readonly previous: TurnUsageState | undefined;
diff --git a/packages/eve/src/runtime/subagents/workflow.test.ts b/packages/eve/src/runtime/subagents/workflow.test.ts
index f21e44e40..d6730ff5e 100644
--- a/packages/eve/src/runtime/subagents/workflow.test.ts
+++ b/packages/eve/src/runtime/subagents/workflow.test.ts
@@ -7,6 +7,7 @@ import type { WorkflowBodyInput } from "#execution/tools/workflow/body.js";
import type { WorkflowToolRunMessage } from "#execution/tools/workflow/messages.js";
import { startServeBody } from "#execution/tools/workflow/serve.js";
import type { AgentTurnResult } from "#shared/agent-turn-outcome.js";
+import type { TokenUsage } from "#shared/token-usage.js";
/** The agent's side of the task: the messages it read and the turns it owes a reply. */
const agent = vi.hoisted(() => ({
@@ -83,8 +84,14 @@ const input: WorkflowBodyInput = {
workflowId: "workflow//eve//agentToolServeWorkflow",
};
-function turnEnded(result: AgentTurnResult): RuntimeActionResultHookPayload {
- const usageDelta = { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 0, outputTokens: 0 };
+function usage(inputTokens: number, outputTokens: number, costUsd?: number): TokenUsage {
+ return { cacheReadTokens: 0, cacheWriteTokens: 0, costUsd, inputTokens, outputTokens };
+}
+
+function turnEnded(
+ result: AgentTurnResult,
+ usageDelta: TokenUsage = usage(0, 0),
+): RuntimeActionResultHookPayload {
return {
kind: "runtime-action-result",
results: [
@@ -123,6 +130,28 @@ async function startReview(): Promise<ReturnType<typeof startServeBody>> {
return started;
}
+/** Alice's next message: check the plan against the Friday freeze. */
+const fridayCheck = {
+ call: {
+ agentContext,
+ auth: alice,
+ callId: "call-2",
+ input: { message: "Check it against the Friday freeze." },
+ sequence: 1,
+ stepIndex: 1,
+ turnId: "turn",
+ },
+ kind: "call",
+} as const;
+
+/** The messages that carried the task's usage to its session, in order. */
+function usageMessages(): unknown[] {
+ return agent.delivered.flatMap((message): unknown[] => {
+ if (message.kind === "reply") return [{ reply: message.callIds, usage: message.usage }];
+ return message.kind === "usage" ? [{ usage: message.usage }] : [];
+ });
+}
+
/**
* Alice asks the reviewer for a review, and her next message reaches the task
* `offset` microtasks after the reviewer's first turn ends. If `cancelled`,
@@ -138,18 +167,7 @@ async function sendAsTheTurnEnds(offset: number, { cancelled }: { readonly cance
);
for (let tick = 0; tick < offset; tick += 1) await Promise.resolve();
const repliedFirst = replies().length > 0;
- started.control.apply({
- call: {
- agentContext,
- auth: alice,
- callId: "call-2",
- input: { message: "Check it against the Friday freeze." },
- sequence: 1,
- stepIndex: 1,
- turnId: "turn",
- },
- kind: "call",
- });
+ started.control.apply(fridayCheck);
await settle();
agent.turns[1]?.(turnEnded({ kind: "succeeded", output: "The plan misses the Friday freeze." }));
await settle();
@@ -214,3 +232,91 @@ it("fails the task with the reason the agent's turn failed and how to retry", as
status: "failed",
});
});
+
+it("carries the task's running usage on each reply", async () => {
+ const started = await startReview();
+ agent.turns[0]?.(
+ turnEnded({ kind: "succeeded", output: "The plan looks ready." }, usage(1_000, 100, 0.25)),
+ );
+ await settle();
+ started.control.apply(fridayCheck);
+ await settle();
+ agent.turns[1]?.(
+ turnEnded(
+ { kind: "succeeded", output: "The plan misses the Friday freeze." },
+ usage(500, 50, 0.5),
+ ),
+ );
+ await settle();
+ started.control.apply({ kind: "end", reason: "The session ended." });
+ await started.outcome;
+
+ expect(usageMessages()).toEqual([
+ { reply: ["call-1"], usage: usage(1_000, 100, 0.25) },
+ { reply: ["call-2"], usage: usage(1_500, 150, 0.75) },
+ ]);
+});
+
+it("counts a turn that messages joined once, on the reply that settles them all", async () => {
+ const started = await startReview();
+ started.control.apply(fridayCheck);
+ await settle();
+ // The turn reports to the latest message it read, which settles both calls.
+ agent.turns[1]?.(
+ turnEnded({ kind: "succeeded", output: "Ready, and clear of the freeze." }, usage(800, 80)),
+ );
+ await settle();
+ started.control.apply({ kind: "end", reason: "The session ended." });
+ await started.outcome;
+
+ expect(usageMessages()).toEqual([{ reply: ["call-1", "call-2"], usage: usage(800, 80) }]);
+});
+
+it("sends a cancelled turn's usage on its own, since no reply carries it", async () => {
+ const started = await startReview();
+ started.control.apply({ kind: "cancel", reason: "Alice cancelled the review." });
+ agent.turns[0]?.(turnEnded({ kind: "cancelled" }, usage(400, 40)));
+ await settle();
+ started.control.apply(fridayCheck);
+ await settle();
+ agent.turns[1]?.(
+ turnEnded({ kind: "succeeded", output: "The plan misses the Friday freeze." }, usage(100, 10)),
+ );
+ await settle();
+ started.control.apply({ kind: "end", reason: "The session ended." });
+ await started.outcome;
+
+ expect(usageMessages()).toEqual([
+ { usage: usage(400, 40) },
+ { reply: ["call-2"], usage: usage(500, 50) },
+ ]);
+});
+
+it("sends nothing for a cancelled turn that spent nothing since the last reply", async () => {
+ const started = await startReview();
+ agent.turns[0]?.(
+ turnEnded({ kind: "succeeded", output: "The plan looks ready." }, usage(300, 30)),
+ );
+ await settle();
+ started.control.apply(fridayCheck);
+ await settle();
+ // Alice cancels the check before the reviewer's model spends anything on it.
+ started.control.apply({ kind: "cancel", reason: "Alice cancelled the check." });
+ agent.turns[1]?.(turnEnded({ kind: "cancelled" }, usage(0, 0)));
+ await settle();
+ started.control.apply({ kind: "end", reason: "The session ended." });
+ await started.outcome;
+
+ expect(usageMessages()).toEqual([{ reply: ["call-1"], usage: usage(300, 30) }]);
+});
+
+it("sends no usage once the session ended, since no one would count it", async () => {
+ const started = await startReview();
+ started.control.apply({ kind: "cancel", reason: "Alice cancelled the review." });
+ started.control.apply({ kind: "end", reason: "The session ended." });
+ agent.turns[0]?.(turnEnded({ kind: "cancelled" }, usage(400, 40)));
+ await settle();
+ await started.outcome;
+
+ expect(usageMessages()).toEqual([]);
+});
diff --git a/packages/eve/src/shared/action-types.ts b/packages/eve/src/shared/action-types.ts
index 6514599e5..b4902aa3e 100644
--- a/packages/eve/src/shared/action-types.ts
+++ b/packages/eve/src/shared/action-types.ts
@@ -243,12 +243,12 @@ const runtimeToolResultActionResultSchema = z
* trade-off, not an oversight.
*
* `outcome` is the child engine's explicit lifecycle verdict for the settled
- * turn. The parent settles the agent handle from `outcome.kind` and folds
- * `outcome.usageDelta` into its session totals; `output`/`isError` remain
- * the tool-result projection shown to the model. Every producer states the
- * envelope explicitly, so the parent never infers lifecycle from an absent
- * field. `usage`
- * carries the turn's token spend so the caller can attribute the
+ * turn. The run that opened the child reads the turn's status from `outcome`
+ * and adds `outcome.usageDelta` to the running total it reports to its calling
+ * session, which counts it once; `output`/`isError` remain the tool-result
+ * projection shown to the model. Every producer states the envelope
+ * explicitly, so the parent never infers lifecycle from an absent field.
+ * `usage` carries the turn's token spend so the caller can attribute the
* subagent's tokens.
*/
export interface RuntimeSubagentChildResult {
diff --git a/packages/eve/src/subagents/callback-route.ts b/packages/eve/src/subagents/callback-route.ts
index c2f485797..9e3412c0d 100644
--- a/packages/eve/src/subagents/callback-route.ts
+++ b/packages/eve/src/subagents/callback-route.ts
@@ -96,8 +96,8 @@ function projectSessionCallbackResult(value: unknown): RuntimeSubagentChildResul
outcome: payload.outcome,
output: payload.output ?? "",
subagentName: payload.subagentName,
- // Per-result usage projection (usage spans); the parent folds
- // `outcome.usageDelta`, never this field, when an outcome is present.
+ // Per-result usage projection (usage spans); the run that opened the
+ // child tallies `outcome.usageDelta`, never this field, when present.
usage: payload.outcome.usageDelta,
};
}
diff --git a/packages/eve/src/subagents/parent-notification.ts b/packages/eve/src/subagents/parent-notification.ts
index 106f31934..99ffc15c6 100644
--- a/packages/eve/src/subagents/parent-notification.ts
+++ b/packages/eve/src/subagents/parent-notification.ts
@@ -160,8 +160,8 @@ function createSettledTurnResult(input: {
output,
subagentName: input.caller.subagentName,
};
- // Legacy per-result usage projection (usage spans); the parent folds
- // `outcome.usageDelta`, never this field, when an outcome is present.
+ // Legacy per-result usage projection (usage spans); the run that opened the
+ // child tallies `outcome.usageDelta`, never this field, when present.
return input.settled.usage === undefined ? result : { ...result, usage: input.settled.usage };
}
diff --git a/packages/eve/src/subagents/token-budget.test.ts b/packages/eve/src/subagents/token-budget.test.ts
index 34c0f1358..57bdfc50b 100644
--- a/packages/eve/src/subagents/token-budget.test.ts
+++ b/packages/eve/src/subagents/token-budget.test.ts
@@ -44,7 +44,7 @@ function createSessionWithUsage(input: {
describe("resolveRemainingSessionTokenLimits", () => {
it("returns false axes for an uncapped session", () => {
- expect(resolveRemainingSessionTokenLimits(createSessionWithUsage({}))).toEqual({
+ expect(resolveRemainingSessionTokenLimits(createSessionWithUsage({}), 1)).toEqual({
maxInputTokensPerSession: false,
maxOutputTokensPerSession: false,
});
@@ -57,7 +57,7 @@ describe("resolveRemainingSessionTokenLimits", () => {
usedOutputTokens: 20_000,
});
- expect(resolveRemainingSessionTokenLimits(session)).toEqual({
+ expect(resolveRemainingSessionTokenLimits(session, 1)).toEqual({
maxInputTokensPerSession: 700_000,
maxOutputTokensPerSession: 30_000,
});
@@ -68,7 +68,7 @@ describe("resolveRemainingSessionTokenLimits", () => {
limits: { maxInputTokensPerSession: 1_000_000 },
});
- expect(resolveRemainingSessionTokenLimits(session)).toEqual({
+ expect(resolveRemainingSessionTokenLimits(session, 1)).toEqual({
maxInputTokensPerSession: 1_000_000,
maxOutputTokensPerSession: false,
});
@@ -82,7 +82,7 @@ describe("resolveRemainingSessionTokenLimits", () => {
});
const continued = bumpSessionRuntimeUsageLimits(exhausted);
- expect(resolveRemainingSessionTokenLimits(continued)).toEqual({
+ expect(resolveRemainingSessionTokenLimits(continued, 1)).toEqual({
maxInputTokensPerSession: 1_000_000,
maxOutputTokensPerSession: 100_000,
});
@@ -94,19 +94,45 @@ describe("resolveRemainingSessionTokenLimits", () => {
usedInputTokens: 150_000,
});
- expect(resolveRemainingSessionTokenLimits(session)).toEqual({
+ 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)).toEqual({
+ 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.ts
index 67f0288e5..97bf29960 100644
--- a/packages/eve/src/subagents/token-budget.ts
+++ b/packages/eve/src/subagents/token-budget.ts
@@ -4,25 +4,37 @@ 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, when the
- * child opens. `false` marks an axis with no inherited cap. A granted
- * continuation bumps the parent's runtime limit, so children opened after a
- * grant draw from the fresh window.
+ * 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: remaining.inputTokens,
- maxOutputTokensPerSession: remaining.outputTokens,
+ maxInputTokensPerSession: grantTokenShare(remaining.inputTokens, shares),
+ maxOutputTokensPerSession: grantTokenShare(remaining.outputTokens, shares),
};
if (remaining.costUsd !== false) {
- limits.maxTokenCostUsdPerSession = remaining.costUsd;
+ 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);
+}