@cloudflare/think 0.20.1 → 0.21.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 CHANGED
@@ -170,36 +170,78 @@ drill-in, and cleanup patterns.
170
170
 
171
171
  ## Built-in workspace
172
172
 
173
- 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.
174
-
175
- 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.
176
- The `bash` tool runs sandboxed shell workflows through `just-bash`, with network
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 — no setup needed
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
- Override to add R2 spillover for large files:
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
- sql: this.ctx.storage.sql,
197
- r2: this.env.R2,
198
- name: () => this.name
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
+ To work in a Workspace another Durable Object owns, use `lazyWorkspace`:
232
+
233
+ ```ts
234
+ import { getWorkspace } from "@cloudflare/computer";
235
+ import { lazyWorkspace } from "@cloudflare/think";
236
+
237
+ override workspace = lazyWorkspace(async () =>
238
+ getWorkspace(await this.parentAgent(Directory))
239
+ );
240
+ ```
241
+
242
+ Every Think agent can hand out its own Workspace the same way: `getWorkspace`
243
+ calls the agent's `__getWorkspaceStub()` over RPC.
244
+
203
245
  ## Agent Skills
204
246
 
205
247
  Think supports the [Agent Skills](https://agentskills.io/) directory format as
@@ -263,8 +305,8 @@ turn automatically.
263
305
 
264
306
  Think can also project each resolved `SKILL.md` into the active workspace so
265
307
  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. Computer uses
267
- `/workspace/.agents/skills`; legacy Shell uses `/.agents/skills`. Existing
308
+ load from their sources and nothing is written to the Workspace. Skills land
309
+ under `/workspace/.agents/skills`. Existing
268
310
  workspace edits are preserved and affect later activation. Resources copy into
269
311
  the workspace on first use rather than at startup. Think records a durable
270
312
  source fingerprint, so unchanged cold wakes do not stat or rewrite every skill
@@ -342,12 +384,11 @@ Script execution requires a Worker Loader binding:
342
384
 
343
385
  | Export | Description |
344
386
  | --------------------------------------- | ------------------------------------------------------------- |
345
- | `@cloudflare/think` | `Think`, `Session`, `Workspace` — main class + re-exports |
387
+ | `@cloudflare/think` | `Think`, `Session`, `lazyWorkspace` — main class + re-exports |
346
388
  | `agents/sessions` | `Sessions`, `Session`, `createCompactFunction`, attachments |
347
389
  | `agents/context` | `ContextBlocks`, providers, `ContextConfig` — prompt assembly |
348
390
  | `@cloudflare/think/messengers` | Messenger contracts, Chat SDK bridge, state agent, delivery |
349
391
  | `@cloudflare/think/messengers/telegram` | Telegram messenger provider and delivery helpers |
350
- | `@cloudflare/think/tools/workspace` | `createWorkspaceTools()` — for custom storage backends |
351
392
  | `@cloudflare/think/tools/fetch` | `createFetchTools()` — opt-in allowlisted HTTP reads |
352
393
  | `@cloudflare/think/tools/execute` | `createExecuteTool()` — sandboxed code execution via codemode |
353
394
  | `@cloudflare/think/tools/extensions` | `createExtensionTools()` — LLM-driven extension loading |
@@ -378,7 +419,6 @@ Script execution requires a Worker Loader binding:
378
419
  | `getSkillScriptRunner()` | `null` | Optional runner for `run_skill_script` |
379
420
  | `getExtensions()` | `[]` | Sandboxed extension declarations (load order) |
380
421
  | `extensionLoader` | `undefined` | `WorkerLoader` binding — enables extensions |
381
- | `workspaceBash` | `true` | Include the default workspace `bash` tool |
382
422
  | `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
423
  | `includeMcpTools` | `true` | Automatically convert connected MCP tools to AI SDK tools and merge them into model turns |
384
424
  | `waitForMcpConnections` | `false` | Wait for MCP connections to settle before inference |
@@ -855,8 +895,7 @@ Splitting never reclaims database space — the continuation rows live in the
855
895
  same Durable Object as the message — and Sessions imposes no upper bound on a
856
896
  single message, so one very large write can consume a meaningful share of the
857
897
  10 GB an object has. Bounding untrusted input is the application's job. Files
858
- belong in the Workspace, which spills to R2; put a reference to one in the
859
- message. This is a storage detail: invisible to the model, and unrelated to
898
+ 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
899
  media eviction.
861
900
 
862
901
  #### Media eviction
@@ -1017,30 +1056,22 @@ For values you want broadcast to connected clients, use `state` / `setState` fro
1017
1056
  - **Message sanitization** — strips ephemeral provider metadata before storage
1018
1057
  - **Row size enforcement** — compacts tool outputs exceeding 1.8MB
1019
1058
 
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
1059
  ## Code execution tool
1035
1060
 
1061
+ > **Deprecated.** Use `exec` with `ws:tools` (see [Built-in workspace](#built-in-workspace)).
1062
+
1036
1063
  Let the LLM write and run JavaScript in a sandboxed Worker:
1037
1064
 
1038
1065
  ```ts
1066
+ import { createAITools } from "@cloudflare/computer/tools/ai-sdk";
1039
1067
  import { createExecuteTool } from "@cloudflare/think/tools/execute";
1040
1068
 
1041
1069
  getTools() {
1042
1070
  return {
1043
- execute: createExecuteTool({ tools: wsTools, loader: this.env.LOADER })
1071
+ // tools.* in the sandbox includes the workspace tools
1072
+ execute: createExecuteTool(this, {
1073
+ tools: createAITools({ workspace: this.workspace })
1074
+ })
1044
1075
  };
1045
1076
  }
1046
1077
  ```
@@ -1133,10 +1164,9 @@ getTools() {
1133
1164
  | `agents` | Cloudflare Agents SDK peer dependency |
1134
1165
  | `ai` | Vercel AI SDK v6 peer dependency |
1135
1166
  | `zod` | Schema validation peer dependency |
1136
- | `@cloudflare/shell` | Workspace filesystem |
1167
+ | `@cloudflare/computer` | Workspace and workspace tools peer dependency |
1137
1168
  | `@cloudflare/codemode` | Code execution, `createExecuteTool`, and JS skill scripts |
1138
1169
  | `@cloudflare/worker-bundler` | TypeScript skill script compilation |
1139
- | `just-bash` | Bash skill script execution |
1140
1170
  | `@chat-adapter/telegram` | Required for Telegram messengers |
1141
1171
 
1142
1172
  ## 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 };
@@ -1,4 +1,5 @@
1
- import { a as _assertClassBrand, s as _classPrivateMethodInitSpec, t as ExtensionManager } from "../manager-Cb3DNZgp.js";
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,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R,6DACF;AAEJ;AAEA,SAAA,0BAAgC;CAC9B,IAAI,CAAC,KAAK,aAAa,SAAS,UAC9B,MAAM,IAAI,MACR,0DACF;AAEJ;;;;;;;AClFF,IAAa,yBAAb,MAAoC;CAIlC,YAAY,OAAe,YAAwC;EACjE,KAAK,SAAS;EACd,KAAK,cAAc;CACrB;CAEA,KAAK,QAAsB,CAAC;CAE5B,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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