Open History to see the last commit
1---
2id: DefinedChatMiddleware
3title: DefinedChatMiddleware
4---
5
6Defined in: [packages/ai/src/activities/chat/middleware/define.ts:11](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/define.ts#L11)
7
8A middleware whose `requires`/`provides` tuple types are captured precisely
9(via `const` inference) for the array coverage check and the builder.
10
11## Extends
12
13- [`ChatMiddleware`](ChatMiddleware.md)\<`TContext`, `TInterruptDefinitions`\>
14
15## Type Parameters
16
17### TContext
18
19`TContext`
20
21### TRequires
22
23`TRequires` *extends* `ReadonlyArray`\<[`CapabilityHandle`](../type-aliases/CapabilityHandle.md)\>
24
25### TProvides
26
27`TProvides` *extends* `ReadonlyArray`\<[`CapabilityHandle`](../type-aliases/CapabilityHandle.md)\>
28
29### TInterruptDefinitions
30
31`TInterruptDefinitions` *extends* `AnyInterruptDefinition` = `never`
32
33## Properties
34
35### name?
36
37```ts
38optional name?: string;
39```
40
41Defined in: [packages/ai/src/activities/chat/middleware/types.ts:688](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L688)
42
43Optional name for debugging and identification
44
45#### Inherited from
46
47[`ChatMiddleware`](ChatMiddleware.md).[`name`](ChatMiddleware.md#name)
48
49***
50
51### onAbort?
52
53```ts
54optional onAbort?: (ctx, info) => void | Promise<void>;
55```
56
57Defined in: [packages/ai/src/activities/chat/middleware/types.ts:907](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L907)
58
59Called when the chat run is aborted.
60Exactly one of onFinish/onAbort/onError will be called per run.
61
62#### Parameters
63
64##### ctx
65
66[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
67
68##### info
69
70[`AbortInfo`](AbortInfo.md)
71
72#### Returns
73
74`void` \| `Promise`\<`void`\>
75
76#### Inherited from
77
78[`ChatMiddleware`](ChatMiddleware.md).[`onAbort`](ChatMiddleware.md#onabort)
79
80***
81
82### onAfterToolCall?
83
84```ts
85optional onAfterToolCall?: (ctx, info) =>
86 | AfterToolCallDecision
87| Promise<AfterToolCallDecision>;
88```
89
90Defined in: [packages/ai/src/activities/chat/middleware/types.ts:871](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L871)
91
92Called after a tool execution completes (success or failure).
93Return `{ type: 'replaceResult', result }` to change the result that the
94model and the stream see. Middleware run in order. Each one sees the
95result of the one before it.
96
97Also called for a tool call that did not run because the output limit
98cut its answer. Then `ok` is false, and `error` is an `Error` with the
99code `'max_tokens'`.
100
101#### Parameters
102
103##### ctx
104
105[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
106
107##### info
108
109[`AfterToolCallInfo`](AfterToolCallInfo.md)
110
111#### Returns
112
113 \| [`AfterToolCallDecision`](../type-aliases/AfterToolCallDecision.md)
114 \| `Promise`\<[`AfterToolCallDecision`](../type-aliases/AfterToolCallDecision.md)\>
115
116#### Inherited from
117
118[`ChatMiddleware`](ChatMiddleware.md).[`onAfterToolCall`](ChatMiddleware.md#onaftertoolcall)
119
120***
121
122### onBeforeToolCall?
123
124```ts
125optional onBeforeToolCall?: (ctx, hookCtx) =>
126 | BeforeToolCallDecision
127| Promise<BeforeToolCallDecision>;
128```
129
130Defined in: [packages/ai/src/activities/chat/middleware/types.ts:856](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L856)
131
132Called before a server tool runs and before a client tool is sent to the
133client. Not called while the call waits for approval.
134Can observe, transform args, skip execution, or abort the run.
135The tool's `inputSchema` checks the args after this hook.
136
137#### Parameters
138
139##### ctx
140
141[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
142
143##### hookCtx
144
145[`ToolCallHookContext`](ToolCallHookContext.md)
146
147#### Returns
148
149 \| [`BeforeToolCallDecision`](../type-aliases/BeforeToolCallDecision.md)
150 \| `Promise`\<[`BeforeToolCallDecision`](../type-aliases/BeforeToolCallDecision.md)\>
151
152#### Inherited from
153
154[`ChatMiddleware`](ChatMiddleware.md).[`onBeforeToolCall`](ChatMiddleware.md#onbeforetoolcall)
155
156***
157
158### onChunk?
159
160```ts
161optional onChunk?: (ctx, chunk) =>
162 | void
163 | AGUIEvent
164 | AGUIEvent[]
165 | Promise<void | AGUIEvent | AGUIEvent[] | null>
166 | null;
167```
168
169Defined in: [packages/ai/src/activities/chat/middleware/types.ts:840](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L840)
170
171Called for every chunk yielded by chat().
172Can observe, transform, expand, or drop chunks.
173
174#### Parameters
175
176##### ctx
177
178[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
179
180##### chunk
181
182[`AGUIEvent`](../type-aliases/AGUIEvent.md)
183
184#### Returns
185
186 \| `void`
187 \| [`AGUIEvent`](../type-aliases/AGUIEvent.md)
188 \| [`AGUIEvent`](../type-aliases/AGUIEvent.md)[]
189 \| `Promise`\<void \| AGUIEvent \| AGUIEvent\[\] \| null\>
190 \| `null`
191
192void (pass through), chunk (replace), chunk[] (expand), null (drop)
193
194#### Inherited from
195
196[`ChatMiddleware`](ChatMiddleware.md).[`onChunk`](ChatMiddleware.md#onchunk)
197
198***
199
200### onConfig?
201
202```ts
203optional onConfig?: (ctx, config) =>
204 | void
205 | Partial<ChatMiddlewareConfig>
206 | Promise<
207 | void
208 | Partial<ChatMiddlewareConfig>
209 | null>
210 | null;
211```
212
213Defined in: [packages/ai/src/activities/chat/middleware/types.ts:752](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L752)
214
215Called to observe or transform the chat configuration.
216Called at init and at the beginning of each agent iteration.
217
218Return a partial config to merge with the current config, or void to pass through.
219Only the fields you return are overwritten — everything else is preserved.
220
221#### Parameters
222
223##### ctx
224
225[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
226
227##### config
228
229[`ChatMiddlewareConfig`](ChatMiddlewareConfig.md)
230
231#### Returns
232
233 \| `void`
234 \| `Partial`\<[`ChatMiddlewareConfig`](ChatMiddlewareConfig.md)\>
235 \| `Promise`\<
236 \| `void`
237 \| `Partial`\<[`ChatMiddlewareConfig`](ChatMiddlewareConfig.md)\>
238 \| `null`\>
239 \| `null`
240
241#### Inherited from
242
243[`ChatMiddleware`](ChatMiddleware.md).[`onConfig`](ChatMiddleware.md#onconfig)
244
245***
246
247### onError?
248
249```ts
250optional onError?: (ctx, info) => void | Promise<void>;
251```
252
253Defined in: [packages/ai/src/activities/chat/middleware/types.ts:916](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L916)
254
255Called when the chat run encounters an unhandled error.
256Exactly one of onFinish/onAbort/onError will be called per run.
257
258#### Parameters
259
260##### ctx
261
262[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
263
264##### info
265
266[`ErrorInfo`](ErrorInfo.md)
267
268#### Returns
269
270`void` \| `Promise`\<`void`\>
271
272#### Inherited from
273
274[`ChatMiddleware`](ChatMiddleware.md).[`onError`](ChatMiddleware.md#onerror)
275
276***
277
278### onFinish?
279
280```ts
281optional onFinish?: (ctx, info) => void | Promise<void>;
282```
283
284Defined in: [packages/ai/src/activities/chat/middleware/types.ts:898](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L898)
285
286Called when the chat run completes normally.
287Exactly one of onFinish/onAbort/onError will be called per run.
288
289#### Parameters
290
291##### ctx
292
293[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
294
295##### info
296
297[`FinishInfo`](FinishInfo.md)
298
299#### Returns
300
301`void` \| `Promise`\<`void`\>
302
303#### Inherited from
304
305[`ChatMiddleware`](ChatMiddleware.md).[`onFinish`](ChatMiddleware.md#onfinish)
306
307***
308
309### onInterruptBoundary?
310
311```ts
312optional onInterruptBoundary?: (ctx) =>
313 | InterruptBoundaryResult<TInterruptDefinitions>
314| Promise<InterruptBoundaryResult<TInterruptDefinitions>>;
315```
316
317Defined in: [packages/ai/src/activities/chat/middleware/types.ts:700](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L700)
318
319Called at a lifecycle boundary. Return interrupt requests to pause the run.
320Requests from every middleware in the same boundary form one batch.
321
322#### Parameters
323
324##### ctx
325
326[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\> & `object`
327
328#### Returns
329
330 \| [`InterruptBoundaryResult`](../type-aliases/InterruptBoundaryResult.md)\<`TInterruptDefinitions`\>
331 \| `Promise`\<[`InterruptBoundaryResult`](../type-aliases/InterruptBoundaryResult.md)\<`TInterruptDefinitions`\>\>
332
333#### Inherited from
334
335[`ChatMiddleware`](ChatMiddleware.md).[`onInterruptBoundary`](ChatMiddleware.md#oninterruptboundary)
336
337***
338
339### onInterruptResolution?
340
341```ts
342optional onInterruptResolution?: (ctx, resolutions) =>
343 | InterruptResolutionResult
344| Promise<InterruptResolutionResult>;
345```
346
347Defined in: [packages/ai/src/activities/chat/middleware/types.ts:710](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L710)
348
349Called on a continuation run after the client answers registered interrupts.
350Return `toolResume` to decide whether pending tools continue, cancel, or stop.
351
352#### Parameters
353
354##### ctx
355
356[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
357
358##### resolutions
359
360[`InterruptResolutionCollection`](InterruptResolutionCollection.md)\<`TInterruptDefinitions`\>
361
362#### Returns
363
364 \| [`InterruptResolutionResult`](../type-aliases/InterruptResolutionResult.md)
365 \| `Promise`\<[`InterruptResolutionResult`](../type-aliases/InterruptResolutionResult.md)\>
366
367#### Inherited from
368
369[`ChatMiddleware`](ChatMiddleware.md).[`onInterruptResolution`](ChatMiddleware.md#oninterruptresolution)
370
371***
372
373### onIteration?
374
375```ts
376optional onIteration?: (ctx, info) => void | Promise<void>;
377```
378
379Defined in: [packages/ai/src/activities/chat/middleware/types.ts:794](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L794)
380
381Called at the start of each agent loop iteration, after a new assistant message ID
382is created. Use this to observe iteration boundaries.
383
384#### Parameters
385
386##### ctx
387
388[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
389
390##### info
391
392[`IterationInfo`](IterationInfo.md)
393
394#### Returns
395
396`void` \| `Promise`\<`void`\>
397
398#### Inherited from
399
400[`ChatMiddleware`](ChatMiddleware.md).[`onIteration`](ChatMiddleware.md#oniteration)
401
402***
403
404### onModelError?
405
406```ts
407optional onModelError?: (ctx, error) => void | Promise<void>;
408```
409
410Defined in: [packages/ai/src/activities/chat/middleware/types.ts:829](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L829)
411
412Called when the adapter sends a `RUN_ERROR` before any output of the
413model call. The error does not reach `onChunk` or the caller yet. An
414exception that the adapter throws goes to `onError`, not here.
415
416Call `ctx.retry()` to call the model again. Then `onConfig` runs again
417(phase `beforeModel`), so the middleware can change the request first,
418and the failed call is dropped from the stream. Without `ctx.retry()`,
419the error goes on as usual. A model call retries at most 2 times this
420way. The structured-output call is not retried.
421
422#### Parameters
423
424##### ctx
425
426[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
427
428##### error
429
430[`RunErrorEvent`](RunErrorEvent.md)
431
432#### Returns
433
434`void` \| `Promise`\<`void`\>
435
436#### Inherited from
437
438[`ChatMiddleware`](ChatMiddleware.md).[`onModelError`](ChatMiddleware.md#onmodelerror)
439
440***
441
442### onShouldContinue?
443
444```ts
445optional onShouldContinue?: (ctx, state) => boolean | void | Promise<boolean | void>;
446```
447
448Defined in: [packages/ai/src/activities/chat/middleware/types.ts:813](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L813)
449
450Called when the engine is deciding whether to start another agent-loop
451iteration (after a tool phase or between model turns).
452
453Return `false` to stop further iterations. Return `true`, `void`, or
454`undefined` to allow continuation. Combined with AND semantics across
455middleware and with `agentLoopStrategy` — any `false` stops the loop.
456
457Does not abort the run: the stream finishes normally with the current
458messages. Use `ctx.abort()` only when you need a hard abort.
459
460Receives the same [AgentLoopState](AgentLoopState.md) passed to strategies
461(`iterationCount`, `toolCallCount`, `lastTurnToolCallCount`, etc.).
462
463#### Parameters
464
465##### ctx
466
467[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
468
469##### state
470
471[`AgentLoopState`](AgentLoopState.md)
472
473#### Returns
474
475`boolean` \| `void` \| `Promise`\<`boolean` \| `void`\>
476
477#### Inherited from
478
479[`ChatMiddleware`](ChatMiddleware.md).[`onShouldContinue`](ChatMiddleware.md#onshouldcontinue)
480
481***
482
483### onStart?
484
485```ts
486optional onStart?: (ctx) => void | Promise<void>;
487```
488
489Defined in: [packages/ai/src/activities/chat/middleware/types.ts:788](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L788)
490
491Called when the chat run starts (after initial onConfig).
492
493#### Parameters
494
495##### ctx
496
497[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
498
499#### Returns
500
501`void` \| `Promise`\<`void`\>
502
503#### Inherited from
504
505[`ChatMiddleware`](ChatMiddleware.md).[`onStart`](ChatMiddleware.md#onstart)
506
507***
508
509### onStructuredOutputConfig?
510
511```ts
512optional onStructuredOutputConfig?: (ctx, config) =>
513 | void
514 | Partial<StructuredOutputMiddlewareConfig>
515 | Promise<
516 | void
517 | Partial<StructuredOutputMiddlewareConfig>
518 | null>
519 | null;
520```
521
522Defined in: [packages/ai/src/activities/chat/middleware/types.ts:776](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L776)
523
524Called at the start of the final structured-output call (when the chat
525was invoked with outputSchema). Pipes through middleware in order, like
526onConfig, but with access to the JSON Schema being sent to the provider.
527
528Return a partial to shallow-merge into the current config, or void to
529pass through.
530
531Fires BEFORE onConfig at the structured-output boundary. onConfig also
532re-fires at the same boundary with ctx.phase === 'structuredOutput',
533receiving the post-onStructuredOutputConfig view of the config (minus
534outputSchema). Use onConfig for general-purpose transforms that apply
535to every adapter call; use this hook when you need to transform the
536outputSchema or apply structured-output-specific behavior.
537
538#### Parameters
539
540##### ctx
541
542[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
543
544##### config
545
546[`StructuredOutputMiddlewareConfig`](StructuredOutputMiddlewareConfig.md)
547
548#### Returns
549
550 \| `void`
551 \| `Partial`\<[`StructuredOutputMiddlewareConfig`](StructuredOutputMiddlewareConfig.md)\>
552 \| `Promise`\<
553 \| `void`
554 \| `Partial`\<[`StructuredOutputMiddlewareConfig`](StructuredOutputMiddlewareConfig.md)\>
555 \| `null`\>
556 \| `null`
557
558#### Inherited from
559
560[`ChatMiddleware`](ChatMiddleware.md).[`onStructuredOutputConfig`](ChatMiddleware.md#onstructuredoutputconfig)
561
562***
563
564### onToolPhaseComplete?
565
566```ts
567optional onToolPhaseComplete?: (ctx, info) => void | Promise<void>;
568```
569
570Defined in: [packages/ai/src/activities/chat/middleware/types.ts:880](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L880)
571
572Called after all tool calls in an iteration have been processed.
573Provides aggregate data about tool execution results, approvals, and client tools.
574
575#### Parameters
576
577##### ctx
578
579[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
580
581##### info
582
583[`ToolPhaseCompleteInfo`](ToolPhaseCompleteInfo.md)
584
585#### Returns
586
587`void` \| `Promise`\<`void`\>
588
589#### Inherited from
590
591[`ChatMiddleware`](ChatMiddleware.md).[`onToolPhaseComplete`](ChatMiddleware.md#ontoolphasecomplete)
592
593***
594
595### onUsage?
596
597```ts
598optional onUsage?: (ctx, usage) => void | Promise<void>;
599```
600
601Defined in: [packages/ai/src/activities/chat/middleware/types.ts:889](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L889)
602
603Called when usage data is available from a RUN_FINISHED chunk.
604Called once per model iteration that reports usage.
605
606#### Parameters
607
608##### ctx
609
610[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
611
612##### usage
613
614[`UsageInfo`](UsageInfo.md)
615
616#### Returns
617
618`void` \| `Promise`\<`void`\>
619
620#### Inherited from
621
622[`ChatMiddleware`](ChatMiddleware.md).[`onUsage`](ChatMiddleware.md#onusage)
623
624***
625
626### optionalRequires?
627
628```ts
629optional optionalRequires?: readonly CapabilityHandle[];
630```
631
632Defined in: [packages/ai/src/activities/chat/middleware/types.ts:735](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L735)
633
634Capabilities this middleware uses if present but does not require.
635Non-gating: never causes a validation error. Read with
636`getX(ctx, { optional: true })`.
637
638#### Inherited from
639
640[`ChatMiddleware`](ChatMiddleware.md).[`optionalRequires`](ChatMiddleware.md#optionalrequires)
641
642***
643
644### provides?
645
646```ts
647optional provides?: TProvides;
648```
649
650Defined in: [packages/ai/src/activities/chat/middleware/define.ts:18](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/define.ts#L18)
651
652Capabilities this middleware provides. Each declared capability MUST be
653provided (via its `provide` accessor) inside `setup`, or `chat()` throws
654after the setup phase.
655
656#### Overrides
657
658[`ChatMiddleware`](ChatMiddleware.md).[`provides`](ChatMiddleware.md#provides)
659
660***
661
662### requires?
663
664```ts
665optional requires?: TRequires;
666```
667
668Defined in: [packages/ai/src/activities/chat/middleware/define.ts:17](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/define.ts#L17)
669
670Capabilities this middleware requires. `chat()` validates that some
671middleware (or the adapter) provides each one; unsatisfied requirements are
672a compile-time error (array coverage / builder) and a runtime error before
673the adapter runs.
674
675#### Overrides
676
677[`ChatMiddleware`](ChatMiddleware.md).[`requires`](ChatMiddleware.md#requires)
678
679***
680
681### routedSubagentPersistence?
682
683```ts
684optional routedSubagentPersistence?: RoutedSubagentPersistence;
685```
686
687Defined in: [packages/ai/src/activities/chat/middleware/types.ts:694](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L694)
688
689Present when this middleware stores subagent runs.
690The router calls it. An app does not set it.
691
692#### Inherited from
693
694[`ChatMiddleware`](ChatMiddleware.md).[`routedSubagentPersistence`](ChatMiddleware.md#routedsubagentpersistence)
695
696***
697
698### sandbox?
699
700```ts
701optional sandbox?: ChatSandboxHooks<TContext>;
702```
703
704Defined in: [packages/ai/src/activities/chat/middleware/types.ts:925](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L925)
705
706Sandbox file-event hooks. Fire when a sandbox provided by `withSandbox` is
707active during the run and a file is created/changed/deleted. Server-side.
708
709#### Inherited from
710
711[`ChatMiddleware`](ChatMiddleware.md).[`sandbox`](ChatMiddleware.md#sandbox)
712
713***
714
715### setup?
716
717```ts
718optional setup?: (ctx) => void | Promise<void>;
719```
720
721Defined in: [packages/ai/src/activities/chat/middleware/types.ts:743](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L743)
722
723Provisioning hook. Runs FIRST — before `onConfig` (init) — across all
724middleware in array order. Use it to call `provide` accessors so later
725middleware (`onConfig` onward) can consume the capabilities. Receives the
726stable context; does NOT receive the mutable config.
727
728#### Parameters
729
730##### ctx
731
732[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
733
734#### Returns
735
736`void` \| `Promise`\<`void`\>
737
738#### Inherited from
739
740[`ChatMiddleware`](ChatMiddleware.md).[`setup`](ChatMiddleware.md#setup)