@cloudflare/think 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/README.md +10 -17
  2. package/dist/{chat-sdk-Bb93yaZh.js → chat-sdk-D6cUghsQ.js} +33 -8
  3. package/dist/chat-sdk-D6cUghsQ.js.map +1 -0
  4. package/dist/cli/index.js +224 -55
  5. package/dist/cli/index.js.map +1 -1
  6. package/dist/{codegen-CuPdJRpV.js → codegen-DlA2QQuU.js} +6 -38
  7. package/dist/codegen-DlA2QQuU.js.map +1 -0
  8. package/dist/{config-D512sQYg.d.ts → config-CD7hqncK.d.ts} +5 -5
  9. package/dist/extensions/index.js +1 -1
  10. package/dist/framework/index.d.ts +17 -62
  11. package/dist/framework/index.js +3 -57
  12. package/dist/{think-i1Pkgb1R.d.ts → index-D_S5mETO.d.ts} +1587 -702
  13. package/dist/{manager-BPndMP_6.js → manager-CSk5htym.js} +7 -7
  14. package/dist/{manager-BPndMP_6.js.map → manager-CSk5htym.js.map} +1 -1
  15. package/dist/{manifest-CpB-xngB.d.ts → manifest-DK5HuGga.d.ts} +16 -18
  16. package/dist/messengers/index.d.ts +59 -55
  17. package/dist/messengers/index.js +2 -2
  18. package/dist/messengers/telegram.d.ts +4 -4
  19. package/dist/messengers/telegram.js +1 -1
  20. package/dist/react.d.ts +79 -0
  21. package/dist/react.js +28 -0
  22. package/dist/react.js.map +1 -0
  23. package/dist/server-entry.d.ts +1 -1
  24. package/dist/server-entry.js +1 -1
  25. package/dist/server-entry.js.map +1 -1
  26. package/dist/studio/assets/{angular-html-z-TUogET.js → angular-html-D27LthTc.js} +1 -1
  27. package/dist/studio/assets/{angular-ts-DMGuEVeg.js → angular-ts-DtNL2gQ7.js} +1 -1
  28. package/dist/studio/assets/{apl-KvrEROqd.js → apl-BgEcDqM0.js} +1 -1
  29. package/dist/studio/assets/{astro-Bm_woEti.js → astro-CstbRF9e.js} +1 -1
  30. package/dist/studio/assets/{blade-BdCF3r89.js → blade-CLG-7epG.js} +1 -1
  31. package/dist/studio/assets/{c-CDqDtkvZ.js → c-CssQqwxO.js} +1 -1
  32. package/dist/studio/assets/{cobol-CeFM1vZz.js → cobol-CjmzHCjg.js} +1 -1
  33. package/dist/studio/assets/{coffee-2ed6LBym.js → coffee-B_rqYPkp.js} +1 -1
  34. package/dist/studio/assets/{cpp-Dj3nX0J4.js → cpp-5YyZJlb7.js} +1 -1
  35. package/dist/studio/assets/{crystal-BsIYZMQ3.js → crystal-D7uKze0i.js} +1 -1
  36. package/dist/studio/assets/{css-B48fnuoH.js → css-k9oPgg7G.js} +1 -1
  37. package/dist/studio/assets/{edge-C7qt1aza.js → edge-CGgsSt0x.js} +1 -1
  38. package/dist/studio/assets/{elixir-CiTmwoQ3.js → elixir-BX_d5Evo.js} +1 -1
  39. package/dist/studio/assets/{elm-exDZ-PRY.js → elm-DENxDm5e.js} +1 -1
  40. package/dist/studio/assets/{erb-3fmfgt-Q.js → erb-DvYOup03.js} +1 -1
  41. package/dist/studio/assets/{git-rebase-75I-C7zW.js → git-rebase-BsAdTS5A.js} +1 -1
  42. package/dist/studio/assets/{glimmer-js-JjRzYRv8.js → glimmer-js-e0h98Z67.js} +1 -1
  43. package/dist/studio/assets/{glimmer-ts-DcC_g6bi.js → glimmer-ts-C9s5Kv8m.js} +1 -1
  44. package/dist/studio/assets/{glsl-CHo__hpu.js → glsl-CCiyeTRs.js} +1 -1
  45. package/dist/studio/assets/{graphql-J3cHpSdo.js → graphql-BRtHwsqk.js} +1 -1
  46. package/dist/studio/assets/{hack-or1FCnPg.js → hack-Dnt0QXHh.js} +1 -1
  47. package/dist/studio/assets/{haml-uv3vtlo6.js → haml-EXGmzuB1.js} +1 -1
  48. package/dist/studio/assets/{handlebars--xrOP0sp.js → handlebars-CzyBIDJE.js} +1 -1
  49. package/dist/studio/assets/{highlighted-body-OFNGDK62-D5UBAw6b.js → highlighted-body-OFNGDK62-CQUFKLNu.js} +1 -1
  50. package/dist/studio/assets/{html-CWnTqWKh.js → html-BAT8b_VM.js} +1 -1
  51. package/dist/studio/assets/{html-derivative-DWyLco-z.js → html-derivative-7tkS-r6F.js} +1 -1
  52. package/dist/studio/assets/{http-BGB8mLqf.js → http-Cgka02Qq.js} +1 -1
  53. package/dist/studio/assets/{hurl-BWdvIVUG.js → hurl-Cbkh8WEw.js} +1 -1
  54. package/dist/studio/assets/index-D6n8vpkp.js +390 -0
  55. package/dist/studio/assets/index-DkGWw6ES.css +2 -0
  56. package/dist/studio/assets/{java-BqyrPpKF.js → java-DrRKiUno.js} +1 -1
  57. package/dist/studio/assets/{javascript-D8Aej0xg.js → javascript-9LAnHOxD.js} +1 -1
  58. package/dist/studio/assets/{jinja-SIORrXov.js → jinja-CqRt4prs.js} +1 -1
  59. package/dist/studio/assets/{jison-B2T4v51n.js → jison-BX-IOQpJ.js} +1 -1
  60. package/dist/studio/assets/{json-BFdVRj9r.js → json-dOrE-En8.js} +1 -1
  61. package/dist/studio/assets/{jsx-w4r1xieS.js → jsx-BSTPfqWX.js} +1 -1
  62. package/dist/studio/assets/{julia-BFBtDmmM.js → julia-Dvz-BPmf.js} +1 -1
  63. package/dist/studio/assets/{just-CjAPsU_y.js → just-BHQm0Atq.js} +1 -1
  64. package/dist/studio/assets/{latex-CghDKqKz.js → latex-CxdhxuXv.js} +1 -1
  65. package/dist/studio/assets/{liquid-Cp9loVkE.js → liquid-D-hM-Q_F.js} +1 -1
  66. package/dist/studio/assets/{lua-HNnIDxnY.js → lua-5qtqjLHq.js} +1 -1
  67. package/dist/studio/assets/{marko-BXT10Apm.js → marko-5FJaM2co.js} +1 -1
  68. package/dist/studio/assets/{mdc-CaiOz4_A.js → mdc-BhYW7lCG.js} +1 -1
  69. package/dist/studio/assets/mermaid-GHXKKRXX-CWM2EB-u.js +1 -0
  70. package/dist/studio/assets/{nginx-DgYZ5SY9.js → nginx-rtAXrRye.js} +1 -1
  71. package/dist/studio/assets/{nim-CAMVX-MV.js → nim-DQSmaN9U.js} +1 -1
  72. package/dist/studio/assets/{perl-Dc6Wp7SD.js → perl-B54AdcaE.js} +1 -1
  73. package/dist/studio/assets/{php-DgLi8LNU.js → php-DpvTxCny.js} +1 -1
  74. package/dist/studio/assets/{pug-ZHFv4Vgd.js → pug-Cyffw0Ho.js} +1 -1
  75. package/dist/studio/assets/{qml-DU62cSZp.js → qml-CxRetSkO.js} +1 -1
  76. package/dist/studio/assets/{r-BwU69RSh.js → r-CXWRxrXc.js} +1 -1
  77. package/dist/studio/assets/{razor-BUgi_XZM.js → razor-BJzI-zc9.js} +1 -1
  78. package/dist/studio/assets/{regexp-DuNhqfkW.js → regexp-dqxdfrnE.js} +1 -1
  79. package/dist/studio/assets/{rst-BB3BeaSy.js → rst-BW7eKYj4.js} +1 -1
  80. package/dist/studio/assets/{ruby-T0tkEfUZ.js → ruby-D5Npyj8-.js} +1 -1
  81. package/dist/studio/assets/{sas-CMhZa3S0.js → sas-DZLppjul.js} +1 -1
  82. package/dist/studio/assets/{scss-DtXjZ3vZ.js → scss-CbqoxyAe.js} +1 -1
  83. package/dist/studio/assets/{shellscript-BESt-FLs.js → shellscript-CFHqBeXu.js} +1 -1
  84. package/dist/studio/assets/{shellsession-8irtvYxL.js → shellsession-CbZDA4Bf.js} +1 -1
  85. package/dist/studio/assets/{soy-CIvhOgLR.js → soy-PImjtV58.js} +1 -1
  86. package/dist/studio/assets/{sql-obAOXh1G.js → sql-DhGo8urW.js} +1 -1
  87. package/dist/studio/assets/{stata-D3OCK8xW.js → stata-CjHWbU2v.js} +1 -1
  88. package/dist/studio/assets/{surrealql-Dk_bguB0.js → surrealql-o8Qr4t56.js} +1 -1
  89. package/dist/studio/assets/{svelte-C0-KQt-t.js → svelte-DlSIyEV1.js} +1 -1
  90. package/dist/studio/assets/{templ-lg4nvF9H.js → templ-qizfwU1w.js} +1 -1
  91. package/dist/studio/assets/{tex-BNcQSX7R.js → tex-Ca7T661H.js} +1 -1
  92. package/dist/studio/assets/{ts-tags-AgW9jVv0.js → ts-tags-DUmjLkgl.js} +1 -1
  93. package/dist/studio/assets/{tsx-CL8XyR3d.js → tsx-CfwgIqHW.js} +1 -1
  94. package/dist/studio/assets/{twig-VkSbsH0Y.js → twig-D7NAYUBY.js} +1 -1
  95. package/dist/studio/assets/{typescript-BfD1znAG.js → typescript-Bbz9oX-P.js} +1 -1
  96. package/dist/studio/assets/{vue-html-w3sbjuft.js → vue-html-CcxTb_Jn.js} +1 -1
  97. package/dist/studio/assets/{vue-gv_2i8Vk.js → vue-vYpz06zQ.js} +1 -1
  98. package/dist/studio/assets/{vue-vine-C9sgcRlL.js → vue-vine-DW4RqCKF.js} +1 -1
  99. package/dist/studio/assets/{xml-nNPxMKnG.js → xml-R4LZ_u4f.js} +1 -1
  100. package/dist/studio/assets/{xsl-C7iHP36x.js → xsl-CS-xzp3L.js} +1 -1
  101. package/dist/studio/assets/{yaml-Cq3YaG6o.js → yaml-CqDWbYXd.js} +1 -1
  102. package/dist/studio/index.html +2 -2
  103. package/dist/think.d.ts +2 -2
  104. package/dist/think.js +8292 -2
  105. package/dist/think.js.map +1 -0
  106. package/dist/tools/extensions.js +1 -1
  107. package/dist/tools/workspace.js +2 -2
  108. package/dist/tools/workspace.js.map +1 -1
  109. package/dist/{types-codegen-B6c5KpYH.js → types-codegen-C-9yeFao.js} +9 -33
  110. package/dist/types-codegen-C-9yeFao.js.map +1 -0
  111. package/dist/vite.d.ts +5 -5
  112. package/dist/vite.js +1 -1
  113. package/dist/workflows.d.ts +1 -1
  114. package/docs/actions.md +297 -0
  115. package/docs/channels.md +185 -0
  116. package/docs/client-tools.md +233 -0
  117. package/docs/getting-started.md +314 -0
  118. package/docs/index.md +1272 -0
  119. package/docs/lifecycle-hooks.md +839 -0
  120. package/docs/messengers.md +197 -0
  121. package/docs/programmatic-submissions.md +206 -0
  122. package/docs/sub-agents.md +520 -0
  123. package/docs/tools.md +582 -0
  124. package/docs/workflows.md +217 -0
  125. package/package.json +46 -17
  126. package/dist/chat-sdk-Bb93yaZh.js.map +0 -1
  127. package/dist/codegen-CuPdJRpV.js.map +0 -1
  128. package/dist/framework/index.js.map +0 -1
  129. package/dist/studio/assets/index-Cbb3GlZY.js +0 -496
  130. package/dist/studio/assets/index-DN9_cL01.css +0 -2
  131. package/dist/studio/assets/mermaid-GHXKKRXX-I2ZcYo7k.js +0 -1
  132. package/dist/think-BYZXQ-vm.js +0 -6513
  133. package/dist/think-BYZXQ-vm.js.map +0 -1
  134. package/dist/types-codegen-B6c5KpYH.js.map +0 -1
package/docs/index.md ADDED
@@ -0,0 +1,1272 @@
1
+ # Think (Experimental)
2
+
3
+ `@cloudflare/think` is an opinionated chat agent base class for Cloudflare Workers. It handles the full chat lifecycle — agentic loop, message persistence, streaming, tool execution, client tools, stream resumption, and extensions — all backed by Durable Object SQLite.
4
+
5
+ Think works as both a **top-level agent** (WebSocket chat to browser clients via `useAgentChat`) and a **sub-agent** (RPC streaming from a parent agent via `chat()`).
6
+
7
+ > **Experimental.** The API surface is stable but may evolve before graduating out of experimental.
8
+
9
+ ## Related package documentation
10
+
11
+ Think builds on packages that are installed alongside it:
12
+
13
+ - `agents/docs/index.md` — Durable Objects, state, routing, sessions, scheduling, MCP, and shared agent primitives
14
+ - `@cloudflare/codemode/docs/index.md` — sandboxed execution, tool providers, connectors, approvals, and snippets
15
+ - `@cloudflare/shell/docs/index.md` — Workspace, filesystem operations, and the `state.*` and `git.*` providers used by Think's tools
16
+ - `create-think/README.md` — CLI commands, templates, and generated project structure
17
+
18
+ ## Why Think
19
+
20
+ Think is for agents whose work must outlive the request. The opinionated pieces are the ones that are tedious and dangerous to get right by hand:
21
+
22
+ - **Durable turns** — an in-flight turn survives Durable Object eviction and resumes; it is not silently lost on deploy or hibernation.
23
+ - **Recovery-aware delivery** — replies are snapshotted as `accepted`, `streaming`, or `completed`, so a restart replays a not-yet-streamed answer but posts a safe interruption notice instead of a duplicate partial. See [Delivery and Recovery](./messengers.md#delivery-and-recovery).
24
+ - **Durable submissions** — webhooks and RPC callers submit a turn with an idempotency key and check status later. See [Programmatic Submissions](./programmatic-submissions.md).
25
+ - **Sessions, not just a message list** — tree-structured history with branching, compaction, and full-text search.
26
+ - **Human-in-the-loop and client tools** — a turn can pause for approval or a browser-side tool and resume later, without holding a request open. See [Human in the Loop](https://github.com/cloudflare/agents/blob/main/docs/agents/human-in-the-loop.md) and [Client Tools](./client-tools.md).
27
+
28
+ If you only need a chat-protocol adapter where you own the loop and the `Response`, use [`AIChatAgent`](https://github.com/cloudflare/agents/blob/main/docs/agents/chat-agents.md) instead. See [Choose your path](https://github.com/cloudflare/agents/blob/main/docs/agents/index.md#choose-your-path) for the full comparison.
29
+
30
+ ## Quick Start
31
+
32
+ ### Install
33
+
34
+ ```sh
35
+ npm install @cloudflare/think agents ai @cloudflare/shell zod workers-ai-provider
36
+ ```
37
+
38
+ ### Server
39
+
40
+ ```typescript
41
+ import { Think } from "@cloudflare/think";
42
+ import { createWorkersAI } from "workers-ai-provider";
43
+ import { routeAgentRequest } from "agents";
44
+
45
+ export class MyAgent extends Think<Env> {
46
+ getModel() {
47
+ return createWorkersAI({ binding: this.env.AI })(
48
+ "@cf/moonshotai/kimi-k2.7-code"
49
+ );
50
+ }
51
+ }
52
+
53
+ export default {
54
+ async fetch(request: Request, env: Env) {
55
+ return (
56
+ (await routeAgentRequest(request, env)) ||
57
+ new Response("Not found", { status: 404 })
58
+ );
59
+ }
60
+ } satisfies ExportedHandler<Env>;
61
+ ```
62
+
63
+ That is it. Think handles the WebSocket chat protocol, message persistence, the agentic loop, message sanitization, stream resumption, client tool support, and workspace file tools. The built-in `read` tool reads text with line numbers and passes images/PDFs through to multimodal-capable models.
64
+
65
+ ## Think Framework
66
+
67
+ The Think Vite plugin can wire agents from an `agents/` directory into a
68
+ generated Worker entry. This removes the hand-written routing boilerplate while
69
+ keeping stable Durable Object class names for production deployments.
70
+
71
+ ```typescript
72
+ // vite.config.ts
73
+ import { cloudflare } from "@cloudflare/vite-plugin";
74
+ import { think } from "@cloudflare/think/vite";
75
+ import { defineConfig } from "vite";
76
+
77
+ export default defineConfig({
78
+ plugins: [think(), cloudflare()]
79
+ });
80
+ ```
81
+
82
+ ### Agent Conventions
83
+
84
+ Put top-level agents under the root `agents/` directory:
85
+
86
+ ```text
87
+ agents/support.ts
88
+ agents/assistant/agent.ts
89
+ ```
90
+
91
+ Put sub-agents under a nested `agents/` directory owned by the parent:
92
+
93
+ ```text
94
+ agents/assistant/agent.ts
95
+ agents/assistant/agents/researcher.ts
96
+ agents/assistant/agents/code-reviewer/agent.ts
97
+ ```
98
+
99
+ Each convention file should export one Agent-compatible class. If a module
100
+ exports multiple Agent-compatible classes, Think fails with a focused diagnostic
101
+ so the generated Durable Object export stays unambiguous.
102
+
103
+ The framework derives stable generated class names from this topology:
104
+
105
+ | Convention path | Generated class |
106
+ | ------------------------------------------------ | -------------------------------------- |
107
+ | `agents/support.ts` | `ThinkAgent_Support` |
108
+ | `agents/assistant/agent.ts` | `ThinkAgent_Assistant` |
109
+ | `agents/assistant/agents/researcher.ts` | `ThinkSubAgent_Assistant_Researcher` |
110
+ | `agents/assistant/agents/code-reviewer/agent.ts` | `ThinkSubAgent_Assistant_CodeReviewer` |
111
+
112
+ Top-level agents need Durable Object bindings and migrations. The binding
113
+ `class_name` must be the generated class, but the binding `name` can stay
114
+ app-owned, such as `AssistantDirectory`. Sub-agents are facets: the generated
115
+ Worker entry exports their classes so parent agents can use `ctx.exports`, but
116
+ production `wrangler.jsonc` does not need facet-only Durable Object bindings,
117
+ migrations, or public routes.
118
+
119
+ Think currently supports top-level agents and one layer of sub-agents. Nested
120
+ sub-agent conventions, such as
121
+ `agents/assistant/agents/researcher/agents/coder.ts`, are intentionally not
122
+ supported yet. If your app needs deeper nesting, please reach out with the use
123
+ case so we can design the routing and lifecycle model deliberately.
124
+
125
+ ### Friendly Routes
126
+
127
+ Generated class names are stable, but URLs stay friendly. A request can use:
128
+
129
+ ```text
130
+ /agents/assistant/alice/sub/researcher/chat-1
131
+ ```
132
+
133
+ Internally, the Think router resolves `assistant` and `researcher` through the
134
+ manifest and adapts the request to the lower-level Agents facet router, which
135
+ still expects generated class segments. Repeated child names under different
136
+ parents are safe because sub-agent aliases are scoped by parent. Treat this as a
137
+ routing helper contract rather than a URL-rewriting API.
138
+
139
+ Use a custom route prefix when you want agents under another path:
140
+
141
+ ```typescript
142
+ think({ routePrefix: "/api/agents" });
143
+ ```
144
+
145
+ The generated config and routing diagnostics use that prefix, so direct routes
146
+ become:
147
+
148
+ ```text
149
+ /api/agents/assistant/alice
150
+ ```
151
+
152
+ ### Custom App Server
153
+
154
+ If `src/server.ts` exists, the generated entry calls it first. If it returns
155
+ `null` or `undefined`, Think handles the request. Any `Response` stops
156
+ fallthrough, including an intentional `404`; auth-gated apps can use that to
157
+ prevent direct `/agents/*` access.
158
+
159
+ ```typescript
160
+ export default {
161
+ async fetch(request: Request) {
162
+ if (new URL(request.url).pathname === "/health") {
163
+ return new Response("ok");
164
+ }
165
+
166
+ return null;
167
+ }
168
+ };
169
+ ```
170
+
171
+ For auth-gated or app-owned routes, use the injected Think router. The generated
172
+ entry passes it as the fourth argument to your `fetch()` handler:
173
+
174
+ ```typescript
175
+ import { getAgentByName } from "agents";
176
+
177
+ type ThinkContext = {
178
+ router: {
179
+ routeSubAgent(
180
+ request: Request,
181
+ parent: { fetch(request: Request): Promise<Response> },
182
+ options: { parent: string }
183
+ ): Promise<Response>;
184
+ };
185
+ };
186
+
187
+ export default {
188
+ async fetch(
189
+ request: Request,
190
+ env: Env,
191
+ ctx: ExecutionContext,
192
+ think?: ThinkContext
193
+ ) {
194
+ const url = new URL(request.url);
195
+
196
+ if (url.pathname === "/chat" || url.pathname.startsWith("/chat/")) {
197
+ const user = await requireUser(request);
198
+ const directory = await getAgentByName(
199
+ env.AssistantDirectory,
200
+ user.login
201
+ );
202
+
203
+ if (!think?.router) {
204
+ return new Response(
205
+ 'Assistant chat routing requires "main": "virtual:think/entry".',
206
+ { status: 500 }
207
+ );
208
+ }
209
+
210
+ return think.router.routeSubAgent(request, directory, {
211
+ parent: "assistant"
212
+ });
213
+ }
214
+
215
+ return null;
216
+ }
217
+ };
218
+ ```
219
+
220
+ This keeps authentication and tenancy in your app code while still letting Think
221
+ resolve friendly sub-agent URLs such as `/chat/sub/researcher/chat-1`. If a
222
+ request has a `/sub/...` segment that cannot be resolved for the declared parent,
223
+ `routeSubAgent()` returns `404`; paths without a `/sub/...` segment continue to
224
+ the parent agent.
225
+
226
+ ### React Router Hosts
227
+
228
+ React Router framework apps can use Think as an additive Vite plugin while
229
+ React Router owns the app routes, loaders, and SSR.
230
+
231
+ See `examples/think-react-router` for a complete runnable example.
232
+
233
+ ```typescript
234
+ // vite.config.ts
235
+ import { cloudflare } from "@cloudflare/vite-plugin";
236
+ import { reactRouter } from "@react-router/dev/vite";
237
+ import { think } from "@cloudflare/think/vite";
238
+ import { defineConfig } from "vite";
239
+
240
+ export default defineConfig({
241
+ plugins: [
242
+ cloudflare({ viteEnvironment: { name: "ssr" } }),
243
+ reactRouter(),
244
+ think({ routePrefix: "/api/agents", allowNonVirtualMain: true })
245
+ ]
246
+ });
247
+ ```
248
+
249
+ ```typescript
250
+ // react-router.config.ts
251
+ import type { Config } from "@react-router/dev/config";
252
+
253
+ export default {
254
+ appDirectory: "app",
255
+ ssr: true,
256
+ future: {
257
+ v8_viteEnvironmentApi: true
258
+ }
259
+ } satisfies Config;
260
+ ```
261
+
262
+ Point `wrangler.jsonc.main` at a normal Worker entry file and make that file a
263
+ tiny Think shim:
264
+
265
+ ```typescript
266
+ // src/worker.ts
267
+ export { default } from "virtual:think/entry";
268
+ export * from "virtual:think/entry";
269
+ ```
270
+
271
+ Then delegate ordinary app requests to React Router from `src/server.ts` and
272
+ return `null` for Think-owned paths:
273
+
274
+ ```typescript
275
+ // src/server.ts
276
+ import { createRequestHandler } from "react-router";
277
+ import type { ThinkAppContext } from "@cloudflare/think/server-entry";
278
+ import type { ServerBuild } from "react-router";
279
+
280
+ const reactRouterHandler = createRequestHandler(
281
+ () =>
282
+ import("virtual:react-router/server-build").then(
283
+ (mod) => (mod.default ?? mod) as ServerBuild
284
+ ),
285
+ import.meta.env.MODE
286
+ );
287
+
288
+ export default {
289
+ async fetch(
290
+ request: Request,
291
+ env: Env,
292
+ ctx: ExecutionContext,
293
+ _think?: ThinkAppContext
294
+ ) {
295
+ const url = new URL(request.url);
296
+ if (url.pathname.startsWith("/api/agents/")) {
297
+ return null;
298
+ }
299
+
300
+ return reactRouterHandler(request, {
301
+ cloudflare: {
302
+ env,
303
+ ctx
304
+ }
305
+ });
306
+ }
307
+ };
308
+ ```
309
+
310
+ This is still a normal React Router app: `app/routes.ts`, `app/root.tsx`, and
311
+ route modules stay under React Router's conventions. The Worker shim exists so
312
+ Think can keep exporting generated Durable Object classes while the host
313
+ framework owns app rendering.
314
+
315
+ ### TanStack Start Hosts
316
+
317
+ TanStack Start apps use the same host-framework shape: the Cloudflare Vite plugin
318
+ creates the `ssr` workerd environment, TanStack owns document routing, and Think
319
+ handles its route prefix after the app server returns `null`.
320
+
321
+ See `examples/think-tanstack-start` for a complete runnable example.
322
+
323
+ ```typescript
324
+ // vite.config.ts
325
+ import { cloudflare } from "@cloudflare/vite-plugin";
326
+ import { tanstackStart } from "@tanstack/react-start/plugin/vite";
327
+ import react from "@vitejs/plugin-react";
328
+ import { think } from "@cloudflare/think/vite";
329
+ import { defineConfig } from "vite";
330
+
331
+ export default defineConfig({
332
+ plugins: [
333
+ cloudflare({ viteEnvironment: { name: "ssr" } }),
334
+ tanstackStart(),
335
+ react(),
336
+ think({ routePrefix: "/api/agents", allowNonVirtualMain: true })
337
+ ]
338
+ });
339
+ ```
340
+
341
+ Use the same Worker shim:
342
+
343
+ ```typescript
344
+ // src/worker.ts
345
+ export { default } from "virtual:think/entry";
346
+ export * from "virtual:think/entry";
347
+ ```
348
+
349
+ Then delegate ordinary app requests to TanStack Start:
350
+
351
+ ```typescript
352
+ // src/server.ts
353
+ import handler from "@tanstack/react-start/server-entry";
354
+ import type { ThinkAppContext } from "@cloudflare/think/server-entry";
355
+
356
+ export default {
357
+ async fetch(
358
+ request: Request,
359
+ env: Env,
360
+ ctx: ExecutionContext,
361
+ _think?: ThinkAppContext
362
+ ) {
363
+ const url = new URL(request.url);
364
+ if (url.pathname.startsWith("/api/agents/")) {
365
+ return null;
366
+ }
367
+
368
+ return handler.fetch(request);
369
+ }
370
+ };
371
+ ```
372
+
373
+ TanStack route modules are also part of the client build. If a route needs
374
+ Cloudflare bindings, access them through a TanStack server function instead of
375
+ importing `cloudflare:workers` into client-executed code.
376
+
377
+ ### Diagnostics
378
+
379
+ During Vite build/startup, Think reads `wrangler.jsonc` or `wrangler.json`,
380
+ watches Wrangler config files (`wrangler.jsonc`, `wrangler.json`, and
381
+ `wrangler.toml`) plus the `agents/` tree, discovers convention agents, and
382
+ reports framework-specific diagnostics for:
383
+
384
+ - `wrangler.jsonc.main` values that bypass `virtual:think/entry`,
385
+ - missing Durable Object bindings or migrations for top-level generated classes,
386
+ - missing Worker Loader bindings when colocated skills require one,
387
+ - custom `assets.run_worker_first` values that omit the configured route prefix,
388
+ - duplicate generated class names, agent ids, route ids, or orphan sub-agents.
389
+
390
+ Platform bindings such as AI, KV, R2, D1, and secrets remain user-owned. Think
391
+ does not infer or silently add those bindings.
392
+
393
+ `wrangler.toml` is watched so dev servers notice config churn, but Think's
394
+ framework diagnostics currently parse JSON/JSONC Wrangler config. Prefer
395
+ `wrangler.jsonc` for framework apps.
396
+
397
+ Advanced embedders that intentionally do not use `virtual:think/entry` can opt
398
+ out of the `main` diagnostic with:
399
+
400
+ ```typescript
401
+ think({ allowNonVirtualMain: true });
402
+ ```
403
+
404
+ Use that only when another wrapper still re-exports Think's generated Durable
405
+ Object classes.
406
+
407
+ ### CLI Type Generation
408
+
409
+ Use `think types` to keep Think-specific TypeScript declarations in sync with the
410
+ discovered manifest:
411
+
412
+ ```bash
413
+ npx @cloudflare/think types
414
+ ```
415
+
416
+ By default, the command only writes Think-owned declarations to `think.d.ts`:
417
+ `virtual:think/entry`, `virtual:think/router`, generated Durable Object exports,
418
+ skill stubs, and the generated Durable Object bindings on `Cloudflare.Env`.
419
+
420
+ When you also want Wrangler platform declarations, use `--all`. Wrangler flags
421
+ can be passed through after `--`:
422
+
423
+ ```bash
424
+ npx @cloudflare/think types --all -- --env production
425
+ ```
426
+
427
+ With `--all`, Think runs `wrangler types env.d.ts --include-runtime false` before
428
+ generating `think.d.ts`. Pass `--wrangler-env-file` to change Wrangler's output
429
+ path, or pass `-- --include-runtime true` when you intentionally want Wrangler's
430
+ runtime declarations included.
431
+
432
+ `think types` does not generate an importable Env module. App code can use the
433
+ augmented `Cloudflare.Env` directly, or define its own local alias if it prefers
434
+ imported types.
435
+
436
+ Use `think types --check` in CI to verify Think-generated files are current
437
+ without modifying the working tree.
438
+
439
+ ### Runtime CLI
440
+
441
+ Once an agent is running — locally with `pnpm dev` or deployed to a Worker — you
442
+ can reach it from the terminal. `think init`, `think inspect`, and `think types`
443
+ are build-time tools; `think studio` and `think state` connect to the live
444
+ Durable Object over the same chat WebSocket the browser client uses.
445
+
446
+ > These commands are experimental and may change in any release.
447
+
448
+ Launch Think Studio — a local web app for chatting with and inspecting a running
449
+ Think instance:
450
+
451
+ ```bash
452
+ # Local dev server (defaults to localhost:5173)
453
+ npx @cloudflare/think studio support
454
+
455
+ # A specific instance, against a deployed Worker, with an auth token
456
+ npx @cloudflare/think studio support alice --url https://app.example.com --token "$TOKEN"
457
+ ```
458
+
459
+ `studio` starts a tiny local server, opens your browser, and serves a bundled
460
+ single-page app. The connect screen is pre-filled from the flags you passed (and
461
+ from the local manifest's agent list when run inside a Think project), but you
462
+ can point it at any local or remote Think instance from the UI. Once connected,
463
+ Studio gives you:
464
+
465
+ - A **chat view** with token-by-token streaming, tool calls, and inline
466
+ approve/reject buttons for `needsApproval` tools.
467
+ - A read-only **inspector** showing the agent's identity, connection status,
468
+ live state, recent history count, and a turn/recovery status badge.
469
+
470
+ The browser talks to the agent directly over a WebSocket, so the Studio server
471
+ stays a thin static launcher (`--port` to change it, `--no-open` to skip
472
+ opening the browser). **Chatting drives a real, persisted turn** against the live
473
+ agent — it writes to the agent's session exactly as any browser client would.
474
+
475
+ When you run `pnpm dev`, the Think Vite plugin also adds an **`s` shortcut** to
476
+ the dev server: press `s` (alongside Vite's built-in `r`/`u`/`o`/`c`/`q`) to
477
+ launch Studio pointed at the running dev server. Pass `studioShortcut: false` to
478
+ the `think()` Vite plugin to disable it.
479
+
480
+ Print an agent's identity, state, and recent history without sending a message:
481
+
482
+ ```bash
483
+ npx @cloudflare/think state support alice --limit 20
484
+ npx @cloudflare/think state support --json
485
+ ```
486
+
487
+ Both commands share the same connection flags:
488
+
489
+ | Flag | Description |
490
+ | ---------------- | ----------------------------------------------------------- |
491
+ | `<agent>` | Manifest agent id/alias, or a raw route segment |
492
+ | `[instance]` | Agent instance name (default `default`) |
493
+ | `--url <origin>` | Remote origin, e.g. `https://app.example.com` (implies wss) |
494
+ | `--host <h[:p]>` | Local host (default `localhost:5173`; Wrangler uses `8787`) |
495
+ | `--protocol` | Force `ws` or `wss` |
496
+ | `--token <t>` | Auth token, sent as the `token` query param |
497
+ | `--query k=v` | Extra query params (repeatable) |
498
+ | `--route-prefix` | Override the Think route prefix |
499
+ | `--root` | Project root used to discover the manifest (default cwd) |
500
+
501
+ WebSocket upgrades cannot send custom headers, so `--token` is delivered as a
502
+ query parameter — see [Cross-domain authentication](/agents/api-reference/cross-domain-authentication/)
503
+ for how to validate it server-side. Run from inside a Think project so the CLI
504
+ can resolve friendly agent ids and a custom route prefix from the manifest; from
505
+ anywhere else, pass the literal route segment and `--route-prefix` directly.
506
+
507
+ The CLI uses Node's built-in `WebSocket`, so it requires Node.js 24+ and adds no
508
+ extra dependencies.
509
+
510
+ ## Messengers
511
+
512
+ Think agents can receive and reply to messenger webhooks directly. Messenger
513
+ helpers are exported from `@cloudflare/think/messengers`, while provider
514
+ implementations use provider subpaths so unused Chat SDK adapters are not
515
+ bundled.
516
+
517
+ For Telegram messengers, also install the Telegram adapter:
518
+
519
+ ```bash
520
+ npm install @chat-adapter/telegram
521
+ ```
522
+
523
+ ```typescript
524
+ import { Think } from "@cloudflare/think";
525
+ import { ThinkMessengerStateAgent } from "@cloudflare/think/messengers";
526
+ import telegramMessenger from "@cloudflare/think/messengers/telegram";
527
+
528
+ export { ThinkMessengerStateAgent };
529
+
530
+ export class SupportAgent extends Think<Env> {
531
+ getMessengers() {
532
+ return {
533
+ telegram: telegramMessenger({
534
+ token: this.env.TELEGRAM_BOT_TOKEN,
535
+ userName: "support_bot",
536
+ secretToken: this.env.TELEGRAM_WEBHOOK_SECRET_TOKEN
537
+ })
538
+ };
539
+ }
540
+ }
541
+ ```
542
+
543
+ The root Think agent handles messenger webhook routes before user-defined
544
+ `onRequest` fallback. By default, the `telegram` key maps to
545
+ `/messengers/telegram/webhook`. Direct messages and mentions route to the model
546
+ by default. New mentions subscribe the thread so later mentions are still
547
+ observed; ordinary subscribed-thread messages and button actions are opt-in with
548
+ `respondTo: ["subscribed-thread", "action"]`. Each Chat SDK thread gets its own
549
+ Think sub-agent for memory isolation. A root agent owns one Chat SDK runtime for
550
+ all configured messengers, so multiple providers share state and webhook
551
+ handling without competing over Chat SDK singleton registration.
552
+
553
+ Use `conversation: "self"` to run messenger turns on the root Think agent:
554
+
555
+ ```typescript
556
+ telegramMessenger({
557
+ token: this.env.TELEGRAM_BOT_TOKEN,
558
+ userName: "support_bot",
559
+ secretToken: this.env.TELEGRAM_WEBHOOK_SECRET_TOKEN,
560
+ conversation: "self"
561
+ });
562
+ ```
563
+
564
+ Messenger state is backed by `agents/chat-sdk`. Export
565
+ `ThinkMessengerStateAgent` from the Worker module so sub-agent routing can
566
+ resolve it. Production applications do not need a separate Durable Object
567
+ binding or migration for the state agent when it is mounted as a sub-agent
568
+ facet.
569
+
570
+ Inbound messenger replies use `chat()` with a streaming callback inside an
571
+ idempotent root-agent fiber. Use `submitMessages()` for non-streaming
572
+ programmatic sends, scheduled digests, or background work. Normalized messenger
573
+ events include thread, author, message, capabilities, actions, and attachment
574
+ metadata. Attachment bytes are fetched only when the provider supplies a safe
575
+ fetch function.
576
+
577
+ Messenger reply recovery stores serializable event and thread snapshots. If a
578
+ Durable Object restarts before streaming starts, Think can resume the answer; if
579
+ it restarts after streaming has begun, the delivery policy posts the configured
580
+ interruption message. `getMessengerContext()` returns the initiating messenger
581
+ context during the turn. Telegram webhook verification must be explicit: set
582
+ `secretToken`, provide `verifyWebhook`, or use `verifyWebhook: false` to opt out
583
+ intentionally. Custom `chatSdkMessenger()` definitions must also choose a
584
+ verification posture explicitly. Delivery failures use a generic user-facing
585
+ error by default so internal exception details are not posted into external
586
+ chats.
587
+
588
+ ### Client
589
+
590
+ ```tsx
591
+ import { useAgent } from "agents/react";
592
+ import { useAgentChat } from "@cloudflare/think/react";
593
+
594
+ function Chat() {
595
+ const agent = useAgent({ agent: "MyAgent" });
596
+ const { messages, sendMessage, status } = useAgentChat({ agent });
597
+
598
+ return (
599
+ <div>
600
+ {messages.map((msg) => (
601
+ <div key={msg.id}>
602
+ <strong>{msg.role}:</strong>
603
+ {msg.parts.map((part, i) =>
604
+ part.type === "text" ? <span key={i}>{part.text}</span> : null
605
+ )}
606
+ </div>
607
+ ))}
608
+
609
+ <form
610
+ onSubmit={(e) => {
611
+ e.preventDefault();
612
+ const input = e.currentTarget.elements.namedItem(
613
+ "input"
614
+ ) as HTMLInputElement;
615
+ sendMessage({ text: input.value });
616
+ input.value = "";
617
+ }}
618
+ >
619
+ <input name="input" placeholder="Send a message..." />
620
+ <button type="submit">Send</button>
621
+ </form>
622
+ </div>
623
+ );
624
+ }
625
+ ```
626
+
627
+ ### Manual wrangler.jsonc
628
+
629
+ This manual configuration is for using `Think` directly without the Think Vite
630
+ framework conventions. If you are using `think()` from `@cloudflare/think/vite`,
631
+ keep `main` set to `virtual:think/entry` and use the generated class names shown
632
+ in the framework section above.
633
+
634
+ ```jsonc
635
+ {
636
+ "compatibility_date": "2026-01-28",
637
+ "compatibility_flags": ["nodejs_compat"],
638
+ "ai": { "binding": "AI" },
639
+ "durable_objects": {
640
+ "bindings": [{ "class_name": "MyAgent", "name": "MyAgent" }]
641
+ },
642
+ "migrations": [{ "new_sqlite_classes": ["MyAgent"], "tag": "v1" }],
643
+ "main": "src/server.ts"
644
+ }
645
+ ```
646
+
647
+ ## Think vs AIChatAgent
648
+
649
+ Both Think and [`AIChatAgent`](https://github.com/cloudflare/agents/blob/main/docs/agents/chat-agents.md) extend `Agent` and speak the same `cf_agent_chat_*` WebSocket protocol. They serve different goals.
650
+
651
+ **AIChatAgent** is a protocol adapter. You override `onChatMessage` and are responsible for calling `streamText`, wiring tools, converting messages, and returning a `Response`. AIChatAgent handles the plumbing — message persistence, streaming, abort, resume — but the LLM call is entirely your concern.
652
+
653
+ **Think** is an opinionated framework. It makes decisions for you: `getModel()` returns the model, `getSystemPrompt()` or `configureSession()` sets the prompt, `getTools()` returns tools. The default `onChatMessage` runs the complete agentic loop. You override individual pieces, not the whole pipeline.
654
+
655
+ | Concern | AIChatAgent | Think |
656
+ | ---------------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------- |
657
+ | **Minimal subclass** | ~15 lines (wire `streamText` + tools + system prompt + response) | 3 lines (`getModel()` only) |
658
+ | **Storage** | Flat SQL table | Session: tree-structured messages, context blocks, compaction, FTS5 |
659
+ | **Regeneration** | Destructive (old response deleted) | Non-destructive branching (old responses preserved) |
660
+ | **Context management** | Manual | Context blocks with LLM-writable persistent memory |
661
+ | **Sub-agent RPC** | Not built in | `chat()` with `StreamCallback` |
662
+ | **Programmatic turns** | `saveMessages()` | `saveMessages()`, `submitMessages()`, `continueLastTurn()` |
663
+ | **Compaction** | `maxPersistedMessages` (deletes oldest) | Non-destructive summaries via overlays |
664
+ | **Search** | Not available | FTS5 full-text search per-session and cross-session |
665
+
666
+ ### When to use AIChatAgent
667
+
668
+ - You need full control over the LLM call (RAG, multi-model, custom streaming)
669
+ - You are migrating from AI SDK v4 (`autoTransformMessages` provides the bridge)
670
+ - You want the `Response` return type for HTTP middleware or testing
671
+ - You are building a simple chatbot with no memory requirements
672
+
673
+ ### When to use Think
674
+
675
+ - You want to ship fast (3-line subclass with everything wired)
676
+ - You need persistent memory (context blocks the model can read and write)
677
+ - You need long conversations (non-destructive compaction)
678
+ - You need conversation search (FTS5)
679
+ - You are building a sub-agent system (parent-child RPC with streaming)
680
+ - You need proactive agents (programmatic turns from scheduled tasks or webhooks)
681
+ - You need durable async submission for webhook/RPC callers — see [Programmatic submissions](./programmatic-submissions.md)
682
+
683
+ ## Choosing a Turn API
684
+
685
+ Think has several ways to start or continue a turn. They all funnel through one
686
+ public entry point — `runTurn(options)` — and the older methods remain as
687
+ convenience shortcuts.
688
+
689
+ ### `runTurn()`
690
+
691
+ > **Experimental.** Stable in shape, but may evolve before Think graduates.
692
+
693
+ `runTurn()` is the unified turn-admission API. One method, three modes, selected
694
+ by `options.mode`:
695
+
696
+ | Mode | Use when | Returns | Shortcut for |
697
+ | ------------------ | ------------------------------------------------------------ | ------------------------------- | ------------------ |
698
+ | `"wait"` (default) | The caller can block until the model response is finished | `Promise<TurnResult>` | `saveMessages()` |
699
+ | `"submit"` | The caller needs fast, durable acceptance and a later status | `Promise<SubmitMessagesResult>` | `submitMessages()` |
700
+ | `"stream"` | The caller wants the response streamed to a callback (RPC) | `Promise<void>` | `chat()` |
701
+
702
+ The `input` accepts a string, a `UIMessage`, an array of messages, or — in
703
+ `wait` and `stream` modes — a function `(current) => UIMessage[]` evaluated at
704
+ admission. (`submit` does not accept function input.)
705
+
706
+ ```typescript
707
+ // wait — block for the result
708
+ const result = await this.runTurn({ input: "Summarize the latest thread" });
709
+ if (result.status === "completed") {
710
+ // result.message is the assistant SessionMessage; result.continuation is false
711
+ }
712
+
713
+ // submit — durable acceptance, check status later
714
+ const submission = await this.runTurn({
715
+ mode: "submit",
716
+ input: "Process this webhook",
717
+ idempotencyKey: inboundEventId // dedupe; safe to retry
718
+ });
719
+ // submission.accepted is true on first accept; submission.status is "pending"
720
+
721
+ // stream — drive a callback (the same surface as chat())
722
+ await this.runTurn({
723
+ mode: "stream",
724
+ input: "Stream me",
725
+ callback: {
726
+ onStart({ requestId }) {},
727
+ onEvent(json) {}, // UIMessageChunk JSON
728
+ onDone() {},
729
+ onError(error) {}
730
+ }
731
+ });
732
+ ```
733
+
734
+ Continue the last assistant turn (instead of sending new input) by passing
735
+ `continuation: true` in `wait` mode — pass exactly one of `input` or
736
+ `continuation`:
737
+
738
+ ```typescript
739
+ await this.runTurn({ continuation: true });
740
+ ```
741
+
742
+ Key behaviors:
743
+
744
+ - **Blocking modes cannot nest.** Calling `wait`/`stream`/`continuation` (or the
745
+ equivalent shortcut) from _inside_ an active turn — for example, from a tool's
746
+ `execute` — throws, because it would deadlock the turn queue. From inside a
747
+ turn, use `runTurn({ mode: "submit" })` (durable, runs after the current turn
748
+ frees the queue) or [`addMessages()`](#adding-messages-without-a-turn)
749
+ (transcript only, no inference).
750
+ - **`submit` is idempotent.** Pass `submissionId` and/or `idempotencyKey`;
751
+ re-submitting a known key returns the existing record with `accepted: false`
752
+ instead of starting a second turn. See [Programmatic
753
+ Submissions](./programmatic-submissions.md).
754
+ - **Recovery-safe.** When `chatRecovery` is enabled, the `wait`, `stream`, and
755
+ drained `submit` paths all run inference inside a recovery fiber, so an
756
+ interrupted turn resumes after eviction.
757
+
758
+ `runTurn` is exported alongside its option and result types: `RunTurnOptions`,
759
+ `RunTurnWait`, `RunTurnSubmit`, `RunTurnStream`, `TurnInputMessages`, and
760
+ `TurnResult`.
761
+
762
+ ### Picking a shortcut
763
+
764
+ The table below maps each scenario to the most direct call. Each shortcut has an
765
+ unchanged signature; reach for them when you want the narrower surface, or use
766
+ `runTurn()` when you want one mental model.
767
+
768
+ | Use case | API |
769
+ | -------------------------------------------------------------- | ----------------------------------------------- |
770
+ | A browser user sends chat messages | `useAgentChat` over the WebSocket chat protocol |
771
+ | Server code can wait for the model response | `saveMessages()` |
772
+ | Server code needs fast durable acceptance and later status | `submitMessages()` |
773
+ | Code should create recurring prompt-driven turns or handlers | `getScheduledTasks()` |
774
+ | Parent code needs direct streaming RPC to a specific child | `subAgent(...).chat()` |
775
+ | A parent agent delegates work to a retained child agent | `agentTool()` or `runAgentTool()` |
776
+ | Surround a turn with idempotent app-owned side effects | `startFiber()` |
777
+ | Coordinate multi-step durable orchestration | Workflows |
778
+ | Add context or messages without starting a model turn | `addMessages()` |
779
+ | Advanced subclass or recovery code continues an assistant turn | `continueLastTurn()` |
780
+
781
+ Use [`saveMessages()`](./sub-agents.md#programmatic-turns-with-savemessages)
782
+ when the caller owns the trigger and can wait for the turn to finish. Use
783
+ [`submitMessages()`](./programmatic-submissions.md) when timeout ambiguity would
784
+ make retries unsafe.
785
+
786
+ Use [`chat()`](./sub-agents.md#sub-agent-via-chat) for low-level parent-to-child
787
+ streaming when your code owns forwarding, cancellation, and replay policy. Use
788
+ [Agent Tools](https://github.com/cloudflare/agents/blob/main/docs/agents/agent-tools.md) when a parent model or workflow delegates to a
789
+ child agent and you want retained child runs, event replay, abort bridging, and
790
+ UI drill-in.
791
+
792
+ Use [`startFiber()`](https://github.com/cloudflare/agents/blob/main/docs/agents/durable-execution.md#startfiber) outside Think when the
793
+ durable unit is an application job around a turn: accepting a webhook once,
794
+ restoring a serialized channel/thread target, posting a visible reply, or
795
+ recording app-level recovery policy. Think submissions own conversation
796
+ admission and turn serialization; managed fibers own external job acceptance,
797
+ idempotent side effects, and application recovery. Think and AIChat internals
798
+ continue to use raw `runFiber()` for stream recovery because those fibers are
799
+ internal recovery records, not externally inspectable application jobs.
800
+
801
+ Use [Workflows](https://github.com/cloudflare/agents/blob/main/docs/agents/workflows.md) when the durable unit is a multi-step process
802
+ with retries per step, long waits, external events, or approvals.
803
+
804
+ ### Adding messages without a turn
805
+
806
+ Use `addMessages()` to write to the transcript **without** starting a model turn
807
+ — for importing prior history or injecting background context the next turn
808
+ should see:
809
+
810
+ ```typescript
811
+ await this.addMessages([
812
+ {
813
+ id: crypto.randomUUID(),
814
+ role: "user",
815
+ parts: [{ type: "text", text: "Imported context" }]
816
+ }
817
+ ]);
818
+ ```
819
+
820
+ `addMessages()` appends (or upserts) into the Session tree:
821
+
822
+ - It does **not** run inference and does **not** enter the turn queue, so it is
823
+ safe to call from inside a tool's `execute` without deadlocking.
824
+ - Array entries are appended **linearly** (each attaches under the previous one),
825
+ so imported history stays a single path. By default the first message attaches
826
+ to the latest committed leaf; pass `parentId` to attach elsewhere, or `null`
827
+ for a root message.
828
+ - Appends are **idempotent by message id**. Pass `{ mode: "upsert" }` to update
829
+ an existing message in place instead.
830
+
831
+ This is distinct from `saveMessages()` (which runs a turn) and from
832
+ `AIChatAgent`'s `persistMessages()` (which replaces/reconciles a flat array
833
+ rather than appending into a tree). The supported pattern is "add context, then
834
+ run a turn": call `addMessages()`, then `saveMessages()` / the WebSocket chat
835
+ path.
836
+
837
+ ## Configuration Overrides
838
+
839
+ | Method / Property | Default | Description |
840
+ | -------------------------- | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
841
+ | `getModel()` | throws | Return the `LanguageModel` to use |
842
+ | `getSystemPrompt()` | `"You are a helpful assistant."` | System prompt (fallback when no context blocks) |
843
+ | `getTools()` | `{}` | AI SDK `ToolSet` for the agentic loop |
844
+ | `getScheduledTasks()` | `{}` | Code-declared recurring prompts or handlers |
845
+ | `getDefaultTimezone()` | `undefined` | Default timezone for wall-clock scheduled tasks |
846
+ | `getMessengers()` | `{}` | Messenger ingress and delivery declarations — see [Messengers](./messengers.md) |
847
+ | `getActions()` | `{}` | Server actions (idempotency, approvals, authorization) compiled into tools — see [Actions](./actions.md) |
848
+ | `configureChannels()` | `{}` | Per-channel policy and surfaces beyond the implicit `web` channel — see [Channels](./channels.md) |
849
+ | `maxSteps` | `10` | Max tool-call rounds per turn |
850
+ | `sendReasoning` | `true` | Send reasoning chunks to chat clients |
851
+ | `configureSession()` | identity | Add context blocks, compaction, search, skills — see [Sessions](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md) |
852
+ | `getSkills()` | `[]` | Return Agent Skills sources for on-demand skill activation |
853
+ | `getSkillScriptRunner()` | `null` | Enable the optional `run_skill_script` tool |
854
+ | `workspaceBash` | `true` | Include or configure the default workspace `bash` tool |
855
+ | `messageConcurrency` | `"queue"` | How overlapping submits behave — see [Client Tools](./client-tools.md) |
856
+ | `waitForMcpConnections` | `false` | Wait for MCP servers before inference |
857
+ | `chatRecovery` | `true` | Wrap turns in `runFiber` for durable execution, including sub-agent turns. Set to `{ maxAttempts, stableTimeoutMs, terminalMessage, onExhausted }` to tune bounded recovery. |
858
+ | `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; with `chatRecovery` on (the default) 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. |
859
+ | `contextOverflow` | `undefined` | Opt-in mid-turn context-overflow handling: `{ reactive?, maxRetries?, proactive? }`. Requires `classifyChatError` + a session compaction function. See [Context-window overflow recovery](#context-window-overflow-recovery). |
860
+
861
+ ## Agent Skills
862
+
863
+ Think supports [Agent Skills](https://agentskills.io/) as on-demand
864
+ instructions. A skill source provides a catalog of skill names and descriptions;
865
+ Think adds that catalog to the system prompt and exposes tools the model can use
866
+ when a user task matches a skill.
867
+
868
+ Bundled skills are usually imported with the Think Vite plugin, which includes
869
+ the Agent Skills import support:
870
+
871
+ ```typescript
872
+ import { Think, skills } from "@cloudflare/think";
873
+ import bundledSkills from "agents:skills"; // resolves to ./skills next to this file
874
+
875
+ type Env = {
876
+ AI: Ai;
877
+ LOADER: WorkerLoader;
878
+ SKILLS_BUCKET: R2Bucket;
879
+ };
880
+
881
+ export class MyAgent extends Think<Env> {
882
+ getSkills() {
883
+ return [
884
+ bundledSkills,
885
+ skills.r2(this.env.SKILLS_BUCKET, { prefix: "skills/" })
886
+ ];
887
+ }
888
+
889
+ getSkillScriptRunner() {
890
+ return skills.runner({
891
+ loader: this.env.LOADER,
892
+ workspaceInstance: this.workspace
893
+ });
894
+ }
895
+ }
896
+ ```
897
+
898
+ `agents:skills` resolves to a `./skills` directory next to the importing file;
899
+ use `agents:skills/<dir>` to point at a differently named sibling directory.
900
+ The `agents:skills` import is typed by ambient declarations that ship with
901
+ `agents`, so importing `Think` in the same file brings the type into scope (for
902
+ a file that imports only the specifier, add
903
+ `/// <reference types="agents/skills-module" />`). If you are not using the
904
+ Agents Vite plugin, build a source with `skills.fromManifest(...)` instead.
905
+
906
+ The skills engine lives in `agents/skills` and is framework-agnostic, so any
907
+ agent (including a plain `@cloudflare/ai-chat` `onChatMessage`) can build a
908
+ `SkillRegistry`; `@cloudflare/think` re-exports it as `skills` and wires
909
+ `getSkills()` into the turn automatically.
910
+
911
+ Sources are applied in order; the first source to register a skill name wins,
912
+ and later duplicates (or a source that fails to load) are skipped with a logged
913
+ warning rather than failing the agent.
914
+
915
+ The imported directory should contain one child directory per skill:
916
+
917
+ ```text
918
+ agents/my-agent/skills/release-notes/SKILL.md
919
+ agents/my-agent/skills/release-notes/scripts/format-release-notes.ts
920
+ agents/my-agent/skills/release-notes/references/style-guide.md
921
+ ```
922
+
923
+ When skills are available, Think exposes:
924
+
925
+ | Tool | Purpose |
926
+ | --------------------- | ------------------------------------------------------------------- |
927
+ | `activate_skill` | Load a matching skill's instructions and bundled resource list |
928
+ | `read_skill_resource` | Read a bundled resource by `{ name, path }` or `skill-name/path` |
929
+ | `run_skill_script` | Run a bundled script when `getSkillScriptRunner()` returns a runner |
930
+
931
+ Skills are not always-on system prompt text. Use `getSystemPrompt()` or a
932
+ Session context block for behavior that should apply to every turn. Use skills
933
+ for task-specific procedures, references, scripts, templates, and assets that
934
+ should be loaded only when relevant.
935
+
936
+ Script execution is opt-in and requires a Worker Loader binding:
937
+
938
+ ```jsonc
939
+ {
940
+ "worker_loaders": [{ "binding": "LOADER" }]
941
+ }
942
+ ```
943
+
944
+ `skills.runner()` is experimental and runs JavaScript, TypeScript, Python, and
945
+ Bash scripts under `scripts/`. TypeScript is compiled with
946
+ `@cloudflare/worker-bundler`; Python runs as Python Dynamic Workers; Bash runs
947
+ through `just-bash`.
948
+
949
+ JavaScript and TypeScript scripts are function-style:
950
+
951
+ ```typescript
952
+ import type { SkillRunContext } from "@cloudflare/think";
953
+
954
+ export default async function run(input: unknown, ctx: SkillRunContext) {
955
+ const guide = ctx.files["references/style-guide.md"]; // bundled text resources
956
+ const docs = await ctx.workspace.readFile("README.md"); // gated by permission
957
+ const summary = await ctx.tools.call("summarize", { input }); // explicit tools
958
+ await ctx.output.writeFile("notes.md", summary); // scratch artifact
959
+ return { ok: true };
960
+ }
961
+ ```
962
+
963
+ `ctx` is `{ skill, files, workspace, tools, output }`. `ctx.files` holds bundled
964
+ text resources by relative path, `ctx.workspace` is gated by the workspace
965
+ permission, `ctx.tools` only exposes tools the runner was given, and
966
+ `ctx.output.writeFile(name, content)` returns scratch artifacts to the model
967
+ (it does not mutate the workspace). Python and Bash use the path-based contract
968
+ instead: `/input.json`, `/context.json`, bundled resources under `/skill`, and
969
+ `/output` for artifacts.
970
+
971
+ Passing `workspaceInstance` gives scripts read-only workspace access by default.
972
+ Network access, tools, and workspace writes are opt-in. The default timeout is
973
+ 30 seconds.
974
+
975
+ ### Chat Recovery
976
+
977
+ Think wraps chat turns in recoverable fibers by default. 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.
978
+
979
+ A stream-stall watchdog abort (`chatStreamStallTimeoutMs`, above) is treated as just another interruption: when `chatRecovery` is on, a stall routes into this same bounded path — the settled partial is preserved and a continuation is scheduled — so a transient hang recovers automatically. A persistently hanging provider exhausts the budget and terminalizes through the **same** exhaustion handling as a deploy/eviction interruption: `onExhausted` fires, the `chat:recovery:exhausted` event is emitted, and the configured `terminalMessage` is shown (not a raw stall error).
980
+
981
+ Override `onChatRecovery` when you need provider-specific recovery, such as retrieving a stored OpenAI Responses result instead of issuing a new model call:
982
+
983
+ ```typescript
984
+ import type {
985
+ ChatRecoveryContext,
986
+ ChatRecoveryOptions
987
+ } from "@cloudflare/think";
988
+
989
+ export class MyAgent extends Think<Env> {
990
+ override chatRecovery = {
991
+ maxAttempts: 10,
992
+ terminalMessage: "The assistant was interrupted. Please try again."
993
+ };
994
+
995
+ override async onChatRecovery(
996
+ ctx: ChatRecoveryContext
997
+ ): Promise<ChatRecoveryOptions> {
998
+ console.log("Recovering chat turn", ctx.incidentId, ctx.attempt);
999
+ return {}; // persist partial output and continue/retry when possible
1000
+ }
1001
+ }
1002
+ ```
1003
+
1004
+ The same recovery events are available through `agents/observability` on the `chat` channel. Transcript repairs are emitted on the `transcript` channel.
1005
+
1006
+ #### Repairing interrupted tool calls
1007
+
1008
+ 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.
1009
+
1010
+ 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:
1011
+
1012
+ ```typescript
1013
+ import type { UIMessage } from "ai";
1014
+
1015
+ export class MyAgent extends Think<Env> {
1016
+ protected override repairInterruptedToolPart(
1017
+ part: UIMessage["parts"][number]
1018
+ ): UIMessage["parts"][number] {
1019
+ const record = part as Record<string, unknown>;
1020
+ if (record.type === "tool-ask_user") {
1021
+ const input = record.input as { prompt?: string } | undefined;
1022
+ if (input?.prompt) {
1023
+ return { type: "text", text: input.prompt };
1024
+ }
1025
+ }
1026
+ return super.repairInterruptedToolPart(part);
1027
+ }
1028
+ }
1029
+ ```
1030
+
1031
+ This runs during transcript repair — before the repaired transcript is persisted and sent to the model — so the conversion shapes the current turn, not just the next one. The `input` is already normalized to a valid object. A returned tool part must carry a settled result (`output-available`, `output-error`, or `output-denied`); returning a non-tool part such as text is also fine.
1032
+
1033
+ ### Context-window overflow recovery
1034
+
1035
+ [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.
1036
+
1037
+ 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. Both require [`classifyChatError`](./lifecycle-hooks.md#classifychaterror) to tell Think which errors are overflows — Think ships no provider-specific matching in core.
1038
+
1039
+ **1. Reactive backstop — `contextOverflow.reactive`.** When a turn fails with an error you classify as `"context_overflow"`, 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.
1040
+
1041
+ ```typescript
1042
+ import { Think, defaultContextOverflowClassifier } from "@cloudflare/think";
1043
+
1044
+ export class MyAgent extends Think<Env> {
1045
+ override contextOverflow = { reactive: true };
1046
+
1047
+ // The bundled classifier covers the common providers (Anthropic, OpenAI,
1048
+ // Google, Bedrock, …). Assign it directly, or write your own.
1049
+ override classifyChatError = defaultContextOverflowClassifier;
1050
+ }
1051
+ ```
1052
+
1053
+ **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.
1054
+
1055
+ ```typescript
1056
+ import { Think, defaultContextOverflowClassifier } from "@cloudflare/think";
1057
+
1058
+ export class MyAgent extends Think<Env> {
1059
+ override contextOverflow = {
1060
+ reactive: true,
1061
+ // Compact mid-turn once a step approaches 90% of a 200K window.
1062
+ proactive: { maxInputTokens: 200_000 }
1063
+ };
1064
+
1065
+ override classifyChatError = defaultContextOverflowClassifier;
1066
+ }
1067
+ ```
1068
+
1069
+ Use either layer alone, or both together: the proactive guard avoids most overflows, and the reactive backstop catches any that still slip through (for example, a turn that starts already over budget, or a single tool result so large that compaction cannot help — in which case it terminalizes cleanly). Both apply to every turn entry path (WebSocket, sub-agent `chat()`, and programmatic `saveMessages()` / `submitMessages()`), and both emit a `chat:context:compacted` [observability event](https://github.com/cloudflare/agents/blob/main/docs/agents/observability.md#chat-context-events).
1070
+
1071
+ > A no-op compaction cannot rescue an over-budget turn, so recovery is only as effective as your compaction configuration. For tool-heavy histories, configure a `tokenCounter` on `compactAfter()` (see [Sessions](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md#auto-compaction)).
1072
+
1073
+ For a runnable demo against a real Workers AI model, see [`examples/context-overflow-recovery`](https://github.com/cloudflare/agents/tree/main/examples/context-overflow-recovery).
1074
+
1075
+ ## Dynamic Configuration
1076
+
1077
+ `configure()` and `getConfig()` persist a JSON-serializable config blob in SQLite. It survives hibernation and restarts. Pass the config shape as a method-level generic for typed call sites:
1078
+
1079
+ ```typescript
1080
+ type MyConfig = { modelTier: "fast" | "capable"; theme: string };
1081
+
1082
+ export class MyAgent extends Think<Env> {
1083
+ getModel() {
1084
+ const tier = this.getConfig<MyConfig>()?.modelTier ?? "fast";
1085
+ const models = {
1086
+ fast: "@cf/moonshotai/kimi-k2.7-code",
1087
+ capable: "@cf/meta/llama-4-scout-17b-16e-instruct"
1088
+ };
1089
+ return createWorkersAI({ binding: this.env.AI })(models[tier]);
1090
+ }
1091
+ }
1092
+ ```
1093
+
1094
+ | Method | Description |
1095
+ | ---------------------- | ------------------------------------------------------------- |
1096
+ | `configure<T>(config)` | Persist a config object (type checked via the method generic) |
1097
+ | `getConfig<T>()` | Read the persisted configuration, or null if never configured |
1098
+
1099
+ Prefer `state` / `setState` from `Agent` when you want the value broadcast to connected clients. Use `configure` for private, server-side settings.
1100
+
1101
+ Expose configuration to the client via `@callable`:
1102
+
1103
+ ```typescript
1104
+ import { callable } from "agents";
1105
+
1106
+ export class MyAgent extends Think<Env> {
1107
+ getModel() {
1108
+ /* ... */
1109
+ }
1110
+
1111
+ @callable()
1112
+ updateConfig(config: MyConfig) {
1113
+ this.configure<MyConfig>(config);
1114
+ }
1115
+ }
1116
+ ```
1117
+
1118
+ ## Scheduled Tasks
1119
+
1120
+ Use `getScheduledTasks()` when code should create recurring Think turns or
1121
+ deterministic scheduled handlers. Think reconciles the declarations on startup,
1122
+ stores a durable one-shot schedule for the next occurrence, and re-arms the next
1123
+ occurrence after each run.
1124
+
1125
+ ```typescript
1126
+ import { Think } from "@cloudflare/think";
1127
+ import type { ThinkScheduledTasks } from "@cloudflare/think";
1128
+
1129
+ export class DigestAgent extends Think<Env> {
1130
+ getDefaultTimezone() {
1131
+ return "Europe/London";
1132
+ }
1133
+
1134
+ getScheduledTasks(): ThinkScheduledTasks {
1135
+ return {
1136
+ weeklyCommitReport: {
1137
+ schedule: "every week on monday at 09:00",
1138
+ prompt:
1139
+ "Compile all my GitHub commits for the last week and send a concise summary."
1140
+ },
1141
+ workout: {
1142
+ schedule: "every day at 08:00 in Europe/London",
1143
+ prompt: "Start my workout."
1144
+ },
1145
+ customerDigest: {
1146
+ schedule: "every day at 09:00",
1147
+ timezone: "America/New_York",
1148
+ metadata: { workflowName: "customer-digest" },
1149
+ retry: { maxAttempts: 3 },
1150
+ handler: async ({
1151
+ idempotencyKey,
1152
+ scheduledFor,
1153
+ scheduleKind,
1154
+ timezone
1155
+ }) => {
1156
+ await this.env.DIGEST_WORKFLOW.create({
1157
+ id: idempotencyKey,
1158
+ params: { scheduledFor, scheduleKind, timezone }
1159
+ });
1160
+ }
1161
+ }
1162
+ };
1163
+ }
1164
+ }
1165
+ ```
1166
+
1167
+ The DSL supports `every <n> minutes`, `every <n> hours`,
1168
+ `every day at HH:mm`, `every weekday at HH:mm`, and
1169
+ `every week on monday,wednesday at HH:mm`. Wall-clock schedules require either
1170
+ an inline timezone, a task `timezone`, or `getDefaultTimezone()`. If an alarm is
1171
+ late, Think runs the intended occurrence once and schedules the next future
1172
+ occurrence; it does not backfill missed runs.
1173
+
1174
+ Each task must define exactly one of `prompt` or `handler`. Prompt tasks create a
1175
+ durable submission with `submitMessages()`. Handler tasks receive
1176
+ `{ taskId, scheduledFor, scheduledForDate, occurrenceKey, idempotencyKey,
1177
+ schedule, scheduleKind, timezone, metadata }` and are intended for app-owned
1178
+ work such as creating a Workflow run or writing a run ledger. Delivery is
1179
+ at-least-once; use `idempotencyKey` or `occurrenceKey` for your own durable
1180
+ idempotency.
1181
+
1182
+ Static declarations reconcile on startup. If `getScheduledTasks()` reads
1183
+ product-owned data that can change while the Durable Object is live, call
1184
+ `internal_reconcileScheduledTasks()` after updating that data. During
1185
+ reconciliation Think records the task row before creating the underlying Agent
1186
+ schedule, so a missing `schedule_id` is only a pending reconcile state and is
1187
+ repaired on the next reconcile. The task `retry` option retries the prompt or
1188
+ handler action before the failure is logged. The next occurrence is still
1189
+ scheduled after the action succeeds or exhausts its retries, so failed
1190
+ occurrences do not block future runs.
1191
+
1192
+ ## Session Integration
1193
+
1194
+ Think uses [Session](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md) for conversation storage. Override `configureSession` to add persistent memory, compaction, search, and skills:
1195
+
1196
+ ```typescript
1197
+ import { Think, Session } from "@cloudflare/think";
1198
+
1199
+ export class MyAgent extends Think<Env> {
1200
+ getModel() {
1201
+ /* ... */
1202
+ }
1203
+
1204
+ configureSession(session: Session) {
1205
+ return session
1206
+ .withContext("soul", {
1207
+ provider: { get: async () => "You are a helpful coding assistant." }
1208
+ })
1209
+ .withContext("memory", {
1210
+ description: "Important facts learned during conversation.",
1211
+ maxTokens: 2000
1212
+ })
1213
+ .withCachedPrompt();
1214
+ }
1215
+ }
1216
+ ```
1217
+
1218
+ Think's `this.messages` getter reads directly from Session's tree-structured storage. Context blocks, compaction overlays, and search are all handled by Session. See the [Sessions documentation](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md) for the full API.
1219
+
1220
+ ## Package Exports
1221
+
1222
+ | Export | Description |
1223
+ | --------------------------------------- | ------------------------------------------------------------- |
1224
+ | `@cloudflare/think` | `Think`, `Session`, `Workspace`, `skills` namespace |
1225
+ | `@cloudflare/think/framework` | Framework manifest discovery and Worker config helpers |
1226
+ | `@cloudflare/think/server-entry` | Framework Worker entry helpers for custom server handlers |
1227
+ | `@cloudflare/think/messengers` | Messenger contracts, Chat SDK bridge, state agent, delivery |
1228
+ | `@cloudflare/think/messengers/telegram` | Telegram messenger provider and delivery helpers |
1229
+ | `@cloudflare/think/workflows` | `ThinkWorkflow`, `step.prompt()` — Workflow prompts |
1230
+ | `@cloudflare/think/tools/workspace` | `createWorkspaceTools()` — for custom storage backends |
1231
+ | `@cloudflare/think/tools/execute` | `createExecuteTool()` — sandboxed code execution via codemode |
1232
+ | `@cloudflare/think/tools/extensions` | `createExtensionTools()` — LLM-driven extension loading |
1233
+ | `@cloudflare/think/extensions` | `ExtensionManager`, `HostBridgeLoopback` — extension runtime |
1234
+ | `@cloudflare/think/vite` | Think Vite plugin and generated Worker config helpers |
1235
+
1236
+ ## Dependencies
1237
+
1238
+ Peer dependencies you provide:
1239
+
1240
+ | Package | Required | Notes |
1241
+ | ------------------------ | -------- | -------------------------------------------- |
1242
+ | `agents` | yes | Cloudflare Agents SDK |
1243
+ | `ai` | yes | Vercel AI SDK v6 |
1244
+ | `zod` | yes | Schema validation (v4) |
1245
+ | `@chat-adapter/telegram` | optional | Required for Telegram messengers |
1246
+ | `vite` | optional | Required for the Think Vite plugin (`/vite`) |
1247
+
1248
+ Bundled with `@cloudflare/think`:
1249
+
1250
+ | Package | Notes |
1251
+ | ---------------------- | ----------------------------------------------------- |
1252
+ | `@cloudflare/shell` | `Workspace` filesystem |
1253
+ | `@cloudflare/codemode` | Code execution for `createExecuteTool()` |
1254
+ | `just-bash` | Sandboxed shell for the default workspace `bash` tool |
1255
+ | `aywson` | Wrangler JSON/JSONC parsing for the framework plugin |
1256
+
1257
+ The Agent Skills engine and its script runner live in
1258
+ [`agents/skills`](https://github.com/cloudflare/agents/blob/main/packages/agents/AGENTS.md) (so skill scripts pull
1259
+ `@cloudflare/worker-bundler` and `just-bash` through `agents`, not Think).
1260
+
1261
+ ## Docs
1262
+
1263
+ - [Getting Started](./getting-started.md) — Build a Think agent step by step
1264
+ - [Lifecycle Hooks](./lifecycle-hooks.md) — `beforeTurn`, `beforeStep`, `onStepFinish`, `onChunk`, `onChatResponse`, and more
1265
+ - [Tools](./tools.md) — Workspace tools, code execution, extensions
1266
+ - [Actions](./actions.md) — Server actions with idempotency, approvals, authorization, and reply attachments
1267
+ - [Channels](./channels.md) — Per-channel policy, channel selection, and out-of-band notices
1268
+ - [Messengers](./messengers.md) — Chat SDK messenger ingress and delivery
1269
+ - [Client Tools](./client-tools.md) — Browser-side tools, approvals, and concurrency
1270
+ - [Sub-agents and Programmatic Turns](./sub-agents.md) — RPC streaming, `saveMessages`, recovery
1271
+ - [Programmatic Submissions](./programmatic-submissions.md) — durable acceptance, idempotent retry, cancellation, and status inspection
1272
+ - [Workflows](./workflows.md) — `ThinkWorkflow`, `step.prompt()`, structured output, and long-running workflow steps