Open History to see the last commit
1---
2title: Lifecycle Boundaries
3id: interrupts-boundaries
4order: 5
5description: "Pick the point in the chat lifecycle 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
17Pause a generic interrupt after the model has a draft and before a tool runs.
18
19Each agent iteration has four boundaries. You pick one with a `ctx.phase` guard
20in `onInterruptBoundary`.
21
22This page assumes that you have a definition from
23[Generic Interrupts](./generic).
24
25## Quick setup
26
27### 1. Pick a phase
28
29| Phase | When it runs | Use it to |
30| --- | --- | --- |
31| `beforeModel` | After `onConfig` for this iteration, before the adapter call | Get a choice from the user before you pay for tokens |
32| `afterModel` | After the model stream ends, before tools run | Review the draft that the model wrote |
33| `beforeTools` | After the assistant tool-call message is in `messages`, before the tools run | Allow or block side effects |
34| `afterTools` | After the tools finish and their results are in `messages` | Audit tool results before the model reads them |
35
36### 2. Guard on the phase
37
38Return `{ interrupts }` to pause. Return nothing to let the run continue. This
39example pauses at `beforeModel` on the first iteration only:
40
41```ts
42import type { ChatMiddleware } from '@tanstack/ai'
43import { reviewPlan } from './interrupts'
44
45export const requestReview: ChatMiddleware<unknown, typeof reviewPlan> = {
46 name: 'request-review',
47 onInterruptBoundary(ctx) {
48 if (ctx.phase !== 'beforeModel') return
49 if (ctx.parentRunId) return
50 if (ctx.iteration !== 0) return
51 return {
52 interrupts: [
53 reviewPlan.interrupt({
54 key: 'initial-plan',
55 reason: 'review-required',
56 message: 'Review the proposed plan.',
57 payload: {
58 title: 'Release plan',
59 changes: ['Add search', 'Add tests'],
60 },
61 }),
62 ],
63 }
64 },
65}
66```
67
68### 3. Skip the pause on the continuation
69
70Keep the `ctx.parentRunId` guard from step 2. The continuation is a new
71`chat()` call, and every boundary hook runs again. If the hook returns the same
72request, the run pauses again. `ctx.parentRunId` is set only on a continuation,
73so the guard limits the pause to the original request.
74
75## How it works
76
77- The engine collects every request from every middleware at the same phase
78 into one interrupt batch.
79- That batch ends the current run with one `interrupt` outcome.
80- `onInterruptBoundary` can only pause. It cannot change config. To change
81 prompts, tools, or messages from the answer, see
82 [Apply Answers](./apply-answers).
83
84## Examples for each phase
85
86### `beforeModel`: get a choice first
87
88Ask for a plan, an audience, or a locale before the model writes:
89
90- "Which brand voice must this reply use?"
91- "Which ticket do I work on?"
92- "Is this request in scope for this agent?"
93
94### `afterModel`: review the draft
95
96The model wrote text, and a human must accept it before tools run:
97
98- Review an email draft before `sendEmail`.
99- Review a SQL query before `runQuery`.
100- Review a support reply before the user sees it.
101
102### `beforeTools`: gate the side effects
103
104The model asked for tools, and nothing has run yet:
105
106- Confirm a bulk delete.
107- Confirm a payment.
108- Confirm a deploy.
109
110This is close to [tool approval](./tool-approval). Use a generic interrupt in these cases:
111
112- The question is more than a yes or no on one tool.
113- You judge several tools as one batch.
114
115### `afterTools`: audit the results
116
117The tools ran, and a human must see the output before the model uses it:
118
119- A search returned customer PII. Ask if it can stay in context.
120- A code run made a diff. Ask if the next turn can apply it.
121- A lookup returned a low-confidence match. Ask which record to keep.
122
123## Try it
124
125The React chat example has a playground for all four phases.
126
1271. Start `examples/ts-react-chat`.
1282. Open `/generic-interrupts`.
1293. Pick a phase and resolve both cards.
130
131## Advanced
132
133### What `ctx` holds
134
135Every hook gets the same `ChatMiddlewareContext`. Its contents change from phase
136to phase.
137
138The fields that you use most:
139
140- `phase` and `iteration`.
141- `parentRunId`: set on a continuation.
142- `messages`: a read-only view.
143- `accumulatedContent`: the assistant text for this model turn.
144- `context`: your `chat({ context })` value.
145
146Other fields:
147
148- `systemPrompts`, `toolNames`, `hasTools`, `modelOptions`.
149- `model` and `provider`, fixed for this request.
150- `abort(reason)` and `defer(promise)`.
151
152A change to `ctx.messages` does not change the engine config.
153
154### `beforeModel`
155
156`onConfig` for this iteration has already run. Prompts, tools, messages, and
157`modelOptions` hold the values after that merge.
158
159- `accumulatedContent` is empty.
160- `messages` is the conversation so far.
161
162### `afterModel`
163
164The model stream is complete.
165
166- `accumulatedContent` has the assistant text for this turn.
167- `messages` does **not** include this turn yet.
168- The proposed tool calls are not on `ctx`, and they are not in `messages` yet.
169
170If you need tool names or arguments, use `beforeTools`. You can also watch
171`onChunk` during `modelStream`.
172
173### `beforeTools`
174
175The engine has added the assistant message with `toolCalls` to `messages`. The
176tools have not run. Read the proposed calls here, before any side effect.
177
178### `afterTools`
179
180The tools have run. Result messages with `role: 'tool'` are in `messages`, and
181`onToolPhaseComplete` has already run. Read the results here, before the next
182model turn.