@cloudflare/think 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/README.md +10 -17
  2. package/dist/{chat-sdk-Bb93yaZh.js → chat-sdk-D6cUghsQ.js} +33 -8
  3. package/dist/chat-sdk-D6cUghsQ.js.map +1 -0
  4. package/dist/cli/index.js +224 -55
  5. package/dist/cli/index.js.map +1 -1
  6. package/dist/{codegen-CuPdJRpV.js → codegen-DlA2QQuU.js} +6 -38
  7. package/dist/codegen-DlA2QQuU.js.map +1 -0
  8. package/dist/{config-D512sQYg.d.ts → config-CD7hqncK.d.ts} +5 -5
  9. package/dist/extensions/index.js +1 -1
  10. package/dist/framework/index.d.ts +17 -62
  11. package/dist/framework/index.js +3 -57
  12. package/dist/{think-i1Pkgb1R.d.ts → index-D_S5mETO.d.ts} +1587 -702
  13. package/dist/{manager-BPndMP_6.js → manager-CSk5htym.js} +7 -7
  14. package/dist/{manager-BPndMP_6.js.map → manager-CSk5htym.js.map} +1 -1
  15. package/dist/{manifest-CpB-xngB.d.ts → manifest-DK5HuGga.d.ts} +16 -18
  16. package/dist/messengers/index.d.ts +59 -55
  17. package/dist/messengers/index.js +2 -2
  18. package/dist/messengers/telegram.d.ts +4 -4
  19. package/dist/messengers/telegram.js +1 -1
  20. package/dist/react.d.ts +79 -0
  21. package/dist/react.js +28 -0
  22. package/dist/react.js.map +1 -0
  23. package/dist/server-entry.d.ts +1 -1
  24. package/dist/server-entry.js +1 -1
  25. package/dist/server-entry.js.map +1 -1
  26. package/dist/studio/assets/{angular-html-z-TUogET.js → angular-html-D27LthTc.js} +1 -1
  27. package/dist/studio/assets/{angular-ts-DMGuEVeg.js → angular-ts-DtNL2gQ7.js} +1 -1
  28. package/dist/studio/assets/{apl-KvrEROqd.js → apl-BgEcDqM0.js} +1 -1
  29. package/dist/studio/assets/{astro-Bm_woEti.js → astro-CstbRF9e.js} +1 -1
  30. package/dist/studio/assets/{blade-BdCF3r89.js → blade-CLG-7epG.js} +1 -1
  31. package/dist/studio/assets/{c-CDqDtkvZ.js → c-CssQqwxO.js} +1 -1
  32. package/dist/studio/assets/{cobol-CeFM1vZz.js → cobol-CjmzHCjg.js} +1 -1
  33. package/dist/studio/assets/{coffee-2ed6LBym.js → coffee-B_rqYPkp.js} +1 -1
  34. package/dist/studio/assets/{cpp-Dj3nX0J4.js → cpp-5YyZJlb7.js} +1 -1
  35. package/dist/studio/assets/{crystal-BsIYZMQ3.js → crystal-D7uKze0i.js} +1 -1
  36. package/dist/studio/assets/{css-B48fnuoH.js → css-k9oPgg7G.js} +1 -1
  37. package/dist/studio/assets/{edge-C7qt1aza.js → edge-CGgsSt0x.js} +1 -1
  38. package/dist/studio/assets/{elixir-CiTmwoQ3.js → elixir-BX_d5Evo.js} +1 -1
  39. package/dist/studio/assets/{elm-exDZ-PRY.js → elm-DENxDm5e.js} +1 -1
  40. package/dist/studio/assets/{erb-3fmfgt-Q.js → erb-DvYOup03.js} +1 -1
  41. package/dist/studio/assets/{git-rebase-75I-C7zW.js → git-rebase-BsAdTS5A.js} +1 -1
  42. package/dist/studio/assets/{glimmer-js-JjRzYRv8.js → glimmer-js-e0h98Z67.js} +1 -1
  43. package/dist/studio/assets/{glimmer-ts-DcC_g6bi.js → glimmer-ts-C9s5Kv8m.js} +1 -1
  44. package/dist/studio/assets/{glsl-CHo__hpu.js → glsl-CCiyeTRs.js} +1 -1
  45. package/dist/studio/assets/{graphql-J3cHpSdo.js → graphql-BRtHwsqk.js} +1 -1
  46. package/dist/studio/assets/{hack-or1FCnPg.js → hack-Dnt0QXHh.js} +1 -1
  47. package/dist/studio/assets/{haml-uv3vtlo6.js → haml-EXGmzuB1.js} +1 -1
  48. package/dist/studio/assets/{handlebars--xrOP0sp.js → handlebars-CzyBIDJE.js} +1 -1
  49. package/dist/studio/assets/{highlighted-body-OFNGDK62-D5UBAw6b.js → highlighted-body-OFNGDK62-CQUFKLNu.js} +1 -1
  50. package/dist/studio/assets/{html-CWnTqWKh.js → html-BAT8b_VM.js} +1 -1
  51. package/dist/studio/assets/{html-derivative-DWyLco-z.js → html-derivative-7tkS-r6F.js} +1 -1
  52. package/dist/studio/assets/{http-BGB8mLqf.js → http-Cgka02Qq.js} +1 -1
  53. package/dist/studio/assets/{hurl-BWdvIVUG.js → hurl-Cbkh8WEw.js} +1 -1
  54. package/dist/studio/assets/index-D6n8vpkp.js +390 -0
  55. package/dist/studio/assets/index-DkGWw6ES.css +2 -0
  56. package/dist/studio/assets/{java-BqyrPpKF.js → java-DrRKiUno.js} +1 -1
  57. package/dist/studio/assets/{javascript-D8Aej0xg.js → javascript-9LAnHOxD.js} +1 -1
  58. package/dist/studio/assets/{jinja-SIORrXov.js → jinja-CqRt4prs.js} +1 -1
  59. package/dist/studio/assets/{jison-B2T4v51n.js → jison-BX-IOQpJ.js} +1 -1
  60. package/dist/studio/assets/{json-BFdVRj9r.js → json-dOrE-En8.js} +1 -1
  61. package/dist/studio/assets/{jsx-w4r1xieS.js → jsx-BSTPfqWX.js} +1 -1
  62. package/dist/studio/assets/{julia-BFBtDmmM.js → julia-Dvz-BPmf.js} +1 -1
  63. package/dist/studio/assets/{just-CjAPsU_y.js → just-BHQm0Atq.js} +1 -1
  64. package/dist/studio/assets/{latex-CghDKqKz.js → latex-CxdhxuXv.js} +1 -1
  65. package/dist/studio/assets/{liquid-Cp9loVkE.js → liquid-D-hM-Q_F.js} +1 -1
  66. package/dist/studio/assets/{lua-HNnIDxnY.js → lua-5qtqjLHq.js} +1 -1
  67. package/dist/studio/assets/{marko-BXT10Apm.js → marko-5FJaM2co.js} +1 -1
  68. package/dist/studio/assets/{mdc-CaiOz4_A.js → mdc-BhYW7lCG.js} +1 -1
  69. package/dist/studio/assets/mermaid-GHXKKRXX-CWM2EB-u.js +1 -0
  70. package/dist/studio/assets/{nginx-DgYZ5SY9.js → nginx-rtAXrRye.js} +1 -1
  71. package/dist/studio/assets/{nim-CAMVX-MV.js → nim-DQSmaN9U.js} +1 -1
  72. package/dist/studio/assets/{perl-Dc6Wp7SD.js → perl-B54AdcaE.js} +1 -1
  73. package/dist/studio/assets/{php-DgLi8LNU.js → php-DpvTxCny.js} +1 -1
  74. package/dist/studio/assets/{pug-ZHFv4Vgd.js → pug-Cyffw0Ho.js} +1 -1
  75. package/dist/studio/assets/{qml-DU62cSZp.js → qml-CxRetSkO.js} +1 -1
  76. package/dist/studio/assets/{r-BwU69RSh.js → r-CXWRxrXc.js} +1 -1
  77. package/dist/studio/assets/{razor-BUgi_XZM.js → razor-BJzI-zc9.js} +1 -1
  78. package/dist/studio/assets/{regexp-DuNhqfkW.js → regexp-dqxdfrnE.js} +1 -1
  79. package/dist/studio/assets/{rst-BB3BeaSy.js → rst-BW7eKYj4.js} +1 -1
  80. package/dist/studio/assets/{ruby-T0tkEfUZ.js → ruby-D5Npyj8-.js} +1 -1
  81. package/dist/studio/assets/{sas-CMhZa3S0.js → sas-DZLppjul.js} +1 -1
  82. package/dist/studio/assets/{scss-DtXjZ3vZ.js → scss-CbqoxyAe.js} +1 -1
  83. package/dist/studio/assets/{shellscript-BESt-FLs.js → shellscript-CFHqBeXu.js} +1 -1
  84. package/dist/studio/assets/{shellsession-8irtvYxL.js → shellsession-CbZDA4Bf.js} +1 -1
  85. package/dist/studio/assets/{soy-CIvhOgLR.js → soy-PImjtV58.js} +1 -1
  86. package/dist/studio/assets/{sql-obAOXh1G.js → sql-DhGo8urW.js} +1 -1
  87. package/dist/studio/assets/{stata-D3OCK8xW.js → stata-CjHWbU2v.js} +1 -1
  88. package/dist/studio/assets/{surrealql-Dk_bguB0.js → surrealql-o8Qr4t56.js} +1 -1
  89. package/dist/studio/assets/{svelte-C0-KQt-t.js → svelte-DlSIyEV1.js} +1 -1
  90. package/dist/studio/assets/{templ-lg4nvF9H.js → templ-qizfwU1w.js} +1 -1
  91. package/dist/studio/assets/{tex-BNcQSX7R.js → tex-Ca7T661H.js} +1 -1
  92. package/dist/studio/assets/{ts-tags-AgW9jVv0.js → ts-tags-DUmjLkgl.js} +1 -1
  93. package/dist/studio/assets/{tsx-CL8XyR3d.js → tsx-CfwgIqHW.js} +1 -1
  94. package/dist/studio/assets/{twig-VkSbsH0Y.js → twig-D7NAYUBY.js} +1 -1
  95. package/dist/studio/assets/{typescript-BfD1znAG.js → typescript-Bbz9oX-P.js} +1 -1
  96. package/dist/studio/assets/{vue-html-w3sbjuft.js → vue-html-CcxTb_Jn.js} +1 -1
  97. package/dist/studio/assets/{vue-gv_2i8Vk.js → vue-vYpz06zQ.js} +1 -1
  98. package/dist/studio/assets/{vue-vine-C9sgcRlL.js → vue-vine-DW4RqCKF.js} +1 -1
  99. package/dist/studio/assets/{xml-nNPxMKnG.js → xml-R4LZ_u4f.js} +1 -1
  100. package/dist/studio/assets/{xsl-C7iHP36x.js → xsl-CS-xzp3L.js} +1 -1
  101. package/dist/studio/assets/{yaml-Cq3YaG6o.js → yaml-CqDWbYXd.js} +1 -1
  102. package/dist/studio/index.html +2 -2
  103. package/dist/think.d.ts +2 -2
  104. package/dist/think.js +8292 -2
  105. package/dist/think.js.map +1 -0
  106. package/dist/tools/extensions.js +1 -1
  107. package/dist/tools/workspace.js +2 -2
  108. package/dist/tools/workspace.js.map +1 -1
  109. package/dist/{types-codegen-B6c5KpYH.js → types-codegen-C-9yeFao.js} +9 -33
  110. package/dist/types-codegen-C-9yeFao.js.map +1 -0
  111. package/dist/vite.d.ts +5 -5
  112. package/dist/vite.js +1 -1
  113. package/dist/workflows.d.ts +1 -1
  114. package/docs/actions.md +297 -0
  115. package/docs/channels.md +185 -0
  116. package/docs/client-tools.md +233 -0
  117. package/docs/getting-started.md +314 -0
  118. package/docs/index.md +1272 -0
  119. package/docs/lifecycle-hooks.md +839 -0
  120. package/docs/messengers.md +197 -0
  121. package/docs/programmatic-submissions.md +206 -0
  122. package/docs/sub-agents.md +520 -0
  123. package/docs/tools.md +582 -0
  124. package/docs/workflows.md +217 -0
  125. package/package.json +46 -17
  126. package/dist/chat-sdk-Bb93yaZh.js.map +0 -1
  127. package/dist/codegen-CuPdJRpV.js.map +0 -1
  128. package/dist/framework/index.js.map +0 -1
  129. package/dist/studio/assets/index-Cbb3GlZY.js +0 -496
  130. package/dist/studio/assets/index-DN9_cL01.css +0 -2
  131. package/dist/studio/assets/mermaid-GHXKKRXX-I2ZcYo7k.js +0 -1
  132. package/dist/think-BYZXQ-vm.js +0 -6513
  133. package/dist/think-BYZXQ-vm.js.map +0 -1
  134. package/dist/types-codegen-B6c5KpYH.js.map +0 -1
@@ -0,0 +1,520 @@
1
+ # Sub-agents and Programmatic Turns
2
+
3
+ Think works as both a top-level agent (WebSocket to browser) and a sub-agent (RPC from a parent agent). It also supports programmatic turns — injecting messages and triggering model turns without a WebSocket connection.
4
+
5
+ This page focuses on Think's `chat()` RPC surface and programmatic turns. For the generic framework primitives underneath (`subAgent`, `onBeforeSubAgent`, `useAgent({ sub })`, `parentAgent`, `hasSubAgent`, `listSubAgents`, routing shape), see [Sub-agents](https://github.com/cloudflare/agents/blob/main/docs/agents/sub-agents.md).
6
+
7
+ For a quick comparison of `chat()`, `saveMessages()`, `submitMessages()`, and
8
+ agent tools, see [Choosing a turn API](./index.md#choosing-a-turn-api).
9
+
10
+ ## Sub-agent via chat()
11
+
12
+ When used as a sub-agent, the `chat()` method runs a full turn (persist user message, run agentic loop, persist assistant response) and streams events via a callback.
13
+
14
+ ```typescript
15
+ async chat(
16
+ userMessage: string | UIMessage,
17
+ callback: StreamCallback,
18
+ options?: ChatOptions
19
+ ): Promise<void>
20
+ ```
21
+
22
+ ### StreamCallback
23
+
24
+ ```typescript
25
+ interface StreamCallback {
26
+ onStart(event: { requestId: string }): void | Promise<void>;
27
+ onEvent(json: string): void | Promise<void>;
28
+ onDone(): void | Promise<void>;
29
+ onError(error: string): void | Promise<void>;
30
+ }
31
+ ```
32
+
33
+ | Method | When it fires |
34
+ | ---------------- | --------------------------------------------------------------- |
35
+ | `onStart(event)` | Before work starts; exposes the request id for cancellation |
36
+ | `onEvent(json)` | For each streaming chunk (JSON-serialized UIMessageChunk) |
37
+ | `onDone()` | After the turn completes and the assistant message is persisted |
38
+ | `onError(error)` | On error during the turn |
39
+
40
+ ### ChatOptions
41
+
42
+ ```typescript
43
+ interface ChatOptions {
44
+ signal?: AbortSignal;
45
+ }
46
+ ```
47
+
48
+ | Field | Description |
49
+ | -------- | ------------------------------------------- |
50
+ | `signal` | `AbortSignal` to cancel the turn mid-stream |
51
+
52
+ Tools belong to the child agent. Define durable capabilities with the child's `getTools()`, extensions, MCP tools, or client tool schemas. Legacy callers that pass `options.tools` to `chat()` get a warning and the value is ignored.
53
+
54
+ ### Example: Parent agent calling a child
55
+
56
+ ```typescript
57
+ import { Think, Session } from "@cloudflare/think";
58
+ import type { StreamCallback } from "@cloudflare/think";
59
+
60
+ export class ParentAgent extends Think<Env> {
61
+ getModel() {
62
+ /* ... */
63
+ }
64
+
65
+ async delegateToChild(task: string) {
66
+ const child = await this.subAgent(ChildAgent, "child-1");
67
+
68
+ const chunks: string[] = [];
69
+ await child.chat(task, {
70
+ onStart: (event) => {
71
+ console.log("Child started:", event.requestId);
72
+ },
73
+ onEvent: (json) => {
74
+ chunks.push(json);
75
+ // Optionally forward to a connected client
76
+ },
77
+ onDone: () => {
78
+ console.log("Child completed");
79
+ },
80
+ onError: (error) => {
81
+ console.error("Child failed:", error);
82
+ }
83
+ });
84
+
85
+ return chunks;
86
+ }
87
+ }
88
+
89
+ export class ChildAgent extends Think<Env> {
90
+ getModel() {
91
+ /* ... */
92
+ }
93
+
94
+ getSystemPrompt() {
95
+ return "You are a research assistant. Analyze data and report findings.";
96
+ }
97
+ }
98
+ ```
99
+
100
+ ### Passing a string vs UIMessage
101
+
102
+ `chat()` accepts either a plain string or a `UIMessage`. A string is auto-wrapped:
103
+
104
+ ```typescript
105
+ // These are equivalent:
106
+ await child.chat("Analyze this data", callback);
107
+ await child.chat(
108
+ {
109
+ id: crypto.randomUUID(),
110
+ role: "user",
111
+ parts: [{ type: "text", text: "Analyze this data" }]
112
+ },
113
+ callback
114
+ );
115
+ ```
116
+
117
+ ### Cancelling a sub-agent turn
118
+
119
+ Use `onStart` and `cancelChat()` for RPC-safe cancellation across a
120
+ sub-agent boundary:
121
+
122
+ ```typescript
123
+ let requestId: string | undefined;
124
+
125
+ const callback: StreamCallback = {
126
+ onStart(event) {
127
+ requestId = event.requestId;
128
+ },
129
+ onEvent(json) {
130
+ // Forward stream chunks.
131
+ },
132
+ onDone() {},
133
+ onError(error) {
134
+ console.error(error);
135
+ }
136
+ };
137
+
138
+ const turn = child.chat("Long analysis task", callback);
139
+
140
+ // Later, from another RPC call or failure handler:
141
+ if (requestId) {
142
+ await child.cancelChat(requestId, "client disconnected");
143
+ }
144
+
145
+ await turn;
146
+ ```
147
+
148
+ If the caller and callee are not separated by Workers RPC, you can also pass an
149
+ `AbortSignal` to cancel mid-stream:
150
+
151
+ ```typescript
152
+ const controller = new AbortController();
153
+
154
+ setTimeout(() => controller.abort(), 30_000);
155
+
156
+ await child.chat("Long analysis task", callback, {
157
+ signal: controller.signal
158
+ });
159
+ ```
160
+
161
+ When aborted, the partial assistant message is still persisted.
162
+
163
+ ---
164
+
165
+ ## Programmatic Turns with saveMessages
166
+
167
+ `saveMessages` injects messages and triggers a model turn without a WebSocket connection. Use for scheduled responses, webhook-triggered turns, proactive agents, or chaining from `onChatResponse`.
168
+
169
+ ```typescript
170
+ async saveMessages(
171
+ messages: UIMessage[] | ((current: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>),
172
+ options?: SaveMessagesOptions
173
+ ): Promise<SaveMessagesResult>
174
+ ```
175
+
176
+ Returns `{ requestId, status, error? }` where `status` is `"completed"`, `"error"`, `"skipped"`, or `"aborted"`.
177
+
178
+ | `status` | When |
179
+ | ------------- | ------------------------------------------------------------------------------------------------------------------------- |
180
+ | `"completed"` | Turn ran to completion. |
181
+ | `"error"` | Turn started but the stream reported an error. `error` contains the stream error message when available. |
182
+ | `"skipped"` | Turn invalidated mid-flight (e.g. by `chat-clear`); user message persisted, no model run. |
183
+ | `"aborted"` | Turn cancelled before completion via `options.signal` or `chat-request-cancel`. Partial assistant chunks still persisted. |
184
+
185
+ ### Static messages
186
+
187
+ ```typescript
188
+ await this.saveMessages([
189
+ {
190
+ id: crypto.randomUUID(),
191
+ role: "user",
192
+ parts: [{ type: "text", text: "Time for your daily summary." }]
193
+ }
194
+ ]);
195
+ ```
196
+
197
+ ### Function form
198
+
199
+ When multiple `saveMessages` calls queue up, the function form runs with the latest messages when the turn actually starts:
200
+
201
+ ```typescript
202
+ await this.saveMessages((current) => [
203
+ ...current,
204
+ {
205
+ id: crypto.randomUUID(),
206
+ role: "user",
207
+ parts: [{ type: "text", text: "Continue your analysis." }]
208
+ }
209
+ ]);
210
+ ```
211
+
212
+ ### Scheduled responses
213
+
214
+ Trigger a recurring prompt turn with `getScheduledTasks()`:
215
+
216
+ ```typescript
217
+ export class MyAgent extends Think<Env> {
218
+ getModel() {
219
+ /* ... */
220
+ }
221
+
222
+ getScheduledTasks() {
223
+ return {
224
+ dailyReport: {
225
+ schedule: "every day at 09:00",
226
+ timezone: "UTC",
227
+ prompt: "Generate the daily report."
228
+ }
229
+ };
230
+ }
231
+ }
232
+ ```
233
+
234
+ ### Chaining from onChatResponse
235
+
236
+ Start a follow-up turn after the current one completes:
237
+
238
+ ```typescript
239
+ async onChatResponse(result: ChatResponseResult) {
240
+ if (result.status === "completed" && this.needsFollowUp(result.message)) {
241
+ await this.saveMessages([{
242
+ id: crypto.randomUUID(),
243
+ role: "user",
244
+ parts: [{ type: "text", text: "Now summarize what you found." }]
245
+ }]);
246
+ }
247
+ }
248
+ ```
249
+
250
+ ### External cancellation with `options.signal`
251
+
252
+ `saveMessages` accepts an `AbortSignal` so callers can cancel the turn from outside without knowing the internally-generated request id. The signal is linked to Think's per-turn `AbortController`; when it aborts:
253
+
254
+ - the inference loop's signal aborts (the same path `chat-request-cancel` takes);
255
+ - partial chunks already streamed are persisted to the resumable stream;
256
+ - `saveMessages` resolves with `{ status: "aborted" }`;
257
+ - `onChatResponse` fires with `status: "aborted"`.
258
+
259
+ If the signal is **already aborted** when `saveMessages` is called, no inference work runs.
260
+
261
+ ```typescript
262
+ class MyAgent extends Think<Env> {
263
+ async runWithTimeout(text: string) {
264
+ const controller = new AbortController();
265
+ setTimeout(() => controller.abort(), 30_000);
266
+
267
+ const { status } = await this.saveMessages(
268
+ [
269
+ {
270
+ id: crypto.randomUUID(),
271
+ role: "user",
272
+ parts: [{ type: "text", text }]
273
+ }
274
+ ],
275
+ { signal: controller.signal }
276
+ );
277
+
278
+ if (status === "aborted") {
279
+ console.log("Turn cancelled by external signal");
280
+ }
281
+ }
282
+ }
283
+ ```
284
+
285
+ #### Crossing DO boundaries
286
+
287
+ `AbortSignal` cannot be passed as an RPC argument across Durable Object boundaries — workerd's JSRPC layer rejects it at serialization time. Construct the controller **inside** the DO that calls `saveMessages` and bridge the parent's intent through a serializable mechanism.
288
+
289
+ For agent orchestration, prefer [Agent Tools](https://github.com/cloudflare/agents/blob/main/docs/agents/agent-tools.md). `runAgentTool()`
290
+ and `agentTool()` handle the parent abort signal, child-local `saveMessages({
291
+ signal })`, event forwarding, replay, and cleanup for Think and `AIChatAgent`
292
+ child agents.
293
+
294
+ For lower-level custom RPC patterns, return a `ReadableStream` from the child and
295
+ let the parent cancel its reader. workerd propagates that cancellation back to
296
+ the source stream's `cancel` callback, where the child can abort its local
297
+ controller.
298
+
299
+ #### Hibernation and recovery
300
+
301
+ Think chat recovery works in sub-agents. The underlying fiber is stored in the sub-agent's own SQLite database, and the top-level parent keeps a small index of active child fibers. When the parent alarm fires, it routes recovery checks into the owning sub-agent, so recovery runs with the sub-agent as `this` even if the child is otherwise idle. Recovered continuations can call `schedule()` inside the sub-agent — the top-level parent owns the physical alarm and routes the continuation back into the child.
302
+
303
+ The external signal lives in memory only. If the Durable Object hibernates mid-turn and `chatRecovery` is enabled, the recovered turn runs via `continueLastTurn()` **without** the original `options.signal` — the listener was lost on eviction, and the recovery path has no way to reach back to the original caller.
304
+
305
+ In practice this means:
306
+
307
+ - A signal that aborts **after** the DO restarts has no effect on the recovered turn.
308
+ - Subclasses that need the recovered turn to honor a fresh signal should override `onChatRecovery` and reject continuation (`return { continue: false }`) when the original caller is gone.
309
+ - Recovery is best for long-lived chat sub-agents that have their own client reconnect path. Agent tools define a parent-side replay and terminal-state policy for cases where the original parent forwarding loop is gone.
310
+ - If the parent restarts mid-agent-tool run, stored child chunks can replay, but the parent marks the run `interrupted` unless a future live-tail policy reattaches to recovered work.
311
+
312
+ See [`cloudflare/agents#1406`](https://github.com/cloudflare/agents/issues/1406) for the original motivation, and [Agent Tools](https://github.com/cloudflare/agents/blob/main/docs/agents/agent-tools.md) for the shipped orchestration API.
313
+
314
+ ---
315
+
316
+ ## continueLastTurn
317
+
318
+ Resume the last assistant turn without injecting a new user message. Useful after tool results are received or after recovery from an interruption.
319
+
320
+ ```typescript
321
+ protected async continueLastTurn(
322
+ body?: Record<string, unknown>,
323
+ options?: SaveMessagesOptions
324
+ ): Promise<SaveMessagesResult>
325
+ ```
326
+
327
+ Returns `{ requestId, status: "skipped" }` if the last message is not an assistant message.
328
+
329
+ Most applications do not call this directly. Treat `continueLastTurn()` as an
330
+ advanced subclass and recovery primitive; user-facing, server-triggered turns
331
+ usually use `saveMessages()` or `submitMessages()` instead.
332
+
333
+ The optional `body` parameter overrides the stored body for this continuation. If omitted, the last body from the previous turn is used. The optional `options.signal` accepts an external `AbortSignal` for cancellation, matching the `saveMessages` contract.
334
+
335
+ ---
336
+
337
+ ## Aborting in-flight turns
338
+
339
+ For callers that don't have access to the `requestId` but need a coarse "cancel whatever is running" handle (e.g. an RPC-driven sub-agent helper that runs one turn at a time), Think exposes two protected methods:
340
+
341
+ ```typescript
342
+ protected abortRequest(requestId: string, reason?: unknown): void
343
+ protected abortAllRequests(): void
344
+ ```
345
+
346
+ - **`abortRequest(id, reason?)`** — abort a specific in-flight turn by id. No-op if no controller exists for that id. Equivalent to a client `chat-request-cancel`.
347
+ - **`abortAllRequests()`** — abort every in-flight controller in the registry. Used by single-purpose sub-agents that don't track ids.
348
+
349
+ Both methods produce the same end state as `chat-request-cancel`: inference loop terminates, partial chunks persist, the turn's `ChatResponseResult` reports `status: "aborted"`. Prefer `options.signal` on `saveMessages` / `continueLastTurn` when driving a turn programmatically — it threads the abort intent in from turn start without requiring the caller to know the id.
350
+
351
+ ---
352
+
353
+ ## Chat Recovery
354
+
355
+ Think can wrap chat turns in Durable Object fibers for durable execution. When a DO is evicted mid-turn, the turn can be recovered on restart. This works for top-level agents and sub-agents; for sub-agents, the top-level parent alarm drives recovery checks back into the child facet.
356
+
357
+ ### Setup
358
+
359
+ ```typescript
360
+ export class MyAgent extends Think<Env> {
361
+ chatRecovery = true;
362
+
363
+ getModel() {
364
+ /* ... */
365
+ }
366
+ }
367
+ ```
368
+
369
+ When `chatRecovery` is `true`, every turn entry path is wrapped in `runFiber`: WebSocket chat, sub-agent `chat()` RPC, auto-continuation, `saveMessages()`, `submitMessages()` execution, and `continueLastTurn()`.
370
+
371
+ ### onChatRecovery
372
+
373
+ When an interrupted chat fiber is detected after DO restart, Think calls the `onChatRecovery` hook:
374
+
375
+ ```typescript
376
+ onChatRecovery(ctx: ChatRecoveryContext): ChatRecoveryOptions | void
377
+ ```
378
+
379
+ ### ChatRecoveryContext
380
+
381
+ | Field | Type | Description |
382
+ | ----------------- | -------------------------- | -------------------------------------------------------------------------------------- |
383
+ | `incidentId` | `string` | Stable ID for this recovery incident |
384
+ | `attempt` | `number` | Current attempt number for this incident, starting at 1 |
385
+ | `maxAttempts` | `number` | Configured attempt cap before terminal exhaustion |
386
+ | `recoveryKind` | `"retry" \| "continue"` | Whether recovery retries an unanswered user turn or continues a partial assistant turn |
387
+ | `streamId` | `string` | The stream ID of the interrupted turn |
388
+ | `requestId` | `string` | The request ID of the interrupted turn |
389
+ | `partialText` | `string` | Text generated before the interruption |
390
+ | `partialParts` | `MessagePart[]` | Parts accumulated before the interruption |
391
+ | `recoveryData` | `unknown \| null` | Data from `this.stash()` during the turn |
392
+ | `messages` | `UIMessage[]` | Current conversation history |
393
+ | `lastBody` | `Record<string, unknown>?` | Body from the interrupted turn |
394
+ | `lastClientTools` | `ClientToolSchema[]?` | Client tools from the interrupted turn |
395
+ | `createdAt` | `number` | Epoch milliseconds when the underlying fiber started |
396
+
397
+ ### ChatRecoveryOptions
398
+
399
+ | Field | Type | Description |
400
+ | ---------- | ---------- | ----------------------------------------------------------------- |
401
+ | `persist` | `boolean?` | Whether to persist the partial assistant message |
402
+ | `continue` | `boolean?` | Whether to auto-continue with a new turn via `continueLastTurn()` |
403
+
404
+ ### Example
405
+
406
+ ```typescript
407
+ export class MyAgent extends Think<Env> {
408
+ chatRecovery = true;
409
+
410
+ getModel() {
411
+ /* ... */
412
+ }
413
+
414
+ onChatRecovery(ctx: ChatRecoveryContext) {
415
+ console.log(
416
+ `Recovering turn ${ctx.requestId}, partial: ${ctx.partialText.length} chars`
417
+ );
418
+ return {
419
+ persist: true,
420
+ continue: true
421
+ };
422
+ }
423
+ }
424
+ ```
425
+
426
+ With `persist: true`, the partial message is saved. With `continue: true`, Think calls `continueLastTurn()` after the agent reaches a stable state.
427
+
428
+ For pre-stream interruptions, where `ctx.streamId === ""` and `ctx.partialText === ""` but the latest persisted message is still the unanswered user message, Think retries that turn automatically unless `continue` is `false`.
429
+
430
+ ```typescript
431
+ onChatRecovery(ctx: ChatRecoveryContext): ChatRecoveryOptions {
432
+ if (!ctx.streamId && !ctx.partialText) {
433
+ console.log("Recovering a pre-stream interruption");
434
+ }
435
+ return {};
436
+ }
437
+ ```
438
+
439
+ To suppress continuation for turns that have been orphaned too long to safely replay, gate on `ctx.createdAt`:
440
+
441
+ ```typescript
442
+ onChatRecovery(ctx: ChatRecoveryContext): ChatRecoveryOptions {
443
+ if (Date.now() - ctx.createdAt > 2 * 60 * 1000) {
444
+ return { continue: false };
445
+ }
446
+ return {};
447
+ }
448
+ ```
449
+
450
+ ### Recovery budgets and limits
451
+
452
+ Instead of `chatRecovery = true`, assign an object to tune how long recovery is allowed to run and when it is given up on. A turn that keeps making forward progress is never terminated by the framework on its own — duration is not a bound. Recovery is only sealed by one of the limits below.
453
+
454
+ ```typescript
455
+ export class MyAgent extends Think<Env> {
456
+ chatRecovery = {
457
+ maxAttempts: 10,
458
+ noProgressTimeoutMs: 5 * 60 * 1000,
459
+ maxRecoveryWork: Infinity,
460
+ terminalMessage: "The assistant was interrupted and could not recover.",
461
+ // Consulted from the second recovery attempt onward. Return false to stop.
462
+ // Called as `config.shouldKeepRecovering(ctx)`, so it is NOT bound to the
463
+ // agent instance — track real token/cost spend in your own store keyed by
464
+ // `ctx.recoveryRootRequestId`.
465
+ async shouldKeepRecovering(ctx) {
466
+ return (await getSpendForTurn(ctx.recoveryRootRequestId)) < MAX_SPEND;
467
+ },
468
+ async onExhausted(ctx) {
469
+ console.warn("Recovery exhausted", ctx.incidentId, ctx.reason);
470
+ }
471
+ };
472
+ }
473
+ ```
474
+
475
+ | Field | Default | Description |
476
+ | ---------------------- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
477
+ | `maxAttempts` | `10` | Attempt cap. Resets on forward progress, so it catches a tight no-progress alarm loop, not a healthy long turn. |
478
+ | `stableTimeoutMs` | `10_000` | How long an attempt waits for the isolate to reach stable state before rescheduling. |
479
+ | `noProgressTimeoutMs` | `300_000` (5 min) | Primary stuck-turn bound: max time without forward progress before sealing. **Resets on every progress-bearing attempt.** |
480
+ | `maxRecoveryWork` | `Infinity` | Runaway-loop guard: max produced content/tool units since the incident opened before a still-progressing turn is sealed. No cap by default. |
481
+ | `shouldKeepRecovering` | — | Caller policy consulted from the second attempt onward. Return `false` to stop recovery. The hook point for a token/cost budget (`ctx.work` is a coarse segment count, not tokens). |
482
+ | `terminalMessage` | generic message | Message shown to the user when recovery is given up on. |
483
+ | `onExhausted` | — | Called once when recovery is given up on. Inspect `ctx.reason`. |
484
+
485
+ `ctx.reason` on the exhausted hook is one of: `no_progress_timeout` (stuck), `max_attempts_exceeded` (no-progress alarm loop), `work_budget_exceeded` (runaway), `recovery_aborted` (your `shouldKeepRecovering` returned `false`), or `stable_timeout` (extreme churn). See [`chat-agents.md`](https://github.com/cloudflare/agents/blob/main/docs/agents/chat-agents.md#stream-recovery) for the full shared reference — Think and `@cloudflare/ai-chat` use the same recovery configuration.
486
+
487
+ ---
488
+
489
+ ## Stability Detection
490
+
491
+ Think provides methods to check if the agent is in a stable state — no pending tool results, no pending approvals, no active turns.
492
+
493
+ ### hasPendingInteraction
494
+
495
+ ```typescript
496
+ protected hasPendingInteraction(): boolean
497
+ ```
498
+
499
+ Returns `true` if any assistant message has pending tool calls (tools without results or pending approvals).
500
+
501
+ ### waitUntilStable
502
+
503
+ ```typescript
504
+ protected async waitUntilStable(options?: { timeout?: number }): Promise<boolean>
505
+ ```
506
+
507
+ Returns a promise that resolves to `true` when the agent reaches a stable state, or `false` if the timeout is exceeded.
508
+
509
+ ```typescript
510
+ const stable = await this.waitUntilStable({ timeout: 30_000 });
511
+ if (stable) {
512
+ await this.saveMessages([
513
+ {
514
+ id: crypto.randomUUID(),
515
+ role: "user",
516
+ parts: [{ type: "text", text: "Now that you are done, summarize." }]
517
+ }
518
+ ]);
519
+ }
520
+ ```