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#
When a parent chat({ stream: false, subagents }) runs agents in tool mode, result.text contains the children's text as well as the parent's. With children that stream at the same time, their deltas interleave character by character:
"Delegating. RepoRepoReport frt frt for tor tor task ask ask 1.2.3.All done."
Expected: "Delegating. All done.". The children's text already reaches the parent model as tool results, and the client shows it in subagent parts.
The cause is streamToText (packages/ai/src/stream-to-response.ts), which runNonStreamingText uses. It adds every TEXT_MESSAGE_CONTENT delta to text, including the child chunks that the parent stream re-emits with a subagentRunId. It also happens when run returns ctx.chat({ stream: false }) or a string; the children's text is then appended whole rather than interleaved.
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. No API key needed.
import { chat, defineAgent } from "@tanstack/ai";
import { fakeText } from "@tanstack/ai/testing";
import { z } from "zod";
const researcher = defineAgent({
name: "researcher",
description: "Researches one task",
inputSchema: z.object({ label: z.string() }),
run: (ctx) => {
const child = fakeText({ tokensPerSecond: 50 });
child.setResponses([{ text: `Report for ${ctx.input.label}.` }]);
return ctx.chat({ adapter: child });
},
});
const parent = fakeText();
parent.setResponses([
{
text: "Delegating. ",
toolCalls: [1, 2, 3].map((n) => ({
name: "researcher",
input: { label: `task ${n}` },
})),
},
{ text: "All done." },
]);
const result = await chat({
adapter: parent,
messages: [{ role: "user", content: "Research tasks 1 to 3" }],
threadId: "thread-1",
subagents: { agents: [researcher] },
stream: false,
});
console.log(JSON.stringify(result.text));
Suggested fix: in streamToText, skip TEXT_MESSAGE_CONTENT chunks that carry a subagentRunId, as runChild in spawn.ts already does in reverse when it collects one child's text. chunks can keep them.
Workaround: read the answer from the transcript (the last assistant message) instead of result.text.
A related question: text also joins the text of every iteration of the parent ("Delegating. " from the tool-calling step plus "All done." from the last one). The docs call it "the full reply as one string", so this may be intended, but for an agent the answer is usually only the last step's text, and preamble such as "Let me check that file." ends up in it. Is that intended? If so, it would help for the docs to say so, and for ChatResult to offer the final answer on its own (for example the last assistant message's text), since today it has to be rebuilt from chunks or a stored transcript.