@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/README.md
CHANGED
|
@@ -170,36 +170,67 @@ drill-in, and cleanup patterns.
|
|
|
170
170
|
|
|
171
171
|
## Built-in workspace
|
|
172
172
|
|
|
173
|
-
Every Think agent gets `this.workspace
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
access disabled by default, and syncs changed files and empty directories back
|
|
178
|
-
into the workspace. It snapshots up to 1,000 files by default, skips files larger
|
|
179
|
-
than 1 MB, and treats skipped paths as protected during write-back. Set
|
|
180
|
-
`workspaceBash = false` on your Think subclass to opt out, or pass an options
|
|
181
|
-
object to tune limits, timeout, and network access.
|
|
173
|
+
Every Think agent gets `this.workspace`: a `Workspace` from
|
|
174
|
+
[`@cloudflare/computer`](https://github.com/cloudflare/computer), stored in the
|
|
175
|
+
agent's own SQLite. The `@cloudflare/computer` tools (`read`, `ls`, `find`,
|
|
176
|
+
`grep`, `write`, `edit`, `delete`) are available to the model on every turn.
|
|
182
177
|
|
|
183
178
|
```ts
|
|
184
179
|
export class MyAgent extends Think<Env> {
|
|
185
180
|
getModel() { ... }
|
|
186
|
-
// this.workspace is ready to use
|
|
187
|
-
// workspace tools are auto-merged into every chat turn
|
|
181
|
+
// this.workspace is ready to use, and the workspace tools join every turn
|
|
188
182
|
}
|
|
189
183
|
```
|
|
190
184
|
|
|
191
|
-
|
|
185
|
+
The model gets an `exec` tool once the Workspace has execution backends.
|
|
186
|
+
Configure the backends, and the modules they offer, on the `Workspace`:
|
|
192
187
|
|
|
193
188
|
```ts
|
|
189
|
+
import { Workspace } from "@cloudflare/computer";
|
|
190
|
+
import { WorkerJavaScriptBackend } from "@cloudflare/computer/backends/worker-javascript";
|
|
191
|
+
import { createGitModule } from "@cloudflare/computer/modules/git";
|
|
192
|
+
|
|
194
193
|
export class MyAgent extends Think<Env> {
|
|
195
194
|
override workspace = new Workspace({
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
195
|
+
storage: this.ctx.storage,
|
|
196
|
+
backends: [
|
|
197
|
+
new WorkerJavaScriptBackend({
|
|
198
|
+
id: "js",
|
|
199
|
+
loader: this.env.LOADER,
|
|
200
|
+
modules: { "ws:git": createGitModule() }
|
|
201
|
+
})
|
|
202
|
+
]
|
|
199
203
|
});
|
|
200
204
|
}
|
|
201
205
|
```
|
|
202
206
|
|
|
207
|
+
To change a built-in tool, return a tool with the same name from `getTools()`.
|
|
208
|
+
To hide tools for a turn, return `activeTools` from `beforeTurn`.
|
|
209
|
+
|
|
210
|
+
Give a backend a `ws:tools` module, and code the model runs with `exec` can
|
|
211
|
+
import the agent's tools; files come from `node:fs`:
|
|
212
|
+
|
|
213
|
+
```ts
|
|
214
|
+
import { createToolBindings } from "@cloudflare/computer/modules/tools";
|
|
215
|
+
import { forAISDKTools } from "@cloudflare/computer/tools/ai-sdk";
|
|
216
|
+
|
|
217
|
+
new WorkerJavaScriptBackend({
|
|
218
|
+
id: "js",
|
|
219
|
+
loader: this.env.LOADER,
|
|
220
|
+
modules: {
|
|
221
|
+
"ws:tools": createToolBindings(forAISDKTools(() => this.getTools()))
|
|
222
|
+
}
|
|
223
|
+
});
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
```ts
|
|
227
|
+
import { getWeather } from "ws:tools";
|
|
228
|
+
export default async () => (await getWeather({ city: "Lisbon" })).text;
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
Every Think agent can hand out its own Workspace: `getWorkspace(stub)` from
|
|
232
|
+
`@cloudflare/computer` calls the agent's `__getWorkspaceStub()` over RPC.
|
|
233
|
+
|
|
203
234
|
## Agent Skills
|
|
204
235
|
|
|
205
236
|
Think supports the [Agent Skills](https://agentskills.io/) directory format as
|
|
@@ -263,8 +294,8 @@ turn automatically.
|
|
|
263
294
|
|
|
264
295
|
Think can also project each resolved `SKILL.md` into the active workspace so
|
|
265
296
|
the agent can read and edit skills as files. This is off by default: skills
|
|
266
|
-
load from their sources and nothing is written to the Workspace.
|
|
267
|
-
`/workspace/.agents/skills
|
|
297
|
+
load from their sources and nothing is written to the Workspace. Skills land
|
|
298
|
+
under `/workspace/.agents/skills`. Existing
|
|
268
299
|
workspace edits are preserved and affect later activation. Resources copy into
|
|
269
300
|
the workspace on first use rather than at startup. Think records a durable
|
|
270
301
|
source fingerprint, so unchanged cold wakes do not stat or rewrite every skill
|
|
@@ -342,12 +373,11 @@ Script execution requires a Worker Loader binding:
|
|
|
342
373
|
|
|
343
374
|
| Export | Description |
|
|
344
375
|
| --------------------------------------- | ------------------------------------------------------------- |
|
|
345
|
-
| `@cloudflare/think` | `Think`, `Session
|
|
376
|
+
| `@cloudflare/think` | `Think`, `Session` — main class + re-exports |
|
|
346
377
|
| `agents/sessions` | `Sessions`, `Session`, `createCompactFunction`, attachments |
|
|
347
378
|
| `agents/context` | `ContextBlocks`, providers, `ContextConfig` — prompt assembly |
|
|
348
379
|
| `@cloudflare/think/messengers` | Messenger contracts, Chat SDK bridge, state agent, delivery |
|
|
349
380
|
| `@cloudflare/think/messengers/telegram` | Telegram messenger provider and delivery helpers |
|
|
350
|
-
| `@cloudflare/think/tools/workspace` | `createWorkspaceTools()` — for custom storage backends |
|
|
351
381
|
| `@cloudflare/think/tools/fetch` | `createFetchTools()` — opt-in allowlisted HTTP reads |
|
|
352
382
|
| `@cloudflare/think/tools/execute` | `createExecuteTool()` — sandboxed code execution via codemode |
|
|
353
383
|
| `@cloudflare/think/tools/extensions` | `createExtensionTools()` — LLM-driven extension loading |
|
|
@@ -378,7 +408,6 @@ Script execution requires a Worker Loader binding:
|
|
|
378
408
|
| `getSkillScriptRunner()` | `null` | Optional runner for `run_skill_script` |
|
|
379
409
|
| `getExtensions()` | `[]` | Sandboxed extension declarations (load order) |
|
|
380
410
|
| `extensionLoader` | `undefined` | `WorkerLoader` binding — enables extensions |
|
|
381
|
-
| `workspaceBash` | `true` | Include the default workspace `bash` tool |
|
|
382
411
|
| `fetchTools` | `false` | Opt-in allowlisted HTTP read tools (`fetch_url` + per-binding `fetch_<name>`). Set to a config object; see [Fetch tool](#fetch-tool) |
|
|
383
412
|
| `includeMcpTools` | `true` | Automatically convert connected MCP tools to AI SDK tools and merge them into model turns |
|
|
384
413
|
| `waitForMcpConnections` | `false` | Wait for MCP connections to settle before inference |
|
|
@@ -685,9 +714,7 @@ Extensions can subscribe to `beforeTurn`, `beforeToolCall`, `afterToolCall`, `on
|
|
|
685
714
|
```js
|
|
686
715
|
// extension source (loaded via getExtensions())
|
|
687
716
|
({
|
|
688
|
-
tools: {
|
|
689
|
-
/* ... */
|
|
690
|
-
},
|
|
717
|
+
tools: {/* ... */},
|
|
691
718
|
hooks: {
|
|
692
719
|
beforeToolCall: async (snapshot, host) => {
|
|
693
720
|
/* observation */
|
|
@@ -855,8 +882,7 @@ Splitting never reclaims database space — the continuation rows live in the
|
|
|
855
882
|
same Durable Object as the message — and Sessions imposes no upper bound on a
|
|
856
883
|
single message, so one very large write can consume a meaningful share of the
|
|
857
884
|
10 GB an object has. Bounding untrusted input is the application's job. Files
|
|
858
|
-
belong in the Workspace
|
|
859
|
-
message. This is a storage detail: invisible to the model, and unrelated to
|
|
885
|
+
belong in the Workspace; put a reference to one in the message. This is a storage detail: invisible to the model, and unrelated to
|
|
860
886
|
media eviction.
|
|
861
887
|
|
|
862
888
|
#### Media eviction
|
|
@@ -1017,30 +1043,22 @@ For values you want broadcast to connected clients, use `state` / `setState` fro
|
|
|
1017
1043
|
- **Message sanitization** — strips ephemeral provider metadata before storage
|
|
1018
1044
|
- **Row size enforcement** — compacts tool outputs exceeding 1.8MB
|
|
1019
1045
|
|
|
1020
|
-
## Workspace tools
|
|
1021
|
-
|
|
1022
|
-
File operation tools are built into Think and available to the model on every turn. For custom storage backends, the individual tool factories are also exported:
|
|
1023
|
-
|
|
1024
|
-
```ts
|
|
1025
|
-
import { createWorkspaceTools } from "@cloudflare/think/tools/workspace";
|
|
1026
|
-
|
|
1027
|
-
// Use with a custom ReadOperations/WriteOperations implementation
|
|
1028
|
-
const tools = createWorkspaceTools(myCustomStorage);
|
|
1029
|
-
const toolsWithoutBash = createWorkspaceTools(myCustomStorage, { bash: false });
|
|
1030
|
-
```
|
|
1031
|
-
|
|
1032
|
-
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.
|
|
1033
|
-
|
|
1034
1046
|
## Code execution tool
|
|
1035
1047
|
|
|
1048
|
+
> **Deprecated.** Use `exec` with `ws:tools` (see [Built-in workspace](#built-in-workspace)).
|
|
1049
|
+
|
|
1036
1050
|
Let the LLM write and run JavaScript in a sandboxed Worker:
|
|
1037
1051
|
|
|
1038
1052
|
```ts
|
|
1053
|
+
import { createAITools } from "@cloudflare/computer/tools/ai-sdk";
|
|
1039
1054
|
import { createExecuteTool } from "@cloudflare/think/tools/execute";
|
|
1040
1055
|
|
|
1041
1056
|
getTools() {
|
|
1042
1057
|
return {
|
|
1043
|
-
|
|
1058
|
+
// tools.* in the sandbox includes the workspace tools
|
|
1059
|
+
execute: createExecuteTool(this, {
|
|
1060
|
+
tools: createAITools({ workspace: this.workspace })
|
|
1061
|
+
})
|
|
1044
1062
|
};
|
|
1045
1063
|
}
|
|
1046
1064
|
```
|
|
@@ -1131,12 +1149,11 @@ getTools() {
|
|
|
1131
1149
|
| Package | Notes |
|
|
1132
1150
|
| ---------------------------- | --------------------------------------------------------- |
|
|
1133
1151
|
| `agents` | Cloudflare Agents SDK peer dependency |
|
|
1134
|
-
| `ai` | Vercel AI SDK
|
|
1152
|
+
| `ai` | Vercel AI SDK v7 peer dependency |
|
|
1135
1153
|
| `zod` | Schema validation peer dependency |
|
|
1136
|
-
| `@cloudflare/
|
|
1154
|
+
| `@cloudflare/computer` | Workspace and workspace tools peer dependency |
|
|
1137
1155
|
| `@cloudflare/codemode` | Code execution, `createExecuteTool`, and JS skill scripts |
|
|
1138
1156
|
| `@cloudflare/worker-bundler` | TypeScript skill script compilation |
|
|
1139
|
-
| `just-bash` | Bash skill script execution |
|
|
1140
1157
|
| `@chat-adapter/telegram` | Required for Telegram messengers |
|
|
1141
1158
|
|
|
1142
1159
|
## Acknowledgments
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
//#region \0@oxc-project+runtime@0.137.0/helpers/esm/checkPrivateRedeclaration.js
|
|
2
|
+
function _checkPrivateRedeclaration(e, t) {
|
|
3
|
+
if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object");
|
|
4
|
+
}
|
|
5
|
+
//#endregion
|
|
6
|
+
//#region \0@oxc-project+runtime@0.137.0/helpers/esm/classPrivateFieldInitSpec.js
|
|
7
|
+
function _classPrivateFieldInitSpec(e, t, a) {
|
|
8
|
+
_checkPrivateRedeclaration(e, t), t.set(e, a);
|
|
9
|
+
}
|
|
10
|
+
//#endregion
|
|
11
|
+
//#region \0@oxc-project+runtime@0.137.0/helpers/esm/assertClassBrand.js
|
|
12
|
+
function _assertClassBrand(e, t, n) {
|
|
13
|
+
if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n;
|
|
14
|
+
throw new TypeError("Private element is not present on this object");
|
|
15
|
+
}
|
|
16
|
+
//#endregion
|
|
17
|
+
//#region \0@oxc-project+runtime@0.137.0/helpers/esm/classPrivateFieldGet2.js
|
|
18
|
+
function _classPrivateFieldGet2(s, a) {
|
|
19
|
+
return s.get(_assertClassBrand(s, a));
|
|
20
|
+
}
|
|
21
|
+
//#endregion
|
|
22
|
+
//#region \0@oxc-project+runtime@0.137.0/helpers/esm/classPrivateFieldSet2.js
|
|
23
|
+
function _classPrivateFieldSet2(s, a, r) {
|
|
24
|
+
return s.set(_assertClassBrand(s, a), r), r;
|
|
25
|
+
}
|
|
26
|
+
//#endregion
|
|
27
|
+
export { _checkPrivateRedeclaration as a, _classPrivateFieldInitSpec as i, _classPrivateFieldGet2 as n, _assertClassBrand as r, _classPrivateFieldSet2 as t };
|
package/dist/extensions/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { r as _assertClassBrand } from "../classPrivateFieldSet2-DwGJfC3w.js";
|
|
2
|
+
import { r as _classPrivateMethodInitSpec, t as ExtensionManager } from "../manager-BubfmA3q.js";
|
|
2
3
|
import { WorkerEntrypoint } from "cloudflare:workers";
|
|
3
4
|
//#region src/extensions/host-bridge.ts
|
|
4
5
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/extensions/host-bridge.ts","../../src/extensions/bridge-provider.ts"],"sourcesContent":["/**\n * HostBridgeLoopback — a WorkerEntrypoint that provides controlled workspace\n * access to extension Workers loaded via WorkerLoader.\n *\n * This is a loopback: the extension worker's `env.host` binding points here,\n * and each method call resolves the parent agent via `ctx.exports`, then\n * delegates to the agent's workspace proxy methods (`_hostReadFile`, etc.).\n *\n * Props carry serializable identifiers (agent class name, agent ID, and\n * permissions) so the binding survives across requests and hibernation.\n *\n * Users must re-export this class from their worker entry point:\n *\n * ```typescript\n * export { HostBridgeLoopback } from \"@cloudflare/think/extensions\";\n * ```\n *\n * @experimental The API surface may change before stabilizing.\n */\n\nimport { WorkerEntrypoint } from \"cloudflare:workers\";\nimport type { ExtensionPermissions } from \"./types\";\n\nexport type HostBridgeLoopbackProps = {\n agentClassName: string;\n agentId: string;\n permissions: ExtensionPermissions;\n /** Namespaced context labels this extension declared (for \"own\" write validation). */\n ownContextLabels?: string[];\n};\n\nexport class HostBridgeLoopback extends WorkerEntrypoint<\n Record<string, unknown>,\n HostBridgeLoopbackProps\n> {\n private _permissions = this.ctx.props.permissions;\n\n private _getAgent() {\n const { agentClassName, agentId } = this.ctx.props;\n // @ts-expect-error — experimental: ctx.exports on WorkerEntrypoint\n const ns = this.ctx.exports[agentClassName] as DurableObjectNamespace;\n return ns.get(ns.idFromString(agentId));\n }\n\n // ── Permission checks ──────────────────────────────────────────\n\n #requireWorkspace(level: \"read\" | \"read-write\"): void {\n const ws = this._permissions.workspace ?? \"none\";\n if (ws === \"none\") {\n throw new Error(\"Extension error: no workspace permission declared\");\n }\n if (level === \"read-write\" && ws !== \"read-write\") {\n throw new Error(\n \"Extension error: workspace write permission required, but only read granted\"\n );\n }\n }\n\n #requireContextRead(label: string): void {\n const ctx = this._permissions.context;\n if (!ctx?.read) {\n throw new Error(\"Extension error: no context read permission declared\");\n }\n if (ctx.read !== \"all\" && !ctx.read.includes(label)) {\n throw new Error(\n `Extension error: no read permission for context label \"${label}\"`\n );\n }\n }\n\n #requireContextWrite(label: string): void {\n const ctx = this._permissions.context;\n if (!ctx?.write) {\n throw new Error(\"Extension error: no context write permission declared\");\n }\n if (ctx.write === \"own\") {\n const owned = this.ctx.props.ownContextLabels ?? [];\n if (!owned.includes(label)) {\n throw new Error(\n `Extension error: label \"${label}\" is not owned by this extension`\n );\n }\n } else if (!ctx.write.includes(label)) {\n throw new Error(\n `Extension error: no write permission for context label \"${label}\"`\n );\n }\n }\n\n #requireMessages(): void {\n if (this._permissions.messages !== \"read\") {\n throw new Error(\"Extension error: no messages read permission declared\");\n }\n }\n\n #requireSendMessage(): void {\n if (!this._permissions.session?.sendMessage) {\n throw new Error(\n \"Extension error: no session.sendMessage permission declared\"\n );\n }\n }\n\n #requireSessionMetadata(): void {\n if (!this._permissions.session?.metadata) {\n throw new Error(\n \"Extension error: no session.metadata permission declared\"\n );\n }\n }\n\n // ── Workspace (existing) ───────────────────────────────────────\n\n async readFile(path: string): Promise<string | null> {\n this.#requireWorkspace(\"read\");\n return (\n this._getAgent() as unknown as {\n _hostReadFile(path: string): Promise<string | null>;\n }\n )._hostReadFile(path);\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n this.#requireWorkspace(\"read-write\");\n return (\n this._getAgent() as unknown as {\n _hostWriteFile(path: string, content: string): Promise<void>;\n }\n )._hostWriteFile(path, content);\n }\n\n async deleteFile(path: string): Promise<boolean> {\n this.#requireWorkspace(\"read-write\");\n return (\n this._getAgent() as unknown as {\n _hostDeleteFile(path: string): Promise<boolean>;\n }\n )._hostDeleteFile(path);\n }\n\n async listFiles(\n dir: string\n ): Promise<\n Array<{ name: string; type: string; size: number; path: string }>\n > {\n this.#requireWorkspace(\"read\");\n return (\n this._getAgent() as unknown as {\n _hostListFiles(\n dir: string\n ): Promise<\n Array<{ name: string; type: string; size: number; path: string }>\n >;\n }\n )._hostListFiles(dir);\n }\n\n // ── Context blocks (new) ───────────────────────────────────────\n\n async getContext(label: string): Promise<string | null> {\n this.#requireContextRead(label);\n return (\n this._getAgent() as unknown as {\n _hostGetContext(label: string): Promise<string | null>;\n }\n )._hostGetContext(label);\n }\n\n async setContext(label: string, content: string): Promise<void> {\n this.#requireContextWrite(label);\n return (\n this._getAgent() as unknown as {\n _hostSetContext(label: string, content: string): Promise<void>;\n }\n )._hostSetContext(label, content);\n }\n\n // ── Messages (new) ────────────────────────────────────────────\n\n async getMessages(\n limit?: number\n ): Promise<Array<{ id: string; role: string; content: string }>> {\n this.#requireMessages();\n return (\n this._getAgent() as unknown as {\n _hostGetMessages(\n limit?: number\n ): Promise<Array<{ id: string; role: string; content: string }>>;\n }\n )._hostGetMessages(limit);\n }\n\n async sendMessage(content: string): Promise<void> {\n this.#requireSendMessage();\n return (\n this._getAgent() as unknown as {\n _hostSendMessage(content: string): Promise<void>;\n }\n )._hostSendMessage(content);\n }\n\n // ── Session metadata (new) ────────────────────────────────────\n\n async getSessionInfo(): Promise<{ messageCount: number }> {\n this.#requireSessionMetadata();\n return (\n this._getAgent() as unknown as {\n _hostGetSessionInfo(): Promise<{ messageCount: number }>;\n }\n )._hostGetSessionInfo();\n }\n}\n","/**\n * Bridge providers that adapt extension Worker RPC into Session's\n * ContextProvider / WritableContextProvider interfaces.\n *\n * When an extension declares context blocks in its manifest, Think creates\n * a bridge provider for each block. The bridge delegates `get()`, `load()`,\n * and `set()` to the extension Worker's entrypoint via RPC.\n *\n * This allows extensions to contribute context blocks to the Session's\n * system prompt without Session knowing about the extension system.\n */\n\ninterface ExtensionContextEntrypoint {\n contextGet(label: string): Promise<string | null>;\n contextLoad?(label: string, key: string): Promise<string | null>;\n contextSet?(\n label: string,\n key: string,\n content: string,\n description?: string\n ): Promise<void>;\n}\n\n/**\n * A readonly context provider backed by an extension Worker.\n * Delegates `get()` to the extension's `contextGet` RPC method.\n */\nexport class ExtensionContextBridge {\n protected _label: string;\n protected _entrypoint: ExtensionContextEntrypoint;\n\n constructor(label: string, entrypoint: ExtensionContextEntrypoint) {\n this._label = label;\n this._entrypoint = entrypoint;\n }\n\n init(_label: string): void {}\n\n async get(): Promise<string | null> {\n return this._entrypoint.contextGet(this._label);\n }\n}\n\n/**\n * A writable context provider backed by an extension Worker.\n * Delegates `get()` and `set()` to the extension's RPC methods.\n */\nexport class ExtensionWritableBridge extends ExtensionContextBridge {\n async set(content: string): Promise<void> {\n await this._entrypoint.contextSet?.(this._label, \"\", content);\n }\n}\n\n/**\n * A skill provider backed by an extension Worker.\n * Delegates `get()`, `load()`, and optionally `set()` to the extension's RPC methods.\n */\nexport class ExtensionSkillBridge extends ExtensionContextBridge {\n async load(key: string): Promise<string | null> {\n return (await this._entrypoint.contextLoad?.(this._label, key)) ?? null;\n }\n\n async set(key: string, content: string, description?: string): Promise<void> {\n await this._entrypoint.contextSet?.(this._label, key, content, description);\n }\n}\n\n/**\n * Create the appropriate bridge provider based on the context block type.\n */\nexport function createBridgeProvider(\n label: string,\n type: \"readonly\" | \"writable\" | \"skill\" | \"searchable\",\n entrypoint: ExtensionContextEntrypoint\n) {\n switch (type) {\n case \"skill\":\n return new ExtensionSkillBridge(label, entrypoint);\n case \"writable\":\n return new ExtensionWritableBridge(label, entrypoint);\n case \"readonly\":\n case \"searchable\":\n default:\n return new ExtensionContextBridge(label, entrypoint);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA+BA,IAAa,qBAAb,cAAwC,iBAGtC;;;;EACA,KAAQ,eAAe,KAAK,IAAI,MAAM;;CAEtC,YAAoB;EAClB,MAAM,EAAE,gBAAgB,YAAY,KAAK,IAAI;EAE7C,MAAM,KAAK,KAAK,IAAI,QAAQ;EAC5B,OAAO,GAAG,IAAI,GAAG,aAAa,OAAO,CAAC;CACxC;CAuEA,MAAM,SAAS,MAAsC;EACnD,k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,MAAM,MAA8B;EAClC,OAAO,KAAK,YAAY,WAAW,KAAK,MAAM;CAChD;AACF;;;;;AAMA,IAAa,0BAAb,cAA6C,uBAAuB;CAClE,MAAM,IAAI,SAAgC;EACxC,MAAM,KAAK,YAAY,aAAa,KAAK,QAAQ,IAAI,OAAO;CAC9D;AACF;;;;;AAMA,IAAa,uBAAb,cAA0C,uBAAuB;CAC/D,MAAM,KAAK,KAAqC;EAC9C,OAAQ,MAAM,KAAK,YAAY,cAAc,KAAK,QAAQ,GAAG,KAAM;CACrE;CAEA,MAAM,IAAI,KAAa,SAAiB,aAAqC;EAC3E,MAAM,KAAK,YAAY,aAAa,KAAK,QAAQ,KAAK,SAAS,WAAW;CAC5E;AACF;;;;AAKA,SAAgB,qBACd,OACA,MACA,YACA;CACA,QAAQ,MAAR;EACE,KAAK,SACH,OAAO,IAAI,qBAAqB,OAAO,UAAU;EACnD,KAAK,YACH,OAAO,IAAI,wBAAwB,OAAO,UAAU;EAGtD,SACE,OAAO,IAAI,uBAAuB,OAAO,UAAU;CACvD;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/extensions/host-bridge.ts","../../src/extensions/bridge-provider.ts"],"sourcesContent":["/**\n * HostBridgeLoopback — a WorkerEntrypoint that provides controlled workspace\n * access to extension Workers loaded via WorkerLoader.\n *\n * This is a loopback: the extension worker's `env.host` binding points here,\n * and each method call resolves the parent agent via `ctx.exports`, then\n * delegates to the agent's workspace proxy methods (`_hostReadFile`, etc.).\n *\n * Props carry serializable identifiers (agent class name, agent ID, and\n * permissions) so the binding survives across requests and hibernation.\n *\n * Users must re-export this class from their worker entry point:\n *\n * ```typescript\n * export { HostBridgeLoopback } from \"@cloudflare/think/extensions\";\n * ```\n *\n * @experimental The API surface may change before stabilizing.\n */\n\nimport { WorkerEntrypoint } from \"cloudflare:workers\";\nimport type { ExtensionPermissions } from \"./types\";\n\nexport type HostBridgeLoopbackProps = {\n agentClassName: string;\n agentId: string;\n permissions: ExtensionPermissions;\n /** Namespaced context labels this extension declared (for \"own\" write validation). */\n ownContextLabels?: string[];\n};\n\nexport class HostBridgeLoopback extends WorkerEntrypoint<\n Record<string, unknown>,\n HostBridgeLoopbackProps\n> {\n private _permissions = this.ctx.props.permissions;\n\n private _getAgent() {\n const { agentClassName, agentId } = this.ctx.props;\n // @ts-expect-error — experimental: ctx.exports on WorkerEntrypoint\n const ns = this.ctx.exports[agentClassName] as DurableObjectNamespace;\n return ns.get(ns.idFromString(agentId));\n }\n\n // ── Permission checks ──────────────────────────────────────────\n\n #requireWorkspace(level: \"read\" | \"read-write\"): void {\n const ws = this._permissions.workspace ?? \"none\";\n if (ws === \"none\") {\n throw new Error(\"Extension error: no workspace permission declared\");\n }\n if (level === \"read-write\" && ws !== \"read-write\") {\n throw new Error(\n \"Extension error: workspace write permission required, but only read granted\"\n );\n }\n }\n\n #requireContextRead(label: string): void {\n const ctx = this._permissions.context;\n if (!ctx?.read) {\n throw new Error(\"Extension error: no context read permission declared\");\n }\n if (ctx.read !== \"all\" && !ctx.read.includes(label)) {\n throw new Error(\n `Extension error: no read permission for context label \"${label}\"`\n );\n }\n }\n\n #requireContextWrite(label: string): void {\n const ctx = this._permissions.context;\n if (!ctx?.write) {\n throw new Error(\"Extension error: no context write permission declared\");\n }\n if (ctx.write === \"own\") {\n const owned = this.ctx.props.ownContextLabels ?? [];\n if (!owned.includes(label)) {\n throw new Error(\n `Extension error: label \"${label}\" is not owned by this extension`\n );\n }\n } else if (!ctx.write.includes(label)) {\n throw new Error(\n `Extension error: no write permission for context label \"${label}\"`\n );\n }\n }\n\n #requireMessages(): void {\n if (this._permissions.messages !== \"read\") {\n throw new Error(\"Extension error: no messages read permission declared\");\n }\n }\n\n #requireSendMessage(): void {\n if (!this._permissions.session?.sendMessage) {\n throw new Error(\n \"Extension error: no session.sendMessage permission declared\"\n );\n }\n }\n\n #requireSessionMetadata(): void {\n if (!this._permissions.session?.metadata) {\n throw new Error(\n \"Extension error: no session.metadata permission declared\"\n );\n }\n }\n\n // ── Workspace (existing) ───────────────────────────────────────\n\n async readFile(path: string): Promise<string | null> {\n this.#requireWorkspace(\"read\");\n return (\n this._getAgent() as unknown as {\n _hostReadFile(path: string): Promise<string | null>;\n }\n )._hostReadFile(path);\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n this.#requireWorkspace(\"read-write\");\n return (\n this._getAgent() as unknown as {\n _hostWriteFile(path: string, content: string): Promise<void>;\n }\n )._hostWriteFile(path, content);\n }\n\n async deleteFile(path: string): Promise<boolean> {\n this.#requireWorkspace(\"read-write\");\n return (\n this._getAgent() as unknown as {\n _hostDeleteFile(path: string): Promise<boolean>;\n }\n )._hostDeleteFile(path);\n }\n\n async listFiles(\n dir: string\n ): Promise<\n Array<{ name: string; type: string; size: number; path: string }>\n > {\n this.#requireWorkspace(\"read\");\n return (\n this._getAgent() as unknown as {\n _hostListFiles(\n dir: string\n ): Promise<\n Array<{ name: string; type: string; size: number; path: string }>\n >;\n }\n )._hostListFiles(dir);\n }\n\n // ── Context blocks (new) ───────────────────────────────────────\n\n async getContext(label: string): Promise<string | null> {\n this.#requireContextRead(label);\n return (\n this._getAgent() as unknown as {\n _hostGetContext(label: string): Promise<string | null>;\n }\n )._hostGetContext(label);\n }\n\n async setContext(label: string, content: string): Promise<void> {\n this.#requireContextWrite(label);\n return (\n this._getAgent() as unknown as {\n _hostSetContext(label: string, content: string): Promise<void>;\n }\n )._hostSetContext(label, content);\n }\n\n // ── Messages (new) ────────────────────────────────────────────\n\n async getMessages(\n limit?: number\n ): Promise<Array<{ id: string; role: string; content: string }>> {\n this.#requireMessages();\n return (\n this._getAgent() as unknown as {\n _hostGetMessages(\n limit?: number\n ): Promise<Array<{ id: string; role: string; content: string }>>;\n }\n )._hostGetMessages(limit);\n }\n\n async sendMessage(content: string): Promise<void> {\n this.#requireSendMessage();\n return (\n this._getAgent() as unknown as {\n _hostSendMessage(content: string): Promise<void>;\n }\n )._hostSendMessage(content);\n }\n\n // ── Session metadata (new) ────────────────────────────────────\n\n async getSessionInfo(): Promise<{ messageCount: number }> {\n this.#requireSessionMetadata();\n return (\n this._getAgent() as unknown as {\n _hostGetSessionInfo(): Promise<{ messageCount: number }>;\n }\n )._hostGetSessionInfo();\n }\n}\n","/**\n * Bridge providers that adapt extension Worker RPC into Session's\n * ContextProvider / WritableContextProvider interfaces.\n *\n * When an extension declares context blocks in its manifest, Think creates\n * a bridge provider for each block. The bridge delegates `get()`, `load()`,\n * and `set()` to the extension Worker's entrypoint via RPC.\n *\n * This allows extensions to contribute context blocks to the Session's\n * system prompt without Session knowing about the extension system.\n */\n\ninterface ExtensionContextEntrypoint {\n contextGet(label: string): Promise<string | null>;\n contextLoad?(label: string, key: string): Promise<string | null>;\n contextSet?(\n label: string,\n key: string,\n content: string,\n description?: string\n ): Promise<void>;\n}\n\n/**\n * A readonly context provider backed by an extension Worker.\n * Delegates `get()` to the extension's `contextGet` RPC method.\n */\nexport class ExtensionContextBridge {\n protected _label: string;\n protected _entrypoint: ExtensionContextEntrypoint;\n\n constructor(label: string, entrypoint: ExtensionContextEntrypoint) {\n this._label = label;\n this._entrypoint = entrypoint;\n }\n\n init(_label: string): void {}\n\n async get(): Promise<string | null> {\n return this._entrypoint.contextGet(this._label);\n }\n}\n\n/**\n * A writable context provider backed by an extension Worker.\n * Delegates `get()` and `set()` to the extension's RPC methods.\n */\nexport class ExtensionWritableBridge extends ExtensionContextBridge {\n async set(content: string): Promise<void> {\n await this._entrypoint.contextSet?.(this._label, \"\", content);\n }\n}\n\n/**\n * A skill provider backed by an extension Worker.\n * Delegates `get()`, `load()`, and optionally `set()` to the extension's RPC methods.\n */\nexport class ExtensionSkillBridge extends ExtensionContextBridge {\n async load(key: string): Promise<string | null> {\n return (await this._entrypoint.contextLoad?.(this._label, key)) ?? null;\n }\n\n async set(key: string, content: string, description?: string): Promise<void> {\n await this._entrypoint.contextSet?.(this._label, key, content, description);\n }\n}\n\n/**\n * Create the appropriate bridge provider based on the context block type.\n */\nexport function createBridgeProvider(\n label: string,\n type: \"readonly\" | \"writable\" | \"skill\" | \"searchable\",\n entrypoint: ExtensionContextEntrypoint\n) {\n switch (type) {\n case \"skill\":\n return new ExtensionSkillBridge(label, entrypoint);\n case \"writable\":\n return new ExtensionWritableBridge(label, entrypoint);\n case \"readonly\":\n case \"searchable\":\n default:\n return new ExtensionContextBridge(label, entrypoint);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA+BA,IAAa,qBAAb,cAAwC,iBAGtC;;;;EACA,KAAQ,eAAe,KAAK,IAAI,MAAM;;CAEtC,YAAoB;EAClB,MAAM,EAAE,gBAAgB,YAAY,KAAK,IAAI;EAE7C,MAAM,KAAK,KAAK,IAAI,QAAQ;EAC5B,OAAO,GAAG,IAAI,GAAG,aAAa,OAAO,CAAC;CACxC;CAuEA,MAAM,SAAS,MAAsC;EACnD,kBAAA,2BAAA,MAAA,iBAAA,CAAA,CAAA,KAAA,MAAuB,MAAM;EAC7B,OACE,KAAK,UAAU,CAAC,CAGhB,cAAc,IAAI;CACtB;CAEA,MAAM,UAAU,MAAc,SAAgC;EAC5D,kBAAA,2BAAA,MAAA,iBAAA,CAAA,CAAA,KAAA,MAAuB,YAAY;EACnC,OACE,KAAK,UAAU,CAAC,CAGhB,eAAe,MAAM,OAAO;CAChC;CAEA,MAAM,WAAW,MAAgC;EAC/C,kBAAA,2BAAA,MAAA,iBAAA,CAAA,CAAA,KAAA,MAAuB,YAAY;EACnC,OACE,KAAK,UAAU,CAAC,CAGhB,gBAAgB,IAAI;CACxB;CAEA,MAAM,UACJ,KAGA;EACA,kBAAA,2BAAA,MAAA,iBAAA,CAAA,CAAA,KAAA,MAAuB,MAAM;EAC7B,OACE,KAAK,UAAU,CAAC,CAOhB,eAAe,GAAG;CACtB;CAIA,MAAM,WAAW,OAAuC;EACtD,kBAAA,2BAAA,MAAA,mBAAA,CAAA,CAAA,KAAA,MAAyB,KAAK;EAC9B,OACE,KAAK,UAAU,CAAC,CAGhB,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
1
1
|
import { JSONValue, ToolSet } from "ai";
|
|
2
|
+
import { Workspace } from "@cloudflare/computer";
|
|
3
|
+
import { CreateAIToolsOptions } from "@cloudflare/computer/tools/ai-sdk";
|
|
2
4
|
|
|
5
|
+
//#region src/workspace-files.d.ts
|
|
6
|
+
/**
|
|
7
|
+
* The filesystem methods Think uses, from `@cloudflare/computer`'s
|
|
8
|
+
* `workspace.fs`.
|
|
9
|
+
*/
|
|
10
|
+
type ThinkWorkspaceFilesystem = Pick<
|
|
11
|
+
Workspace["fs"],
|
|
12
|
+
| "readFile"
|
|
13
|
+
| "writeFile"
|
|
14
|
+
| "mkdir"
|
|
15
|
+
| "rm"
|
|
16
|
+
| "stat"
|
|
17
|
+
| "readdir"
|
|
18
|
+
| "find"
|
|
19
|
+
| "grep"
|
|
20
|
+
>;
|
|
21
|
+
/** The parts of a Workspace the `@cloudflare/computer` tools use besides `fs`. */
|
|
22
|
+
type ToolsWorkspace = CreateAIToolsOptions["workspace"];
|
|
23
|
+
/**
|
|
24
|
+
* The Workspace a Think agent works in.
|
|
25
|
+
*
|
|
26
|
+
* A `Workspace` from `@cloudflare/computer` satisfies this, and so does the
|
|
27
|
+
* client `getWorkspace(stub)` returns for a Workspace owned by another
|
|
28
|
+
* Durable Object. Think reads and writes through `workspace.fs`. The
|
|
29
|
+
* `@cloudflare/computer` tools also use `runtime` for `exec` and `assets`
|
|
30
|
+
* for `publish` when the Workspace has them.
|
|
31
|
+
*
|
|
32
|
+
* @experimental The API surface may change before stabilizing.
|
|
33
|
+
*/
|
|
34
|
+
type ThinkWorkspace = {
|
|
35
|
+
/** The Workspace filesystem. */ readonly fs: ThinkWorkspaceFilesystem;
|
|
36
|
+
} & Partial<Pick<ToolsWorkspace, "runtime" | "sessionId" | "assets">>;
|
|
37
|
+
//#endregion
|
|
3
38
|
//#region src/tools/fetch.d.ts
|
|
4
39
|
type FetchResponseMode = "text" | "json" | "auto" | "workspace";
|
|
5
40
|
type FetchRedirectPolicy = "allowlisted" | "same-origin" | "none";
|
|
@@ -44,21 +79,6 @@ interface FetchToolEvent {
|
|
|
44
79
|
response?: FetchResponseMode;
|
|
45
80
|
code?: FetchErrorCode;
|
|
46
81
|
}
|
|
47
|
-
/**
|
|
48
|
-
* Minimal workspace surface the fetch tool needs to spill large/binary
|
|
49
|
-
* responses to a file. A concrete `Workspace` from `@cloudflare/shell`
|
|
50
|
-
* satisfies this.
|
|
51
|
-
*/
|
|
52
|
-
interface FetchWorkspace {
|
|
53
|
-
writeFile(path: string, content: string): Promise<void> | void;
|
|
54
|
-
writeFileBytes?(path: string, content: Uint8Array): Promise<void> | void;
|
|
55
|
-
mkdir(
|
|
56
|
-
path: string,
|
|
57
|
-
opts?: {
|
|
58
|
-
recursive?: boolean;
|
|
59
|
-
}
|
|
60
|
-
): Promise<void> | void;
|
|
61
|
-
}
|
|
62
82
|
interface FetchBindingTarget {
|
|
63
83
|
/** The service binding / Fetcher requests are routed through. */
|
|
64
84
|
binding: Fetcher;
|
|
@@ -94,7 +114,7 @@ interface CreateFetchToolsOptions {
|
|
|
94
114
|
/** Allow large/binary bodies to spill to a workspace file. Default false. */
|
|
95
115
|
spillToWorkspace?: boolean;
|
|
96
116
|
/** Workspace used for `response: "workspace"` / spill. */
|
|
97
|
-
workspace?:
|
|
117
|
+
workspace?: ThinkWorkspace;
|
|
98
118
|
/** Per-request timeout in ms. Default 10_000. */
|
|
99
119
|
timeoutMs?: number;
|
|
100
120
|
/** Default response handling. Default `"auto"`. */
|
|
@@ -135,13 +155,14 @@ declare function createFetchTools(options: CreateFetchToolsOptions): ToolSet;
|
|
|
135
155
|
//#endregion
|
|
136
156
|
export {
|
|
137
157
|
FetchResponseMode as a,
|
|
138
|
-
|
|
158
|
+
createFetchTools as c,
|
|
139
159
|
FetchRedirectPolicy as i,
|
|
140
|
-
|
|
160
|
+
ThinkWorkspace as l,
|
|
141
161
|
FetchBindingTarget as n,
|
|
142
162
|
FetchResult as o,
|
|
143
163
|
FetchErrorCode as r,
|
|
144
164
|
FetchToolEvent as s,
|
|
145
|
-
CreateFetchToolsOptions as t
|
|
165
|
+
CreateFetchToolsOptions as t,
|
|
166
|
+
ThinkWorkspaceFilesystem as u
|
|
146
167
|
};
|
|
147
|
-
//# sourceMappingURL=fetch-
|
|
168
|
+
//# sourceMappingURL=fetch-CU2fC7O6.d.ts.map
|