@cloudflare/think 0.23.0 → 0.24.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.
@@ -63,7 +63,7 @@ import {
63
63
  *
64
64
  * export class MyAgent extends Think<Env> {
65
65
  * getModel() {
66
- * return createWorkersAI({ binding: this.env.AI })("@cf/moonshotai/kimi-k2.7-code");
66
+ * return createWorkersAI({ binding: this.env.AI })("@cf/deepseek-ai/deepseek-v4.1-flash-1017");
67
67
  * }
68
68
  *
69
69
  * getTools() {
@@ -33,7 +33,7 @@ import { createBrowserRuntime, createBrowserTools as createBrowserTools$1, creat
33
33
  *
34
34
  * export class MyAgent extends Think<Env> {
35
35
  * getModel() {
36
- * return createWorkersAI({ binding: this.env.AI })("@cf/moonshotai/kimi-k2.7-code");
36
+ * return createWorkersAI({ binding: this.env.AI })("@cf/deepseek-ai/deepseek-v4.1-flash-1017");
37
37
  * }
38
38
  *
39
39
  * getTools() {
@@ -1 +1 @@
1
- {"version":3,"file":"browser.js","names":["createBrowserToolsForAi"],"sources":["../../src/tools/browser.ts"],"sourcesContent":["import type { ToolSet } from \"ai\";\nimport {\n createBrowserRuntime,\n createBrowserTools as createBrowserToolsForAi,\n createQuickActionTools,\n type BrowserRuntime,\n type CreateBrowserToolsOptions,\n type CreateQuickActionToolsOptions,\n type QuickActionToolName\n} from \"agents/browser/ai\";\n\nexport {\n createBrowserRuntime,\n type BrowserRuntime,\n type CreateBrowserToolsOptions\n};\n\n// Stateless Quick Action tools — re-exported so a Think agent can expose them\n// from `getTools()` with a single import, including the loader-free path\n// (`createQuickActionTools`) that needs only the `browser` binding.\nexport {\n createQuickActionTools,\n type CreateQuickActionToolsOptions,\n type QuickActionToolName\n};\nexport {\n browserContent,\n browserExtract,\n browserLinks,\n browserMarkdown,\n browserPdf,\n browserScrape,\n browserScreenshot,\n browserSnapshot,\n runQuickAction,\n type QuickAction,\n type QuickActionBinary,\n type QuickActionBinding,\n type QuickActionCommonOptions,\n type QuickActionExtractInput,\n type QuickActionInput,\n type QuickActionPage,\n type QuickActionScrapeInput,\n type QuickActionScrapeResult,\n type QuickActionScreenshotInput,\n type QuickActionSnapshot\n} from \"agents/browser\";\n\n/**\n * Create browser automation tools for Think agents.\n *\n * Returns the durable `browser_execute` tool backed by a codemode runtime —\n * the model writes TypeScript against the `cdp` connector (`cdp.send`,\n * `cdp.attachToTarget`, `cdp.spec`, …); executions are recorded for\n * abort-and-replay, and browser sessions are keyed by execution (they survive\n * pauses and, in `reuse`/`dynamic` modes, span executions) — plus the stateless\n * {@link createQuickActionTools | Quick Action} tools (`browser_markdown`,\n * `browser_extract`, …) by default whenever a `browser` binding is present.\n * Pass `quickActions: false` to omit them, or use `createQuickActionTools`\n * directly for the stateless tools alone (no Worker Loader required).\n *\n * Setup checklist:\n *\n * - `\"browser\": { \"binding\": \"BROWSER\" }` in wrangler.jsonc\n * - `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` in wrangler.jsonc\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 * Use {@link createBrowserRuntime} instead when you also need the runtime\n * handle (approvals, audit, `expirePaused`) or the connector's host-side\n * session helpers (`sessionInfo`, `closeSession`, `sweep`).\n *\n * @example\n * ```ts\n * import { Think } from \"@cloudflare/think\";\n * import { createBrowserTools } from \"@cloudflare/think/tools/browser\";\n *\n * export class MyAgent extends Think<Env> {\n * getModel() {\n * return createWorkersAI({ binding: this.env.AI })(\"@cf/moonshotai/kimi-k2.7-code\");\n * }\n *\n * getTools() {\n * return {\n * ...createBrowserTools({\n * ctx: this.ctx,\n * browser: this.env.BROWSER,\n * loader: this.env.LOADER,\n * session: { mode: \"dynamic\" }\n * }),\n * };\n * }\n * }\n * ```\n */\nexport function createBrowserTools(\n options: CreateBrowserToolsOptions\n): ToolSet {\n return createBrowserToolsForAi(options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgGA,SAAgB,mBACd,SACS;CACT,OAAOA,qBAAwB,OAAO;AACxC"}
1
+ {"version":3,"file":"browser.js","names":["createBrowserToolsForAi"],"sources":["../../src/tools/browser.ts"],"sourcesContent":["import type { ToolSet } from \"ai\";\nimport {\n createBrowserRuntime,\n createBrowserTools as createBrowserToolsForAi,\n createQuickActionTools,\n type BrowserRuntime,\n type CreateBrowserToolsOptions,\n type CreateQuickActionToolsOptions,\n type QuickActionToolName\n} from \"agents/browser/ai\";\n\nexport {\n createBrowserRuntime,\n type BrowserRuntime,\n type CreateBrowserToolsOptions\n};\n\n// Stateless Quick Action tools — re-exported so a Think agent can expose them\n// from `getTools()` with a single import, including the loader-free path\n// (`createQuickActionTools`) that needs only the `browser` binding.\nexport {\n createQuickActionTools,\n type CreateQuickActionToolsOptions,\n type QuickActionToolName\n};\nexport {\n browserContent,\n browserExtract,\n browserLinks,\n browserMarkdown,\n browserPdf,\n browserScrape,\n browserScreenshot,\n browserSnapshot,\n runQuickAction,\n type QuickAction,\n type QuickActionBinary,\n type QuickActionBinding,\n type QuickActionCommonOptions,\n type QuickActionExtractInput,\n type QuickActionInput,\n type QuickActionPage,\n type QuickActionScrapeInput,\n type QuickActionScrapeResult,\n type QuickActionScreenshotInput,\n type QuickActionSnapshot\n} from \"agents/browser\";\n\n/**\n * Create browser automation tools for Think agents.\n *\n * Returns the durable `browser_execute` tool backed by a codemode runtime —\n * the model writes TypeScript against the `cdp` connector (`cdp.send`,\n * `cdp.attachToTarget`, `cdp.spec`, …); executions are recorded for\n * abort-and-replay, and browser sessions are keyed by execution (they survive\n * pauses and, in `reuse`/`dynamic` modes, span executions) — plus the stateless\n * {@link createQuickActionTools | Quick Action} tools (`browser_markdown`,\n * `browser_extract`, …) by default whenever a `browser` binding is present.\n * Pass `quickActions: false` to omit them, or use `createQuickActionTools`\n * directly for the stateless tools alone (no Worker Loader required).\n *\n * Setup checklist:\n *\n * - `\"browser\": { \"binding\": \"BROWSER\" }` in wrangler.jsonc\n * - `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` in wrangler.jsonc\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 * Use {@link createBrowserRuntime} instead when you also need the runtime\n * handle (approvals, audit, `expirePaused`) or the connector's host-side\n * session helpers (`sessionInfo`, `closeSession`, `sweep`).\n *\n * @example\n * ```ts\n * import { Think } from \"@cloudflare/think\";\n * import { createBrowserTools } from \"@cloudflare/think/tools/browser\";\n *\n * export class MyAgent extends Think<Env> {\n * getModel() {\n * return createWorkersAI({ binding: this.env.AI })(\"@cf/deepseek-ai/deepseek-v4.1-flash-1017\");\n * }\n *\n * getTools() {\n * return {\n * ...createBrowserTools({\n * ctx: this.ctx,\n * browser: this.env.BROWSER,\n * loader: this.env.LOADER,\n * session: { mode: \"dynamic\" }\n * }),\n * };\n * }\n * }\n * ```\n */\nexport function createBrowserTools(\n options: CreateBrowserToolsOptions\n): ToolSet {\n return createBrowserToolsForAi(options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgGA,SAAgB,mBACd,SACS;CACT,OAAOA,qBAAwB,OAAO;AACxC"}
@@ -119,7 +119,7 @@ interface ExecuteRuntime {
119
119
  * reach it.
120
120
  *
121
121
  * @deprecated Code execution is moving to the Workspace: give it a
122
- * JavaScript backend with a `ws:tools` module
122
+ * codemode backend with a `codemode:tools` module
123
123
  * (`createToolBindings(forAISDKTools(() => this.getTools()))` from
124
124
  * `@cloudflare/computer`), so code the model runs with `exec` imports the
125
125
  * agent's tools and reads files through `node:fs`.
@@ -182,7 +182,7 @@ declare function truncatePausedExecutionOutput(output: unknown): unknown;
182
182
  * (approvals, audit, snippets) and the connector set.
183
183
  *
184
184
  * @deprecated Code execution is moving to the Workspace: give it a
185
- * JavaScript backend with a `ws:tools` module
185
+ * codemode backend with a `codemode:tools` module
186
186
  * (`createToolBindings(forAISDKTools(() => this.getTools()))` from
187
187
  * `@cloudflare/computer`), so code the model runs with `exec` imports the
188
188
  * agent's tools and reads files through `node:fs`.
@@ -26,7 +26,7 @@ function optionsFromAgent(agent) {
26
26
  * reach it.
27
27
  *
28
28
  * @deprecated Code execution is moving to the Workspace: give it a
29
- * JavaScript backend with a `ws:tools` module
29
+ * codemode backend with a `codemode:tools` module
30
30
  * (`createToolBindings(forAISDKTools(() => this.getTools()))` from
31
31
  * `@cloudflare/computer`), so code the model runs with `exec` imports the
32
32
  * agent's tools and reads files through `node:fs`.
@@ -168,7 +168,7 @@ function truncatePausedExecutionOutput(output) {
168
168
  * (approvals, audit, snippets) and the connector set.
169
169
  *
170
170
  * @deprecated Code execution is moving to the Workspace: give it a
171
- * JavaScript backend with a `ws:tools` module
171
+ * codemode backend with a `codemode:tools` module
172
172
  * (`createToolBindings(forAISDKTools(() => this.getTools()))` from
173
173
  * `@cloudflare/computer`), so code the model runs with `exec` imports the
174
174
  * agent's tools and reads files through `node:fs`.
@@ -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 {\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,OAAO;EACL;EACA,QAAQ,IAAI;EACZ,SAAS,IAAI;CACf;AACF;;;;;;;;;;;;;;;;;AAkBA,SAAgB,qBACd,QACA,WACgB;CAChB,MAAM,QAAQ,QAAQ,MAAM,IAAI,SAAS,KAAA;CACzC,MAAM,UAAoC,QAAQ,MAAM,IACpD;EAAE,GAAG,iBAAiB,MAAM;EAAG,GAAG;CAAU,IAC5C;EAAE,GAAG;EAAQ,GAAG;CAAU;CAE9B,IAAI,SAAS,CAAC,QAAQ,YAAY,CAAC,QAAQ,QACzC,MAAM,IAAI,MACR,2NAGF;CAGF,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;MA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Q,SACV,MAAM,MACJ;CAMJ,OAAO;AACT;;AAGA,MAAM,yBAAyB;;;;;;;AAQ/B,SAAgB,8BAA8B,QAA0B;CACtE,IAAI,OAAO,WAAW,YAAY,WAAW,MAAM,OAAO;CAC1D,MAAM,IAAI;CACV,IAAI,EAAE,WAAW,YAAY,CAAC,MAAM,QAAQ,EAAE,OAAO,GAAG,OAAO;CAC/D,OAAO;EACL,GAAG;EACH,SAAS,EAAE,QAAQ,KAAK,WAAW;GACjC,IAAI,OAAO,WAAW,YAAY,WAAW,MAAM,OAAO;GAC1D,MAAM,IAAI;GACV,IAAI,EAAE,UAAU,IAAI,OAAO;GAC3B,OAAO;IACL,GAAG;IACH,MAAM,eAAe,EAAE,MAAM,EAAE,UAAU,uBAAuB,CAAC;GACnE;EACF,CAAC;CACH;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,SAAgB,kBACd,QACA,WACM;CACN,OAAO,qBAAqB,QAAQ,SAAS,CAAC,CAAC;AACjD"}
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 {\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 * codemode backend with a `codemode: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 * codemode backend with a `codemode: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,OAAO;EACL;EACA,QAAQ,IAAI;EACZ,SAAS,IAAI;CACf;AACF;;;;;;;;;;;;;;;;;AAkBA,SAAgB,qBACd,QACA,WACgB;CAChB,MAAM,QAAQ,QAAQ,MAAM,IAAI,SAAS,KAAA;CACzC,MAAM,UAAoC,QAAQ,MAAM,IACpD;EAAE,GAAG,iBAAiB,MAAM;EAAG,GAAG;CAAU,IAC5C;EAAE,GAAG;EAAQ,GAAG;CAAU;CAE9B,IAAI,SAAS,CAAC,QAAQ,YAAY,CAAC,QAAQ,QACzC,MAAM,IAAI,MACR,2NAGF;CAGF,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,+JAGF;CAGF,MAAM,aAAk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A,MAAM,yBAAyB;;;;;;;AAQ/B,SAAgB,8BAA8B,QAA0B;CACtE,IAAI,OAAO,WAAW,YAAY,WAAW,MAAM,OAAO;CAC1D,MAAM,IAAI;CACV,IAAI,EAAE,WAAW,YAAY,CAAC,MAAM,QAAQ,EAAE,OAAO,GAAG,OAAO;CAC/D,OAAO;EACL,GAAG;EACH,SAAS,EAAE,QAAQ,KAAK,WAAW;GACjC,IAAI,OAAO,WAAW,YAAY,WAAW,MAAM,OAAO;GAC1D,MAAM,IAAI;GACV,IAAI,EAAE,UAAU,IAAI,OAAO;GAC3B,OAAO;IACL,GAAG;IACH,MAAM,eAAe,EAAE,MAAM,EAAE,UAAU,uBAAuB,CAAC;GACnE;EACF,CAAC;CACH;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,SAAgB,kBACd,QACA,WACM;CACN,OAAO,qBAAqB,QAAQ,SAAS,CAAC,CAAC;AACjD"}
@@ -1,4 +1,4 @@
1
- import { t as ExtensionManager } from "../manager-rze95KCk.js";
1
+ import { t as ExtensionManager } from "../manager-CtXhU1fK.js";
2
2
  import { ToolSet } from "ai";
3
3
 
4
4
  //#region src/tools/extensions.d.ts
@@ -1,4 +1,4 @@
1
- import { n as sanitizeName } from "../manager-BubfmA3q.js";
1
+ import { n as sanitizeName } from "../manager-sfWIcYJT.js";
2
2
  import { tool } from "ai";
3
3
  import { z } from "zod";
4
4
  //#region src/tools/extensions.ts
@@ -1,4 +1,4 @@
1
- import { Tn as ThinkSubmissionStatus, gn as Think } from "./index-DDnny6kt.js";
1
+ import { Tn as ThinkSubmissionStatus, gn as Think } from "./index-DIQ9oY1t.js";
2
2
  import { ZodObject, z } from "zod";
3
3
  import { WorkflowEvent, WorkflowSleepDuration } from "cloudflare:workers";
4
4
  import {
@@ -87,7 +87,7 @@ export class MyAgent extends Think<Env> {
87
87
  // A string is resolved through Think's built-in workers-ai-provider off the
88
88
  // `AI` binding. Use a "@cf/..." id for Workers AI, or a "provider/model"
89
89
  // slug like "openai/gpt-5.5" to route through AI Gateway.
90
- return "@cf/moonshotai/kimi-k2.7-code";
90
+ return "@cf/deepseek-ai/deepseek-v4.1-flash-1017";
91
91
  }
92
92
 
93
93
  getSystemPrompt() {
@@ -207,7 +207,7 @@ import type { ContextConfig } from "agents/context";
207
207
 
208
208
  export class MyAgent extends Think<Env> {
209
209
  getModel() {
210
- return "@cf/moonshotai/kimi-k2.7-code";
210
+ return "@cf/deepseek-ai/deepseek-v4.1-flash-1017";
211
211
  }
212
212
 
213
213
  configureContext(): ContextConfig[] {
package/docs/index.md CHANGED
@@ -47,7 +47,7 @@ export class MyAgent extends Think<Env> {
47
47
  // Resolved via Think's built-in workers-ai-provider off the `AI` binding.
48
48
  // Use a "@cf/..." id for Workers AI, or a "provider/model" slug like
49
49
  // "openai/gpt-5.5" to route through AI Gateway.
50
- return "@cf/moonshotai/kimi-k2.7-code";
50
+ return "@cf/deepseek-ai/deepseek-v4.1-flash-1017";
51
51
  }
52
52
  }
53
53
 
@@ -726,8 +726,8 @@ export class MyAgent extends Think<Env> {
726
726
  getModel() {
727
727
  const tier = this.getConfig<MyConfig>()?.modelTier ?? "fast";
728
728
  const models = {
729
- fast: "@cf/moonshotai/kimi-k2.7-code",
730
- capable: "@cf/meta/llama-4-scout-17b-16e-instruct"
729
+ fast: "@cf/qwen/qwen3.8-27b",
730
+ capable: "@cf/deepseek-ai/deepseek-v4.1-flash-1017"
731
731
  };
732
732
  return models[tier];
733
733
  }
@@ -84,7 +84,7 @@ export class AssistantDirectory extends Think<Env, DirectoryState> {
84
84
 
85
85
  // Required by Think; nothing in the directory role calls it.
86
86
  override getModel() {
87
- return "@cf/moonshotai/kimi-k2.7-code";
87
+ return "@cf/deepseek-ai/deepseek-v4.1-flash-1017";
88
88
  }
89
89
 
90
90
  onStart() {
package/docs/tools.md CHANGED
@@ -43,7 +43,7 @@ The default Workspace has no execution backends, so there is no `exec` tool unti
43
43
  ```typescript
44
44
  import { Think } from "@cloudflare/think";
45
45
  import { Workspace } from "@cloudflare/computer";
46
- import { WorkerJavaScriptBackend } from "@cloudflare/computer/backends/worker-javascript";
46
+ import { CodemodeBackend } from "@cloudflare/computer/backends/codemode";
47
47
  import { createGitClient } from "@cloudflare/computer/git";
48
48
  import { createGitModule } from "@cloudflare/computer/modules/git";
49
49
 
@@ -52,11 +52,10 @@ export class MyAgent extends Think<Env> {
52
52
  storage: this.ctx.storage,
53
53
  git: createGitClient(),
54
54
  backends: [
55
- new WorkerJavaScriptBackend({
56
- id: "js",
55
+ new CodemodeBackend({
57
56
  loader: this.env.LOADER,
58
57
  access: "read-write",
59
- modules: { "ws:git": createGitModule() }
58
+ modules: { "codemode:git": createGitModule() }
60
59
  })
61
60
  ]
62
61
  });
@@ -67,28 +66,27 @@ export class MyAgent extends Think<Env> {
67
66
  }
68
67
  ```
69
68
 
70
- Computer ships a JavaScript backend and a just-bash shell backend that run in Dynamic Workers, and a container backend with a full Linux userland. See the [Computer README](https://github.com/cloudflare/computer/tree/main/packages/computer#choosing-a-backend) for each backend's bindings.
69
+ Computer ships a codemode backend for JavaScript and a just-bash shell backend that run in Dynamic Workers, and a container backend with a full Linux userland. See the [Computer README](https://github.com/cloudflare/computer/tree/main/packages/computer#choosing-a-backend) for each backend's bindings.
71
70
 
72
71
  ### Calling the agent's tools from code
73
72
 
74
- Give a JavaScript backend a `ws:tools` module, and code the model runs with `exec` can import the agent's tools. Files come from `node:fs/promises`, so serve `getTools()` rather than the workspace tools:
73
+ Give a codemode backend a `codemode:tools` module, and code the model runs with `exec` can import the agent's tools. Files come from `node:fs/promises`, so serve `getTools()` rather than the workspace tools:
75
74
 
76
75
  ```typescript
77
76
  import { createToolBindings } from "@cloudflare/computer/modules/tools";
78
77
  import { forAISDKTools } from "@cloudflare/computer/tools/ai-sdk";
79
78
 
80
- new WorkerJavaScriptBackend({
81
- id: "js",
79
+ new CodemodeBackend({
82
80
  loader: this.env.LOADER,
83
81
  modules: {
84
- "ws:tools": createToolBindings(forAISDKTools(() => this.getTools()))
82
+ "codemode:tools": createToolBindings(forAISDKTools(() => this.getTools()))
85
83
  }
86
84
  });
87
85
  ```
88
86
 
89
87
  ```ts
90
88
  import { readFile } from "node:fs/promises";
91
- import { getWeather } from "ws:tools";
89
+ import { getWeather } from "codemode:tools";
92
90
 
93
91
  export default async function () {
94
92
  const cities = JSON.parse(await readFile("/workspace/cities.json", "utf8"));
@@ -98,7 +96,7 @@ export default async function () {
98
96
  }
99
97
  ```
100
98
 
101
- Tools that need approval, and tools that run in the browser, are not exported: nothing can approve or run them from code. Calls from code do not go through `beforeToolCall`. See [`ws:tools`](https://github.com/cloudflare/computer/blob/main/docs/17_isolate_javascript.md#wstools) for how calls and results work.
99
+ Tools that need approval, and tools that run in the browser, are not exported: nothing can approve or run them from code. Calls from code do not go through `beforeToolCall`. See [`codemode:tools`](https://github.com/cloudflare/computer/blob/main/docs/17_isolate_javascript.md#codemodetools) for how calls and results work.
102
100
 
103
101
  ### Changing the tools
104
102
 
@@ -257,7 +255,7 @@ See [Connecting to MCP Servers](https://github.com/cloudflare/agents/blob/main/d
257
255
 
258
256
  ## Code Execution Tool
259
257
 
260
- > **Deprecated.** Use `exec` on a JavaScript backend with `ws:tools` instead; see [Calling the agent's tools from code](#calling-the-agents-tools-from-code). `createExecuteTool` will be removed along with `@cloudflare/codemode`.
258
+ > **Deprecated.** Use `exec` on a codemode backend with `codemode:tools` instead; see [Calling the agent's tools from code](#calling-the-agents-tools-from-code). `createExecuteTool` will be removed along with `@cloudflare/codemode`.
261
259
 
262
260
  Let the LLM write and run TypeScript in a sandboxed Worker, recorded on a durable codemode runtime (abort-and-replay, human approvals, audit trail, reusable snippets). Requires `@cloudflare/codemode` and a `worker_loaders` binding.
263
261
 
package/docs/workflows.md CHANGED
@@ -118,7 +118,7 @@ a terminal error state and `step.prompt()` throws.
118
118
  - **The model must support streaming tool calls.** Think streams every turn, so
119
119
  `step.prompt()` works only with models that reliably emit a forced tool call
120
120
  while streaming. Strong tool-callers (for example OpenAI `gpt-4o-mini`,
121
- Anthropic `claude-haiku-4-5`, and Workers AI `@cf/moonshotai/kimi-k2.7-code`) are
121
+ Anthropic `claude-haiku-4-5`, and Workers AI `@cf/deepseek-ai/deepseek-v4.1-flash-1017`) are
122
122
  verified to work. Some models honor a forced `toolChoice` only on
123
123
  non-streaming requests and will reply in plain text and stop while streaming —
124
124
  for example Workers AI `@cf/meta/llama-3.3-70b-instruct-fp8-fast`. With those
package/package.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "tools"
10
10
  ],
11
11
  "type": "module",
12
- "version": "0.23.0",
12
+ "version": "0.24.0",
13
13
  "license": "MIT",
14
14
  "repository": {
15
15
  "directory": "packages/think",
@@ -30,12 +30,12 @@
30
30
  "devDependencies": {
31
31
  "@ai-sdk/react": "^4.0.0",
32
32
  "@chat-adapter/telegram": "^4.31.0",
33
- "@cloudflare/computer": "^0.8.0",
33
+ "@cloudflare/computer": "^0.10.0",
34
34
  "@testing-library/react": "^16.3.2",
35
35
  "@types/react": "^19.2.17",
36
36
  "@types/react-dom": "^19.2.3",
37
37
  "@vitejs/plugin-react": "^6.0.3",
38
- "agents": "^0.32.0",
38
+ "agents": "^0.34.0",
39
39
  "ai": "^7.0.0",
40
40
  "jsdom": "^29.1.1",
41
41
  "react": "^19.2.7",
@@ -46,8 +46,8 @@
46
46
  "peerDependencies": {
47
47
  "@ai-sdk/react": "^4.0.0",
48
48
  "@chat-adapter/telegram": "^4.29.0",
49
- "@cloudflare/computer": "^0.8.0",
50
- "agents": ">=0.28.0 <1.0.0",
49
+ "@cloudflare/computer": "^0.10.0",
50
+ "agents": ">=0.34.0 <1.0.0",
51
51
  "ai": "^7.0.0",
52
52
  "react": "^19.0.0",
53
53
  "zod": "^4.0.0"
@@ -1 +0,0 @@
1
- {"version":3,"file":"manager-BubfmA3q.js","names":[],"sources":["../src/extensions/manager.ts"],"sourcesContent":["/**\n * ExtensionManager — loads, manages, and exposes tools from extension Workers.\n *\n * Extensions are sandboxed Workers created via WorkerLoader. Each extension\n * declares tools (with JSON Schema inputs) and permissions. The manager:\n *\n * 1. Wraps extension source in a Worker module with describe/execute RPC\n * 2. Loads it via WorkerLoader with permission-gated bindings\n * 3. Discovers tools via describe() RPC call\n * 4. Exposes them as AI SDK tools via getTools()\n *\n * Extension source format — a JS object expression defining tools:\n *\n * ```js\n * ({\n * greet: {\n * description: \"Greet someone\",\n * parameters: { name: { type: \"string\" } },\n * required: [\"name\"],\n * execute: async (args, host) => `Hello, ${args.name}!`\n * }\n * })\n * ```\n *\n * The `host` parameter in execute is provided via `env.host` — a loopback\n * binding that resolves the parent agent and delegates workspace operations\n * (gated by permissions). See HostBridgeLoopback.\n */\n\nimport { tool, jsonSchema } from \"ai\";\nimport type { ToolSet } from \"ai\";\nimport type {\n ExtensionManifest,\n ExtensionPermissions,\n ExtensionInfo,\n ExtensionToolDescriptor\n} from \"./types\";\n\n/**\n * Sanitize a name for use as a tool name prefix.\n * Replaces any non-alphanumeric characters with underscores and\n * collapses consecutive underscores.\n */\nexport function sanitizeName(name: string): string {\n if (!name || name.trim().length === 0) {\n throw new Error(\"Extension name must not be empty\");\n }\n return name\n .replace(/[^a-zA-Z0-9]/g, \"_\")\n .replace(/_+/g, \"_\")\n .replace(/^_|_$/g, \"\");\n}\n\ninterface ExtensionEntrypoint {\n describe(): Promise<string>;\n manifest(): Promise<string>;\n execute(toolName: string, argsJson: string): Promise<string>;\n hook(name: string, ctxProxy: unknown): Promise<string>;\n}\n\ninterface LoadedExtension {\n manifest: ExtensionManifest;\n tools: ExtensionToolDescriptor[];\n hooks: string[];\n entrypoint: ExtensionEntrypoint;\n}\n\n/** Shape persisted to DO storage for each extension. */\ninterface PersistedExtension {\n manifest: ExtensionManifest;\n source: string;\n}\n\nconst STORAGE_PREFIX = \"ext:\";\n\nexport interface ExtensionManagerOptions {\n /** WorkerLoader binding for creating sandboxed extension Workers. */\n loader: WorkerLoader;\n /**\n * Durable Object storage for persisting extensions across hibernation.\n * If provided, loaded extensions survive DO restarts. Call `restore()`\n * on each turn to rebuild in-memory state from storage.\n */\n storage?: DurableObjectStorage;\n /**\n * Factory that creates a loopback Fetcher for workspace access, given\n * an extension's declared permissions. The returned binding is injected\n * into the extension worker's `env.host`.\n *\n * If not provided, extensions receive no host binding (workspace tools\n * will get `null` for the host parameter).\n *\n * Typically wired up using HostBridgeLoopback via `ctx.exports`:\n * ```typescript\n * createHostBinding: (permissions, ownContextLabels) =>\n * ctx.exports.HostBridgeLoopback({\n * props: { agentClassName: \"ChatSession\", agentId: ctx.id.toString(), permissions, ownContextLabels }\n * })\n * ```\n */\n createHostBinding?: (\n permissions: ExtensionPermissions,\n ownContextLabels: string[]\n ) => Fetcher;\n}\n\nexport class ExtensionManager {\n #loader: WorkerLoader;\n #storage: DurableObjectStorage | null;\n #createHostBinding:\n | ((\n permissions: ExtensionPermissions,\n ownContextLabels: string[]\n ) => Fetcher)\n | null;\n #extensions = new Map<string, LoadedExtension>();\n #restored = false;\n #onUnload:\n | ((name: string, contextLabels: string[]) => void | Promise<void>)\n | null = null;\n\n constructor(options: ExtensionManagerOptions) {\n this.#loader = options.loader;\n this.#storage = options.storage ?? null;\n this.#createHostBinding = options.createHostBinding ?? null;\n }\n\n /**\n * Load an extension from source code.\n *\n * The source is a JS object expression defining tools. Each tool has\n * `description`, `parameters` (JSON Schema properties), optional\n * `required` array, and an `execute` async function.\n *\n * @returns Summary of the loaded extension including discovered tools.\n */\n /**\n * Restore extensions from DO storage after hibernation.\n *\n * Idempotent — skips extensions already in memory. Call this at the\n * start of each chat turn (e.g. in onChatMessage before getTools).\n */\n async restore(): Promise<void> {\n if (this.#restored || !this.#storage) return;\n this.#restored = true;\n\n const entries = await this.#storage.list<PersistedExtension>({\n prefix: STORAGE_PREFIX\n });\n\n for (const persisted of entries.values()) {\n if (this.#extensions.has(persisted.manifest.name)) continue;\n await this.#loadInternal(persisted.manifest, persisted.source);\n }\n }\n\n async load(\n manifest: ExtensionManifest,\n source: string\n ): Promise<ExtensionInfo> {\n if (this.#extensions.has(manifest.name)) {\n throw new Error(\n `Extension \"${manifest.name}\" is already loaded. Unload it first.`\n );\n }\n\n const info = await this.#loadInternal(manifest, source);\n\n // Persist to storage so it survives hibernation\n if (this.#storage) {\n await this.#storage.put<PersistedExtension>(\n `${STORAGE_PREFIX}${manifest.name}`,\n { manifest, source }\n );\n }\n\n return info;\n }\n\n async #loadInternal(\n manifest: ExtensionManifest,\n source: string\n ): Promise<ExtensionInfo> {\n const workerModule = wrapExtensionSource(source);\n const permissions = manifest.permissions ?? {};\n\n // Build env bindings for the dynamic worker. Inject a loopback\n // Fetcher as env.host when the extension declares ANY permission\n // that requires host access (workspace, context, messages, session).\n const workerEnv: Record<string, Fetcher> = {};\n const needsHost =\n (permissions.workspace ?? \"none\") !== \"none\" ||\n permissions.context?.read !== undefined ||\n permissions.context?.write !== undefined ||\n (permissions.messages ?? \"none\") !== \"none\" ||\n permissions.session?.sendMessage ||\n permissions.session?.metadata;\n if (this.#createHostBinding && needsHost) {\n const prefix = sanitizeName(manifest.name);\n const ownLabels = (manifest.context ?? []).map(\n (c) => `${prefix}_${c.label}`\n );\n workerEnv.host = this.#createHostBinding(permissions, ownLabels);\n }\n\n const worker = this.#loader.get(\n `ext-${manifest.name}-${manifest.version}-${Date.now()}`,\n () => ({\n compatibilityDate: \"2025-06-01\",\n compatibilityFlags: [\"nodejs_compat\"],\n mainModule: \"extension.js\",\n modules: { \"extension.js\": workerModule },\n globalOutbound: permissions.network?.length ? undefined : null,\n ...(Object.keys(workerEnv).length > 0 ? { env: workerEnv } : {})\n })\n );\n\n const entrypoint = worker.getEntrypoint() as unknown as ExtensionEntrypoint;\n\n // Discover tools and hooks via RPC\n const descriptorsJson = await entrypoint.describe();\n const tools = JSON.parse(descriptorsJson) as ExtensionToolDescriptor[];\n\n let hooks: string[] = [];\n try {\n const manifestJson = await entrypoint.manifest();\n const runtimeManifest = JSON.parse(manifestJson) as {\n hooks?: string[];\n };\n hooks = runtimeManifest.hooks ?? [];\n } catch {\n // Legacy extensions may not have manifest() — treat as no hooks\n }\n\n this.#extensions.set(manifest.name, {\n manifest,\n tools,\n hooks,\n entrypoint\n });\n\n return toExtensionInfo(manifest, tools);\n }\n\n /**\n * Unload an extension, removing its tools from the agent.\n * If an onUnload callback is registered, it fires with the\n * extension's namespaced context labels so the caller can\n * remove context blocks from the Session.\n */\n async unload(name: string): Promise<boolean> {\n const ext = this.#extensions.get(name);\n if (!ext) return false;\n\n const removed = this.#extensions.delete(name);\n if (removed && this.#storage) {\n await this.#storage.delete(`${STORAGE_PREFIX}${name}`);\n }\n\n if (removed && this.#onUnload) {\n const prefix = sanitizeName(name);\n const contextLabels = (ext.manifest.context ?? []).map(\n (c) => `${prefix}_${c.label}`\n );\n await this.#onUnload(name, contextLabels);\n }\n\n return removed;\n }\n\n /**\n * Register a callback invoked when an extension is unloaded.\n * Think uses this to remove the extension's context blocks from Session.\n */\n onUnload(\n cb: (name: string, contextLabels: string[]) => void | Promise<void>\n ): void {\n this.#onUnload = cb;\n }\n\n /**\n * Get the namespaced context labels for all loaded extensions\n * that declare context blocks in their manifests.\n */\n getContextLabels(): Array<{ extName: string; label: string }> {\n const result: Array<{ extName: string; label: string }> = [];\n for (const ext of this.#extensions.values()) {\n if (!ext.manifest.context) continue;\n const prefix = sanitizeName(ext.manifest.name);\n for (const ctx of ext.manifest.context) {\n result.push({\n extName: ext.manifest.name,\n label: `${prefix}_${ctx.label}`\n });\n }\n }\n return result;\n }\n\n /**\n * Get extension manifest by name.\n */\n getManifest(name: string): ExtensionManifest | null {\n return this.#extensions.get(name)?.manifest ?? null;\n }\n\n /**\n * Get extensions that subscribe to a specific hook, in load order.\n */\n getHookSubscribers(\n hookName: string\n ): Array<{ name: string; entrypoint: ExtensionEntrypoint }> {\n const result: Array<{ name: string; entrypoint: ExtensionEntrypoint }> = [];\n for (const ext of this.#extensions.values()) {\n if (ext.hooks.includes(hookName)) {\n result.push({ name: ext.manifest.name, entrypoint: ext.entrypoint });\n }\n }\n return result;\n }\n\n /**\n * List all loaded extensions.\n */\n list(): ExtensionInfo[] {\n return [...this.#extensions.values()].map((ext) =>\n toExtensionInfo(ext.manifest, ext.tools)\n );\n }\n\n /**\n * Get AI SDK tools from all loaded extensions.\n *\n * Tool names are prefixed with the sanitized extension name to avoid\n * collisions: e.g. extension \"github\" with tool \"create_pr\" → \"github_create_pr\".\n */\n getTools(): ToolSet {\n const tools: ToolSet = {};\n\n for (const ext of this.#extensions.values()) {\n const prefix = sanitizeName(ext.manifest.name);\n\n for (const descriptor of ext.tools) {\n const toolName = `${prefix}_${descriptor.name}`;\n\n tools[toolName] = tool({\n description: `[${ext.manifest.name}] ${descriptor.description}`,\n inputSchema: jsonSchema(\n descriptor.inputSchema as Record<string, unknown>\n ),\n execute: async (args: Record<string, unknown>) => {\n if (!this.#extensions.has(ext.manifest.name)) {\n throw new Error(\n `Extension \"${ext.manifest.name}\" has been unloaded. Tool \"${toolName}\" is no longer available.`\n );\n }\n const resultJson = await ext.entrypoint.execute(\n descriptor.name,\n JSON.stringify(args)\n );\n const parsed = JSON.parse(resultJson) as {\n result?: unknown;\n error?: string;\n };\n if (parsed.error) throw new Error(parsed.error);\n return parsed.result;\n }\n });\n }\n }\n\n return tools;\n }\n}\n\nfunction toExtensionInfo(\n manifest: ExtensionManifest,\n tools: ExtensionToolDescriptor[]\n): ExtensionInfo {\n const prefix = sanitizeName(manifest.name);\n return {\n name: manifest.name,\n version: manifest.version,\n description: manifest.description,\n tools: tools.map((t) => `${prefix}_${t.name}`),\n contextLabels: (manifest.context ?? []).map((c) => `${prefix}_${c.label}`),\n permissions: manifest.permissions ?? {}\n };\n}\n\n/**\n * Wrap an extension source in a Worker module that exposes\n * describe(), execute(), manifest(), and hook RPC methods.\n *\n * Source format: `({ tools: {...}, hooks: {...} })`\n * Both `tools` and `hooks` are optional.\n */\nfunction wrapExtensionSource(source: string): string {\n return `import { WorkerEntrypoint } from \"cloudflare:workers\";\n\nconst __ext = (${source});\nif (__ext && typeof __ext === \"object\" && !(\"tools\" in __ext) && !(\"hooks\" in __ext)) {\n throw new Error(\n \"Invalid extension source format. Expected { tools: {...}, hooks: {...} } \" +\n \"but got a flat object. Wrap your tools in a 'tools' key.\"\n );\n}\nconst __tools = __ext.tools || {};\nconst __hooks = __ext.hooks || {};\n\nexport default class Extension extends WorkerEntrypoint {\n describe() {\n const descriptors = [];\n for (const [name, def] of Object.entries(__tools)) {\n descriptors.push({\n name,\n description: def.description || name,\n inputSchema: {\n type: \"object\",\n properties: def.parameters || {},\n required: def.required || []\n }\n });\n }\n return JSON.stringify(descriptors);\n }\n\n manifest() {\n return JSON.stringify({\n hooks: Object.keys(__hooks)\n });\n }\n\n async execute(toolName, argsJson) {\n const def = __tools[toolName];\n if (!def || !def.execute) {\n return JSON.stringify({ error: \"Unknown tool: \" + toolName });\n }\n try {\n const args = JSON.parse(argsJson);\n const result = await def.execute(args, this.env.host ?? null);\n return JSON.stringify({ result });\n } catch (err) {\n return JSON.stringify({ error: err.message || String(err) });\n }\n }\n\n async hook(name, ctxSnapshot) {\n const fn = __hooks[name];\n if (!fn) return JSON.stringify({ skipped: true });\n try {\n // Hook handlers receive (ctxSnapshot, host) — symmetric with tool\n // executes. \\`host\\` is null when the extension was loaded without\n // host-requiring permissions or when the worker entry point doesn't\n // re-export HostBridgeLoopback.\n const result = await fn(ctxSnapshot, this.env.host ?? null);\n return JSON.stringify({ result: result ?? {} });\n } catch (err) {\n return JSON.stringify({ error: err.message || String(err) });\n }\n }\n}\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,SAAgB,aAAa,MAAsB;CACjD,IAAI,CAAC,QAAQ,KAAK,KAAK,CAAC,CAAC,WAAW,GAClC,MAAM,IAAI,MAAM,kCAAkC;CAEpD,OAAO,KACJ,QAAQ,iBAAiB,GAAG,CAAC,CAC7B,QAAQ,OAAO,GAAG,CAAC,CACnB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