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

overview.md

251 lines9.4 KB

1---
2title: Overview
3id: interrupts-overview
4order: 1
5description: "Pause an agent run for a human or application decision, then continue it exactly where it stopped."
6keywords:
7 - tanstack ai
8 - ag-ui interrupts
9 - human in the loop
10 - tool approval
11 - resolveInterrupt
12---
13​
14Most agent runs are fire and forget. The model calls tools, they run, you get an
15answer back. But some steps must not happen on their own: moving money,
16deleting a project, sending an email. And sometimes the agent needs an answer
17only the user can give before it can go on.
18​
19An interrupt is a pause. The run stops, hands you a decision to make, and then
20picks up exactly where it left off once you answer.
21​
22## How it works
23​
241. The server reaches a step that needs a decision and ends the run with an
25 `interrupt` outcome instead of a final answer.
262. The client gives you the pending decisions as `interrupts`.
273. You resolve each one (approve, reject, submit a value, or cancel).
284. The client starts a fresh continuation run that carries your answers and
29 continues the agent.
30​
31```mermaid
32sequenceDiagram
33 participant User
34 participant Client
35 participant Server
36​
37 Client->>Server: send message, run starts
38 Server-->>Client: interrupt outcome, run ends without a final answer
39 Client->>User: pending decisions surface as `interrupts`
40 User->>Client: approve / reject / submit a value
41 Client->>Server: continuation request with the answers, a fresh run
42 Server-->>Client: the agent picks up where it paused, final answer
43```
44​
45Note that the pause spans **two runs**: the interrupted one ends, and the
46continuation is a new run. One user-visible turn, two run lifecycles. See
47[Threads and runs](../chat/stream-events#threads-and-runs).
48​
49When replaying saved events, the client follows `parentRunId` links to avoid
50showing a resolved pause again. A continuation that ends without an interrupt
51clears its ancestor's pending decisions, even if the parent link arrives later.
52Intermediate `tool_calls` events do not mark the run or its ancestors as answered.
53​
54No database is required. The browser sends the full message history back on the
55continuation request, so a stateless server can rebuild the paused step and keep
56going.
57​
58## What pauses a run
59​
60Two kinds of interrupt show up in the `interrupts` array for you to resolve:
61​
62| `kind` | You get a pause when | Guide |
63| --- | --- | --- |
64| `tool-approval` | A tool is marked `needsApproval` and the model calls it | [Tool Approval](./tool-approval) |
65| `generic` | Middleware requests typed client data at a lifecycle boundary | [Generic Interrupts](./generic) |
66​
67An MCP server can also ask for input during a tool call. The run ends with an interrupt. The page is [MCP client input](../tools/mcp-input).
68​
69## First-party generic interrupts
70​
71For a generic interrupt that TanStack AI owns, define it once with
72`defineInterrupt()`. Register the definition with both `chat({ interrupts })`
73and `useChat({ interrupts })`. Middleware emits it through
74`onInterruptBoundary`, and the client receives a typed bound item that it can
75resolve or cancel. See [Generic Interrupts](./generic). To pick a phase, see
76[Lifecycle Boundaries](./boundaries). To apply the answer, see
77[Apply Answers](./apply-answers).
78​
79## External generic interrupts
80​
81An interrupt is a standard AG-UI object, and TanStack AI is not the only thing
82that can put one on a stream. A workflow engine pausing for a durable approval,
83or another agent framework sharing the same connection, emits the same envelope.
84​
85There are three cases:
86​
87- A registered first-party generic interrupt has `kind: 'generic'`, a literal
88 `definitionId`, typed `payload`, and a typed `resolveInterrupt` method.
89- An external generic interrupt with a valid binding also has `kind: 'generic'`.
90 Its response is `unknown`, but it has `resolveInterrupt`, `cancel`, and
91 `clearResolution`. It joins the root batch controls.
92- An interrupt with a missing, malformed, or unsupported binding has
93 `kind: 'unbound'`. It remains visible, but has no controls.
94​
95The binding is stored in the interrupt metadata under
96`INTERRUPT_BINDING_METADATA_KEY`. It records the interrupted run and generation.
97The client uses it to send the answer to the matching paused step.
98​
99Render unbound items as status information. Do not render a response form for
100them:
101​
102```tsx
103import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
104import { toolDefinition } from '@tanstack/ai'
105import { z } from 'zod'
106​
107const transferTool = toolDefinition({
108 name: 'transfer',
109 description: 'Move money between accounts',
110 needsApproval: true,
111 inputSchema: z.object({ recipient: z.string(), amount: z.number() }),
112 outputSchema: z.object({ receiptId: z.string() }),
113}).client()
114​
115export function Pauses() {
116 const { interrupts } = useChat({
117 threadId: 'thread-1',
118 connection: fetchServerSentEvents('/api/chat'),
119 tools: [transferTool] as const,
120 })
121​
122 return (
123 <>
124 {interrupts.map((interrupt) => {
125 if (interrupt.kind === 'unbound') {
126 return (
127 <p key={interrupt.id}>
128 External pause: {interrupt.message ?? interrupt.reason}
129 </p>
130 )
131 }
132 if (interrupt.kind === 'generic') {
133 return (
134 <article key={interrupt.id}>
135 <p>{interrupt.message ?? interrupt.reason}</p>
136 <button
137 onClick={() =>
138 interrupt.resolveInterrupt({ speed: 'express' })
139 }
140 >
141 Choose express
142 </button>
143 <button onClick={() => interrupt.cancel()}>Cancel</button>
144 <button onClick={() => interrupt.clearResolution()}>
145 Clear choice
146 </button>
147 </article>
148 )
149 }
150 return (
151 <button
152 key={interrupt.id}
153 onClick={() => interrupt.resolveInterrupt(true)}
154 >
155 Approve {interrupt.toolName}
156 </button>
157 )
158 })}
159 </>
160 )
162```
163​
164The library will not invent a binding to make these resolvable. Doing so would
165render a form whose answer is sent to a run that has nothing pending. The
166submit would fail only after the user has filled it in. `unbound` says that
167the pause belongs to something else. Unbound items never block you from
168resolving the ones that are yours.
169​
170If an external producer wants the chat client to resume its pause, attach a
171valid binding with `withInterruptBinding`. Do not write the metadata key by
172hand. Use the exact interrupted run id and generation that own the pause:
173​
174```ts
175import {
176 INTERRUPT_BINDING_VERSION,
177 canonicalInterruptJson,
178 digestInterruptJson,
179 withInterruptBinding,
180} from '@tanstack/ai'
181​
182const responseSchema = {
183 type: 'object',
184 properties: { speed: { type: 'string' } },
185 required: ['speed'],
187​
188const descriptor = withInterruptBinding(
189 {
190 id: 'shipping-1',
191 reason: 'confirmation',
192 message: 'Which shipping speed?',
193 responseSchema,
194 },
195 {
196 v: INTERRUPT_BINDING_VERSION,
197 kind: 'generic',
198 interruptId: 'shipping-1',
199 interruptedRunId: 'run-42',
200 generation: 0,
201 // The server checks the schema it hands out still matches the one it
202 // validates against, so the hash is computed from the schema itself.
203 responseSchemaHash: digestInterruptJson(
204 canonicalInterruptJson(responseSchema),
205 ),
206 },
208```
209​
210The client treats this as an untyped generic interrupt. The example above can
211stage a value, cancel it, or clear the draft. It can also join
212`resolveInterrupts(...)` with tool approvals and first-party generic interrupts.
213​
214`v` is the binding wire version. The client rejects unknown versions and bad
215fields. Those interrupts become `unbound` rather than a form that cannot
216resume the owner.
217​
218## What about client tools?
219​
220A tool with a `.client()` implementation runs in the browser on its own and
221reports its own result. That is not a decision you make, so it never appears in
222`interrupts`. See [Client Tools](../tools/client-tools).
223​
224If persistence restores a pending client-tool execution, the client leaves it
225pending rather than running the browser code again. See
226[Client persistence](../persistence/client-persistence#handle-restored-client-tools)
227for recovery policies.
228​
229The one time a tool pauses is when you mark it `needsApproval: true`. Then it
230stops for a yes or no first, whether it runs on the server or in the browser:
231​
232| Tool | What you handle |
233| --- | --- |
234| Server tool | Nothing, unless `needsApproval` adds a `tool-approval` pause. It then runs on the server after you approve. |
235| Client tool | Nothing, it runs in the browser automatically. With `needsApproval` it pauses for approval first, then runs in the browser. |
236​
237So approval is the only thing you resolve for either kind of tool, and both use
238the same `tool-approval` interrupt.
239​
240## Where to go next
241​
242| You want to | Page |
243| --- | --- |
244| Approve or reject a single tool call | [Tool Approval](./tool-approval) |
245| Resolve several pending decisions at once | [Multiple Interrupts](./multiple) |
246| Ask the user something that isn't a tool | [Generic Interrupts](./generic) |
247| Read an MCP input request | [MCP client input](../tools/mcp-input) |
248| Pick `beforeModel`, `afterModel`, `beforeTools`, or `afterTools` | [Lifecycle Boundaries](./boundaries) |
249| Apply a generic answer to prompts or stop the run | [Apply Answers](./apply-answers) |
250| Run a tool in the browser | [Client Tools](../tools/client-tools) |
251| Move off the old `approval-requested` events | [Migration](./migration) |