@cloudflare/think 0.7.3 → 0.8.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 +420 -43
- package/dist/chat-sdk-Bb93yaZh.js +669 -0
- package/dist/chat-sdk-Bb93yaZh.js.map +1 -0
- package/dist/{classPrivateFieldGet2-BP1jgEfY.js → classPrivateFieldGet2-D_obpP6O.js} +5 -5
- package/dist/extensions/index.d.ts +2 -2
- package/dist/extensions/index.js +2 -2
- package/dist/{hook-proxy-5248W-ea.js → hook-proxy-CkF0EhRO.js} +1 -1
- package/dist/{hook-proxy-5248W-ea.js.map → hook-proxy-CkF0EhRO.js.map} +1 -1
- package/dist/{index-BsB4GUsL.d.ts → index-B-zgBVj2.d.ts} +2 -2
- package/dist/index-DpPdyY46.d.ts +2309 -0
- package/dist/{manager-px912SoZ.js → manager-DnCkoyVo.js} +3 -3
- package/dist/{manager-px912SoZ.js.map → manager-DnCkoyVo.js.map} +1 -1
- package/dist/{manager-DCbSiSWT.d.ts → manager-dOcdCX4u.d.ts} +1 -1
- package/dist/messengers/index.d.ts +110 -0
- package/dist/messengers/index.js +2 -0
- package/dist/messengers/telegram.d.ts +62 -0
- package/dist/messengers/telegram.js +84 -0
- package/dist/messengers/telegram.js.map +1 -0
- package/dist/think.d.ts +73 -1160
- package/dist/think.js +2391 -204
- package/dist/think.js.map +1 -1
- package/dist/tools/extensions.d.ts +1 -1
- package/dist/tools/extensions.js +1 -1
- package/dist/tools/workspace.d.ts +35 -334
- package/dist/tools/workspace.js +283 -3
- package/dist/tools/workspace.js.map +1 -1
- package/dist/workflows.d.ts +78 -0
- package/dist/workflows.js +119 -0
- package/dist/workflows.js.map +1 -0
- package/dist/workspace-BZXdZcuw.d.ts +342 -0
- package/package.json +25 -8
package/README.md
CHANGED
|
@@ -27,6 +27,90 @@ export class MyAgent extends Think<Env> {
|
|
|
27
27
|
|
|
28
28
|
That's it. Think handles the WebSocket chat protocol, message persistence, the agentic loop, message sanitization, stream resumption, client tool support, and workspace file tools. Connect from the browser with `useAgentChat` from `@cloudflare/ai-chat`.
|
|
29
29
|
|
|
30
|
+
## Messengers
|
|
31
|
+
|
|
32
|
+
Think can own messenger ingress directly. Declare providers with
|
|
33
|
+
`getMessengers()` and import provider implementations from subpaths so unused
|
|
34
|
+
Chat SDK adapters are not bundled.
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { Think } from "@cloudflare/think";
|
|
38
|
+
import {
|
|
39
|
+
defineMessengers,
|
|
40
|
+
ThinkMessengerStateAgent
|
|
41
|
+
} from "@cloudflare/think/messengers";
|
|
42
|
+
import telegramMessenger from "@cloudflare/think/messengers/telegram";
|
|
43
|
+
|
|
44
|
+
export { ThinkMessengerStateAgent };
|
|
45
|
+
|
|
46
|
+
export class SupportAgent extends Think<Env> {
|
|
47
|
+
getMessengers() {
|
|
48
|
+
return defineMessengers({
|
|
49
|
+
telegram: telegramMessenger({
|
|
50
|
+
token: this.env.TELEGRAM_BOT_TOKEN,
|
|
51
|
+
userName: "support_bot",
|
|
52
|
+
secretToken: this.env.TELEGRAM_WEBHOOK_SECRET_TOKEN
|
|
53
|
+
})
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
The root Think agent handles the webhook route with this precedence: framework
|
|
60
|
+
sub-agent routing, Think internal routes, messenger routes, then user
|
|
61
|
+
`onRequest`. By default, `telegram` maps to
|
|
62
|
+
`/messengers/telegram/webhook`, direct messages and mentions are routed to the
|
|
63
|
+
agent, and new mentions subscribe the thread so later mentions in the same
|
|
64
|
+
thread are still observed. Ordinary subscribed-thread messages and button
|
|
65
|
+
actions are opt-in with `respondTo: ["subscribed-thread", "action"]`. Each Chat
|
|
66
|
+
SDK thread runs in its own Think sub-agent to avoid accidental context sharing.
|
|
67
|
+
Each root agent owns one Chat SDK runtime for all configured messengers, so
|
|
68
|
+
multi-provider agents do not fight over Chat SDK singleton state.
|
|
69
|
+
|
|
70
|
+
Use `conversation: "self"` when all messenger traffic should share the root
|
|
71
|
+
agent's memory. Use a custom `conversation(event)` resolver to route by thread,
|
|
72
|
+
channel, tenant, or user.
|
|
73
|
+
|
|
74
|
+
Messenger state uses `agents/chat-sdk` under the hood. Export
|
|
75
|
+
`ThinkMessengerStateAgent` from the Worker module so sub-agent routing can
|
|
76
|
+
resolve it; production apps do not need to add a separate durable object binding
|
|
77
|
+
or migration for this facet-only class. Test harnesses may still need explicit
|
|
78
|
+
bindings.
|
|
79
|
+
|
|
80
|
+
Inbound messenger replies use the streamed `chat()` path by default: the root
|
|
81
|
+
agent starts an idempotent fiber, resolves the conversation target, calls
|
|
82
|
+
`target.chat(message, callback)`, and lets the provider delivery policy post or
|
|
83
|
+
edit messages. Recovery snapshots store only serializable event/thread data, so
|
|
84
|
+
interrupted replies can either resume before streaming starts or post the
|
|
85
|
+
configured interruption message after streaming has begun. `submitMessages()`
|
|
86
|
+
remains the right primitive for non-streaming programmatic sends, scheduled
|
|
87
|
+
digests, or background work.
|
|
88
|
+
|
|
89
|
+
During a messenger turn, `getMessengerContext()` returns the initiating
|
|
90
|
+
messenger context even after assistant messages are persisted. Telegram webhook
|
|
91
|
+
verification is explicit: provide `secretToken`, a custom `verifyWebhook`, or
|
|
92
|
+
`verifyWebhook: false` when intentionally running without verification. Custom
|
|
93
|
+
messengers built with `chatSdkMessenger()` must make the same choice explicitly.
|
|
94
|
+
Delivery failures use a generic user-facing error by default so internal
|
|
95
|
+
exception details are not posted into external chats.
|
|
96
|
+
|
|
97
|
+
Provider-neutral events include thread, author, message, action, capabilities,
|
|
98
|
+
and attachment metadata. Attachment bytes are only fetched when a provider
|
|
99
|
+
supplies a safe fetch function. Telegram is the first provider implementation;
|
|
100
|
+
future Slack, Discord, or Teams entrypoints implement the same messenger
|
|
101
|
+
contract from their own subpaths.
|
|
102
|
+
|
|
103
|
+
Common messenger options:
|
|
104
|
+
|
|
105
|
+
| Option | Default | Description |
|
|
106
|
+
| -------------------- | ------------------------------- | ------------------------------------------------------------------------------- |
|
|
107
|
+
| `path` | `/messengers/{id}/webhook` | Webhook path handled before user `onRequest` |
|
|
108
|
+
| `respondTo` | `["direct-message", "mention"]` | Event kinds that should start a Think reply |
|
|
109
|
+
| `subscribeOnMention` | `true` | Subscribe Chat SDK threads after a new mention |
|
|
110
|
+
| `conversation` | `"thread"` | Use one Think sub-agent per Chat SDK thread; set `"self"` to use the root agent |
|
|
111
|
+
| `verifyWebhook` | required | Verification function, or `false` to opt out explicitly |
|
|
112
|
+
| `delivery` | provider defaults | Streaming limits, text splitting, and safe user-facing failure messages |
|
|
113
|
+
|
|
30
114
|
## Agent tools
|
|
31
115
|
|
|
32
116
|
Think subclasses can be dispatched as agent tools from another Agent. The parent
|
|
@@ -65,9 +149,15 @@ drill-in, and cleanup patterns.
|
|
|
65
149
|
|
|
66
150
|
## Built-in workspace
|
|
67
151
|
|
|
68
|
-
Every Think agent gets `this.workspace` — a virtual filesystem backed by the DO's SQLite storage. Workspace tools (`read`, `write`, `edit`, `list`, `find`, `grep`, `delete`) are automatically available to the model.
|
|
152
|
+
Every Think agent gets `this.workspace` — a virtual filesystem backed by the DO's SQLite storage. Workspace tools (`read`, `write`, `edit`, `list`, `find`, `grep`, `delete`, `bash`) are automatically available to the model.
|
|
69
153
|
|
|
70
154
|
The `read` tool returns line-numbered text for text files. For images and PDFs, it keeps the persisted tool result compact and passes file bytes to multimodal-capable models using AI SDK content parts.
|
|
155
|
+
The `bash` tool runs sandboxed shell workflows through `just-bash`, with network
|
|
156
|
+
access disabled by default, and syncs changed files and empty directories back
|
|
157
|
+
into the workspace. It snapshots up to 1,000 files by default, skips files larger
|
|
158
|
+
than 1 MB, and treats skipped paths as protected during write-back. Set
|
|
159
|
+
`workspaceBash = false` on your Think subclass to opt out, or pass an options
|
|
160
|
+
object to tune limits, timeout, and network access.
|
|
71
161
|
|
|
72
162
|
```ts
|
|
73
163
|
export class MyAgent extends Think<Env> {
|
|
@@ -89,48 +179,309 @@ export class MyAgent extends Think<Env> {
|
|
|
89
179
|
}
|
|
90
180
|
```
|
|
91
181
|
|
|
182
|
+
## Agent Skills
|
|
183
|
+
|
|
184
|
+
Think supports the [Agent Skills](https://agentskills.io/) directory format as
|
|
185
|
+
a first-class API. Return one or more `SkillSource` objects from `getSkills()`;
|
|
186
|
+
Think adds the skill catalog to the prompt and exposes `activate_skill` and
|
|
187
|
+
`read_skill_resource` tools when skills are available.
|
|
188
|
+
|
|
189
|
+
```ts
|
|
190
|
+
import { Think, skills } from "@cloudflare/think";
|
|
191
|
+
import bundledSkills from "agents:skills"; // resolves to ./skills next to this file
|
|
192
|
+
|
|
193
|
+
type Env = {
|
|
194
|
+
AI: Ai;
|
|
195
|
+
LOADER: WorkerLoader;
|
|
196
|
+
SKILLS_BUCKET: R2Bucket;
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
export class MyAgent extends Think<Env> {
|
|
200
|
+
getSkills() {
|
|
201
|
+
return [
|
|
202
|
+
bundledSkills,
|
|
203
|
+
skills.r2(this.env.SKILLS_BUCKET, { prefix: "skills/" })
|
|
204
|
+
];
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
getSkillScriptRunner() {
|
|
208
|
+
return skills.runner({
|
|
209
|
+
loader: this.env.LOADER,
|
|
210
|
+
workspaceInstance: this.workspace
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
Bundled skills use the Agents Vite plugin. The `agents:skills` specifier
|
|
217
|
+
resolves to a `./skills` directory next to the importing file; use
|
|
218
|
+
`agents:skills/<dir>` for a differently named sibling directory:
|
|
219
|
+
|
|
220
|
+
```ts
|
|
221
|
+
import bundledSkills from "agents:skills";
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
The import is typed by ambient declarations shipped with `agents` (importing
|
|
225
|
+
`Think`, which pulls in `agents`, is enough; otherwise add
|
|
226
|
+
`/// <reference types="agents/skills-module" />`). Without the Vite plugin,
|
|
227
|
+
construct a source with `skills.fromManifest(...)`. Sources are applied in
|
|
228
|
+
order: the first to register a skill name wins, and duplicate or failing
|
|
229
|
+
sources are skipped with a warning instead of failing the agent.
|
|
230
|
+
|
|
231
|
+
The skills engine itself lives in `agents/skills` (so any agent, including a
|
|
232
|
+
plain `@cloudflare/ai-chat` `onChatMessage`, can build a `SkillRegistry`);
|
|
233
|
+
`@cloudflare/think` re-exports it as `skills` and wires `getSkills()` into the
|
|
234
|
+
turn automatically.
|
|
235
|
+
|
|
236
|
+
The imported directory should contain one child directory per skill:
|
|
237
|
+
|
|
238
|
+
```text
|
|
239
|
+
src/skills/release-notes/SKILL.md
|
|
240
|
+
src/skills/release-notes/scripts/format-release-notes.ts
|
|
241
|
+
src/skills/release-notes/references/style-guide.md
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
Bundled resources are packaged with explicit `encoding` metadata. Text resources
|
|
245
|
+
are returned directly; binary assets are returned as base64. `read_skill_resource`
|
|
246
|
+
can read `{ name, path }` or a qualified path such as
|
|
247
|
+
`release-notes/references/style-guide.md`, which helps skills reference resources
|
|
248
|
+
from other skills.
|
|
249
|
+
|
|
250
|
+
Skills are on-demand instructions, not always-on system prompt text. The model
|
|
251
|
+
sees the catalog first, then calls `activate_skill` when a user task matches a
|
|
252
|
+
skill description. Use `getSystemPrompt()` or a Session context block for
|
|
253
|
+
behavior that should apply to every turn.
|
|
254
|
+
|
|
255
|
+
Script execution is opt-in and **experimental**. `getSkillScriptRunner()`
|
|
256
|
+
enables `run_skill_script`, which can run JavaScript, TypeScript, Python, and
|
|
257
|
+
Bash scripts under `scripts/`.
|
|
258
|
+
|
|
259
|
+
JavaScript and TypeScript scripts are function-style:
|
|
260
|
+
|
|
261
|
+
```ts
|
|
262
|
+
import type { SkillRunContext } from "@cloudflare/think";
|
|
263
|
+
|
|
264
|
+
export default async function run(input: unknown, ctx: SkillRunContext) {
|
|
265
|
+
const guide = ctx.files["references/style-guide.md"]; // bundled text resources
|
|
266
|
+
const summary = await ctx.tools.call("summarize", { input }); // explicit tools
|
|
267
|
+
await ctx.output.writeFile("notes.md", summary); // scratch artifact
|
|
268
|
+
return { ok: true };
|
|
269
|
+
}
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
`ctx` is `{ skill, files, workspace, tools, output }`: `ctx.files` holds bundled
|
|
273
|
+
text resources by relative path, `ctx.workspace` is gated by the workspace
|
|
274
|
+
permission, `ctx.tools` exposes only the tools the runner was given, and
|
|
275
|
+
`ctx.output.writeFile(name, content)` returns scratch artifacts without mutating
|
|
276
|
+
the workspace. Python and Bash scripts instead use the path-based contract:
|
|
277
|
+
`/input.json`, `/context.json`, bundled resources under `/skill`, and `/output`
|
|
278
|
+
for artifacts (Python supports both `def run(input, ctx)` and CLI-style scripts).
|
|
279
|
+
|
|
280
|
+
If `workspaceInstance` is provided, scripts get read-only workspace access by
|
|
281
|
+
default. Workspace writes, tools, and network access are opt-in. Scripts default
|
|
282
|
+
to a 30 second timeout, which can be overridden with `timeout`. TypeScript
|
|
283
|
+
scripts are compiled with `@cloudflare/worker-bundler`; Python scripts run as
|
|
284
|
+
Python Dynamic Workers; Bash scripts run through `just-bash`.
|
|
285
|
+
|
|
286
|
+
Script execution requires a Worker Loader binding:
|
|
287
|
+
|
|
288
|
+
```jsonc
|
|
289
|
+
{
|
|
290
|
+
"worker_loaders": [{ "binding": "LOADER" }]
|
|
291
|
+
}
|
|
292
|
+
```
|
|
293
|
+
|
|
92
294
|
## Exports
|
|
93
295
|
|
|
94
|
-
| Export
|
|
95
|
-
|
|
|
96
|
-
| `@cloudflare/think`
|
|
97
|
-
| `@cloudflare/think/
|
|
98
|
-
| `@cloudflare/think/
|
|
99
|
-
| `@cloudflare/think/tools/
|
|
100
|
-
| `@cloudflare/think/
|
|
296
|
+
| Export | Description |
|
|
297
|
+
| --------------------------------------- | ------------------------------------------------------------- |
|
|
298
|
+
| `@cloudflare/think` | `Think`, `Session`, `Workspace` — main class + re-exports |
|
|
299
|
+
| `@cloudflare/think/messengers` | Messenger contracts, Chat SDK bridge, state agent, delivery |
|
|
300
|
+
| `@cloudflare/think/messengers/telegram` | Telegram messenger provider and delivery helpers |
|
|
301
|
+
| `@cloudflare/think/tools/workspace` | `createWorkspaceTools()` — for custom storage backends |
|
|
302
|
+
| `@cloudflare/think/tools/execute` | `createExecuteTool()` — sandboxed code execution via codemode |
|
|
303
|
+
| `@cloudflare/think/tools/extensions` | `createExtensionTools()` — LLM-driven extension loading |
|
|
304
|
+
| `@cloudflare/think/extensions` | `ExtensionManager`, `HostBridgeLoopback` — extension runtime |
|
|
101
305
|
|
|
102
306
|
## Think
|
|
103
307
|
|
|
104
308
|
### Configuration
|
|
105
309
|
|
|
106
|
-
| Method / Property
|
|
107
|
-
|
|
|
108
|
-
| `getModel()`
|
|
109
|
-
| `getSystemPrompt()`
|
|
110
|
-
| `getTools()`
|
|
111
|
-
| `
|
|
112
|
-
| `
|
|
113
|
-
| `
|
|
114
|
-
| `
|
|
115
|
-
| `
|
|
116
|
-
| `
|
|
310
|
+
| Method / Property | Default | Description |
|
|
311
|
+
| -------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
312
|
+
| `getModel()` | throws | Return the `LanguageModel` to use |
|
|
313
|
+
| `getSystemPrompt()` | careful assistant operating prompt | System prompt (fallback when no context blocks) |
|
|
314
|
+
| `getTools()` | `{}` | AI SDK `ToolSet` for the agentic loop |
|
|
315
|
+
| `getMessengers()` | `{}` | Messenger ingress and delivery declarations |
|
|
316
|
+
| `getScheduledTasks()` | `{}` | Code-declared recurring prompts |
|
|
317
|
+
| `getDefaultTimezone()` | `undefined` | Default timezone for wall-clock schedules |
|
|
318
|
+
| `maxSteps` | `10` | Max tool-call rounds per turn (property) |
|
|
319
|
+
| `sendReasoning` | `true` | Send reasoning chunks to chat clients |
|
|
320
|
+
| `configureSession()` | identity | Add context blocks, compaction, search, skills |
|
|
321
|
+
| `getSkills()` | `[]` | First-class Agent Skills sources |
|
|
322
|
+
| `getSkillScriptRunner()` | `null` | Optional runner for `run_skill_script` |
|
|
323
|
+
| `getExtensions()` | `[]` | Sandboxed extension declarations (load order) |
|
|
324
|
+
| `extensionLoader` | `undefined` | `WorkerLoader` binding — enables extensions |
|
|
325
|
+
| `workspaceBash` | `true` | Include the default workspace `bash` tool |
|
|
326
|
+
| `chatRecovery` | `true` | Wrap turns in `runFiber` for durable execution. Set `{ maxAttempts, terminalMessage, onExhausted }` to tune bounded recovery |
|
|
327
|
+
| `chatStreamStallTimeoutMs` | `0` (off) | Inactivity watchdog: abort a turn whose model stream produces no chunk for this long, surfacing a terminal stream error instead of an infinite spinner |
|
|
117
328
|
|
|
118
329
|
On each turn, Think appends a small capability block to the assembled system prompt. The block is based on the tools available for that turn, so models learn about workspace tools, context-loading tools, extension tools, sandboxed execution, MCP/client tools, and delegated-agent tools only when they are actually exposed.
|
|
119
330
|
|
|
331
|
+
Think enables Durable Object eviction recovery by default. This is separate from client resumable streaming: resumable streaming handles browser disconnect/reconnect while the object keeps running, while `chatRecovery` recovers turns interrupted by process restarts, deploys, or object eviction.
|
|
332
|
+
|
|
333
|
+
`chatStreamStallTimeoutMs` is a separate, opt-in safety net for a different failure: a model stream that **parks without ever throwing** (no chunk, no error, no `done`), which otherwise leaves the client spinning forever. When set, if no UI-message-stream chunk arrives within the window the watchdog aborts the turn and a `chat:stream:stalled` observability event fires. With `chatRecovery` on (the default), the stall is then routed into the **same bounded recovery path** as a deploy/eviction interruption: the settled partial is preserved and a continuation is scheduled, so a transient hang recovers automatically. A persistently hanging provider still terminalizes once the recovery budget is exhausted — and it exhausts through the **same path as deploy recovery**, so your configured `terminalMessage` is shown, `onExhausted` fires, and the `chat:recovery:exhausted` event is emitted (you do **not** get the raw `"Chat stream stalled…"` error). (With `chatRecovery` disabled, the watchdog exits with a terminal stream error via `onChatError` `stage: "stream"`.) When the stalled turn is a sub-agent dispatched via `runAgentTool()`, a recovering stall closes the RPC stream without firing `onError`/`onDone` — the scheduled continuation owns the real terminal outcome, so the parent observes a (slightly delayed) completion rather than an error, exactly as it would for a deploy-interrupted child. It is **off by default** because it measures the gap _between_ stream chunks, which includes server-side tool execution time (no chunks flow while a tool runs) — set it comfortably above your slowest model time-to-first-token and slowest tool, e.g. `120_000`, or you will abort healthy long turns. For a turn you _know_ will invoke a slow tool, return `{ chatStreamStallTimeoutMs }` from `beforeTurn` (a `TurnConfig` field) to raise or disable (`0`) the watchdog for that one turn instead of permanently widening the global window; it auto-resets afterward.
|
|
334
|
+
|
|
335
|
+
Override `onChatRecovery(ctx)` when you need provider-specific recovery. The default behavior persists partial assistant output and continues or retries when safe:
|
|
336
|
+
|
|
337
|
+
```ts
|
|
338
|
+
import type {
|
|
339
|
+
ChatRecoveryContext,
|
|
340
|
+
ChatRecoveryOptions
|
|
341
|
+
} from "@cloudflare/think";
|
|
342
|
+
|
|
343
|
+
export class MyAgent extends Think<Env> {
|
|
344
|
+
override chatRecovery = {
|
|
345
|
+
maxAttempts: 6,
|
|
346
|
+
terminalMessage: "The assistant was interrupted. Please try again."
|
|
347
|
+
};
|
|
348
|
+
|
|
349
|
+
override async onChatRecovery(
|
|
350
|
+
ctx: ChatRecoveryContext
|
|
351
|
+
): Promise<ChatRecoveryOptions> {
|
|
352
|
+
console.log("Recovering", ctx.incidentId, ctx.attempt, ctx.recoveryKind);
|
|
353
|
+
return {};
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
When a turn is interrupted mid-flight, an unsettled tool call left in the
|
|
359
|
+
transcript is repaired before the next provider call so the model does not
|
|
360
|
+
re-run it (and the provider does not 400 with `AI_MissingToolResultsError`). The
|
|
361
|
+
default flips it to an errored tool result; override `repairInterruptedToolPart`
|
|
362
|
+
to customize the repaired shape — for example, convert an interrupted
|
|
363
|
+
client-resolved `ask_user` (a question with no server `execute`) into a plain
|
|
364
|
+
text part carrying the prompt so the model treats it as ordinary conversation:
|
|
365
|
+
|
|
366
|
+
```ts
|
|
367
|
+
protected override repairInterruptedToolPart(
|
|
368
|
+
part: UIMessage["parts"][number]
|
|
369
|
+
): UIMessage["parts"][number] {
|
|
370
|
+
const record = part as Record<string, unknown>;
|
|
371
|
+
if (record.type === "tool-ask_user") {
|
|
372
|
+
const input = record.input as { prompt?: string } | undefined;
|
|
373
|
+
if (input?.prompt) return { type: "text", text: input.prompt };
|
|
374
|
+
}
|
|
375
|
+
return super.repairInterruptedToolPart(part);
|
|
376
|
+
}
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
While a turn is being recovered, Think broadcasts a `cf_agent_chat_recovering`
|
|
380
|
+
status (and replays it on connect) so clients can show a "recovering…" indicator
|
|
381
|
+
instead of looking frozen — surface it on the client with `useAgentChat`'s
|
|
382
|
+
`isRecovering` flag. It is set when a recovery continuation is scheduled and
|
|
383
|
+
cleared on every terminal outcome, so the indicator never spins forever. To
|
|
384
|
+
record recovery counts or reasons in your own analytics, subscribe to the
|
|
385
|
+
`chat:recovery:*` observability events and route them to your sink.
|
|
386
|
+
|
|
387
|
+
### Scheduled tasks
|
|
388
|
+
|
|
389
|
+
Use `getScheduledTasks()` for code-declared recurring prompts or deterministic
|
|
390
|
+
scheduled handlers. Think reconciles these declarations on startup, stores
|
|
391
|
+
durable one-shot schedules for the next occurrence, and re-arms the next
|
|
392
|
+
occurrence after each run.
|
|
393
|
+
|
|
394
|
+
```ts
|
|
395
|
+
import { Think } from "@cloudflare/think";
|
|
396
|
+
import type { ThinkScheduledTasks } from "@cloudflare/think";
|
|
397
|
+
|
|
398
|
+
export class Assistant extends Think<Env> {
|
|
399
|
+
getDefaultTimezone() {
|
|
400
|
+
return "Europe/London";
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
getScheduledTasks(): ThinkScheduledTasks {
|
|
404
|
+
return {
|
|
405
|
+
weeklyCommitReport: {
|
|
406
|
+
schedule: "every week on monday at 09:00",
|
|
407
|
+
prompt:
|
|
408
|
+
"Compile all my GitHub commits for the last week and write a concise summary."
|
|
409
|
+
},
|
|
410
|
+
workout: {
|
|
411
|
+
schedule: "every day at 08:00 in Europe/London",
|
|
412
|
+
prompt: "Start my workout."
|
|
413
|
+
},
|
|
414
|
+
customerDigest: {
|
|
415
|
+
schedule: "every day at 09:00",
|
|
416
|
+
timezone: "America/New_York",
|
|
417
|
+
metadata: { workflowName: "customer-digest" },
|
|
418
|
+
retry: { maxAttempts: 3 },
|
|
419
|
+
handler: async ({
|
|
420
|
+
idempotencyKey,
|
|
421
|
+
scheduledFor,
|
|
422
|
+
scheduleKind,
|
|
423
|
+
timezone
|
|
424
|
+
}) => {
|
|
425
|
+
await this.env.DIGEST_WORKFLOW.create({
|
|
426
|
+
id: idempotencyKey,
|
|
427
|
+
params: { scheduledFor, scheduleKind, timezone }
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
```
|
|
435
|
+
|
|
436
|
+
The DSL is intentionally small: `every <n> minutes`, `every <n> hours`,
|
|
437
|
+
`every day at HH:mm`, `every weekday at HH:mm`, and
|
|
438
|
+
`every week on monday,wednesday at HH:mm`. Wall-clock schedules require either
|
|
439
|
+
an inline timezone, a task `timezone`, or `getDefaultTimezone()`. If an alarm is
|
|
440
|
+
late, Think runs the intended occurrence once and schedules the next future
|
|
441
|
+
occurrence; it does not backfill missed runs.
|
|
442
|
+
|
|
443
|
+
The return type annotation gives TypeScript literal checks for schedule strings.
|
|
444
|
+
If you prefer not to annotate the method, wrap the object with
|
|
445
|
+
`defineScheduledTasks(...)` to keep the same checks. Think also validates
|
|
446
|
+
scheduled tasks at runtime during startup reconciliation, so dynamically built
|
|
447
|
+
objects still fail before schedules are persisted.
|
|
448
|
+
|
|
449
|
+
Each task must define exactly one of `prompt` or `handler`. Prompt tasks create a
|
|
450
|
+
durable submission with `submitMessages()`. Handler tasks receive
|
|
451
|
+
`{ taskId, scheduledFor, scheduledForDate, occurrenceKey, idempotencyKey,
|
|
452
|
+
schedule, scheduleKind, timezone, metadata }` and are intended for app-owned
|
|
453
|
+
work such as creating a Workflow run or writing a run ledger. Delivery is
|
|
454
|
+
at-least-once; use `idempotencyKey` or `occurrenceKey` for your own durable
|
|
455
|
+
idempotency.
|
|
456
|
+
|
|
457
|
+
Static declarations reconcile on startup. If `getScheduledTasks()` reads
|
|
458
|
+
product-owned data that can change while the Durable Object is live, call
|
|
459
|
+
`internal_reconcileScheduledTasks()` after updating that data. During
|
|
460
|
+
reconciliation Think records the task row before creating the underlying Agent
|
|
461
|
+
schedule, so a `schedule_id` may be temporarily empty if the object is
|
|
462
|
+
interrupted mid-reconcile; the next reconcile repairs that pending row. The
|
|
463
|
+
task `retry` option retries the prompt or handler action before the failure is
|
|
464
|
+
logged. The next occurrence is still scheduled after the action succeeds or
|
|
465
|
+
exhausts its retries, so failed occurrences do not block future runs.
|
|
466
|
+
|
|
120
467
|
### Lifecycle hooks
|
|
121
468
|
|
|
122
469
|
Think owns the `streamText` call. Hooks fire on every turn regardless of entry path (WebSocket, `chat()`, `saveMessages()`, durable `submitMessages()` execution, `continueLastTurn()`, auto-continuation).
|
|
123
470
|
|
|
124
|
-
| Hook
|
|
125
|
-
|
|
|
126
|
-
| `beforeTurn(ctx)`
|
|
127
|
-
| `beforeStep(ctx)`
|
|
128
|
-
| `beforeToolCall(ctx)`
|
|
129
|
-
| `afterToolCall(ctx)`
|
|
130
|
-
| `onStepFinish(ctx)`
|
|
131
|
-
| `onChunk(ctx)`
|
|
132
|
-
| `onChatResponse(result)`
|
|
133
|
-
| `onChatError(error)`
|
|
471
|
+
| Hook | When it fires | Return |
|
|
472
|
+
| ------------------------- | ------------------------------------------- | ------------------------------ |
|
|
473
|
+
| `beforeTurn(ctx)` | Before `streamText` — see assembled context | `TurnConfig` overrides or void |
|
|
474
|
+
| `beforeStep(ctx)` | Before each model step | `StepConfig` overrides or void |
|
|
475
|
+
| `beforeToolCall(ctx)` | Before tool's `execute` runs | `ToolCallDecision` or void |
|
|
476
|
+
| `afterToolCall(ctx)` | After tool execution (success or failure) | void |
|
|
477
|
+
| `onStepFinish(ctx)` | After each step completes | void |
|
|
478
|
+
| `onChunk(ctx)` | Per streaming chunk (high-frequency) | void |
|
|
479
|
+
| `onChatResponse(result)` | After turn completes + message persisted | void |
|
|
480
|
+
| `onChatError(error, ctx)` | On error during a turn | error to propagate |
|
|
481
|
+
|
|
482
|
+
`onChatError` receives `ctx.stage`, `ctx.requestId`, and `ctx.messagesPersisted`
|
|
483
|
+
so apps can distinguish pre-persist request failures from stream failures. The
|
|
484
|
+
same failures emit `chat:request:failed` observability events.
|
|
134
485
|
|
|
135
486
|
The AI SDK-derived contexts spread the SDK's own types at the top level — no information is dropped:
|
|
136
487
|
|
|
@@ -319,9 +670,13 @@ session.removeContext("notes");
|
|
|
319
670
|
await session.refreshSystemPrompt();
|
|
320
671
|
```
|
|
321
672
|
|
|
322
|
-
#### Skills
|
|
673
|
+
#### Legacy Session Skills
|
|
323
674
|
|
|
324
|
-
|
|
675
|
+
Session still supports lower-level loadable context providers. Prefer the
|
|
676
|
+
first-class Think skills API (`getSkills()`, `activate_skill`, and
|
|
677
|
+
`read_skill_resource`) for new Agent Skills directories. Use Session skill
|
|
678
|
+
providers only when you need generic `load_context` / `unload_context`
|
|
679
|
+
management instead of Think's skills workflow.
|
|
325
680
|
|
|
326
681
|
```ts
|
|
327
682
|
import { R2SkillProvider } from "agents/experimental/memory/session";
|
|
@@ -333,7 +688,6 @@ configureSession(session: Session) {
|
|
|
333
688
|
})
|
|
334
689
|
.withCachedPrompt();
|
|
335
690
|
}
|
|
336
|
-
// Model gets load_context and unload_context tools automatically
|
|
337
691
|
```
|
|
338
692
|
|
|
339
693
|
### MCP integration
|
|
@@ -352,6 +706,8 @@ Use browser chat through `useAgentChat` when a user drives the conversation. Use
|
|
|
352
706
|
`saveMessages()` when server code controls the trigger and can wait for the
|
|
353
707
|
model response. Use `submitMessages()` when a caller needs fast durable
|
|
354
708
|
acceptance, idempotent retries, cancellation, and later status inspection.
|
|
709
|
+
Use `getScheduledTasks()` when code should create recurring prompt submissions
|
|
710
|
+
or deterministic scheduled handlers.
|
|
355
711
|
|
|
356
712
|
Use `subAgent(...).chat()` for direct streaming RPC to a specific child when
|
|
357
713
|
your code owns forwarding and replay policy. Use `agentTool()` or
|
|
@@ -374,10 +730,15 @@ When used as a sub-agent (via `this.subAgent()`), the `chat()` method runs a ful
|
|
|
374
730
|
|
|
375
731
|
```ts
|
|
376
732
|
interface StreamCallback {
|
|
377
|
-
onStart
|
|
733
|
+
onStart(event: { requestId: string }): void | Promise<void>;
|
|
378
734
|
onEvent(json: string): void | Promise<void>;
|
|
379
735
|
onDone(): void | Promise<void>;
|
|
380
|
-
onError
|
|
736
|
+
onError(error: string): void | Promise<void>;
|
|
737
|
+
// Optional. The attempt was interrupted (a stream-stall watchdog abort routed
|
|
738
|
+
// into bounded recovery) and a scheduled continuation — in a later isolate,
|
|
739
|
+
// without this callback — owns the final outcome. NOT done, NOT a terminal
|
|
740
|
+
// error. Defaults to a no-op, so existing implementers are unaffected.
|
|
741
|
+
onInterrupted?(): void | Promise<void>;
|
|
381
742
|
}
|
|
382
743
|
|
|
383
744
|
const agent = await this.subAgent(MyAgent, "thread-1");
|
|
@@ -388,6 +749,17 @@ await agent.chat("Summarize the project", relay);
|
|
|
388
749
|
`agent.cancelChat(requestId, reason)` if the parent needs to stop the child turn
|
|
389
750
|
after it has started.
|
|
390
751
|
|
|
752
|
+
`onInterrupted` matters for a `chat()`-driven turn that is interrupted and
|
|
753
|
+
recovers: the RPC promise resolves **cleanly** (the isolate is still alive), so a
|
|
754
|
+
consumer that keys off the clean resolve would mis-read it as success and
|
|
755
|
+
finalize whatever partial it had streamed. Treat `onInterrupted` as "not done,
|
|
756
|
+
not failed — a continuation owns the answer": keep the channel open, show a
|
|
757
|
+
recovering state, or re-attach, rather than finalizing the partial. (The built-in
|
|
758
|
+
messenger delivery already does this — it surfaces an "interrupted, please retry"
|
|
759
|
+
reply instead of posting the truncated partial.) Note: a deploy/eviction
|
|
760
|
+
interruption kills the isolate before this can fire — the caller sees a transport
|
|
761
|
+
break instead; `onInterrupted` covers the in-isolate stall→recovery path.
|
|
762
|
+
|
|
391
763
|
Tools belong to the child agent; define them with `getTools()` or use
|
|
392
764
|
`agentTool()` / `runAgentTool()` for parent-child orchestration.
|
|
393
765
|
|
|
@@ -416,6 +788,7 @@ For values you want broadcast to connected clients, use `state` / `setState` fro
|
|
|
416
788
|
- **Stream resumption** — page refresh replays buffered chunks via `ResumableStream`
|
|
417
789
|
- **Client tools** — accept tool schemas from clients, handle results and approvals
|
|
418
790
|
- **Durable submissions** — accept webhook/RPC-triggered turns with idempotent retry and status inspection
|
|
791
|
+
- **Messengers** — receive Chat SDK webhooks and deliver streamed replies with provider-safe recovery
|
|
419
792
|
- **Auto-continuation** — debounce-based continuation after tool results
|
|
420
793
|
- **MCP integration** — MCP tools auto-merged, wait for connections before inference
|
|
421
794
|
- **Abort/cancel** — pass an `AbortSignal` or send a cancel message
|
|
@@ -433,6 +806,7 @@ import { createWorkspaceTools } from "@cloudflare/think/tools/workspace";
|
|
|
433
806
|
|
|
434
807
|
// Use with a custom ReadOperations/WriteOperations implementation
|
|
435
808
|
const tools = createWorkspaceTools(myCustomStorage);
|
|
809
|
+
const toolsWithoutBash = createWorkspaceTools(myCustomStorage, { bash: false });
|
|
436
810
|
```
|
|
437
811
|
|
|
438
812
|
Each tool is an AI SDK `tool()` with Zod schemas. The underlying operations are abstracted behind interfaces (`ReadOperations`, `WriteOperations`, etc.) so you can create tools backed by any storage.
|
|
@@ -471,15 +845,18 @@ getTools() {
|
|
|
471
845
|
}
|
|
472
846
|
```
|
|
473
847
|
|
|
474
|
-
##
|
|
475
|
-
|
|
476
|
-
| Package
|
|
477
|
-
|
|
|
478
|
-
| `agents`
|
|
479
|
-
| `ai`
|
|
480
|
-
| `zod`
|
|
481
|
-
| `@cloudflare/shell`
|
|
482
|
-
| `@cloudflare/codemode`
|
|
848
|
+
## Runtime dependencies
|
|
849
|
+
|
|
850
|
+
| Package | Notes |
|
|
851
|
+
| ---------------------------- | --------------------------------------------------------- |
|
|
852
|
+
| `agents` | Cloudflare Agents SDK peer dependency |
|
|
853
|
+
| `ai` | Vercel AI SDK v6 peer dependency |
|
|
854
|
+
| `zod` | Schema validation peer dependency |
|
|
855
|
+
| `@cloudflare/shell` | Workspace filesystem |
|
|
856
|
+
| `@cloudflare/codemode` | Code execution, `createExecuteTool`, and JS skill scripts |
|
|
857
|
+
| `@cloudflare/worker-bundler` | TypeScript skill script compilation |
|
|
858
|
+
| `just-bash` | Bash skill script execution |
|
|
859
|
+
| `@chat-adapter/telegram` | Required for Telegram messengers |
|
|
483
860
|
|
|
484
861
|
## Acknowledgments
|
|
485
862
|
|