Open History to see the last commit
1---
2title: Write a harness plugin
3id: harness-plugins
4order: 5
5description: "Package tools, prompts, middleware, settings, commands, and state as a plugin that any harness can load."
6keywords:
7 - tanstack ai
8 - harness
9 - plugins
10 - definePlugin
11 - extension points
12---
13
14You built a feature for one harness, a todo list or a GitHub integration, and now you want it in every harness you ship. A plugin packages it: tools and prompts for the model, commands for the user, settings, and state that survives restarts.
15
16## The smallest plugin
17
18```ts group=harness-plugins
19import { definePlugin } from '@tanstack/ai-harness'
20
21export const today = definePlugin({
22 name: 'acme/today',
23 setup: () => ({ prompts: [`Today is ${new Date().toDateString()}.`] }),
24})
25```
26
27Add it with `plugins: () => [today]` in `defineHarness`. `setup` runs once per session. To share one setup between all the sessions of a host, see [Share one setup between sessions](#share-one-setup-between-sessions).
28
29## What `setup` can return
30
31For the model:
32
33- `tools`: tools for the model, made with `toolDefinition`.
34- `prompts`: text for the system prompt. A function runs for each turn, so it can show current state. For text that changes often, see [Put changing text last](#put-changing-text-last).
35- `middleware`: chat middleware for the lead turn, the same type as `chat({ middleware })`. `agentMiddleware` is for agent runs, see [Middleware in every agent](#middleware-in-every-agent).
36- `generationMiddleware`: middleware for the activities agents call.
37- `adapter`: a picker for the model of each turn, see [Pick the model of a turn](#pick-the-model-of-a-turn).
38
39For agents and users:
40
41- `agents`: agents added to `session.agents`. `routing.router` can send a turn to them too, see [Route a turn to an agent](./subagents#route-a-turn-to-an-agent).
42- `subagents`: agents the model can call as tools. They are also added to `session.agents`.
43- `commands`: user actions, see below.
44- `config`: session settings, see below.
45- `contribute`: items for another plugin's extension point.
46
47If two plugins add the same tool, command, setting, or prompt id, `host.open` fails and names both plugins.
48
49Return these from `setup`, not from the top level of `definePlugin`. A key like `adapter` or `tools` at the top level is a type error, and `definePlugin` throws for it. Other keys at the top level stay on the plugin object, so a plugin can give your code its own functions.
50
51### Put changing text last
52
53Set `placement: 'context'` on a prompt whose text changes often:
54
55```ts group=harness-plugins
56let openTickets = 0
57
58export const tickets = definePlugin({
59 name: 'acme/tickets',
60 setup: () => ({
61 prompts: [
62 {
63 id: 'acme/tickets:count',
64 text: () => `Open tickets: ${openTickets}.`,
65 placement: 'context',
66 },
67 ],
68 }),
69})
70```
71
72A provider caches the start of each request: the system prompts, then the history. A change of a system prompt makes the cache miss from that prompt on. A `'context'` prompt is the last system prompt, so the system prompts before it stay in the cache.
73
74- The model gets all `'context'` text as one system prompt, after the other system prompts. The harness makes it again at each model call.
75- The text has the authority of a system prompt, not of a user message.
76- The default is `'system'`: the text goes in the system prompts, in plugin order.
77- The log does not keep `'context'` text.
78- The first-party todos, goal, and plan mode prompts use `'context'`.
79
80### Refresh state at the start of a turn
81
82A prompt function must return at once, so it cannot read a file or call a server. Do that work in `onTurnStart`. The harness calls it once at the start of each turn, before it reads the prompts:
83
84```ts group=harness-plugins
85import { readFile } from 'node:fs/promises'
86
87let rules = ''
88
89export const projectRules = definePlugin({
90 name: 'acme/project-rules',
91 setup: () => ({
92 onTurnStart: async () => {
93 rules = await readFile('RULES.md', 'utf8')
94 },
95 prompts: [() => rules],
96 }),
97})
98```
99
100- `onTurnStart` gets the turn. `turn.run` has the user of the turn and the credentials of that user.
101- It runs one time for each turn, also when the turn makes many model calls.
102- If it throws, the turn continues, and clients get a `harness.plugin.warning` event.
103
104## Add commands and settings
105
106Commands are actions for the user, not the model: slash commands and buttons in your app. Settings are typed, saved per session, and apply at the next turn.
107
108```ts group=harness-plugins
109import { configOption, defineCommand } from '@tanstack/ai-harness'
110import { z } from 'zod'
111
112export const greeter = definePlugin({
113 name: 'acme/greeter',
114 setup: (ctx) => ({
115 config: {
116 tone: configOption.select({ options: ['plain', 'warm'], default: 'plain' }),
117 },
118 commands: {
119 greet: defineCommand({
120 description: 'Greet someone',
121 input: z.object({ name: z.string() }),
122 run: async ({ name }, command) => {
123 const sure = await command.step.ask({
124 name: 'confirm',
125 message: `Greet ${name}?`,
126 schema: z.boolean(),
127 })
128 if (!sure) return 'Skipped.'
129 return ctx.config.get('tone') === 'warm' ? `Hello, dear ${name}!` : `Hello, ${name}.`
130 },
131 }),
132 },
133 }),
134})
135```
136
137- `session.runCommand({ name: 'greet', input: { name: 'Ada' } })` runs the command. A Standard Schema input (zod here) is checked, and the command gets the parsed value. A JSON Schema input is not checked, the same as a JSON Schema tool input.
138- `session.setPluginSetting({ key: 'tone', value: 'warm' })` changes the setting. A value the option does not accept is rejected.
139- `step.ask` waits for `session.answer({ questionId, value })`. The log keeps the question as a [wait](./waits), so a user on any server can answer it. The question goes to `session.onQuestion` listeners, and it stays in `session.snapshot().pendingWaits` until someone answers.
140- When the host stops while the command waits, the next host runs the command again from the top. Put each side effect before the ask in `command.step.do`, so it does not run twice.
141- `ctx.session.ask` is only for an MCP server that asks during a tool call. Anywhere else it throws. Use `step.ask`, the `question` tool, or a [permission rule](./permissions#rules-for-your-own-tool).
142
143## Change commands while the session runs
144
145Some commands come from data that changes: a folder of prompts, saved shortcuts, a list from a server. `ctx.commands` adds and removes them while the session runs. Here `/macro` saves a new command that sends a message:
146
147```ts group=harness-plugins
148export const macros = definePlugin({
149 name: 'acme/macros',
150 setup: (ctx) => ({
151 commands: {
152 macro: defineCommand({
153 description: 'Save a command that sends a message: /macro <name> <message>',
154 run: (input: unknown) => {
155 const [name = '', ...words] = String(input ?? '').trim().split(' ')
156 if (ctx.commands.has(name)) return `/${name} is taken.`
157 ctx.commands.set(
158 name,
159 defineCommand({
160 description: `Send: ${words.join(' ')}`,
161 run: () => {
162 void ctx.session.send(words.join(' '))
163 },
164 }),
165 )
166 return `Saved /${name}.`
167 },
168 }),
169 },
170 }),
171})
172```
173
174- `ctx.commands.set(name, command)` adds a command of this plugin, or replaces it. A name that another plugin owns throws.
175- `ctx.commands.delete(name)` removes a command of this plugin. Another plugin's name does nothing.
176- Each change sends a `harness.commands.changed` event, so a client can read `session.commands()` again. A [session view](./custom-ui) reads the new list by itself.
177- During `setup`, wait for `ctx.commands.ready` before you call `has` or `set`. The plugins after this one add their commands later, so a name can look free and still be taken.
178
179```ts group=harness-plugins
180export const greetings = definePlugin({
181 name: 'acme/greetings',
182 setup: (ctx) => {
183 void ctx.commands.ready.then(() => {
184 if (!ctx.commands.has('hi')) {
185 ctx.commands.set('hi', defineCommand({ description: 'Say hi', run: () => 'Hi!' }))
186 }
187 })
188 },
189})
190```
191
192The [skills plugin](./skills) works this way: one command for each skill in a folder.
193
194## Change agents while the session runs
195
196Agents can come from data that changes too. `ctx.agents.set` and `ctx.agents.delete` work like `ctx.commands`. Here `/helper` adds an agent that the session can run at once:
197
198```ts group=harness-plugins
199import { defineAgent } from '@tanstack/ai'
200
201export const helpers = definePlugin({
202 name: 'acme/helpers',
203 setup: (ctx) => ({
204 commands: {
205 helper: defineCommand({
206 description: 'Add an agent: /helper <name>',
207 run: (input: unknown) => {
208 const name = String(input ?? '').trim()
209 ctx.agents.set(
210 defineAgent({ name, description: `The ${name} agent`, run: async () => 'Done.' }),
211 )
212 return `Added the ${name} agent.`
213 },
214 }),
215 },
216 }),
217})
218```
219
220- `ctx.agents.set(agent)` adds an agent of this plugin, or replaces the one with the same name. A name that another plugin or the harness owns throws.
221- `ctx.agents.set(agent, { subagent: true })` also gives the model a tool that runs the agent as a subagent, from the next turn. The tool has the name of the agent.
222- `ctx.agents.delete(name)` removes an agent of this plugin, and its subagent tool. Another owner's name does nothing.
223- `session.agent(name)`, `ctx.agents.list()`, and `routing` see the change at once.
224
225`ctx.agents` also runs agents: `start`, `run`, and `group`, with `g.start` for each child of a group. It has the same type, `AgentActions`, as `ctx.harness.agents` in agent code. See [Run agents from a plugin](./subagents#run-agents-from-a-plugin).
226
227## Keep state
228
229`ctx.state(initial)` gives a plugin its own state for the thread. The session log keeps each change as a record, so any host that opens the thread reads the state back, also after a restart. Clients see each change as an AG-UI `STATE_SNAPSHOT` event.
230
231```ts group=harness-plugins
232export const counter = definePlugin({
233 name: 'acme/counter',
234 setup: (ctx) => {
235 const state = ctx.state({ count: 0 })
236 return {
237 commands: {
238 bump: defineCommand({
239 description: 'Add one',
240 run: async () => (await state.update((current) => ({ count: current.count + 1 }))).count,
241 }),
242 },
243 }
244 },
245})
246```
247
248- The state is JSON.
249- A key or a token of the session in the state goes into the log as `[redacted]`. `update` resolves with that same value. See [Keep tokens out of the log and the model](./auth#keep-tokens-out-of-the-log-and-the-model).
250- The updates of one plugin run one at a time. Each `update` function gets the value that the update before it wrote.
251- [`host.sessions.delete`](./lifecycle#delete-a-thread-for-good) deletes the state with the log. A fork does not copy it.
252- For a long list of records, such as one record for each step, append records to the log and set `keepRecords`. Read them with `ctx.session.keptRecords(type)`. See [Keep records after a truncate](./session-log#keep-records-after-a-truncate).
253- Agents get a state with the same `get` and `update` from `ctx.harness.state({ key, initial })`. See [Share state between agents](./subagents#share-state-between-agents).
254
255## Store a file from a tool
256
257A tool of your plugin makes an image or a PDF. Inline bytes in a tool result stay in the transcript and the log, and each later model call sends them again. Store the bytes with `ctx.session.putMedia`, and return `mediaPart(record)`:
258
259```ts group=harness-plugins
260import { mediaPart } from '@tanstack/ai-harness/media'
261
262declare function drawChart(values: Array<number>): Promise<Uint8Array>
263
264export const charts = definePlugin({
265 name: 'acme/charts',
266 setup: (ctx) => ({
267 tools: [
268 toolDefinition({
269 name: 'draw_chart',
270 description: 'Draw a bar chart of the values',
271 inputSchema: z.object({ values: z.array(z.number()) }),
272 }).server(async ({ values }) => {
273 const record = await ctx.session.putMedia({
274 body: await drawChart(values),
275 mimeType: 'image/png',
276 name: 'chart.png',
277 })
278 return [mediaPart(record)]
279 }),
280 ],
281 }),
282})
283```
284
285- The transcript and the log keep a small `harness-media:` reference. The model gets the bytes.
286- `putMedia` throws a `MediaError` when the file is bigger than `media.maxBytes`, or when its kind is not in `media.kinds`. See [Limit files, and choose what the model reads](./media#limit-files-and-choose-what-the-model-reads).
287
288[Give your agent a computer](./computer-use) stores each screenshot this way.
289
290## Middleware in every agent
291
292You want to track token cost, or apply a policy, for every model call. But `middleware` runs only in the lead turn. The agents that the lead model calls, the agents you start in the background, and their own children each run a separate chat. Put the same middleware in `agentMiddleware` too. Then it runs in each of those chats.
293
294```ts group=harness-plugins
295import type { ChatMiddleware } from '@tanstack/ai'
296
297export const usageByAgent = definePlugin({
298 name: 'acme/usage-by-agent',
299 setup: () => {
300 const tokens = new Map<string, number>()
301 const tracker: ChatMiddleware = {
302 name: 'acme/usage-by-agent',
303 onUsage: (ctx, usage) => {
304 const agent = ctx.subagentName ?? 'lead'
305 tokens.set(agent, (tokens.get(agent) ?? 0) + usage.totalTokens)
306 },
307 }
308 return {
309 middleware: [tracker],
310 agentMiddleware: [tracker],
311 commands: {
312 tokens: defineCommand({
313 description: 'Show the tokens of each agent',
314 run: () => Object.fromEntries(tokens),
315 }),
316 },
317 }
318 },
319})
320```
321
322- `ctx.subagentName` is the name of the agent. In the lead turn, it is `undefined`.
323- `ctx.subagentRunId` is different for each run of an agent. For a nested child, `ctx.parentSubagentRunId` is the id of the child that started it.
324- Each model call goes to `onUsage` one time, in the run that made the call. The lead turn does not count the usage of a child again.
325- A background run that a turn starts keeps the plugins of that turn. So the `agentMiddleware` of a plugin with `lifetime: 'turn'` runs in it too. The turn plugins are cleaned up when the turn and its runs have settled.
326- A tool result that your `onAfterToolCall` replaces is the result that the session log keeps. After a crash, the model gets that result again. See [The other tools of a cut batch](./durable-tools#the-other-tools-of-a-cut-batch).
327
328## Act as the user of a run
329
330Several people can write in one thread, and a background agent can run after its turn ended. A tool must use the GitHub token of the user who started its own run, not of the user who sent the latest message. Each run carries its user, and that user's credentials and keys, as the run context:
331
332```ts group=harness-plugins
333import { toolDefinition } from '@tanstack/ai'
334import type { HarnessRunContext } from '@tanstack/ai-harness'
335
336export const github = definePlugin({
337 name: 'acme/github',
338 setup: () => ({
339 tools: [
340 toolDefinition({ name: 'my_repos', description: 'List my GitHub repos' }).server<HarnessRunContext>(
341 async (_args, ctx) => {
342 const credential = await ctx.context.run.credentials.require('github')
343 const token = credential.type === 'oauth' ? credential.accessToken : credential.value
344 const response = await fetch('https://api.github.com/user/repos', {
345 headers: { authorization: `Bearer ${token}` },
346 })
347 return response.json()
348 },
349 ),
350 ],
351 }),
352})
353```
354
355Where each part of a plugin reads the run:
356
357- A tool or a middleware hook: `ctx.context.run`. Type it with `HarnessRunContext`, for example `.server<HarnessRunContext>(...)` or `ChatMiddleware<HarnessRunContext>`.
358- A command: `run` of the command context. Its `credentials` is the same as `run.credentials`.
359- A plugin with `lifetime: 'turn'`: `ctx.turn.run`. Its `ctx.credentials` and `ctx.keys` belong to the same user.
360- A session plugin (the default lifetime): `ctx.credentials` and `ctx.keys` have no user, so each call throws. `ctx.session.user` is the owner of the session.
361- A plugin with `lifetime: 'host'`: its setup has no user and no session. Its tools read the user of each call from `ctx.context.run`.
362
363`prepareTools` gets `run` too: the run of the turn, with its id and its user. `onTurnStart` gets the turn, with its run in `turn.run`.
364
365A plugin that starts a turn picks its user. `ctx.session.send(text, { user })` and `ctx.session.note(text, { wake: true, user })` run that turn as `user`. Without it, the turn runs as `ctx.session.user`. To continue the work of a run, pass the `user` of that run.
366
367The run has these fields:
368
369| Field | What it is |
370| --- | --- |
371| `user` | The user who started the run: `{ id, tenantId }`. `undefined` in a session with no user. |
372| `tenantId` | The tenant of the session. `undefined` in the default tenant. |
373| `threadId`, `runId`, `parentRunId` | The thread, this run, and the run that started this one. |
374| `logId` | The id of the log of the session tree in the store, with its tenant. |
375| `epoch` | The ownership epoch of the log when the run started. See [Fence your own side effects](./durable-sessions#fence-your-own-side-effects). |
376| `idempotencyKey(step, scope?)` | A key for one side effect of the run. A run again on any host gets the same key. |
377| `signal` | Aborts when the run stops. |
378| `source`, `label` | Who made the model call: `'turn'`, or the source and the label of a `ctx.model.chat` call. See [Tell plugin calls from turn calls in middleware](#tell-plugin-calls-from-turn-calls-in-middleware). |
379| `credentials`, `keys` | The credentials and the model provider keys of the user of the run. The session replaces their values with `[redacted]` in what it keeps and sends. To refresh an OAuth token, use `credentials.refresh`. See [Auth and connectors](./auth#refresh-a-token). |
380
381## Call a model from a plugin
382
383Your plugin needs a model call of its own: a judge, a title, or a summary. A plain `chat()` call does not count in `session.usage()`, and it keeps running after the user cancels the turn. Call the model with `ctx.model.chat` instead:
384
385```ts group=harness-plugins
386export const recap = definePlugin({
387 name: 'acme/recap',
388 setup: (ctx) => ({
389 commands: {
390 recap: defineCommand({
391 description: 'Sum up the conversation in three lines',
392 run: async (_input, { run }) => {
393 const transcript = await ctx.session.transcript()
394 const { text } = await ctx.model.chat({
395 run,
396 label: 'recap',
397 options: {
398 messages: [...transcript, { role: 'user', content: 'Sum up this conversation in three lines.' }],
399 },
400 })
401 return text
402 },
403 }),
404 },
405 }),
406})
407```
408
409The options:
410
411- `run`: the run that the call is for. The call uses the keys of its user, and the budget of the run applies. A plugin with `lifetime: 'turn'` can leave it out. Then the call uses the run of its turn.
412- `adapter`: the model. Without it, the call uses the model of the session: the thread setting `model`, else the harness `adapter`. A `keyedAdapter(...)` gets the key of the user of the run.
413- `options`: `messages`, `systemPrompts`, and `outputSchema`. With `outputSchema`, the call resolves to the checked value. Without it, the call resolves to `{ text, chunks }`.
414- `label`: a name for the call in its usage record.
415- `timeoutMs`: the time limit of the call. The default is 2 minutes.
416
417The call stops when its run stops, for example on a cancel, and when the time limit ends. Then it rejects. Its usage counts in the session under `plugin:<name>`, here `plugin:acme/recap`. See [Usage of plugins](./usage#usage-of-plugins). The call runs the harness `middleware`, as a turn call does, so your cost ledger and traces see it. The middleware gets the run in `ctx.context.run`. The `goal()`, `title()`, and `compact()` plugins call their models this way.
418
419### Tell plugin calls from turn calls in middleware
420
421Your cost ledger in the harness `middleware` sees the model calls of each turn and of each plugin. Read `ctx.context.run.source` to know who made the call:
422
423```ts group=harness-plugins
424const costs = new Map<string, number>()
425
426const ledger: ChatMiddleware<HarnessRunContext> = {
427 name: 'acme/ledger',
428 onUsage: (ctx, usage) => {
429 const { source, label } = ctx.context.run
430 const key = label ? `${source}:${label}` : String(source)
431 costs.set(key, (costs.get(key) ?? 0) + usage.totalTokens)
432 },
433}
434
435export const ledgered = defineHarness({
436 name: 'acme/ledgered',
437 adapter: anthropicText('claude-sonnet-5-5'),
438 middleware: [ledger],
439 plugins: () => [recap],
440})
441```
442
443`source` has one of these values:
444
445- `'turn'`: a model call of a chat turn.
446- `'plugin:<name>'`: a `ctx.model.chat` call of a plugin, here `'plugin:acme/recap'`. `label` is the `label` of the call, here `'recap'`.
447- `'router'`: a `model.chat` call of `routing.router`.
448- `'transfer'`: the summary call of `host.transfer`. Its `label` is `'summary'`.
449
450`source` and `label` are the same names that the usage records use. See [Usage of plugins](./usage#usage-of-plugins).
451
452## Write warnings to the host logger
453
454Your plugin has a warning for the developer of the app, for example a service that does not answer. A `console.warn` line does not go where the app sends its logs, and it breaks a full-screen terminal UI. Write the warning to `ctx.logger`, the [host logger](./host-options#send-the-warnings-to-your-own-logger):
455
456```ts group=harness-plugins
457export const prices = definePlugin({
458 name: 'acme/prices',
459 setup: (ctx) => {
460 let latest = 'unknown'
461 return {
462 onTurnStart: async () => {
463 try {
464 const response = await fetch('https://prices.example.com/today')
465 if (!response.ok) throw new Error(`HTTP ${response.status}`)
466 latest = await response.text()
467 } catch (error) {
468 ctx.logger.warn('[acme/prices] Cannot load the prices. The turn uses the old prices.', { error })
469 }
470 },
471 prompts: [() => `Prices: ${latest}`],
472 }
473 },
474})
475```
476
477- `ctx.logger` has `debug`, `info`, `warn`, and `error`. Put an error in the meta as `{ error }`, as the harness does.
478- The logger does not add the name of your plugin. Start each message with it.
479- A call to `ctx.logger` never throws. A logger that fails loses the line, and your plugin goes on.
480- Every plugin gets `ctx.logger`: a session plugin, a turn plugin, and the setup of a `lifetime: 'host'` plugin.
481
482The `mcp()`, `codeMode()`, and `skills()` plugins write their warnings this way.
483
484## Pick the model of a turn
485
486Some turns need another model: a short question does not need your strongest model, and an organization can allow only some models. Return an `adapter` picker from `setup`. When each turn starts, the session calls it with the message, context, and sender of that turn:
487
488```ts group=harness-plugins
489import { anthropicText } from '@tanstack/ai-anthropic'
490
491export const cheapForShortTurns = definePlugin({
492 name: 'acme/cheap-for-short-turns',
493 setup: () => ({
494 adapter: (turn) =>
495 typeof turn.message === 'string' && turn.message.length < 200
496 ? anthropicText('claude-haiku-5-5')
497 : anthropicText('claude-sonnet-5-5'),
498 }),
499})
500```
501
502A short message now runs on Claude Haiku, and a long one on Claude Sonnet.
503
504The `turn` has these fields:
505
506| Field | What it is |
507| --- | --- |
508| `operationId` | The id of the operation that runs the turn. |
509| `inputId` | The id of the input, when the turn has one. |
510| `message` | The user message of the input. `undefined` for a resolve and a continue. |
511| `context` | The [context of the input](./inputs#send-context-with-a-message). It is client data, so do not trust it. |
512| `user` | Who the turn runs as. Its tools get this user's credentials and keys. It is the sender of the input, and for a resolve the sender of the stopped turn. Default: the user that opened the session. See [Share a thread](./shared-threads). |
513| `sender` | Who sent the input. The same as `user`, except on a resolve: there it is the user who resolved. |
514| `overrides` | The [overrides of the prompt](./turn-control#give-one-prompt-its-own-settings), when it has some. |
515| `run` | The run of the turn: its user, and that user's credentials and keys. See [Act as the user of a run](#act-as-the-user-of-a-run). |
516| `model` | The model of the turn, as `provider/model`. The turn sets it when it picks its adapter, so `setup`, `onTurnStart`, and the picker do not see it yet. |
517| `attempt` | How many times the input ran: `1` the first time. A turn that recovery runs again after a host stopped has a larger number. |
518
519The session uses the picks like this:
520
521- `undefined` keeps the harness adapter.
522- If more than one plugin returns an adapter, the last plugin wins.
523- The `overrides.adapter` of the turn wins over every pick.
524- A model that the thread stored with `session.updateThreadSettings` wins over a plain pick. See [Store settings per thread](./thread-settings).
525- A pick with `override: true` wins over the stored model. See below.
526- A keyed adapter gets the provider key of the sender.
527
528If the picker does not need the turn, it can take no parameter.
529
530### Win over the stored model
531
532Return `{ adapter, override: true }` when your pick must win over the model that the thread stored. For example, a plugin that moves every turn to a smaller model when an organization is over its budget:
533
534```ts group=harness-plugins
535// Your check, for example a usage query.
536function overBudget(tenantId: string | undefined) {
537 return tenantId === 'trial'
538}
539
540export const budgetGuard = definePlugin({
541 name: 'acme/budget-guard',
542 setup: () => ({
543 adapter: (turn) =>
544 overBudget(turn.user?.tenantId)
545 ? { adapter: anthropicText('claude-haiku-5-5'), override: true }
546 : undefined,
547 }),
548})
549```
550
551- The `overrides.adapter` of the prompt still wins over this pick.
552- If more than one plugin returns an `override: true` pick, the last one wins. A later plain pick does not change that.
553
554### Read the model from your data
555
556The picker is synchronous. To read a database first, give the plugin `lifetime: 'turn'`. The session then runs its `setup` for each turn and gives it the same turn as `ctx.turn`. An async `setup` can read the model from your data:
557
558```ts group=harness-plugins
559// Your lookup, for example a database query.
560async function planOf(tenantId: string | undefined) {
561 return tenantId === 'acme' ? 'strong' : 'fast'
562}
563
564export const modelOfTheOrg = definePlugin({
565 name: 'acme/model-of-the-org',
566 lifetime: 'turn',
567 setup: async (ctx) => {
568 const plan = await planOf(ctx.turn?.user?.tenantId)
569 const adapter =
570 plan === 'strong'
571 ? anthropicText('claude-sonnet-5-5')
572 : anthropicText('claude-haiku-5-5')
573 return { adapter: () => adapter }
574 },
575})
576```
577
578A plugin with the default lifetime has no turn at setup, so its `ctx.turn` is `undefined`.
579
580A `lifetime: 'turn'` plugin lives for one turn, so it cannot add commands or config options. If it tries, the turn fails with an error. Put them in a plugin with the default lifetime.
581
582### Leave out the harness model
583
584When a plugin picks the model of every turn, `defineHarness` needs no `adapter`:
585
586```ts group=harness-plugins
587import { defineHarness } from '@tanstack/ai-harness'
588
589export const assistant = defineHarness({
590 name: 'acme/assistant',
591 plugins: () => [modelOfTheOrg],
592})
593```
594
595If no plugin picks a model and the turn has no `overrides.adapter`, the turn fails with this error:
596
597```text
598This turn has no model. Set `adapter` in defineHarness, return one from a plugin `adapter()`, or pass `overrides.adapter` to the turn.
599```
600
601## Let plugins work together
602
603Three ways, from simple to loose:
604
605- **Capabilities.** One plugin declares `provides: [cap]` and calls `ctx.provide(cap, value)`. Another declares `requires: [cap]` and reads `ctx.get(cap)`. The provider must come first.
606- **Extension points.** One plugin reads a list, and others add to it in any order.
607- **Events.** `ctx.emit(event, value)` reaches every `ctx.on(event, handler)`. A listener stops when its plugin is cleaned up, for example on a reload.
608
609```ts group=harness-plugins
610import { createExtensionPoint, createPluginEvent } from '@tanstack/ai-harness'
611
612export const Checks = createExtensionPoint<{ name: string }>('acme/checks')
613export const checked = createPluginEvent<{ name: string }>('acme/checked')
614
615export const runner = definePlugin({
616 name: 'acme/check-runner',
617 setup: (ctx) => {
618 const checks = ctx.collect(Checks)
619 return {
620 commands: {
621 check: defineCommand({
622 description: 'Run every check',
623 run: () => {
624 for (const check of checks) ctx.emit(checked, check)
625 return checks.map((check) => check.name)
626 },
627 }),
628 },
629 }
630 },
631})
632
633export const lint = definePlugin({
634 name: 'acme/lint',
635 setup: () => ({ contribute: [Checks.item({ name: 'lint' })] }),
636})
637```
638
639Read `ctx.collect` at run time (in a command, a tool, or a middleware hook). During `setup`, later plugins have not added their items yet.
640
641## Clean up resources
642
643Open resources with `ctx.resources.acquire(open, close)`. They close when the plugin is cleaned up, newest first: when the session closes, or for `lifetime: 'turn'`, after the turn and the background runs that it started. If a later plugin fails in `setup`, every plugin set up so far is cleaned up, and no model request is sent.
644
645Set `lifetime: 'turn'` to set a plugin up again for each turn.
646
647## Share one setup between sessions
648
649A plugin that opens a database pool, or starts a process, does that work again for each session. A host with 300 open sessions then holds 300 pools. Set `lifetime: 'host'`, and the host sets the plugin up one time and shares it with every session:
650
651```ts group=harness-plugins-host
652import { toolDefinition } from '@tanstack/ai'
653import { definePlugin } from '@tanstack/ai-harness'
654
655// Your shared client, for example a database pool.
656async function connect() {
657 return { countOrders: async () => 42, end: async () => {} }
658}
659
660export const orders = definePlugin({
661 name: 'acme/orders',
662 lifetime: 'host',
663 setup: async (ctx) => {
664 const db = await ctx.resources.acquire(connect, (pool) => pool.end())
665 return {
666 tools: [
667 toolDefinition({ name: 'count_orders', description: 'Count the orders' }).server(
668 async () => db.countOrders(),
669 ),
670 ],
671 }
672 },
673})
674```
675
676- The host sets the plugin up one time for each harness and plugin object. Every session of that harness that uses the same object shares this setup.
677- Create the plugin one time, outside the `plugins` function, as `orders` is above. Then use it with `plugins: () => [orders]`. A `plugins` function that calls `definePlugin` or `mcp()` for each session gives each session its own setup.
678- The host cleans it up when the last session that uses it closes, or at `host.close()`.
679- Its setup context has no session, no credentials, no keys, and no commands. It has `harness` (the name of the harness), `resources`, and `logger`. See [Write warnings to the host logger](#write-warnings-to-the-host-logger).
680- A tool of the plugin reads the user of its call from `ctx.context.run`. See [Act as the user of a run](#act-as-the-user-of-a-run).
681
682Some parts need the session: a command, a setting, plugin state, or a question to the user. Return them from `session`. It runs for each session, with the same context as a session plugin:
683
684```ts group=harness-plugins-host
685import { defineCommand } from '@tanstack/ai-harness'
686
687export const pool = definePlugin({
688 name: 'acme/pool',
689 lifetime: 'host',
690 setup: async (ctx) => {
691 const db = await ctx.resources.acquire(connect, (shared) => shared.end())
692 return {
693 session: (session) => ({
694 commands: {
695 orders: defineCommand({
696 description: 'Count the orders',
697 run: async () => `${await db.countOrders()} orders in ${session.session.threadId}`,
698 }),
699 },
700 }),
701 }
702 },
703})
704```
705
706The session gets the shared contributions and the `session` contributions together. The resources of `session` close with the session.
707
708The [MCP plugin](./mcp) works this way for `stdio` servers: one process serves every session of the host.
709
710## Reload plugins
711
712You changed a plugin, an agent file, or the list that `plugins()` returns, and an open session still runs the old setup. `session.reloadPlugins()` sets the plugins up again:
713
714```ts group=harness-plugins
715import { watch } from 'node:fs'
716import { createHarnessHost } from '@tanstack/ai-harness'
717
718const host = createHarnessHost()
719const session = await host.open(assistant, { threadId: 'thread-1' })
720
721// One session.
722await session.reloadPlugins()
723
724// Every open session of the harness, each time a file in the folder changes.
725watch('./plugins', () => void host.reload(assistant))
726```
727
728A reload works like this:
729
7301. It waits for the running turn to end. No new turn starts until the reload ends.
7312. It cleans up the resources of the session plugins, newest first.
7323. It calls `plugins()` again and runs `setup` of each session plugin.
7334. Clients get a `harness.reloaded` event. Read the commands, the settings, and the agents again.
734
735The transcript, the log, the thread settings, and the inputs that wait stay. The next turn gets the new tools, prompts, and middleware. The `ctx.on` listeners of the old plugins stop.
736
737The harness does not watch files. Your host decides when to reload, as the `watch` call above does.
738
739If a `setup` throws, the session keeps working with no plugins. The promise rejects with the error, and the `harness.reloaded` event has its `error` message. Fix the plugin and call `reloadPlugins()` again.
740
741## See the plan
742
743`session.inspect()` lists the plugins in order, and who owns each tool, prompt, command, setting, and extension point item.
744
745## What you have now
746
747- A plugin that adds tools, prompts, commands, settings, and state to any harness.
748- Middleware that sees every model call, in the lead turn and in every agent.
749- Tools and commands that act as the user of their own run.
750- Model calls of your plugin that count in the session usage and stop with their run.
751- A picker that chooses the model of each turn from its message, context, and sender.
752- Plugins that share services, lists, and events without knowing each other.
753- Commands, agents, and whole plugins that change while the session runs.
754
755Next: add the first-party plugins from `@tanstack/ai-harness/plugins` and `@tanstack/ai-harness/plugins/node`. [Ask before risky tool calls](./permissions) and [Switch between agent profiles](./agents) are two of them.