@cloudflare/think 0.10.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -17
- package/dist/{chat-sdk-Bb93yaZh.js → chat-sdk-D6cUghsQ.js} +33 -8
- package/dist/chat-sdk-D6cUghsQ.js.map +1 -0
- package/dist/cli/index.js +224 -55
- package/dist/cli/index.js.map +1 -1
- package/dist/{codegen-CuPdJRpV.js → codegen-DlA2QQuU.js} +6 -38
- package/dist/codegen-DlA2QQuU.js.map +1 -0
- package/dist/{config-D512sQYg.d.ts → config-CD7hqncK.d.ts} +5 -5
- package/dist/extensions/index.js +1 -1
- package/dist/framework/index.d.ts +17 -62
- package/dist/framework/index.js +3 -57
- package/dist/{think-i1Pkgb1R.d.ts → index-D_S5mETO.d.ts} +1587 -702
- package/dist/{manager-BPndMP_6.js → manager-CSk5htym.js} +7 -7
- package/dist/{manager-BPndMP_6.js.map → manager-CSk5htym.js.map} +1 -1
- package/dist/{manifest-CpB-xngB.d.ts → manifest-DK5HuGga.d.ts} +16 -18
- package/dist/messengers/index.d.ts +59 -55
- package/dist/messengers/index.js +2 -2
- package/dist/messengers/telegram.d.ts +4 -4
- package/dist/messengers/telegram.js +1 -1
- package/dist/react.d.ts +79 -0
- package/dist/react.js +28 -0
- package/dist/react.js.map +1 -0
- package/dist/server-entry.d.ts +1 -1
- package/dist/server-entry.js +1 -1
- package/dist/server-entry.js.map +1 -1
- package/dist/studio/assets/{angular-html-z-TUogET.js → angular-html-D27LthTc.js} +1 -1
- package/dist/studio/assets/{angular-ts-DMGuEVeg.js → angular-ts-DtNL2gQ7.js} +1 -1
- package/dist/studio/assets/{apl-KvrEROqd.js → apl-BgEcDqM0.js} +1 -1
- package/dist/studio/assets/{astro-Bm_woEti.js → astro-CstbRF9e.js} +1 -1
- package/dist/studio/assets/{blade-BdCF3r89.js → blade-CLG-7epG.js} +1 -1
- package/dist/studio/assets/{c-CDqDtkvZ.js → c-CssQqwxO.js} +1 -1
- package/dist/studio/assets/{cobol-CeFM1vZz.js → cobol-CjmzHCjg.js} +1 -1
- package/dist/studio/assets/{coffee-2ed6LBym.js → coffee-B_rqYPkp.js} +1 -1
- package/dist/studio/assets/{cpp-Dj3nX0J4.js → cpp-5YyZJlb7.js} +1 -1
- package/dist/studio/assets/{crystal-BsIYZMQ3.js → crystal-D7uKze0i.js} +1 -1
- package/dist/studio/assets/{css-B48fnuoH.js → css-k9oPgg7G.js} +1 -1
- package/dist/studio/assets/{edge-C7qt1aza.js → edge-CGgsSt0x.js} +1 -1
- package/dist/studio/assets/{elixir-CiTmwoQ3.js → elixir-BX_d5Evo.js} +1 -1
- package/dist/studio/assets/{elm-exDZ-PRY.js → elm-DENxDm5e.js} +1 -1
- package/dist/studio/assets/{erb-3fmfgt-Q.js → erb-DvYOup03.js} +1 -1
- package/dist/studio/assets/{git-rebase-75I-C7zW.js → git-rebase-BsAdTS5A.js} +1 -1
- package/dist/studio/assets/{glimmer-js-JjRzYRv8.js → glimmer-js-e0h98Z67.js} +1 -1
- package/dist/studio/assets/{glimmer-ts-DcC_g6bi.js → glimmer-ts-C9s5Kv8m.js} +1 -1
- package/dist/studio/assets/{glsl-CHo__hpu.js → glsl-CCiyeTRs.js} +1 -1
- package/dist/studio/assets/{graphql-J3cHpSdo.js → graphql-BRtHwsqk.js} +1 -1
- package/dist/studio/assets/{hack-or1FCnPg.js → hack-Dnt0QXHh.js} +1 -1
- package/dist/studio/assets/{haml-uv3vtlo6.js → haml-EXGmzuB1.js} +1 -1
- package/dist/studio/assets/{handlebars--xrOP0sp.js → handlebars-CzyBIDJE.js} +1 -1
- package/dist/studio/assets/{highlighted-body-OFNGDK62-D5UBAw6b.js → highlighted-body-OFNGDK62-CQUFKLNu.js} +1 -1
- package/dist/studio/assets/{html-CWnTqWKh.js → html-BAT8b_VM.js} +1 -1
- package/dist/studio/assets/{html-derivative-DWyLco-z.js → html-derivative-7tkS-r6F.js} +1 -1
- package/dist/studio/assets/{http-BGB8mLqf.js → http-Cgka02Qq.js} +1 -1
- package/dist/studio/assets/{hurl-BWdvIVUG.js → hurl-Cbkh8WEw.js} +1 -1
- package/dist/studio/assets/index-D6n8vpkp.js +390 -0
- package/dist/studio/assets/index-DkGWw6ES.css +2 -0
- package/dist/studio/assets/{java-BqyrPpKF.js → java-DrRKiUno.js} +1 -1
- package/dist/studio/assets/{javascript-D8Aej0xg.js → javascript-9LAnHOxD.js} +1 -1
- package/dist/studio/assets/{jinja-SIORrXov.js → jinja-CqRt4prs.js} +1 -1
- package/dist/studio/assets/{jison-B2T4v51n.js → jison-BX-IOQpJ.js} +1 -1
- package/dist/studio/assets/{json-BFdVRj9r.js → json-dOrE-En8.js} +1 -1
- package/dist/studio/assets/{jsx-w4r1xieS.js → jsx-BSTPfqWX.js} +1 -1
- package/dist/studio/assets/{julia-BFBtDmmM.js → julia-Dvz-BPmf.js} +1 -1
- package/dist/studio/assets/{just-CjAPsU_y.js → just-BHQm0Atq.js} +1 -1
- package/dist/studio/assets/{latex-CghDKqKz.js → latex-CxdhxuXv.js} +1 -1
- package/dist/studio/assets/{liquid-Cp9loVkE.js → liquid-D-hM-Q_F.js} +1 -1
- package/dist/studio/assets/{lua-HNnIDxnY.js → lua-5qtqjLHq.js} +1 -1
- package/dist/studio/assets/{marko-BXT10Apm.js → marko-5FJaM2co.js} +1 -1
- package/dist/studio/assets/{mdc-CaiOz4_A.js → mdc-BhYW7lCG.js} +1 -1
- package/dist/studio/assets/mermaid-GHXKKRXX-CWM2EB-u.js +1 -0
- package/dist/studio/assets/{nginx-DgYZ5SY9.js → nginx-rtAXrRye.js} +1 -1
- package/dist/studio/assets/{nim-CAMVX-MV.js → nim-DQSmaN9U.js} +1 -1
- package/dist/studio/assets/{perl-Dc6Wp7SD.js → perl-B54AdcaE.js} +1 -1
- package/dist/studio/assets/{php-DgLi8LNU.js → php-DpvTxCny.js} +1 -1
- package/dist/studio/assets/{pug-ZHFv4Vgd.js → pug-Cyffw0Ho.js} +1 -1
- package/dist/studio/assets/{qml-DU62cSZp.js → qml-CxRetSkO.js} +1 -1
- package/dist/studio/assets/{r-BwU69RSh.js → r-CXWRxrXc.js} +1 -1
- package/dist/studio/assets/{razor-BUgi_XZM.js → razor-BJzI-zc9.js} +1 -1
- package/dist/studio/assets/{regexp-DuNhqfkW.js → regexp-dqxdfrnE.js} +1 -1
- package/dist/studio/assets/{rst-BB3BeaSy.js → rst-BW7eKYj4.js} +1 -1
- package/dist/studio/assets/{ruby-T0tkEfUZ.js → ruby-D5Npyj8-.js} +1 -1
- package/dist/studio/assets/{sas-CMhZa3S0.js → sas-DZLppjul.js} +1 -1
- package/dist/studio/assets/{scss-DtXjZ3vZ.js → scss-CbqoxyAe.js} +1 -1
- package/dist/studio/assets/{shellscript-BESt-FLs.js → shellscript-CFHqBeXu.js} +1 -1
- package/dist/studio/assets/{shellsession-8irtvYxL.js → shellsession-CbZDA4Bf.js} +1 -1
- package/dist/studio/assets/{soy-CIvhOgLR.js → soy-PImjtV58.js} +1 -1
- package/dist/studio/assets/{sql-obAOXh1G.js → sql-DhGo8urW.js} +1 -1
- package/dist/studio/assets/{stata-D3OCK8xW.js → stata-CjHWbU2v.js} +1 -1
- package/dist/studio/assets/{surrealql-Dk_bguB0.js → surrealql-o8Qr4t56.js} +1 -1
- package/dist/studio/assets/{svelte-C0-KQt-t.js → svelte-DlSIyEV1.js} +1 -1
- package/dist/studio/assets/{templ-lg4nvF9H.js → templ-qizfwU1w.js} +1 -1
- package/dist/studio/assets/{tex-BNcQSX7R.js → tex-Ca7T661H.js} +1 -1
- package/dist/studio/assets/{ts-tags-AgW9jVv0.js → ts-tags-DUmjLkgl.js} +1 -1
- package/dist/studio/assets/{tsx-CL8XyR3d.js → tsx-CfwgIqHW.js} +1 -1
- package/dist/studio/assets/{twig-VkSbsH0Y.js → twig-D7NAYUBY.js} +1 -1
- package/dist/studio/assets/{typescript-BfD1znAG.js → typescript-Bbz9oX-P.js} +1 -1
- package/dist/studio/assets/{vue-html-w3sbjuft.js → vue-html-CcxTb_Jn.js} +1 -1
- package/dist/studio/assets/{vue-gv_2i8Vk.js → vue-vYpz06zQ.js} +1 -1
- package/dist/studio/assets/{vue-vine-C9sgcRlL.js → vue-vine-DW4RqCKF.js} +1 -1
- package/dist/studio/assets/{xml-nNPxMKnG.js → xml-R4LZ_u4f.js} +1 -1
- package/dist/studio/assets/{xsl-C7iHP36x.js → xsl-CS-xzp3L.js} +1 -1
- package/dist/studio/assets/{yaml-Cq3YaG6o.js → yaml-CqDWbYXd.js} +1 -1
- package/dist/studio/index.html +2 -2
- package/dist/think.d.ts +2 -2
- package/dist/think.js +8292 -2
- package/dist/think.js.map +1 -0
- package/dist/tools/extensions.js +1 -1
- package/dist/tools/workspace.js +2 -2
- package/dist/tools/workspace.js.map +1 -1
- package/dist/{types-codegen-B6c5KpYH.js → types-codegen-C-9yeFao.js} +9 -33
- package/dist/types-codegen-C-9yeFao.js.map +1 -0
- package/dist/vite.d.ts +5 -5
- package/dist/vite.js +1 -1
- package/dist/workflows.d.ts +1 -1
- package/docs/actions.md +297 -0
- package/docs/channels.md +185 -0
- package/docs/client-tools.md +233 -0
- package/docs/getting-started.md +314 -0
- package/docs/index.md +1272 -0
- package/docs/lifecycle-hooks.md +839 -0
- package/docs/messengers.md +197 -0
- package/docs/programmatic-submissions.md +206 -0
- package/docs/sub-agents.md +520 -0
- package/docs/tools.md +582 -0
- package/docs/workflows.md +217 -0
- package/package.json +46 -17
- package/dist/chat-sdk-Bb93yaZh.js.map +0 -1
- package/dist/codegen-CuPdJRpV.js.map +0 -1
- package/dist/framework/index.js.map +0 -1
- package/dist/studio/assets/index-Cbb3GlZY.js +0 -496
- package/dist/studio/assets/index-DN9_cL01.css +0 -2
- package/dist/studio/assets/mermaid-GHXKKRXX-I2ZcYo7k.js +0 -1
- package/dist/think-BYZXQ-vm.js +0 -6513
- package/dist/think-BYZXQ-vm.js.map +0 -1
- package/dist/types-codegen-B6c5KpYH.js.map +0 -1
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
# Client Tools
|
|
2
|
+
|
|
3
|
+
Think supports tools that execute in the browser. The client sends tool schemas in the chat request body, Think merges them with server tools, and when the LLM calls a client tool, the call is routed to the client for execution.
|
|
4
|
+
|
|
5
|
+
## How Client Tools Work
|
|
6
|
+
|
|
7
|
+
1. The client sends tool schemas as part of the chat request body
|
|
8
|
+
2. Think merges client tools with server-side tools (workspace, `getTools()`, session, MCP)
|
|
9
|
+
3. The LLM calls a client tool — the tool call chunk is sent to the client over WebSocket
|
|
10
|
+
4. The client executes the tool and sends back a `CF_AGENT_TOOL_RESULT` message
|
|
11
|
+
5. Think persists the result, broadcasts `CF_AGENT_MESSAGE_UPDATED`, and optionally auto-continues
|
|
12
|
+
|
|
13
|
+
Client tools are tools without an `execute` function on the server — they only have a schema. When the LLM produces a tool call for one of these, Think sends the call to the client instead of executing it server-side.
|
|
14
|
+
|
|
15
|
+
## Defining Client Tools
|
|
16
|
+
|
|
17
|
+
On the client, pass `clientTools` to `useAgentChat`:
|
|
18
|
+
|
|
19
|
+
```tsx
|
|
20
|
+
import { useAgent } from "agents/react";
|
|
21
|
+
import { useAgentChat } from "@cloudflare/think/react";
|
|
22
|
+
|
|
23
|
+
function Chat() {
|
|
24
|
+
const agent = useAgent({ agent: "MyAgent" });
|
|
25
|
+
const { messages, sendMessage } = useAgentChat({
|
|
26
|
+
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
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
// ... render chat UI
|
|
46
|
+
}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
The `parameters` field is a JSON Schema object describing the tool's input. The `execute` function runs in the browser.
|
|
50
|
+
|
|
51
|
+
## Client Tools over the Sub-Agent RPC `chat()` Path
|
|
52
|
+
|
|
53
|
+
When a parent agent delegates to a Think sub-agent over RPC with `chat()` (rather than the browser WebSocket), there is no WebSocket to carry `clientTools` or to send tool results back. Pass them through `ChatOptions` instead:
|
|
54
|
+
|
|
55
|
+
```typescript
|
|
56
|
+
await child.chat(message, callback, {
|
|
57
|
+
signal,
|
|
58
|
+
clientTools: [
|
|
59
|
+
{
|
|
60
|
+
name: "get_user_timezone",
|
|
61
|
+
description: "Get the caller's timezone",
|
|
62
|
+
parameters: { type: "object" }
|
|
63
|
+
}
|
|
64
|
+
],
|
|
65
|
+
onClientToolCall: async ({ toolName, input }) => {
|
|
66
|
+
// Run the client tool wherever the parent can — return its output.
|
|
67
|
+
return runClientTool(toolName, input);
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
- `clientTools` registers the tool schemas for the turn, exactly like the WebSocket `clientTools` field.
|
|
73
|
+
- `onClientToolCall` executes a client-tool call and returns its output. The model can call a client tool, receive the result, and continue — all within the single `chat()` call.
|
|
74
|
+
|
|
75
|
+
If you omit `onClientToolCall`, the tools are registered but have no result: the model's call is surfaced through the stream callback and the turn ends with a dangling tool call (the RPC stream callback has no inbound result channel of its own). Supply `onClientToolCall` whenever you want the round trip to complete.
|
|
76
|
+
|
|
77
|
+
### Behavior notes
|
|
78
|
+
|
|
79
|
+
- **Recovery:** neither the schemas nor the `onClientToolCall` executor are persisted — they are per-turn only. The executor is a live RPC reference that dies with the isolate, and (unlike the WebSocket path) there is no SPA to replay a `tool-result` after an eviction. So if an eviction interrupts the turn while a client-tool call is mid-flight, chat recovery treats the orphaned call like a server tool: `continueLastTurn`'s transcript repair errors it and the model proceeds. (Persisting the schemas would instead make recovery mistake the orphan for a pending human interaction and park forever.) To re-run cleanly, the parent re-invokes `chat()` with the `clientTools` and `onClientToolCall` again.
|
|
80
|
+
- **Errors:** if `onClientToolCall` throws, the failure is surfaced to the model as a tool error (`output-error`) and the turn continues — it does not crash the turn.
|
|
81
|
+
- **Serialization:** the value returned from `onClientToolCall` becomes the tool output, so it must be JSON-serializable (it travels back over RPC and into the model context).
|
|
82
|
+
- **No approval gate:** RPC client tools execute immediately through `onClientToolCall`. The WebSocket approval flow (`needsApproval`) does not apply on this path — gate execution inside your executor if you need it.
|
|
83
|
+
- **Name precedence:** client tools are merged after server tools, so a client tool that shares a name with a server tool (for example a workspace tool) overrides it for that turn — the same as the WebSocket path.
|
|
84
|
+
- **Abort:** aborting the turn via `signal` stops the loop, but an in-flight `onClientToolCall` is not itself cancelled; the turn ends after the current call resolves.
|
|
85
|
+
|
|
86
|
+
## Tool Approval
|
|
87
|
+
|
|
88
|
+
Tools can require user approval before execution. This works for both server-side and client-side tools.
|
|
89
|
+
|
|
90
|
+
### Server-side approval
|
|
91
|
+
|
|
92
|
+
Use `needsApproval` in the tool definition:
|
|
93
|
+
|
|
94
|
+
```typescript
|
|
95
|
+
getTools(): ToolSet {
|
|
96
|
+
return {
|
|
97
|
+
calculate: tool({
|
|
98
|
+
description: "Perform a calculation",
|
|
99
|
+
inputSchema: z.object({
|
|
100
|
+
a: z.number(),
|
|
101
|
+
b: z.number(),
|
|
102
|
+
operator: z.enum(["+", "-", "*", "/"])
|
|
103
|
+
}),
|
|
104
|
+
needsApproval: async ({ a, b }) =>
|
|
105
|
+
Math.abs(a) > 1000 || Math.abs(b) > 1000,
|
|
106
|
+
execute: async ({ a, b, operator }) => {
|
|
107
|
+
const ops: Record<string, (x: number, y: number) => number> = {
|
|
108
|
+
"+": (x, y) => x + y, "-": (x, y) => x - y,
|
|
109
|
+
"*": (x, y) => x * y, "/": (x, y) => x / y
|
|
110
|
+
};
|
|
111
|
+
return { result: ops[operator](a, b) };
|
|
112
|
+
}
|
|
113
|
+
})
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
When `needsApproval` returns `true`:
|
|
119
|
+
|
|
120
|
+
1. Think sends the tool call to the client with a pending approval state
|
|
121
|
+
2. The conversation pauses
|
|
122
|
+
3. The client shows an approval UI and sends `CF_AGENT_TOOL_APPROVAL` (approve or deny)
|
|
123
|
+
4. If approved, the tool executes and the conversation continues
|
|
124
|
+
5. If denied, the denial reason is returned to the model as the tool result
|
|
125
|
+
|
|
126
|
+
### Handling approvals on the client
|
|
127
|
+
|
|
128
|
+
`useAgentChat` provides approval helpers:
|
|
129
|
+
|
|
130
|
+
```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
|
+
}
|
|
140
|
+
});
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
See [Client Tools Continuation](https://github.com/cloudflare/agents/blob/main/docs/agents/client-tools-continuation.md) for the full protocol reference.
|
|
144
|
+
|
|
145
|
+
## Auto-Continuation
|
|
146
|
+
|
|
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.
|
|
148
|
+
|
|
149
|
+
The continuation turn has `continuation: true` in the `TurnContext`, which you can use in `beforeTurn` to adjust model or tool selection:
|
|
150
|
+
|
|
151
|
+
```typescript
|
|
152
|
+
beforeTurn(ctx: TurnContext) {
|
|
153
|
+
if (ctx.continuation) {
|
|
154
|
+
return { model: this.cheapModel };
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
## Message Concurrency
|
|
160
|
+
|
|
161
|
+
The `messageConcurrency` property controls how overlapping user submits behave when a chat turn is already active.
|
|
162
|
+
|
|
163
|
+
```typescript
|
|
164
|
+
import { Think } from "@cloudflare/think";
|
|
165
|
+
import type { MessageConcurrency } from "@cloudflare/think";
|
|
166
|
+
|
|
167
|
+
export class MyAgent extends Think<Env> {
|
|
168
|
+
override messageConcurrency: MessageConcurrency = "queue"; // default
|
|
169
|
+
|
|
170
|
+
getModel() {
|
|
171
|
+
/* ... */
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
### Strategies
|
|
177
|
+
|
|
178
|
+
| Strategy | Behavior |
|
|
179
|
+
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
|
|
180
|
+
| `"queue"` | Queue every submit and process them in order. Default. |
|
|
181
|
+
| `"latest"` | Keep only the latest overlapping submit. Superseded submits still persist their user messages but do not start their own model turn. |
|
|
182
|
+
| `"merge"` | Like `"latest"`, but all overlapping user messages remain in the conversation history. The model sees them all in one turn. |
|
|
183
|
+
| `"drop"` | Ignore overlapping submits entirely. Messages are not persisted. |
|
|
184
|
+
| `{ strategy: "debounce", debounceMs?: number }` | Trailing-edge latest with a quiet window (default 750ms). |
|
|
185
|
+
|
|
186
|
+
Concurrency strategies only apply to `submit-message` requests. Regenerations, tool continuations, approvals, clears, `saveMessages`, durable `submitMessages` submissions, and `continueLastTurn` keep their serialized behavior.
|
|
187
|
+
|
|
188
|
+
### Examples
|
|
189
|
+
|
|
190
|
+
For a search-as-you-type UI where each keystroke sends a new query:
|
|
191
|
+
|
|
192
|
+
```typescript
|
|
193
|
+
export class SearchAgent extends Think<Env> {
|
|
194
|
+
override messageConcurrency: MessageConcurrency = "latest";
|
|
195
|
+
getModel() {
|
|
196
|
+
/* ... */
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
For a collaborative editor where multiple users type simultaneously:
|
|
202
|
+
|
|
203
|
+
```typescript
|
|
204
|
+
export class CollabAgent extends Think<Env> {
|
|
205
|
+
override messageConcurrency: MessageConcurrency = "merge";
|
|
206
|
+
getModel() {
|
|
207
|
+
/* ... */
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
For a debounced input where the model only responds after the user stops typing:
|
|
213
|
+
|
|
214
|
+
```typescript
|
|
215
|
+
export class DebouncedAgent extends Think<Env> {
|
|
216
|
+
override messageConcurrency: MessageConcurrency = {
|
|
217
|
+
strategy: "debounce",
|
|
218
|
+
debounceMs: 1000
|
|
219
|
+
};
|
|
220
|
+
getModel() {
|
|
221
|
+
/* ... */
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
## Multi-Tab Broadcast
|
|
227
|
+
|
|
228
|
+
Think broadcasts streaming responses to all connected WebSocket clients. When multiple browser tabs are connected to the same agent:
|
|
229
|
+
|
|
230
|
+
- All tabs see the streamed response in real time
|
|
231
|
+
- Tool call states (pending, result, approval) are broadcast to all tabs
|
|
232
|
+
- The tab that resumes a stream is excluded from the broadcast to avoid duplicates
|
|
233
|
+
- `CF_AGENT_MESSAGE_UPDATED` events are sent to all tabs after tool results and message persistence
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
# Getting Started with Think
|
|
2
|
+
|
|
3
|
+
Build a chat agent with persistent memory, built-in file tools, and streaming — step by step.
|
|
4
|
+
|
|
5
|
+
By the end of this tutorial you will have a Think agent that:
|
|
6
|
+
|
|
7
|
+
- Streams responses to a React chat UI
|
|
8
|
+
- Has persistent memory the model can read and write
|
|
9
|
+
- Includes workspace file tools (read, write, edit, find, grep, delete)
|
|
10
|
+
- Supports custom server-side tools
|
|
11
|
+
|
|
12
|
+
## Prerequisites
|
|
13
|
+
|
|
14
|
+
- Node.js 24+
|
|
15
|
+
- A Cloudflare account with Workers AI access
|
|
16
|
+
- Familiarity with TypeScript and Cloudflare Workers
|
|
17
|
+
|
|
18
|
+
## 1. Create a project
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
mkdir my-think-agent && cd my-think-agent
|
|
22
|
+
npm init -y
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Install dependencies:
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
npm install @cloudflare/think agents ai @cloudflare/shell zod workers-ai-provider react react-dom
|
|
29
|
+
npm install -D wrangler @cloudflare/vite-plugin @cloudflare/workers-types @vitejs/plugin-react @tailwindcss/vite tailwindcss typescript vite
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## 2. Configure wrangler
|
|
33
|
+
|
|
34
|
+
Create `wrangler.jsonc`:
|
|
35
|
+
|
|
36
|
+
```jsonc
|
|
37
|
+
{
|
|
38
|
+
"name": "my-think-agent",
|
|
39
|
+
"compatibility_date": "2026-01-28",
|
|
40
|
+
"compatibility_flags": ["nodejs_compat"],
|
|
41
|
+
"ai": { "binding": "AI" },
|
|
42
|
+
"assets": {
|
|
43
|
+
"not_found_handling": "single-page-application",
|
|
44
|
+
"run_worker_first": ["/agents/*"]
|
|
45
|
+
},
|
|
46
|
+
"durable_objects": {
|
|
47
|
+
"bindings": [{ "class_name": "MyAgent", "name": "MyAgent" }]
|
|
48
|
+
},
|
|
49
|
+
"migrations": [{ "new_sqlite_classes": ["MyAgent"], "tag": "v1" }],
|
|
50
|
+
"main": "src/server.ts"
|
|
51
|
+
}
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Create `vite.config.ts`:
|
|
55
|
+
|
|
56
|
+
```typescript
|
|
57
|
+
import { cloudflare } from "@cloudflare/vite-plugin";
|
|
58
|
+
import tailwindcss from "@tailwindcss/vite";
|
|
59
|
+
import react from "@vitejs/plugin-react";
|
|
60
|
+
import { defineConfig } from "vite";
|
|
61
|
+
|
|
62
|
+
export default defineConfig({
|
|
63
|
+
plugins: [react(), cloudflare(), tailwindcss()]
|
|
64
|
+
});
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Create `tsconfig.json`:
|
|
68
|
+
|
|
69
|
+
```json
|
|
70
|
+
{
|
|
71
|
+
"extends": "agents/tsconfig"
|
|
72
|
+
}
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## 3. Define the agent
|
|
76
|
+
|
|
77
|
+
Create `src/server.ts`:
|
|
78
|
+
|
|
79
|
+
```typescript
|
|
80
|
+
import { Think } from "@cloudflare/think";
|
|
81
|
+
import { createWorkersAI } from "workers-ai-provider";
|
|
82
|
+
import { routeAgentRequest } from "agents";
|
|
83
|
+
|
|
84
|
+
export class MyAgent extends Think<Env> {
|
|
85
|
+
getModel() {
|
|
86
|
+
return createWorkersAI({ binding: this.env.AI })(
|
|
87
|
+
"@cf/moonshotai/kimi-k2.7-code"
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
getSystemPrompt() {
|
|
92
|
+
return "You are a helpful assistant with access to a workspace filesystem.";
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export default {
|
|
97
|
+
async fetch(request: Request, env: Env) {
|
|
98
|
+
return (
|
|
99
|
+
(await routeAgentRequest(request, env)) ||
|
|
100
|
+
new Response("Not found", { status: 404 })
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
} satisfies ExportedHandler<Env>;
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
This is a working agent. Think automatically provides:
|
|
107
|
+
|
|
108
|
+
- WebSocket chat protocol (compatible with `useAgentChat`)
|
|
109
|
+
- Message persistence in SQLite
|
|
110
|
+
- Resumable streaming (page refresh replays buffered chunks)
|
|
111
|
+
- Workspace file tools (read, write, edit, list, find, grep, delete)
|
|
112
|
+
- Abort/cancel support
|
|
113
|
+
- Error handling with partial message persistence
|
|
114
|
+
|
|
115
|
+
## 4. Connect a React client
|
|
116
|
+
|
|
117
|
+
Create `src/client.tsx`:
|
|
118
|
+
|
|
119
|
+
```tsx
|
|
120
|
+
import { createRoot } from "react-dom/client";
|
|
121
|
+
import { useAgent } from "agents/react";
|
|
122
|
+
import { useAgentChat } from "@cloudflare/think/react";
|
|
123
|
+
|
|
124
|
+
function Chat() {
|
|
125
|
+
const agent = useAgent({ agent: "MyAgent" });
|
|
126
|
+
const { messages, sendMessage, status } = useAgentChat({ agent });
|
|
127
|
+
|
|
128
|
+
return (
|
|
129
|
+
<div style={{ maxWidth: 600, margin: "0 auto", padding: 20 }}>
|
|
130
|
+
<h1>Think Agent</h1>
|
|
131
|
+
|
|
132
|
+
<div>
|
|
133
|
+
{messages.map((msg) => (
|
|
134
|
+
<div key={msg.id} style={{ margin: "12px 0" }}>
|
|
135
|
+
<strong>{msg.role}:</strong>{" "}
|
|
136
|
+
{msg.parts.map((part, i) =>
|
|
137
|
+
part.type === "text" ? <span key={i}>{part.text}</span> : null
|
|
138
|
+
)}
|
|
139
|
+
</div>
|
|
140
|
+
))}
|
|
141
|
+
</div>
|
|
142
|
+
|
|
143
|
+
<form
|
|
144
|
+
onSubmit={(e) => {
|
|
145
|
+
e.preventDefault();
|
|
146
|
+
const input = e.currentTarget.elements.namedItem(
|
|
147
|
+
"input"
|
|
148
|
+
) as HTMLInputElement;
|
|
149
|
+
if (!input.value.trim()) return;
|
|
150
|
+
sendMessage({ text: input.value });
|
|
151
|
+
input.value = "";
|
|
152
|
+
}}
|
|
153
|
+
>
|
|
154
|
+
<input
|
|
155
|
+
name="input"
|
|
156
|
+
placeholder="Send a message..."
|
|
157
|
+
style={{ width: "80%", padding: 8 }}
|
|
158
|
+
/>
|
|
159
|
+
<button type="submit" style={{ padding: 8 }}>
|
|
160
|
+
Send
|
|
161
|
+
</button>
|
|
162
|
+
</form>
|
|
163
|
+
|
|
164
|
+
<p style={{ fontSize: 12, color: "#666" }}>Status: {status}</p>
|
|
165
|
+
</div>
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
createRoot(document.getElementById("root")!).render(<Chat />);
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
Create `index.html`:
|
|
173
|
+
|
|
174
|
+
```html
|
|
175
|
+
<!doctype html>
|
|
176
|
+
<html lang="en">
|
|
177
|
+
<head>
|
|
178
|
+
<meta charset="UTF-8" />
|
|
179
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
180
|
+
<title>Think Agent</title>
|
|
181
|
+
</head>
|
|
182
|
+
<body>
|
|
183
|
+
<div id="root"></div>
|
|
184
|
+
<script type="module" src="/src/client.tsx"></script>
|
|
185
|
+
</body>
|
|
186
|
+
</html>
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
## 5. Run it
|
|
190
|
+
|
|
191
|
+
```sh
|
|
192
|
+
npx vite dev
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
Open the browser and send a message. The agent responds with streaming text, and workspace file tools are available to the model automatically.
|
|
196
|
+
|
|
197
|
+
> **`setMessages` is display-only on Think.** Think is server-authoritative — its transcript is a projection of the Session tree, not a flat array the client owns. `useAgentChat` from `@cloudflare/think/react` therefore keeps `setMessages` local to the React view: edits update what's on screen but are **not** persisted and won't survive a refresh or reconnect (the server re-projects the authoritative history). To persist a clear, call `clearHistory()`. If you push a full transcript to Think anyway (for example, by using `@cloudflare/ai-chat/react` against a Think server), the server ignores it and logs a one-time dev warning.
|
|
198
|
+
|
|
199
|
+
## 6. Add persistent memory
|
|
200
|
+
|
|
201
|
+
Override `configureSession` to give the model writable memory that survives restarts:
|
|
202
|
+
|
|
203
|
+
```typescript
|
|
204
|
+
export class MyAgent extends Think<Env> {
|
|
205
|
+
getModel(): LanguageModel {
|
|
206
|
+
return createWorkersAI({ binding: this.env.AI })(
|
|
207
|
+
"@cf/moonshotai/kimi-k2.7-code"
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
configureSession(session: Session) {
|
|
212
|
+
return session
|
|
213
|
+
.withContext("soul", {
|
|
214
|
+
provider: {
|
|
215
|
+
get: async () =>
|
|
216
|
+
"You are a helpful assistant. Remember important facts about the user."
|
|
217
|
+
}
|
|
218
|
+
})
|
|
219
|
+
.withContext("memory", {
|
|
220
|
+
description: "Important facts about the user and conversation.",
|
|
221
|
+
maxTokens: 2000
|
|
222
|
+
})
|
|
223
|
+
.withCachedPrompt();
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
Now the model sees a `MEMORY` section in its system prompt and gets a `set_context` tool to update it. Facts written to memory persist in SQLite and survive DO hibernation and restarts.
|
|
229
|
+
|
|
230
|
+
When you use `configureSession`, the system prompt is built from context blocks rather than `getSystemPrompt()`. 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 proactively updates it when it learns something useful.
|
|
231
|
+
|
|
232
|
+
See the [Sessions documentation](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md) for context blocks, compaction, search, skills, and multi-session support.
|
|
233
|
+
|
|
234
|
+
## 7. Add custom tools
|
|
235
|
+
|
|
236
|
+
Override `getTools()` to add your own tools alongside the built-in workspace tools:
|
|
237
|
+
|
|
238
|
+
```typescript
|
|
239
|
+
import { tool } from "ai";
|
|
240
|
+
import { z } from "zod";
|
|
241
|
+
|
|
242
|
+
export class MyAgent extends Think<Env> {
|
|
243
|
+
getModel(): LanguageModel {
|
|
244
|
+
/* ... */
|
|
245
|
+
}
|
|
246
|
+
configureSession(session: Session) {
|
|
247
|
+
/* ... */
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
getTools(): ToolSet {
|
|
251
|
+
return {
|
|
252
|
+
getWeather: tool({
|
|
253
|
+
description: "Get the current weather for a city",
|
|
254
|
+
inputSchema: z.object({
|
|
255
|
+
city: z.string().describe("City name")
|
|
256
|
+
}),
|
|
257
|
+
execute: async ({ city }) => {
|
|
258
|
+
const res = await fetch(
|
|
259
|
+
`https://api.weatherapi.com/v1/current.json?key=${this.env.WEATHER_KEY}&q=${city}`
|
|
260
|
+
);
|
|
261
|
+
return res.json();
|
|
262
|
+
}
|
|
263
|
+
})
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
Think merges tools from multiple sources automatically. On every turn, the model has access to:
|
|
270
|
+
|
|
271
|
+
1. **Workspace tools** — read, write, edit, list, find, grep, delete (built-in)
|
|
272
|
+
2. **Session tools** — set_context, load_context, search_context (from `configureSession`)
|
|
273
|
+
3. **Your tools** — from `getTools()`
|
|
274
|
+
4. **Skill tools** — activate_skill, read_skill_resource, and optional run_skill_script (from `getSkills()`)
|
|
275
|
+
5. **MCP tools** — from connected MCP servers (if any)
|
|
276
|
+
6. **Client tools** — from the browser (if any)
|
|
277
|
+
|
|
278
|
+
## 8. Add lifecycle hooks
|
|
279
|
+
|
|
280
|
+
Think provides hooks that fire on every turn, regardless of entry path:
|
|
281
|
+
|
|
282
|
+
```typescript
|
|
283
|
+
import type {
|
|
284
|
+
TurnContext,
|
|
285
|
+
TurnConfig,
|
|
286
|
+
ChatResponseResult
|
|
287
|
+
} from "@cloudflare/think";
|
|
288
|
+
|
|
289
|
+
export class MyAgent extends Think<Env> {
|
|
290
|
+
getModel(): LanguageModel {
|
|
291
|
+
/* ... */
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
beforeTurn(ctx: TurnContext): TurnConfig | void {
|
|
295
|
+
console.log(
|
|
296
|
+
`Turn starting: ${Object.keys(ctx.tools).length} tools available`
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
onChatResponse(result: ChatResponseResult) {
|
|
301
|
+
console.log(`Turn ${result.status}: ${result.message.parts.length} parts`);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
See [Lifecycle Hooks](./lifecycle-hooks.md) for the full reference.
|
|
307
|
+
|
|
308
|
+
## Next Steps
|
|
309
|
+
|
|
310
|
+
- [Lifecycle Hooks](./lifecycle-hooks.md) — control model behavior, switch models per-turn, restrict tools
|
|
311
|
+
- [Tools](./tools.md) — workspace tools, code execution, extensions
|
|
312
|
+
- [Client Tools](./client-tools.md) — browser-side tools, approval flows, concurrency
|
|
313
|
+
- [Sub-agents and Programmatic Turns](./sub-agents.md) — RPC streaming, scheduled turns, recovery
|
|
314
|
+
- [Sessions](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md) — context blocks, compaction, search, multi-session
|