Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

DefinedChatMiddleware.md

690 lines17.3 KB

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:626](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L626)
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:820](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L820)
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) => void | Promise<void>;
86```
87​
88Defined in: [packages/ai/src/activities/chat/middleware/types.ts:784](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L784)
89​
90Called after a tool execution completes (success or failure).
91​
92#### Parameters
93​
94##### ctx
95​
96[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
97​
98##### info
99​
100[`AfterToolCallInfo`](AfterToolCallInfo.md)
101​
102#### Returns
103​
104`void` \| `Promise`\<`void`\>
105​
106#### Inherited from
107​
108[`ChatMiddleware`](ChatMiddleware.md).[`onAfterToolCall`](ChatMiddleware.md#onaftertoolcall)
109​
110***
111​
112### onBeforeToolCall?
113​
114```ts
115optional onBeforeToolCall?: (ctx, hookCtx) =>
116 | BeforeToolCallDecision
117| Promise<BeforeToolCallDecision>;
118```
119​
120Defined 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)
121​
122Called before a tool is executed.
123Can observe, transform args, skip execution, or abort the run.
124​
125#### Parameters
126​
127##### ctx
128​
129[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
130​
131##### hookCtx
132​
133[`ToolCallHookContext`](ToolCallHookContext.md)
134​
135#### Returns
136​
137 \| [`BeforeToolCallDecision`](../type-aliases/BeforeToolCallDecision.md)
138 \| `Promise`\<[`BeforeToolCallDecision`](../type-aliases/BeforeToolCallDecision.md)\>
139​
140#### Inherited from
141​
142[`ChatMiddleware`](ChatMiddleware.md).[`onBeforeToolCall`](ChatMiddleware.md#onbeforetoolcall)
143​
144***
145​
146### onChunk?
147​
148```ts
149optional onChunk?: (ctx, chunk) =>
150 | void
151 | AGUIEvent
152 | AGUIEvent[]
153 | Promise<void | AGUIEvent | AGUIEvent[] | null>
154 | null;
155```
156​
157Defined in: [packages/ai/src/activities/chat/middleware/types.ts:762](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L762)
158​
159Called for every chunk yielded by chat().
160Can observe, transform, expand, or drop chunks.
161​
162#### Parameters
163​
164##### ctx
165​
166[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
167​
168##### chunk
169​
170[`AGUIEvent`](../type-aliases/AGUIEvent.md)
171​
172#### Returns
173​
174 \| `void`
175 \| [`AGUIEvent`](../type-aliases/AGUIEvent.md)
176 \| [`AGUIEvent`](../type-aliases/AGUIEvent.md)[]
177 \| `Promise`\<void \| AGUIEvent \| AGUIEvent\[\] \| null\>
178 \| `null`
179​
180void (pass through), chunk (replace), chunk[] (expand), null (drop)
181​
182#### Inherited from
183​
184[`ChatMiddleware`](ChatMiddleware.md).[`onChunk`](ChatMiddleware.md#onchunk)
185​
186***
187​
188### onConfig?
189​
190```ts
191optional onConfig?: (ctx, config) =>
192 | void
193 | Partial<ChatMiddlewareConfig>
194 | Promise<
195 | void
196 | Partial<ChatMiddlewareConfig>
197 | null>
198 | null;
199```
200​
201Defined in: [packages/ai/src/activities/chat/middleware/types.ts:690](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L690)
202​
203Called to observe or transform the chat configuration.
204Called at init and at the beginning of each agent iteration.
205​
206Return a partial config to merge with the current config, or void to pass through.
207Only the fields you return are overwritten — everything else is preserved.
208​
209#### Parameters
210​
211##### ctx
212​
213[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
214​
215##### config
216​
217[`ChatMiddlewareConfig`](ChatMiddlewareConfig.md)
218​
219#### Returns
220​
221 \| `void`
222 \| `Partial`\<[`ChatMiddlewareConfig`](ChatMiddlewareConfig.md)\>
223 \| `Promise`\<
224 \| `void`
225 \| `Partial`\<[`ChatMiddlewareConfig`](ChatMiddlewareConfig.md)\>
226 \| `null`\>
227 \| `null`
228​
229#### Inherited from
230​
231[`ChatMiddleware`](ChatMiddleware.md).[`onConfig`](ChatMiddleware.md#onconfig)
232​
233***
234​
235### onError?
236​
237```ts
238optional onError?: (ctx, info) => void | Promise<void>;
239```
240​
241Defined 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)
242​
243Called when the chat run encounters an unhandled error.
244Exactly one of onFinish/onAbort/onError will be called per run.
245​
246#### Parameters
247​
248##### ctx
249​
250[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
251​
252##### info
253​
254[`ErrorInfo`](ErrorInfo.md)
255​
256#### Returns
257​
258`void` \| `Promise`\<`void`\>
259​
260#### Inherited from
261​
262[`ChatMiddleware`](ChatMiddleware.md).[`onError`](ChatMiddleware.md#onerror)
263​
264***
265​
266### onFinish?
267​
268```ts
269optional onFinish?: (ctx, info) => void | Promise<void>;
270```
271​
272Defined in: [packages/ai/src/activities/chat/middleware/types.ts:811](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L811)
273​
274Called when the chat run completes normally.
275Exactly one of onFinish/onAbort/onError will be called per run.
276​
277#### Parameters
278​
279##### ctx
280​
281[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
282​
283##### info
284​
285[`FinishInfo`](FinishInfo.md)
286​
287#### Returns
288​
289`void` \| `Promise`\<`void`\>
290​
291#### Inherited from
292​
293[`ChatMiddleware`](ChatMiddleware.md).[`onFinish`](ChatMiddleware.md#onfinish)
294​
295***
296​
297### onInterruptBoundary?
298​
299```ts
300optional onInterruptBoundary?: (ctx) =>
301 | InterruptBoundaryResult<TInterruptDefinitions>
302| Promise<InterruptBoundaryResult<TInterruptDefinitions>>;
303```
304​
305Defined in: [packages/ai/src/activities/chat/middleware/types.ts:638](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L638)
306​
307Called at a lifecycle boundary. Return interrupt requests to pause the run.
308Requests from every middleware in the same boundary form one batch.
309​
310#### Parameters
311​
312##### ctx
313​
314[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\> & `object`
315​
316#### Returns
317​
318 \| [`InterruptBoundaryResult`](../type-aliases/InterruptBoundaryResult.md)\<`TInterruptDefinitions`\>
319 \| `Promise`\<[`InterruptBoundaryResult`](../type-aliases/InterruptBoundaryResult.md)\<`TInterruptDefinitions`\>\>
320​
321#### Inherited from
322​
323[`ChatMiddleware`](ChatMiddleware.md).[`onInterruptBoundary`](ChatMiddleware.md#oninterruptboundary)
324​
325***
326​
327### onInterruptResolution?
328​
329```ts
330optional onInterruptResolution?: (ctx, resolutions) =>
331 | InterruptResolutionResult
332| Promise<InterruptResolutionResult>;
333```
334​
335Defined in: [packages/ai/src/activities/chat/middleware/types.ts:648](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L648)
336​
337Called on a continuation run after the client answers registered interrupts.
338Return `toolResume` to decide whether pending tools continue, cancel, or stop.
339​
340#### Parameters
341​
342##### ctx
343​
344[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
345​
346##### resolutions
347​
348[`InterruptResolutionCollection`](InterruptResolutionCollection.md)\<`TInterruptDefinitions`\>
349​
350#### Returns
351​
352 \| [`InterruptResolutionResult`](../type-aliases/InterruptResolutionResult.md)
353 \| `Promise`\<[`InterruptResolutionResult`](../type-aliases/InterruptResolutionResult.md)\>
354​
355#### Inherited from
356​
357[`ChatMiddleware`](ChatMiddleware.md).[`onInterruptResolution`](ChatMiddleware.md#oninterruptresolution)
358​
359***
360​
361### onIteration?
362​
363```ts
364optional onIteration?: (ctx, info) => void | Promise<void>;
365```
366​
367Defined in: [packages/ai/src/activities/chat/middleware/types.ts:732](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L732)
368​
369Called at the start of each agent loop iteration, after a new assistant message ID
370is created. Use this to observe iteration boundaries.
371​
372#### Parameters
373​
374##### ctx
375​
376[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
377​
378##### info
379​
380[`IterationInfo`](IterationInfo.md)
381​
382#### Returns
383​
384`void` \| `Promise`\<`void`\>
385​
386#### Inherited from
387​
388[`ChatMiddleware`](ChatMiddleware.md).[`onIteration`](ChatMiddleware.md#oniteration)
389​
390***
391​
392### onShouldContinue?
393​
394```ts
395optional onShouldContinue?: (ctx, state) => boolean | void | Promise<boolean | void>;
396```
397​
398Defined in: [packages/ai/src/activities/chat/middleware/types.ts:751](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L751)
399​
400Called when the engine is deciding whether to start another agent-loop
401iteration (after a tool phase or between model turns).
402​
403Return `false` to stop further iterations. Return `true`, `void`, or
404`undefined` to allow continuation. Combined with AND semantics across
405middleware and with `agentLoopStrategy` — any `false` stops the loop.
406​
407Does not abort the run: the stream finishes normally with the current
408messages. Use `ctx.abort()` only when you need a hard abort.
409​
410Receives the same [AgentLoopState](AgentLoopState.md) passed to strategies
411(`iterationCount`, `toolCallCount`, `lastTurnToolCallCount`, etc.).
412​
413#### Parameters
414​
415##### ctx
416​
417[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
418​
419##### state
420​
421[`AgentLoopState`](AgentLoopState.md)
422​
423#### Returns
424​
425`boolean` \| `void` \| `Promise`\<`boolean` \| `void`\>
426​
427#### Inherited from
428​
429[`ChatMiddleware`](ChatMiddleware.md).[`onShouldContinue`](ChatMiddleware.md#onshouldcontinue)
430​
431***
432​
433### onStart?
434​
435```ts
436optional onStart?: (ctx) => void | Promise<void>;
437```
438​
439Defined in: [packages/ai/src/activities/chat/middleware/types.ts:726](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L726)
440​
441Called when the chat run starts (after initial onConfig).
442​
443#### Parameters
444​
445##### ctx
446​
447[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
448​
449#### Returns
450​
451`void` \| `Promise`\<`void`\>
452​
453#### Inherited from
454​
455[`ChatMiddleware`](ChatMiddleware.md).[`onStart`](ChatMiddleware.md#onstart)
456​
457***
458​
459### onStructuredOutputConfig?
460​
461```ts
462optional onStructuredOutputConfig?: (ctx, config) =>
463 | void
464 | Partial<StructuredOutputMiddlewareConfig>
465 | Promise<
466 | void
467 | Partial<StructuredOutputMiddlewareConfig>
468 | null>
469 | null;
470```
471​
472Defined in: [packages/ai/src/activities/chat/middleware/types.ts:714](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L714)
473​
474Called at the start of the final structured-output call (when the chat
475was invoked with outputSchema). Pipes through middleware in order, like
476onConfig, but with access to the JSON Schema being sent to the provider.
477​
478Return a partial to shallow-merge into the current config, or void to
479pass through.
480​
481Fires BEFORE onConfig at the structured-output boundary. onConfig also
482re-fires at the same boundary with ctx.phase === 'structuredOutput',
483receiving the post-onStructuredOutputConfig view of the config (minus
484outputSchema). Use onConfig for general-purpose transforms that apply
485to every adapter call; use this hook when you need to transform the
486outputSchema or apply structured-output-specific behavior.
487​
488#### Parameters
489​
490##### ctx
491​
492[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
493​
494##### config
495​
496[`StructuredOutputMiddlewareConfig`](StructuredOutputMiddlewareConfig.md)
497​
498#### Returns
499​
500 \| `void`
501 \| `Partial`\<[`StructuredOutputMiddlewareConfig`](StructuredOutputMiddlewareConfig.md)\>
502 \| `Promise`\<
503 \| `void`
504 \| `Partial`\<[`StructuredOutputMiddlewareConfig`](StructuredOutputMiddlewareConfig.md)\>
505 \| `null`\>
506 \| `null`
507​
508#### Inherited from
509​
510[`ChatMiddleware`](ChatMiddleware.md).[`onStructuredOutputConfig`](ChatMiddleware.md#onstructuredoutputconfig)
511​
512***
513​
514### onToolPhaseComplete?
515​
516```ts
517optional onToolPhaseComplete?: (ctx, info) => void | Promise<void>;
518```
519​
520Defined in: [packages/ai/src/activities/chat/middleware/types.ts:793](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L793)
521​
522Called after all tool calls in an iteration have been processed.
523Provides aggregate data about tool execution results, approvals, and client tools.
524​
525#### Parameters
526​
527##### ctx
528​
529[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
530​
531##### info
532​
533[`ToolPhaseCompleteInfo`](ToolPhaseCompleteInfo.md)
534​
535#### Returns
536​
537`void` \| `Promise`\<`void`\>
538​
539#### Inherited from
540​
541[`ChatMiddleware`](ChatMiddleware.md).[`onToolPhaseComplete`](ChatMiddleware.md#ontoolphasecomplete)
542​
543***
544​
545### onUsage?
546​
547```ts
548optional onUsage?: (ctx, usage) => void | Promise<void>;
549```
550​
551Defined in: [packages/ai/src/activities/chat/middleware/types.ts:802](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L802)
552​
553Called when usage data is available from a RUN_FINISHED chunk.
554Called once per model iteration that reports usage.
555​
556#### Parameters
557​
558##### ctx
559​
560[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
561​
562##### usage
563​
564[`UsageInfo`](UsageInfo.md)
565​
566#### Returns
567​
568`void` \| `Promise`\<`void`\>
569​
570#### Inherited from
571​
572[`ChatMiddleware`](ChatMiddleware.md).[`onUsage`](ChatMiddleware.md#onusage)
573​
574***
575​
576### optionalRequires?
577​
578```ts
579optional optionalRequires?: readonly CapabilityHandle[];
580```
581​
582Defined in: [packages/ai/src/activities/chat/middleware/types.ts:673](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L673)
583​
584Capabilities this middleware uses if present but does not require.
585Non-gating: never causes a validation error. Read with
586`getX(ctx, { optional: true })`.
587​
588#### Inherited from
589​
590[`ChatMiddleware`](ChatMiddleware.md).[`optionalRequires`](ChatMiddleware.md#optionalrequires)
591​
592***
593​
594### provides?
595​
596```ts
597optional provides?: TProvides;
598```
599​
600Defined 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)
601​
602Capabilities this middleware provides. Each declared capability MUST be
603provided (via its `provide` accessor) inside `setup`, or `chat()` throws
604after the setup phase.
605​
606#### Overrides
607​
608[`ChatMiddleware`](ChatMiddleware.md).[`provides`](ChatMiddleware.md#provides)
609​
610***
611​
612### requires?
613​
614```ts
615optional requires?: TRequires;
616```
617​
618Defined 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)
619​
620Capabilities this middleware requires. `chat()` validates that some
621middleware (or the adapter) provides each one; unsatisfied requirements are
622a compile-time error (array coverage / builder) and a runtime error before
623the adapter runs.
624​
625#### Overrides
626​
627[`ChatMiddleware`](ChatMiddleware.md).[`requires`](ChatMiddleware.md#requires)
628​
629***
630​
631### routedSubagentPersistence?
632​
633```ts
634optional routedSubagentPersistence?: RoutedSubagentPersistence;
635```
636​
637Defined in: [packages/ai/src/activities/chat/middleware/types.ts:632](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L632)
638​
639Present when this middleware stores subagent runs.
640The router calls it. An app does not set it.
641​
642#### Inherited from
643​
644[`ChatMiddleware`](ChatMiddleware.md).[`routedSubagentPersistence`](ChatMiddleware.md#routedsubagentpersistence)
645​
646***
647​
648### sandbox?
649​
650```ts
651optional sandbox?: ChatSandboxHooks<TContext>;
652```
653​
654Defined in: [packages/ai/src/activities/chat/middleware/types.ts:838](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L838)
655​
656Sandbox file-event hooks. Fire when a sandbox provided by `withSandbox` is
657active during the run and a file is created/changed/deleted. Server-side.
658​
659#### Inherited from
660​
661[`ChatMiddleware`](ChatMiddleware.md).[`sandbox`](ChatMiddleware.md#sandbox)
662​
663***
664​
665### setup?
666​
667```ts
668optional setup?: (ctx) => void | Promise<void>;
669```
670​
671Defined in: [packages/ai/src/activities/chat/middleware/types.ts:681](https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts#L681)
672​
673Provisioning hook. Runs FIRST — before `onConfig` (init) — across all
674middleware in array order. Use it to call `provide` accessors so later
675middleware (`onConfig` onward) can consume the capabilities. Receives the
676stable context; does NOT receive the mutable config.
677​
678#### Parameters
679​
680##### ctx
681​
682[`ChatMiddlewareContext`](ChatMiddlewareContext.md)\<`TContext`\>
683​
684#### Returns
685​
686`void` \| `Promise`\<`void`\>
687​
688#### Inherited from
689​
690[`ChatMiddleware`](ChatMiddleware.md).[`setup`](ChatMiddleware.md#setup)