@cloudflare/think 0.24.0 → 0.25.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.
- package/README.md +18 -26
- package/dist/{chat-sdk-BEjKXjCm.js → chat-sdk-4Nu96eDX.js} +375 -256
- package/dist/chat-sdk-4Nu96eDX.js.map +1 -0
- package/dist/extensions/index.d.ts +30 -72
- package/dist/extensions/index.js +45 -47
- package/dist/extensions/index.js.map +1 -1
- package/dist/{fetch-DO3uQ9py.js → fetch-BbYxtlff.js} +10 -2
- package/dist/fetch-BbYxtlff.js.map +1 -0
- package/dist/manager-B3rcb_6p.js +493 -0
- package/dist/manager-B3rcb_6p.js.map +1 -0
- package/dist/manager-CWGumyKi.d.ts +3391 -0
- package/dist/messengers/index.d.ts +54 -66
- package/dist/messengers/index.js +2 -2
- package/dist/messengers/telegram.d.ts +4 -4
- package/dist/messengers/telegram.js +1 -1
- package/dist/think.d.ts +2 -2
- package/dist/think.js +8493 -10759
- package/dist/think.js.map +1 -1
- package/dist/tools/extensions.d.ts +1 -1
- package/dist/tools/extensions.js +1 -1
- package/dist/tools/fetch.js +1 -1
- package/dist/workflows.d.ts +5 -2
- package/docs/actions.md +12 -0
- package/docs/channels.md +10 -4
- package/docs/client-tools.md +57 -27
- package/docs/context.md +92 -0
- package/docs/getting-started.md +2 -2
- package/docs/index.md +109 -49
- package/docs/lifecycle-hooks.md +10 -21
- package/docs/multi-chat.md +5 -5
- package/docs/programmatic-submissions.md +28 -10
- package/docs/sub-agents.md +45 -51
- package/docs/tools.md +31 -3
- package/docs/workflows.md +4 -3
- package/package.json +13 -8
- package/dist/chat-sdk-BEjKXjCm.js.map +0 -1
- package/dist/fetch-DO3uQ9py.js.map +0 -1
- package/dist/hook-proxy-DY2sBNa0.js +0 -117
- package/dist/hook-proxy-DY2sBNa0.js.map +0 -1
- package/dist/index-DIQ9oY1t.d.ts +0 -5864
- package/dist/manager-CtXhU1fK.d.ts +0 -243
- package/dist/manager-sfWIcYJT.js +0 -333
- package/dist/manager-sfWIcYJT.js.map +0 -1
package/docs/index.md
CHANGED
|
@@ -400,7 +400,6 @@ path.
|
|
|
400
400
|
| `getSystemPrompt()` | `"You are a helpful assistant."` | Instructions at the top of the system prompt, above context blocks. The default is used only with no context blocks |
|
|
401
401
|
| `getTools()` | `{}` | AI SDK `ToolSet` for the agentic loop |
|
|
402
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) |
|
|
404
403
|
| `getDefaultTimezone()` | `undefined` | Default timezone for wall-clock scheduled tasks |
|
|
405
404
|
| `getMessengers()` | `{}` | Messenger ingress and delivery declarations — see [Messengers](./messengers.md) |
|
|
406
405
|
| `getActions()` | `{}` | Server actions (idempotency, approvals, authorization) compiled into tools — see [Actions](./actions.md) |
|
|
@@ -421,7 +420,7 @@ path.
|
|
|
421
420
|
| `waitForMcpConnections` | `false` | Wait for MCP servers before inference |
|
|
422
421
|
| `chatRecovery` | Always on | Durable recovery configuration. See [`ChatRecoveryConfig`](https://github.com/cloudflare/agents/blob/main/docs/agents/chat-agents.md#stream-recovery) for all options and defaults. |
|
|
423
422
|
| `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. |
|
|
424
|
-
| `contextOverflow` | `undefined` | Opt-in mid-turn context-overflow handling: `{ reactive?, maxRetries?, proactive? }`. Requires
|
|
423
|
+
| `contextOverflow` | `undefined` | Opt-in mid-turn context-overflow handling: `{ reactive?, maxRetries?, proactive? }`. Requires a session compaction function. See [Context-window overflow recovery](#context-window-overflow-recovery). |
|
|
425
424
|
|
|
426
425
|
### AI Gateway options
|
|
427
426
|
|
|
@@ -584,7 +583,10 @@ Outside Think, import it from `agents/skills/runner`. It is a separate entry
|
|
|
584
583
|
point because it loads `just-bash` and `@cloudflare/codemode`.
|
|
585
584
|
|
|
586
585
|
The runner runs JavaScript, Python, and Bash scripts under `scripts/`. Python
|
|
587
|
-
runs as Python Dynamic Workers and Bash runs through `just-bash`.
|
|
586
|
+
runs as Python Dynamic Workers and Bash runs through `just-bash`. `just-bash`
|
|
587
|
+
is an optional peer dependency that the runner loads when a Bash script runs:
|
|
588
|
+
install it if your skills have Bash scripts. A Worker that extends Think
|
|
589
|
+
bundles without it. There is no
|
|
588
590
|
in-Worker bundler: a JavaScript script must be one self-contained module, so
|
|
589
591
|
compile TypeScript or multi-file scripts (for example with esbuild) before
|
|
590
592
|
storing the skill.
|
|
@@ -617,6 +619,8 @@ Network access, tools, and workspace writes are opt-in. The default timeout is
|
|
|
617
619
|
|
|
618
620
|
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.
|
|
619
621
|
|
|
622
|
+
A continuation is a new model call, and with no output limit set a reasoning model can spend the provider's default budget on reasoning and add no text, so where that matters, return a `maxOutputTokens` from [`beforeTurn`](./lifecycle-hooks.md#turnconfig).
|
|
623
|
+
|
|
620
624
|
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).
|
|
621
625
|
|
|
622
626
|
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.
|
|
@@ -646,10 +650,44 @@ export class MyAgent extends Think<Env> {
|
|
|
646
650
|
|
|
647
651
|
The same recovery events are available through `agents/observability` on the `chat` channel. Transcript repairs are emitted on the `transcript` channel.
|
|
648
652
|
|
|
653
|
+
#### A server tool a restart cut off
|
|
654
|
+
|
|
655
|
+
A server tool whose call a restart cut off is not run again by default. When the turn recovers, the model is told the call was interrupted and may or may not have taken effect, and it decides what to do next. This keeps a payment, an email or any other side effect from happening twice without the model knowing.
|
|
656
|
+
|
|
657
|
+
A tool that is safe to run twice, such as a read or an idempotent write, can opt into running again after a restart. Mark it with `recovery: "rerun"`:
|
|
658
|
+
|
|
659
|
+
```typescript
|
|
660
|
+
import { tool } from "ai";
|
|
661
|
+
import { z } from "zod";
|
|
662
|
+
|
|
663
|
+
export class MyAgent extends Think<Env> {
|
|
664
|
+
getTools() {
|
|
665
|
+
return {
|
|
666
|
+
lookup: {
|
|
667
|
+
...tool({
|
|
668
|
+
description: "Look up an order",
|
|
669
|
+
inputSchema: z.object({ id: z.string() }),
|
|
670
|
+
execute: async ({ id }) => this.env.ORDERS.get(id)
|
|
671
|
+
}),
|
|
672
|
+
recovery: "rerun"
|
|
673
|
+
}
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
```
|
|
678
|
+
|
|
679
|
+
Calls the conversation moved past (an approval that was never given, an approved call that never ran, a client tool that was never answered) are repaired as described below; `recovery` does not change them.
|
|
680
|
+
|
|
649
681
|
#### Repairing interrupted tool calls
|
|
650
682
|
|
|
651
683
|
When a turn is interrupted mid-flight, the transcript can contain a tool call with no settled result. Before the next provider call, Think repairs each such call so the model does not silently re-run it and the provider does not reject the transcript with `AI_MissingToolResultsError`. The default flips the interrupted call to an errored tool result, so the record survives and conversion still has a tool result for it.
|
|
652
684
|
|
|
685
|
+
This covers a client tool call or approval request the user never answered before sending a new message, and a call the user approved that never ran. The error text says which: a client tool "may still have run", an unanswered approval "did not run". A result that arrives for a settled call is ignored, so make a client tool with side effects safe to run twice. A continuation turn keeps the calls in the message it continues that a client can still answer. While there is one, `continueLastTurn()` changes nothing and returns `{ requestId: "", status: "skipped", reason: "awaiting-client" }` without calling the model, and the client's answer starts the continuation.
|
|
686
|
+
|
|
687
|
+
The same repair removes the reasoning a reply ends in. A reply cut off right after the model's reasoning would otherwise fail every later request on Anthropic, which rejects an assistant message whose final block is a thinking block.
|
|
688
|
+
|
|
689
|
+
A reply that holds nothing once that reasoning is gone (it was cut off while the model was still reasoning) is not stored, and one that is already stored is removed. Refer to [A reply that holds nothing](../agents/client-tools-continuation.md#a-reply-that-holds-nothing).
|
|
690
|
+
|
|
653
691
|
Override `repairInterruptedToolPart` to customize the repaired shape. The common case is a client-resolved tool — for example an `ask_user` question that has no server `execute` and is normally answered by the user's next message. Converting it to a plain text part lets the model treat it as ordinary conversation rather than a tool error, and keeps the question verbatim through compaction:
|
|
654
692
|
|
|
655
693
|
```typescript
|
|
@@ -677,26 +715,22 @@ This runs during transcript repair — before the repaired transcript is persist
|
|
|
677
715
|
|
|
678
716
|
[Compaction](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md#compaction) is checked **between turns** — `compactAfter()` runs after each `appendMessage()`. But a single long, tool-heavy turn grows the prompt step by step inside one `streamText` loop and can exceed the model's context window **mid-turn**, before the next pre-turn check. The provider then rejects the request (`"prompt is too long"`, `context_length_exceeded`), and the turn would otherwise die terminally.
|
|
679
717
|
|
|
680
|
-
Think recovers from this with two opt-in, provider-agnostic layers, both configured through the `contextOverflow` property. Both are off by default, so existing behavior is unchanged. Both reuse your session's compaction function, so they require a `configureSession()` with `onCompaction()` configured.
|
|
718
|
+
Think recovers from this with two opt-in, provider-agnostic layers, both configured through the `contextOverflow` property. Both are off by default, so existing behavior is unchanged. Both reuse your session's compaction function, so they require a `configureSession()` with `onCompaction()` configured. Think recognises the common providers' context-window errors (Anthropic, OpenAI, Google, Bedrock, Mistral, Workers AI) by itself; override [`classifyChatError`](./lifecycle-hooks.md#classifychaterror) to classify errors it does not know, and your classification wins.
|
|
681
719
|
|
|
682
|
-
**1. Reactive backstop — `contextOverflow.reactive`.** When a turn fails with
|
|
720
|
+
**1. Reactive backstop — `contextOverflow.reactive`.** When a turn fails with a context-overflow error, Think discards the truncated partial, runs `session.compact()`, and re-runs the turn from the compacted history. The partial is not persisted: the turn restarts from scratch, so keeping the cut-off assistant message would orphan it beside the recovered answer. It is bounded by `contextOverflow.maxRetries` (default `1`); if compaction cannot shorten history or the budget is spent, the overflow surfaces terminally through `onChatError` with `classification: "context_overflow"` — it never loops or ends silently.
|
|
683
721
|
|
|
684
722
|
```typescript
|
|
685
|
-
import { Think
|
|
723
|
+
import { Think } from "@cloudflare/think";
|
|
686
724
|
|
|
687
725
|
export class MyAgent extends Think<Env> {
|
|
688
726
|
override contextOverflow = { reactive: true };
|
|
689
|
-
|
|
690
|
-
// The bundled classifier covers the common providers (Anthropic, OpenAI,
|
|
691
|
-
// Google, Bedrock, …). Assign it directly, or write your own.
|
|
692
|
-
override classifyChatError = defaultContextOverflowClassifier;
|
|
693
727
|
}
|
|
694
728
|
```
|
|
695
729
|
|
|
696
730
|
**2. Proactive guard — `contextOverflow.proactive`.** Heads off the provider error before it happens. Before each step, Think reads the previous step's model-reported `usage.inputTokens` (provider-agnostic) and, if it crosses `maxInputTokens * (headroom ?? 0.9)`, compacts in place and feeds the recompacted history into the upcoming step. If a provider omits `inputTokens`, it falls back to `usage.totalTokens` (a safe over-approximation — it compacts slightly early rather than missing the threshold). It compacts at most `proactive.maxCompactions` times per turn (default `1`) — independent of the reactive `maxRetries` budget — so a history that cannot shorten does not compact on every step.
|
|
697
731
|
|
|
698
732
|
```typescript
|
|
699
|
-
import { Think
|
|
733
|
+
import { Think } from "@cloudflare/think";
|
|
700
734
|
|
|
701
735
|
export class MyAgent extends Think<Env> {
|
|
702
736
|
override contextOverflow = {
|
|
@@ -704,8 +738,6 @@ export class MyAgent extends Think<Env> {
|
|
|
704
738
|
// Compact mid-turn once a step approaches 90% of a 200K window.
|
|
705
739
|
proactive: { maxInputTokens: 200_000 }
|
|
706
740
|
};
|
|
707
|
-
|
|
708
|
-
override classifyChatError = defaultContextOverflowClassifier;
|
|
709
741
|
}
|
|
710
742
|
```
|
|
711
743
|
|
|
@@ -762,8 +794,8 @@ export class MyAgent extends Think<Env> {
|
|
|
762
794
|
|
|
763
795
|
Use `getScheduledTasks()` when code should create recurring Think turns or
|
|
764
796
|
deterministic scheduled handlers. Think reconciles the declarations on startup,
|
|
765
|
-
|
|
766
|
-
|
|
797
|
+
keeps one pending occurrence per task, and arms the next occurrence after each
|
|
798
|
+
run.
|
|
767
799
|
|
|
768
800
|
```typescript
|
|
769
801
|
import { Think } from "@cloudflare/think";
|
|
@@ -822,36 +854,18 @@ work such as creating a Workflow run or writing a run ledger. Delivery is
|
|
|
822
854
|
at-least-once; use `idempotencyKey` or `occurrenceKey` for your own durable
|
|
823
855
|
idempotency.
|
|
824
856
|
|
|
825
|
-
Declared tasks are armed on the
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
dispatch each occurrence once per live sub-agent on top of the root. Override
|
|
829
|
-
`getScheduledTasksScope()` to return `"all"` when a class genuinely declares
|
|
830
|
-
different tasks per sub-agent — each sub-agent then owns an independent
|
|
831
|
-
schedule.
|
|
832
|
-
|
|
833
|
-
```typescript
|
|
834
|
-
export class PerUserAgent extends Think<Env> {
|
|
835
|
-
getScheduledTasksScope() {
|
|
836
|
-
return "all" as const;
|
|
837
|
-
}
|
|
838
|
-
|
|
839
|
-
async getScheduledTasks(): Promise<ThinkScheduledTasks> {
|
|
840
|
-
const reminder = await this.getReminderForThisUser();
|
|
841
|
-
return reminder ? { reminder } : {};
|
|
842
|
-
}
|
|
843
|
-
}
|
|
844
|
-
```
|
|
857
|
+
Declared tasks are armed on the agent that declares them, a sub-agent
|
|
858
|
+
included: each sub-agent arms its own, and its root wakes it when one is due.
|
|
859
|
+
To run a schedule once for many sub-agents, declare the task on the root.
|
|
845
860
|
|
|
846
|
-
Static declarations reconcile on startup.
|
|
847
|
-
|
|
848
|
-
`
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
occurrences do not block future runs.
|
|
861
|
+
Each task is one durable job holding its next occurrence. Static declarations reconcile on startup. A changed schedule, timezone or
|
|
862
|
+
`retry` re-arms the task from now; a changed prompt, handler or `metadata`
|
|
863
|
+
keeps the pending occurrence. If `getScheduledTasks()` reads product-owned data
|
|
864
|
+
that can change while the Durable Object is live, call
|
|
865
|
+
`internal_reconcileScheduledTasks()` after updating that data. The task `retry`
|
|
866
|
+
option retries the prompt or handler action before the failure goes to
|
|
867
|
+
`onError()`. The next occurrence is still scheduled after the action succeeds
|
|
868
|
+
or exhausts its retries, so failed occurrences do not block future runs.
|
|
855
869
|
|
|
856
870
|
## Fetch tool
|
|
857
871
|
|
|
@@ -905,7 +919,7 @@ You do not need new machinery to gate egress per call: `beforeToolCall` can `blo
|
|
|
905
919
|
|
|
906
920
|
## Session and context
|
|
907
921
|
|
|
908
|
-
Think splits conversation storage from prompt assembly. [`agents/sessions`](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md) stores messages; [
|
|
922
|
+
Think splits conversation storage from prompt assembly. [`agents/sessions`](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md) stores messages; [context](./context.md) builds the system prompt and records on the session what each turn was sent. Think wires both during `onStart`.
|
|
909
923
|
|
|
910
924
|
`configureSession()` configures the default session handle: compaction and search.
|
|
911
925
|
|
|
@@ -946,10 +960,55 @@ export class MyAgent extends Think<Env> {
|
|
|
946
960
|
}
|
|
947
961
|
```
|
|
948
962
|
|
|
949
|
-
A block declared without a `provider` is auto-wired to durable per-agent SQLite, so `memory` above is writable through the `set_context` tool with no extra wiring. The
|
|
963
|
+
A block declared without a `provider` is auto-wired to durable per-agent SQLite, so `memory` above is writable through the `set_context` tool with no extra wiring. The transcript records the system prompt each turn was sent with, so there is nothing to opt into: a cold wake reuses the exact prompt the model already cached. A changed `whenChanged: "remind"` block is delivered once, after the user message of the turn that noticed it, and stays there in later requests. See [Context](./context.md).
|
|
950
964
|
|
|
951
965
|
The assembled blocks are available as `this.context` once the Lifecycle has started.
|
|
952
966
|
|
|
967
|
+
### Upgrading from 0.24
|
|
968
|
+
|
|
969
|
+
- **A tool that finishes after its tab closed keeps its result.** When the browser tab that started a turn closes while a server tool is running, the tool runs to its end and its result is stored. Before, the call was stored as interrupted (an error), although the tool had run. Code that treated such an error as "the tool did not run" now sees the tool's output.
|
|
970
|
+
|
|
971
|
+
- **A recovered turn keeps its request id and ends once.** When Think recovers a turn after a restart, the reply goes on streaming under the request id it started with, and the tab gets one `done` frame for it at the end. Before, the tab saw the request end as aborted and the recovered reply arrive under a new request id. If your app has its own WebSocket client, do not wait for a new request id after a recovery: keep listening on the original one until its `done` frame.
|
|
972
|
+
|
|
973
|
+
- **A continued reply is one message.** When a reply goes on after a client tool result, an approval or a durable pause's outcome, the rest is added to the same assistant message; it used to start a second one, and a client tool's continuation moved into it when the turn ended. A UI that counts messages or keys on their ids sees one message per reply. Conversations stored before the upgrade keep their two messages and still render.
|
|
974
|
+
|
|
975
|
+
- **A waiting submission reads `pending`.** A submission accepted while another turn runs reads `pending` until its own turn starts, as [Programmatic submissions](./programmatic-submissions.md) says. Before, it read `running` from the moment Think picked it up, also while it still waited. Code that treats `running` as "the model is being asked" is now right; `onSubmissionStatus` for one cancelled while it waited reports `pending`, then `aborted`.
|
|
976
|
+
|
|
977
|
+
- **`cancelSubmission()` says what the submission wrote.** `messagesApplied` is `false` for a submission cancelled before it stored anything, also when a message with the same id was already in the conversation. Before, a message that was already there counted. If you retry on `messagesApplied: false`, that retry now happens in this case too.
|
|
978
|
+
|
|
979
|
+
- **A submission ends when its recovery hook throws.** If `onChatRecovery` throws while Think recovers a submission's turn after a restart, the submission ends `error`. Before, it stayed `running` for good. A caller waiting on it gets an answer.
|
|
980
|
+
|
|
981
|
+
- **A reply streaming during the upgrade continues.** If a reply was streaming when your agent was upgraded, Think keeps the text already streamed and continues the reply under the same request id (a submission's reply: under its submission id): at once for a chat turn, and, when the turn was a submission, after a wait of the same length as a redeploy of the previous release takes (seconds to under a minute for an ordinary reply, in our runs).
|
|
982
|
+
|
|
983
|
+
- **A tab that returns after a reply ended in an error is sent the stored messages.** They hold the partial reply; the error follows. Before, the reply's chunks were replayed first. The screen is the same. A client of your own that rebuilt the reply from replayed chunks reads it from the message list instead.
|
|
984
|
+
|
|
985
|
+
- **`continueLastTurn()` leaves a waiting call waiting.** While the latest reply waits on a client tool result or an approval, `continueLastTurn()` changes nothing and returns `{ status: "skipped", reason: "awaiting-client" }`; the client's answer starts the continuation. Before, it called the model again and the waiting call ended as an error. If you called it to move such a reply on, answer or reject the call instead.
|
|
986
|
+
|
|
987
|
+
- **`this.context` is a `Context`.** It takes every call it took before (`getBlock`, `setBlock`, `appendToBlock`, `addBlock`, `removeBlock`, `reminder`, `freezeSystemPrompt`, `refreshSystemPrompt`, `tools`). If your code names its type, write `Context` where it says `ContextBlocks`; both come from `agents/context`. Nothing else changes.
|
|
988
|
+
|
|
989
|
+
- **`recovery: "rerun"` is new.** A server tool whose call a restart cut off is not run again, as before: the call is stored as an error and the model is told it was interrupted. A tool that is safe to repeat can now opt into running again; see [A server tool that a restart cut off](#a-server-tool-a-restart-cut-off).
|
|
990
|
+
|
|
991
|
+
- **Rate limits and provider outages are retried.** Think reads a provider's 429, 408, 5xx or 529 itself and retries the turn within the `chatRecovery` budget, honouring `Retry-After` up to 60 s. Before, such a turn ended with the error unless `classifyChatError` named it. To fail one at once, return `"fatal"` for it from `classifyChatError`.
|
|
992
|
+
|
|
993
|
+
- **`saveMessages()` on a turn that stalls.** It resolves when recovery has finished the reply, with how it ended. Before, it resolved `aborted` at the stall while recovery went on to finish the reply.
|
|
994
|
+
|
|
995
|
+
- **A request delivered twice while its reply streams is answered once.** Before, it was answered twice.
|
|
996
|
+
|
|
997
|
+
- **An old durable pause is dropped.** A durable pause that has waited for its approval longer than `actionPendingApprovalTtlMs` (30 days by default) is dropped when the agent starts; 0.24 kept it across a restart. Set it to `false` to keep them. See [Actions](./actions.md).
|
|
998
|
+
- **A workflow is told after a reset.** An agent reset (not a deploy) in the middle of a `ThinkWorkflow` `step.prompt()` turn no longer leaves the workflow waiting: the turn finishes after the reset and the workflow is told. A workflow 0.24 already left waiting this way is not repaired by the upgrade.
|
|
999
|
+
- **An approval sent while the reply still streams is kept.** An approval or a denial sent while the reply that asked for it is still streaming is kept when the agent restarts before that reply is stored. On 0.24 it was lost: the call went back to waiting for approval, or sometimes ended as an error, and the tool never ran.
|
|
1000
|
+
- **The current AI SDK 7.x releases.** Think's Workers and React tests pass on `ai` 7.0.188 and `@ai-sdk/react` 4.0.193 (the newest when this was measured); its recorded messenger replays were not run on them. On them 0.24 left a paused `execute` execution `input-available` after an approval or a rejection, and `chat()` client tools failed over RPC. Both work on this release.
|
|
1001
|
+
|
|
1002
|
+
#### What the upgrade costs
|
|
1003
|
+
|
|
1004
|
+
An agent's first start after the upgrade carries the previous release's rows over once.
|
|
1005
|
+
|
|
1006
|
+
Afterwards the agent's storage is what an agent created on this release has, except that three of the previous release's tables stay, empty: `cf_agents_runs`, `cf_agents_fibers` and `cf_agents_facet_runs`. In a sub-agent, more of the previous release's tables stay.
|
|
1007
|
+
|
|
1008
|
+
#### Rolling back
|
|
1009
|
+
|
|
1010
|
+
Rolling back to the previous release (`agents` 0.34, `@cloudflare/ai-chat` 0.12, `@cloudflare/think` 0.24) after this one has run is not supported.
|
|
1011
|
+
|
|
953
1012
|
### Upgrading from 0.17
|
|
954
1013
|
|
|
955
1014
|
A subclass written against 0.17 keeps compiling and running. `configureSession(session)` still accepts the `withContext()` / `withCachedPrompt()` chain, and `this.session` still carries the context methods (`addContext`, `getContextBlock`, `replaceContextBlock`, `refreshSystemPrompt`, `freezeSystemPrompt`, `tools()`), which now forward to `this.context`. They are deprecated; move blocks into `configureContext()` and read `this.context` at your own pace. Blocks from both hooks are merged, `configureContext()` first.
|
|
@@ -967,7 +1026,7 @@ Think's `this.messages` getter reads directly from the Session tree. Compaction
|
|
|
967
1026
|
|
|
968
1027
|
### Message storage
|
|
969
1028
|
|
|
970
|
-
Sessions stores MESSAGES; it is not a file store. A message rides in one SQLite row until its serialized JSON exceeds the
|
|
1029
|
+
Sessions stores MESSAGES; it is not a file store. A message rides in one SQLite row until its serialized JSON exceeds the 7.9 MB row budget; a message larger than that is split across continuation rows and reassembled on read, byte for byte. Nothing is truncated and no message is too large to store, so there is no size error to handle and nothing to configure. Splitting never reclaims database space — the continuation rows live in the same Durable Object as the message — and Sessions imposes no upper bound on a single message, so a Durable Object's 10 GB ceiling is the real bound on how much one conversation can hold and bounding untrusted input is the application's job. Files belong in the Workspace; put a reference to one in the message. This is a storage detail: it is invisible to the model, and it is unrelated to media eviction.
|
|
971
1030
|
|
|
972
1031
|
### Media eviction
|
|
973
1032
|
|
|
@@ -987,7 +1046,7 @@ Startup hydration reads a recent window bounded by `hydrationByteBudget` (32 MiB
|
|
|
987
1046
|
|
|
988
1047
|
### Prompt caching
|
|
989
1048
|
|
|
990
|
-
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
|
|
1049
|
+
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 transcript records the system prompt and every context change where it was delivered, 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:
|
|
991
1050
|
|
|
992
1051
|
| Mechanism | What it rewrites | How often the prefix changes |
|
|
993
1052
|
| -------------------- | ---------------------------------------------------------------------------------- | ------------------------------------------- |
|
|
@@ -1041,7 +1100,7 @@ Think's workspace is a `Workspace` from [`@cloudflare/computer`](https://github.
|
|
|
1041
1100
|
- Image and PDF reads stored by the old `read` tool replay as an error asking the model to read the file again.
|
|
1042
1101
|
- Agent Skills (`agents/skills`) accept only a Computer Workspace, for both `skills.workspace()` and `skills.runner({ workspaceInstance })`. Relative paths in skill scripts resolve against `/workspace`.
|
|
1043
1102
|
|
|
1044
|
-
Files a Shell Workspace stored are not moved. [Migrating to `@cloudflare/computer`](
|
|
1103
|
+
Files a Shell Workspace stored are not moved. [Migrating to `@cloudflare/computer`](https://github.com/cloudflare/agents/blob/main/docs/shell/migrating-to-computer.md) documents both storage schemas and a copy script.
|
|
1045
1104
|
|
|
1046
1105
|
## Dependencies
|
|
1047
1106
|
|
|
@@ -1070,6 +1129,7 @@ The Agent Skills parser, sources, and script runner live in
|
|
|
1070
1129
|
- [Getting Started](./getting-started.md) — Build a Think agent step by step
|
|
1071
1130
|
- [Lifecycle Hooks](./lifecycle-hooks.md) — `beforeTurn`, `beforeStep`, `onStepFinish`, `onChunk`, `onChatResponse`, and more
|
|
1072
1131
|
- [Tools](./tools.md) — Workspace tools, code execution, extensions
|
|
1132
|
+
- [Context](./context.md) — Context blocks, memory, and what the model is sent (experimental)
|
|
1073
1133
|
- [Actions](./actions.md) — Server actions with idempotency, approvals, authorization, and reply attachments
|
|
1074
1134
|
- [Channels](./channels.md) — Per-channel policy, channel selection, and out-of-band notices
|
|
1075
1135
|
- [Messengers](./messengers.md) — Chat SDK messenger ingress and delivery
|
package/docs/lifecycle-hooks.md
CHANGED
|
@@ -128,7 +128,7 @@ export class MyAgent extends Think<Env> {
|
|
|
128
128
|
|
|
129
129
|
A block declared without a `provider` is auto-wired to durable per-agent SQLite, so `memory` above is writable through the `set_context` tool with no extra wiring. When context blocks are configured, Think builds the system prompt from an overridden `getSystemPrompt()` followed by those blocks. Think's default `getSystemPrompt()` is only used when there are no blocks. The frozen system prompt is always persisted, so a cold wake reuses the exact prompt string the model already cached.
|
|
130
130
|
|
|
131
|
-
The assembled blocks are available as `this.context` once the Lifecycle has started. See
|
|
131
|
+
The assembled blocks are available as `this.context` once the Lifecycle has started. See [Context](./context.md) for providers, tools, and what the model is sent.
|
|
132
132
|
|
|
133
133
|
---
|
|
134
134
|
|
|
@@ -578,7 +578,6 @@ beforeToolCall(ctx: ToolCallContext): ToolCallDecision | void {
|
|
|
578
578
|
### Notes & limitations
|
|
579
579
|
|
|
580
580
|
- **Substituted input is not re-validated.** The AI SDK validates the model's emitted input against the tool's `inputSchema` _before_ `execute` runs. When `beforeToolCall` returns `{ action: "allow", input: ... }`, that substituted input is passed straight through to `execute` without going through the schema again. If you substitute, ensure the shape stays valid for the tool you're calling.
|
|
581
|
-
- **`stepNumber` is `undefined` in `ToolCallContext`.** The AI SDK's `ToolExecutionOptions` doesn't expose the current step index. The same field _is_ populated on `ToolCallResultContext` (sourced from `experimental_onToolCallFinish`).
|
|
582
581
|
- **Throwing from `beforeToolCall`** propagates as a tool error — the AI SDK records it in the same way it would record an `execute` failure, and `afterToolCall` fires with `success: false, error: ...`.
|
|
583
582
|
- **Streaming tools (AsyncIterable returns).** The AI SDK supports tools whose `execute` returns `AsyncIterable<output>` to emit preliminary results before a final value. The canonical form is an async generator (`async function* execute(...) { … }`). Think preserves preliminary streaming for that form even through `beforeToolCall`: each yielded value reaches the model as a `preliminary` tool-result, and the last as the final value. The non-canonical `async function execute(...) { return makeIter(); }` form returns a `Promise<AsyncIterable>`, which does not stream even in the raw AI SDK — Think collapses it to the last yielded value. Use an `async function*` `execute` if you need preliminary streaming.
|
|
584
583
|
- **Blocking/substituting an `async function*` tool emits one `preliminary` chunk.** To keep an `async function*` tool streaming through `beforeToolCall`, its wrapper must commit to an `AsyncIterable` shape synchronously — before the (async) decision is known. The AI SDK turns every value sent through that iterable into a `preliminary` tool-result plus a `final`, so a `block`/`substitute` outcome surfaces one extra `preliminary: true` chunk to observers like `onChunk` (a scalar-`execute` tool never does). The model-visible final output is identical and correct; this only affects observation hooks for the narrow case of blocking/substituting a streaming tool, and it matches how any streaming tool that emits a single value already behaves.
|
|
@@ -684,7 +683,7 @@ onStepFinish(ctx: StepContext) {
|
|
|
684
683
|
console.log(
|
|
685
684
|
`Step ${ctx.stepNumber} (${ctx.finishReason}): ` +
|
|
686
685
|
`${ctx.usage.inputTokens}in/${ctx.usage.outputTokens}out, ` +
|
|
687
|
-
`${ctx.usage.
|
|
686
|
+
`${ctx.usage.inputTokenDetails?.cacheReadTokens ?? 0} cached`
|
|
688
687
|
);
|
|
689
688
|
}
|
|
690
689
|
```
|
|
@@ -697,7 +696,9 @@ onStepFinish(ctx: StepContext) {
|
|
|
697
696
|
this.env.LOGS.writeDataPoint({ blobs: ["reasoning", ctx.reasoningText] });
|
|
698
697
|
}
|
|
699
698
|
for (const source of ctx.sources) {
|
|
700
|
-
|
|
699
|
+
// A source is a URL or a document; only the first has `url`.
|
|
700
|
+
if (source.sourceType !== "url") continue;
|
|
701
|
+
this.env.LOGS.writeDataPoint({ blobs: ["source", source.url] });
|
|
701
702
|
}
|
|
702
703
|
}
|
|
703
704
|
```
|
|
@@ -874,9 +875,9 @@ classifyChatError(error: unknown, ctx?: ChatErrorContext): ChatErrorClassificati
|
|
|
874
875
|
|
|
875
876
|
- `"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
877
|
- `"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"
|
|
878
|
+
- `"fatal"` and `"unknown"` keep the existing terminal behavior. `void` (the default) lets Think read the provider's error itself, as described below.
|
|
878
879
|
|
|
879
|
-
|
|
880
|
+
When `classifyChatError` returns nothing (or is not overridden), Think reads the provider's error itself: a context-window error (OpenAI `context_length_exceeded`, Anthropic "prompt is too long", and the other common providers' wording) is `"context_overflow"`, an HTTP 429 is `"rate_limit"`, and a 408, 5xx or 529 is `"transient"`. The `agents/models` errors, AI SDK `APICallError`s and any error with an HTTP status are read this way. Your override always wins. To stop Think from retrying such an error (a 429 you want to fail at once, for example), return `"fatal"` for it.
|
|
880
881
|
|
|
881
882
|
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.)
|
|
882
883
|
|
|
@@ -884,27 +885,15 @@ The second argument is a [`ChatErrorContext`](#onchaterror): when consulted for
|
|
|
884
885
|
|
|
885
886
|
### Example
|
|
886
887
|
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
```typescript
|
|
890
|
-
import { Think, defaultContextOverflowClassifier } from "@cloudflare/think";
|
|
891
|
-
|
|
892
|
-
export class MyAgent extends Think<Env> {
|
|
893
|
-
override classifyChatError = defaultContextOverflowClassifier;
|
|
894
|
-
}
|
|
895
|
-
```
|
|
896
|
-
|
|
897
|
-
Or write your own, optionally delegating to the bundled classifier:
|
|
888
|
+
Think already reads the common providers' errors, so override this only for errors it does not know. Return nothing to fall back to Think's own reading:
|
|
898
889
|
|
|
899
890
|
```typescript
|
|
900
891
|
import type { ChatErrorClassification } from "@cloudflare/think";
|
|
901
|
-
import { defaultContextOverflowClassifier } from "@cloudflare/think";
|
|
902
892
|
|
|
903
893
|
classifyChatError(error: unknown): ChatErrorClassification | void {
|
|
904
|
-
if (error instanceof Error && /
|
|
905
|
-
return "
|
|
894
|
+
if (error instanceof Error && /quota exhausted/i.test(error.message)) {
|
|
895
|
+
return "fatal";
|
|
906
896
|
}
|
|
907
|
-
return defaultContextOverflowClassifier(error);
|
|
908
897
|
}
|
|
909
898
|
```
|
|
910
899
|
|
package/docs/multi-chat.md
CHANGED
|
@@ -75,7 +75,8 @@ sub-agent management, `onBeforeSubAgent`, `addMcpServer()`, `setState()`, and
|
|
|
75
75
|
|
|
76
76
|
```typescript
|
|
77
77
|
import { callable } from "agents";
|
|
78
|
-
import { Think
|
|
78
|
+
import { Think } from "@cloudflare/think";
|
|
79
|
+
import { Workspace } from "@cloudflare/computer";
|
|
79
80
|
import { nanoid } from "nanoid";
|
|
80
81
|
import { MyAssistant } from "./agents/my-assistant/agent";
|
|
81
82
|
|
|
@@ -518,10 +519,9 @@ export class AssistantDirectory extends Think<Env, DirectoryState> {
|
|
|
518
519
|
message, which runs a normal durable turn in that chat. Like `recordChatTurn()`,
|
|
519
520
|
it is not `@callable()`.
|
|
520
521
|
|
|
521
|
-
Declared scheduled tasks run
|
|
522
|
-
on the chat class
|
|
523
|
-
|
|
524
|
-
directory.
|
|
522
|
+
Declared scheduled tasks also run in a chat that is a sub-agent: a
|
|
523
|
+
`getScheduledTasks()` on the chat class arms them in each chat. Keep
|
|
524
|
+
cross-chat schedules on the directory, so they run once.
|
|
525
525
|
|
|
526
526
|
See [Scheduled Tasks](./index.md#scheduled-tasks) for the schedule syntax.
|
|
527
527
|
|
|
@@ -56,14 +56,14 @@ The array must contain at least one message.
|
|
|
56
56
|
|
|
57
57
|
## Statuses
|
|
58
58
|
|
|
59
|
-
| Status | Meaning
|
|
60
|
-
| ----------- |
|
|
61
|
-
| `pending` | Accepted and waiting for its turn
|
|
62
|
-
| `running` | Claimed by the agent and executing
|
|
63
|
-
| `completed` | The Think turn completed successfully
|
|
64
|
-
| `aborted` | The submission was cancelled
|
|
65
|
-
| `skipped` | Turn state was reset before
|
|
66
|
-
| `error` | Execution failed or recovery was unsafe
|
|
59
|
+
| Status | Meaning |
|
|
60
|
+
| ----------- | --------------------------------------- |
|
|
61
|
+
| `pending` | Accepted and waiting for its turn |
|
|
62
|
+
| `running` | Claimed by the agent and executing |
|
|
63
|
+
| `completed` | The Think turn completed successfully |
|
|
64
|
+
| `aborted` | The submission was cancelled |
|
|
65
|
+
| `skipped` | Turn state was reset before it finished |
|
|
66
|
+
| `error` | Execution failed or recovery was unsafe |
|
|
67
67
|
|
|
68
68
|
## Idempotent retries
|
|
69
69
|
|
|
@@ -168,8 +168,26 @@ If you cancel a submission before its messages have been applied, including one
|
|
|
168
168
|
that has been claimed but is still waiting for its turn, those messages are not
|
|
169
169
|
persisted to the conversation.
|
|
170
170
|
|
|
171
|
-
If the chat is cleared or turn state is reset
|
|
172
|
-
|
|
171
|
+
If the chat is cleared or turn state is reset, every submission that has not
|
|
172
|
+
finished is marked `skipped`.
|
|
173
|
+
|
|
174
|
+
If the isolate resets while one submission runs and others are pending, the
|
|
175
|
+
running one's turn is recovered first. The pending submissions run after that
|
|
176
|
+
recovery settles, in order, each with its own reply, and a submission accepted
|
|
177
|
+
after the reset runs after them.
|
|
178
|
+
|
|
179
|
+
A restart that cuts off `onSubmissionStatus` for a finished
|
|
180
|
+
submission runs it again for that status, so write the hook so that a repeat
|
|
181
|
+
is harmless. The workflow
|
|
182
|
+
event of a workflow submission is sent once either way.
|
|
183
|
+
|
|
184
|
+
A submission whose run is interrupted by a restart runs again, at most three
|
|
185
|
+
times in all. After the third interrupted run it ends `error` with
|
|
186
|
+
`Interrupted 3 times`.
|
|
187
|
+
|
|
188
|
+
Client requests sent over a WebSocket get the same treatment: a waiting
|
|
189
|
+
request's messages join the Session when its turn starts. See
|
|
190
|
+
[Requests waiting behind an interrupted turn](https://github.com/cloudflare/agents/blob/main/docs/agents/chat-agents.md#requests-waiting-behind-an-interrupted-turn).
|
|
173
191
|
|
|
174
192
|
## Compared with `saveMessages`
|
|
175
193
|
|