Skip to content
Source
Sign inSign up
TanStack/ai

feat(ai, ai-harness): agentMiddleware runs plugin middleware in every agent #1550

ClosedAlemTuzlakwants to merge 5 commits intofeat/harness-p12-cli fromfeat/harness-p13-agent-middlewareopened View on GitHub

AlemTuzlakcommented

A 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

  • agentMiddleware on PluginContributions: chat middleware for every agent run, but not for the lead turn. mountPlugins collects it into MountedPlugins.agentMiddleware. To see every model call, put the same middleware in middleware and in agentMiddleware.
  • Run plugins reach the agents of their turn. The lead turn gives its agents the agentMiddleware and generationMiddleware of the session plugins, then of the run plugins. Before, only the generationMiddleware of session plugins got to agents. A background agent from session.agent(name).start() gets the session plugins.

@tanstack/ai

  • Two new middleware context fields. subagentName is the agent name. For a nested child, parentSubagentRunId is the id of the child that started it. chat() and TextOptions take both as options, and the bound ctx.chat sets them.
  • Nested children get the host middleware. When a child calls ctx.chat({ subagents }), its own children get the host chatMiddleware and generationMiddleware first, then their own. This also works when the binding has no budget. Before, only the budget went down.
  • A nested child gets parentSubagentRunId on its run input, in tool mode and in router mode. chat() sends its subagentRunId down through SpawnContext and createSyntheticSubagentTools.

Also in this PR:

  • usage() counts every agent. The first-party usage counter sits in middleware and agentMiddleware, so /usage covers 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 from docs/harness/subagents.md. One paragraph in docs/chat/subagents.md about the two new context fields.
  • Changeset: @tanstack/ai and @tanstack/ai-harness minor.
  • Cleanups in touched files: the two @tanstack/ai test files have no as any or as never casts now. createBoundActivities and runContext use satisfies in place of return type annotations. Both functions are internal. They take agentName as 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, and test:build (publint: all good).
  • @tanstack/ai-harness: vitest run (31 files, 263 tests pass), test:types, test:oxlint (0 errors), build, and test:build (publint: all good). tests/agent-middleware.test.ts passed 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), and oxfmt --check on the changed files.
  • On Windows, the first full @tanstack/ai-harness run had 2 failed tests, and I did not get their names. That run left a bun.exe from tests/build.test.ts open, and it locked tests/.tmp-build for the next runs. After I stopped it, every run passed. This PR does not change tests/build.test.ts or src/build.ts.
  • I skipped the full pnpm test:pr because 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:

  1. Run pnpm install, then pnpm build:all.
  2. Run pnpm -C packages/ai-harness exec vitest run tests/agent-middleware.test.ts. Expect 4 passed tests.
  3. 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). With usage(), a lead, a subagent, and a nested child give 5 model calls, 133 input tokens, 0 output tokens, 133 total. (it passed 3 runs in a row). agentMiddleware runs 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 from session.agent('worker').start(), and for a run-lifetime plugin.
  • The same file: one usage tracker in middleware and agentMiddleware records this exact list of token counts: lead 1, researcher 10, fetcher 100, researcher 20, lead 2. So onUsage runs 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 and parentSubagentRunId. The same works with a router parent and no budget. Host generationMiddleware gets to the grandchild. The old ctx.chat test also checks subagentName now.
  • 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 pins subagentName.

Risk / rollback

Low. The stack is not released yet. Three things change for code on this stack:

  • For a nested child, SUBAGENT_STARTED does not carry parentSubagentRunId in the stream of the chat that started it. That chat lists the child as a direct child. attributeChunk still adds the id one level up, so every stream in the repo looks the same as before. A direct runAgentStream caller that passes input.parentSubagentRunId does not see it on SUBAGENT_STARTED now. 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 generationMiddleware of run plugins now gets to the agents of their turn.

Not in this PR:

  • In a child run, agentMiddleware cannot read plugin capabilities with getX(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

https://claude.ai/code/session_01APYv1qshKyjPPpkFyRZhfZ

    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      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.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository: TanStack/ai/.coderabbit.yaml

      Review profile: CHILL

      Plan: Advanced

      Run ID: 23ea11fb-6b8e-409b-a5f5-d231763e155a

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review

      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
      Comment `@coderabbitai help` to get the list of available commands.
    2. nx-cloud[bot](GitHub profile, opens in a new tab)commented

      View your CI Pipeline Execution ↗ for commit a3b364b95bf52d450565f7ac2995f37037741da3

      CommandStatusDurationResult
      nx run-many --targets=build --exclude=examples/...✅ Succeeded2m 23sView ↗

      ☁️ Nx Cloud last updated this comment at 2026-09-28 15:13:10 UTC

    3. pkg-pr-new[bot](GitHub profile, opens in a new tab)commented

      Open in StackBlitz

      @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@1550

      commit: 47ee22f

    4. github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer

    5. AlemTuzlakcommented

      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.

    6. AlemTuzlak closed this

Sign in to join this conversation.