Subagent usage doesn't reach the parent's `onUsage` or final `RUN_FINISHED`, and is dropped when `run` returns a string #2298
TanStack AI version#
@tanstack/ai 1.10.1 (npm latest)
Framework/Library version#
Node 26.14.0, server only, zod 4.6.7
Describe the bug and the steps to reproduce it#
docs/chat/subagents.md says:
The parent
RUN_FINISHED.usageincludes the token usage of every child.
In practice, a caller that tracks spend through the parent can miss all of the children's usage:
runreturns a string: the usage of the child'sctx.chat()calls is dropped. It appears on no parent chunk at all.subagents-advanced.mdpresents returning a plain value as a normal pattern ("runcan return a promise of any value"), and those model calls go through the library's ownctx.chat, so it could count them whateverrunreturns.runreturns a stream or aChatResult: the children's usage is added to theRUN_FINISHEDof the parent step that called them, as an AG-UIusage[]array. The lastRUN_FINISHEDcarries only the parent's last model call, in TanStack's{ promptTokens, ... }shape. A caller that reads the lastRUN_FINISHED, or adds uponUsage, never sees the children.- Parent
onUsage: fires only for the parent's own model calls, in both cases. The docs say the parent's middleware doesn't reach the child, so this may be by design, but then the parent's middleware has no hook that sees the children's usage. For example,withPersistenceor a cost tracker on the parent can't record it.
Steps: install @tanstack/ai@1.10.1 and zod in an ESM package, save the script below as repro.mjs, and run node repro.mjs result, then node repro.mjs string. No API key needed.
import { chat, defineAgent } from "@tanstack/ai";
import { fakeText } from "@tanstack/ai/testing";
import { z } from "zod";
// result: run returns the ctx.chat({ stream: false }) result
// string: run returns that result's .text
const mode = process.argv[2] ?? "result";
const researcher = defineAgent({
name: "researcher",
description: "Researches one task",
inputSchema: z.object({ label: z.string() }),
run: async (ctx) => {
const child = fakeText();
child.setResponses([{ text: `Report for ${ctx.input.label}.` }]);
const result = await ctx.chat({ adapter: child, stream: false });
return mode === "string" ? result.text : result;
},
});
const parent = fakeText();
parent.setResponses([
{
toolCalls: [1, 2].map((n) => ({
name: "researcher",
input: { label: `task ${n}` },
})),
},
{ text: "Done." },
]);
const onUsage = [];
const result = await chat({
adapter: parent,
messages: [{ role: "user", content: "Research tasks 1 and 2" }],
threadId: "thread-1",
subagents: { agents: [researcher] },
middleware: [{ name: "log-usage", onUsage: (_ctx, usage) => void onUsage.push(usage) }],
stream: false,
});
console.log("onUsage calls:", onUsage);
result.chunks
.filter((c) => c.type === "RUN_FINISHED")
.forEach((c, i) => console.log(`RUN_FINISHED #${i + 1} usage:`, JSON.stringify(c.usage)));
Output with result:
onUsage calls: [
{ promptTokens: 7, completionTokens: 15, totalTokens: 22 },
{ promptTokens: 43, completionTokens: 2, totalTokens: 45 }
]
RUN_FINISHED #1 usage: [{"inputTokens":7,"outputTokens":15,"totalTokens":22},{"inputTokens":7,"outputTokens":5,"totalTokens":12},{"inputTokens":7,"outputTokens":5,"totalTokens":12}]
RUN_FINISHED #2 usage: {"promptTokens":43,"completionTokens":2,"totalTokens":45}
Output with string: the two children's 12-token calls appear nowhere.
onUsage calls: [
{ promptTokens: 7, completionTokens: 15, totalTokens: 22 },
{ promptTokens: 43, completionTokens: 2, totalTokens: 45 }
]
RUN_FINISHED #1 usage: {"promptTokens":7,"completionTokens":15,"totalTokens":22}
RUN_FINISHED #2 usage: {"promptTokens":43,"completionTokens":2,"totalTokens":45}
Expected: the children's usage reaches the parent whatever run returns, and the parent exposes it somewhere a caller would look for the run's total: the final RUN_FINISHED, or a middleware hook.
Suggested fix:
- Count the usage of the bound activities on
ctx(ctx.chatand the generation calls) into the child'sSubagentSinkas they finish, rather than only from the streamrunreturns (collectUsageinspawnAgentStream). Arunthat returns a stream would need its chunks deduplicated against that. - Give the parent's middleware a way to see child usage, either
onUsagewithctx.subagentRunIdset, or a separateonSubagentUsage. - Say in the docs which
RUN_FINISHEDcarries the roll-up, and that itsusageis then an array in AG-UI's shape, not aTokenUsageobject.
Workaround: pass a usage middleware to every child ctx.chat() call and add it to the parent's total yourself.
Related: #2261 (usage not persisted for router-owned subagent runs).
tanstack-source added labelsbug
github-actions[bot](GitHub profile, opens in a new tab) assignedtombeckenham
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: author
Sign in to join this conversation.
Reproduced on
main(0ac51d8). All three claims in the issue hold. The child token usage is lost, or sits on the wrong chunk, or never reachesonUsage.What I measured#
The parent makes two model calls (22 and 45 tokens). The two children make one 12-token call each. The run total is 91 tokens.
runreturnsonUsagetotalRUN_FINISHEDRUN_FINISHEDChatResultrunreturns a string: both 12-token child calls appear on no chunk at all.valueResultChunksinspawn.tsturns the value into text chunks only, socollectUsagenever runs for those calls.runreturns aChatResultor a stream: the children land on the firstRUN_FINISHEDas an AG-UIusage[]array. The lastRUN_FINISHEDcarries only the parent's own 45 tokens, in the{ promptTokens, ... }shape. A caller that reads the last chunk sees 45 of 91.onUsage: fires twice, for 22 and 45 tokens, in every mode. It never sees a child call. The parent middleware has no hook that reports child usage, so a cost tracker on the parent under-counts by 24 tokens here.The docs at
docs/chat/subagents.md:130still say "The parentRUN_FINISHED.usageincludes the token usage of every child." That sentence holds only for the firstRUN_FINISHEDand only whenrunreturns a stream or aChatResult.Suspected files#
packages/ai/src/activities/chat/agents/spawn.ts:spawnAgentStream(line 752) callscollectUsageonly on chunks of the stream thatrunreturns (line 825).valueResultChunks(line 674) drops the usage of the boundctx.chatcalls.collectUsage(line 599) andwithChildUsage(line 621) are the roll-up.packages/ai/src/activities/chat/index.ts:streamWithChildUsage(line 7005) adds child usage to the firstRUN_FINISHEDit sees, not the final one.packages/ai/src/activities/chat/middleware/types.ts:onUsage(line 1003) has no subagent form, and noonSubagentUsageexists.docs/chat/subagents.mdline 130 anddocs/chat/subagents-advanced.mdline 248: the docs do not say whichRUN_FINISHEDcarries the roll-up, nor that itsusageis an array.How I ran it#
The sandbox has no
node_modules, andpnpm installfails here with a SQLite disk I/O error. I installed the runtime dependencies with npm in/tmp/reproand symlinked them tonode_modules. The repro is a vitest file, so it runs in the repository's own test setup.Repro#
Path:
repro/issue-2298.test.tsCommand:node_modules/.bin/vitest run repro/issue-2298.test.ts --root .Output (end):
TanStack Source bot, investigate agent