@cloudflare/think 0.10.0 → 0.11.1
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 +73 -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/fetch-By3eIQ-a.d.ts +147 -0
- package/dist/framework/index.d.ts +17 -62
- package/dist/framework/index.js +3 -57
- package/dist/{think-i1Pkgb1R.d.ts → index-CR4-ffm_.d.ts} +1734 -736
- 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 +3 -2
- package/dist/think.js +8406 -2
- package/dist/think.js.map +1 -0
- package/dist/tools/extensions.js +1 -1
- package/dist/tools/fetch.d.ts +22 -0
- package/dist/tools/fetch.js +646 -0
- package/dist/tools/fetch.js.map +1 -0
- 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 +1324 -0
- package/docs/lifecycle-hooks.md +850 -0
- package/docs/messengers.md +197 -0
- package/docs/programmatic-submissions.md +206 -0
- package/docs/sub-agents.md +524 -0
- package/docs/tools.md +582 -0
- package/docs/workflows.md +217 -0
- package/package.json +50 -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
package/docs/index.md
ADDED
|
@@ -0,0 +1,1324 @@
|
|
|
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
|
+
| `fetchTools` | `false` | Opt-in allowlisted, read-only HTTP fetch tools (`fetch_url` + per-binding `fetch_<name>`). Set to a config object; see [Fetch tool](#fetch-tool) |
|
|
856
|
+
| `messageConcurrency` | `"queue"` | How overlapping submits behave — see [Client Tools](./client-tools.md) |
|
|
857
|
+
| `waitForMcpConnections` | `false` | Wait for MCP servers before inference |
|
|
858
|
+
| `chatRecovery` | `true` | Wrap turns in `runFiber` for durable execution, including sub-agent turns. Set to `{ maxAttempts, stableTimeoutMs, terminalMessage, onExhausted }` to tune bounded recovery. |
|
|
859
|
+
| `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. |
|
|
860
|
+
| `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). |
|
|
861
|
+
|
|
862
|
+
## Agent Skills
|
|
863
|
+
|
|
864
|
+
Think supports [Agent Skills](https://agentskills.io/) as on-demand
|
|
865
|
+
instructions. A skill source provides a catalog of skill names and descriptions;
|
|
866
|
+
Think adds that catalog to the system prompt and exposes tools the model can use
|
|
867
|
+
when a user task matches a skill.
|
|
868
|
+
|
|
869
|
+
Bundled skills are usually imported with the Think Vite plugin, which includes
|
|
870
|
+
the Agent Skills import support:
|
|
871
|
+
|
|
872
|
+
```typescript
|
|
873
|
+
import { Think, skills } from "@cloudflare/think";
|
|
874
|
+
import bundledSkills from "agents:skills"; // resolves to ./skills next to this file
|
|
875
|
+
|
|
876
|
+
type Env = {
|
|
877
|
+
AI: Ai;
|
|
878
|
+
LOADER: WorkerLoader;
|
|
879
|
+
SKILLS_BUCKET: R2Bucket;
|
|
880
|
+
};
|
|
881
|
+
|
|
882
|
+
export class MyAgent extends Think<Env> {
|
|
883
|
+
getSkills() {
|
|
884
|
+
return [
|
|
885
|
+
bundledSkills,
|
|
886
|
+
skills.r2(this.env.SKILLS_BUCKET, { prefix: "skills/" })
|
|
887
|
+
];
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
getSkillScriptRunner() {
|
|
891
|
+
return skills.runner({
|
|
892
|
+
loader: this.env.LOADER,
|
|
893
|
+
workspaceInstance: this.workspace
|
|
894
|
+
});
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
```
|
|
898
|
+
|
|
899
|
+
`agents:skills` resolves to a `./skills` directory next to the importing file;
|
|
900
|
+
use `agents:skills/<dir>` to point at a differently named sibling directory.
|
|
901
|
+
The `agents:skills` import is typed by ambient declarations that ship with
|
|
902
|
+
`agents`, so importing `Think` in the same file brings the type into scope (for
|
|
903
|
+
a file that imports only the specifier, add
|
|
904
|
+
`/// <reference types="agents/skills-module" />`). If you are not using the
|
|
905
|
+
Agents Vite plugin, build a source with `skills.fromManifest(...)` instead.
|
|
906
|
+
|
|
907
|
+
The skills engine lives in `agents/skills` and is framework-agnostic, so any
|
|
908
|
+
agent (including a plain `@cloudflare/ai-chat` `onChatMessage`) can build a
|
|
909
|
+
`SkillRegistry`; `@cloudflare/think` re-exports it as `skills` and wires
|
|
910
|
+
`getSkills()` into the turn automatically.
|
|
911
|
+
|
|
912
|
+
Sources are applied in order; the first source to register a skill name wins,
|
|
913
|
+
and later duplicates (or a source that fails to load) are skipped with a logged
|
|
914
|
+
warning rather than failing the agent.
|
|
915
|
+
|
|
916
|
+
The imported directory should contain one child directory per skill:
|
|
917
|
+
|
|
918
|
+
```text
|
|
919
|
+
agents/my-agent/skills/release-notes/SKILL.md
|
|
920
|
+
agents/my-agent/skills/release-notes/scripts/format-release-notes.ts
|
|
921
|
+
agents/my-agent/skills/release-notes/references/style-guide.md
|
|
922
|
+
```
|
|
923
|
+
|
|
924
|
+
When skills are available, Think exposes:
|
|
925
|
+
|
|
926
|
+
| Tool | Purpose |
|
|
927
|
+
| --------------------- | ------------------------------------------------------------------- |
|
|
928
|
+
| `activate_skill` | Load a matching skill's instructions and bundled resource list |
|
|
929
|
+
| `read_skill_resource` | Read a bundled resource by `{ name, path }` or `skill-name/path` |
|
|
930
|
+
| `run_skill_script` | Run a bundled script when `getSkillScriptRunner()` returns a runner |
|
|
931
|
+
|
|
932
|
+
Skills are not always-on system prompt text. Use `getSystemPrompt()` or a
|
|
933
|
+
Session context block for behavior that should apply to every turn. Use skills
|
|
934
|
+
for task-specific procedures, references, scripts, templates, and assets that
|
|
935
|
+
should be loaded only when relevant.
|
|
936
|
+
|
|
937
|
+
Script execution is opt-in and requires a Worker Loader binding:
|
|
938
|
+
|
|
939
|
+
```jsonc
|
|
940
|
+
{
|
|
941
|
+
"worker_loaders": [{ "binding": "LOADER" }]
|
|
942
|
+
}
|
|
943
|
+
```
|
|
944
|
+
|
|
945
|
+
`skills.runner()` is experimental and runs JavaScript, TypeScript, Python, and
|
|
946
|
+
Bash scripts under `scripts/`. TypeScript is compiled with
|
|
947
|
+
`@cloudflare/worker-bundler`; Python runs as Python Dynamic Workers; Bash runs
|
|
948
|
+
through `just-bash`.
|
|
949
|
+
|
|
950
|
+
JavaScript and TypeScript scripts are function-style:
|
|
951
|
+
|
|
952
|
+
```typescript
|
|
953
|
+
import type { SkillRunContext } from "@cloudflare/think";
|
|
954
|
+
|
|
955
|
+
export default async function run(input: unknown, ctx: SkillRunContext) {
|
|
956
|
+
const guide = ctx.files["references/style-guide.md"]; // bundled text resources
|
|
957
|
+
const docs = await ctx.workspace.readFile("README.md"); // gated by permission
|
|
958
|
+
const summary = await ctx.tools.call("summarize", { input }); // explicit tools
|
|
959
|
+
await ctx.output.writeFile("notes.md", summary); // scratch artifact
|
|
960
|
+
return { ok: true };
|
|
961
|
+
}
|
|
962
|
+
```
|
|
963
|
+
|
|
964
|
+
`ctx` is `{ skill, files, workspace, tools, output }`. `ctx.files` holds bundled
|
|
965
|
+
text resources by relative path, `ctx.workspace` is gated by the workspace
|
|
966
|
+
permission, `ctx.tools` only exposes tools the runner was given, and
|
|
967
|
+
`ctx.output.writeFile(name, content)` returns scratch artifacts to the model
|
|
968
|
+
(it does not mutate the workspace). Python and Bash use the path-based contract
|
|
969
|
+
instead: `/input.json`, `/context.json`, bundled resources under `/skill`, and
|
|
970
|
+
`/output` for artifacts.
|
|
971
|
+
|
|
972
|
+
Passing `workspaceInstance` gives scripts read-only workspace access by default.
|
|
973
|
+
Network access, tools, and workspace writes are opt-in. The default timeout is
|
|
974
|
+
30 seconds.
|
|
975
|
+
|
|
976
|
+
### Chat Recovery
|
|
977
|
+
|
|
978
|
+
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.
|
|
979
|
+
|
|
980
|
+
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).
|
|
981
|
+
|
|
982
|
+
Override `onChatRecovery` when you need provider-specific recovery, such as retrieving a stored OpenAI Responses result instead of issuing a new model call:
|
|
983
|
+
|
|
984
|
+
```typescript
|
|
985
|
+
import type {
|
|
986
|
+
ChatRecoveryContext,
|
|
987
|
+
ChatRecoveryOptions
|
|
988
|
+
} from "@cloudflare/think";
|
|
989
|
+
|
|
990
|
+
export class MyAgent extends Think<Env> {
|
|
991
|
+
override chatRecovery = {
|
|
992
|
+
maxAttempts: 10,
|
|
993
|
+
terminalMessage: "The assistant was interrupted. Please try again."
|
|
994
|
+
};
|
|
995
|
+
|
|
996
|
+
override async onChatRecovery(
|
|
997
|
+
ctx: ChatRecoveryContext
|
|
998
|
+
): Promise<ChatRecoveryOptions> {
|
|
999
|
+
console.log("Recovering chat turn", ctx.incidentId, ctx.attempt);
|
|
1000
|
+
return {}; // persist partial output and continue/retry when possible
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
```
|
|
1004
|
+
|
|
1005
|
+
The same recovery events are available through `agents/observability` on the `chat` channel. Transcript repairs are emitted on the `transcript` channel.
|
|
1006
|
+
|
|
1007
|
+
#### Repairing interrupted tool calls
|
|
1008
|
+
|
|
1009
|
+
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.
|
|
1010
|
+
|
|
1011
|
+
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:
|
|
1012
|
+
|
|
1013
|
+
```typescript
|
|
1014
|
+
import type { UIMessage } from "ai";
|
|
1015
|
+
|
|
1016
|
+
export class MyAgent extends Think<Env> {
|
|
1017
|
+
protected override repairInterruptedToolPart(
|
|
1018
|
+
part: UIMessage["parts"][number]
|
|
1019
|
+
): UIMessage["parts"][number] {
|
|
1020
|
+
const record = part as Record<string, unknown>;
|
|
1021
|
+
if (record.type === "tool-ask_user") {
|
|
1022
|
+
const input = record.input as { prompt?: string } | undefined;
|
|
1023
|
+
if (input?.prompt) {
|
|
1024
|
+
return { type: "text", text: input.prompt };
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
return super.repairInterruptedToolPart(part);
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
```
|
|
1031
|
+
|
|
1032
|
+
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.
|
|
1033
|
+
|
|
1034
|
+
### Context-window overflow recovery
|
|
1035
|
+
|
|
1036
|
+
[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.
|
|
1037
|
+
|
|
1038
|
+
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.
|
|
1039
|
+
|
|
1040
|
+
**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.
|
|
1041
|
+
|
|
1042
|
+
```typescript
|
|
1043
|
+
import { Think, defaultContextOverflowClassifier } from "@cloudflare/think";
|
|
1044
|
+
|
|
1045
|
+
export class MyAgent extends Think<Env> {
|
|
1046
|
+
override contextOverflow = { reactive: true };
|
|
1047
|
+
|
|
1048
|
+
// The bundled classifier covers the common providers (Anthropic, OpenAI,
|
|
1049
|
+
// Google, Bedrock, …). Assign it directly, or write your own.
|
|
1050
|
+
override classifyChatError = defaultContextOverflowClassifier;
|
|
1051
|
+
}
|
|
1052
|
+
```
|
|
1053
|
+
|
|
1054
|
+
**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.
|
|
1055
|
+
|
|
1056
|
+
```typescript
|
|
1057
|
+
import { Think, defaultContextOverflowClassifier } from "@cloudflare/think";
|
|
1058
|
+
|
|
1059
|
+
export class MyAgent extends Think<Env> {
|
|
1060
|
+
override contextOverflow = {
|
|
1061
|
+
reactive: true,
|
|
1062
|
+
// Compact mid-turn once a step approaches 90% of a 200K window.
|
|
1063
|
+
proactive: { maxInputTokens: 200_000 }
|
|
1064
|
+
};
|
|
1065
|
+
|
|
1066
|
+
override classifyChatError = defaultContextOverflowClassifier;
|
|
1067
|
+
}
|
|
1068
|
+
```
|
|
1069
|
+
|
|
1070
|
+
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).
|
|
1071
|
+
|
|
1072
|
+
> 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)).
|
|
1073
|
+
|
|
1074
|
+
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).
|
|
1075
|
+
|
|
1076
|
+
## Dynamic Configuration
|
|
1077
|
+
|
|
1078
|
+
`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:
|
|
1079
|
+
|
|
1080
|
+
```typescript
|
|
1081
|
+
type MyConfig = { modelTier: "fast" | "capable"; theme: string };
|
|
1082
|
+
|
|
1083
|
+
export class MyAgent extends Think<Env> {
|
|
1084
|
+
getModel() {
|
|
1085
|
+
const tier = this.getConfig<MyConfig>()?.modelTier ?? "fast";
|
|
1086
|
+
const models = {
|
|
1087
|
+
fast: "@cf/moonshotai/kimi-k2.7-code",
|
|
1088
|
+
capable: "@cf/meta/llama-4-scout-17b-16e-instruct"
|
|
1089
|
+
};
|
|
1090
|
+
return createWorkersAI({ binding: this.env.AI })(models[tier]);
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
```
|
|
1094
|
+
|
|
1095
|
+
| Method | Description |
|
|
1096
|
+
| ---------------------- | ------------------------------------------------------------- |
|
|
1097
|
+
| `configure<T>(config)` | Persist a config object (type checked via the method generic) |
|
|
1098
|
+
| `getConfig<T>()` | Read the persisted configuration, or null if never configured |
|
|
1099
|
+
|
|
1100
|
+
Prefer `state` / `setState` from `Agent` when you want the value broadcast to connected clients. Use `configure` for private, server-side settings.
|
|
1101
|
+
|
|
1102
|
+
Expose configuration to the client via `@callable`:
|
|
1103
|
+
|
|
1104
|
+
```typescript
|
|
1105
|
+
import { callable } from "agents";
|
|
1106
|
+
|
|
1107
|
+
export class MyAgent extends Think<Env> {
|
|
1108
|
+
getModel() {
|
|
1109
|
+
/* ... */
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
@callable()
|
|
1113
|
+
updateConfig(config: MyConfig) {
|
|
1114
|
+
this.configure<MyConfig>(config);
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
```
|
|
1118
|
+
|
|
1119
|
+
## Scheduled Tasks
|
|
1120
|
+
|
|
1121
|
+
Use `getScheduledTasks()` when code should create recurring Think turns or
|
|
1122
|
+
deterministic scheduled handlers. Think reconciles the declarations on startup,
|
|
1123
|
+
stores a durable one-shot schedule for the next occurrence, and re-arms the next
|
|
1124
|
+
occurrence after each run.
|
|
1125
|
+
|
|
1126
|
+
```typescript
|
|
1127
|
+
import { Think } from "@cloudflare/think";
|
|
1128
|
+
import type { ThinkScheduledTasks } from "@cloudflare/think";
|
|
1129
|
+
|
|
1130
|
+
export class DigestAgent extends Think<Env> {
|
|
1131
|
+
getDefaultTimezone() {
|
|
1132
|
+
return "Europe/London";
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
getScheduledTasks(): ThinkScheduledTasks {
|
|
1136
|
+
return {
|
|
1137
|
+
weeklyCommitReport: {
|
|
1138
|
+
schedule: "every week on monday at 09:00",
|
|
1139
|
+
prompt:
|
|
1140
|
+
"Compile all my GitHub commits for the last week and send a concise summary."
|
|
1141
|
+
},
|
|
1142
|
+
workout: {
|
|
1143
|
+
schedule: "every day at 08:00 in Europe/London",
|
|
1144
|
+
prompt: "Start my workout."
|
|
1145
|
+
},
|
|
1146
|
+
customerDigest: {
|
|
1147
|
+
schedule: "every day at 09:00",
|
|
1148
|
+
timezone: "America/New_York",
|
|
1149
|
+
metadata: { workflowName: "customer-digest" },
|
|
1150
|
+
retry: { maxAttempts: 3 },
|
|
1151
|
+
handler: async ({
|
|
1152
|
+
idempotencyKey,
|
|
1153
|
+
scheduledFor,
|
|
1154
|
+
scheduleKind,
|
|
1155
|
+
timezone
|
|
1156
|
+
}) => {
|
|
1157
|
+
await this.env.DIGEST_WORKFLOW.create({
|
|
1158
|
+
id: idempotencyKey,
|
|
1159
|
+
params: { scheduledFor, scheduleKind, timezone }
|
|
1160
|
+
});
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
};
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
```
|
|
1167
|
+
|
|
1168
|
+
The DSL supports `every <n> minutes`, `every <n> hours`,
|
|
1169
|
+
`every day at HH:mm`, `every weekday at HH:mm`, and
|
|
1170
|
+
`every week on monday,wednesday at HH:mm`. Wall-clock schedules require either
|
|
1171
|
+
an inline timezone, a task `timezone`, or `getDefaultTimezone()`. If an alarm is
|
|
1172
|
+
late, Think runs the intended occurrence once and schedules the next future
|
|
1173
|
+
occurrence; it does not backfill missed runs.
|
|
1174
|
+
|
|
1175
|
+
Each task must define exactly one of `prompt` or `handler`. Prompt tasks create a
|
|
1176
|
+
durable submission with `submitMessages()`. Handler tasks receive
|
|
1177
|
+
`{ taskId, scheduledFor, scheduledForDate, occurrenceKey, idempotencyKey,
|
|
1178
|
+
schedule, scheduleKind, timezone, metadata }` and are intended for app-owned
|
|
1179
|
+
work such as creating a Workflow run or writing a run ledger. Delivery is
|
|
1180
|
+
at-least-once; use `idempotencyKey` or `occurrenceKey` for your own durable
|
|
1181
|
+
idempotency.
|
|
1182
|
+
|
|
1183
|
+
Static declarations reconcile on startup. If `getScheduledTasks()` reads
|
|
1184
|
+
product-owned data that can change while the Durable Object is live, call
|
|
1185
|
+
`internal_reconcileScheduledTasks()` after updating that data. During
|
|
1186
|
+
reconciliation Think records the task row before creating the underlying Agent
|
|
1187
|
+
schedule, so a missing `schedule_id` is only a pending reconcile state and is
|
|
1188
|
+
repaired on the next reconcile. The task `retry` option retries the prompt or
|
|
1189
|
+
handler action before the failure is logged. The next occurrence is still
|
|
1190
|
+
scheduled after the action succeeds or exhausts its retries, so failed
|
|
1191
|
+
occurrences do not block future runs.
|
|
1192
|
+
|
|
1193
|
+
## Fetch tool
|
|
1194
|
+
|
|
1195
|
+
Think can give the model a conservative, **read-only** way to read HTTP resources. It is **off by default**. Set the `fetchTools` property for static config, or call `createFetchTools()` inside `getTools()` for per-tenant/dynamic allowlists (it runs every turn). When configured, Think registers a generic `fetch_url` tool (when a public `allowlist` is provided) plus one `fetch_<name>` tool per binding target, and advertises the capability in the system prompt.
|
|
1196
|
+
|
|
1197
|
+
```typescript
|
|
1198
|
+
export class DocsAgent extends Think<Env> {
|
|
1199
|
+
getModel() {
|
|
1200
|
+
/* ... */
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
fetchTools = {
|
|
1204
|
+
allowlist: ["https://developers.cloudflare.com/**"],
|
|
1205
|
+
bindings: {
|
|
1206
|
+
docsApi: {
|
|
1207
|
+
binding: this.env.DOCS_API, // a service binding / Fetcher
|
|
1208
|
+
description: "Internal docs search API.",
|
|
1209
|
+
allowlist: ["/v1/docs/**"],
|
|
1210
|
+
headers: { "x-agent": "think" } // fixed, server-side, never model-set
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
};
|
|
1214
|
+
}
|
|
1215
|
+
```
|
|
1216
|
+
|
|
1217
|
+
The model sees named tools — `fetch_url({ url, response?, headers? })` and `fetch_docsApi({ path, response?, headers? })` — rather than one polymorphic tool, so per-target policy is baked into each tool.
|
|
1218
|
+
|
|
1219
|
+
**Safety model.** The threat surface is the Workers runtime: reaching loopback/`.internal`/internally bound targets, allowlist-bypass tricks, prompt-injected URLs, credential leakage, and context/storage bloat.
|
|
1220
|
+
|
|
1221
|
+
- **Read-only** — `GET` only. Mutations belong in explicit, approval-gated [Actions](#actions), not here.
|
|
1222
|
+
- **Allowlisted** — every request must match the configured allowlist. URLs are normalized (host lowercased, credentials rejected, paths resolved) before matching, and private/loopback/link-local/`*.internal` targets are blocked for `fetch_url` even if the allowlist is misconfigured.
|
|
1223
|
+
- **Bounded** — `maxBytes` caps the download, `maxModelChars` truncates the model-facing text (`truncated: true`), and `response: "workspace"` (or `spillToWorkspace: true` in auto mode) writes large or binary bodies to a workspace file so the transcript stays small.
|
|
1224
|
+
- **Header-safe** — only headers in `modelHeaderAllowlist` (default `accept`, `accept-language`, `range`) may be set by the model; fixed binding headers are server-side only and are stripped on cross-origin redirects.
|
|
1225
|
+
- **Markdown-first** — a weighted default `Accept` header (`text/markdown` → `text/plain` → `application/json` → `text/html` → `*/*;q=0.1`) nudges content-negotiating endpoints (docs platforms, `llms.txt`-style endpoints) to return clean markdown instead of HTML, while still accepting anything so a strict server never returns `406`. Override per call (the model can set `accept`) or globally via `defaultAccept` (`""` disables it).
|
|
1226
|
+
- **Redirects** — `followRedirects` (`allowlisted` by default) follows a redirect only when the final URL is still allowlisted; binding targets never follow cross-origin redirects.
|
|
1227
|
+
|
|
1228
|
+
Results are structured values (never thrown). Success carries `{ ok: true, status, finalUrl, contentType, bytes, truncated, response, body?/json?/path? }`; failure carries `{ ok: false, code, message, status?, finalUrl? }` where `code` is one of `disallowed_url`, `disallowed_redirect`, `timeout`, `aborted`, `non_2xx`, `unsupported_content_type`, `invalid_json`, `too_large`, `request_failed`. A `tool:fetch` observability event fires on every call, including blocked attempts, for audit.
|
|
1229
|
+
|
|
1230
|
+
**Allowlist semantics.** A bare origin (`https://example.com`) matches that origin and every subpath. Patterns are globs — `**` matches any characters (including `/`) and `*` matches any character except `/`; a pattern with an explicit path and no glob matches that path literally (`https://x.com/v1` matches only `/v1`). Matching ignores the query string and fragment (only scheme + host + port + path are compared), though the original query/fragment are still sent. Binding allowlists should be path-based (`/v1/docs/**`). Note that `json` responses are bounded by `maxBytes` (only `text` is truncated by `maxModelChars`), so for large JSON APIs lower `maxBytes` or use `response: "workspace"`.
|
|
1231
|
+
|
|
1232
|
+
You do not need new machinery to gate egress per call: `beforeToolCall` can `block` or `substitute` a fetch, and channel `tools(...)` policy can narrow which fetch tools are available.
|
|
1233
|
+
|
|
1234
|
+
**When to use what:**
|
|
1235
|
+
|
|
1236
|
+
| Capability | Use it for |
|
|
1237
|
+
| -------------------------------- | ---------------------------------------------------------------------------------------- |
|
|
1238
|
+
| Fetch tool | Reading a known, allowlisted URL or service binding; no code generation |
|
|
1239
|
+
| `createExecuteTool()` (codemode) | Composing/transforming several calls in sandboxed code (`globalOutbound`) |
|
|
1240
|
+
| Browser Run (`tools/browser`) | Rendered pages, auth flows, screenshots, CDP automation |
|
|
1241
|
+
| Typed tools / `agentTool()` | Calling a `WorkerEntrypoint`/DO method with a typed schema, or delegating to a sub-agent |
|
|
1242
|
+
|
|
1243
|
+
## Session Integration
|
|
1244
|
+
|
|
1245
|
+
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:
|
|
1246
|
+
|
|
1247
|
+
```typescript
|
|
1248
|
+
import { Think, Session } from "@cloudflare/think";
|
|
1249
|
+
|
|
1250
|
+
export class MyAgent extends Think<Env> {
|
|
1251
|
+
getModel() {
|
|
1252
|
+
/* ... */
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
configureSession(session: Session) {
|
|
1256
|
+
return session
|
|
1257
|
+
.withContext("soul", {
|
|
1258
|
+
provider: { get: async () => "You are a helpful coding assistant." }
|
|
1259
|
+
})
|
|
1260
|
+
.withContext("memory", {
|
|
1261
|
+
description: "Important facts learned during conversation.",
|
|
1262
|
+
maxTokens: 2000
|
|
1263
|
+
})
|
|
1264
|
+
.withCachedPrompt();
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
```
|
|
1268
|
+
|
|
1269
|
+
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.
|
|
1270
|
+
|
|
1271
|
+
## Package Exports
|
|
1272
|
+
|
|
1273
|
+
| Export | Description |
|
|
1274
|
+
| --------------------------------------- | ------------------------------------------------------------- |
|
|
1275
|
+
| `@cloudflare/think` | `Think`, `Session`, `Workspace`, `skills` namespace |
|
|
1276
|
+
| `@cloudflare/think/framework` | Framework manifest discovery and Worker config helpers |
|
|
1277
|
+
| `@cloudflare/think/server-entry` | Framework Worker entry helpers for custom server handlers |
|
|
1278
|
+
| `@cloudflare/think/messengers` | Messenger contracts, Chat SDK bridge, state agent, delivery |
|
|
1279
|
+
| `@cloudflare/think/messengers/telegram` | Telegram messenger provider and delivery helpers |
|
|
1280
|
+
| `@cloudflare/think/workflows` | `ThinkWorkflow`, `step.prompt()` — Workflow prompts |
|
|
1281
|
+
| `@cloudflare/think/tools/workspace` | `createWorkspaceTools()` — for custom storage backends |
|
|
1282
|
+
| `@cloudflare/think/tools/fetch` | `createFetchTools()` — opt-in allowlisted HTTP reads |
|
|
1283
|
+
| `@cloudflare/think/tools/execute` | `createExecuteTool()` — sandboxed code execution via codemode |
|
|
1284
|
+
| `@cloudflare/think/tools/extensions` | `createExtensionTools()` — LLM-driven extension loading |
|
|
1285
|
+
| `@cloudflare/think/extensions` | `ExtensionManager`, `HostBridgeLoopback` — extension runtime |
|
|
1286
|
+
| `@cloudflare/think/vite` | Think Vite plugin and generated Worker config helpers |
|
|
1287
|
+
|
|
1288
|
+
## Dependencies
|
|
1289
|
+
|
|
1290
|
+
Peer dependencies you provide:
|
|
1291
|
+
|
|
1292
|
+
| Package | Required | Notes |
|
|
1293
|
+
| ------------------------ | -------- | -------------------------------------------- |
|
|
1294
|
+
| `agents` | yes | Cloudflare Agents SDK |
|
|
1295
|
+
| `ai` | yes | Vercel AI SDK v6 |
|
|
1296
|
+
| `zod` | yes | Schema validation (v4) |
|
|
1297
|
+
| `@chat-adapter/telegram` | optional | Required for Telegram messengers |
|
|
1298
|
+
| `vite` | optional | Required for the Think Vite plugin (`/vite`) |
|
|
1299
|
+
|
|
1300
|
+
Bundled with `@cloudflare/think`:
|
|
1301
|
+
|
|
1302
|
+
| Package | Notes |
|
|
1303
|
+
| ---------------------- | ----------------------------------------------------- |
|
|
1304
|
+
| `@cloudflare/shell` | `Workspace` filesystem |
|
|
1305
|
+
| `@cloudflare/codemode` | Code execution for `createExecuteTool()` |
|
|
1306
|
+
| `just-bash` | Sandboxed shell for the default workspace `bash` tool |
|
|
1307
|
+
| `aywson` | Wrangler JSON/JSONC parsing for the framework plugin |
|
|
1308
|
+
|
|
1309
|
+
The Agent Skills engine and its script runner live in
|
|
1310
|
+
[`agents/skills`](https://github.com/cloudflare/agents/blob/main/packages/agents/AGENTS.md) (so skill scripts pull
|
|
1311
|
+
`@cloudflare/worker-bundler` and `just-bash` through `agents`, not Think).
|
|
1312
|
+
|
|
1313
|
+
## Docs
|
|
1314
|
+
|
|
1315
|
+
- [Getting Started](./getting-started.md) — Build a Think agent step by step
|
|
1316
|
+
- [Lifecycle Hooks](./lifecycle-hooks.md) — `beforeTurn`, `beforeStep`, `onStepFinish`, `onChunk`, `onChatResponse`, and more
|
|
1317
|
+
- [Tools](./tools.md) — Workspace tools, code execution, extensions
|
|
1318
|
+
- [Actions](./actions.md) — Server actions with idempotency, approvals, authorization, and reply attachments
|
|
1319
|
+
- [Channels](./channels.md) — Per-channel policy, channel selection, and out-of-band notices
|
|
1320
|
+
- [Messengers](./messengers.md) — Chat SDK messenger ingress and delivery
|
|
1321
|
+
- [Client Tools](./client-tools.md) — Browser-side tools, approvals, and concurrency
|
|
1322
|
+
- [Sub-agents and Programmatic Turns](./sub-agents.md) — RPC streaming, `saveMessages`, recovery
|
|
1323
|
+
- [Programmatic Submissions](./programmatic-submissions.md) — durable acceptance, idempotent retry, cancellation, and status inspection
|
|
1324
|
+
- [Workflows](./workflows.md) — `ThinkWorkflow`, `step.prompt()`, structured output, and long-running workflow steps
|