@cloudflare/think 0.22.0 → 0.23.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
@@ -233,113 +233,79 @@ Every Think agent can hand out its own Workspace: `getWorkspace(stub)` from
233
233
 
234
234
  ## Agent Skills
235
235
 
236
- Think supports the [Agent Skills](https://agentskills.io/) directory format as
237
- a first-class API. Return one or more `SkillSource` objects from `getSkills()`;
238
- Think adds the skill catalog to the prompt and exposes `activate_skill` and
236
+ Think supports [Agent Skills](https://agentskills.io/). A skill is a directory
237
+ with a `SKILL.md` file. Return skill sources from `getSkills()`; Think adds the
238
+ skill catalog to the prompt and exposes `activate_skill` and
239
239
  `read_skill_resource` tools when skills are available.
240
240
 
241
+ Keep skills as files in the agent's Workspace. Every
242
+ `/workspace/.agents/skills/<name>/SKILL.md` is a skill, and the files beside it
243
+ are its resources:
244
+
241
245
  ```ts
242
246
  import { Think, skills } from "@cloudflare/think";
243
- import bundledSkills from "agents:skills"; // resolves to ./skills next to this file
244
247
 
245
248
  export class MyAgent extends Think<Env> {
246
249
  getSkills() {
247
250
  return [
248
- bundledSkills,
251
+ skills.workspace(this.workspace),
249
252
  skills.r2(this.env.SKILLS_BUCKET, { prefix: "skills/" })
250
253
  ];
251
254
  }
252
-
253
- getSkillScriptRunner() {
254
- return skills.runner({
255
- loader: this.env.LOADER,
256
- workspaceInstance: this.workspace
257
- });
258
- }
259
255
  }
260
256
  ```
261
257
 
262
- Bundled skills use the Agents Vite plugin. Register it alongside the Cloudflare
263
- plugin in `vite.config.ts`:
264
-
265
- ```ts
266
- import { cloudflare } from "@cloudflare/vite-plugin";
267
- import agents from "agents/vite";
268
- import { defineConfig } from "vite";
269
-
270
- export default defineConfig({
271
- plugins: [agents(), cloudflare()]
272
- });
273
- ```
274
-
275
- The `agents:skills` specifier resolves to a `./skills` directory next to the
276
- importing file; use `agents:skills/<dir>` for a differently named sibling
277
- directory:
278
-
279
- ```ts
280
- import bundledSkills from "agents:skills";
281
- ```
282
-
283
- The import is typed by ambient declarations shipped with `agents` (importing
284
- `Think`, which pulls in `agents`, is enough; otherwise add
285
- `/// <reference types="agents/skills-module" />`). Without the Vite plugin,
286
- construct a source with `skills.fromManifest(...)`. Sources are applied in
287
- order: the first to register a skill name wins, and duplicate or failing
288
- sources are skipped with a warning instead of failing the agent.
289
-
290
- The skills engine itself lives in `agents/skills` (so any agent, including a
291
- plain `@cloudflare/ai-chat` `onChatMessage`, can build a `SkillRegistry`);
292
- `@cloudflare/think` re-exports it as `skills` and wires `getSkills()` into the
293
- turn automatically.
294
-
295
- Think can also project each resolved `SKILL.md` into the active workspace so
296
- the agent can read and edit skills as files. This is off by default: skills
297
- load from their sources and nothing is written to the Workspace. Skills land
298
- under `/workspace/.agents/skills`. Existing
299
- workspace edits are preserved and affect later activation. Resources copy into
300
- the workspace on first use rather than at startup. Think records a durable
301
- source fingerprint, so unchanged cold wakes do not stat or rewrite every skill
302
- file.
303
-
304
- Enable projection, or override its path, with:
305
-
306
- ```ts
307
- skillWorkspace = {};
308
- // or, for a custom Computer proxy that presents legacy direct methods:
309
- skillWorkspace = { root: "/workspace/.agents/skills" };
310
- ```
311
-
312
- The imported directory should contain one child directory per skill:
313
-
314
258
  ```text
315
- src/skills/release-notes/SKILL.md
316
- src/skills/release-notes/scripts/format-release-notes.ts
317
- src/skills/release-notes/references/style-guide.md
259
+ /workspace/.agents/skills/release-notes/SKILL.md
260
+ /workspace/.agents/skills/release-notes/scripts/format-release-notes.js
261
+ /workspace/.agents/skills/release-notes/references/style-guide.md
318
262
  ```
319
263
 
320
- Bundled resources are packaged with explicit `encoding` metadata. Text resources
321
- are returned directly; binary assets are returned as base64. `read_skill_resource`
322
- can read `{ name, path }` or a qualified path such as
323
- `release-notes/references/style-guide.md`, which helps skills reference resources
324
- from other skills.
264
+ Sources are listed again before every turn, so a skill written, edited, or
265
+ deleted in the Workspace takes effect on the next turn. `skills.r2()` reads the
266
+ same layout from a bucket, and `skills.manifest(...)` defines skills in
267
+ code. Sources are applied in order: the first to provide a skill name wins, and
268
+ duplicate or failing sources are skipped with a logged warning.
269
+
270
+ Each `SKILL.md` is checked against the
271
+ [spec](https://agentskills.io/specification) and loaded the way the spec's
272
+ guide for agents recommends: a skill whose `name` breaks the format or does
273
+ not match its directory still loads, with a logged warning. Skills with no
274
+ `description` or unreadable frontmatter are skipped and logged. To check a
275
+ skill before writing it, parse it with `skills.parseSkill()` and require
276
+ `warnings` to be empty. Unknown frontmatter keys are kept in
277
+ `skill.extraFields`.
278
+
279
+ Text resources are returned directly; binary assets are returned as base64.
280
+ `read_skill_resource` accepts `{ name, path }` or a qualified path such as
281
+ `release-notes/references/style-guide.md`. Skills from a Workspace also report
282
+ their directory, so a model with the Workspace `exec` tool can run their
283
+ scripts in place.
284
+
285
+ The parser, sources, and catalog live in `agents/skills` and work without
286
+ Think; `@cloudflare/think` re-exports the module as `skills` and wires
287
+ `getSkills()` into the turn.
325
288
 
326
289
  Skills are on-demand instructions, not always-on system prompt text. The model
327
290
  sees the catalog first, then calls `activate_skill` when a user task matches a
328
291
  skill description. Use a context block from `configureContext()` for behavior
329
292
  that should apply to every turn, especially when the agent also uses skills.
330
- `getSystemPrompt()` is a legacy fallback and is ignored once context blocks are
331
- configured.
293
+ An overridden `getSystemPrompt()` stays at the top of the system prompt, above
294
+ the context blocks and the skills catalog. When skills change mid-conversation,
295
+ the frozen system prompt stays the same; the new catalog reaches the model as a
296
+ reminder until the next compaction or history clear.
332
297
 
333
- Script execution is opt-in and **experimental**. `getSkillScriptRunner()`
334
- enables `run_skill_script`, which can run JavaScript, TypeScript, Python, and
335
- Bash scripts under `scripts/`.
298
+ ### Skill script runner
336
299
 
337
- JavaScript and TypeScript scripts are function-style:
300
+ For skills outside a Workspace (for example in R2), `getSkillScriptRunner()`
301
+ enables `run_skill_script`. It is **experimental**; prefer keeping skills in a
302
+ Workspace and running scripts with `exec`. The runner runs JavaScript, Python,
303
+ and Bash scripts under `scripts/`. A JavaScript script must be one
304
+ self-contained module; compile TypeScript or multi-file scripts before storing
305
+ the skill.
338
306
 
339
- ```ts
340
- import type { SkillRunContext } from "@cloudflare/think";
341
-
342
- export default async function run(input: unknown, ctx: SkillRunContext) {
307
+ ```js
308
+ export default async function run(input, ctx) {
343
309
  const guide = ctx.files["references/style-guide.md"]; // bundled text resources
344
310
  const summary = await ctx.tools.call("summarize", { input }); // explicit tools
345
311
  await ctx.output.writeFile("notes.md", summary); // scratch artifact
@@ -347,19 +313,19 @@ export default async function run(input: unknown, ctx: SkillRunContext) {
347
313
  }
348
314
  ```
349
315
 
350
- `ctx` is `{ skill, files, workspace, tools, output }`: `ctx.files` holds bundled
351
- text resources by relative path, `ctx.workspace` is gated by the workspace
352
- permission, `ctx.tools` exposes only the tools the runner was given, and
353
- `ctx.output.writeFile(name, content)` returns scratch artifacts without mutating
354
- the workspace. Python and Bash scripts instead use the path-based contract:
355
- `/input.json`, `/context.json`, bundled resources under `/skill`, and `/output`
356
- for artifacts (Python supports both `def run(input, ctx)` and CLI-style scripts).
316
+ `ctx` is `{ skill, files, workspace, tools, output }` (`SkillRunContext`):
317
+ `ctx.files` holds bundled text resources by relative path, `ctx.workspace` is
318
+ gated by the workspace permission, `ctx.tools` exposes only the tools the
319
+ runner was given, and `ctx.output.writeFile(name, content)` returns scratch
320
+ artifacts without mutating the workspace. Python and Bash scripts instead use
321
+ the path-based contract: `/input.json`, `/context.json`, bundled resources under
322
+ `/skill`, and `/output` for artifacts (Python supports both
323
+ `def run(input, ctx)` and CLI-style scripts).
357
324
 
358
325
  If `workspaceInstance` is provided, scripts get read-only workspace access by
359
326
  default. Workspace writes, tools, and network access are opt-in. Scripts default
360
- to a 30 second timeout, which can be overridden with `timeout`. TypeScript
361
- scripts are compiled with `@cloudflare/worker-bundler`; Python scripts run as
362
- Python Dynamic Workers; Bash scripts run through `just-bash`.
327
+ to a 30 second timeout, which can be overridden with `timeout`. Python scripts
328
+ run as Python Dynamic Workers; Bash scripts run through `just-bash`.
363
329
 
364
330
  Script execution requires a Worker Loader binding:
365
331
 
@@ -390,7 +356,7 @@ Script execution requires a Worker Loader binding:
390
356
  | Method / Property | Default | Description |
391
357
  | -------------------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
392
358
  | `getModel()` | throws | Return the `LanguageModel` to use |
393
- | `getSystemPrompt()` | careful assistant operating prompt | Legacy system prompt fallback used only when no Session context blocks are configured |
359
+ | `getSystemPrompt()` | careful assistant operating prompt | Instructions at the top of the system prompt, above context blocks. The default is used only with no context blocks |
394
360
  | `getTools()` | `{}` | AI SDK `ToolSet` for the agentic loop |
395
361
  | `getMessengers()` | `{}` | Messenger ingress and delivery declarations |
396
362
  | `getScheduledTasks()` | `{}` | Code-declared recurring prompts |
@@ -404,7 +370,6 @@ Script execution requires a Worker Loader binding:
404
370
  | `hydrationByteBudget` | 32 MiB | Byte budget for startup transcript hydration. Charges each row its full stored size, including the continuation rows a large message is split across |
405
371
  | `mediaEviction` | `true` | Media eviction policy: aged media leaves the conversation and is preserved as a Workspace file. `false` keeps aged media in the conversation |
406
372
  | `getSkills()` | `[]` | First-class Agent Skills sources |
407
- | `skillWorkspace` | `false` | Project skills into the Workspace as files; `{}` enables with defaults |
408
373
  | `getSkillScriptRunner()` | `null` | Optional runner for `run_skill_script` |
409
374
  | `getExtensions()` | `[]` | Sandboxed extension declarations (load order) |
410
375
  | `extensionLoader` | `undefined` | `WorkerLoader` binding — enables extensions |
@@ -1146,15 +1111,14 @@ getTools() {
1146
1111
 
1147
1112
  ## Runtime dependencies
1148
1113
 
1149
- | Package | Notes |
1150
- | ---------------------------- | --------------------------------------------------------- |
1151
- | `agents` | Cloudflare Agents SDK peer dependency |
1152
- | `ai` | Vercel AI SDK v7 peer dependency |
1153
- | `zod` | Schema validation peer dependency |
1154
- | `@cloudflare/computer` | Workspace and workspace tools peer dependency |
1155
- | `@cloudflare/codemode` | Code execution, `createExecuteTool`, and JS skill scripts |
1156
- | `@cloudflare/worker-bundler` | TypeScript skill script compilation |
1157
- | `@chat-adapter/telegram` | Required for Telegram messengers |
1114
+ | Package | Notes |
1115
+ | ------------------------ | --------------------------------------------------------- |
1116
+ | `agents` | Cloudflare Agents SDK peer dependency |
1117
+ | `ai` | Vercel AI SDK v7 peer dependency |
1118
+ | `zod` | Schema validation peer dependency |
1119
+ | `@cloudflare/computer` | Workspace and workspace tools peer dependency |
1120
+ | `@cloudflare/codemode` | Code execution, `createExecuteTool`, and JS skill scripts |
1121
+ | `@chat-adapter/telegram` | Required for Telegram messengers |
1158
1122
 
1159
1123
  ## Acknowledgments
1160
1124
 
@@ -5,7 +5,7 @@ import {
5
5
  o as ExtensionToolDescriptor,
6
6
  r as ExtensionInfo,
7
7
  t as ExtensionManager
8
- } from "../manager-dOcdCX4u.js";
8
+ } from "../manager-rze95KCk.js";
9
9
  import { WorkerEntrypoint } from "cloudflare:workers";
10
10
 
11
11
  //#region src/extensions/host-bridge.d.ts
@@ -54,15 +54,14 @@ declare class HostBridgeLoopback extends WorkerEntrypoint<
54
54
  * ContextProvider / WritableContextProvider interfaces.
55
55
  *
56
56
  * When an extension declares context blocks in its manifest, Think creates
57
- * a bridge provider for each block. The bridge delegates `get()`, `load()`,
58
- * and `set()` to the extension Worker's entrypoint via RPC.
57
+ * a bridge provider for each block. The bridge delegates `get()` and
58
+ * `set()` to the extension Worker's entrypoint via RPC.
59
59
  *
60
60
  * This allows extensions to contribute context blocks to the Session's
61
61
  * system prompt without Session knowing about the extension system.
62
62
  */
63
63
  interface ExtensionContextEntrypoint {
64
64
  contextGet(label: string): Promise<string | null>;
65
- contextLoad?(label: string, key: string): Promise<string | null>;
66
65
  contextSet?(
67
66
  label: string,
68
67
  key: string,
@@ -88,20 +87,12 @@ declare class ExtensionContextBridge {
88
87
  declare class ExtensionWritableBridge extends ExtensionContextBridge {
89
88
  set(content: string): Promise<void>;
90
89
  }
91
- /**
92
- * A skill provider backed by an extension Worker.
93
- * Delegates `get()`, `load()`, and optionally `set()` to the extension's RPC methods.
94
- */
95
- declare class ExtensionSkillBridge extends ExtensionContextBridge {
96
- load(key: string): Promise<string | null>;
97
- set(key: string, content: string, description?: string): Promise<void>;
98
- }
99
90
  /**
100
91
  * Create the appropriate bridge provider based on the context block type.
101
92
  */
102
93
  declare function createBridgeProvider(
103
94
  label: string,
104
- type: "readonly" | "writable" | "skill" | "searchable",
95
+ type: "readonly" | "writable" | "searchable",
105
96
  entrypoint: ExtensionContextEntrypoint
106
97
  ): ExtensionContextBridge;
107
98
  //#endregion
@@ -112,7 +103,6 @@ export {
112
103
  type ExtensionManagerOptions,
113
104
  type ExtensionManifest,
114
105
  type ExtensionPermissions,
115
- ExtensionSkillBridge,
116
106
  type ExtensionToolDescriptor,
117
107
  ExtensionWritableBridge,
118
108
  HostBridgeLoopback,
@@ -122,28 +122,15 @@ var ExtensionWritableBridge = class extends ExtensionContextBridge {
122
122
  }
123
123
  };
124
124
  /**
125
- * A skill provider backed by an extension Worker.
126
- * Delegates `get()`, `load()`, and optionally `set()` to the extension's RPC methods.
127
- */
128
- var ExtensionSkillBridge = class extends ExtensionContextBridge {
129
- async load(key) {
130
- return await this._entrypoint.contextLoad?.(this._label, key) ?? null;
131
- }
132
- async set(key, content, description) {
133
- await this._entrypoint.contextSet?.(this._label, key, content, description);
134
- }
135
- };
136
- /**
137
125
  * Create the appropriate bridge provider based on the context block type.
138
126
  */
139
127
  function createBridgeProvider(label, type, entrypoint) {
140
128
  switch (type) {
141
- case "skill": return new ExtensionSkillBridge(label, entrypoint);
142
129
  case "writable": return new ExtensionWritableBridge(label, entrypoint);
143
130
  default: return new ExtensionContextBridge(label, entrypoint);
144
131
  }
145
132
  }
146
133
  //#endregion
147
- export { ExtensionContextBridge, ExtensionManager, ExtensionSkillBridge, ExtensionWritableBridge, HostBridgeLoopback, createBridgeProvider };
134
+ export { ExtensionContextBridge, ExtensionManager, ExtensionWritableBridge, HostBridgeLoopback, createBridgeProvider };
148
135
 
149
136
  //# sourceMappingURL=index.js.map
@@ -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,kBAAA,2BAAA,MAAA,iBAAA,CAAA,CAAA,KAAA,MAAuB,MAAM;EAC7B,OACE,KAAK,UAAU,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a,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()` and\n * `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 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 * Create the appropriate bridge provider based on the context block type.\n */\nexport function createBridgeProvider(\n label: string,\n type: \"readonly\" | \"writable\" | \"searchable\",\n entrypoint: ExtensionContextEntrypoint\n) {\n switch (type) {\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,MA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