@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.
Files changed (43) hide show
  1. package/README.md +18 -26
  2. package/dist/{chat-sdk-BEjKXjCm.js → chat-sdk-4Nu96eDX.js} +375 -256
  3. package/dist/chat-sdk-4Nu96eDX.js.map +1 -0
  4. package/dist/extensions/index.d.ts +30 -72
  5. package/dist/extensions/index.js +45 -47
  6. package/dist/extensions/index.js.map +1 -1
  7. package/dist/{fetch-DO3uQ9py.js → fetch-BbYxtlff.js} +10 -2
  8. package/dist/fetch-BbYxtlff.js.map +1 -0
  9. package/dist/manager-B3rcb_6p.js +493 -0
  10. package/dist/manager-B3rcb_6p.js.map +1 -0
  11. package/dist/manager-CWGumyKi.d.ts +3391 -0
  12. package/dist/messengers/index.d.ts +54 -66
  13. package/dist/messengers/index.js +2 -2
  14. package/dist/messengers/telegram.d.ts +4 -4
  15. package/dist/messengers/telegram.js +1 -1
  16. package/dist/think.d.ts +2 -2
  17. package/dist/think.js +8493 -10759
  18. package/dist/think.js.map +1 -1
  19. package/dist/tools/extensions.d.ts +1 -1
  20. package/dist/tools/extensions.js +1 -1
  21. package/dist/tools/fetch.js +1 -1
  22. package/dist/workflows.d.ts +5 -2
  23. package/docs/actions.md +12 -0
  24. package/docs/channels.md +10 -4
  25. package/docs/client-tools.md +57 -27
  26. package/docs/context.md +92 -0
  27. package/docs/getting-started.md +2 -2
  28. package/docs/index.md +109 -49
  29. package/docs/lifecycle-hooks.md +10 -21
  30. package/docs/multi-chat.md +5 -5
  31. package/docs/programmatic-submissions.md +28 -10
  32. package/docs/sub-agents.md +45 -51
  33. package/docs/tools.md +31 -3
  34. package/docs/workflows.md +4 -3
  35. package/package.json +13 -8
  36. package/dist/chat-sdk-BEjKXjCm.js.map +0 -1
  37. package/dist/fetch-DO3uQ9py.js.map +0 -1
  38. package/dist/hook-proxy-DY2sBNa0.js +0 -117
  39. package/dist/hook-proxy-DY2sBNa0.js.map +0 -1
  40. package/dist/index-DIQ9oY1t.d.ts +0 -5864
  41. package/dist/manager-CtXhU1fK.d.ts +0 -243
  42. package/dist/manager-sfWIcYJT.js +0 -333
  43. package/dist/manager-sfWIcYJT.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { t as ExtensionManager } from "../manager-CtXhU1fK.js";
1
+ import { t as ExtensionManager } from "../manager-CWGumyKi.js";
2
2
  import { ToolSet } from "ai";
3
3
 
4
4
  //#region src/tools/extensions.d.ts
@@ -1,4 +1,4 @@
1
- import { n as sanitizeName } from "../manager-sfWIcYJT.js";
1
+ import { c as sanitizeName } from "../manager-B3rcb_6p.js";
2
2
  import { tool } from "ai";
3
3
  import { z } from "zod";
4
4
  //#region src/tools/extensions.ts
@@ -1,2 +1,2 @@
1
- import { t as createFetchTools } from "../fetch-DO3uQ9py.js";
1
+ import { t as createFetchTools } from "../fetch-BbYxtlff.js";
2
2
  export { createFetchTools };
@@ -1,6 +1,9 @@
1
- import { Tn as ThinkSubmissionStatus, gn as Think } from "./index-DIQ9oY1t.js";
2
- import { ZodObject, z } from "zod";
1
+ import {
2
+ un as Think,
3
+ wn as ThinkSubmissionStatus
4
+ } from "./manager-CWGumyKi.js";
3
5
  import { WorkflowEvent, WorkflowSleepDuration } from "cloudflare:workers";
6
+ import { ZodObject, z } from "zod";
4
7
  import {
5
8
  AgentWorkflow,
6
9
  AgentWorkflowStep,
package/docs/actions.md CHANGED
@@ -186,6 +186,14 @@ await agent.rejectExecution(executionId, "Stop here", { autoContinue: false });
186
186
 
187
187
  The rejection is still recorded in the transcript, so the next user message
188
188
  continues the conversation with it in view.
189
+
190
+ If `getActions()` no longer returns the action when the approval is taken,
191
+ `execute` does not run: the approval is consumed and the call is answered with
192
+ an error that says the action is no longer registered. The action is looked up
193
+ each time Think tries the approved call: when the approval is taken, and again
194
+ if a restart interrupts the call and it is tried again. An action you withdraw
195
+ while a try is already running still runs to its end.
196
+
189
197
  `pendingApprovals()` merges parked actions and paused Codemode executions, so a
190
198
  single approval UI can drive both. (`durable-pause` requires an `approval`
191
199
  policy — an action that would never park is rejected at definition time.)
@@ -205,6 +213,10 @@ removal are applied before the next model call. A client that resubmits an
205
213
  older copy of the message, still showing the paused output, does not restore
206
214
  the paused output or the removed text.
207
215
 
216
+ A durable pause that has waited for its approval longer than
217
+ `actionPendingApprovalTtlMs` (30 days by default) is dropped when the agent
218
+ starts; 0.24 kept it across a restart. Set it to `false` to keep them.
219
+
208
220
  Both approval-gated and durable-pause parts carry a stable
209
221
  `ActionApprovalDescriptor` (`{ requestId, toolCallId, action, summary, input,
210
222
  permissions, risk, kind }`) so your UI has everything it needs to render the
package/docs/channels.md CHANGED
@@ -22,11 +22,11 @@ Override `configureChannels()` to return a map of channel id to
22
22
  `ChannelDefinition`. The id is how you select the channel on a turn:
23
23
 
24
24
  ```typescript
25
- import { Think, messengerChannel } from "@cloudflare/think";
26
- import { telegram } from "@chat-adapter/telegram";
25
+ import { Think, messengerChannel, type ThinkChannels } from "@cloudflare/think";
26
+ import { telegramMessenger } from "@cloudflare/think/messengers/telegram";
27
27
 
28
28
  export class Assistant extends Think<Env> {
29
- configureChannels() {
29
+ configureChannels(): ThinkChannels {
30
30
  return {
31
31
  // Override policy for the built-in web channel.
32
32
  web: {
@@ -42,7 +42,13 @@ export class Assistant extends Think<Env> {
42
42
  maxTurns: 3
43
43
  },
44
44
  // A messenger channel (Chat SDK webhook).
45
- telegram: messengerChannel(telegram({/* adapter config */}))
45
+ telegram: messengerChannel(
46
+ telegramMessenger({
47
+ token: this.env.TELEGRAM_BOT_TOKEN,
48
+ userName: "support_bot",
49
+ secretToken: this.env.TELEGRAM_WEBHOOK_SECRET_TOKEN
50
+ })
51
+ )
46
52
  };
47
53
  }
48
54
  }
@@ -14,31 +14,44 @@ Client tools are tools without an `execute` function on the server — they only
14
14
 
15
15
  ## Defining Client Tools
16
16
 
17
- On the client, pass `clientTools` to `useAgentChat`:
17
+ On the client, pass the tools to `useAgentChat` as `tools`, and run them in `onToolCall`. The hook sends the schema of each tool that has an `execute` with every request. When the model calls one, `onToolCall` runs it and sends its output back with `addToolOutput`:
18
18
 
19
19
  ```tsx
20
20
  import { useAgent } from "agents/react";
21
21
  import { useAgentChat } from "@cloudflare/think/react";
22
22
 
23
+ const tools = {
24
+ getUserTimezone: {
25
+ description: "Get the user's timezone from their browser",
26
+ parameters: { type: "object" as const, properties: {} },
27
+ execute: async () => Intl.DateTimeFormat().resolvedOptions().timeZone
28
+ },
29
+ getUserLanguage: {
30
+ description: "Get the language the user's browser is set to",
31
+ parameters: { type: "object" as const, properties: {} },
32
+ execute: async () => navigator.language
33
+ }
34
+ };
35
+
23
36
  function Chat() {
24
37
  const agent = useAgent({ agent: "MyAgent" });
25
38
  const { messages, sendMessage } = useAgentChat({
26
39
  agent,
27
- clientTools: {
28
- getUserTimezone: {
29
- description: "Get the user's timezone from their browser",
30
- parameters: {},
31
- execute: async () => {
32
- return Intl.DateTimeFormat().resolvedOptions().timeZone;
33
- }
34
- },
35
- getClipboard: {
36
- description: "Read text from the user's clipboard",
37
- parameters: {},
38
- execute: async () => {
39
- return navigator.clipboard.readText();
40
- }
40
+ tools,
41
+ onToolCall: async ({ toolCall, addToolOutput }) => {
42
+ const tool = tools[toolCall.toolName as keyof typeof tools];
43
+ if (!tool) {
44
+ addToolOutput({
45
+ toolCallId: toolCall.toolCallId,
46
+ state: "output-error",
47
+ errorText: `No client tool named ${toolCall.toolName}`
48
+ });
49
+ return;
41
50
  }
51
+ addToolOutput({
52
+ toolCallId: toolCall.toolCallId,
53
+ output: await tool.execute()
54
+ });
42
55
  }
43
56
  });
44
57
 
@@ -46,7 +59,7 @@ function Chat() {
46
59
  }
47
60
  ```
48
61
 
49
- The `parameters` field is a JSON Schema object describing the tool's input. The `execute` function runs in the browser.
62
+ The `parameters` field is a JSON Schema object describing the tool's input. A tool in `tools` without an `execute` is not sent. A tool the server declares in `getTools()` without an `execute` still reaches the client: its calls come to `onToolCall` the same way. `useAgentChat` does not run `execute` by itself: `onToolCall` must answer every call, with an output or an error, or the turn waits for a result.
50
63
 
51
64
  ## Client Tools over the Sub-Agent RPC `chat()` Path
52
65
 
@@ -125,26 +138,41 @@ When `needsApproval` returns `true`:
125
138
 
126
139
  ### Handling approvals on the client
127
140
 
128
- `useAgentChat` provides approval helpers:
141
+ A tool call that waits for approval is a tool part in the `approval-requested` state. Render your approval UI from it, and answer with `addToolApprovalResponse`, passing the part's approval id:
129
142
 
130
143
  ```tsx
131
- const { messages, sendMessage, addToolResult } = useAgentChat({
132
- agent,
133
- onToolCall: ({ toolCall }) => {
134
- // Auto-approve safe tools
135
- if (toolCall.toolName === "read") {
136
- return { approve: true };
137
- }
138
- // Others go through the UI approval flow
139
- }
144
+ const { messages, sendMessage, addToolApprovalResponse } = useAgentChat({
145
+ agent
140
146
  });
147
+
148
+ // In the render of a tool part:
149
+ if (part.state === "approval-requested") {
150
+ return (
151
+ <>
152
+ <button
153
+ onClick={() =>
154
+ addToolApprovalResponse({ id: part.approval.id, approved: true })
155
+ }
156
+ >
157
+ Approve
158
+ </button>
159
+ <button
160
+ onClick={() =>
161
+ addToolApprovalResponse({ id: part.approval.id, approved: false })
162
+ }
163
+ >
164
+ Deny
165
+ </button>
166
+ </>
167
+ );
168
+ }
141
169
  ```
142
170
 
143
171
  See [Client Tools Continuation](https://github.com/cloudflare/agents/blob/main/docs/agents/client-tools-continuation.md) for the full protocol reference.
144
172
 
145
173
  ## Auto-Continuation
146
174
 
147
- After a client tool result is received, Think can automatically continue the conversation without a new user message. This is the default behavior — when all pending tool results are received, Think starts a new model turn with the tool results in context.
175
+ After a client tool result is received, Think can automatically continue the conversation without a new user message. This is the default behavior — when all pending tool results are received, Think starts a new model turn with the tool results in context. A result sent with `state: "output-error"` does not ask for that continuation itself: when it is the only result, it is stored and the turn does not continue; when another result in the same batch asks to continue, the turn continues with both.
148
176
 
149
177
  The continuation turn has `continuation: true` in the `TurnContext`, which you can use in `beforeTurn` to adjust model or tool selection:
150
178
 
@@ -183,6 +211,8 @@ export class MyAgent extends Think<Env> {
183
211
  | `"drop"` | Ignore overlapping submits entirely. Messages are not persisted. |
184
212
  | `{ strategy: "debounce", debounceMs?: number }` | Trailing-edge latest with a quiet window (default 750ms). |
185
213
 
214
+ A message that arrives while a turn runs waits until its own turn starts before it is stored in the Session, as a child of the reply it waited behind. Each turn answers its own message: the conversation reads `U1, A1, U2, A2`, and the model never sees a question queued behind the turn it is answering. Every tab sees the waiting message at once: the message list Think sends ends with it and names it in `queuedMessageIds`, and `useAgentChat` draws it after the reply that is streaming. A superseded message under `"latest"`, `"merge"` or `"debounce"`, or a message whose request is stopped while it waits, is stored when its turn would have started. A clear drops it.
215
+
186
216
  Concurrency strategies only apply to `submit-message` requests. Regenerations, tool continuations, approvals, clears, `saveMessages`, durable `submitMessages` submissions, and `continueLastTurn` keep their serialized behavior.
187
217
 
188
218
  ### Examples
@@ -0,0 +1,92 @@
1
+ # Context
2
+
3
+ > **Experimental.** Think's context API may change between releases while it stabilizes.
4
+
5
+ Context is how a Think agent arranges its system prompt and keeps data the model reads and writes across turns: who the agent is, what it has learned about the user, a knowledge base it can search. You declare it as labelled blocks. Think renders the blocks into the system prompt, gives the model tools for the blocks it can change, and records on the session what each turn was sent, so a long conversation keeps hitting the model provider's prompt cache.
6
+
7
+ The [session](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md) is the transcript: messages, branches, compaction. Context sits beside it. It never changes a message, and the transcript never holds the prompt text.
8
+
9
+ ## Declare blocks
10
+
11
+ ```ts
12
+ import { Think } from "@cloudflare/think";
13
+ import type { ContextConfig } from "agents/context";
14
+
15
+ export class MyAgent extends Think<Env> {
16
+ configureContext(): ContextConfig[] {
17
+ return [
18
+ {
19
+ label: "soul",
20
+ provider: { get: async () => "You are a helpful coding assistant." }
21
+ },
22
+ {
23
+ label: "memory",
24
+ description: "Facts learned about the user",
25
+ maxTokens: 1_100
26
+ },
27
+ {
28
+ label: "environment",
29
+ provider: {
30
+ get: async () => `Today is ${new Date().toISOString().slice(0, 10)}.`
31
+ },
32
+ whenChanged: "remind"
33
+ }
34
+ ];
35
+ }
36
+ }
37
+ ```
38
+
39
+ Each block renders as a section of the system prompt with a header: the label, the description, how much of `maxTokens` it uses, and whether the model can change it (`[readonly]`, `[writable]`, `[searchable]`). An empty read-only block is left out.
40
+
41
+ What a block can do depends on its provider:
42
+
43
+ | Provider | The block is |
44
+ | ---------------------- | ------------------------------------------------ |
45
+ | none | writable, stored in the agent's SQLite |
46
+ | `get()` | read-only text |
47
+ | `get()` and `set()` | writable, stored wherever your provider keeps it |
48
+ | `get()` and `search()` | a summary in the prompt, searched through a tool |
49
+
50
+ The model writes a writable block with the `set_context` tool and searches a searchable one with `search_context`. `AgentSearchProvider` from `agents/context` is a searchable block backed by full-text search in the agent's SQLite.
51
+
52
+ Blocks can also come from the `withContext()` chain in `configureSession()`; those render after the ones `configureContext()` returns.
53
+
54
+ ## What the model is sent
55
+
56
+ The first turn renders every block and records that exact prompt on the session. Every later turn opens with the same text, so the provider can reuse the cached prefix.
57
+
58
+ When the model writes a block with `set_context`, the block is saved at once and the prompt stays as it is: the tool call and its result in the conversation are the model's record of the write, so nothing sends it again. The prompt is rebuilt from the blocks at the first turn after a compaction, when the cached prefix is gone anyway, and a change the model did not make (a write from your code, or a `whenChanged: "remind"` block whose value moved on) is sent once, after the next user message.
59
+
60
+ A block declared `whenChanged: "remind"` is for values that move on while the conversation runs: the date, the state of a workspace. When its value changes, the next turn sends the new value once, after that turn's user message, and records it there. Every later request shows it in the same place, so nothing already sent is rewritten. A value that changes in an ordinary block's provider, without a write through `this.context`, reaches the model at the next rebuild.
61
+
62
+ `this.context.refreshSystemPrompt()` renders the blocks again; the next turn records the new prompt. That costs one prompt-cache miss, so Think does it where the cache is already gone: after a compaction and after the history is cleared. A refresh survives the agent being evicted before its next turn.
63
+
64
+ A regenerated answer is sent the prompt its own branch was sent, never a newer one. A turn that is recovered or retried after being cut off is sent again exactly as it was first sent; a change or a refresh that arrived in between waits for the next user message.
65
+
66
+ A compaction summary is written from the stored messages, which never hold a reminder. A request after a compaction that cannot rebuild the prompt (a continuation of the last answer) restates, once and right after the summary, a value the hidden turns delivered. A forked session keeps the prompt and reminders its copied turns were sent with.
67
+
68
+ ## Change blocks from code
69
+
70
+ `this.context` is available inside your agent class once the agent has started:
71
+
72
+ ```ts
73
+ await this.context.setBlock("memory", "Prefers TypeScript.");
74
+ await this.context.appendToBlock("memory", "Deploys on Fridays.");
75
+ this.context.getBlock("memory")?.content;
76
+
77
+ await this.context.addBlock({ label: "project", provider: projectBrief });
78
+ this.context.removeBlock("project");
79
+ await this.context.refreshSystemPrompt();
80
+ ```
81
+
82
+ A block written with `setBlock()` or `appendToBlock()` reaches the model once, after the next user message, and stays there. If a request goes out before that message (a continuation of an answer, or a regenerated one), the value also rides on that request, so the model is not working from the old one; that copy is not kept. Added and removed blocks enter or leave the prompt at the next rebuild: after a compaction, or a refresh.
83
+
84
+ ## What changed
85
+
86
+ If you used `agents/context` directly before this release:
87
+
88
+ - `freezeSystemPrompt()`, `refreshSystemPrompt()` and `reminder()` moved from `ContextBlocks` to `Context`, Think's context bound to a session. `ContextBlocks` keeps the blocks and their tools, and no longer takes a prompt store; `renderSystemPrompt()` renders the blocks as they stand.
89
+ - Think's `this.context` is a `Context`. The methods you called on it keep their names and signatures.
90
+ - An agent upgraded from an earlier release keeps the prompt it last froze: its first turn opens with exactly that text, and an answer from before the upgrade is regenerated with it. A remind block that changed since is sent once on that turn. A conversation started after the upgrade, or after the chat is cleared, does not use it.
91
+ - Think no longer writes a `_system_prompt` row; each prompt it records lives on the session.
92
+ - A store passed to `withCachedPrompt(provider)` is no longer written. It is only read, for the prompt frozen before the upgrade, which the turns from before the upgrade are sent until the chat is cleared. A store that throws or holds nothing is treated as having no prompt.
@@ -233,7 +233,7 @@ Now the model sees a `MEMORY` section in its system prompt and gets a `set_conte
233
233
 
234
234
  When you declare context blocks, the system prompt is built from those blocks, with an overridden `getSystemPrompt()` at the top. The `"soul"` block above acts as the system identity: it is read-only and always appears first. The `"memory"` block is writable, and the model updates it when it learns something useful. The frozen system prompt is always persisted, so a cold wake reuses the exact prompt string the model already cached.
235
235
 
236
- The assembled blocks are available as `this.context` once the Lifecycle has started. See the [Context documentation](https://github.com/cloudflare/agents/blob/main/docs/agents/context.md) for providers, tools, and frozen-prompt behavior, and the [Sessions documentation](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md) for compaction, search, and multi-session support.
236
+ 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, and the [Sessions documentation](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md) for compaction, search, and multi-session support.
237
237
 
238
238
  ## 7. Add custom tools
239
239
 
@@ -315,5 +315,5 @@ See [Lifecycle Hooks](./lifecycle-hooks.md) for the full reference.
315
315
  - [Tools](./tools.md) — workspace tools, code execution, extensions
316
316
  - [Client Tools](./client-tools.md) — browser-side tools, approval flows, concurrency
317
317
  - [Sub-agents and Programmatic Turns](./sub-agents.md) — RPC streaming, scheduled turns, recovery
318
- - [Context](https://github.com/cloudflare/agents/blob/main/docs/agents/context.md) — context blocks, providers, prompt assembly
318
+ - [Context](./context.md) — context blocks, providers, what the model is sent
319
319
  - [Sessions](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md) — compaction, search, attachments, multi-session