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

boundaries.md

210 lines6.0 KB

1---
2title: Lifecycle Boundaries
3id: interrupts-boundaries
4order: 5
5description: "Pick the chat lifecycle phase where a generic interrupt pauses the run."
6keywords:
7 - tanstack ai
8 - generic interrupt
9 - onInterruptBoundary
10 - INTERRUPT_BOUNDARY_PHASES
11 - beforeModel
12 - afterModel
13 - beforeTools
14 - afterTools
15---
16​
17You know you need a generic interrupt. You do not know which phase to pause
18in. If you pause too early, the model has no draft to review. If you pause too
19late, a tool has already run.
20​
21By the end of this page you can pick one phase from
22`INTERRUPT_BOUNDARY_PHASES` and write the `ctx.phase` guard for it.
23​
24For the define, register, and resolve steps, see
25[Generic Interrupts](./generic).
26​
27## The four phases
28​
29`onInterruptBoundary` runs at each of these points in one agent iteration.
30Return `{ interrupts }` to pause. Return nothing to let the run continue.
31​
32| Phase | When it runs | Typical question |
33| --- | --- | --- |
34| `beforeModel` | After `onConfig` for this iteration, before the adapter call | Do we have enough from the user to spend tokens? |
35| `afterModel` | After the model stream ends, before tools run | Is this draft or these tool calls acceptable? |
36| `beforeTools` | After the assistant tool-call message is in `messages`, before execution | May these tools run? |
37| `afterTools` | After tools finish and their result messages are in `messages` | May these results go back to the model? |
38​
39The engine combines every request from every middleware at the same phase into
40one interrupt batch. That batch ends the current run with one `interrupt`
41outcome.
42​
43```ts
44import type { ChatMiddleware } from '@tanstack/ai'
45import { reviewPlan } from './interrupts'
46​
47export const requestReview: ChatMiddleware<unknown, typeof reviewPlan> = {
48 name: 'request-review',
49 onInterruptBoundary(ctx) {
50 if (ctx.phase !== 'beforeModel') return
51 if (ctx.parentRunId) return
52 if (ctx.iteration !== 0) return
53 return {
54 interrupts: [
55 reviewPlan.interrupt({
56 key: 'initial-plan',
57 reason: 'review-required',
58 message: 'Review the proposed plan.',
59 payload: {
60 title: 'Release plan',
61 changes: ['Add search', 'Add tests'],
62 },
63 }),
64 ],
65 }
66 },
68```
69​
70`onInterruptBoundary` cannot change config. It can only pause. To change
71prompts, tools, or messages from the user answer, see
72[Apply Answers](./apply-answers).
73​
74## Skip the pause on the continuation
75​
76The continuation is a new `chat()` call. Every boundary hook runs again.
77​
78If you return the same request, the run pauses again. If `ctx.parentRunId` is
79set, skip the emit. Use that skip when the pause belongs to the original
80request only.
81​
82```ts ignore
83onInterruptBoundary(ctx) {
84 if (ctx.phase !== 'beforeModel') return
85 if (ctx.parentRunId) return
86 return {
87 interrupts: [
88 reviewPlan.interrupt({
89 key: 'initial-plan',
90 reason: 'review-required',
91 message: 'Review the proposed plan.',
92 payload: {
93 title: 'Release plan',
94 changes: ['Add search'],
95 },
96 }),
97 ],
98 }
100```
101​
102## What you can read at each phase
103​
104Every hook receives the same `ChatMiddlewareContext`. The **contents** change.
105​
106Useful fields on `ctx`:
107​
108- `phase` and `iteration`
109- `parentRunId` (set on a continuation)
110- `messages` (read-only view)
111- `systemPrompts`, `toolNames`, `hasTools`, `modelOptions`
112- `accumulatedContent` (assistant text for this model turn)
113- `model` and `provider` (fixed for this request)
114- `context` (your `chat({ context })` value)
115- `abort(reason)` and `defer(promise)`
116​
117Mutating `ctx.messages` does not change the engine config.
118​
119### `beforeModel`
120​
121`onConfig` for this iteration has already run. Prompts, tools, messages, and
122`modelOptions` are the values after that merge.
123​
124- `accumulatedContent` is empty
125- `messages` is the conversation so far
126​
127Use this phase when you need data **before** you pay for a model call.
128​
129### `afterModel`
130​
131The model stream is complete.
132​
133- `accumulatedContent` has this turn's assistant text
134- `messages` does **not** include this turn yet
135- Proposed tool calls are not on `ctx`. They are not in `messages` yet
136​
137If you need tool names or args, wait for `beforeTools`, or watch `onChunk`
138during `modelStream`.
139​
140### `beforeTools`
141​
142The engine has added the assistant message with `toolCalls` to `messages`.
143Tools have not run.
144​
145Use this phase to inspect the proposed calls before any side effect.
146​
147### `afterTools`
148​
149Tools have run. Result messages with `role: 'tool'` are already in
150`messages`. `onToolPhaseComplete` has already run.
151​
152Use this phase to inspect results before the next model turn.
153​
154## Real uses
155​
156### `beforeModel`: collect a choice first
157​
158Ask for a plan, an audience, or a locale before the model writes.
159​
160Examples:
161​
162- "Which brand voice should this reply use?"
163- "Which ticket should I work on?"
164- "Is this request in scope for this agent?"
165​
166### `afterModel`: review the draft
167​
168The model has written text. You want a human to accept it before tools run.
169​
170Examples:
171​
172- Review an email draft before `sendEmail`
173- Review a SQL query before `runQuery`
174- Review a support reply before it reaches the user
175​
176### `beforeTools`: gate the side effects
177​
178The model asked for tools. Nothing has executed.
179​
180Examples:
181​
182- Confirm a bulk delete
183- Confirm a payment
184- Confirm a deploy
185​
186This is close to [tool approval](./tool-approval). Use a generic interrupt
187when the question is not a yes or no on one tool. Also use it when several
188tools must be judged as one batch.
189​
190### `afterTools`: audit the results
191​
192The tools have already run. You want a human to see the output before the
193model uses it.
194​
195Examples:
196​
197- A search returned customer PII. Ask if it may stay in context
198- A code run produced a diff. Ask if the next turn may apply it
199- A lookup returned a low-confidence match. Ask which record to keep
200​
201## Try it
202​
203The React chat example has a playground for all four phases.
204​
2051. Start `examples/ts-react-chat`.
2062. Open `/generic-interrupts`.
2073. Pick a phase and resolve both cards.
208​
209When you are ready to apply the answer to prompts or to stop the run, go to
210[Apply Answers](./apply-answers).