@cloudflare/think 0.19.0 → 0.20.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.
@@ -1,4 +1,4 @@
1
- import { _n as ThinkSubmissionStatus, cn as Think } from "./index-BLkPlEbF.js";
1
+ import { hn as Think, wn as ThinkSubmissionStatus } from "./index-DwPAhQRQ.js";
2
2
  import { ZodObject, z } from "zod";
3
3
  import { WorkflowEvent, WorkflowSleepDuration } from "cloudflare:workers";
4
4
  import {
package/docs/actions.md CHANGED
@@ -175,11 +175,36 @@ await agent.rejectExecution(executionId, "Not this release");
175
175
  ```
176
176
 
177
177
  `approveExecution()` runs `execute` once and auto-continues the turn even if no
178
- client is connected; `rejectExecution()` resolves the action without running it.
178
+ client is connected; `rejectExecution()` resolves the action without running it
179
+ and, by default, continues the turn so the model can adapt. Pass
180
+ `{ autoContinue: false }` when the user wants the agent to stop and wait for a
181
+ new instruction instead:
182
+
183
+ ```typescript
184
+ await agent.rejectExecution(executionId, "Stop here", { autoContinue: false });
185
+ ```
186
+
187
+ The rejection is still recorded in the transcript, so the next user message
188
+ continues the conversation with it in view.
179
189
  `pendingApprovals()` merges parked actions and paused Codemode executions, so a
180
190
  single approval UI can drive both. (`durable-pause` requires an `approval`
181
191
  policy — an action that would never park is rejected at definition time.)
182
192
 
193
+ After an action parks, the model can still write a reply in the same turn, such
194
+ as "Once approved, the deploy will start." That text describes the pending
195
+ state, so it is wrong once the execution resolves. When you approve or reject,
196
+ Think replaces the paused output with the outcome and removes the text and
197
+ reasoning parts that follow it in that assistant message. Earlier content and
198
+ later tool and file parts are kept. The continuation then reads a transcript
199
+ that ends with the real outcome. If the outcome arrives while the parking turn
200
+ is still streaming, the removal waits until that turn is saved and runs before
201
+ the next model call, whether that is the continuation or a new user turn. The
202
+ outcome is saved in Durable Object storage before the transcript is updated, so
203
+ if the agent restarts before either write lands, both the outcome and the
204
+ removal are applied before the next model call. A client that resubmits an
205
+ older copy of the message, still showing the paused output, does not restore
206
+ the paused output or the removed text.
207
+
183
208
  Both approval-gated and durable-pause parts carry a stable
184
209
  `ActionApprovalDescriptor` (`{ requestId, toolCallId, action, summary, input,
185
210
  permissions, risk, kind }`) so your UI has everything it needs to render the
@@ -279,16 +304,16 @@ into a channel notice.
279
304
 
280
305
  ### Hooks and methods on the agent
281
306
 
282
- | Member | Description |
283
- | --------------------------------------- | ---------------------------------------------------------------------------------- |
284
- | `getActions()` | Return the action descriptors to compile into tools. |
285
- | `authorizeTurn(ctx)` | Decide granted permissions once per turn. Defaults to full grant. |
286
- | `authorizeAction(ctx)` | Decide authorization per action call. Defaults to checking `authorizeTurn` grants. |
287
- | `pendingApprovals(executionId?)` | List parked actions and paused Codemode executions awaiting approval. |
288
- | `approveExecution(executionId)` | Approve a parked execution; runs `execute` and auto-continues the turn. |
289
- | `rejectExecution(executionId, reason?)` | Reject a parked execution without running it. |
290
- | `replyAttachments(requestId?)` | Read the advisory attachments recorded during a turn. |
291
- | `actionLedgerPendingRetryLeaseMs` | Stale-pending reclaim window (default `300000`; `false` to disable). |
307
+ | Member | Description |
308
+ | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
309
+ | `getActions()` | Return the action descriptors to compile into tools. |
310
+ | `authorizeTurn(ctx)` | Decide granted permissions once per turn. Defaults to full grant. |
311
+ | `authorizeAction(ctx)` | Decide authorization per action call. Defaults to checking `authorizeTurn` grants. |
312
+ | `pendingApprovals(executionId?)` | List parked actions and paused Codemode executions awaiting approval. |
313
+ | `approveExecution(executionId)` | Approve a parked execution; runs `execute` and auto-continues the turn. |
314
+ | `rejectExecution(executionId, reason?, { autoContinue? })` | Reject a parked execution without running it. `autoContinue: false` skips the continuation. |
315
+ | `replyAttachments(requestId?)` | Read the advisory attachments recorded during a turn. |
316
+ | `actionLedgerPendingRetryLeaseMs` | Stale-pending reclaim window (default `300000`; `false` to disable). |
292
317
 
293
318
  ## Related
294
319
 
package/docs/channels.md CHANGED
@@ -100,8 +100,21 @@ await this.runTurn({ input: "Read this out loud", channel: "voice" });
100
100
 
101
101
  Inside a turn, the active channel is available as `this.activeChannel` (a
102
102
  `ChannelContext` with `channelId`, `kind`, and messenger details when relevant).
103
- A turn with no `channel` runs without a channel context and applies no channel
104
- policy.
103
+
104
+ Turns from browser clients over WebSocket chat (`useAgentChat`) always run on the
105
+ implicit `web` channel, so a `web` entry in `configureChannels()` applies its
106
+ `instructions`, `tools`, and `maxTurns` to them. The channel is stamped on each
107
+ new user message, so continuations after tool results and recovered turns keep
108
+ it. Clients cannot choose or forge a channel. Regenerating a message another
109
+ channel sent runs on `web` and leaves that message's channel unchanged; a
110
+ continuation after a tool result keeps `web`, but one that runs after the agent
111
+ was evicted takes the stored message's channel. More generally, a continuation
112
+ without a `channel` extends the channel of the turn before it, including a
113
+ channel passed explicitly to `runTurn({ continuation: true, channel })`.
114
+
115
+ A `runTurn()` or `chat()` call with no `channel` runs without a channel context
116
+ and applies no channel policy. Pass `channel: "web"` to apply the `web` policy to
117
+ such a turn.
105
118
 
106
119
  ## Deliver out of band
107
120
 
package/docs/index.md CHANGED
@@ -187,7 +187,7 @@ Durable Object binding and migration explicitly.
187
187
 
188
188
  ```jsonc
189
189
  {
190
- "compatibility_date": "2026-01-28",
190
+ "compatibility_date": "2026-06-11",
191
191
  "compatibility_flags": ["nodejs_compat"],
192
192
  "ai": { "binding": "AI" },
193
193
  "durable_objects": {
@@ -204,18 +204,18 @@ Both Think and [`AIChatAgent`](https://github.com/cloudflare/agents/blob/main/do
204
204
 
205
205
  **AIChatAgent** is a protocol adapter. You override `onChatMessage` and are responsible for calling `streamText`, wiring tools, converting messages, and returning a `Response`. AIChatAgent handles the plumbing — message persistence, streaming, abort, resume — but the LLM call is entirely your concern.
206
206
 
207
- **Think** is an opinionated framework. It makes decisions for you: `getModel()` returns the model, `getSystemPrompt()` or `configureContext()` sets the prompt, `getTools()` returns tools. The default `onChatMessage` runs the complete agentic loop. You override individual pieces, not the whole pipeline.
207
+ **Think** is an opinionated framework. It makes decisions for you: `getModel()` returns the model, `getSystemPrompt()` or `configureContext()` sets the prompt, `getTools()` returns tools. Think runs the complete agentic loop itself; there is no `onChatMessage` to override. You customize individual pieces through these overrides and the lifecycle hooks (`beforeTurn`, `beforeStep`, `beforeToolCall`, and so on), not the whole pipeline.
208
208
 
209
209
  | Concern | AIChatAgent | Think |
210
210
  | ---------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------- |
211
211
  | **Minimal subclass** | ~15 lines (wire `streamText` + tools + system prompt + response) | 3 lines (`getModel()` only) |
212
- | **Storage** | Flat SQL table | Sessions: tree-structured messages, compaction, FTS5 |
212
+ | **Storage** | Sessions, used as a single linear transcript | Sessions: tree-structured messages, compaction, FTS5 |
213
213
  | **Regeneration** | Destructive (old response deleted) | Non-destructive branching (old responses preserved) |
214
214
  | **Context management** | Manual | Context blocks with LLM-writable persistent memory |
215
215
  | **Sub-agent RPC** | Not built in | `chat()` with `StreamCallback` |
216
216
  | **Programmatic turns** | `saveMessages()` | `saveMessages()`, `submitMessages()`, `continueLastTurn()` |
217
217
  | **Compaction** | `maxPersistedMessages` (deletes oldest) | Non-destructive summaries via overlays |
218
- | **Search** | Not available | FTS5 full-text search per-session and cross-session |
218
+ | **Search** | Not available | FTS5 full-text search within the conversation |
219
219
 
220
220
  ### When to use AIChatAgent
221
221
 
@@ -261,7 +261,9 @@ admission. (`submit` does not accept function input.)
261
261
  // wait — block for the result
262
262
  const result = await this.runTurn({ input: "Summarize the latest thread" });
263
263
  if (result.status === "completed") {
264
- // result.message is the assistant SessionMessage; result.continuation is false
264
+ // result.message is the assistant SessionMessage; result.continuation is false.
265
+ // When beforeTurn returns a structured `output` spec, result.output holds
266
+ // the parsed value; an answer that does not parse ends the turn with "error".
265
267
  }
266
268
 
267
269
  // submit — durable acceptance, check status later
@@ -393,14 +395,18 @@ path.
393
395
  | Method / Property | Default | Description |
394
396
  | -------------------------- | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
395
397
  | `getModel()` | throws | Return a model id `string` (resolved via the bundled `workers-ai-provider` off `getAIBinding()` — a `@cf/...` id hits Workers AI, a `"provider/model"` slug routes through AI Gateway) or a `LanguageModel` |
398
+ | `getGateway(model)` | `undefined` | AI Gateway options (`id`, `metadata`, cache settings) for a string model — see [AI Gateway options](#ai-gateway-options) |
396
399
  | `getAIBinding()` | `this.env.AI` | Workers AI binding used to resolve string models from `getModel()` |
397
400
  | `getSystemPrompt()` | `"You are a helpful assistant."` | System prompt (fallback when no context blocks) |
398
401
  | `getTools()` | `{}` | AI SDK `ToolSet` for the agentic loop |
399
402
  | `getScheduledTasks()` | `{}` | Code-declared recurring prompts or handlers |
403
+ | `getScheduledTasksScope()` | `"root"` | Which instances arm the declared tasks — `"root"` (top-level agent only) or `"all"` (sub-agents too) |
400
404
  | `getDefaultTimezone()` | `undefined` | Default timezone for wall-clock scheduled tasks |
401
405
  | `getMessengers()` | `{}` | Messenger ingress and delivery declarations — see [Messengers](./messengers.md) |
402
406
  | `getActions()` | `{}` | Server actions (idempotency, approvals, authorization) compiled into tools — see [Actions](./actions.md) |
403
407
  | `configureChannels()` | `{}` | Per-channel policy and surfaces beyond the implicit `web` channel — see [Channels](./channels.md) |
408
+ | `messengerConcurrency` | Burst, 600 ms | Chat SDK concurrency strategy for every messenger on the agent. Set it as a class field — see [Messengers](./messengers.md#change-the-concurrency-strategy) |
409
+ | `truncationStep` | `8` | Move the read-time truncation cutoff once every this many messages. `1` cuts every turn — see [Prompt caching](#prompt-caching) |
404
410
  | `maxSteps` | `10` | Max tool-call rounds per turn |
405
411
  | `sendReasoning` | `true` | Send reasoning chunks to chat clients |
406
412
  | `configureSession()` | identity | Configure the default session handle: compaction and search — see [Sessions](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md) |
@@ -419,6 +425,37 @@ path.
419
425
  | `chatStreamStallTimeoutMs` | `0` (off) | Opt-in inactivity watchdog: abort a turn whose model stream produces no chunk for this long (measures the gap between chunks, including tool execution — set above your slowest model TTFT + tool, e.g. `120_000`). Emits a `chat:stream:stalled` event; the stall routes into bounded recovery (see below) instead of an infinite spinner, and only terminalizes once the budget is exhausted. Override per-turn via `TurnConfig.chatStreamStallTimeoutMs` (returned from `beforeTurn`) for a turn with a known-slow tool. |
420
426
  | `contextOverflow` | `undefined` | Opt-in mid-turn context-overflow handling: `{ reactive?, maxRetries?, proactive? }`. Requires `classifyChatError` + a session compaction function. See [Context-window overflow recovery](#context-window-overflow-recovery). |
421
427
 
428
+ ### AI Gateway options
429
+
430
+ When `getModel()` returns a string, override `getGateway(model)` to choose the
431
+ AI Gateway and attach metadata to the request log. Think calls it each time it
432
+ resolves a string model: once per turn, plus once for each string `model`
433
+ override returned from `beforeTurn` or `beforeStep`. It can read
434
+ `this.activeTurn`, `this.getMessengerContext()`, or agent state:
435
+
436
+ ```ts
437
+ import { Think } from "@cloudflare/think";
438
+
439
+ export class SupportAgent extends Think<Env> {
440
+ getModel() {
441
+ return "openai/gpt-5.5";
442
+ }
443
+
444
+ getGateway() {
445
+ return {
446
+ id: "support",
447
+ metadata: { agent: this.name, trigger: this.activeTurn?.trigger ?? null }
448
+ };
449
+ }
450
+ }
451
+ ```
452
+
453
+ A `"provider/model"` slug uses the account's `default` gateway when
454
+ `getGateway()` returns `undefined`. A `@cf/...` id calls Workers AI directly
455
+ unless you return a gateway. `getGateway()` is not called when `getModel()`
456
+ returns a `LanguageModel`, or when an overridden `resolveModel()` builds the
457
+ model without calling `super.resolveModel()`.
458
+
422
459
  ### MCP tools exposed outside the harness
423
460
 
424
461
  Think normally calls `this.mcp.getAITools()` while assembling every turn. If you expose MCP tools through Code Mode or another mechanism outside Think's automatic tool set, set `includeMcpTools = false` to avoid direct JSON Schema-to-Zod materialization:
@@ -522,10 +559,16 @@ When skills are available, Think exposes:
522
559
  | `read_skill_resource` | Read a bundled resource by `{ name, path }` or `skill-name/path` |
523
560
  | `run_skill_script` | Run a bundled script when `getSkillScriptRunner()` returns a runner |
524
561
 
525
- Skills are not always-on system prompt text. Use `getSystemPrompt()` or a
526
- context block from `configureContext()` for behavior that should apply to every
527
- turn. Use skills for task-specific procedures, references, scripts, templates,
528
- and assets that should be loaded only when relevant.
562
+ Skills are not always-on system prompt text. Use a context block from
563
+ `configureContext()` for behavior that should apply to every turn. Use skills
564
+ for task-specific procedures, references, scripts, templates, and assets that
565
+ should be loaded only when relevant.
566
+
567
+ Skills register a context block of their own, and `getSystemPrompt()` is only a
568
+ fallback for agents with no context blocks. Once `getSkills()` returns a source,
569
+ an overridden `getSystemPrompt()` is no longer part of the prompt, and Think
570
+ logs a one-time warning suggesting you move that text into `configureContext()`.
571
+ Agents that keep the default `getSystemPrompt()` do not see the warning.
529
572
 
530
573
  Script execution is opt-in and requires a Worker Loader binding:
531
574
 
@@ -568,9 +611,11 @@ Network access, tools, and workspace writes are opt-in. The default timeout is
568
611
 
569
612
  ### Chat Recovery
570
613
 
571
- Think always wraps chat turns in recoverable fibers. If the Durable Object is evicted mid-stream, Think reconstructs any buffered chunks, persists partial output, and schedules either a continuation of the assistant turn or a retry of the unanswered user turn. `chatRecovery = false` is no longer supported; assign an object only to tune recovery.
614
+ Think always wraps chat turns in recoverable fibers. If the Durable Object is evicted mid-stream, Think reconstructs any buffered chunks, persists partial output, and schedules either a continuation of the assistant turn or a retry of the unanswered user turn. A continuation streams into the interrupted assistant message, so the recovered answer stays one message. An interrupted regeneration recovers on its own branch, beside the response it replaces. `chatRecovery = false` is no longer supported; assign an object only to tune recovery.
615
+
616
+ A stream-stall watchdog abort (`chatStreamStallTimeoutMs`, above) is treated as just another interruption and routes into this same bounded path. Think calls `onChatRecovery` (see below), preserves the settled partial, and schedules a continuation, so a transient hang recovers automatically. If the stall happens before the model produces its first chunk, there is no partial to continue, so Think retries the unanswered user message instead. A persistently hanging provider exhausts the budget and terminalizes through the **same** exhaustion handling as a deploy/eviction interruption: `onExhausted` fires, the `chat:recovery:exhausted` event is emitted, and the configured `terminalMessage` is shown (not a raw stall error).
572
617
 
573
- A stream-stall watchdog abort (`chatStreamStallTimeoutMs`, above) is treated as just another interruption and routes into this same bounded path. The settled partial is preserved and a continuation is scheduled, so a transient hang recovers automatically. A persistently hanging provider exhausts the budget and terminalizes through the **same** exhaustion handling as a deploy/eviction interruption: `onExhausted` fires, the `chat:recovery:exhausted` event is emitted, and the configured `terminalMessage` is shown (not a raw stall error).
618
+ For a stall, `onChatRecovery` runs while the turn is still live. `recoveryData` is the latest value the turn passed to `this.stash()`, and `createdAt` is when the turn started. Returning `{ continue: false }` ends the turn as interrupted, and `{ persist: false }` discards the partial unless it holds settled tool results. `recoveryKind` describes the partial the hook was shown: if the hook discards it, or it holds nothing Think persists, the user's message is the latest message again and Think retries that turn instead of continuing. A `chat()` caller receives `onInterrupted()` for the stalled attempt, because the recovered answer arrives later through the transcript rather than through its callback.
574
619
 
575
620
  Override `onChatRecovery` when you need provider-specific recovery, such as retrieving a stored OpenAI Responses result instead of issuing a new model call:
576
621
 
@@ -773,6 +818,27 @@ work such as creating a Workflow run or writing a run ledger. Delivery is
773
818
  at-least-once; use `idempotencyKey` or `occurrenceKey` for your own durable
774
819
  idempotency.
775
820
 
821
+ Declared tasks are armed on the **root agent only**. Because
822
+ `getScheduledTasks()` is normally a static declaration, it returns the same
823
+ tasks on every instance of the class, so arming it on sub-agents as well would
824
+ dispatch each occurrence once per live sub-agent on top of the root. Override
825
+ `getScheduledTasksScope()` to return `"all"` when a class genuinely declares
826
+ different tasks per sub-agent — each sub-agent then owns an independent
827
+ schedule.
828
+
829
+ ```typescript
830
+ export class PerUserAgent extends Think<Env> {
831
+ getScheduledTasksScope() {
832
+ return "all" as const;
833
+ }
834
+
835
+ async getScheduledTasks(): Promise<ThinkScheduledTasks> {
836
+ const reminder = await this.getReminderForThisUser();
837
+ return reminder ? { reminder } : {};
838
+ }
839
+ }
840
+ ```
841
+
776
842
  Static declarations reconcile on startup. If `getScheduledTasks()` reads
777
843
  product-owned data that can change while the Durable Object is live, call
778
844
  `internal_reconcileScheduledTasks()` after updating that data. During
@@ -909,12 +975,40 @@ Media eviction is a different concern: a context-window technique, not a storage
909
975
 
910
976
  The bytes are written to the Workspace at that path, raw and with their real mime type — not as a `data:` URL string. The workspace `read` tool recognises `image/*`, so when the agent decides it needs to look at the picture again it reads the path out of the marker and the actual image goes back into context. Eviction is visible to the model and lossy on purpose; nothing reconstructs it behind the model's back.
911
977
 
912
- Passes are bounded (`maxRowsPerPass`, 64 by default) and run in the background after a turn or a hydration read, rescheduling themselves while a backlog remains. Only payloads of at least `minPartBytes` are evicted, and `keepRecentMessages` is clamped to the four messages the model replays at full fidelity, so eviction can never rewrite content the model is still reading. Once a row is rewritten, the Sessions attachment reference is dropped and the blob is reaped: the bytes exist in exactly one place, the Workspace file.
978
+ Passes are bounded (`maxRowsPerPass`, 64 by default) and run in the background after a turn or a hydration read, rescheduling themselves while a backlog remains. Only payloads of at least `minPartBytes` are evicted, and `keepRecentMessages` is clamped to the four messages the model replays at full fidelity, so eviction can never rewrite content the model is still reading. The eviction cutoff moves in the same `truncationStep` steps as read-time truncation, so evicting media does not rewrite the prompt prefix on turns where truncation leaves it alone; media can stay in up to `truncationStep - 1` messages past `keepRecentMessages`. Once a row is rewritten, the Sessions attachment reference is dropped and the blob is reaped: the bytes exist in exactly one place, the Workspace file.
913
979
 
914
980
  `mediaEviction: false` keeps aged media in the conversation, so the model keeps seeing it. It does not change where Sessions keeps the bytes — a large payload may still be stored as a pointer, which is unobservable.
915
981
 
916
982
  Startup hydration reads a recent window bounded by `hydrationByteBudget` (32 MiB by default). The budget charges each row its stored bytes plus the attachment bytes it re-inflates, so it bounds isolate memory rather than the on-disk footprint.
917
983
 
984
+ ### Prompt caching
985
+
986
+ Providers cache on a byte-identical prompt prefix, so a request only reads the cache up to the first byte that differs from an earlier request. Think keeps that prefix stable: the frozen system prompt is persisted, and each turn's first model request extends the previous request unless one of the context-reduction mechanisms rewrote history. Each mechanism rewrites the prefix on a bounded schedule:
987
+
988
+ | Mechanism | What it rewrites | How often the prefix changes |
989
+ | -------------------- | ---------------------------------------------------------------------------------- | ------------------------------------------- |
990
+ | Read-time truncation | Tool outputs over 500 characters and text over 10,000 characters in older messages | Once every 8 messages (about every 4 turns) |
991
+ | Media eviction | An aged file part becomes a marker | With the read-time truncation cutoff |
992
+ | Compaction | A span of older turns becomes one summary | Once per compaction |
993
+
994
+ Read-time truncation keeps at least the 4 most recent messages at full fidelity and cuts the rest at a multiple of 8 messages, so between cuts up to 11 recent messages stay whole. A cutoff that moved every turn would rewrite a message near the end of the prefix on every turn. In a 16-turn run with a 4,000-character tool output per turn, and cached input billed at a tenth of fresh input, that cost about twice as much as sending the untruncated history. Cutting every 8 messages brings it close to the untruncated cost while still bounding the context.
995
+
996
+ The extra full-fidelity messages cost context. For a model with a small context window, set `truncationStep` to cut more often, or to `1` to cut every turn and keep only the 4 most recent messages whole:
997
+
998
+ ```ts
999
+ import { Think } from "@cloudflare/think";
1000
+
1001
+ export class SmallModelAgent extends Think<Env> {
1002
+ truncationStep = 1;
1003
+ }
1004
+ ```
1005
+
1006
+ Set `truncationStep` to `Infinity` to turn read-time truncation off: older messages are never cut, and the prefix only changes on media eviction or compaction. Pair it with compaction so the context stays bounded.
1007
+
1008
+ A compaction threshold that the compacted history still exceeds compacts on every append, which rewrites the summary every turn. Set `compactAfter()` well above the size of a summary plus the recent messages it keeps.
1009
+
1010
+ `hydrationByteBudget` does not affect caching while the transcript fits in it. Its 32 MiB default is larger than any model's context window, so this holds unless large attachments fill the budget. Once the transcript exceeds the budget, the hydrated window starts later as messages are added, which rewrites the start of the prompt. Media eviction keeps a transcript with large attachments under the budget.
1011
+
918
1012
  ## Package Exports
919
1013
 
920
1014
  | Export | Description |
@@ -962,5 +1056,6 @@ The Agent Skills engine and its script runner live in
962
1056
  - [Messengers](./messengers.md) — Chat SDK messenger ingress and delivery
963
1057
  - [Client Tools](./client-tools.md) — Browser-side tools, approvals, and concurrency
964
1058
  - [Sub-agents and Programmatic Turns](./sub-agents.md) — RPC streaming, `saveMessages`, recovery
1059
+ - [Multi-chat Applications](./multi-chat.md) — a per-user directory with one Think agent per conversation, sharing a workspace and MCP servers
965
1060
  - [Programmatic Submissions](./programmatic-submissions.md) — durable acceptance, idempotent retry, cancellation, and status inspection
966
1061
  - [Workflows](./workflows.md) — `ThinkWorkflow`, `step.prompt()`, structured output, and long-running workflow steps
@@ -142,45 +142,66 @@ beforeTurn(ctx: TurnContext): TurnConfig | void | Promise<TurnConfig | void>
142
142
 
143
143
  ### TurnContext
144
144
 
145
- | Field | Type | Description |
146
- | -------------- | ------------------------- | ------------------------------------------------------------------------ |
147
- | `system` | `string` | Assembled system prompt (from context blocks or `getSystemPrompt()`) |
148
- | `messages` | `ModelMessage[]` | Assembled model messages (truncated) |
149
- | `tools` | `ToolSet` | Merged tool set (workspace + getTools + context + MCP + client + caller) |
150
- | `model` | `LanguageModel` | The resolved model (a string from `getModel()` is already resolved here) |
151
- | `continuation` | `boolean` | Whether this is a continuation turn (auto-continue after tool result) |
152
- | `body` | `Record<string, unknown>` | Custom body fields from the client request |
145
+ | Field | Type | Description |
146
+ | -------------- | ------------------------------- | ------------------------------------------------------------------------ |
147
+ | `system` | `string` | Assembled system prompt (from context blocks or `getSystemPrompt()`) |
148
+ | `messages` | `ModelMessage[]` | Assembled model messages (truncated) |
149
+ | `tools` | `ToolSet` | Merged tool set (workspace + getTools + context + MCP + client + caller) |
150
+ | `model` | `LanguageModel` | The resolved model (a string from `getModel()` is already resolved here) |
151
+ | `continuation` | `boolean` | Whether this is a continuation turn (auto-continue after tool result) |
152
+ | `body` | `Record<string, unknown>` | Custom body fields from the client request |
153
+ | `requestId` | `string \| undefined` | The request this turn runs for. See [Turn identity](#turn-identity) |
154
+ | `trigger` | `TurnTrigger \| undefined` | What admitted the turn: `"ws-chat"`, `"rpc"`, `"submission"`, and so on |
155
+ | `abortSignal` | `AbortSignal \| undefined` | Aborts when the turn is cancelled. Pass it to I/O the hook awaits |
156
+ | `messenger` | `MessengerContext \| undefined` | The messenger thread this turn answers, fixed when the turn was admitted |
157
+
158
+ ### Turn identity
159
+
160
+ Every turn has a request id. `beforePersist`, `beforeTurn`, `beforeToolCall`, `onChatResponse` and `onChatError` all receive the same id for the same turn, so state a subclass keeps for a turn can be keyed by it instead of by a shared field that a later turn could overwrite.
161
+
162
+ Anywhere else inside a turn, such as a tool's `execute` or a helper called from a hook, read `this.activeTurn`. It returns `{ requestId, trigger, continuation, channel? }` for the running turn, and `undefined` outside a turn, including in work a turn schedules to run later.
163
+
164
+ ```typescript
165
+ override async beforeTurn(ctx: TurnContext) {
166
+ console.log("turn", ctx.requestId, "admitted by", ctx.trigger);
167
+ const profile = await loadProfile({ signal: ctx.abortSignal });
168
+ return { system: `${ctx.system}\n\n${profile}` };
169
+ }
170
+ ```
171
+
172
+ A continuation turn, for example the one that runs after a tool approval, has its own request id rather than the id of the turn that asked for the approval.
153
173
 
154
174
  ### TurnConfig
155
175
 
156
176
  All fields are optional. Return only what you want to change.
157
177
 
158
- | Field | Type | Description |
159
- | -------------------------- | ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
160
- | `model` | `ThinkModel` | Override the model for this turn — a model id string or a `LanguageModel` |
161
- | `system` | `string` | Override the system prompt |
162
- | `messages` | `ModelMessage[]` | Override the assembled messages |
163
- | `tools` | `ToolSet` | Extra tools to merge (additive) |
164
- | `activeTools` | `string[]` | Limit which tools the model can call |
165
- | `toolChoice` | `ToolChoice` | Force a specific tool call |
166
- | `maxSteps` | `number` | Override `maxSteps` for this turn |
167
- | `stopWhen` | `StopCondition \| StopCondition[]` | Additional early-exit conditions |
168
- | `sendReasoning` | `boolean` | Send reasoning chunks for this turn |
169
- | `maxOutputTokens` | `number` | Maximum tokens to generate |
170
- | `temperature` | `number` | Sampling temperature |
171
- | `topP` | `number` | Nucleus sampling value |
172
- | `topK` | `number` | Top-K sampling value |
173
- | `presencePenalty` | `number` | Presence penalty |
174
- | `frequencyPenalty` | `number` | Frequency penalty |
175
- | `stopSequences` | `string[]` | Stop generation sequences |
176
- | `seed` | `number` | Sampling seed when supported |
177
- | `maxRetries` | `number` | Maximum retries for this turn |
178
- | `timeout` | `TimeoutConfiguration` | Timeout for this turn |
179
- | `chatStreamStallTimeoutMs` | `number` | Override the stream-stall watchdog for this turn (`0` disables it); auto-resets after the turn. Useful for a turn with a known-slow tool — see [Think configuration](./index.md). |
180
- | `headers` | `Record<string, string>` | Additional provider request headers |
181
- | `providerOptions` | `Record<string, unknown>` | Provider-specific options |
182
- | `repairToolCall` | `ToolCallRepairFunction` | Repair a tool call that the AI SDK cannot parse or validate. The returned call is revalidated before execution. |
183
- | `experimental_transform` | `StreamTextTransform \| StreamTextTransform[]` | AI SDK stream transform(s) for this turn — inspect or rewrite stream parts (for example, emit `source` parts derived from tool results). Applied in order. |
178
+ | Field | Type | Description |
179
+ | -------------------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
180
+ | `model` | `ThinkModel` | Override the model for this turn — a model id string or a `LanguageModel` |
181
+ | `system` | `string` | Override the system prompt |
182
+ | `messages` | `ModelMessage[]` | Override the assembled messages |
183
+ | `tools` | `ToolSet` | Extra tools to merge (additive) |
184
+ | `activeTools` | `string[]` | Limit which tools the model can call |
185
+ | `toolChoice` | `ToolChoice` | Force a specific tool call |
186
+ | `maxSteps` | `number` | Override `maxSteps` for this turn |
187
+ | `stopWhen` | `StopCondition \| StopCondition[]` | Additional early-exit conditions |
188
+ | `sendReasoning` | `boolean` | Send reasoning chunks for this turn |
189
+ | `messageMetadata` | `MessageMetadataCallback` | Write server-authored metadata onto the assistant message this turn persists. Called per stream part; return JSON-serializable metadata from `start`/`finish` (shallow-merged). Overrides the instance-level `messageMetadata`. |
190
+ | `maxOutputTokens` | `number` | Maximum tokens to generate |
191
+ | `temperature` | `number` | Sampling temperature |
192
+ | `topP` | `number` | Nucleus sampling value |
193
+ | `topK` | `number` | Top-K sampling value |
194
+ | `presencePenalty` | `number` | Presence penalty |
195
+ | `frequencyPenalty` | `number` | Frequency penalty |
196
+ | `stopSequences` | `string[]` | Stop generation sequences |
197
+ | `seed` | `number` | Sampling seed when supported |
198
+ | `maxRetries` | `number` | Maximum retries for this turn |
199
+ | `timeout` | `TimeoutConfiguration` | Timeout for this turn |
200
+ | `chatStreamStallTimeoutMs` | `number` | Override the stream-stall watchdog for this turn (`0` disables it); auto-resets after the turn. Useful for a turn with a known-slow tool — see [Think configuration](./index.md). |
201
+ | `headers` | `Record<string, string>` | Additional provider request headers |
202
+ | `providerOptions` | `Record<string, unknown>` | Provider-specific options |
203
+ | `repairToolCall` | `ToolCallRepairFunction` | Repair a tool call that the AI SDK cannot parse or validate. The returned call is revalidated before execution. |
204
+ | `experimental_transform` | `StreamTextTransform \| StreamTextTransform[]` | AI SDK stream transform(s) for this turn — inspect or rewrite stream parts (for example, emit `source` parts derived from tool results). Applied in order. |
184
205
 
185
206
  ### Examples
186
207
 
@@ -301,6 +322,25 @@ beforeTurn(ctx: TurnContext) {
301
322
  }
302
323
  ```
303
324
 
325
+ Stamp server-authored metadata on the assistant message this turn persists. The callback runs for every stream part and each non-`undefined` return is shallow-merged into the message's metadata, then broadcast to clients and persisted. An auto-continuation (for example, after a tool approval or client tool result) is its own turn: `beforeTurn` runs again with `ctx.continuation: true` and the continuation persists as a separate assistant message with its own metadata.
326
+
327
+ ```typescript
328
+ beforeTurn(ctx: TurnContext) {
329
+ return {
330
+ messageMetadata: ({ part }) => {
331
+ if (part.type === "start") {
332
+ return { createdAt: Date.now(), continuation: ctx.continuation };
333
+ }
334
+ if (part.type === "finish") {
335
+ return { finishReason: part.finishReason };
336
+ }
337
+ }
338
+ };
339
+ }
340
+ ```
341
+
342
+ For metadata that applies to every turn, set the instance-level `messageMetadata` property on your `Think` subclass instead of returning it from `beforeTurn`. A `TurnConfig.messageMetadata` overrides it for one turn.
343
+
304
344
  Disable retries and apply a streaming timeout for a recovery turn:
305
345
 
306
346
  ```typescript
@@ -471,6 +511,7 @@ beforeToolCall(ctx: ToolCallContext): ToolCallDecision | void | Promise<ToolCall
471
511
  | `stepNumber` | `number \| undefined` | Index of the current step where this tool call occurs |
472
512
  | `messages` | `ReadonlyArray<ModelMessage>` | Conversation messages visible at tool execution time |
473
513
  | `abortSignal` | `AbortSignal \| undefined` | Aborts if the turn is cancelled |
514
+ | `requestId?` | `string` | Request id of the turn making the call. See [Turn identity](#turn-identity) |
474
515
 
475
516
  Pass an explicit `TOOLS` generic to get full input typing:
476
517
 
@@ -557,19 +598,20 @@ afterToolCall(ctx: ToolCallResultContext): void | Promise<void>
557
598
 
558
599
  `ToolCallResultContext<TOOLS>` is backed by the AI SDK's `OnToolCallFinishEvent<TOOLS>` (the parameter of `experimental_onToolCallFinish`). It spreads the originating `TypedToolCall<TOOLS>` at the top level, plus the per-call event extras and a discriminated outcome:
559
600
 
560
- | Field | Type | Description |
561
- | ------------ | ----------------------------------------- | ---------------------------------------------------- |
562
- | `type` | `"tool-call"` | Discriminator (carried over from the call) |
563
- | `toolCallId` | `string` | Unique id matching the originating `ToolCallContext` |
564
- | `toolName` | `string` | Name of the tool that was called |
565
- | `input` | typed when `TOOLS` is passed | Arguments the tool was called with |
566
- | `dynamic?` | `boolean` | `true` for runtime-registered tools |
567
- | `stepNumber` | `number \| undefined` | Index of the current step |
568
- | `messages` | `ReadonlyArray<ModelMessage>` | Conversation messages visible at tool execution time |
569
- | `durationMs` | `number` | Wall-clock execution time of `execute` |
570
- | `success` | `boolean` | Discriminator: `true` on success, `false` on failure |
571
- | `output` | typed per tool (when `success` is `true`) | Whatever the tool's `execute` returned |
572
- | `error` | `unknown` (when `success` is `false`) | Whatever was thrown from `execute` |
601
+ | Field | Type | Description |
602
+ | ------------ | ----------------------------------------- | ------------------------------------------------------------------------------ |
603
+ | `type` | `"tool-call"` | Discriminator (carried over from the call) |
604
+ | `toolCallId` | `string` | Unique id matching the originating `ToolCallContext` |
605
+ | `toolName` | `string` | Name of the tool that was called |
606
+ | `input` | typed when `TOOLS` is passed | Arguments the tool was called with |
607
+ | `dynamic?` | `boolean` | `true` for runtime-registered tools |
608
+ | `stepNumber` | `number \| undefined` | Index of the current step |
609
+ | `messages` | `ReadonlyArray<ModelMessage>` | Conversation messages visible at tool execution time |
610
+ | `durationMs` | `number` | Wall-clock execution time of `execute` |
611
+ | `requestId?` | `string` | Request id of the turn that made the call. See [Turn identity](#turn-identity) |
612
+ | `success` | `boolean` | Discriminator: `true` on success, `false` on failure |
613
+ | `output` | typed per tool (when `success` is `true`) | Whatever the tool's `execute` returned |
614
+ | `error` | `unknown` (when `success` is `false`) | Whatever was thrown from `execute` |
573
615
 
574
616
  When you pass an explicit `TOOLS` generic, narrowing on `ctx.toolName` (together with `ctx.success`) narrows `ctx.output` to that tool's inferred output type. Dynamic tools (runtime-registered, MCP) stay `unknown`:
575
617
 
@@ -720,19 +762,22 @@ Called after a chat turn completes and the assistant message has been persisted.
720
762
 
721
763
  Fires for all turn completion paths that persist an assistant message: WebSocket, sub-agent RPC, `saveMessages()`, durable `submitMessages()` execution, `continueLastTurn()`, and auto-continuation.
722
764
 
765
+ If the Durable Object resets after the assistant message is persisted but before the hook runs, Think fires the hook when the agent wakes, with `recovered: true` and the stored message. A reset while the hook itself is running can fire it again on wake, so make side effects in the hook idempotent (for example, keyed by `requestId`). A recovered hook runs outside the original turn, so it has no reply attachments and no channel context from that turn.
766
+
723
767
  ```typescript
724
768
  onChatResponse(result: ChatResponseResult): void | Promise<void>
725
769
  ```
726
770
 
727
771
  ### ChatResponseResult
728
772
 
729
- | Field | Type | Description |
730
- | -------------- | ------------------------------------- | ------------------------------------------ |
731
- | `message` | `UIMessage` | The persisted assistant message |
732
- | `requestId` | `string` | Unique ID for this turn |
733
- | `continuation` | `boolean` | Whether this was a continuation turn |
734
- | `status` | `"completed" \| "error" \| "aborted"` | How the turn ended |
735
- | `error` | `string?` | Error message (when `status` is `"error"`) |
773
+ | Field | Type | Description |
774
+ | -------------- | ------------------------------------- | ----------------------------------------------------------------------- |
775
+ | `message` | `UIMessage` | The persisted assistant message |
776
+ | `requestId` | `string` | Unique ID for this turn |
777
+ | `continuation` | `boolean` | Whether this was a continuation turn |
778
+ | `status` | `"completed" \| "error" \| "aborted"` | How the turn ended |
779
+ | `error` | `string?` | Error message (when `status` is `"error"`) |
780
+ | `recovered` | `boolean?` | `true` when the hook is fired on wake for a turn interrupted by a reset |
736
781
 
737
782
  ### Examples
738
783
 
@@ -825,7 +870,13 @@ Called when an error occurs during a turn, **before** `onChatError`. Maps a raw
825
870
  classifyChatError(error: unknown, ctx?: ChatErrorContext): ChatErrorClassification | void
826
871
  ```
827
872
 
828
- `ChatErrorClassification` is `"context_overflow" | "rate_limit" | "transient" | "fatal" | "unknown"`. Today this hook drives **only** context-overflow recovery: Think calls it when a turn errors **and** `contextOverflow.reactive` is enabled (if reactive is off, it is not called). Returning `"context_overflow"` runs the compact-and-retry backstop (see [Context-window overflow recovery](./index.md#context-window-overflow-recovery)); if recovery cannot save the turn, that classification is surfaced on the terminal `onChatError` call via `ChatErrorContext.classification`. The other categories are reserved for future use — returning one today is a no-op (the turn terminalizes as usual) and is not forwarded to `onChatError`. Returning `void` (the default) keeps the existing terminal behavior.
873
+ `ChatErrorClassification` is `"context_overflow" | "rate_limit" | "transient" | "fatal" | "unknown"`. Think calls this hook when a turn's stream errors, and reacts to the result:
874
+
875
+ - `"context_overflow"` runs the compact-and-retry backstop when `contextOverflow.reactive` is enabled (see [Context-window overflow recovery](./index.md#context-window-overflow-recovery)). If recovery cannot save the turn, that classification is surfaced on the terminal `onChatError` call via `ChatErrorContext.classification`.
876
+ - `"transient"` and `"rate_limit"` route the turn into bounded chat recovery, the same path as a stream stall. Think calls `onChatRecovery`, keeps the partial response (unless the hook returns `persist: false`), and schedules a continuation. The continuation waits 1 second on the first attempt and doubles on each later attempt, up to 30 seconds. Once `chatRecovery.maxAttempts` is spent, the turn ends with the configured terminal message and `onExhausted`, not the raw error.
877
+ - `"fatal"`, `"unknown"`, and `void` (the default) keep the existing terminal behavior.
878
+
879
+ If `contextOverflow.reactive` is enabled but neither your class nor a parent class overrides `classifyChatError` (as a method or a class field), Think logs a one-time warning and skips overflow recovery, since the default classifier never returns `"context_overflow"`.
829
880
 
830
881
  The argument may be an `Error`, an AI SDK `APICallError` (with `statusCode`/`responseBody`), or — for in-stream provider errors that surface as a stream error part rather than a throw — the error message string. Narrow accordingly. (Think confirms provider context-overflow errors always surface as in-stream error parts, never thrown exceptions out of `streamText`, so this hook sees them whether you read the `Error` or the string form.)
831
882
 
@@ -895,13 +946,13 @@ The handler receives `(snapshot, host)` — symmetric with tool `execute`. `host
895
946
 
896
947
  Snapshots are intentionally narrower than the subclass `Context` types — class instances, `AbortSignal`s, and other non-JSON-clonable values can't cross the Workers RPC boundary.
897
948
 
898
- | Hook | Snapshot fields |
899
- | ---------------- | ------------------------------------------------------------------------------------------------------------ |
900
- | `beforeTurn` | `{ system, toolNames, messageCount, continuation, body?, modelId }` — see `TurnContextSnapshot` |
901
- | `beforeToolCall` | `{ toolName, toolCallId, input, stepNumber, dynamic? }` |
902
- | `afterToolCall` | `{ toolName, toolCallId, input, stepNumber, durationMs, success, output? \| error?, dynamic? }` |
903
- | `onStepFinish` | `{ stepNumber, finishReason, text, reasoningText, toolCallCount, toolResultCount, usage, providerMetadata }` |
904
- | `onChunk` | `{ type, text?, toolName?, toolCallId? }` — minimal because this fires per token |
949
+ | Hook | Snapshot fields |
950
+ | ---------------- | --------------------------------------------------------------------------------------------------------------------- |
951
+ | `beforeTurn` | `{ system, toolNames, messageCount, continuation, body?, modelId, requestId?, trigger? }` — see `TurnContextSnapshot` |
952
+ | `beforeToolCall` | `{ toolName, toolCallId, input, stepNumber, dynamic? }` |
953
+ | `afterToolCall` | `{ toolName, toolCallId, input, stepNumber, durationMs, success, output? \| error?, dynamic? }` |
954
+ | `onStepFinish` | `{ stepNumber, finishReason, text, reasoningText, toolCallCount, toolResultCount, usage, providerMetadata }` |
955
+ | `onChunk` | `{ type, text?, toolName?, toolCallId? }` — minimal because this fires per token |
905
956
 
906
957
  ### Return values
907
958