@cloudflare/think 0.8.8 → 0.9.1
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 +1 -1
- package/dist/cli/index.js +7 -7
- package/dist/cli/index.js.map +1 -1
- package/dist/{codegen-CauNNguA.js → codegen-CuPdJRpV.js} +3 -2
- package/dist/codegen-CuPdJRpV.js.map +1 -0
- package/dist/extensions/index.js +1 -1
- package/dist/framework/index.d.ts +4 -4
- package/dist/framework/index.js +3 -3
- package/dist/{manager-EBL4uMVp.js → manager-BPndMP_6.js} +7 -7
- package/dist/{manager-EBL4uMVp.js.map → manager-BPndMP_6.js.map} +1 -1
- package/dist/messengers/index.d.ts +54 -54
- package/dist/messengers/telegram.d.ts +4 -4
- package/dist/{project-D1o1-3dN.js → project-BHurFdu4.js} +2 -2
- package/dist/{project-D1o1-3dN.js.map → project-BHurFdu4.js.map} +1 -1
- package/dist/server-entry.d.ts +2 -0
- package/dist/server-entry.js +2 -1
- package/dist/server-entry.js.map +1 -1
- package/dist/think-2nHHEcY3.js +6446 -0
- package/dist/think-2nHHEcY3.js.map +1 -0
- package/dist/{think-8jik2oZ5.d.ts → think-CwxWGsX1.d.ts} +563 -133
- package/dist/think.d.ts +2 -2
- package/dist/think.js +1 -5825
- package/dist/tools/browser.d.ts +80 -45
- package/dist/tools/browser.js +25 -41
- package/dist/tools/browser.js.map +1 -1
- package/dist/tools/execute.d.ts +145 -75
- package/dist/tools/execute.js +180 -54
- package/dist/tools/execute.js.map +1 -1
- package/dist/tools/extensions.js +2 -2
- package/dist/tools/extensions.js.map +1 -1
- package/dist/tools/workspace.js +10 -8
- package/dist/tools/workspace.js.map +1 -1
- package/dist/vite.js +2 -2
- package/dist/workflows.d.ts +1 -1
- package/package.json +8 -8
- package/dist/codegen-CauNNguA.js.map +0 -1
- package/dist/think.js.map +0 -1
package/dist/tools/execute.js
CHANGED
|
@@ -1,76 +1,202 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { DynamicWorkerExecutor } from "@cloudflare/codemode";
|
|
3
|
-
import {
|
|
1
|
+
import { createWorkspaceStateBackend } from "@cloudflare/shell";
|
|
2
|
+
import { DynamicWorkerExecutor, createCodemodeRuntime, truncateResult } from "@cloudflare/codemode";
|
|
3
|
+
import { ToolSetConnector } from "@cloudflare/codemode/ai";
|
|
4
|
+
import { StateConnector } from "@cloudflare/shell/workers";
|
|
5
|
+
import { BrowserConnector, DurableBrowserSessionStore } from "agents/browser";
|
|
4
6
|
//#region src/tools/execute.ts
|
|
7
|
+
function isAgent(source) {
|
|
8
|
+
return "env" in source && !("executor" in source) && !("loader" in source);
|
|
9
|
+
}
|
|
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
|
+
function optionsFromAgent(agent) {
|
|
35
|
+
const env = agent.env ?? {};
|
|
36
|
+
const ctx = agent.ctx;
|
|
37
|
+
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
|
+
return {
|
|
40
|
+
ctx,
|
|
41
|
+
loader: env.LOADER,
|
|
42
|
+
state: fs ? createWorkspaceStateBackend(fs) : void 0,
|
|
43
|
+
browser: env.BROWSER
|
|
44
|
+
};
|
|
45
|
+
}
|
|
5
46
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
47
|
+
* Build the codemode runtime behind the execute tool, returning the runtime
|
|
48
|
+
* handle and connectors alongside the tool. Use this instead of
|
|
49
|
+
* {@link createExecuteTool} when the host needs approvals, the audit trail,
|
|
50
|
+
* snippets, or browser session management.
|
|
8
51
|
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
52
|
+
* When called with an agent, the runtime handle is also assigned to
|
|
53
|
+
* `agent.codemode` so callables (and Think's built-in approval flow) can
|
|
54
|
+
* reach it.
|
|
55
|
+
*/
|
|
56
|
+
function createExecuteRuntime(source, overrides) {
|
|
57
|
+
const agent = isAgent(source) ? source : void 0;
|
|
58
|
+
const options = isAgent(source) ? {
|
|
59
|
+
...optionsFromAgent(source),
|
|
60
|
+
...overrides
|
|
61
|
+
} : {
|
|
62
|
+
...source,
|
|
63
|
+
...overrides
|
|
64
|
+
};
|
|
65
|
+
if (agent && !options.executor && !options.loader) throw new Error("createExecuteTool(agent) requires a WorkerLoader binding named LOADER — add `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` to wrangler.jsonc, or call createExecuteTool({ ctx, loader, ... }) with explicit options.");
|
|
66
|
+
let executor;
|
|
67
|
+
if (options.executor) executor = options.executor;
|
|
68
|
+
else if (options.loader) executor = new DynamicWorkerExecutor({
|
|
69
|
+
loader: options.loader,
|
|
70
|
+
timeout: options.timeout,
|
|
71
|
+
globalOutbound: options.globalOutbound
|
|
72
|
+
});
|
|
73
|
+
else throw new Error("createExecuteTool requires either an `executor` or a `loader` (WorkerLoader binding — `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` in wrangler.jsonc).");
|
|
74
|
+
const connectors = [];
|
|
75
|
+
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
|
+
if (options.browser) connectors.push(new BrowserConnector(options.ctx, {
|
|
78
|
+
browser: options.browser,
|
|
79
|
+
store: new DurableBrowserSessionStore(options.ctx.storage),
|
|
80
|
+
session: options.session ?? { mode: "dynamic" },
|
|
81
|
+
timeout: options.timeout
|
|
82
|
+
}));
|
|
83
|
+
connectors.push(...options.connectors ?? []);
|
|
84
|
+
if (connectors.length === 0) throw new Error("createExecuteTool has nothing to expose — provide at least one of `tools`, `state`, `browser`, or `connectors`.");
|
|
85
|
+
const runtime = createCodemodeRuntime({
|
|
86
|
+
ctx: options.ctx,
|
|
87
|
+
executor,
|
|
88
|
+
connectors,
|
|
89
|
+
name: options.name ?? "execute",
|
|
90
|
+
transformResult: truncateResult
|
|
91
|
+
});
|
|
92
|
+
if (agent) agent.codemode = runtime;
|
|
93
|
+
const baseTool = runtime.tool({
|
|
94
|
+
description: options.description,
|
|
95
|
+
connectorHints: connectorHints(options)
|
|
96
|
+
});
|
|
97
|
+
const baseExecute = baseTool.execute;
|
|
98
|
+
return {
|
|
99
|
+
runtime,
|
|
100
|
+
connectors,
|
|
101
|
+
tool: baseExecute ? {
|
|
102
|
+
...baseTool,
|
|
103
|
+
execute: async (input, callOptions) => truncatePausedExecutionOutput(await baseExecute(input, callOptions))
|
|
104
|
+
} : baseTool
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* One-line usage hints for the namespaces createExecuteTool itself wires up,
|
|
109
|
+
* rendered into the default tool description. Models otherwise tend to guess
|
|
110
|
+
* a filesystem API (`host.*`, `fs.*`) instead of discovering `state.*` /
|
|
111
|
+
* `tools.*` via `codemode.search`.
|
|
112
|
+
*/
|
|
113
|
+
function connectorHints(options) {
|
|
114
|
+
const hints = {};
|
|
115
|
+
if (options.tools) {
|
|
116
|
+
const names = Object.entries(options.tools).filter(([, t]) => typeof t.execute === "function").map(([name]) => name);
|
|
117
|
+
if (names.length > 0) hints.tools = `your host tools as async functions — e.g. \`await tools.${names[0]}({ ... })\`. Available: ${names.join(", ")}`;
|
|
118
|
+
}
|
|
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
|
+
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
|
+
return hints;
|
|
122
|
+
}
|
|
123
|
+
/** Character budget for a pending action's args in the transcript. */
|
|
124
|
+
const PENDING_ARGS_MAX_CHARS = 2e3;
|
|
125
|
+
/**
|
|
126
|
+
* Truncate the `pending[].args` of a paused execution output for transcript /
|
|
127
|
+
* model consumption. The full args stay on the runtime facet (used by the
|
|
128
|
+
* actual resume); only the model-facing copy is bounded. Non-paused outputs
|
|
129
|
+
* pass through unchanged.
|
|
130
|
+
*/
|
|
131
|
+
function truncatePausedExecutionOutput(output) {
|
|
132
|
+
if (typeof output !== "object" || output === null) return output;
|
|
133
|
+
const o = output;
|
|
134
|
+
if (o.status !== "paused" || !Array.isArray(o.pending)) return output;
|
|
135
|
+
return {
|
|
136
|
+
...o,
|
|
137
|
+
pending: o.pending.map((action) => {
|
|
138
|
+
if (typeof action !== "object" || action === null) return action;
|
|
139
|
+
const a = action;
|
|
140
|
+
if (!("args" in a)) return action;
|
|
141
|
+
return {
|
|
142
|
+
...a,
|
|
143
|
+
args: truncateResult(a.args, { maxChars: PENDING_ARGS_MAX_CHARS })
|
|
144
|
+
};
|
|
145
|
+
})
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Create a code execution tool that lets the LLM write and run TypeScript
|
|
150
|
+
* against your tools, the workspace filesystem, and (optionally) a live
|
|
151
|
+
* browser — all inside a sandboxed Worker, recorded on a durable codemode
|
|
152
|
+
* runtime (abort-and-replay, approvals, snippets).
|
|
12
153
|
*
|
|
13
|
-
*
|
|
14
|
-
* `
|
|
154
|
+
* The model sees typed namespaces: `tools.*` for your AI SDK tools,
|
|
155
|
+
* `state.*` for the filesystem (object args: `state.readFile({ path })`),
|
|
156
|
+
* and `cdp.*` for the browser.
|
|
15
157
|
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
158
|
+
* Setup checklist:
|
|
159
|
+
*
|
|
160
|
+
* - `"worker_loaders": [{ "binding": "LOADER" }]` in wrangler.jsonc
|
|
161
|
+
* - `"browser": { "binding": "BROWSER" }` in wrangler.jsonc (for `cdp.*`)
|
|
162
|
+
* - export the runtime class from your worker entry:
|
|
163
|
+
* `export { CodemodeRuntime } from "@cloudflare/codemode"`
|
|
164
|
+
* (the `@cloudflare/codemode/vite` plugin does this automatically)
|
|
20
165
|
*
|
|
166
|
+
* @example One-liner — defaults from the agent
|
|
167
|
+
* ```ts
|
|
21
168
|
* getTools() {
|
|
22
|
-
* const workspaceTools = createWorkspaceTools(this.workspace);
|
|
23
|
-
* const backend = createWorkspaceStateBackend(this.workspace);
|
|
24
169
|
* return {
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
* state: backend, // state.* — full filesystem API
|
|
29
|
-
* loader: this.env.LOADER,
|
|
30
|
-
* }),
|
|
170
|
+
* // state.* from this.workspace, cdp.* if env.BROWSER is bound,
|
|
171
|
+
* // executor from env.LOADER
|
|
172
|
+
* execute: createExecuteTool(this)
|
|
31
173
|
* };
|
|
32
174
|
* }
|
|
33
175
|
* ```
|
|
34
176
|
*
|
|
35
|
-
* @example
|
|
177
|
+
* @example Agent defaults plus overrides (e.g. custom tools.*)
|
|
36
178
|
* ```ts
|
|
37
|
-
* createExecuteTool({
|
|
38
|
-
* tools: myTools,
|
|
39
|
-
* loader: this.env.LOADER,
|
|
40
|
-
* });
|
|
179
|
+
* execute: createExecuteTool(this, { tools: myDomainTools })
|
|
41
180
|
* ```
|
|
42
181
|
*
|
|
43
|
-
* @example
|
|
182
|
+
* @example Explicit options
|
|
44
183
|
* ```ts
|
|
45
|
-
*
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
* createExecuteTool({ tools: myTools, executor });
|
|
184
|
+
* execute: createExecuteTool({
|
|
185
|
+
* ctx: this.ctx,
|
|
186
|
+
* tools: myDomainTools, // tools.*
|
|
187
|
+
* state: createWorkspaceStateBackend(this.workspace), // state.*
|
|
188
|
+
* browser: this.env.BROWSER, // cdp.*
|
|
189
|
+
* loader: this.env.LOADER
|
|
190
|
+
* })
|
|
53
191
|
* ```
|
|
192
|
+
*
|
|
193
|
+
* Use {@link createExecuteRuntime} to also get the runtime handle
|
|
194
|
+
* (approvals, audit, snippets) and the connector set.
|
|
54
195
|
*/
|
|
55
|
-
function createExecuteTool(
|
|
56
|
-
|
|
57
|
-
let executor;
|
|
58
|
-
if (options.executor) executor = options.executor;
|
|
59
|
-
else if (options.loader) executor = new DynamicWorkerExecutor({
|
|
60
|
-
loader: options.loader,
|
|
61
|
-
timeout: options.timeout,
|
|
62
|
-
globalOutbound: options.globalOutbound
|
|
63
|
-
});
|
|
64
|
-
else throw new Error("createExecuteTool requires either an `executor` or a `loader` (WorkerLoader binding).");
|
|
65
|
-
const providers = [{ tools }, ...options.providers ?? []];
|
|
66
|
-
if (state) providers.push(stateToolsFromBackend(state));
|
|
67
|
-
return createCodeTool({
|
|
68
|
-
tools: providers,
|
|
69
|
-
executor,
|
|
70
|
-
description
|
|
71
|
-
});
|
|
196
|
+
function createExecuteTool(source, overrides) {
|
|
197
|
+
return createExecuteRuntime(source, overrides).tool;
|
|
72
198
|
}
|
|
73
199
|
//#endregion
|
|
74
|
-
export { createExecuteTool };
|
|
200
|
+
export { createExecuteRuntime, createExecuteTool, truncatePausedExecutionOutput };
|
|
75
201
|
|
|
76
202
|
//# sourceMappingURL=execute.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execute.js","names":[],"sources":["../../src/tools/execute.ts"],"sourcesContent":["import type { ToolSet } from \"ai\";\nimport { createCodeTool } from \"@cloudflare/codemode/ai\";\nimport { DynamicWorkerExecutor } from \"@cloudflare/codemode\";\nimport type { Executor, ToolProvider } from \"@cloudflare/codemode\";\nimport type { StateBackend } from \"@cloudflare/shell\";\nimport { stateToolsFromBackend } from \"@cloudflare/shell/workers\";\n\nexport interface CreateExecuteToolOptions {\n /**\n * The tools available inside the sandboxed code as `codemode.*`.\n *\n * Typically the workspace tools from `createWorkspaceTools()`,\n * but can include any AI SDK tools with `execute` functions.\n */\n tools: ToolSet;\n\n /**\n * Optional StateBackend to expose as `state.*` inside the sandbox.\n *\n * When provided, the sandbox has both `codemode.*` tool calls and\n * the full `state.*` filesystem API (readFile, writeFile, glob,\n * searchFiles, replaceInFiles, planEdits, etc.).\n *\n * This is the preferred way to give the LLM rich filesystem access:\n * use individual workspace tools for simple one-shot operations,\n * and `state.*` for coordinated multi-file work.\n *\n * @example\n * ```ts\n * import { createWorkspaceStateBackend } from \"@cloudflare/shell\";\n *\n * createExecuteTool({\n * tools: myDomainTools,\n * state: createWorkspaceStateBackend(this.workspace),\n * loader: this.env.LOADER,\n * });\n * // sandbox: codemode.myTool() AND state.readFile() AND state.planEdits()\n * ```\n */\n state?: StateBackend;\n\n /**\n * Additional tool providers for the sandbox beyond the default tools and state.\n * Each provider adds a named namespace alongside `codemode.*` and `state.*`.\n */\n providers?: ToolProvider[];\n\n /**\n * The executor that runs the generated code.\n *\n * Use `DynamicWorkerExecutor` for Cloudflare Workers (requires a\n * `worker_loaders` binding in wrangler.jsonc), or implement the\n * `Executor` interface for other runtimes.\n *\n * If not provided, you must provide a `loader` instead.\n */\n executor?: Executor;\n\n /**\n * WorkerLoader binding for creating a `DynamicWorkerExecutor`.\n * This is a convenience alternative to passing a full `executor`.\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. Use `{{types}}` as a placeholder for the\n * auto-generated TypeScript type definitions of the available tools.\n */\n description?: string;\n}\n\n/**\n * Create a code execution tool that lets the LLM write and run JavaScript\n * with access to your tools in a sandboxed environment.\n *\n * The LLM sees typed `codemode.*` functions and writes code that calls them.\n * Code runs in an isolated Worker via `DynamicWorkerExecutor` — external\n * network access is blocked by default.\n *\n * Pass `state` to also expose the full `state.*` filesystem API alongside\n * `codemode.*`:\n *\n * @example\n * ```ts\n * import { createWorkspaceTools, createExecuteTool } from \"@cloudflare/think\";\n * import { createWorkspaceStateBackend } from \"@cloudflare/shell\";\n *\n * getTools() {\n * const workspaceTools = createWorkspaceTools(this.workspace);\n * const backend = createWorkspaceStateBackend(this.workspace);\n * return {\n * ...workspaceTools,\n * execute: createExecuteTool({\n * tools: myDomainTools, // codemode.* — non-filesystem tools\n * state: backend, // state.* — full filesystem API\n * loader: this.env.LOADER,\n * }),\n * };\n * }\n * ```\n *\n * @example Tools only (no filesystem in sandbox)\n * ```ts\n * createExecuteTool({\n * tools: myTools,\n * loader: this.env.LOADER,\n * });\n * ```\n *\n * @example Custom executor\n * ```ts\n * import { DynamicWorkerExecutor } from \"@cloudflare/codemode\";\n *\n * const executor = new DynamicWorkerExecutor({\n * loader: this.env.LOADER,\n * timeout: 60000,\n * });\n *\n * createExecuteTool({ tools: myTools, executor });\n * ```\n */\nexport function createExecuteTool(options: CreateExecuteToolOptions) {\n const { tools, description, state } = options;\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` (WorkerLoader binding).\"\n );\n }\n\n const providers: ToolProvider[] = [\n { tools }, // default \"codemode\" namespace\n ...(options.providers ?? [])\n ];\n if (state) {\n providers.push(stateToolsFromBackend(state));\n }\n\n return createCodeTool({ tools: providers, executor, description });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2IA,SAAgB,kBAAkB,SAAmC;CACnE,MAAM,EAAE,OAAO,aAAa,UAAU;CAEtC,IAAI;CACJ,IAAI,QAAQ,UACV,WAAW,QAAQ;MACd,IAAI,QAAQ,QACjB,WAAW,IAAI,sBAAsB;EACnC,QAAQ,QAAQ;EAChB,SAAS,QAAQ;EACjB,gBAAgB,QAAQ;CAC1B,CAAC;MAED,MAAM,IAAI,MACR,uFACF;CAGF,MAAM,YAA4B,CAChC,EAAE,MAAM,GACR,GAAI,QAAQ,aAAa,CAAC,CAC5B;CACA,IAAI,OACF,UAAU,KAAK,sBAAsB,KAAK,CAAC;CAG7C,OAAO,eAAe;EAAE,OAAO;EAAW;EAAU;CAAY,CAAC;AACnE"}
|
|
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":"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"}
|
package/dist/tools/extensions.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as sanitizeName } from "../manager-
|
|
1
|
+
import { n as sanitizeName } from "../manager-BPndMP_6.js";
|
|
2
2
|
import { tool } from "ai";
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
//#region src/tools/extensions.ts
|
|
@@ -27,7 +27,7 @@ function createExtensionTools(options) {
|
|
|
27
27
|
const { manager } = options;
|
|
28
28
|
return {
|
|
29
29
|
load_extension: tool({
|
|
30
|
-
description: "Load an extension from JavaScript source code. The source is a JS object expression with { tools, hooks }. Each tool has: description, parameters (JSON Schema properties), optional required array, and an async execute function. The execute function receives (args, host) where host provides workspace access (host.readFile, host.writeFile, host.listFiles), context access (host.getContext, host.setContext), and message access (host.getMessages, host.sendMessage). Hooks are optional lifecycle functions (beforeTurn, etc.). IMPORTANT: Use only lowercase letters, numbers, and underscores in the extension name. Tool names are prefixed: name 'math' with tool 'add' becomes 'math_add'. New tools become available on the next message turn — call them by their full prefixed name.",
|
|
30
|
+
description: "Load an extension from JavaScript source code. The source is a JS object expression with { tools, hooks }. Each tool has: description, parameters (JSON Schema properties), optional required array, and an async execute function. The execute function receives (args, host) where host provides workspace access (host.readFile, host.writeFile, host.listFiles), context access (host.getContext, host.setContext), and message access (host.getMessages, host.sendMessage). NOTE: `host` exists ONLY inside extension source code passed to this tool — it is NOT a global in the `execute` code sandbox or anywhere else. Hooks are optional lifecycle functions (beforeTurn, etc.). IMPORTANT: Use only lowercase letters, numbers, and underscores in the extension name. Tool names are prefixed: name 'math' with tool 'add' becomes 'math_add'. New tools become available on the next message turn — call them by their full prefixed name.",
|
|
31
31
|
inputSchema: z.object({
|
|
32
32
|
name: z.string().describe("Unique name for the extension"),
|
|
33
33
|
version: z.string().describe("Semver version (e.g. '1.0.0')"),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extensions.js","names":[],"sources":["../../src/tools/extensions.ts"],"sourcesContent":["import { tool } 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 * ...createWorkspaceTools(this.workspace),\n * ...extensionTools,\n * ...extensions.getTools(), // tools from loaded extensions\n * };\n * }\n * ```\n */\nexport function createExtensionTools(options: ExtensionToolsOptions) {\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 \"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,SAAgC;CACnE,MAAM,EAAE,YAAY;CAEpB,OAAO;EACL,gBAAgB,KAAK;GACnB,aACE;
|
|
1
|
+
{"version":3,"file":"extensions.js","names":[],"sources":["../../src/tools/extensions.ts"],"sourcesContent":["import { tool } 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 * ...createWorkspaceTools(this.workspace),\n * ...extensionTools,\n * ...extensions.getTools(), // tools from loaded extensions\n * };\n * }\n * ```\n */\nexport function createExtensionTools(options: ExtensionToolsOptions) {\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,SAAgC;CACnE,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/workspace.js
CHANGED
|
@@ -586,17 +586,19 @@ const DEFAULT_BASH_MAX_WORKSPACE_FILES = 1e3;
|
|
|
586
586
|
const DEFAULT_BASH_MAX_WORKSPACE_FILE_BYTES = 1e6;
|
|
587
587
|
const DEFAULT_BASH_MAX_OUTPUT_BYTES = 64e3;
|
|
588
588
|
const BASH_READDIR_PAGE_SIZE = 1e3;
|
|
589
|
-
const
|
|
590
|
-
"/
|
|
591
|
-
"/
|
|
592
|
-
"/
|
|
589
|
+
const BASH_EXCLUDED_SYNC_ROOTS = [
|
|
590
|
+
"/bin",
|
|
591
|
+
"/usr",
|
|
592
|
+
"/dev",
|
|
593
|
+
"/proc",
|
|
594
|
+
"/sys"
|
|
593
595
|
];
|
|
594
596
|
function createBashTool(options) {
|
|
595
597
|
return tool({
|
|
596
|
-
description: "Run a Bash script against the workspace. Use for shell-style workflows that combine multiple file operations. The script runs in a sandboxed virtual filesystem mounted
|
|
598
|
+
description: "Run a Bash script against the workspace. Use for shell-style workflows that combine multiple file operations. The script runs in a sandboxed virtual filesystem with the workspace mounted at `/` (also the default working directory) — there is no `/workspace` or `/home`; use absolute paths like `/notes.txt`. Changed files are written back to the workspace.",
|
|
597
599
|
inputSchema: z.object({
|
|
598
600
|
script: z.string().describe("Bash script to run"),
|
|
599
|
-
cwd: z.string().optional().describe("Working directory for the script. Defaults to /")
|
|
601
|
+
cwd: z.string().optional().describe("Working directory for the script. Defaults to / (the workspace root)")
|
|
600
602
|
}),
|
|
601
603
|
execute: async ({ script, cwd }) => {
|
|
602
604
|
const timeout = options.timeout ?? DEFAULT_BASH_TIMEOUT_MS;
|
|
@@ -808,8 +810,8 @@ function shouldSyncBashPath(path, initialFiles, protectedPaths) {
|
|
|
808
810
|
if (path === "/") return false;
|
|
809
811
|
if (initialFiles.has(path)) return true;
|
|
810
812
|
if (protectedPaths.has(path)) return true;
|
|
811
|
-
if (path.startsWith("/tmp/")) return false;
|
|
812
|
-
return !
|
|
813
|
+
if (path === "/tmp" || path.startsWith("/tmp/")) return false;
|
|
814
|
+
return !BASH_EXCLUDED_SYNC_ROOTS.some((root) => path === root || path.startsWith(`${root}/`));
|
|
813
815
|
}
|
|
814
816
|
function hasProtectedDescendant(path, protectedPaths) {
|
|
815
817
|
const prefix = path.endsWith("/") ? path : `${path}/`;
|