@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 +69 -39
- package/dist/classPrivateFieldSet2-DwGJfC3w.js +27 -0
- package/dist/extensions/index.js +2 -1
- package/dist/extensions/index.js.map +1 -1
- package/dist/fetch-9f1p8UrI.js +772 -0
- package/dist/fetch-9f1p8UrI.js.map +1 -0
- package/dist/{fetch-By3eIQ-a.d.ts → fetch-C7s1mpgg.d.ts} +70 -20
- package/dist/{index-CmhSKa6U.d.ts → index-Cjq_e9F2.d.ts} +55 -75
- package/dist/{manager-Cb3DNZgp.js → manager-BubfmA3q.js} +3 -28
- package/dist/{manager-Cb3DNZgp.js.map → manager-BubfmA3q.js.map} +1 -1
- package/dist/messengers/index.d.ts +1 -1
- package/dist/messengers/telegram.d.ts +1 -1
- package/dist/think.d.ts +3 -4
- package/dist/think.js +79 -97
- package/dist/think.js.map +1 -1
- package/dist/tools/execute.d.ts +19 -24
- package/dist/tools/execute.js +20 -40
- package/dist/tools/execute.js.map +1 -1
- package/dist/tools/extensions.d.ts +1 -1
- package/dist/tools/extensions.js +2 -2
- package/dist/tools/extensions.js.map +1 -1
- package/dist/tools/fetch.d.ts +2 -4
- package/dist/tools/fetch.js +1 -645
- package/dist/workflows.d.ts +1 -1
- package/docs/getting-started.md +4 -4
- package/docs/index.md +31 -16
- package/docs/multi-chat.md +22 -59
- package/docs/sub-agents.md +13 -13
- package/docs/tools.md +90 -109
- package/package.json +7 -11
- package/dist/tools/fetch.js.map +0 -1
- package/dist/tools/workspace.d.ts +0 -60
- package/dist/tools/workspace.js +0 -869
- package/dist/tools/workspace.js.map +0 -1
- package/dist/workspace-CNeXc2vl.d.ts +0 -201
package/dist/tools/execute.d.ts
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
import { h as WorkspaceLike } from "../workspace-CNeXc2vl.js";
|
|
2
1
|
import { Tool, ToolSet } from "ai";
|
|
3
|
-
import { StateBackend } from "@cloudflare/shell";
|
|
4
2
|
import {
|
|
5
3
|
CodemodeConnector,
|
|
6
4
|
CodemodeRuntimeHandle,
|
|
@@ -18,7 +16,6 @@ import { BrowserBinding, BrowserConnectorSessionOptions } from "agents/browser";
|
|
|
18
16
|
* which would break structural assignability of `this`.)
|
|
19
17
|
*/
|
|
20
18
|
interface ExecuteToolAgent {
|
|
21
|
-
workspace?: WorkspaceLike;
|
|
22
19
|
/** Set by `createExecuteRuntime(agent)` so callables can reach the runtime. */
|
|
23
20
|
codemode?: CodemodeRuntimeHandle;
|
|
24
21
|
}
|
|
@@ -39,18 +36,6 @@ interface CreateExecuteToolOptions {
|
|
|
39
36
|
* provider-executed) are skipped — the sandbox can't call them.
|
|
40
37
|
*/
|
|
41
38
|
tools?: ToolSet;
|
|
42
|
-
/**
|
|
43
|
-
* StateBackend exposed as `state.*` inside the sandbox — the full
|
|
44
|
-
* filesystem API (readFile, writeFile, glob, searchFiles, replaceInFiles,
|
|
45
|
-
* planEdits, …). Every method takes a single object argument.
|
|
46
|
-
*
|
|
47
|
-
* @example
|
|
48
|
-
* ```ts
|
|
49
|
-
* import { createWorkspaceStateBackend } from "@cloudflare/shell";
|
|
50
|
-
* state: createWorkspaceStateBackend(this.workspace)
|
|
51
|
-
* ```
|
|
52
|
-
*/
|
|
53
|
-
state?: StateBackend;
|
|
54
39
|
/**
|
|
55
40
|
* Browser Rendering binding. When provided, the sandbox gets the `cdp.*`
|
|
56
41
|
* connector (cdp.send, cdp.attachToTarget, cdp.spec, …) — a live browser
|
|
@@ -65,7 +50,7 @@ interface CreateExecuteToolOptions {
|
|
|
65
50
|
*/
|
|
66
51
|
session?: BrowserConnectorSessionOptions;
|
|
67
52
|
/**
|
|
68
|
-
* Additional connectors for the sandbox beyond `tools
|
|
53
|
+
* Additional connectors for the sandbox beyond `tools` and `cdp`.
|
|
69
54
|
* Each adds its own named namespace.
|
|
70
55
|
*/
|
|
71
56
|
connectors?: CodemodeConnector[];
|
|
@@ -97,7 +82,7 @@ interface CreateExecuteToolOptions {
|
|
|
97
82
|
/**
|
|
98
83
|
* Custom tool description. Replaces the generated default entirely — the
|
|
99
84
|
* default explains the codemode workflow and lists each configured
|
|
100
|
-
* namespace (`tools.*`, `
|
|
85
|
+
* namespace (`tools.*`, `cdp.*`) with a usage hint.
|
|
101
86
|
*/
|
|
102
87
|
description?: string;
|
|
103
88
|
/**
|
|
@@ -132,6 +117,12 @@ interface ExecuteRuntime {
|
|
|
132
117
|
* When called with an agent, the runtime handle is also assigned to
|
|
133
118
|
* `agent.codemode` so callables (and Think's built-in approval flow) can
|
|
134
119
|
* reach it.
|
|
120
|
+
*
|
|
121
|
+
* @deprecated Code execution is moving to the Workspace: give it a
|
|
122
|
+
* JavaScript backend with a `ws:tools` module
|
|
123
|
+
* (`createToolBindings(forAISDKTools(() => this.getTools()))` from
|
|
124
|
+
* `@cloudflare/computer`), so code the model runs with `exec` imports the
|
|
125
|
+
* agent's tools and reads files through `node:fs`.
|
|
135
126
|
*/
|
|
136
127
|
declare function createExecuteRuntime(
|
|
137
128
|
source: CreateExecuteToolOptions | ExecuteToolAgent,
|
|
@@ -146,13 +137,12 @@ declare function createExecuteRuntime(
|
|
|
146
137
|
declare function truncatePausedExecutionOutput(output: unknown): unknown;
|
|
147
138
|
/**
|
|
148
139
|
* Create a code execution tool that lets the LLM write and run TypeScript
|
|
149
|
-
* against your tools
|
|
150
|
-
* browser — all inside a sandboxed Worker, recorded on a durable codemode
|
|
140
|
+
* against your tools and (optionally) a live browser — all inside a sandboxed Worker, recorded on a durable codemode
|
|
151
141
|
* runtime (abort-and-replay, approvals, snippets).
|
|
152
142
|
*
|
|
153
|
-
* The model sees typed namespaces: `tools.*` for your AI SDK tools
|
|
154
|
-
* `
|
|
155
|
-
*
|
|
143
|
+
* The model sees typed namespaces: `tools.*` for your AI SDK tools and
|
|
144
|
+
* `cdp.*` for the browser. To give the sandbox the workspace, pass the
|
|
145
|
+
* workspace tools: `tools: createAITools({ workspace: this.workspace })`.
|
|
156
146
|
*
|
|
157
147
|
* Setup checklist:
|
|
158
148
|
*
|
|
@@ -166,7 +156,7 @@ declare function truncatePausedExecutionOutput(output: unknown): unknown;
|
|
|
166
156
|
* ```ts
|
|
167
157
|
* getTools() {
|
|
168
158
|
* return {
|
|
169
|
-
* //
|
|
159
|
+
* // cdp.* if env.BROWSER is bound,
|
|
170
160
|
* // executor from env.LOADER
|
|
171
161
|
* execute: createExecuteTool(this)
|
|
172
162
|
* };
|
|
@@ -183,7 +173,6 @@ declare function truncatePausedExecutionOutput(output: unknown): unknown;
|
|
|
183
173
|
* execute: createExecuteTool({
|
|
184
174
|
* ctx: this.ctx,
|
|
185
175
|
* tools: myDomainTools, // tools.*
|
|
186
|
-
* state: createWorkspaceStateBackend(this.workspace), // state.*
|
|
187
176
|
* browser: this.env.BROWSER, // cdp.*
|
|
188
177
|
* loader: this.env.LOADER
|
|
189
178
|
* })
|
|
@@ -191,6 +180,12 @@ declare function truncatePausedExecutionOutput(output: unknown): unknown;
|
|
|
191
180
|
*
|
|
192
181
|
* Use {@link createExecuteRuntime} to also get the runtime handle
|
|
193
182
|
* (approvals, audit, snippets) and the connector set.
|
|
183
|
+
*
|
|
184
|
+
* @deprecated Code execution is moving to the Workspace: give it a
|
|
185
|
+
* JavaScript backend with a `ws:tools` module
|
|
186
|
+
* (`createToolBindings(forAISDKTools(() => this.getTools()))` from
|
|
187
|
+
* `@cloudflare/computer`), so code the model runs with `exec` imports the
|
|
188
|
+
* agent's tools and reads files through `node:fs`.
|
|
194
189
|
*/
|
|
195
190
|
declare function createExecuteTool(
|
|
196
191
|
source: CreateExecuteToolOptions | ExecuteToolAgent,
|
package/dist/tools/execute.js
CHANGED
|
@@ -1,45 +1,17 @@
|
|
|
1
|
-
import { createWorkspaceStateBackend } from "@cloudflare/shell";
|
|
2
1
|
import { DynamicWorkerExecutor, createCodemodeRuntime, truncateResult } from "@cloudflare/codemode";
|
|
3
2
|
import { ToolSetConnector } from "@cloudflare/codemode/ai";
|
|
4
|
-
import { StateConnector } from "@cloudflare/shell/workers";
|
|
5
3
|
import { BrowserConnector, DurableBrowserSessionStore } from "agents/browser";
|
|
6
4
|
//#region src/tools/execute.ts
|
|
7
5
|
function isAgent(source) {
|
|
8
6
|
return "env" in source && !("executor" in source) && !("loader" in source);
|
|
9
7
|
}
|
|
10
|
-
const WORKSPACE_FS_METHODS = [
|
|
11
|
-
"readFile",
|
|
12
|
-
"readFileBytes",
|
|
13
|
-
"writeFile",
|
|
14
|
-
"writeFileBytes",
|
|
15
|
-
"appendFile",
|
|
16
|
-
"exists",
|
|
17
|
-
"stat",
|
|
18
|
-
"lstat",
|
|
19
|
-
"mkdir",
|
|
20
|
-
"readDir",
|
|
21
|
-
"rm",
|
|
22
|
-
"cp",
|
|
23
|
-
"mv",
|
|
24
|
-
"symlink",
|
|
25
|
-
"readlink",
|
|
26
|
-
"glob"
|
|
27
|
-
];
|
|
28
|
-
function workspaceFs(workspace) {
|
|
29
|
-
if (!workspace) return void 0;
|
|
30
|
-
const candidate = workspace;
|
|
31
|
-
for (const method of WORKSPACE_FS_METHODS) if (typeof candidate[method] !== "function") return void 0;
|
|
32
|
-
return workspace;
|
|
33
|
-
}
|
|
34
8
|
function optionsFromAgent(agent) {
|
|
35
9
|
const env = agent.env ?? {};
|
|
36
10
|
const ctx = agent.ctx;
|
|
37
11
|
if (!ctx) throw new Error("createExecuteTool(agent) requires a Durable Object agent — call createExecuteTool({ ctx, loader, ... }) with explicit options.");
|
|
38
|
-
const fs = workspaceFs(agent.workspace);
|
|
39
12
|
return {
|
|
40
13
|
ctx,
|
|
41
14
|
loader: env.LOADER,
|
|
42
|
-
state: fs ? createWorkspaceStateBackend(fs) : void 0,
|
|
43
15
|
browser: env.BROWSER
|
|
44
16
|
};
|
|
45
17
|
}
|
|
@@ -52,6 +24,12 @@ function optionsFromAgent(agent) {
|
|
|
52
24
|
* When called with an agent, the runtime handle is also assigned to
|
|
53
25
|
* `agent.codemode` so callables (and Think's built-in approval flow) can
|
|
54
26
|
* reach it.
|
|
27
|
+
*
|
|
28
|
+
* @deprecated Code execution is moving to the Workspace: give it a
|
|
29
|
+
* JavaScript backend with a `ws:tools` module
|
|
30
|
+
* (`createToolBindings(forAISDKTools(() => this.getTools()))` from
|
|
31
|
+
* `@cloudflare/computer`), so code the model runs with `exec` imports the
|
|
32
|
+
* agent's tools and reads files through `node:fs`.
|
|
55
33
|
*/
|
|
56
34
|
function createExecuteRuntime(source, overrides) {
|
|
57
35
|
const agent = isAgent(source) ? source : void 0;
|
|
@@ -73,7 +51,6 @@ function createExecuteRuntime(source, overrides) {
|
|
|
73
51
|
else throw new Error("createExecuteTool requires either an `executor` or a `loader` (WorkerLoader binding — `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` in wrangler.jsonc).");
|
|
74
52
|
const connectors = [];
|
|
75
53
|
if (options.tools && Object.keys(options.tools).length > 0) connectors.push(new ToolSetConnector(options.ctx, { tools: options.tools }));
|
|
76
|
-
if (options.state) connectors.push(new StateConnector(options.ctx, options.state));
|
|
77
54
|
if (options.browser) connectors.push(new BrowserConnector(options.ctx, {
|
|
78
55
|
browser: options.browser,
|
|
79
56
|
store: new DurableBrowserSessionStore(options.ctx.storage),
|
|
@@ -81,7 +58,7 @@ function createExecuteRuntime(source, overrides) {
|
|
|
81
58
|
timeout: options.timeout
|
|
82
59
|
}));
|
|
83
60
|
connectors.push(...options.connectors ?? []);
|
|
84
|
-
if (connectors.length === 0) throw new Error("createExecuteTool has nothing to expose — provide at least one of `tools`, `
|
|
61
|
+
if (connectors.length === 0) throw new Error("createExecuteTool has nothing to expose — provide at least one of `tools`, `browser`, or `connectors`.");
|
|
85
62
|
const runtime = createCodemodeRuntime({
|
|
86
63
|
ctx: options.ctx,
|
|
87
64
|
executor,
|
|
@@ -107,8 +84,8 @@ function createExecuteRuntime(source, overrides) {
|
|
|
107
84
|
/**
|
|
108
85
|
* One-line usage hints for the namespaces createExecuteTool itself wires up,
|
|
109
86
|
* rendered into the default tool description. Models otherwise tend to guess
|
|
110
|
-
* a filesystem API (`host.*`, `fs.*`) instead of discovering `
|
|
111
|
-
* `
|
|
87
|
+
* a filesystem API (`host.*`, `fs.*`) instead of discovering `tools.*` via
|
|
88
|
+
* `codemode.search`.
|
|
112
89
|
*/
|
|
113
90
|
function connectorHints(options) {
|
|
114
91
|
const hints = {};
|
|
@@ -116,7 +93,6 @@ function connectorHints(options) {
|
|
|
116
93
|
const names = Object.entries(options.tools).filter(([, t]) => typeof t.execute === "function").map(([name]) => name);
|
|
117
94
|
if (names.length > 0) hints.tools = `your host tools as async functions — e.g. \`await tools.${names[0]}({ ... })\`. Available: ${names.join(", ")}`;
|
|
118
95
|
}
|
|
119
|
-
if (options.state) hints.state = "the workspace filesystem. Every method takes ONE object argument: `state.readFile({ path })`, `state.writeFile({ path, content })`, `state.readdir({ path })`, `state.glob({ pattern })`, …";
|
|
120
96
|
if (options.browser) hints.cdp = "a live browser over the Chrome DevTools Protocol. Target-scoped commands need no sessionId: `cdp.send({ method: \"Target.createTarget\", params: { url } })`. Page-scoped commands (Page.*, Runtime.*, DOM.*) need one: `const { sessionId } = await cdp.attachToTarget({ targetId })`, then `cdp.send({ method, params, sessionId })`. Discover commands with `cdp.spec()`";
|
|
121
97
|
return hints;
|
|
122
98
|
}
|
|
@@ -147,13 +123,12 @@ function truncatePausedExecutionOutput(output) {
|
|
|
147
123
|
}
|
|
148
124
|
/**
|
|
149
125
|
* Create a code execution tool that lets the LLM write and run TypeScript
|
|
150
|
-
* against your tools
|
|
151
|
-
* browser — all inside a sandboxed Worker, recorded on a durable codemode
|
|
126
|
+
* against your tools and (optionally) a live browser — all inside a sandboxed Worker, recorded on a durable codemode
|
|
152
127
|
* runtime (abort-and-replay, approvals, snippets).
|
|
153
128
|
*
|
|
154
|
-
* The model sees typed namespaces: `tools.*` for your AI SDK tools
|
|
155
|
-
* `
|
|
156
|
-
*
|
|
129
|
+
* The model sees typed namespaces: `tools.*` for your AI SDK tools and
|
|
130
|
+
* `cdp.*` for the browser. To give the sandbox the workspace, pass the
|
|
131
|
+
* workspace tools: `tools: createAITools({ workspace: this.workspace })`.
|
|
157
132
|
*
|
|
158
133
|
* Setup checklist:
|
|
159
134
|
*
|
|
@@ -167,7 +142,7 @@ function truncatePausedExecutionOutput(output) {
|
|
|
167
142
|
* ```ts
|
|
168
143
|
* getTools() {
|
|
169
144
|
* return {
|
|
170
|
-
* //
|
|
145
|
+
* // cdp.* if env.BROWSER is bound,
|
|
171
146
|
* // executor from env.LOADER
|
|
172
147
|
* execute: createExecuteTool(this)
|
|
173
148
|
* };
|
|
@@ -184,7 +159,6 @@ function truncatePausedExecutionOutput(output) {
|
|
|
184
159
|
* execute: createExecuteTool({
|
|
185
160
|
* ctx: this.ctx,
|
|
186
161
|
* tools: myDomainTools, // tools.*
|
|
187
|
-
* state: createWorkspaceStateBackend(this.workspace), // state.*
|
|
188
162
|
* browser: this.env.BROWSER, // cdp.*
|
|
189
163
|
* loader: this.env.LOADER
|
|
190
164
|
* })
|
|
@@ -192,6 +166,12 @@ function truncatePausedExecutionOutput(output) {
|
|
|
192
166
|
*
|
|
193
167
|
* Use {@link createExecuteRuntime} to also get the runtime handle
|
|
194
168
|
* (approvals, audit, snippets) and the connector set.
|
|
169
|
+
*
|
|
170
|
+
* @deprecated Code execution is moving to the Workspace: give it a
|
|
171
|
+
* JavaScript backend with a `ws:tools` module
|
|
172
|
+
* (`createToolBindings(forAISDKTools(() => this.getTools()))` from
|
|
173
|
+
* `@cloudflare/computer`), so code the model runs with `exec` imports the
|
|
174
|
+
* agent's tools and reads files through `node:fs`.
|
|
195
175
|
*/
|
|
196
176
|
function createExecuteTool(source, overrides) {
|
|
197
177
|
return createExecuteRuntime(source, overrides).tool;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execute.js","names":[],"sources":["../../src/tools/execute.ts"],"sourcesContent":["import type { Tool, ToolSet } from \"ai\";\nimport {\n createCodemodeRuntime,\n DynamicWorkerExecutor,\n truncateResult,\n type CodemodeConnector,\n type CodemodeRuntimeHandle,\n type Executor\n} from \"@cloudflare/codemode\";\nimport { ToolSetConnector } from \"@cloudflare/codemode/ai\";\nimport type { StateBackend, WorkspaceFsLike } from \"@cloudflare/shell\";\nimport { createWorkspaceStateBackend } from \"@cloudflare/shell\";\nimport { StateConnector } from \"@cloudflare/shell/workers\";\nimport {\n BrowserConnector,\n DurableBrowserSessionStore,\n type BrowserBinding,\n type BrowserConnectorSessionOptions\n} from \"agents/browser\";\nimport type { WorkspaceLike } from \"./workspace\";\n\n/**\n * The minimum agent surface for the `createExecuteTool(this)` one-liner.\n * Any Think agent satisfies it. The agent must be a Durable Object — its\n * `ctx` hosts the codemode runtime facet, and its `env` provides the\n * LOADER/BROWSER bindings. (`ctx` and `env` are not declared here because\n * they are `protected` on the DO base class in some type configurations,\n * which would break structural assignability of `this`.)\n */\nexport interface ExecuteToolAgent {\n workspace?: WorkspaceLike;\n /** Set by `createExecuteRuntime(agent)` so callables can reach the runtime. */\n codemode?: CodemodeRuntimeHandle;\n}\n\nexport interface CreateExecuteToolOptions {\n /**\n * Durable Object state. The codemode runtime that backs the execute tool\n * lives in a facet of this DO — the tool must be created from inside a\n * Durable Object (e.g. a Think agent: pass `this.ctx`).\n */\n ctx: DurableObjectState;\n\n /**\n * AI SDK tools exposed inside the sandbox as `tools.*`. Tools with\n * `needsApproval` get the runtime's durable pause/approve/resume flow:\n * calling one pauses the execution until `approveExecution` /\n * `rejectExecution`. A function-valued `needsApproval` can't be evaluated\n * against sandbox arguments ahead of time, so it conservatively always\n * requires approval. Tools without an `execute` function (client-side /\n * provider-executed) are skipped — the sandbox can't call them.\n */\n tools?: ToolSet;\n\n /**\n * StateBackend exposed as `state.*` inside the sandbox — the full\n * filesystem API (readFile, writeFile, glob, searchFiles, replaceInFiles,\n * planEdits, …). Every method takes a single object argument.\n *\n * @example\n * ```ts\n * import { createWorkspaceStateBackend } from \"@cloudflare/shell\";\n * state: createWorkspaceStateBackend(this.workspace)\n * ```\n */\n state?: StateBackend;\n\n /**\n * Browser Rendering binding. When provided, the sandbox gets the `cdp.*`\n * connector (cdp.send, cdp.attachToTarget, cdp.spec, …) — a live browser\n * over the Chrome DevTools Protocol.\n *\n * Requires `\"browser\": { \"binding\": \"BROWSER\" }` in wrangler.jsonc.\n */\n browser?: BrowserBinding;\n\n /**\n * Browser session lifecycle (only with `browser`). Defaults to `dynamic`:\n * one-shot sessions the model can promote with `cdp.startSession()`.\n */\n session?: BrowserConnectorSessionOptions;\n\n /**\n * Additional connectors for the sandbox beyond `tools`, `state`, and `cdp`.\n * Each adds its own named namespace.\n */\n connectors?: CodemodeConnector[];\n\n /**\n * The executor that runs the generated code. If not provided, a\n * `DynamicWorkerExecutor` is created from `loader`.\n */\n executor?: Executor;\n\n /**\n * WorkerLoader binding for creating a `DynamicWorkerExecutor`.\n *\n * Requires `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` in wrangler.jsonc.\n */\n loader?: WorkerLoader;\n\n /**\n * Timeout in milliseconds for code execution. Defaults to 30000 (30s).\n * Only used when `loader` is provided (ignored if `executor` is given).\n */\n timeout?: number;\n\n /**\n * Controls outbound network access from sandboxed code.\n * - `null` (default): fetch() and connect() throw — sandbox is fully isolated.\n * - `undefined`: inherits parent Worker's network access.\n * - A `Fetcher`: all outbound requests route through this handler.\n *\n * Only used when `loader` is provided (ignored if `executor` is given).\n */\n globalOutbound?: Fetcher | null;\n\n /**\n * Custom tool description. Replaces the generated default entirely — the\n * default explains the codemode workflow and lists each configured\n * namespace (`tools.*`, `state.*`, `cdp.*`) with a usage hint.\n */\n description?: string;\n\n /**\n * Codemode runtime name — the durable identity of the tool's executions\n * and snippets. Defaults to `\"execute\"`. Adding or removing connectors\n * does NOT change the identity, so histories survive configuration\n * changes.\n */\n name?: string;\n}\n\n/**\n * The execute tool's moving parts, for hosts that need more than the tool:\n *\n * - `runtime` — the codemode runtime handle (approve/reject paused runs,\n * `expirePaused`, audit via `executions()`, snippets).\n * - `connectors` — the connector set backing the runtime (e.g. the\n * `BrowserConnector` for host-side `sessionInfo()` / `closeSession()` /\n * `sweep()`).\n * - `tool` — what `createExecuteTool` returns.\n */\nexport interface ExecuteRuntime {\n runtime: CodemodeRuntimeHandle;\n connectors: CodemodeConnector[];\n tool: Tool;\n}\n\nfunction isAgent(\n source: CreateExecuteToolOptions | ExecuteToolAgent\n): source is ExecuteToolAgent {\n // An options bag has no `env`, but guard against a hand-built object that\n // happens to carry one (e.g. spread from a worker handler): an explicit\n // `executor`/`loader` key marks it as options — agents never have those.\n // (Other option keys like `state`/`browser` can legitimately exist on agent\n // subclasses, so they can't discriminate.)\n return \"env\" in source && !(\"executor\" in source) && !(\"loader\" in source);\n}\n\n// The agent one-liner derives state from the workspace, which requires the\n// full filesystem surface (`WorkspaceFsLike`) — a concrete `Workspace` has\n// it; a minimal custom `WorkspaceLike` may not.\nconst WORKSPACE_FS_METHODS = [\n \"readFile\",\n \"readFileBytes\",\n \"writeFile\",\n \"writeFileBytes\",\n \"appendFile\",\n \"exists\",\n \"stat\",\n \"lstat\",\n \"mkdir\",\n \"readDir\",\n \"rm\",\n \"cp\",\n \"mv\",\n \"symlink\",\n \"readlink\",\n \"glob\"\n] as const;\n\nfunction workspaceFs(\n workspace: WorkspaceLike | undefined\n): WorkspaceFsLike | undefined {\n if (!workspace) return undefined;\n const candidate = workspace as unknown as Record<string, unknown>;\n for (const method of WORKSPACE_FS_METHODS) {\n if (typeof candidate[method] !== \"function\") return undefined;\n }\n return workspace as unknown as WorkspaceFsLike;\n}\n\nfunction optionsFromAgent(agent: ExecuteToolAgent): CreateExecuteToolOptions {\n const env = ((agent as unknown as { env?: unknown }).env ?? {}) as {\n LOADER?: WorkerLoader;\n BROWSER?: BrowserBinding;\n };\n const ctx = (agent as unknown as { ctx?: DurableObjectState }).ctx;\n if (!ctx) {\n throw new Error(\n \"createExecuteTool(agent) requires a Durable Object agent — \" +\n \"call createExecuteTool({ ctx, loader, ... }) with explicit options.\"\n );\n }\n const fs = workspaceFs(agent.workspace);\n return {\n ctx,\n loader: env.LOADER,\n state: fs ? createWorkspaceStateBackend(fs) : undefined,\n browser: env.BROWSER\n };\n}\n\n/**\n * Build the codemode runtime behind the execute tool, returning the runtime\n * handle and connectors alongside the tool. Use this instead of\n * {@link createExecuteTool} when the host needs approvals, the audit trail,\n * snippets, or browser session management.\n *\n * When called with an agent, the runtime handle is also assigned to\n * `agent.codemode` so callables (and Think's built-in approval flow) can\n * reach it.\n */\nexport function createExecuteRuntime(\n source: CreateExecuteToolOptions | ExecuteToolAgent,\n overrides?: Partial<Omit<CreateExecuteToolOptions, \"ctx\">>\n): ExecuteRuntime {\n const agent = isAgent(source) ? source : undefined;\n const options: CreateExecuteToolOptions = isAgent(source)\n ? { ...optionsFromAgent(source), ...overrides }\n : { ...source, ...overrides };\n\n if (agent && !options.executor && !options.loader) {\n throw new Error(\n \"createExecuteTool(agent) requires a WorkerLoader binding named LOADER — \" +\n 'add `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` to wrangler.jsonc, ' +\n \"or call createExecuteTool({ ctx, loader, ... }) with explicit options.\"\n );\n }\n\n let executor: Executor;\n if (options.executor) {\n executor = options.executor;\n } else if (options.loader) {\n executor = new DynamicWorkerExecutor({\n loader: options.loader,\n timeout: options.timeout,\n globalOutbound: options.globalOutbound\n });\n } else {\n throw new Error(\n \"createExecuteTool requires either an `executor` or a `loader` \" +\n '(WorkerLoader binding — `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` ' +\n \"in wrangler.jsonc).\"\n );\n }\n\n const connectors: CodemodeConnector[] = [];\n if (options.tools && Object.keys(options.tools).length > 0) {\n connectors.push(\n new ToolSetConnector(options.ctx, { tools: options.tools })\n );\n }\n if (options.state) {\n connectors.push(new StateConnector(options.ctx, options.state));\n }\n if (options.browser) {\n connectors.push(\n new BrowserConnector(options.ctx, {\n browser: options.browser,\n store: new DurableBrowserSessionStore(options.ctx.storage),\n session: options.session ?? { mode: \"dynamic\" },\n timeout: options.timeout\n })\n );\n }\n connectors.push(...(options.connectors ?? []));\n\n if (connectors.length === 0) {\n throw new Error(\n \"createExecuteTool has nothing to expose — provide at least one of \" +\n \"`tools`, `state`, `browser`, or `connectors`.\"\n );\n }\n\n const runtime = createCodemodeRuntime({\n ctx: options.ctx,\n executor,\n connectors,\n name: options.name ?? \"execute\",\n transformResult: truncateResult\n });\n\n if (agent) {\n agent.codemode = runtime;\n }\n\n const baseTool = runtime.tool({\n description: options.description,\n connectorHints: connectorHints(options)\n });\n const baseExecute = baseTool.execute;\n const tool: Tool = baseExecute\n ? ({\n ...baseTool,\n // Paused outputs land in the transcript (and the model context) as a\n // normal tool result; a gated call's raw args (e.g. a writeFile\n // payload) can be huge. Truncate them in the model-facing payload —\n // the runtime facet keeps the full args for the actual resume, and\n // the host can fetch detail via `pendingExecutions`.\n execute: async (input: unknown, callOptions: unknown) =>\n truncatePausedExecutionOutput(\n await (baseExecute as (i: unknown, o: unknown) => Promise<unknown>)(\n input,\n callOptions\n )\n )\n } as Tool)\n : baseTool;\n\n return {\n runtime,\n connectors,\n tool\n };\n}\n\n/**\n * One-line usage hints for the namespaces createExecuteTool itself wires up,\n * rendered into the default tool description. Models otherwise tend to guess\n * a filesystem API (`host.*`, `fs.*`) instead of discovering `state.*` /\n * `tools.*` via `codemode.search`.\n */\nfunction connectorHints(\n options: CreateExecuteToolOptions\n): Record<string, string> {\n const hints: Record<string, string> = {};\n if (options.tools) {\n const names = Object.entries(options.tools)\n .filter(([, t]) => typeof t.execute === \"function\")\n .map(([name]) => name);\n if (names.length > 0) {\n hints.tools =\n `your host tools as async functions — e.g. \\`await tools.${names[0]}({ ... })\\`. ` +\n `Available: ${names.join(\", \")}`;\n }\n }\n if (options.state) {\n hints.state =\n \"the workspace filesystem. Every method takes ONE object argument: \" +\n \"`state.readFile({ path })`, `state.writeFile({ path, content })`, \" +\n \"`state.readdir({ path })`, `state.glob({ pattern })`, …\";\n }\n if (options.browser) {\n hints.cdp =\n \"a live browser over the Chrome DevTools Protocol. \" +\n 'Target-scoped commands need no sessionId: `cdp.send({ method: \"Target.createTarget\", params: { url } })`. ' +\n \"Page-scoped commands (Page.*, Runtime.*, DOM.*) need one: \" +\n \"`const { sessionId } = await cdp.attachToTarget({ targetId })`, then \" +\n \"`cdp.send({ method, params, sessionId })`. Discover commands with `cdp.spec()`\";\n }\n return hints;\n}\n\n/** Character budget for a pending action's args in the transcript. */\nconst PENDING_ARGS_MAX_CHARS = 2_000;\n\n/**\n * Truncate the `pending[].args` of a paused execution output for transcript /\n * model consumption. The full args stay on the runtime facet (used by the\n * actual resume); only the model-facing copy is bounded. Non-paused outputs\n * pass through unchanged.\n */\nexport function truncatePausedExecutionOutput(output: unknown): unknown {\n if (typeof output !== \"object\" || output === null) return output;\n const o = output as { status?: unknown; pending?: unknown };\n if (o.status !== \"paused\" || !Array.isArray(o.pending)) return output;\n return {\n ...o,\n pending: o.pending.map((action) => {\n if (typeof action !== \"object\" || action === null) return action;\n const a = action as { args?: unknown };\n if (!(\"args\" in a)) return action;\n return {\n ...a,\n args: truncateResult(a.args, { maxChars: PENDING_ARGS_MAX_CHARS })\n };\n })\n };\n}\n\n/**\n * Create a code execution tool that lets the LLM write and run TypeScript\n * against your tools, the workspace filesystem, and (optionally) a live\n * browser — all inside a sandboxed Worker, recorded on a durable codemode\n * runtime (abort-and-replay, approvals, snippets).\n *\n * The model sees typed namespaces: `tools.*` for your AI SDK tools,\n * `state.*` for the filesystem (object args: `state.readFile({ path })`),\n * and `cdp.*` for the browser.\n *\n * Setup checklist:\n *\n * - `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` in wrangler.jsonc\n * - `\"browser\": { \"binding\": \"BROWSER\" }` in wrangler.jsonc (for `cdp.*`)\n * - export the runtime class from your worker entry:\n * `export { CodemodeRuntime } from \"@cloudflare/codemode\"`\n * (the `@cloudflare/codemode/vite` plugin does this automatically)\n *\n * @example One-liner — defaults from the agent\n * ```ts\n * getTools() {\n * return {\n * // state.* from this.workspace, cdp.* if env.BROWSER is bound,\n * // executor from env.LOADER\n * execute: createExecuteTool(this)\n * };\n * }\n * ```\n *\n * @example Agent defaults plus overrides (e.g. custom tools.*)\n * ```ts\n * execute: createExecuteTool(this, { tools: myDomainTools })\n * ```\n *\n * @example Explicit options\n * ```ts\n * execute: createExecuteTool({\n * ctx: this.ctx,\n * tools: myDomainTools, // tools.*\n * state: createWorkspaceStateBackend(this.workspace), // state.*\n * browser: this.env.BROWSER, // cdp.*\n * loader: this.env.LOADER\n * })\n * ```\n *\n * Use {@link createExecuteRuntime} to also get the runtime handle\n * (approvals, audit, snippets) and the connector set.\n */\nexport function createExecuteTool(\n source: CreateExecuteToolOptions | ExecuteToolAgent,\n overrides?: Partial<Omit<CreateExecuteToolOptions, \"ctx\">>\n): Tool {\n return createExecuteRuntime(source, overrides).tool;\n}\n"],"mappings":";;;;;;AAqJA,SAAS,QACP,QAC4B;CAM5B,OAAO,SAAS,UAAU,EAAE,cAAc,WAAW,EAAE,YAAY;AACrE;AAKA,MAAM,uBAAuB;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,SAAS,YACP,WAC6B;CAC7B,IAAI,CAAC,WAAW,OAAO,KAAA;CACvB,MAAM,YAAY;CAClB,KAAK,MAAM,UAAU,sBACnB,IAAI,OAAO,UAAU,YAAY,YAAY,OAAO,KAAA;CAEtD,OAAO;AACT;AAEA,SAAS,iBAAiB,OAAmD;CAC3E,MAAM,MAAQ,MAAuC,OAAO,CAAC;CAI7D,MAAM,MAAO,MAAkD;CAC/D,IAAI,CAAC,KACH,MAAM,IAAI,MACR,gIAEF;CAEF,MAAM,KAAK,YAAY,MAAM,SAAS;CACtC,OAAO;EACL;EACA,QAAQ,IAAI;EACZ,OAAO,KAAK,4BAA4B,EAAE,IAAI,KAAA;EAC9C,SAAS,IAAI;CACf;AACF;;;;;;;;;;;AAYA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":3,"file":"execute.js","names":[],"sources":["../../src/tools/execute.ts"],"sourcesContent":["import type { Tool, ToolSet } from \"ai\";\nimport {\n createCodemodeRuntime,\n DynamicWorkerExecutor,\n truncateResult,\n type CodemodeConnector,\n type CodemodeRuntimeHandle,\n type Executor\n} from \"@cloudflare/codemode\";\nimport { ToolSetConnector } from \"@cloudflare/codemode/ai\";\nimport {\n BrowserConnector,\n DurableBrowserSessionStore,\n type BrowserBinding,\n type BrowserConnectorSessionOptions\n} from \"agents/browser\";\n\n/**\n * The minimum agent surface for the `createExecuteTool(this)` one-liner.\n * Any Think agent satisfies it. The agent must be a Durable Object — its\n * `ctx` hosts the codemode runtime facet, and its `env` provides the\n * LOADER/BROWSER bindings. (`ctx` and `env` are not declared here because\n * they are `protected` on the DO base class in some type configurations,\n * which would break structural assignability of `this`.)\n */\nexport interface ExecuteToolAgent {\n /** Set by `createExecuteRuntime(agent)` so callables can reach the runtime. */\n codemode?: CodemodeRuntimeHandle;\n}\n\nexport interface CreateExecuteToolOptions {\n /**\n * Durable Object state. The codemode runtime that backs the execute tool\n * lives in a facet of this DO — the tool must be created from inside a\n * Durable Object (e.g. a Think agent: pass `this.ctx`).\n */\n ctx: DurableObjectState;\n\n /**\n * AI SDK tools exposed inside the sandbox as `tools.*`. Tools with\n * `needsApproval` get the runtime's durable pause/approve/resume flow:\n * calling one pauses the execution until `approveExecution` /\n * `rejectExecution`. A function-valued `needsApproval` can't be evaluated\n * against sandbox arguments ahead of time, so it conservatively always\n * requires approval. Tools without an `execute` function (client-side /\n * provider-executed) are skipped — the sandbox can't call them.\n */\n tools?: ToolSet;\n\n /**\n * Browser Rendering binding. When provided, the sandbox gets the `cdp.*`\n * connector (cdp.send, cdp.attachToTarget, cdp.spec, …) — a live browser\n * over the Chrome DevTools Protocol.\n *\n * Requires `\"browser\": { \"binding\": \"BROWSER\" }` in wrangler.jsonc.\n */\n browser?: BrowserBinding;\n\n /**\n * Browser session lifecycle (only with `browser`). Defaults to `dynamic`:\n * one-shot sessions the model can promote with `cdp.startSession()`.\n */\n session?: BrowserConnectorSessionOptions;\n\n /**\n * Additional connectors for the sandbox beyond `tools` and `cdp`.\n * Each adds its own named namespace.\n */\n connectors?: CodemodeConnector[];\n\n /**\n * The executor that runs the generated code. If not provided, a\n * `DynamicWorkerExecutor` is created from `loader`.\n */\n executor?: Executor;\n\n /**\n * WorkerLoader binding for creating a `DynamicWorkerExecutor`.\n *\n * Requires `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` in wrangler.jsonc.\n */\n loader?: WorkerLoader;\n\n /**\n * Timeout in milliseconds for code execution. Defaults to 30000 (30s).\n * Only used when `loader` is provided (ignored if `executor` is given).\n */\n timeout?: number;\n\n /**\n * Controls outbound network access from sandboxed code.\n * - `null` (default): fetch() and connect() throw — sandbox is fully isolated.\n * - `undefined`: inherits parent Worker's network access.\n * - A `Fetcher`: all outbound requests route through this handler.\n *\n * Only used when `loader` is provided (ignored if `executor` is given).\n */\n globalOutbound?: Fetcher | null;\n\n /**\n * Custom tool description. Replaces the generated default entirely — the\n * default explains the codemode workflow and lists each configured\n * namespace (`tools.*`, `cdp.*`) with a usage hint.\n */\n description?: string;\n\n /**\n * Codemode runtime name — the durable identity of the tool's executions\n * and snippets. Defaults to `\"execute\"`. Adding or removing connectors\n * does NOT change the identity, so histories survive configuration\n * changes.\n */\n name?: string;\n}\n\n/**\n * The execute tool's moving parts, for hosts that need more than the tool:\n *\n * - `runtime` — the codemode runtime handle (approve/reject paused runs,\n * `expirePaused`, audit via `executions()`, snippets).\n * - `connectors` — the connector set backing the runtime (e.g. the\n * `BrowserConnector` for host-side `sessionInfo()` / `closeSession()` /\n * `sweep()`).\n * - `tool` — what `createExecuteTool` returns.\n */\nexport interface ExecuteRuntime {\n runtime: CodemodeRuntimeHandle;\n connectors: CodemodeConnector[];\n tool: Tool;\n}\n\nfunction isAgent(\n source: CreateExecuteToolOptions | ExecuteToolAgent\n): source is ExecuteToolAgent {\n // An options bag has no `env`, but guard against a hand-built object that\n // happens to carry one (e.g. spread from a worker handler): an explicit\n // `executor`/`loader` key marks it as options — agents never have those.\n // (Other option keys like `tools`/`browser` can legitimately exist on agent\n // subclasses, so they can't discriminate.)\n return \"env\" in source && !(\"executor\" in source) && !(\"loader\" in source);\n}\n\nfunction optionsFromAgent(agent: ExecuteToolAgent): CreateExecuteToolOptions {\n const env = ((agent as unknown as { env?: unknown }).env ?? {}) as {\n LOADER?: WorkerLoader;\n BROWSER?: BrowserBinding;\n };\n const ctx = (agent as unknown as { ctx?: DurableObjectState }).ctx;\n if (!ctx) {\n throw new Error(\n \"createExecuteTool(agent) requires a Durable Object agent — \" +\n \"call createExecuteTool({ ctx, loader, ... }) with explicit options.\"\n );\n }\n return {\n ctx,\n loader: env.LOADER,\n browser: env.BROWSER\n };\n}\n\n/**\n * Build the codemode runtime behind the execute tool, returning the runtime\n * handle and connectors alongside the tool. Use this instead of\n * {@link createExecuteTool} when the host needs approvals, the audit trail,\n * snippets, or browser session management.\n *\n * When called with an agent, the runtime handle is also assigned to\n * `agent.codemode` so callables (and Think's built-in approval flow) can\n * reach it.\n *\n * @deprecated Code execution is moving to the Workspace: give it a\n * JavaScript backend with a `ws:tools` module\n * (`createToolBindings(forAISDKTools(() => this.getTools()))` from\n * `@cloudflare/computer`), so code the model runs with `exec` imports the\n * agent's tools and reads files through `node:fs`.\n */\nexport function createExecuteRuntime(\n source: CreateExecuteToolOptions | ExecuteToolAgent,\n overrides?: Partial<Omit<CreateExecuteToolOptions, \"ctx\">>\n): ExecuteRuntime {\n const agent = isAgent(source) ? source : undefined;\n const options: CreateExecuteToolOptions = isAgent(source)\n ? { ...optionsFromAgent(source), ...overrides }\n : { ...source, ...overrides };\n\n if (agent && !options.executor && !options.loader) {\n throw new Error(\n \"createExecuteTool(agent) requires a WorkerLoader binding named LOADER — \" +\n 'add `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` to wrangler.jsonc, ' +\n \"or call createExecuteTool({ ctx, loader, ... }) with explicit options.\"\n );\n }\n\n let executor: Executor;\n if (options.executor) {\n executor = options.executor;\n } else if (options.loader) {\n executor = new DynamicWorkerExecutor({\n loader: options.loader,\n timeout: options.timeout,\n globalOutbound: options.globalOutbound\n });\n } else {\n throw new Error(\n \"createExecuteTool requires either an `executor` or a `loader` \" +\n '(WorkerLoader binding — `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` ' +\n \"in wrangler.jsonc).\"\n );\n }\n\n const connectors: CodemodeConnector[] = [];\n if (options.tools && Object.keys(options.tools).length > 0) {\n connectors.push(\n new ToolSetConnector(options.ctx, { tools: options.tools })\n );\n }\n if (options.browser) {\n connectors.push(\n new BrowserConnector(options.ctx, {\n browser: options.browser,\n store: new DurableBrowserSessionStore(options.ctx.storage),\n session: options.session ?? { mode: \"dynamic\" },\n timeout: options.timeout\n })\n );\n }\n connectors.push(...(options.connectors ?? []));\n\n if (connectors.length === 0) {\n throw new Error(\n \"createExecuteTool has nothing to expose — provide at least one of \" +\n \"`tools`, `browser`, or `connectors`.\"\n );\n }\n\n const runtime = createCodemodeRuntime({\n ctx: options.ctx,\n executor,\n connectors,\n name: options.name ?? \"execute\",\n transformResult: truncateResult\n });\n\n if (agent) {\n agent.codemode = runtime;\n }\n\n const baseTool = runtime.tool({\n description: options.description,\n connectorHints: connectorHints(options)\n });\n const baseExecute = baseTool.execute;\n const tool: Tool = baseExecute\n ? ({\n ...baseTool,\n // Paused outputs land in the transcript (and the model context) as a\n // normal tool result; a gated call's raw args (e.g. a writeFile\n // payload) can be huge. Truncate them in the model-facing payload —\n // the runtime facet keeps the full args for the actual resume, and\n // the host can fetch detail via `pendingExecutions`.\n execute: async (input: unknown, callOptions: unknown) =>\n truncatePausedExecutionOutput(\n await (baseExecute as (i: unknown, o: unknown) => Promise<unknown>)(\n input,\n callOptions\n )\n )\n } as Tool)\n : baseTool;\n\n return {\n runtime,\n connectors,\n tool\n };\n}\n\n/**\n * One-line usage hints for the namespaces createExecuteTool itself wires up,\n * rendered into the default tool description. Models otherwise tend to guess\n * a filesystem API (`host.*`, `fs.*`) instead of discovering `tools.*` via\n * `codemode.search`.\n */\nfunction connectorHints(\n options: CreateExecuteToolOptions\n): Record<string, string> {\n const hints: Record<string, string> = {};\n if (options.tools) {\n const names = Object.entries(options.tools)\n .filter(([, t]) => typeof t.execute === \"function\")\n .map(([name]) => name);\n if (names.length > 0) {\n hints.tools =\n `your host tools as async functions — e.g. \\`await tools.${names[0]}({ ... })\\`. ` +\n `Available: ${names.join(\", \")}`;\n }\n }\n if (options.browser) {\n hints.cdp =\n \"a live browser over the Chrome DevTools Protocol. \" +\n 'Target-scoped commands need no sessionId: `cdp.send({ method: \"Target.createTarget\", params: { url } })`. ' +\n \"Page-scoped commands (Page.*, Runtime.*, DOM.*) need one: \" +\n \"`const { sessionId } = await cdp.attachToTarget({ targetId })`, then \" +\n \"`cdp.send({ method, params, sessionId })`. Discover commands with `cdp.spec()`\";\n }\n return hints;\n}\n\n/** Character budget for a pending action's args in the transcript. */\nconst PENDING_ARGS_MAX_CHARS = 2_000;\n\n/**\n * Truncate the `pending[].args` of a paused execution output for transcript /\n * model consumption. The full args stay on the runtime facet (used by the\n * actual resume); only the model-facing copy is bounded. Non-paused outputs\n * pass through unchanged.\n */\nexport function truncatePausedExecutionOutput(output: unknown): unknown {\n if (typeof output !== \"object\" || output === null) return output;\n const o = output as { status?: unknown; pending?: unknown };\n if (o.status !== \"paused\" || !Array.isArray(o.pending)) return output;\n return {\n ...o,\n pending: o.pending.map((action) => {\n if (typeof action !== \"object\" || action === null) return action;\n const a = action as { args?: unknown };\n if (!(\"args\" in a)) return action;\n return {\n ...a,\n args: truncateResult(a.args, { maxChars: PENDING_ARGS_MAX_CHARS })\n };\n })\n };\n}\n\n/**\n * Create a code execution tool that lets the LLM write and run TypeScript\n * against your tools and (optionally) a live browser — all inside a sandboxed Worker, recorded on a durable codemode\n * runtime (abort-and-replay, approvals, snippets).\n *\n * The model sees typed namespaces: `tools.*` for your AI SDK tools and\n * `cdp.*` for the browser. To give the sandbox the workspace, pass the\n * workspace tools: `tools: createAITools({ workspace: this.workspace })`.\n *\n * Setup checklist:\n *\n * - `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` in wrangler.jsonc\n * - `\"browser\": { \"binding\": \"BROWSER\" }` in wrangler.jsonc (for `cdp.*`)\n * - export the runtime class from your worker entry:\n * `export { CodemodeRuntime } from \"@cloudflare/codemode\"`\n * (the `@cloudflare/codemode/vite` plugin does this automatically)\n *\n * @example One-liner — defaults from the agent\n * ```ts\n * getTools() {\n * return {\n * // cdp.* if env.BROWSER is bound,\n * // executor from env.LOADER\n * execute: createExecuteTool(this)\n * };\n * }\n * ```\n *\n * @example Agent defaults plus overrides (e.g. custom tools.*)\n * ```ts\n * execute: createExecuteTool(this, { tools: myDomainTools })\n * ```\n *\n * @example Explicit options\n * ```ts\n * execute: createExecuteTool({\n * ctx: this.ctx,\n * tools: myDomainTools, // tools.*\n * browser: this.env.BROWSER, // cdp.*\n * loader: this.env.LOADER\n * })\n * ```\n *\n * Use {@link createExecuteRuntime} to also get the runtime handle\n * (approvals, audit, snippets) and the connector set.\n *\n * @deprecated Code execution is moving to the Workspace: give it a\n * JavaScript backend with a `ws:tools` module\n * (`createToolBindings(forAISDKTools(() => this.getTools()))` from\n * `@cloudflare/computer`), so code the model runs with `exec` imports the\n * agent's tools and reads files through `node:fs`.\n */\nexport function createExecuteTool(\n source: CreateExecuteToolOptions | ExecuteToolAgent,\n overrides?: Partial<Omit<CreateExecuteToolOptions, \"ctx\">>\n): Tool {\n return createExecuteRuntime(source, overrides).tool;\n}\n"],"mappings":";;;;AAmIA,SAAS,QACP,QAC4B;CAM5B,OAAO,SAAS,UAAU,EAAE,cAAc,WAAW,EAAE,YAAY;AACrE;AAEA,SAAS,iBAAiB,OAAmD;CAC3E,MAAM,MAAQ,MAAuC,OAAO,CAAC;CAI7D,MAAM,MAAO,MAAkD;CAC/D,IAAI,CAAC,KACH,MAAM,IAAI,MACR,gIAEF;CAEF,O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19
19
|
*
|
|
20
20
|
* getTools() {
|
|
21
21
|
* return {
|
|
22
|
-
* ...
|
|
22
|
+
* ...createAITools({ workspace: this.workspace }),
|
|
23
23
|
* ...extensionTools,
|
|
24
24
|
* ...extensions.getTools(), // tools from loaded extensions
|
|
25
25
|
* };
|
package/dist/tools/extensions.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as sanitizeName } from "../manager-
|
|
1
|
+
import { n as sanitizeName } from "../manager-BubfmA3q.js";
|
|
2
2
|
import { tool } from "ai";
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
//#region src/tools/extensions.ts
|
|
@@ -16,7 +16,7 @@ import { z } from "zod";
|
|
|
16
16
|
*
|
|
17
17
|
* getTools() {
|
|
18
18
|
* return {
|
|
19
|
-
* ...
|
|
19
|
+
* ...createAITools({ workspace: this.workspace }),
|
|
20
20
|
* ...extensionTools,
|
|
21
21
|
* ...extensions.getTools(), // tools from loaded extensions
|
|
22
22
|
* };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extensions.js","names":[],"sources":["../../src/tools/extensions.ts"],"sourcesContent":["import { tool, type ToolSet } from \"ai\";\nimport { z } from \"zod\";\nimport type { ExtensionManager } from \"../extensions/manager\";\nimport { sanitizeName } from \"../extensions/manager\";\n\nexport interface ExtensionToolsOptions {\n manager: ExtensionManager;\n}\n\n/**\n * Create AI SDK tools for managing extensions at runtime.\n *\n * These tools let the LLM load and list extensions dynamically.\n * Loaded extensions expose their own tools on the next inference\n * turn. Unloading is a client-side action (via @callable RPC).\n *\n * @example\n * ```ts\n * const extensions = new ExtensionManager({ loader: this.env.LOADER, workspace: this.workspace });\n * const extensionTools = createExtensionTools({ manager: extensions });\n *\n * getTools() {\n * return {\n * ...
|
|
1
|
+
{"version":3,"file":"extensions.js","names":[],"sources":["../../src/tools/extensions.ts"],"sourcesContent":["import { tool, type ToolSet } from \"ai\";\nimport { z } from \"zod\";\nimport type { ExtensionManager } from \"../extensions/manager\";\nimport { sanitizeName } from \"../extensions/manager\";\n\nexport interface ExtensionToolsOptions {\n manager: ExtensionManager;\n}\n\n/**\n * Create AI SDK tools for managing extensions at runtime.\n *\n * These tools let the LLM load and list extensions dynamically.\n * Loaded extensions expose their own tools on the next inference\n * turn. Unloading is a client-side action (via @callable RPC).\n *\n * @example\n * ```ts\n * const extensions = new ExtensionManager({ loader: this.env.LOADER, workspace: this.workspace });\n * const extensionTools = createExtensionTools({ manager: extensions });\n *\n * getTools() {\n * return {\n * ...createAITools({ workspace: this.workspace }),\n * ...extensionTools,\n * ...extensions.getTools(), // tools from loaded extensions\n * };\n * }\n * ```\n */\nexport function createExtensionTools(options: ExtensionToolsOptions): ToolSet {\n const { manager } = options;\n\n return {\n load_extension: tool({\n description:\n \"Load an extension from JavaScript source code. \" +\n \"The source is a JS object expression with { tools, hooks }. \" +\n \"Each tool has: description, parameters (JSON Schema properties), \" +\n \"optional required array, and an async execute function. \" +\n \"The execute function receives (args, host) where host provides \" +\n \"workspace access (host.readFile, host.writeFile, host.listFiles), \" +\n \"context access (host.getContext, host.setContext), and \" +\n \"message access (host.getMessages, host.sendMessage). \" +\n \"NOTE: `host` exists ONLY inside extension source code passed to this tool — \" +\n \"it is NOT a global in the `execute` code sandbox or anywhere else. \" +\n \"Hooks are optional lifecycle functions (beforeTurn, etc.). \" +\n \"IMPORTANT: Use only lowercase letters, numbers, and underscores in the extension name. \" +\n \"Tool names are prefixed: name 'math' with tool 'add' becomes 'math_add'. \" +\n \"New tools become available on the next message turn — call them by their full prefixed name.\",\n inputSchema: z.object({\n name: z.string().describe(\"Unique name for the extension\"),\n version: z.string().describe(\"Semver version (e.g. '1.0.0')\"),\n description: z\n .string()\n .optional()\n .describe(\"Human-readable description\"),\n source: z\n .string()\n .describe(\n \"JavaScript object expression with { tools, hooks }. Example:\\n\" +\n \"{\\n\" +\n \" tools: {\\n\" +\n ' greet: {\\n description: \"Greet someone\",\\n' +\n ' parameters: { name: { type: \"string\" } },\\n' +\n ' required: [\"name\"],\\n' +\n ' execute: async (args) => \"Hello, \" + args.name\\n }\\n' +\n \" }\\n}\"\n ),\n workspace_access: z\n .enum([\"none\", \"read\", \"read-write\"])\n .optional()\n .describe(\"Workspace access level for the extension (default: none)\"),\n network: z\n .array(z.string())\n .optional()\n .describe(\n \"Network hosts the extension needs access to (default: none)\"\n )\n }),\n execute: async ({\n name,\n version,\n description,\n source,\n workspace_access,\n network\n }) => {\n const info = await manager.load(\n {\n name,\n version,\n description,\n permissions: {\n workspace: workspace_access ?? \"none\",\n network\n }\n },\n source\n );\n return {\n loaded: true,\n name: info.name,\n prefix: sanitizeName(name),\n version: info.version,\n tools: info.tools,\n message: `Extension \"${name}\" loaded. On the NEXT message turn, call these tools by their full name: ${info.tools.join(\", \")}.`\n };\n }\n }),\n\n list_extensions: tool({\n description: \"List all currently loaded extensions and their tools.\",\n inputSchema: z.object({}),\n execute: async () => {\n const extensions = manager.list();\n return {\n count: extensions.length,\n extensions: extensions.map((ext) => ({\n name: ext.name,\n version: ext.version,\n description: ext.description,\n tools: ext.tools,\n permissions: ext.permissions\n }))\n };\n }\n })\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,SAAgB,qBAAqB,SAAyC;CAC5E,MAAM,EAAE,YAAY;CAEpB,OAAO;EACL,gBAAgB,KAAK;GACnB,aACE;GAcF,aAAa,EAAE,OAAO;IACpB,MAAM,EAAE,OAAO,CAAC,CAAC,SAAS,+BAA+B;IACzD,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS,+BAA+B;IAC5D,aAAa,EACV,OAAO,CAAC,CACR,SAAS,CAAC,CACV,SAAS,4BAA4B;IACxC,QAAQ,EACL,OAAO,CAAC,CACR,SACC,yRAQF;IACF,kBAAkB,EACf,KAAK;KAAC;KAAQ;KAAQ;IAAY,CAAC,CAAC,CACpC,SAAS,CAAC,CACV,SAAS,0DAA0D;IACtE,SAAS,EACN,MAAM,EAAE,OAAO,CAAC,CAAC,CACjB,SAAS,CAAC,CACV,SACC,6DACF;GACJ,CAAC;GACD,SAAS,OAAO,EACd,MACA,SACA,aACA,QACA,kBACA,cACI;IACJ,MAAM,OAAO,MAAM,QAAQ,KACzB;KACE;KACA;KACA;KACA,aAAa;MACX,WAAW,oBAAoB;MAC/B;KACF;IACF,GACA,MACF;IACA,OAAO;KACL,QAAQ;KACR,MAAM,KAAK;KACX,QAAQ,aAAa,IAAI;KACzB,SAAS,KAAK;KACd,OAAO,KAAK;KACZ,SAAS,cAAc,KAAK,2EAA2E,KAAK,MAAM,KAAK,IAAI,EAAE;IAC/H;GACF;EACF,CAAC;EAED,iBAAiB,KAAK;GACpB,aAAa;GACb,aAAa,EAAE,OAAO,CAAC,CAAC;GACxB,SAAS,YAAY;IACnB,MAAM,aAAa,QAAQ,KAAK;IAChC,OAAO;KACL,OAAO,WAAW;KAClB,YAAY,WAAW,KAAK,SAAS;MACnC,MAAM,IAAI;MACV,SAAS,IAAI;MACb,aAAa,IAAI;MACjB,OAAO,IAAI;MACX,aAAa,IAAI;KACnB,EAAE;IACJ;GACF;EACF,CAAC;CACH;AACF"}
|
package/dist/tools/fetch.d.ts
CHANGED
|
@@ -1,14 +1,13 @@
|
|
|
1
1
|
import {
|
|
2
2
|
a as FetchResponseMode,
|
|
3
|
-
c as
|
|
3
|
+
c as createFetchTools,
|
|
4
4
|
i as FetchRedirectPolicy,
|
|
5
|
-
l as createFetchTools,
|
|
6
5
|
n as FetchBindingTarget,
|
|
7
6
|
o as FetchResult,
|
|
8
7
|
r as FetchErrorCode,
|
|
9
8
|
s as FetchToolEvent,
|
|
10
9
|
t as CreateFetchToolsOptions
|
|
11
|
-
} from "../fetch-
|
|
10
|
+
} from "../fetch-C7s1mpgg.js";
|
|
12
11
|
export {
|
|
13
12
|
CreateFetchToolsOptions,
|
|
14
13
|
FetchBindingTarget,
|
|
@@ -17,6 +16,5 @@ export {
|
|
|
17
16
|
FetchResponseMode,
|
|
18
17
|
FetchResult,
|
|
19
18
|
FetchToolEvent,
|
|
20
|
-
FetchWorkspace,
|
|
21
19
|
createFetchTools
|
|
22
20
|
};
|