@cloudflare/think 0.20.2 → 0.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +60 -43
- package/dist/classPrivateFieldSet2-DwGJfC3w.js +27 -0
- package/dist/extensions/index.js +2 -1
- package/dist/extensions/index.js.map +1 -1
- package/dist/{fetch-By3eIQ-a.d.ts → fetch-CU2fC7O6.d.ts} +41 -20
- package/dist/fetch-DO3uQ9py.js +727 -0
- package/dist/fetch-DO3uQ9py.js.map +1 -0
- package/dist/{index-CmhSKa6U.d.ts → index-BFK9bpzz.d.ts} +55 -75
- package/dist/{manager-Cb3DNZgp.js → manager-BubfmA3q.js} +3 -28
- package/dist/{manager-Cb3DNZgp.js.map → manager-BubfmA3q.js.map} +1 -1
- package/dist/messengers/index.d.ts +1 -1
- package/dist/messengers/telegram.d.ts +1 -1
- package/dist/think.d.ts +3 -4
- package/dist/think.js +79 -97
- package/dist/think.js.map +1 -1
- package/dist/tools/execute.d.ts +19 -24
- package/dist/tools/execute.js +20 -40
- package/dist/tools/execute.js.map +1 -1
- package/dist/tools/extensions.d.ts +1 -1
- package/dist/tools/extensions.js +2 -2
- package/dist/tools/extensions.js.map +1 -1
- package/dist/tools/fetch.d.ts +2 -4
- package/dist/tools/fetch.js +1 -608
- package/dist/workflows.d.ts +1 -1
- package/docs/channels.md +1 -5
- package/docs/getting-started.md +4 -4
- package/docs/index.md +31 -17
- package/docs/lifecycle-hooks.md +1 -3
- package/docs/multi-chat.md +21 -60
- package/docs/sub-agents.md +13 -13
- package/docs/tools.md +73 -109
- package/package.json +7 -12
- package/dist/tools/fetch.js.map +0 -1
- package/dist/tools/workspace.d.ts +0 -60
- package/dist/tools/workspace.js +0 -869
- package/dist/tools/workspace.js.map +0 -1
- package/dist/workspace-CNeXc2vl.d.ts +0 -201
package/docs/index.md
CHANGED
|
@@ -12,7 +12,7 @@ Think builds on packages that are installed alongside it:
|
|
|
12
12
|
|
|
13
13
|
- `agents/docs/index.md` — Durable Objects, state, routing, sessions, scheduling, MCP, and shared agent primitives
|
|
14
14
|
- `@cloudflare/codemode/docs/index.md` — sandboxed execution, tool providers, connectors, approvals, and snippets
|
|
15
|
-
- `@cloudflare/
|
|
15
|
+
- [`@cloudflare/computer`](https://github.com/cloudflare/computer/tree/main/packages/computer) — the Workspace, its execution backends, and the workspace tools
|
|
16
16
|
|
|
17
17
|
## Why Think
|
|
18
18
|
|
|
@@ -31,7 +31,7 @@ If you only need a chat-protocol adapter where you own the loop and the `Respons
|
|
|
31
31
|
### Install
|
|
32
32
|
|
|
33
33
|
```sh
|
|
34
|
-
npm install @cloudflare/think agents ai
|
|
34
|
+
npm install @cloudflare/think @cloudflare/computer agents ai zod
|
|
35
35
|
```
|
|
36
36
|
|
|
37
37
|
`workers-ai-provider` is bundled with Think, so the common case needs no extra provider package — `getModel()` can return a model id string.
|
|
@@ -416,7 +416,6 @@ path.
|
|
|
416
416
|
| `getSkills()` | `[]` | Return Agent Skills sources for on-demand skill activation |
|
|
417
417
|
| `skillWorkspace` | `false` | Project skills into the Workspace as files; `{}` enables with defaults |
|
|
418
418
|
| `getSkillScriptRunner()` | `null` | Enable the optional `run_skill_script` tool |
|
|
419
|
-
| `workspaceBash` | `true` | Include or configure the default workspace `bash` tool |
|
|
420
419
|
| `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) |
|
|
421
420
|
| `messageConcurrency` | `"queue"` | How overlapping submits behave — see [Client Tools](./client-tools.md) |
|
|
422
421
|
| `includeMcpTools` | `true` | Automatically convert connected MCP tools to AI SDK tools and merge them into model turns |
|
|
@@ -530,14 +529,14 @@ agent (including a plain `@cloudflare/ai-chat` `onChatMessage`) can build a
|
|
|
530
529
|
Think can also project each resolved `SKILL.md` into the active workspace so
|
|
531
530
|
the agent can read and edit skills as files. This is off by default: skills
|
|
532
531
|
load from their sources and nothing is written to the Workspace. Set
|
|
533
|
-
`skillWorkspace = {}` to enable it.
|
|
534
|
-
|
|
532
|
+
`skillWorkspace = {}` to enable it. Skills land under `/workspace/.agents/skills`.
|
|
533
|
+
Existing workspace edits are preserved and
|
|
535
534
|
affect later activation. Resources copy into the workspace when first requested
|
|
536
535
|
rather than at startup. A durable source fingerprint lets unchanged cold wakes
|
|
537
536
|
attach to the existing projection without statting or rewriting every file.
|
|
538
537
|
|
|
539
|
-
Set `skillWorkspace = { root: "/
|
|
540
|
-
|
|
538
|
+
Set `skillWorkspace = { root: "/some/other/dir" }` to project skills somewhere
|
|
539
|
+
else.
|
|
541
540
|
|
|
542
541
|
Sources are applied in order; the first source to register a skill name wins,
|
|
543
542
|
and later duplicates (or a source that fails to load) are skipped with a logged
|
|
@@ -957,20 +956,20 @@ Two things do change on upgrade:
|
|
|
957
956
|
|
|
958
957
|
Annotate a `configureSession` override with `Session` imported from `@cloudflare/think`. The `Session` class exported by `agents/sessions` is the raw storage handle and is not assignable to Think's.
|
|
959
958
|
|
|
960
|
-
`sessionAttachments` is gone (Sessions stores media out of the row on its own), `MediaEvictionConfig.externalizeToWorkspace` is ignored (bytes are always preserved), and
|
|
959
|
+
`sessionAttachments` is gone (Sessions stores media out of the row on its own), `MediaEvictionConfig.externalizeToWorkspace` is ignored (bytes are always preserved), and the workspace is now a `@cloudflare/computer` Workspace (`ThinkWorkspace`).
|
|
961
960
|
|
|
962
961
|
Think's `this.messages` getter reads directly from the Session tree. Compaction overlays and search are handled by Sessions.
|
|
963
962
|
|
|
964
963
|
### Message storage
|
|
965
964
|
|
|
966
|
-
Sessions stores MESSAGES; it is not a file store. A message rides in one SQLite row until its serialized JSON exceeds the 1.5 MiB row budget; a message larger than that is split across continuation rows and reassembled on read, byte for byte. Nothing is truncated and no message is too large to store, so there is no size error to handle and nothing to configure. Splitting never reclaims database space — the continuation rows live in the same Durable Object as the message — and Sessions imposes no upper bound on a single message, so a Durable Object's 10 GB ceiling is the real bound on how much one conversation can hold and bounding untrusted input is the application's job. Files belong in the Workspace
|
|
965
|
+
Sessions stores MESSAGES; it is not a file store. A message rides in one SQLite row until its serialized JSON exceeds the 1.5 MiB row budget; a message larger than that is split across continuation rows and reassembled on read, byte for byte. Nothing is truncated and no message is too large to store, so there is no size error to handle and nothing to configure. Splitting never reclaims database space — the continuation rows live in the same Durable Object as the message — and Sessions imposes no upper bound on a single message, so a Durable Object's 10 GB ceiling is the real bound on how much one conversation can hold and bounding untrusted input is the application's job. Files belong in the Workspace; put a reference to one in the message. This is a storage detail: it is invisible to the model, and it is unrelated to media eviction.
|
|
967
966
|
|
|
968
967
|
### Media eviction
|
|
969
968
|
|
|
970
969
|
Media eviction is a different concern: a context-window technique, not a storage one. Sending a screenshot the model has already looked at back through the context on every subsequent turn is pure cost, so once a message has aged past `mediaEviction.keepRecentMessages` (8 by default) on the active path, Think takes the media out of the conversation and leaves a marker in its place:
|
|
971
970
|
|
|
972
971
|
```
|
|
973
|
-
[evicted image/png, 812004 bytes; preserved at /attachments/evicted/msg_01H8-0.png]
|
|
972
|
+
[evicted image/png, 812004 bytes; preserved at /workspace/attachments/evicted/msg_01H8-0.png]
|
|
974
973
|
```
|
|
975
974
|
|
|
976
975
|
The bytes are written to the Workspace at that path, raw and with their real mime type — not as a `data:` URL string. The workspace `read` tool recognises `image/*`, so when the agent decides it needs to look at the picture again it reads the path out of the marker and the actual image goes back into context. Eviction is visible to the model and lossy on purpose; nothing reconstructs it behind the model's back.
|
|
@@ -1017,12 +1016,28 @@ A compaction threshold that the compacted history still exceeds compacts on ever
|
|
|
1017
1016
|
| `@cloudflare/think/messengers` | Messenger contracts, Chat SDK bridge, state agent, delivery |
|
|
1018
1017
|
| `@cloudflare/think/messengers/telegram` | Telegram messenger provider and delivery helpers |
|
|
1019
1018
|
| `@cloudflare/think/workflows` | `ThinkWorkflow`, `step.prompt()` — Workflow prompts |
|
|
1020
|
-
| `@cloudflare/think/tools/workspace` | `createWorkspaceTools()` — for custom storage backends |
|
|
1021
1019
|
| `@cloudflare/think/tools/fetch` | `createFetchTools()` — opt-in allowlisted HTTP reads |
|
|
1022
1020
|
| `@cloudflare/think/tools/execute` | `createExecuteTool()` — sandboxed code execution via codemode |
|
|
1023
1021
|
| `@cloudflare/think/tools/extensions` | `createExtensionTools()` — LLM-driven extension loading |
|
|
1024
1022
|
| `@cloudflare/think/extensions` | `ExtensionManager`, `HostBridgeLoopback` — extension runtime |
|
|
1025
1023
|
|
|
1024
|
+
## Upgrading to a Computer workspace
|
|
1025
|
+
|
|
1026
|
+
Think's workspace is a `Workspace` from [`@cloudflare/computer`](https://github.com/cloudflare/computer), which replaces `@cloudflare/shell`:
|
|
1027
|
+
|
|
1028
|
+
- Install `@cloudflare/computer`; it is a peer dependency. Import `Workspace` from it rather than from `@cloudflare/think`.
|
|
1029
|
+
- `workspace` is typed `ThinkWorkspace`, which needs only `workspace.fs`. `WorkspaceLike` is gone.
|
|
1030
|
+
- The default Workspace lives on the agent's own storage and has no execution backends. Override `workspace` with `new Workspace({ storage: this.ctx.storage, ... })` to add backends, mounts, or git.
|
|
1031
|
+
- Think writes its own files under `/workspace`: evicted media under `/workspace/attachments/evicted/`, fetched responses under `/workspace/fetched/`, and skills under `/workspace/.agents/skills`.
|
|
1032
|
+
- The execute tool's `state` option and `state.*` namespace are removed. Pass `createAITools({ workspace: this.workspace })` as `tools` to give sandboxed code the workspace.
|
|
1033
|
+
- The workspace tools are `@cloudflare/computer`'s `createAITools`: `read`, `ls`, `find`, `grep`, `write`, `edit`, and `delete`, plus `exec` when the Workspace has backends. `list` is now `ls`. `exec` offers every backend the Workspace has.
|
|
1034
|
+
- `workspaceBash`, `createWorkspaceTools`, and `@cloudflare/think/tools/workspace` are removed, with no replacement. There is no in-process `bash` tool: add a backend to the Workspace to get `exec`. To change a built-in tool, return a same-name tool from `getTools()`; to hide tools for a turn, return `activeTools` from `beforeTurn`.
|
|
1035
|
+
- Every Think agent has `__getWorkspaceStub()`, so `getWorkspace(stub)` and the Worker shell backend can reach a Workspace it owns.
|
|
1036
|
+
- Image and PDF reads stored by the old `read` tool replay as an error asking the model to read the file again.
|
|
1037
|
+
- Agent Skills (`agents/skills`) accept only a Computer Workspace, for both projection and `skills.runner({ workspaceInstance })`. Relative paths in skill scripts resolve against `/workspace`.
|
|
1038
|
+
|
|
1039
|
+
Files a Shell Workspace stored are not moved. [Migrating to `@cloudflare/computer`](../shell/migrating-to-computer.md) documents both storage schemas and a copy script.
|
|
1040
|
+
|
|
1026
1041
|
## Dependencies
|
|
1027
1042
|
|
|
1028
1043
|
Peer dependencies you provide:
|
|
@@ -1030,17 +1045,16 @@ Peer dependencies you provide:
|
|
|
1030
1045
|
| Package | Required | Notes |
|
|
1031
1046
|
| ------------------------ | -------- | -------------------------------- |
|
|
1032
1047
|
| `agents` | yes | Cloudflare Agents SDK |
|
|
1033
|
-
| `ai` | yes | Vercel AI SDK
|
|
1048
|
+
| `ai` | yes | Vercel AI SDK v7 |
|
|
1034
1049
|
| `zod` | yes | Schema validation (v4) |
|
|
1050
|
+
| `@cloudflare/computer` | yes | Workspace and workspace tools |
|
|
1035
1051
|
| `@chat-adapter/telegram` | optional | Required for Telegram messengers |
|
|
1036
1052
|
|
|
1037
1053
|
Bundled with `@cloudflare/think`:
|
|
1038
1054
|
|
|
1039
|
-
| Package | Notes
|
|
1040
|
-
| ---------------------- |
|
|
1041
|
-
| `@cloudflare/
|
|
1042
|
-
| `@cloudflare/codemode` | Code execution for `createExecuteTool()` |
|
|
1043
|
-
| `just-bash` | Sandboxed shell for the default workspace `bash` tool |
|
|
1055
|
+
| Package | Notes |
|
|
1056
|
+
| ---------------------- | ---------------------------------------- |
|
|
1057
|
+
| `@cloudflare/codemode` | Code execution for `createExecuteTool()` |
|
|
1044
1058
|
|
|
1045
1059
|
The Agent Skills engine and its script runner live in
|
|
1046
1060
|
[`agents/skills`](https://github.com/cloudflare/agents/blob/main/packages/agents/AGENTS.md) (so skill scripts pull
|
package/docs/lifecycle-hooks.md
CHANGED
|
@@ -917,9 +917,7 @@ Extensions can subscribe to `beforeTurn`, `beforeToolCall`, `afterToolCall`, `on
|
|
|
917
917
|
```js
|
|
918
918
|
// extension source
|
|
919
919
|
({
|
|
920
|
-
tools: {
|
|
921
|
-
/* ... */
|
|
922
|
-
},
|
|
920
|
+
tools: {/* ... */},
|
|
923
921
|
hooks: {
|
|
924
922
|
beforeTurn: async (snapshot, host) => {
|
|
925
923
|
/* may return TurnConfig */
|
package/docs/multi-chat.md
CHANGED
|
@@ -46,7 +46,7 @@ Browser tab
|
|
|
46
46
|
- messages and branches
|
|
47
47
|
- memory and other context blocks
|
|
48
48
|
- extensions, config, skills
|
|
49
|
-
-
|
|
49
|
+
- workspace client / SharedMCPClient proxy → directory
|
|
50
50
|
```
|
|
51
51
|
|
|
52
52
|
The browser keeps two connections open: one to the directory for the sidebar,
|
|
@@ -56,7 +56,7 @@ conversation itself.
|
|
|
56
56
|
| Resource | Owner | How chats reach it |
|
|
57
57
|
| ----------------------------------------------- | --------- | ----------------------------------------------- |
|
|
58
58
|
| Chat list, titles, previews | Directory | Chats push updates over Durable Object RPC |
|
|
59
|
-
| Workspace files | Directory | `
|
|
59
|
+
| Workspace files | Directory | `getWorkspace()` client, one RPC per file call |
|
|
60
60
|
| MCP registry, OAuth tokens, live connections | Directory | `SharedMCPClient` proxy, merged in `beforeTurn` |
|
|
61
61
|
| Cross-chat scheduled work | Directory | Directory RPCs into the selected chat |
|
|
62
62
|
| Messages, branches, compaction | Chat | Local Session |
|
|
@@ -335,78 +335,39 @@ deleted from another tab, the app selects the most recently active chat.
|
|
|
335
335
|
|
|
336
336
|
## Share the workspace
|
|
337
337
|
|
|
338
|
-
The directory owns one `Workspace` backed by its own
|
|
339
|
-
one chat is visible in every other chat for that
|
|
338
|
+
The directory owns one `@cloudflare/computer` `Workspace` backed by its own
|
|
339
|
+
SQLite, so a file written in one chat is visible in every other chat for that
|
|
340
|
+
user:
|
|
340
341
|
|
|
341
342
|
```typescript
|
|
342
|
-
|
|
343
|
-
workspace = new Workspace({
|
|
344
|
-
sql: this.ctx.storage.sql,
|
|
345
|
-
name: () => this.name,
|
|
346
|
-
onChange: (event) =>
|
|
347
|
-
this.broadcast(JSON.stringify({ type: "workspace-change", event }))
|
|
348
|
-
});
|
|
343
|
+
import { Workspace } from "@cloudflare/computer";
|
|
349
344
|
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
async readFile(path: string): Promise<string | null> {
|
|
353
|
-
return this.workspace.readFile(path);
|
|
354
|
-
}
|
|
355
|
-
|
|
356
|
-
async writeFile(
|
|
357
|
-
path: string,
|
|
358
|
-
content: string,
|
|
359
|
-
mimeType?: Parameters<Workspace["writeFile"]>[2]
|
|
360
|
-
): Promise<void> {
|
|
361
|
-
return this.workspace.writeFile(path, content, mimeType);
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
// ...readFileBytes, writeFileBytes, appendFile, exists, readDir, rm, glob,
|
|
365
|
-
// mkdir, stat, lstat, cp, mv, symlink, readlink
|
|
345
|
+
export class AssistantDirectory extends Think<Env, DirectoryState> {
|
|
346
|
+
override workspace = new Workspace({ storage: this.ctx.storage });
|
|
366
347
|
}
|
|
367
348
|
```
|
|
368
349
|
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
350
|
+
Every Think agent has a `__getWorkspaceStub()` method, which `getWorkspace()`
|
|
351
|
+
from `@cloudflare/computer` calls over Durable Object RPC. Each chat replaces
|
|
352
|
+
Think's default workspace with a client for the directory's:
|
|
372
353
|
|
|
373
354
|
```typescript
|
|
374
|
-
import
|
|
355
|
+
import { getWorkspace } from "@cloudflare/computer";
|
|
375
356
|
|
|
376
357
|
export class MyAssistant extends Think<Env> {
|
|
377
|
-
override workspace
|
|
378
|
-
this.parentAgent(AssistantDirectory)
|
|
379
|
-
);
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
export class SharedWorkspace implements WorkspaceFsLike {
|
|
383
|
-
#stubPromise?: Promise<DurableObjectStub<AssistantDirectory>>;
|
|
384
|
-
|
|
385
|
-
constructor(
|
|
386
|
-
private getParent: () => Promise<DurableObjectStub<AssistantDirectory>>
|
|
387
|
-
) {}
|
|
388
|
-
|
|
389
|
-
private parent() {
|
|
390
|
-
this.#stubPromise ??= this.getParent();
|
|
391
|
-
return this.#stubPromise;
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
async readFile(path: string) {
|
|
395
|
-
return (await this.parent()).readFile(path);
|
|
396
|
-
}
|
|
397
|
-
|
|
398
|
-
// ...every other WorkspaceFsLike method forwards the same way
|
|
358
|
+
override workspace = getWorkspace(() => this.parentAgent(AssistantDirectory));
|
|
399
359
|
}
|
|
400
360
|
```
|
|
401
361
|
|
|
402
|
-
The
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
362
|
+
The client reaches the directory on the first file call, so a chat that never
|
|
363
|
+
touches a file never contacts it.
|
|
364
|
+
|
|
365
|
+
Think's workspace tools, the fetch tool's saved responses, and skill script
|
|
366
|
+
runners all go through it.
|
|
407
367
|
|
|
408
|
-
To keep file browsers
|
|
409
|
-
|
|
368
|
+
To keep file browsers fresh across chats and tabs, each chat calls a
|
|
369
|
+
`workspaceChanged()` method on the directory after every turn, which broadcasts
|
|
370
|
+
`{ type: "workspace-change" }`. `useChats()` listens for those broadcasts and exposes a `workspaceRevision`
|
|
410
371
|
counter that chat panes use as a `useEffect` dependency:
|
|
411
372
|
|
|
412
373
|
```typescript
|
package/docs/sub-agents.md
CHANGED
|
@@ -486,7 +486,7 @@ export class MyAgent extends Think<Env> {
|
|
|
486
486
|
maxAttempts: 10,
|
|
487
487
|
noProgressTimeoutMs: 5 * 60 * 1000,
|
|
488
488
|
maxRecoveryWork: 10_000,
|
|
489
|
-
|
|
489
|
+
maxInterruptedAttempts: 5,
|
|
490
490
|
terminalMessage: "The assistant was interrupted and could not recover.",
|
|
491
491
|
// Consulted from the second recovery attempt onward. Return false to stop.
|
|
492
492
|
// Called as `config.shouldKeepRecovering(ctx)`, so it is NOT bound to the
|
|
@@ -502,20 +502,20 @@ export class MyAgent extends Think<Env> {
|
|
|
502
502
|
}
|
|
503
503
|
```
|
|
504
504
|
|
|
505
|
-
| Field
|
|
506
|
-
|
|
|
507
|
-
| `maxAttempts`
|
|
508
|
-
| `stableTimeoutMs`
|
|
509
|
-
| `noProgressTimeoutMs`
|
|
510
|
-
| `maxRecoveryWork`
|
|
511
|
-
| `
|
|
512
|
-
| `shouldKeepRecovering`
|
|
513
|
-
| `terminalMessage`
|
|
514
|
-
| `onExhausted`
|
|
505
|
+
| Field | Default | Description |
|
|
506
|
+
| ------------------------ | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
507
|
+
| `maxAttempts` | `10` | Attempt cap. Resets on forward progress, so it catches a tight no-progress alarm loop, not a healthy long turn. |
|
|
508
|
+
| `stableTimeoutMs` | `10_000` | How long an attempt waits for the isolate to reach stable state before rescheduling. |
|
|
509
|
+
| `noProgressTimeoutMs` | `300_000` (5 min) | Primary stuck-turn bound: max time without forward progress before sealing. **Resets on every progress-bearing attempt.** |
|
|
510
|
+
| `maxRecoveryWork` | `10000` | Runaway-loop guard: max recovery work since the incident opened before a still-progressing turn is sealed (`work_budget_exceeded`), counted in durable stream segments (see [Recovery work units](https://github.com/cloudflare/agents/blob/main/docs/agents/chat-agents.md#recovery-work-units)). A generous finite backstop so a turn that keeps emitting content but never converges cannot loop forever. Raise it, or set `Infinity`, for a very long agentic turn. |
|
|
511
|
+
| `maxInterruptedAttempts` | `5` | How many of one turn's attempts may be interrupted (their isolate died before they finished, for example a memory-limit reset or a deploy) before recovery seals with `interrupted_attempts_exceeded`. The original turn counts. Progress never resets it. Replaces `maxOomRetries`, which is still read as `maxOomRetries + 1`. |
|
|
512
|
+
| `shouldKeepRecovering` | — | Caller policy consulted from the second attempt onward. Return `false` to stop recovery. The hook point for a token/cost budget (`ctx.work` is a durable segment count, not tokens). |
|
|
513
|
+
| `terminalMessage` | generic message | Message shown to the user when recovery is given up on. |
|
|
514
|
+
| `onExhausted` | — | Called once when recovery is given up on. Inspect `ctx.reason`. |
|
|
515
515
|
|
|
516
|
-
`ctx.reason` on the exhausted hook is one of: `no_progress_timeout` (stuck), `max_attempts_exceeded` (no-progress alarm loop), `work_budget_exceeded` (runaway), `
|
|
516
|
+
`ctx.reason` on the exhausted hook is one of: `no_progress_timeout` (stuck), `max_attempts_exceeded` (no-progress alarm loop), `work_budget_exceeded` (runaway), `interrupted_attempts_exceeded` (the turn's attempts kept dying, for example to memory-limit resets), `out_of_memory` (sealed by the alarm memory-limit breaker), `recovery_aborted` (your `shouldKeepRecovering` returned `false`), or `stable_timeout` (extreme churn). See [`chat-agents.md`](https://github.com/cloudflare/agents/blob/main/docs/agents/chat-agents.md#stream-recovery) for the full shared reference — Think and `@cloudflare/ai-chat` use the same recovery configuration.
|
|
517
517
|
|
|
518
|
-
> **
|
|
518
|
+
> **Out-of-memory crash loops.** A turn that exceeds the 128 MB limit on every run is sealed by `maxInterruptedAttempts`: the next isolate counts each run that died before re-running it, because the isolate that hit the limit cannot write anything. The alarm boundary also stops the platform from retrying the alarm in a tight loop and emits an `alarm:memory_limit_reset` event; its `maxAlarmMemoryLimitStrikes` counter (a base `Agent` static option, default `3`) only advances while storage still accepts writes. None of this shrinks the working set: a turn that no longer fits in 128 MB needs a smaller context.
|
|
519
519
|
|
|
520
520
|
---
|
|
521
521
|
|
package/docs/tools.md
CHANGED
|
@@ -6,7 +6,7 @@ Think provides built-in workspace file tools on every turn, plus integration poi
|
|
|
6
6
|
|
|
7
7
|
On every turn, Think merges tools from multiple sources. Later sources override earlier ones if names collide:
|
|
8
8
|
|
|
9
|
-
1. **Workspace tools** — `read`, `
|
|
9
|
+
1. **Workspace tools** — `read`, `ls`, `find`, `grep`, `write`, `edit`, `delete`, plus `exec` and `publish` when configured (built-in)
|
|
10
10
|
2. **`getTools()`** — your custom server-side tools
|
|
11
11
|
3. **Extension tools** — tools from loaded extensions (prefixed by extension name)
|
|
12
12
|
4. **Context tools** — `set_context`, `search_context` (from `configureContext`)
|
|
@@ -20,57 +20,45 @@ use [Agent Tools](https://github.com/cloudflare/agents/blob/main/docs/agents/age
|
|
|
20
20
|
|
|
21
21
|
## Built-in Workspace Tools
|
|
22
22
|
|
|
23
|
-
Every Think agent gets `this.workspace
|
|
24
|
-
|
|
25
|
-
| Tool | Description |
|
|
26
|
-
| -------- | --------------------------------------------------------------------------- |
|
|
27
|
-
| `read` | Read text with line numbers; pass images and PDFs to multimodal models |
|
|
28
|
-
| `write` | Write content to a file (creates parent directories) |
|
|
29
|
-
| `edit` | Apply a find-and-replace edit to an existing file (supports fuzzy matching) |
|
|
30
|
-
| `list` | List files and directories in a path |
|
|
31
|
-
| `find` | Find files matching a glob pattern |
|
|
32
|
-
| `grep` | Search file contents by regex or fixed string |
|
|
33
|
-
| `delete` | Delete a file or directory |
|
|
34
|
-
| `bash` | Run a sandboxed Bash script against workspace files |
|
|
35
|
-
|
|
36
|
-
The `bash` tool is enabled by default. It mounts workspace files into a
|
|
37
|
-
`just-bash` virtual filesystem, runs with network access disabled, and writes
|
|
38
|
-
created, updated, and deleted files and empty directories back to the workspace.
|
|
39
|
-
Use it for shell-style workflows that combine multiple file operations; use the
|
|
40
|
-
narrower tools for simple reads, writes, and edits.
|
|
41
|
-
|
|
42
|
-
To keep tool calls bounded, the Bash tool snapshots up to 1,000 workspace files
|
|
43
|
-
by default and skips files larger than 1 MB. Skipped files are reported in the
|
|
44
|
-
tool result and are treated as protected during write-back so the script cannot
|
|
45
|
-
accidentally overwrite or delete content that was not mounted. You can tune
|
|
46
|
-
`maxWorkspaceFiles`, `maxWorkspaceFileBytes`, `maxOutputBytes`, `timeout`, and
|
|
47
|
-
`network` through `workspaceBash`.
|
|
48
|
-
|
|
49
|
-
Disable the default Bash tool for conservative deployments:
|
|
23
|
+
Every Think agent gets `this.workspace`: a `Workspace` from [`@cloudflare/computer`](https://github.com/cloudflare/computer), stored in the Durable Object's SQLite. Think adds Computer's AI SDK tools to every turn with no configuration.
|
|
50
24
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
25
|
+
| Tool | Description |
|
|
26
|
+
| --------- | ----------------------------------------------------------------------------------- |
|
|
27
|
+
| `read` | Read text with line and byte paging; pass images and PDFs to multimodal models |
|
|
28
|
+
| `ls` | List files and directories in a path, with pagination |
|
|
29
|
+
| `find` | Find files matching a glob pattern |
|
|
30
|
+
| `grep` | Search file contents by regex or fixed string |
|
|
31
|
+
| `write` | Write content to a file (creates parent directories) |
|
|
32
|
+
| `edit` | Apply exact text replacements to a file, falling back to whitespace-tolerant search |
|
|
33
|
+
| `delete` | Delete a file or directory |
|
|
34
|
+
| `exec` | Run a command or module on one of the Workspace's execution backends |
|
|
35
|
+
| `publish` | Share a workspace file through a presigned URL, when the Workspace has assets |
|
|
54
36
|
|
|
55
|
-
|
|
56
|
-
/* ... */
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
```
|
|
37
|
+
Paths are absolute. Computer's tools and backends treat `/workspace` as the working root, and Think writes its own files there too.
|
|
60
38
|
|
|
61
|
-
###
|
|
39
|
+
### Running code with `exec`
|
|
62
40
|
|
|
63
|
-
|
|
41
|
+
The default Workspace has no execution backends, so there is no `exec` tool until you add one. Configure the backends, and the modules they offer, on the Workspace:
|
|
64
42
|
|
|
65
43
|
```typescript
|
|
66
44
|
import { Think } from "@cloudflare/think";
|
|
67
|
-
import { Workspace } from "@cloudflare/
|
|
45
|
+
import { Workspace } from "@cloudflare/computer";
|
|
46
|
+
import { WorkerJavaScriptBackend } from "@cloudflare/computer/backends/worker-javascript";
|
|
47
|
+
import { createGitClient } from "@cloudflare/computer/git";
|
|
48
|
+
import { createGitModule } from "@cloudflare/computer/modules/git";
|
|
68
49
|
|
|
69
50
|
export class MyAgent extends Think<Env> {
|
|
70
51
|
override workspace = new Workspace({
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
52
|
+
storage: this.ctx.storage,
|
|
53
|
+
git: createGitClient(),
|
|
54
|
+
backends: [
|
|
55
|
+
new WorkerJavaScriptBackend({
|
|
56
|
+
id: "js",
|
|
57
|
+
loader: this.env.LOADER,
|
|
58
|
+
access: "read-write",
|
|
59
|
+
modules: { "ws:git": createGitModule() }
|
|
60
|
+
})
|
|
61
|
+
]
|
|
74
62
|
});
|
|
75
63
|
|
|
76
64
|
getModel() {
|
|
@@ -79,14 +67,43 @@ export class MyAgent extends Think<Env> {
|
|
|
79
67
|
}
|
|
80
68
|
```
|
|
81
69
|
|
|
82
|
-
|
|
70
|
+
Computer ships a JavaScript backend and a just-bash shell backend that run in Dynamic Workers, and a container backend with a full Linux userland. See the [Computer README](https://github.com/cloudflare/computer/tree/main/packages/computer#choosing-a-backend) for each backend's bindings.
|
|
83
71
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
72
|
+
### Calling the agent's tools from code
|
|
73
|
+
|
|
74
|
+
Give a JavaScript backend a `ws:tools` module, and code the model runs with `exec` can import the agent's tools. Files come from `node:fs/promises`, so serve `getTools()` rather than the workspace tools:
|
|
75
|
+
|
|
76
|
+
```typescript
|
|
77
|
+
import { createToolBindings } from "@cloudflare/computer/modules/tools";
|
|
78
|
+
import { forAISDKTools } from "@cloudflare/computer/tools/ai-sdk";
|
|
79
|
+
|
|
80
|
+
new WorkerJavaScriptBackend({
|
|
81
|
+
id: "js",
|
|
82
|
+
loader: this.env.LOADER,
|
|
83
|
+
modules: {
|
|
84
|
+
"ws:tools": createToolBindings(forAISDKTools(() => this.getTools()))
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
import { readFile } from "node:fs/promises";
|
|
91
|
+
import { getWeather } from "ws:tools";
|
|
92
|
+
|
|
93
|
+
export default async function () {
|
|
94
|
+
const cities = JSON.parse(await readFile("/workspace/cities.json", "utf8"));
|
|
95
|
+
const reports = [];
|
|
96
|
+
for (const city of cities) reports.push((await getWeather({ city })).text);
|
|
97
|
+
return reports;
|
|
87
98
|
}
|
|
88
99
|
```
|
|
89
100
|
|
|
101
|
+
Tools that need approval, and tools that run in the browser, are not exported: nothing can approve or run them from code. Calls from code do not go through `beforeToolCall`. See [`ws:tools`](https://github.com/cloudflare/computer/blob/main/docs/17_isolate_javascript.md#wstools) for how calls and results work.
|
|
102
|
+
|
|
103
|
+
### Changing the tools
|
|
104
|
+
|
|
105
|
+
`exec` offers every backend the Workspace has, and each backend describes itself to the model. To change a built-in tool, return a tool with the same name from `getTools()`; it replaces the built-in. To hide tools for a turn, return `activeTools` from `beforeTurn`.
|
|
106
|
+
|
|
90
107
|
## Custom Tools
|
|
91
108
|
|
|
92
109
|
Override `getTools()` to add your own tools. These are standard AI SDK `tool()` definitions with Zod schemas:
|
|
@@ -153,7 +170,7 @@ getTools(): ToolSet {
|
|
|
153
170
|
inputSchema: z.object({ path: z.string() }),
|
|
154
171
|
needsApproval: async ({ path }) => path.startsWith("/important/"),
|
|
155
172
|
execute: async ({ path }) => {
|
|
156
|
-
await this.workspace.rm(path);
|
|
173
|
+
await this.workspace.fs.rm(path);
|
|
157
174
|
return { deleted: path };
|
|
158
175
|
}
|
|
159
176
|
})
|
|
@@ -240,16 +257,19 @@ See [Connecting to MCP Servers](https://github.com/cloudflare/agents/blob/main/d
|
|
|
240
257
|
|
|
241
258
|
## Code Execution Tool
|
|
242
259
|
|
|
260
|
+
> **Deprecated.** Use `exec` on a JavaScript backend with `ws:tools` instead; see [Calling the agent's tools from code](#calling-the-agents-tools-from-code). `createExecuteTool` will be removed along with `@cloudflare/codemode`.
|
|
261
|
+
|
|
243
262
|
Let the LLM write and run TypeScript in a sandboxed Worker, recorded on a durable codemode runtime (abort-and-replay, human approvals, audit trail, reusable snippets). Requires `@cloudflare/codemode` and a `worker_loaders` binding.
|
|
244
263
|
|
|
245
264
|
```sh
|
|
246
265
|
npm install @cloudflare/codemode
|
|
247
266
|
```
|
|
248
267
|
|
|
249
|
-
The one-liner infers
|
|
268
|
+
The one-liner infers the executor from `env.LOADER` and a live browser (`cdp.*`) from `env.BROWSER` if bound. Pass tools for `tools.*`, including the workspace tools if the sandbox should reach the workspace:
|
|
250
269
|
|
|
251
270
|
```typescript
|
|
252
271
|
import { Think } from "@cloudflare/think";
|
|
272
|
+
import { createAITools } from "@cloudflare/computer/tools/ai-sdk";
|
|
253
273
|
import { createExecuteTool } from "@cloudflare/think/tools/execute";
|
|
254
274
|
|
|
255
275
|
export class MyAgent extends Think<Env> {
|
|
@@ -259,7 +279,9 @@ export class MyAgent extends Think<Env> {
|
|
|
259
279
|
|
|
260
280
|
getTools() {
|
|
261
281
|
return {
|
|
262
|
-
execute: createExecuteTool(this
|
|
282
|
+
execute: createExecuteTool(this, {
|
|
283
|
+
tools: createAITools({ workspace: this.workspace })
|
|
284
|
+
})
|
|
263
285
|
};
|
|
264
286
|
}
|
|
265
287
|
}
|
|
@@ -287,25 +309,15 @@ Each missing piece fails with an error naming the step.
|
|
|
287
309
|
Inside the sandbox the model sees typed namespaces plus the platform SDK:
|
|
288
310
|
|
|
289
311
|
- `tools.*` — your AI SDK tools (object args, validated against their schemas). Only tools with an `execute` function are exposed — client-side tools can't run in the sandbox.
|
|
290
|
-
- `state.*` — the workspace filesystem (`state.readFile({ path })`, `state.glob({ pattern })`, `state.planEdits(...)`, …)
|
|
291
312
|
- `cdp.*` — the browser, when a Browser Rendering binding is configured. The execute tool defaults to `session: { mode: "dynamic" }`: sessions are per-execution unless the model promotes one with `cdp.startSession()`.
|
|
292
313
|
- `codemode.search` / `codemode.describe` / `codemode.step` / `codemode.run` — discovery, side-effect boundaries, and saved snippets
|
|
293
314
|
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
```typescript
|
|
297
|
-
execute: createExecuteTool(this, { tools: myDomainTools });
|
|
298
|
-
```
|
|
299
|
-
|
|
300
|
-
Or fully explicit options (no agent inference):
|
|
315
|
+
Or pass fully explicit options (no agent inference):
|
|
301
316
|
|
|
302
317
|
```typescript
|
|
303
|
-
import { createWorkspaceStateBackend } from "@cloudflare/shell";
|
|
304
|
-
|
|
305
318
|
createExecuteTool({
|
|
306
319
|
ctx: this.ctx,
|
|
307
320
|
tools: myDomainTools,
|
|
308
|
-
state: createWorkspaceStateBackend(this.workspace),
|
|
309
321
|
browser: this.env.BROWSER,
|
|
310
322
|
loader: this.env.LOADER
|
|
311
323
|
});
|
|
@@ -393,7 +405,7 @@ Pass `quickActions: false` to keep only `browser_execute`, or `quickActions: { a
|
|
|
393
405
|
|
|
394
406
|
By default each execution gets a fresh browser session (`one-shot`), torn down when the run ends. Pass `session: { mode: "dynamic" }` to let the model promote a session with `cdp.startSession()` so later executions continue in the same browser, or `session: { mode: "reuse", key }` for a named long-lived session. Stale sessions are reclaimed by the connector's `sweep()` — call it from a scheduled task (see `createBrowserRuntime` in `agents/browser` for the connector handle).
|
|
395
407
|
|
|
396
|
-
> The simplest setup is the unified execute tool above: `createExecuteTool(this)` already includes `cdp.*` alongside `
|
|
408
|
+
> The simplest setup is the unified execute tool above: `createExecuteTool(this)` already includes `cdp.*` alongside `tools.*` when `env.BROWSER` is bound — one tool, one durable history. Use `createBrowserTools` when you want a separate, browser-only tool.
|
|
397
409
|
|
|
398
410
|
### Combining with Other Tools
|
|
399
411
|
|
|
@@ -552,51 +564,3 @@ getExtensions() {
|
|
|
552
564
|
```
|
|
553
565
|
|
|
554
566
|
The context block is registered as `notes_scratchpad` (namespaced by extension name).
|
|
555
|
-
|
|
556
|
-
## Workspace Tools for Custom Backends
|
|
557
|
-
|
|
558
|
-
The individual tool factories are exported for use with custom storage backends that implement the operations interfaces:
|
|
559
|
-
|
|
560
|
-
```typescript
|
|
561
|
-
import {
|
|
562
|
-
createReadTool,
|
|
563
|
-
createWriteTool,
|
|
564
|
-
createEditTool,
|
|
565
|
-
createListTool,
|
|
566
|
-
createFindTool,
|
|
567
|
-
createGrepTool,
|
|
568
|
-
createDeleteTool
|
|
569
|
-
} from "@cloudflare/think/tools/workspace";
|
|
570
|
-
import type {
|
|
571
|
-
ReadOperations,
|
|
572
|
-
WriteOperations,
|
|
573
|
-
EditOperations,
|
|
574
|
-
ListOperations,
|
|
575
|
-
FindOperations,
|
|
576
|
-
GrepOperations,
|
|
577
|
-
DeleteOperations
|
|
578
|
-
} from "@cloudflare/think/tools/workspace";
|
|
579
|
-
```
|
|
580
|
-
|
|
581
|
-
Implement the operations interface for your storage backend:
|
|
582
|
-
|
|
583
|
-
```typescript
|
|
584
|
-
const myReadOps: ReadOperations = {
|
|
585
|
-
readFile: async (path) => fetchFromMyStorage(path),
|
|
586
|
-
readFileBytes: async (path) => fetchBytesFromMyStorage(path),
|
|
587
|
-
stat: async (path) => getFileInfo(path)
|
|
588
|
-
};
|
|
589
|
-
|
|
590
|
-
const readTool = createReadTool({ ops: myReadOps });
|
|
591
|
-
```
|
|
592
|
-
|
|
593
|
-
Or create the full set from a Workspace:
|
|
594
|
-
|
|
595
|
-
```typescript
|
|
596
|
-
import { createWorkspaceTools } from "@cloudflare/think/tools/workspace";
|
|
597
|
-
|
|
598
|
-
const tools = createWorkspaceTools(myCustomWorkspace);
|
|
599
|
-
const toolsWithoutBash = createWorkspaceTools(myCustomWorkspace, {
|
|
600
|
-
bash: false
|
|
601
|
-
});
|
|
602
|
-
```
|