@cloudflare/think 0.21.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 +71 -120
- package/dist/extensions/index.d.ts +4 -14
- package/dist/extensions/index.js +1 -14
- package/dist/extensions/index.js.map +1 -1
- package/dist/{fetch-C7s1mpgg.d.ts → fetch-CU2fC7O6.d.ts} +1 -30
- package/dist/{fetch-9f1p8UrI.js → fetch-DO3uQ9py.js} +2 -47
- package/dist/fetch-DO3uQ9py.js.map +1 -0
- package/dist/{index-Cjq_e9F2.d.ts → index-DDnny6kt.d.ts} +189 -73
- package/dist/{manager-dOcdCX4u.d.ts → manager-rze95KCk.d.ts} +1 -2
- package/dist/messengers/index.d.ts +1 -1
- package/dist/messengers/telegram.d.ts +1 -1
- package/dist/rolldown-runtime-D7D4PA-g.js +13 -0
- package/dist/think.d.ts +3 -3
- package/dist/think.js +85 -72
- package/dist/think.js.map +1 -1
- package/dist/tools/extensions.d.ts +1 -1
- package/dist/tools/fetch.d.ts +1 -1
- package/dist/tools/fetch.js +1 -1
- package/dist/workflows.d.ts +1 -1
- package/docs/channels.md +1 -5
- package/docs/getting-started.md +1 -1
- package/docs/index.md +98 -94
- package/docs/lifecycle-hooks.md +14 -16
- package/docs/multi-chat.md +12 -13
- package/docs/tools.md +2 -19
- package/package.json +7 -8
- package/dist/fetch-9f1p8UrI.js.map +0 -1
package/README.md
CHANGED
|
@@ -228,129 +228,84 @@ import { getWeather } from "ws:tools";
|
|
|
228
228
|
export default async () => (await getWeather({ city: "Lisbon" })).text;
|
|
229
229
|
```
|
|
230
230
|
|
|
231
|
-
|
|
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.
|
|
231
|
+
Every Think agent can hand out its own Workspace: `getWorkspace(stub)` from
|
|
232
|
+
`@cloudflare/computer` calls the agent's `__getWorkspaceStub()` over RPC.
|
|
244
233
|
|
|
245
234
|
## Agent Skills
|
|
246
235
|
|
|
247
|
-
Think supports
|
|
248
|
-
a
|
|
249
|
-
|
|
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
|
|
250
239
|
`read_skill_resource` tools when skills are available.
|
|
251
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
|
+
|
|
252
245
|
```ts
|
|
253
246
|
import { Think, skills } from "@cloudflare/think";
|
|
254
|
-
import bundledSkills from "agents:skills"; // resolves to ./skills next to this file
|
|
255
247
|
|
|
256
248
|
export class MyAgent extends Think<Env> {
|
|
257
249
|
getSkills() {
|
|
258
250
|
return [
|
|
259
|
-
|
|
251
|
+
skills.workspace(this.workspace),
|
|
260
252
|
skills.r2(this.env.SKILLS_BUCKET, { prefix: "skills/" })
|
|
261
253
|
];
|
|
262
254
|
}
|
|
263
|
-
|
|
264
|
-
getSkillScriptRunner() {
|
|
265
|
-
return skills.runner({
|
|
266
|
-
loader: this.env.LOADER,
|
|
267
|
-
workspaceInstance: this.workspace
|
|
268
|
-
});
|
|
269
|
-
}
|
|
270
255
|
}
|
|
271
256
|
```
|
|
272
257
|
|
|
273
|
-
Bundled skills use the Agents Vite plugin. Register it alongside the Cloudflare
|
|
274
|
-
plugin in `vite.config.ts`:
|
|
275
|
-
|
|
276
|
-
```ts
|
|
277
|
-
import { cloudflare } from "@cloudflare/vite-plugin";
|
|
278
|
-
import agents from "agents/vite";
|
|
279
|
-
import { defineConfig } from "vite";
|
|
280
|
-
|
|
281
|
-
export default defineConfig({
|
|
282
|
-
plugins: [agents(), cloudflare()]
|
|
283
|
-
});
|
|
284
|
-
```
|
|
285
|
-
|
|
286
|
-
The `agents:skills` specifier resolves to a `./skills` directory next to the
|
|
287
|
-
importing file; use `agents:skills/<dir>` for a differently named sibling
|
|
288
|
-
directory:
|
|
289
|
-
|
|
290
|
-
```ts
|
|
291
|
-
import bundledSkills from "agents:skills";
|
|
292
|
-
```
|
|
293
|
-
|
|
294
|
-
The import is typed by ambient declarations shipped with `agents` (importing
|
|
295
|
-
`Think`, which pulls in `agents`, is enough; otherwise add
|
|
296
|
-
`/// <reference types="agents/skills-module" />`). Without the Vite plugin,
|
|
297
|
-
construct a source with `skills.fromManifest(...)`. Sources are applied in
|
|
298
|
-
order: the first to register a skill name wins, and duplicate or failing
|
|
299
|
-
sources are skipped with a warning instead of failing the agent.
|
|
300
|
-
|
|
301
|
-
The skills engine itself lives in `agents/skills` (so any agent, including a
|
|
302
|
-
plain `@cloudflare/ai-chat` `onChatMessage`, can build a `SkillRegistry`);
|
|
303
|
-
`@cloudflare/think` re-exports it as `skills` and wires `getSkills()` into the
|
|
304
|
-
turn automatically.
|
|
305
|
-
|
|
306
|
-
Think can also project each resolved `SKILL.md` into the active workspace so
|
|
307
|
-
the agent can read and edit skills as files. This is off by default: skills
|
|
308
|
-
load from their sources and nothing is written to the Workspace. Skills land
|
|
309
|
-
under `/workspace/.agents/skills`. Existing
|
|
310
|
-
workspace edits are preserved and affect later activation. Resources copy into
|
|
311
|
-
the workspace on first use rather than at startup. Think records a durable
|
|
312
|
-
source fingerprint, so unchanged cold wakes do not stat or rewrite every skill
|
|
313
|
-
file.
|
|
314
|
-
|
|
315
|
-
Enable projection, or override its path, with:
|
|
316
|
-
|
|
317
|
-
```ts
|
|
318
|
-
skillWorkspace = {};
|
|
319
|
-
// or, for a custom Computer proxy that presents legacy direct methods:
|
|
320
|
-
skillWorkspace = { root: "/workspace/.agents/skills" };
|
|
321
|
-
```
|
|
322
|
-
|
|
323
|
-
The imported directory should contain one child directory per skill:
|
|
324
|
-
|
|
325
258
|
```text
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
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
|
|
329
262
|
```
|
|
330
263
|
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
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.
|
|
336
288
|
|
|
337
289
|
Skills are on-demand instructions, not always-on system prompt text. The model
|
|
338
290
|
sees the catalog first, then calls `activate_skill` when a user task matches a
|
|
339
291
|
skill description. Use a context block from `configureContext()` for behavior
|
|
340
292
|
that should apply to every turn, especially when the agent also uses skills.
|
|
341
|
-
`getSystemPrompt()`
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
enables `run_skill_script`, which can run JavaScript, TypeScript, Python, and
|
|
346
|
-
Bash scripts under `scripts/`.
|
|
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.
|
|
347
297
|
|
|
348
|
-
|
|
298
|
+
### Skill script runner
|
|
349
299
|
|
|
350
|
-
|
|
351
|
-
|
|
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.
|
|
352
306
|
|
|
353
|
-
|
|
307
|
+
```js
|
|
308
|
+
export default async function run(input, ctx) {
|
|
354
309
|
const guide = ctx.files["references/style-guide.md"]; // bundled text resources
|
|
355
310
|
const summary = await ctx.tools.call("summarize", { input }); // explicit tools
|
|
356
311
|
await ctx.output.writeFile("notes.md", summary); // scratch artifact
|
|
@@ -358,19 +313,19 @@ export default async function run(input: unknown, ctx: SkillRunContext) {
|
|
|
358
313
|
}
|
|
359
314
|
```
|
|
360
315
|
|
|
361
|
-
`ctx` is `{ skill, files, workspace, tools, output }
|
|
362
|
-
text resources by relative path, `ctx.workspace` is
|
|
363
|
-
permission, `ctx.tools` exposes only the tools the
|
|
364
|
-
`ctx.output.writeFile(name, content)` returns scratch
|
|
365
|
-
the workspace. Python and Bash scripts instead use
|
|
366
|
-
`/input.json`, `/context.json`, bundled resources under
|
|
367
|
-
for artifacts (Python supports both
|
|
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).
|
|
368
324
|
|
|
369
325
|
If `workspaceInstance` is provided, scripts get read-only workspace access by
|
|
370
326
|
default. Workspace writes, tools, and network access are opt-in. Scripts default
|
|
371
|
-
to a 30 second timeout, which can be overridden with `timeout`.
|
|
372
|
-
|
|
373
|
-
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`.
|
|
374
329
|
|
|
375
330
|
Script execution requires a Worker Loader binding:
|
|
376
331
|
|
|
@@ -384,7 +339,7 @@ Script execution requires a Worker Loader binding:
|
|
|
384
339
|
|
|
385
340
|
| Export | Description |
|
|
386
341
|
| --------------------------------------- | ------------------------------------------------------------- |
|
|
387
|
-
| `@cloudflare/think` | `Think`, `Session
|
|
342
|
+
| `@cloudflare/think` | `Think`, `Session` — main class + re-exports |
|
|
388
343
|
| `agents/sessions` | `Sessions`, `Session`, `createCompactFunction`, attachments |
|
|
389
344
|
| `agents/context` | `ContextBlocks`, providers, `ContextConfig` — prompt assembly |
|
|
390
345
|
| `@cloudflare/think/messengers` | Messenger contracts, Chat SDK bridge, state agent, delivery |
|
|
@@ -401,7 +356,7 @@ Script execution requires a Worker Loader binding:
|
|
|
401
356
|
| Method / Property | Default | Description |
|
|
402
357
|
| -------------------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
403
358
|
| `getModel()` | throws | Return the `LanguageModel` to use |
|
|
404
|
-
| `getSystemPrompt()` | careful assistant operating prompt |
|
|
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 |
|
|
405
360
|
| `getTools()` | `{}` | AI SDK `ToolSet` for the agentic loop |
|
|
406
361
|
| `getMessengers()` | `{}` | Messenger ingress and delivery declarations |
|
|
407
362
|
| `getScheduledTasks()` | `{}` | Code-declared recurring prompts |
|
|
@@ -415,7 +370,6 @@ Script execution requires a Worker Loader binding:
|
|
|
415
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 |
|
|
416
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 |
|
|
417
372
|
| `getSkills()` | `[]` | First-class Agent Skills sources |
|
|
418
|
-
| `skillWorkspace` | `false` | Project skills into the Workspace as files; `{}` enables with defaults |
|
|
419
373
|
| `getSkillScriptRunner()` | `null` | Optional runner for `run_skill_script` |
|
|
420
374
|
| `getExtensions()` | `[]` | Sandboxed extension declarations (load order) |
|
|
421
375
|
| `extensionLoader` | `undefined` | `WorkerLoader` binding — enables extensions |
|
|
@@ -725,9 +679,7 @@ Extensions can subscribe to `beforeTurn`, `beforeToolCall`, `afterToolCall`, `on
|
|
|
725
679
|
```js
|
|
726
680
|
// extension source (loaded via getExtensions())
|
|
727
681
|
({
|
|
728
|
-
tools: {
|
|
729
|
-
/* ... */
|
|
730
|
-
},
|
|
682
|
+
tools: {/* ... */},
|
|
731
683
|
hooks: {
|
|
732
684
|
beforeToolCall: async (snapshot, host) => {
|
|
733
685
|
/* observation */
|
|
@@ -1159,15 +1111,14 @@ getTools() {
|
|
|
1159
1111
|
|
|
1160
1112
|
## Runtime dependencies
|
|
1161
1113
|
|
|
1162
|
-
| Package
|
|
1163
|
-
|
|
|
1164
|
-
| `agents`
|
|
1165
|
-
| `ai`
|
|
1166
|
-
| `zod`
|
|
1167
|
-
| `@cloudflare/computer`
|
|
1168
|
-
| `@cloudflare/codemode`
|
|
1169
|
-
| `@
|
|
1170
|
-
| `@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 |
|
|
1171
1122
|
|
|
1172
1123
|
## Acknowledgments
|
|
1173
1124
|
|
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
o as ExtensionToolDescriptor,
|
|
6
6
|
r as ExtensionInfo,
|
|
7
7
|
t as ExtensionManager
|
|
8
|
-
} from "../manager-
|
|
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()
|
|
58
|
-
*
|
|
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" | "
|
|
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,
|
package/dist/extensions/index.js
CHANGED
|
@@ -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,
|
|
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,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;CAE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K,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,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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B,qBACd,OACA,MACA,YACA;CACA,QAAQ,MAAR;EACE,KAAK,YACH,OAAO,IAAI,wBAAwB,OAAO,UAAU;EAGtD,SACE,OAAO,IAAI,uBAAuB,OAAO,UAAU;CACvD;AACF"}
|
|
@@ -34,34 +34,6 @@ type ToolsWorkspace = CreateAIToolsOptions["workspace"];
|
|
|
34
34
|
type ThinkWorkspace = {
|
|
35
35
|
/** The Workspace filesystem. */ readonly fs: ThinkWorkspaceFilesystem;
|
|
36
36
|
} & Partial<Pick<ToolsWorkspace, "runtime" | "sessionId" | "assets">>;
|
|
37
|
-
/**
|
|
38
|
-
* A {@link ThinkWorkspace} that resolves the real Workspace on first use.
|
|
39
|
-
*
|
|
40
|
-
* Use it for a Workspace another Durable Object owns, so the agent does not
|
|
41
|
-
* reach the owner until a turn actually touches a file:
|
|
42
|
-
*
|
|
43
|
-
* ```ts
|
|
44
|
-
* import { getWorkspace } from "@cloudflare/computer";
|
|
45
|
-
*
|
|
46
|
-
* override workspace = lazyWorkspace(async () =>
|
|
47
|
-
* getWorkspace(await this.parentAgent(Directory))
|
|
48
|
-
* );
|
|
49
|
-
* ```
|
|
50
|
-
*
|
|
51
|
-
* The resolved Workspace is kept and reused. A failed resolution is not
|
|
52
|
-
* kept, so the next operation tries again. To start over with a new client,
|
|
53
|
-
* for example after disposing the old one, assign a new `lazyWorkspace`.
|
|
54
|
-
*
|
|
55
|
-
* Only `fs` is forwarded, so the agent gets the file tools but no `exec`:
|
|
56
|
-
* the exec tool lists the Workspace's backends synchronously, before
|
|
57
|
-
* anything has been resolved.
|
|
58
|
-
*
|
|
59
|
-
* @param resolve - Produces the Workspace.
|
|
60
|
-
* @returns A Workspace whose `fs` forwards to the resolved one.
|
|
61
|
-
*/
|
|
62
|
-
declare function lazyWorkspace(
|
|
63
|
-
resolve: () => Promise<ThinkWorkspace>
|
|
64
|
-
): ThinkWorkspace;
|
|
65
37
|
//#endregion
|
|
66
38
|
//#region src/tools/fetch.d.ts
|
|
67
39
|
type FetchResponseMode = "text" | "json" | "auto" | "workspace";
|
|
@@ -184,7 +156,6 @@ declare function createFetchTools(options: CreateFetchToolsOptions): ToolSet;
|
|
|
184
156
|
export {
|
|
185
157
|
FetchResponseMode as a,
|
|
186
158
|
createFetchTools as c,
|
|
187
|
-
lazyWorkspace as d,
|
|
188
159
|
FetchRedirectPolicy as i,
|
|
189
160
|
ThinkWorkspace as l,
|
|
190
161
|
FetchBindingTarget as n,
|
|
@@ -194,4 +165,4 @@ export {
|
|
|
194
165
|
CreateFetchToolsOptions as t,
|
|
195
166
|
ThinkWorkspaceFilesystem as u
|
|
196
167
|
};
|
|
197
|
-
//# sourceMappingURL=fetch-
|
|
168
|
+
//# sourceMappingURL=fetch-CU2fC7O6.d.ts.map
|
|
@@ -127,51 +127,6 @@ function parentDirectory(path) {
|
|
|
127
127
|
function joinPath(directory, name) {
|
|
128
128
|
return directory.endsWith("/") ? `${directory}${name}` : `${directory}/${name}`;
|
|
129
129
|
}
|
|
130
|
-
/**
|
|
131
|
-
* A {@link ThinkWorkspace} that resolves the real Workspace on first use.
|
|
132
|
-
*
|
|
133
|
-
* Use it for a Workspace another Durable Object owns, so the agent does not
|
|
134
|
-
* reach the owner until a turn actually touches a file:
|
|
135
|
-
*
|
|
136
|
-
* ```ts
|
|
137
|
-
* import { getWorkspace } from "@cloudflare/computer";
|
|
138
|
-
*
|
|
139
|
-
* override workspace = lazyWorkspace(async () =>
|
|
140
|
-
* getWorkspace(await this.parentAgent(Directory))
|
|
141
|
-
* );
|
|
142
|
-
* ```
|
|
143
|
-
*
|
|
144
|
-
* The resolved Workspace is kept and reused. A failed resolution is not
|
|
145
|
-
* kept, so the next operation tries again. To start over with a new client,
|
|
146
|
-
* for example after disposing the old one, assign a new `lazyWorkspace`.
|
|
147
|
-
*
|
|
148
|
-
* Only `fs` is forwarded, so the agent gets the file tools but no `exec`:
|
|
149
|
-
* the exec tool lists the Workspace's backends synchronously, before
|
|
150
|
-
* anything has been resolved.
|
|
151
|
-
*
|
|
152
|
-
* @param resolve - Produces the Workspace.
|
|
153
|
-
* @returns A Workspace whose `fs` forwards to the resolved one.
|
|
154
|
-
*/
|
|
155
|
-
function lazyWorkspace(resolve) {
|
|
156
|
-
let resolved;
|
|
157
|
-
const fs = async () => {
|
|
158
|
-
resolved ??= resolve().catch((error) => {
|
|
159
|
-
resolved = void 0;
|
|
160
|
-
throw error;
|
|
161
|
-
});
|
|
162
|
-
return (await resolved).fs;
|
|
163
|
-
};
|
|
164
|
-
return { fs: {
|
|
165
|
-
readFile: async (...args) => (await fs()).readFile(...args),
|
|
166
|
-
writeFile: async (...args) => (await fs()).writeFile(...args),
|
|
167
|
-
mkdir: async (...args) => (await fs()).mkdir(...args),
|
|
168
|
-
rm: async (...args) => (await fs()).rm(...args),
|
|
169
|
-
stat: async (...args) => (await fs()).stat(...args),
|
|
170
|
-
readdir: async (...args) => (await fs()).readdir(...args),
|
|
171
|
-
find: async (...args) => (await fs()).find(...args),
|
|
172
|
-
grep: async (...args) => (await fs()).grep(...args)
|
|
173
|
-
} };
|
|
174
|
-
}
|
|
175
130
|
//#endregion
|
|
176
131
|
//#region src/tools/fetch.ts
|
|
177
132
|
const DEFAULT_MAX_BYTES = 1e6;
|
|
@@ -767,6 +722,6 @@ function toModelOutput(output) {
|
|
|
767
722
|
};
|
|
768
723
|
}
|
|
769
724
|
//#endregion
|
|
770
|
-
export {
|
|
725
|
+
export { WorkspaceFiles as n, resolveWorkspacePath as r, createFetchTools as t };
|
|
771
726
|
|
|
772
|
-
//# sourceMappingURL=fetch-
|
|
727
|
+
//# sourceMappingURL=fetch-DO3uQ9py.js.map
|