feat(ai, ai-harness): agentMiddleware runs plugin middleware in every agent #1550
feat/harness-p12-cli fromfeat/harness-p13-agent-middleware·opened View on GitHubA plugin can now run chat middleware in every agent run: subagents that the lead model calls, background agents, coding agents, and nested children. Put the middleware in the new agentMiddleware contribution. Middleware can also tell which agent it runs in, with ctx.subagentName, ctx.subagentRunId, and ctx.parentSubagentRunId.
Stacked on #1549 (Phase 12) → #1546 → #1540 → #1538 → #1524 → #1523 → #1522 → #1521 → #1520 → #1519 → #1518 → #1515 → #1513 → #1509. Merge those first.
🎯 Changes#
@tanstack/ai-harness
agentMiddlewareonPluginContributions: chat middleware for every agent run, but not for the lead turn.mountPluginscollects it intoMountedPlugins.agentMiddleware. To see every model call, put the same middleware inmiddlewareand inagentMiddleware.- Run plugins reach the agents of their turn. The lead turn gives its agents the
agentMiddlewareandgenerationMiddlewareof the session plugins, then of the run plugins. Before, only thegenerationMiddlewareof session plugins got to agents. A background agent fromsession.agent(name).start()gets the session plugins.
@tanstack/ai
- Two new middleware context fields.
subagentNameis the agent name. For a nested child,parentSubagentRunIdis the id of the child that started it.chat()andTextOptionstake both as options, and the boundctx.chatsets them. - Nested children get the host middleware. When a child calls
ctx.chat({ subagents }), its own children get the hostchatMiddlewareandgenerationMiddlewarefirst, then their own. This also works when the binding has no budget. Before, only the budget went down. - A nested child gets
parentSubagentRunIdon its run input, in tool mode and in router mode.chat()sends itssubagentRunIddown throughSpawnContextandcreateSyntheticSubagentTools.
Also in this PR:
usage()counts every agent. The first-party usage counter sits inmiddlewareandagentMiddleware, so/usagecovers the lead turn, subagents, background agents, and their children.- Docs: a new section "Middleware in every agent" in
docs/harness/plugins.md, with a usage tracker sample. A link to it fromdocs/harness/subagents.md. One paragraph indocs/chat/subagents.mdabout the two new context fields. - Changeset:
@tanstack/aiand@tanstack/ai-harnessminor. - Cleanups in touched files: the two
@tanstack/aitest files have noas anyoras nevercasts now.createBoundActivitiesandrunContextusesatisfiesin place of return type annotations. Both functions are internal. They takeagentNameas a new first argument.
✅ Checklist#
- I have followed the steps in the Contributing guide.
- I have tested code changes locally with
pnpm run test:pr, or these tests do not apply to this pull request. - I fully understand the code in this pull request, including any code generated with AI assistance.
- Docs: I updated
docs/for this change, or this change is not user-facing. - Changeset: I added a changeset (
pnpm changeset), or this PR does not change a published package.
🚀 Release Impact#
- This change affects published code, and I have generated a changeset.
- This change is docs/CI/dev-only (no release).
Testing#
Commands run (not the full pnpm test:pr, see below):
@tanstack/ai:vitest run(118 files, 1947 tests pass),test:types,test:oxlint(0 errors, and no warning on a line that this PR adds),build, andtest:build(publint: all good).@tanstack/ai-harness:vitest run(31 files, 263 tests pass),test:types,test:oxlint(0 errors),build, andtest:build(publint: all good).tests/agent-middleware.test.tspassed 5 runs in a row.- Root:
test:docs(no broken links),kiira check docs/harness/plugins.md docs/harness/subagents.md docs/chat/subagents.md(15 snippets pass, 9 ignored),test:knip(pass, config hints only), andoxfmt --checkon the changed files. - On Windows, the first full
@tanstack/ai-harnessrun had 2 failed tests, and I did not get their names. That run left abun.exefromtests/build.test.tsopen, and it lockedtests/.tmp-buildfor the next runs. After I stopped it, every run passed. This PR does not changetests/build.test.tsorsrc/build.ts. - I skipped the full
pnpm test:prbecause it is slow on this machine. CI runs it. No new E2E test: this is a server-side plugin hook, and no browser app uses it.
Manual test
No manual run was done. To run the new tests yourself:
- Run
pnpm install, thenpnpm build:all. - Run
pnpm -C packages/ai-harness exec vitest run tests/agent-middleware.test.ts. Expect 4 passed tests. - Run
pnpm -C packages/ai exec vitest run tests/define-agent-results.test.ts tests/bound-activities.test.ts. Expect every test to pass.
How this PR makes testing easy
packages/ai-harness/tests/agent-middleware.test.ts(5 new tests). Withusage(), a lead, a subagent, and a nested child give5 model calls, 133 input tokens, 0 output tokens, 133 total.(it passed 3 runs in a row).agentMiddlewareruns for a subagent that the lead model calls and for its nested child, but not for the lead turn. It also runs for a background agent fromsession.agent('worker').start(), and for a run-lifetime plugin.- The same file: one usage tracker in
middlewareandagentMiddlewarerecords this exact list of token counts: lead 1, researcher 10, fetcher 100, researcher 20, lead 2. SoonUsageruns inside children, and the lead turn does not count child usage again. packages/ai/tests/define-agent-results.test.ts,nested children(3 new tests). A nested child runs the host chat middleware, with its own name andparentSubagentRunId. The same works with a router parent and no budget. HostgenerationMiddlewaregets to the grandchild. The oldctx.chattest also checkssubagentNamenow.packages/ai/tests/bound-activities.test.ts(1 new test): nested children get the host middleware first, then their own, with no budget. The file also pinssubagentName.
Risk / rollback#
Low. The stack is not released yet. Three things change for code on this stack:
- For a nested child,
SUBAGENT_STARTEDdoes not carryparentSubagentRunIdin the stream of the chat that started it. That chat lists the child as a direct child.attributeChunkstill adds the id one level up, so every stream in the repo looks the same as before. A directrunAgentStreamcaller that passesinput.parentSubagentRunIddoes not see it onSUBAGENT_STARTEDnow. No caller in the repo does this. - Middleware that a child puts in
ctx.chat({ subagents: { binding } })now runs after the host middleware, not alone. - The
generationMiddlewareof run plugins now gets to the agents of their turn.
Not in this PR:
- In a child run,
agentMiddlewarecannot read plugin capabilities withgetX(ctx). The capability bridge goes only to the lead turn.
Revert the PR to undo.
Public API change#
Before
const tracker: ChatMiddleware = {
name: 'acme/usage',
// Runs for lead turn model calls only.
onUsage: (ctx, usage) => record('lead', usage.totalTokens),
}
definePlugin({ name: 'acme/usage', setup: () => ({ middleware: [tracker] }) })
After
const tracker: ChatMiddleware = {
name: 'acme/usage',
// Runs for every model call, in the run that made it.
onUsage: (ctx, usage) =>
record(ctx.subagentName ?? 'lead', usage.totalTokens),
}
definePlugin({
name: 'acme/usage',
setup: () => ({ middleware: [tracker], agentMiddleware: [tracker] }),
})
chat() also takes subagentName and parentSubagentRunId. Middleware reads them as ctx.subagentName and ctx.parentSubagentRunId.
🤖 Generated with Claude Code
- 1
View your CI Pipeline Execution ↗ for commit a3b364b95bf52d450565f7ac2995f37037741da3
Command Status Duration Result nx run-many --targets=build --exclude=examples/...✅ Succeeded 2m 23s View ↗
☁️ Nx Cloud last updated this comment at
2026-09-28 15:13:10UTC@tanstack/ai
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai@1550@tanstack/ai-acp
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-acp@1550@tanstack/ai-angular
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-angular@1550@tanstack/ai-anthropic
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-anthropic@1550@tanstack/ai-bedrock
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-bedrock@1550@tanstack/ai-byteplus
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-byteplus@1550@tanstack/ai-claude-code
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-claude-code@1550@tanstack/ai-client
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-client@1550@tanstack/ai-cloudflare
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-cloudflare@1550@tanstack/ai-code-mode
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-code-mode@1550@tanstack/ai-code-mode-snippets
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-code-mode-snippets@1550@tanstack/ai-codex
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-codex@1550@tanstack/ai-cohere
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-cohere@1550@tanstack/ai-compaction
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-compaction@1550@tanstack/ai-dashboard
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-dashboard@1550@tanstack/ai-devtools-core
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-devtools-core@1550@tanstack/ai-durable-stream
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-durable-stream@1550@tanstack/ai-elevenlabs
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-elevenlabs@1550@tanstack/ai-event-client
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-event-client@1550@tanstack/ai-fal
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-fal@1550@tanstack/ai-gemini
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-gemini@1550@tanstack/ai-grok
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-grok@1550@tanstack/ai-grok-build
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-grok-build@1550@tanstack/ai-groq
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-groq@1550@tanstack/ai-harness
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-harness@1550@tanstack/ai-harness-cli
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-harness-cli@1550@tanstack/ai-isolate-cloudflare
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-isolate-cloudflare@1550@tanstack/ai-isolate-daytona
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-isolate-daytona@1550@tanstack/ai-isolate-node
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-isolate-node@1550@tanstack/ai-isolate-quickjs
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-isolate-quickjs@1550@tanstack/ai-isolate-quickjs-bun
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-isolate-quickjs-bun@1550@tanstack/ai-llmgateway
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-llmgateway@1550@tanstack/ai-lovable
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-lovable@1550@tanstack/ai-mcp
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-mcp@1550@tanstack/ai-memory
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-memory@1550@tanstack/ai-mistral
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-mistral@1550@tanstack/ai-octane
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-octane@1550@tanstack/ai-ollama
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-ollama@1550@tanstack/ai-openai
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-openai@1550@tanstack/ai-opencode
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-opencode@1550@tanstack/ai-openrouter
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-openrouter@1550@tanstack/ai-perplexity
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-perplexity@1550@tanstack/ai-persistence
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-persistence@1550@tanstack/ai-preact
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-preact@1550@tanstack/ai-react
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-react@1550@tanstack/ai-react-ui
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-react-ui@1550@tanstack/ai-reactor
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-reactor@1550@tanstack/ai-remix
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-remix@1550@tanstack/ai-sandbox
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox@1550@tanstack/ai-sandbox-blaxel
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-blaxel@1550@tanstack/ai-sandbox-boxd
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-boxd@1550@tanstack/ai-sandbox-cloudflare
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-cloudflare@1550@tanstack/ai-sandbox-daytona
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-daytona@1550@tanstack/ai-sandbox-docker
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-docker@1550@tanstack/ai-sandbox-e2b
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-e2b@1550@tanstack/ai-sandbox-local-process
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-local-process@1550@tanstack/ai-sandbox-sprites
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-sprites@1550@tanstack/ai-sandbox-upstash-box
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-upstash-box@1550@tanstack/ai-sandbox-vercel
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-vercel@1550@tanstack/ai-skills
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-skills@1550@tanstack/ai-solid
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-solid@1550@tanstack/ai-solid-ui
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-solid-ui@1550@tanstack/ai-svelte
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-svelte@1550@tanstack/ai-typesafe
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-typesafe@1550@tanstack/ai-utils
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-utils@1550@tanstack/ai-vercel-gateway
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-vercel-gateway@1550@tanstack/ai-vertex
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-vertex@1550@tanstack/ai-vue
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-vue@1550@tanstack/ai-vue-ui
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-vue-ui@1550@tanstack/ai-worldlabs
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-worldlabs@1550@tanstack/openai-base
npm i https://pkg.pr.new/TanStack/ai/@tanstack/openai-base@1550@tanstack/preact-ai-devtools
npm i https://pkg.pr.new/TanStack/ai/@tanstack/preact-ai-devtools@1550@tanstack/react-ai-devtools
npm i https://pkg.pr.new/TanStack/ai/@tanstack/react-ai-devtools@1550@tanstack/solid-ai-devtools
npm i https://pkg.pr.new/TanStack/ai/@tanstack/solid-ai-devtools@1550@tanstack/svelte-ai-devtools
npm i https://pkg.pr.new/TanStack/ai/@tanstack/svelte-ai-devtools@1550commit:
47ee22fgithub-actions[bot](GitHub profile, opens in a new tab) assignedjherr
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer
Closed in favor of the combined PR #1555, which holds this phase and every other phase of the harness (P0 to P14) on one branch against main. All further fixes go there. This PR stays as the review record of P13.
AlemTuzlak closed this
Sign in to join this conversation.
Important
Review skipped#
Auto reviews are disabled on base/target branches other than the default branch.
Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository: TanStack/ai/.coderabbit.yaml
Review profile: CHILL
Plan: Advanced
Run ID:
23ea11fb-6b8e-409b-a5f5-d231763e155aYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share