@cloudflare/think 0.5.2 → 0.6.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.
@@ -1 +1 @@
1
- {"version":3,"file":"browser.js","names":[],"sources":["../../src/tools/browser.ts"],"sourcesContent":["import type { ToolSet } from \"ai\";\nimport {\n createBrowserToolHandlers,\n SEARCH_DESCRIPTION,\n EXECUTE_DESCRIPTION\n} from \"agents/browser\";\nimport { tool } from \"ai\";\nimport { z } from \"zod\";\n\nexport interface CreateBrowserToolsOptions {\n /**\n * Browser Rendering binding (Fetcher).\n *\n * This is the primary way to connect — works both locally in\n * `wrangler dev` and when deployed to Cloudflare Workers.\n *\n * Requires `\"browser\": { \"binding\": \"BROWSER\" }` in wrangler.jsonc.\n */\n browser?: Fetcher;\n\n /**\n * Optional CDP base URL override (e.g. `http://localhost:9222`).\n *\n * Use when connecting to a manually managed Chrome instance or\n * a remote CDP endpoint behind a tunnel.\n */\n cdpUrl?: string;\n\n /**\n * Headers to send with CDP URL discovery requests.\n * Useful when the CDP endpoint requires authentication\n * (e.g. Cloudflare Access headers).\n */\n cdpHeaders?: Record<string, string>;\n\n /**\n * WorkerLoader binding for sandboxed code execution.\n *\n * Requires `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` in wrangler.jsonc.\n */\n loader: WorkerLoader;\n\n /**\n * Execution timeout in milliseconds. Defaults to 30000 (30s).\n */\n timeout?: number;\n}\n\n/**\n * Create browser automation tools for Think agents.\n *\n * Returns a `ToolSet` with two tools:\n *\n * - **`browser_search`** — query the Chrome DevTools Protocol spec\n * to discover commands, events, and types. The LLM writes JavaScript\n * that runs against a cached, normalized copy of the protocol.\n *\n * - **`browser_execute`** — run CDP commands against a live browser\n * session. Each call opens a fresh session, exposes a `cdp` helper,\n * and closes the session on completion.\n *\n * Both tools use the code-mode pattern: the LLM writes JavaScript\n * async arrow functions that execute in a sandboxed Worker isolate.\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.6\");\n * }\n *\n * getTools() {\n * return {\n * ...createBrowserTools({\n * browser: this.env.BROWSER,\n * loader: this.env.LOADER,\n * }),\n * };\n * }\n * }\n * ```\n */\nexport function createBrowserTools(\n options: CreateBrowserToolsOptions\n): ToolSet {\n const handlers = createBrowserToolHandlers({\n browser: options.browser,\n cdpUrl: options.cdpUrl,\n cdpHeaders: options.cdpHeaders,\n loader: options.loader,\n timeout: options.timeout\n });\n\n return {\n browser_search: tool({\n description: SEARCH_DESCRIPTION,\n inputSchema: z.object({\n code: z\n .string()\n .describe(\"JavaScript async arrow function that queries the CDP spec\")\n }),\n execute: async ({ code }) => {\n const result = await handlers.search(code);\n if (result.isError) {\n throw new Error(result.text);\n }\n return result.text;\n }\n }),\n\n browser_execute: tool({\n description: EXECUTE_DESCRIPTION,\n inputSchema: z.object({\n code: z\n .string()\n .describe(\"JavaScript async arrow function that uses the cdp helper\")\n }),\n execute: async ({ code }) => {\n const result = await handlers.execute(code);\n if (result.isError) {\n throw new Error(result.text);\n }\n return result.text;\n }\n })\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqFA,SAAgB,mBACd,SACS;CACT,MAAM,WAAW,0BAA0B;EACzC,SAAS,QAAQ;EACjB,QAAQ,QAAQ;EAChB,YAAY,QAAQ;EACpB,QAAQ,QAAQ;EAChB,SAAS,QAAQ;EAClB,CAAC;AAEF,QAAO;EACL,gBAAgB,KAAK;GACnB,aAAa;GACb,aAAa,EAAE,OAAO,EACpB,MAAM,EACH,QAAQ,CACR,SAAS,4DAA4D,EACzE,CAAC;GACF,SAAS,OAAO,EAAE,WAAW;IAC3B,MAAM,SAAS,MAAM,SAAS,OAAO,KAAK;AAC1C,QAAI,OAAO,QACT,OAAM,IAAI,MAAM,OAAO,KAAK;AAE9B,WAAO,OAAO;;GAEjB,CAAC;EAEF,iBAAiB,KAAK;GACpB,aAAa;GACb,aAAa,EAAE,OAAO,EACpB,MAAM,EACH,QAAQ,CACR,SAAS,2DAA2D,EACxE,CAAC;GACF,SAAS,OAAO,EAAE,WAAW;IAC3B,MAAM,SAAS,MAAM,SAAS,QAAQ,KAAK;AAC3C,QAAI,OAAO,QACT,OAAM,IAAI,MAAM,OAAO,KAAK;AAE9B,WAAO,OAAO;;GAEjB,CAAC;EACH"}
1
+ {"version":3,"file":"browser.js","names":[],"sources":["../../src/tools/browser.ts"],"sourcesContent":["import type { ToolSet } from \"ai\";\nimport {\n createBrowserToolHandlers,\n SEARCH_DESCRIPTION,\n EXECUTE_DESCRIPTION\n} from \"agents/browser\";\nimport { tool } from \"ai\";\nimport { z } from \"zod\";\n\nexport interface CreateBrowserToolsOptions {\n /**\n * Browser Rendering binding (Fetcher).\n *\n * This is the primary way to connect — works both locally in\n * `wrangler dev` and when deployed to Cloudflare Workers.\n *\n * Requires `\"browser\": { \"binding\": \"BROWSER\" }` in wrangler.jsonc.\n */\n browser?: Fetcher;\n\n /**\n * Optional CDP base URL override (e.g. `http://localhost:9222`).\n *\n * Use when connecting to a manually managed Chrome instance or\n * a remote CDP endpoint behind a tunnel.\n */\n cdpUrl?: string;\n\n /**\n * Headers to send with CDP URL discovery requests.\n * Useful when the CDP endpoint requires authentication\n * (e.g. Cloudflare Access headers).\n */\n cdpHeaders?: Record<string, string>;\n\n /**\n * WorkerLoader binding for sandboxed code execution.\n *\n * Requires `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` in wrangler.jsonc.\n */\n loader: WorkerLoader;\n\n /**\n * Execution timeout in milliseconds. Defaults to 30000 (30s).\n */\n timeout?: number;\n}\n\n/**\n * Create browser automation tools for Think agents.\n *\n * Returns a `ToolSet` with two tools:\n *\n * - **`browser_search`** — query the Chrome DevTools Protocol spec\n * to discover commands, events, and types. The LLM writes JavaScript\n * that runs against a cached, normalized copy of the protocol.\n *\n * - **`browser_execute`** — run CDP commands against a live browser\n * session. Each call opens a fresh session, exposes a `cdp` helper,\n * and closes the session on completion.\n *\n * Both tools use the code-mode pattern: the LLM writes JavaScript\n * async arrow functions that execute in a sandboxed Worker isolate.\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.6\");\n * }\n *\n * getTools() {\n * return {\n * ...createBrowserTools({\n * browser: this.env.BROWSER,\n * loader: this.env.LOADER,\n * }),\n * };\n * }\n * }\n * ```\n */\nexport function createBrowserTools(\n options: CreateBrowserToolsOptions\n): ToolSet {\n const handlers = createBrowserToolHandlers({\n browser: options.browser,\n cdpUrl: options.cdpUrl,\n cdpHeaders: options.cdpHeaders,\n loader: options.loader,\n timeout: options.timeout\n });\n\n return {\n browser_search: tool({\n description: SEARCH_DESCRIPTION,\n inputSchema: z.object({\n code: z\n .string()\n .describe(\"JavaScript async arrow function that queries the CDP spec\")\n }),\n execute: async ({ code }) => {\n const result = await handlers.search(code);\n if (result.isError) {\n throw new Error(result.text);\n }\n return result.text;\n }\n }),\n\n browser_execute: tool({\n description: EXECUTE_DESCRIPTION,\n inputSchema: z.object({\n code: z\n .string()\n .describe(\"JavaScript async arrow function that uses the cdp helper\")\n }),\n execute: async ({ code }) => {\n const result = await handlers.execute(code);\n if (result.isError) {\n throw new Error(result.text);\n }\n return result.text;\n }\n })\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqFA,SAAgB,mBACd,SACS;CACT,MAAM,WAAW,0BAA0B;EACzC,SAAS,QAAQ;EACjB,QAAQ,QAAQ;EAChB,YAAY,QAAQ;EACpB,QAAQ,QAAQ;EAChB,SAAS,QAAQ;EAClB,CAAC;CAEF,OAAO;EACL,gBAAgB,KAAK;GACnB,aAAa;GACb,aAAa,EAAE,OAAO,EACpB,MAAM,EACH,QAAQ,CACR,SAAS,4DAA4D,EACzE,CAAC;GACF,SAAS,OAAO,EAAE,WAAW;IAC3B,MAAM,SAAS,MAAM,SAAS,OAAO,KAAK;IAC1C,IAAI,OAAO,SACT,MAAM,IAAI,MAAM,OAAO,KAAK;IAE9B,OAAO,OAAO;;GAEjB,CAAC;EAEF,iBAAiB,KAAK;GACpB,aAAa;GACb,aAAa,EAAE,OAAO,EACpB,MAAM,EACH,QAAQ,CACR,SAAS,2DAA2D,EACxE,CAAC;GACF,SAAS,OAAO,EAAE,WAAW;IAC3B,MAAM,SAAS,MAAM,SAAS,QAAQ,KAAK;IAC3C,IAAI,OAAO,SACT,MAAM,IAAI,MAAM,OAAO,KAAK;IAE9B,OAAO,OAAO;;GAEjB,CAAC;EACH"}
@@ -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;AACJ,KAAI,QAAQ,SACV,YAAW,QAAQ;UACV,QAAQ,OACjB,YAAW,IAAI,sBAAsB;EACnC,QAAQ,QAAQ;EAChB,SAAS,QAAQ;EACjB,gBAAgB,QAAQ;EACzB,CAAC;KAEF,OAAM,IAAI,MACR,wFACD;CAGH,MAAM,YAA4B,CAChC,EAAE,OAAO,EACT,GAAI,QAAQ,aAAa,EAAE,CAC5B;AACD,KAAI,MACF,WAAU,KAAK,sBAAsB,MAAM,CAAC;AAG9C,QAAO,eAAe;EAAE,OAAO;EAAW;EAAU;EAAa,CAAC"}
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;EACzB,CAAC;MAEF,MAAM,IAAI,MACR,wFACD;CAGH,MAAM,YAA4B,CAChC,EAAE,OAAO,EACT,GAAI,QAAQ,aAAa,EAAE,CAC5B;CACD,IAAI,OACF,UAAU,KAAK,sBAAsB,MAAM,CAAC;CAG9C,OAAO,eAAe;EAAE,OAAO;EAAW;EAAU;EAAa,CAAC"}
@@ -1,4 +1,4 @@
1
- import { r as sanitizeName } from "../manager-DDC3Gb0V.js";
1
+ import { r as sanitizeName } from "../manager-BypfrNX0.js";
2
2
  import { tool } from "ai";
3
3
  import { z } from "zod";
4
4
  //#region src/tools/extensions.ts
@@ -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;AAEpB,QAAO;EACL,gBAAgB,KAAK;GACnB,aACE;GAYF,aAAa,EAAE,OAAO;IACpB,MAAM,EAAE,QAAQ,CAAC,SAAS,gCAAgC;IAC1D,SAAS,EAAE,QAAQ,CAAC,SAAS,gCAAgC;IAC7D,aAAa,EACV,QAAQ,CACR,UAAU,CACV,SAAS,6BAA6B;IACzC,QAAQ,EACL,QAAQ,CACR,SACC,0RAQD;IACH,kBAAkB,EACf,KAAK;KAAC;KAAQ;KAAQ;KAAa,CAAC,CACpC,UAAU,CACV,SAAS,2DAA2D;IACvE,SAAS,EACN,MAAM,EAAE,QAAQ,CAAC,CACjB,UAAU,CACV,SACC,8DACD;IACJ,CAAC;GACF,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;MACD;KACF,EACD,OACD;AACD,WAAO;KACL,QAAQ;KACR,MAAM,KAAK;KACX,QAAQ,aAAa,KAAK;KAC1B,SAAS,KAAK;KACd,OAAO,KAAK;KACZ,SAAS,cAAc,KAAK,2EAA2E,KAAK,MAAM,KAAK,KAAK,CAAC;KAC9H;;GAEJ,CAAC;EAEF,iBAAiB,KAAK;GACpB,aAAa;GACb,aAAa,EAAE,OAAO,EAAE,CAAC;GACzB,SAAS,YAAY;IACnB,MAAM,aAAa,QAAQ,MAAM;AACjC,WAAO;KACL,OAAO,WAAW;KAClB,YAAY,WAAW,KAAK,SAAS;MACnC,MAAM,IAAI;MACV,SAAS,IAAI;MACb,aAAa,IAAI;MACjB,OAAO,IAAI;MACX,aAAa,IAAI;MAClB,EAAE;KACJ;;GAEJ,CAAC;EACH"}
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;GAYF,aAAa,EAAE,OAAO;IACpB,MAAM,EAAE,QAAQ,CAAC,SAAS,gCAAgC;IAC1D,SAAS,EAAE,QAAQ,CAAC,SAAS,gCAAgC;IAC7D,aAAa,EACV,QAAQ,CACR,UAAU,CACV,SAAS,6BAA6B;IACzC,QAAQ,EACL,QAAQ,CACR,SACC,0RAQD;IACH,kBAAkB,EACf,KAAK;KAAC;KAAQ;KAAQ;KAAa,CAAC,CACpC,UAAU,CACV,SAAS,2DAA2D;IACvE,SAAS,EACN,MAAM,EAAE,QAAQ,CAAC,CACjB,UAAU,CACV,SACC,8DACD;IACJ,CAAC;GACF,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;MACD;KACF,EACD,OACD;IACD,OAAO;KACL,QAAQ;KACR,MAAM,KAAK;KACX,QAAQ,aAAa,KAAK;KAC1B,SAAS,KAAK;KACd,OAAO,KAAK;KACZ,SAAS,cAAc,KAAK,2EAA2E,KAAK,MAAM,KAAK,KAAK,CAAC;KAC9H;;GAEJ,CAAC;EAEF,iBAAiB,KAAK;GACpB,aAAa;GACb,aAAa,EAAE,OAAO,EAAE,CAAC;GACzB,SAAS,YAAY;IACnB,MAAM,aAAa,QAAQ,MAAM;IACjC,OAAO;KACL,OAAO,WAAW;KAClB,YAAY,WAAW,KAAK,SAAS;MACnC,MAAM,IAAI;MACV,SAAS,IAAI;MACb,aAAa,IAAI;MACjB,OAAO,IAAI;MACX,aAAa,IAAI;MAClB,EAAE;KACJ;;GAEJ,CAAC;EACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"sandbox.js","names":[],"sources":["../../src/tools/sandbox.ts"],"sourcesContent":["import type { ToolSet } from \"ai\";\n\nlet warned = false;\n\nexport interface CreateSandboxToolsOptions {\n /**\n * Execution timeout in milliseconds. Defaults to 30000 (30s).\n */\n timeout?: number;\n}\n\n/**\n * Create sandbox tools for Think agents.\n *\n * Sandbox tools provide isolated execution environments configured\n * per-agent with toolchains, repos, and snapshots.\n *\n * **Not yet implemented** — this export returns an empty `ToolSet` so\n * that `...createSandboxTools(env.SANDBOX)` compiles and spreads\n * harmlessly. A warning is logged at creation time.\n *\n * @example\n * ```ts\n * import { Think } from \"@cloudflare/think\";\n * import { createSandboxTools } from \"@cloudflare/think/tools/sandbox\";\n *\n * export class MyAgent extends Think<Env> {\n * getTools() {\n * return {\n * ...createSandboxTools(this.env.SANDBOX),\n * };\n * }\n * }\n * ```\n */\nexport function createSandboxTools(\n _binding?: unknown,\n _options?: CreateSandboxToolsOptions\n): ToolSet {\n if (!warned) {\n warned = true;\n console.warn(\n \"[@cloudflare/think] createSandboxTools is not yet implemented. \" +\n \"No tools will be registered.\"\n );\n }\n\n return {};\n}\n"],"mappings":";AAEA,IAAI,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;AAiCb,SAAgB,mBACd,UACA,UACS;AACT,KAAI,CAAC,QAAQ;AACX,WAAS;AACT,UAAQ,KACN,8FAED;;AAGH,QAAO,EAAE"}
1
+ {"version":3,"file":"sandbox.js","names":[],"sources":["../../src/tools/sandbox.ts"],"sourcesContent":["import type { ToolSet } from \"ai\";\n\nlet warned = false;\n\nexport interface CreateSandboxToolsOptions {\n /**\n * Execution timeout in milliseconds. Defaults to 30000 (30s).\n */\n timeout?: number;\n}\n\n/**\n * Create sandbox tools for Think agents.\n *\n * Sandbox tools provide isolated execution environments configured\n * per-agent with toolchains, repos, and snapshots.\n *\n * **Not yet implemented** — this export returns an empty `ToolSet` so\n * that `...createSandboxTools(env.SANDBOX)` compiles and spreads\n * harmlessly. A warning is logged at creation time.\n *\n * @example\n * ```ts\n * import { Think } from \"@cloudflare/think\";\n * import { createSandboxTools } from \"@cloudflare/think/tools/sandbox\";\n *\n * export class MyAgent extends Think<Env> {\n * getTools() {\n * return {\n * ...createSandboxTools(this.env.SANDBOX),\n * };\n * }\n * }\n * ```\n */\nexport function createSandboxTools(\n _binding?: unknown,\n _options?: CreateSandboxToolsOptions\n): ToolSet {\n if (!warned) {\n warned = true;\n console.warn(\n \"[@cloudflare/think] createSandboxTools is not yet implemented. \" +\n \"No tools will be registered.\"\n );\n }\n\n return {};\n}\n"],"mappings":";AAEA,IAAI,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;AAiCb,SAAgB,mBACd,UACA,UACS;CACT,IAAI,CAAC,QAAQ;EACX,SAAS;EACT,QAAQ,KACN,8FAED;;CAGH,OAAO,EAAE"}
@@ -119,17 +119,30 @@ function createReadTool(options) {
119
119
  });
120
120
  },
121
121
  toModelOutput: async ({ input, output }) => {
122
- if ("error" in output) return {
122
+ const replayOutput = output;
123
+ if (!isRecord(replayOutput)) return {
124
+ type: "text",
125
+ value: String(replayOutput)
126
+ };
127
+ if (typeof replayOutput.error === "string") return {
123
128
  type: "error-text",
124
- value: output.error
129
+ value: replayOutput.error
125
130
  };
126
- if ("content" in output) return {
131
+ if (typeof replayOutput.content === "string") return {
127
132
  type: "text",
128
- value: output.content
133
+ value: replayOutput.content
134
+ };
135
+ if (replayOutput.kind === "binary") return {
136
+ type: "json",
137
+ value: toJSONValue(replayOutput)
138
+ };
139
+ if (!isModelFileReadOutput(replayOutput)) return {
140
+ type: "json",
141
+ value: toJSONValue(replayOutput)
129
142
  };
130
- if (output.kind === "binary") return {
143
+ if (!isReadToolInput(input)) return {
131
144
  type: "json",
132
- value: output
145
+ value: toJSONValue(replayOutput)
133
146
  };
134
147
  const bytes = await ops.readFileBytes(input.path);
135
148
  if (bytes === null) return {
@@ -138,11 +151,11 @@ function createReadTool(options) {
138
151
  };
139
152
  if (bytes.byteLength > MAX_MODEL_FILE_BYTES) return {
140
153
  type: "error-text",
141
- value: `Read ${output.path} (${output.mediaType}, ${formatSize(bytes.byteLength)}), but it exceeds the ${formatSize(MAX_MODEL_FILE_BYTES)} inline model output limit.`
154
+ value: `Read ${replayOutput.path} (${replayOutput.mediaType}, ${formatSize(bytes.byteLength)}), but it exceeds the ${formatSize(MAX_MODEL_FILE_BYTES)} inline model output limit.`
142
155
  };
143
156
  const data = uint8ArrayToBase64(bytes);
144
- const note = `Read ${output.path} (${output.mediaType}, ${formatSize(bytes.byteLength)}).`;
145
- if (output.kind === "image") return {
157
+ const note = `Read ${replayOutput.path} (${replayOutput.mediaType}, ${formatSize(bytes.byteLength)}).`;
158
+ if (replayOutput.kind === "image") return {
146
159
  type: "content",
147
160
  value: [{
148
161
  type: "text",
@@ -150,7 +163,7 @@ function createReadTool(options) {
150
163
  }, {
151
164
  type: "image-data",
152
165
  data,
153
- mediaType: output.mediaType
166
+ mediaType: replayOutput.mediaType
154
167
  }]
155
168
  };
156
169
  return {
@@ -161,13 +174,30 @@ function createReadTool(options) {
161
174
  }, {
162
175
  type: "file-data",
163
176
  data,
164
- mediaType: output.mediaType,
165
- filename: output.name
177
+ mediaType: replayOutput.mediaType,
178
+ filename: replayOutput.name
166
179
  }]
167
180
  };
168
181
  }
169
182
  });
170
183
  }
184
+ function isRecord(value) {
185
+ return value !== null && typeof value === "object" && !Array.isArray(value);
186
+ }
187
+ function isModelFileReadOutput(value) {
188
+ return (value.kind === "image" || value.kind === "file") && typeof value.path === "string" && typeof value.name === "string" && typeof value.mediaType === "string";
189
+ }
190
+ function isReadToolInput(value) {
191
+ return isRecord(value) && typeof value.path === "string";
192
+ }
193
+ function toJSONValue(value) {
194
+ try {
195
+ const json = JSON.stringify(value);
196
+ return json === void 0 ? null : JSON.parse(json);
197
+ } catch {
198
+ return String(value);
199
+ }
200
+ }
171
201
  function readTextWithLineNumbers({ ops, path, offset, limit }) {
172
202
  return Promise.resolve(ops.readFile(path)).then((content) => {
173
203
  if (content === null) return { error: `Could not read file: ${path}` };
@@ -1 +1 @@
1
- {"version":3,"file":"workspace.js","names":[],"sources":["../../src/tools/workspace.ts"],"sourcesContent":["import type { Workspace, FileInfo } from \"@cloudflare/shell\";\nimport { tool } from \"ai\";\nimport { z } from \"zod\";\n\n// ── WorkspaceLike ─────────────────────────────────────────────────\n//\n// Minimum workspace surface that Think's internals rely on. Covers the\n// methods called by `createWorkspaceTools()` below plus the handful\n// Think itself uses (`readFile`/`writeFile`/`readDir`/`rm` in\n// `think.ts`). The read tool also needs `readFileBytes` so image/PDF\n// reads can be rehydrated as AI SDK multimodal content. A concrete\n// `Workspace` from `@cloudflare/shell` satisfies this; so do custom\n// implementations like the `SharedWorkspace` proxy in `examples/assistant`\n// that forwards to a parent DO.\n//\n// Consumers who reach for the fuller filesystem API (e.g.\n// `createWorkspaceStateBackend` for codemode's `state.*` in a sandbox)\n// still need a concrete `Workspace`.\n//\n// @experimental The API surface may change before stabilizing.\n\nexport type WorkspaceLike = Pick<\n Workspace,\n | \"readFile\"\n | \"readFileBytes\"\n | \"writeFile\"\n | \"readDir\"\n | \"rm\"\n | \"glob\"\n | \"mkdir\"\n | \"stat\"\n>;\n\n// ── Operations interfaces ─────────────────────────────────────────\n// Abstractions over file I/O so the same tools can work against\n// Workspace, a local filesystem, or anything else.\n\nexport interface ReadOperations {\n readFile(path: string): Promise<string | null>;\n readFileBytes(path: string): Promise<Uint8Array | null>;\n stat(path: string): Promise<FileInfo | null> | FileInfo | null;\n}\n\nexport interface WriteOperations {\n writeFile(path: string, content: string): Promise<void>;\n mkdir(path: string, opts?: { recursive?: boolean }): Promise<void> | void;\n}\n\nexport interface EditOperations {\n readFile(path: string): Promise<string | null>;\n writeFile(path: string, content: string): Promise<void>;\n}\n\nexport interface ListOperations {\n readDir(\n dir: string,\n opts?: { limit?: number; offset?: number }\n ): Promise<FileInfo[]> | FileInfo[];\n}\n\nexport interface FindOperations {\n glob(pattern: string): Promise<FileInfo[]> | FileInfo[];\n}\n\nexport interface DeleteOperations {\n rm(\n path: string,\n opts?: { recursive?: boolean; force?: boolean }\n ): Promise<void>;\n}\n\nexport interface GrepOperations {\n glob(pattern: string): Promise<FileInfo[]> | FileInfo[];\n readFile(path: string): Promise<string | null>;\n}\n\n// ── Workspace-backed operation factories ──────────────────────────\n\nfunction workspaceReadOps(ws: WorkspaceLike): ReadOperations {\n return {\n readFile: (path) => ws.readFile(path),\n readFileBytes: (path) => ws.readFileBytes(path),\n stat: (path) => ws.stat(path)\n };\n}\n\nfunction workspaceWriteOps(ws: WorkspaceLike): WriteOperations {\n return {\n writeFile: (path, content) => ws.writeFile(path, content),\n mkdir: (path, opts) => ws.mkdir(path, opts)\n };\n}\n\nfunction workspaceEditOps(ws: WorkspaceLike): EditOperations {\n return {\n readFile: (path) => ws.readFile(path),\n writeFile: (path, content) => ws.writeFile(path, content)\n };\n}\n\nfunction workspaceListOps(ws: WorkspaceLike): ListOperations {\n return {\n readDir: (dir, opts) => ws.readDir(dir, opts)\n };\n}\n\nfunction workspaceFindOps(ws: WorkspaceLike): FindOperations {\n return {\n glob: (pattern) => ws.glob(pattern)\n };\n}\n\nfunction workspaceDeleteOps(ws: WorkspaceLike): DeleteOperations {\n return {\n rm: (path, opts) => ws.rm(path, opts)\n };\n}\n\nfunction workspaceGrepOps(ws: WorkspaceLike): GrepOperations {\n return {\n glob: (pattern) => ws.glob(pattern),\n readFile: (path) => ws.readFile(path)\n };\n}\n\n/**\n * Create a complete set of AI SDK tools backed by a workspace.\n *\n * Accepts either a concrete `Workspace` from `@cloudflare/shell` or any\n * `WorkspaceLike` implementation — e.g. a proxy that forwards calls to a\n * shared workspace owned by a parent DO.\n *\n * ```ts\n * import { Workspace } from \"@cloudflare/shell\";\n * import { createWorkspaceTools } from \"@cloudflare/think\";\n *\n * class MyAgent extends Agent<Env> {\n * workspace = new Workspace({ sql: this.ctx.storage.sql, name: () => this.name });\n *\n * async onChatMessage() {\n * const tools = createWorkspaceTools(this.workspace);\n * const result = streamText({ model, tools, messages });\n * return result.toUIMessageStreamResponse();\n * }\n * }\n * ```\n */\nexport function createWorkspaceTools(workspace: WorkspaceLike) {\n return {\n read: createReadTool({ ops: workspaceReadOps(workspace) }),\n write: createWriteTool({ ops: workspaceWriteOps(workspace) }),\n edit: createEditTool({ ops: workspaceEditOps(workspace) }),\n list: createListTool({ ops: workspaceListOps(workspace) }),\n find: createFindTool({ ops: workspaceFindOps(workspace) }),\n grep: createGrepTool({ ops: workspaceGrepOps(workspace) }),\n delete: createDeleteTool({ ops: workspaceDeleteOps(workspace) })\n };\n}\n\n// ── Read ────────────────────────────────────────────────────────────\n\nconst MAX_LINES = 2000;\nconst MAX_LINE_LENGTH = 2000;\nconst MAX_MODEL_FILE_BYTES = 3.5 * 1024 * 1024;\n\ntype TextReadToolOutput = {\n path: string;\n content: string;\n totalLines: number;\n fromLine?: number;\n toLine?: number;\n};\n\ntype ImageReadToolOutput = {\n kind: \"image\";\n path: string;\n name: string;\n mediaType: string;\n sizeBytes: number;\n};\n\ntype FileReadToolOutput = {\n kind: \"file\";\n path: string;\n name: string;\n mediaType: string;\n sizeBytes: number;\n};\n\ntype BinaryReadToolOutput = {\n kind: \"binary\";\n path: string;\n name: string;\n mediaType: string;\n sizeBytes: number;\n unsupported: true;\n};\n\ntype ReadToolError = { error: string };\n\ntype ReadToolOutput =\n | TextReadToolOutput\n | ImageReadToolOutput\n | FileReadToolOutput\n | BinaryReadToolOutput\n | ReadToolError;\n\nexport interface ReadToolOptions {\n ops: ReadOperations;\n}\n\nexport function createReadTool(options: ReadToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Read a workspace file. Text files return line-numbered content. \" +\n \"Images and PDFs are passed to capable models as file content. \" +\n \"Use offset and limit for large text files. Returns null if the file does not exist.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file\"),\n offset: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(\"1-indexed line number to start reading from\"),\n limit: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(\"Number of lines to read\")\n }),\n execute: async ({ path, offset, limit }): Promise<ReadToolOutput> => {\n const stat = await ops.stat(path);\n if (!stat) {\n return { error: `File not found: ${path}` };\n }\n if (stat.type === \"directory\") {\n return { error: `${path} is a directory, not a file` };\n }\n\n const mediaType = await detectWorkspaceMediaType({ ops, path, stat });\n\n if (mediaType.startsWith(\"image/\")) {\n return {\n kind: \"image\",\n path,\n name: stat.name,\n mediaType,\n sizeBytes: stat.size\n };\n }\n\n if (mediaType === \"application/pdf\") {\n return {\n kind: \"file\",\n path,\n name: stat.name,\n mediaType,\n sizeBytes: stat.size\n };\n }\n\n if (!isTextMediaType(mediaType)) {\n return {\n kind: \"binary\",\n path,\n name: stat.name,\n mediaType,\n sizeBytes: stat.size,\n unsupported: true\n };\n }\n\n return readTextWithLineNumbers({ ops, path, offset, limit });\n },\n toModelOutput: async ({ input, output }) => {\n if (\"error\" in output) {\n return { type: \"error-text\", value: output.error };\n }\n\n if (\"content\" in output) {\n return { type: \"text\", value: output.content };\n }\n\n if (output.kind === \"binary\") {\n return {\n type: \"json\",\n value: output\n };\n }\n\n const bytes = await ops.readFileBytes(input.path);\n if (bytes === null) {\n return {\n type: \"error-text\",\n value: `Could not read file bytes: ${input.path}`\n };\n }\n if (bytes.byteLength > MAX_MODEL_FILE_BYTES) {\n return {\n type: \"error-text\",\n value:\n `Read ${output.path} (${output.mediaType}, ${formatSize(bytes.byteLength)}), ` +\n `but it exceeds the ${formatSize(MAX_MODEL_FILE_BYTES)} inline model output limit.`\n };\n }\n\n const data = uint8ArrayToBase64(bytes);\n const note = `Read ${output.path} (${output.mediaType}, ${formatSize(bytes.byteLength)}).`;\n\n if (output.kind === \"image\") {\n return {\n type: \"content\",\n value: [\n { type: \"text\", text: note },\n { type: \"image-data\", data, mediaType: output.mediaType }\n ]\n };\n }\n\n return {\n type: \"content\",\n value: [\n { type: \"text\", text: note },\n {\n type: \"file-data\",\n data,\n mediaType: output.mediaType,\n filename: output.name\n }\n ]\n };\n }\n });\n}\n\nfunction readTextWithLineNumbers({\n ops,\n path,\n offset,\n limit\n}: {\n ops: ReadOperations;\n path: string;\n offset?: number;\n limit?: number;\n}): Promise<TextReadToolOutput | ReadToolError> {\n return Promise.resolve(ops.readFile(path)).then((content) => {\n if (content === null) {\n return { error: `Could not read file: ${path}` };\n }\n\n const allLines = content.split(\"\\n\");\n const totalLines = allLines.length;\n\n // Apply offset/limit\n const startLine = offset ? offset - 1 : 0;\n const endLine = limit ? startLine + limit : allLines.length;\n const lines = allLines.slice(startLine, endLine);\n\n // Format with line numbers, truncate long lines\n const numbered = lines.map((line, i) => {\n const lineNum = startLine + i + 1;\n const truncated =\n line.length > MAX_LINE_LENGTH\n ? line.slice(0, MAX_LINE_LENGTH) + \"... (truncated)\"\n : line;\n return `${lineNum}\\t${truncated}`;\n });\n\n // Truncate if too many lines\n let output: string;\n if (numbered.length > MAX_LINES) {\n output =\n numbered.slice(0, MAX_LINES).join(\"\\n\") +\n `\\n... (${numbered.length - MAX_LINES} more lines truncated)`;\n } else {\n output = numbered.join(\"\\n\");\n }\n\n const result: TextReadToolOutput = {\n path,\n content: output,\n totalLines\n };\n\n if (offset || limit) {\n result.fromLine = startLine + 1;\n result.toLine = Math.min(endLine, totalLines);\n }\n\n return result;\n });\n}\n\nasync function detectWorkspaceMediaType({\n ops,\n path,\n stat\n}: {\n ops: ReadOperations;\n path: string;\n stat: FileInfo;\n}): Promise<string> {\n const statMime = normalizeMediaType(stat.mimeType);\n if (statMime && !isGenericMediaType(statMime)) {\n return statMime;\n }\n\n const bytes = await ops.readFileBytes(path);\n if (bytes === null) {\n return statMime || \"application/octet-stream\";\n }\n\n const sniffed = sniffMediaType(bytes);\n if (sniffed) {\n return sniffed;\n }\n\n return looksLikeText(bytes) ? \"text/plain\" : \"application/octet-stream\";\n}\n\nfunction normalizeMediaType(mediaType: string | undefined): string | null {\n const normalized = mediaType?.split(\";\")[0]?.trim().toLowerCase();\n return normalized || null;\n}\n\nfunction isGenericMediaType(mediaType: string): boolean {\n return (\n mediaType === \"application/octet-stream\" ||\n mediaType === \"binary/octet-stream\"\n );\n}\n\nfunction isTextMediaType(mediaType: string): boolean {\n return (\n mediaType.startsWith(\"text/\") ||\n mediaType === \"application/json\" ||\n mediaType === \"application/javascript\" ||\n mediaType === \"application/typescript\" ||\n mediaType === \"application/xml\" ||\n mediaType === \"application/x-javascript\" ||\n mediaType.endsWith(\"+json\") ||\n mediaType.endsWith(\"+xml\")\n );\n}\n\nfunction sniffMediaType(bytes: Uint8Array): string | null {\n if (startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) {\n return \"image/png\";\n }\n if (startsWith(bytes, [0xff, 0xd8, 0xff])) {\n return \"image/jpeg\";\n }\n if (startsWithAscii(bytes, \"GIF87a\") || startsWithAscii(bytes, \"GIF89a\")) {\n return \"image/gif\";\n }\n if (startsWithAscii(bytes, \"RIFF\") && asciiAt(bytes, 8, 12) === \"WEBP\") {\n return \"image/webp\";\n }\n if (startsWithAscii(bytes, \"%PDF-\")) {\n return \"application/pdf\";\n }\n if (looksLikeSvg(bytes)) {\n return \"image/svg+xml\";\n }\n return null;\n}\n\nfunction startsWith(bytes: Uint8Array, prefix: number[]): boolean {\n if (bytes.length < prefix.length) return false;\n return prefix.every((byte, index) => bytes[index] === byte);\n}\n\nfunction startsWithAscii(bytes: Uint8Array, prefix: string): boolean {\n return asciiAt(bytes, 0, prefix.length) === prefix;\n}\n\nfunction asciiAt(bytes: Uint8Array, start: number, end: number): string {\n return String.fromCharCode(...bytes.subarray(start, end));\n}\n\nfunction looksLikeSvg(bytes: Uint8Array): boolean {\n const prefix = new TextDecoder()\n .decode(bytes.subarray(0, Math.min(bytes.length, 512)))\n .trimStart()\n .toLowerCase();\n return prefix.startsWith(\"<svg\") || prefix.includes(\"<svg\");\n}\n\nfunction looksLikeText(bytes: Uint8Array): boolean {\n if (bytes.length === 0) return true;\n if (bytes.includes(0)) return false;\n\n const text = new TextDecoder().decode(bytes.subarray(0, 4096));\n if (text.length === 0) return true;\n\n let replacementChars = 0;\n for (const char of text) {\n if (char === \"\\uFFFD\") {\n replacementChars++;\n }\n }\n return replacementChars / text.length < 0.01;\n}\n\nfunction uint8ArrayToBase64(bytes: Uint8Array): string {\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.length; i += chunkSize) {\n binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));\n }\n return btoa(binary);\n}\n\n// ── Write ───────────────────────────────────────────────────────────\n\nexport interface WriteToolOptions {\n ops: WriteOperations;\n}\n\nexport function createWriteTool(options: WriteToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Write content to a file. Creates the file if it does not exist, \" +\n \"overwrites if it does. Parent directories are created automatically.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file\"),\n content: z.string().describe(\"Content to write to the file\")\n }),\n execute: async ({ path, content }) => {\n // Ensure parent directory exists\n const parent = path.replace(/\\/[^/]+$/, \"\");\n if (parent && parent !== \"/\") {\n await ops.mkdir(parent, { recursive: true });\n }\n\n await ops.writeFile(path, content);\n\n const lines = content.split(\"\\n\").length;\n return {\n path,\n bytesWritten: new TextEncoder().encode(content).byteLength,\n lines\n };\n }\n });\n}\n\n// ── Edit ────────────────────────────────────────────────────────────\n\nexport interface EditToolOptions {\n ops: EditOperations;\n}\n\nexport function createEditTool(options: EditToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Make a targeted edit to a file by replacing an exact string match. \" +\n \"Provide the old_string to find and new_string to replace it with. \" +\n \"The old_string must match exactly (including whitespace and indentation). \" +\n \"Use an empty old_string with new_string to create a new file.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file\"),\n old_string: z\n .string()\n .describe(\n \"Exact text to find and replace. Empty string to create a new file.\"\n ),\n new_string: z.string().describe(\"Replacement text\")\n }),\n execute: async ({ path, old_string, new_string }) => {\n // Create new file\n if (old_string === \"\") {\n const existing = await ops.readFile(path);\n if (existing !== null) {\n return {\n error:\n \"File already exists. Provide old_string to edit, or use the write tool to overwrite.\"\n };\n }\n await ops.writeFile(path, new_string);\n return {\n path,\n created: true,\n lines: new_string.split(\"\\n\").length\n };\n }\n\n // Edit existing file\n const content = await ops.readFile(path);\n if (content === null) {\n return { error: `File not found: ${path}` };\n }\n\n // Count occurrences\n const occurrences = countOccurrences(content, old_string);\n if (occurrences === 0) {\n // Try fuzzy match — normalize whitespace and look again\n const fuzzyResult = fuzzyReplace(content, old_string, new_string);\n if (fuzzyResult === \"ambiguous\") {\n return {\n error:\n \"old_string matches multiple locations after whitespace normalization. \" +\n \"Include more surrounding context to make the match unique.\"\n };\n }\n if (fuzzyResult !== null) {\n await ops.writeFile(path, fuzzyResult);\n return {\n path,\n replaced: true,\n fuzzyMatch: true,\n lines: fuzzyResult.split(\"\\n\").length\n };\n }\n\n return {\n error:\n \"old_string not found in file. Make sure it matches exactly, \" +\n \"including whitespace and indentation. Read the file first to verify.\"\n };\n }\n\n if (occurrences > 1) {\n return {\n error:\n `old_string appears ${occurrences} times in the file. ` +\n \"Include more surrounding context to make the match unique.\"\n };\n }\n\n const newContent = content.replace(old_string, new_string);\n await ops.writeFile(path, newContent);\n\n return {\n path,\n replaced: true,\n lines: newContent.split(\"\\n\").length\n };\n }\n });\n}\n\nfunction countOccurrences(text: string, search: string): number {\n let count = 0;\n let pos = 0;\n while (true) {\n const idx = text.indexOf(search, pos);\n if (idx === -1) break;\n count++;\n pos = idx + 1;\n }\n return count;\n}\n\n/**\n * Fuzzy replacement: normalize whitespace in both the file content\n * and the search string, find the match, then replace the corresponding\n * region in the original content.\n */\nfunction fuzzyReplace(\n content: string,\n oldStr: string,\n newStr: string\n): string | \"ambiguous\" | null {\n const normalizedContent = normalizeWhitespace(content);\n const normalizedSearch = normalizeWhitespace(oldStr);\n\n if (!normalizedSearch) return null;\n\n const idx = normalizedContent.indexOf(normalizedSearch);\n if (idx === -1) return null;\n\n // Check for multiple fuzzy matches\n const secondIdx = normalizedContent.indexOf(\n normalizedSearch,\n idx + normalizedSearch.length\n );\n if (secondIdx !== -1) return \"ambiguous\";\n\n // Map the normalized index back to the original content.\n // Walk both strings in parallel to find the original start/end.\n const originalStart = mapToOriginal(content, idx);\n const originalEnd = mapToOriginal(content, idx + normalizedSearch.length);\n\n return content.slice(0, originalStart) + newStr + content.slice(originalEnd);\n}\n\nfunction normalizeWhitespace(s: string): string {\n return s.replace(/[ \\t]+/g, \" \").replace(/\\r\\n/g, \"\\n\");\n}\n\n/**\n * Map a position in the normalized string back to the original string.\n * Walks both strings char-by-char, skipping extra whitespace in the original.\n */\nfunction mapToOriginal(original: string, normalizedPos: number): number {\n let ni = 0;\n let oi = 0;\n\n while (ni < normalizedPos && oi < original.length) {\n const oc = original[oi];\n if (oc === \"\\r\" && original[oi + 1] === \"\\n\") {\n // \\r\\n in original maps to \\n in normalized\n oi += 2;\n ni += 1;\n } else if (oc === \" \" || oc === \"\\t\") {\n // Consume a run of spaces/tabs in original → single space in normalized\n oi++;\n while (\n oi < original.length &&\n (original[oi] === \" \" || original[oi] === \"\\t\")\n ) {\n oi++;\n }\n ni++;\n } else {\n oi++;\n ni++;\n }\n }\n\n return oi;\n}\n\n// ── List ────────────────────────────────────────────────────────────\n\nexport interface ListToolOptions {\n ops: ListOperations;\n}\n\nexport function createListTool(options: ListToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"List files and directories in a given path. \" +\n \"Returns names, types, and sizes for each entry.\",\n inputSchema: z.object({\n path: z\n .string()\n .default(\"/\")\n .describe(\"Absolute path to the directory to list\"),\n limit: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .optional()\n .describe(\"Maximum number of entries to return (default: 200)\"),\n offset: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe(\"Number of entries to skip (for pagination)\")\n }),\n execute: async ({ path, limit, offset }) => {\n const maxEntries = limit ?? 200;\n const entries = await ops.readDir(path, {\n limit: maxEntries,\n offset: offset ?? 0\n });\n\n const formatted = entries.map((entry) => {\n const suffix = entry.type === \"directory\" ? \"/\" : \"\";\n const sizeStr =\n entry.type === \"file\" ? ` (${formatSize(entry.size)})` : \"\";\n return `${entry.name}${suffix}${sizeStr}`;\n });\n\n return {\n path,\n count: entries.length,\n entries: formatted\n };\n }\n });\n}\n\nfunction formatSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n// ── Find ────────────────────────────────────────────────────────────\n\nexport interface FindToolOptions {\n ops: FindOperations;\n}\n\nexport function createFindTool(options: FindToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Find files matching a glob pattern. \" +\n \"Supports standard glob syntax: * matches any file, ** matches directories recursively, \" +\n \"? matches a single character. Returns matching file paths with types and sizes.\",\n inputSchema: z.object({\n pattern: z\n .string()\n .describe(\n 'Glob pattern to match (e.g. \"**/*.ts\", \"src/**/*.test.ts\", \"*.md\")'\n )\n }),\n execute: async ({ pattern }) => {\n const matches = await ops.glob(pattern);\n\n const MAX_RESULTS = 200;\n const truncated = matches.length > MAX_RESULTS;\n const results = matches.slice(0, MAX_RESULTS);\n\n const formatted = results.map((entry) => {\n const suffix = entry.type === \"directory\" ? \"/\" : \"\";\n return `${entry.path}${suffix}`;\n });\n\n const result: Record<string, unknown> = {\n pattern,\n count: matches.length,\n files: formatted\n };\n\n if (truncated) {\n result.truncated = true;\n result.showing = MAX_RESULTS;\n }\n\n return result;\n }\n });\n}\n\n// ── Grep ────────────────────────────────────────────────────────────\n\nconst MAX_MATCHES = 200;\nconst MAX_FILE_SIZE = 1_048_576; // 1 MB — skip files larger than this in grep\n\nexport interface GrepToolOptions {\n ops: GrepOperations;\n}\n\nexport function createGrepTool(options: GrepToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Search file contents using a regular expression or fixed string. \" +\n \"Returns matching lines with file paths and line numbers. \" +\n \"Searches all files matching the include glob, or all files if not specified.\",\n inputSchema: z.object({\n query: z.string().describe(\"Search pattern (regex or fixed string)\"),\n include: z\n .string()\n .optional()\n .describe(\n 'Glob pattern to filter files (e.g. \"**/*.ts\"). Defaults to \"**/*\"'\n ),\n fixedString: z\n .boolean()\n .optional()\n .describe(\"If true, treat query as a literal string instead of regex\"),\n caseSensitive: z\n .boolean()\n .optional()\n .describe(\"If true, search is case-sensitive (default: false)\"),\n contextLines: z\n .number()\n .int()\n .min(0)\n .max(10)\n .optional()\n .describe(\"Number of context lines around each match (default: 0)\")\n }),\n execute: async ({\n query,\n include,\n fixedString,\n caseSensitive,\n contextLines\n }) => {\n const pattern = include ?? \"**/*\";\n const allFiles = await ops.glob(pattern);\n const files = allFiles.filter((f: { type: string }) => f.type === \"file\");\n\n let regex: RegExp;\n try {\n const escaped = fixedString ? escapeRegex(query) : query;\n regex = new RegExp(escaped, caseSensitive ? \"g\" : \"gi\");\n } catch {\n return { error: `Invalid regex: ${query}` };\n }\n\n const ctx = contextLines ?? 0;\n const matches: Array<{\n file: string;\n line: number;\n text: string;\n context?: string[];\n }> = [];\n let totalMatches = 0;\n let filesSearched = 0;\n let filesWithMatches = 0;\n\n let filesSkipped = 0;\n\n for (const file of files) {\n if (totalMatches >= MAX_MATCHES) break;\n\n // Skip files larger than 1 MB to avoid memory blowup\n if (file.size > MAX_FILE_SIZE) {\n filesSkipped++;\n continue;\n }\n\n const content = await ops.readFile(file.path);\n if (content === null) continue;\n filesSearched++;\n\n const lines = content.split(\"\\n\");\n let fileHasMatch = false;\n\n for (let i = 0; i < lines.length; i++) {\n if (totalMatches >= MAX_MATCHES) break;\n\n regex.lastIndex = 0;\n if (regex.test(lines[i])) {\n if (!fileHasMatch) {\n fileHasMatch = true;\n filesWithMatches++;\n }\n totalMatches++;\n\n const match: {\n file: string;\n line: number;\n text: string;\n context?: string[];\n } = {\n file: file.path,\n line: i + 1,\n text: lines[i]\n };\n\n if (ctx > 0) {\n const start = Math.max(0, i - ctx);\n const end = Math.min(lines.length, i + ctx + 1);\n match.context = lines.slice(start, end).map((l, j) => {\n const lineNum = start + j + 1;\n const marker = lineNum === i + 1 ? \">\" : \" \";\n return `${marker} ${lineNum}\\t${l}`;\n });\n }\n\n matches.push(match);\n }\n }\n }\n\n const result: Record<string, unknown> = {\n query,\n filesSearched,\n filesWithMatches,\n totalMatches,\n matches: matches.map((m) => {\n if (m.context) {\n return {\n file: m.file,\n line: m.line,\n context: m.context.join(\"\\n\")\n };\n }\n return `${m.file}:${m.line}: ${m.text}`;\n })\n };\n\n if (totalMatches >= MAX_MATCHES) {\n result.truncated = true;\n }\n if (filesSkipped > 0) {\n result.filesSkipped = filesSkipped;\n result.note = `${filesSkipped} file(s) skipped (larger than 1 MB)`;\n }\n\n return result;\n }\n });\n}\n\nfunction escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n// ── Delete ──────────────────────────────────────────────────────────\n\nexport interface DeleteToolOptions {\n ops: DeleteOperations;\n}\n\nexport function createDeleteTool(options: DeleteToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Delete a file or directory. \" +\n \"Set recursive to true to remove non-empty directories.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file or directory\"),\n recursive: z\n .boolean()\n .optional()\n .describe(\"If true, remove directories and their contents recursively\")\n }),\n execute: async ({ path, recursive }) => {\n await ops.rm(path, { recursive, force: true });\n return { deleted: path };\n }\n });\n}\n"],"mappings":";;;AA8EA,SAAS,iBAAiB,IAAmC;AAC3D,QAAO;EACL,WAAW,SAAS,GAAG,SAAS,KAAK;EACrC,gBAAgB,SAAS,GAAG,cAAc,KAAK;EAC/C,OAAO,SAAS,GAAG,KAAK,KAAK;EAC9B;;AAGH,SAAS,kBAAkB,IAAoC;AAC7D,QAAO;EACL,YAAY,MAAM,YAAY,GAAG,UAAU,MAAM,QAAQ;EACzD,QAAQ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ACjC;IACH;AAED,OAAI,gBAAgB,YAClB,QAAO,YAAY;AAErB,OAAI,eAAe,GAAG;AACpB,WAAO,eAAe;AACtB,WAAO,OAAO,GAAG,aAAa;;AAGhC,UAAO;;EAEV,CAAC;;AAGJ,SAAS,YAAY,GAAmB;AACtC,QAAO,EAAE,QAAQ,uBAAuB,OAAO;;AASjD,SAAgB,iBAAiB,SAA4B;CAC3D,MAAM,EAAE,QAAQ;AAEhB,QAAO,KAAK;EACV,aACE;EAEF,aAAa,EAAE,OAAO;GACpB,MAAM,EAAE,QAAQ,CAAC,SAAS,yCAAyC;GACnE,WAAW,EACR,SAAS,CACT,UAAU,CACV,SAAS,6DAA6D;GAC1E,CAAC;EACF,SAAS,OAAO,EAAE,MAAM,gBAAgB;AACtC,SAAM,IAAI,GAAG,MAAM;IAAE;IAAW,OAAO;IAAM,CAAC;AAC9C,UAAO,EAAE,SAAS,MAAM;;EAE3B,CAAC"}
1
+ {"version":3,"file":"workspace.js","names":[],"sources":["../../src/tools/workspace.ts"],"sourcesContent":["import type { Workspace, FileInfo } from \"@cloudflare/shell\";\nimport type { JSONValue } from \"ai\";\nimport { tool } from \"ai\";\nimport { z } from \"zod\";\n\n// ── WorkspaceLike ─────────────────────────────────────────────────\n//\n// Minimum workspace surface that Think's internals rely on. Covers the\n// methods called by `createWorkspaceTools()` below plus the handful\n// Think itself uses (`readFile`/`writeFile`/`readDir`/`rm` in\n// `think.ts`). The read tool also needs `readFileBytes` so image/PDF\n// reads can be rehydrated as AI SDK multimodal content. A concrete\n// `Workspace` from `@cloudflare/shell` satisfies this; so do custom\n// implementations like the `SharedWorkspace` proxy in `examples/assistant`\n// that forwards to a parent DO.\n//\n// Consumers who reach for the fuller filesystem API (e.g.\n// `createWorkspaceStateBackend` for codemode's `state.*` in a sandbox)\n// still need a concrete `Workspace`.\n//\n// @experimental The API surface may change before stabilizing.\n\nexport type WorkspaceLike = Pick<\n Workspace,\n | \"readFile\"\n | \"readFileBytes\"\n | \"writeFile\"\n | \"readDir\"\n | \"rm\"\n | \"glob\"\n | \"mkdir\"\n | \"stat\"\n>;\n\n// ── Operations interfaces ─────────────────────────────────────────\n// Abstractions over file I/O so the same tools can work against\n// Workspace, a local filesystem, or anything else.\n\nexport interface ReadOperations {\n readFile(path: string): Promise<string | null>;\n readFileBytes(path: string): Promise<Uint8Array | null>;\n stat(path: string): Promise<FileInfo | null> | FileInfo | null;\n}\n\nexport interface WriteOperations {\n writeFile(path: string, content: string): Promise<void>;\n mkdir(path: string, opts?: { recursive?: boolean }): Promise<void> | void;\n}\n\nexport interface EditOperations {\n readFile(path: string): Promise<string | null>;\n writeFile(path: string, content: string): Promise<void>;\n}\n\nexport interface ListOperations {\n readDir(\n dir: string,\n opts?: { limit?: number; offset?: number }\n ): Promise<FileInfo[]> | FileInfo[];\n}\n\nexport interface FindOperations {\n glob(pattern: string): Promise<FileInfo[]> | FileInfo[];\n}\n\nexport interface DeleteOperations {\n rm(\n path: string,\n opts?: { recursive?: boolean; force?: boolean }\n ): Promise<void>;\n}\n\nexport interface GrepOperations {\n glob(pattern: string): Promise<FileInfo[]> | FileInfo[];\n readFile(path: string): Promise<string | null>;\n}\n\n// ── Workspace-backed operation factories ──────────────────────────\n\nfunction workspaceReadOps(ws: WorkspaceLike): ReadOperations {\n return {\n readFile: (path) => ws.readFile(path),\n readFileBytes: (path) => ws.readFileBytes(path),\n stat: (path) => ws.stat(path)\n };\n}\n\nfunction workspaceWriteOps(ws: WorkspaceLike): WriteOperations {\n return {\n writeFile: (path, content) => ws.writeFile(path, content),\n mkdir: (path, opts) => ws.mkdir(path, opts)\n };\n}\n\nfunction workspaceEditOps(ws: WorkspaceLike): EditOperations {\n return {\n readFile: (path) => ws.readFile(path),\n writeFile: (path, content) => ws.writeFile(path, content)\n };\n}\n\nfunction workspaceListOps(ws: WorkspaceLike): ListOperations {\n return {\n readDir: (dir, opts) => ws.readDir(dir, opts)\n };\n}\n\nfunction workspaceFindOps(ws: WorkspaceLike): FindOperations {\n return {\n glob: (pattern) => ws.glob(pattern)\n };\n}\n\nfunction workspaceDeleteOps(ws: WorkspaceLike): DeleteOperations {\n return {\n rm: (path, opts) => ws.rm(path, opts)\n };\n}\n\nfunction workspaceGrepOps(ws: WorkspaceLike): GrepOperations {\n return {\n glob: (pattern) => ws.glob(pattern),\n readFile: (path) => ws.readFile(path)\n };\n}\n\n/**\n * Create a complete set of AI SDK tools backed by a workspace.\n *\n * Accepts either a concrete `Workspace` from `@cloudflare/shell` or any\n * `WorkspaceLike` implementation — e.g. a proxy that forwards calls to a\n * shared workspace owned by a parent DO.\n *\n * ```ts\n * import { Workspace } from \"@cloudflare/shell\";\n * import { createWorkspaceTools } from \"@cloudflare/think\";\n *\n * class MyAgent extends Agent<Env> {\n * workspace = new Workspace({ sql: this.ctx.storage.sql, name: () => this.name });\n *\n * async onChatMessage() {\n * const tools = createWorkspaceTools(this.workspace);\n * const result = streamText({ model, tools, messages });\n * return result.toUIMessageStreamResponse();\n * }\n * }\n * ```\n */\nexport function createWorkspaceTools(workspace: WorkspaceLike) {\n return {\n read: createReadTool({ ops: workspaceReadOps(workspace) }),\n write: createWriteTool({ ops: workspaceWriteOps(workspace) }),\n edit: createEditTool({ ops: workspaceEditOps(workspace) }),\n list: createListTool({ ops: workspaceListOps(workspace) }),\n find: createFindTool({ ops: workspaceFindOps(workspace) }),\n grep: createGrepTool({ ops: workspaceGrepOps(workspace) }),\n delete: createDeleteTool({ ops: workspaceDeleteOps(workspace) })\n };\n}\n\n// ── Read ────────────────────────────────────────────────────────────\n\nconst MAX_LINES = 2000;\nconst MAX_LINE_LENGTH = 2000;\nconst MAX_MODEL_FILE_BYTES = 3.5 * 1024 * 1024;\n\ntype TextReadToolOutput = {\n path: string;\n content: string;\n totalLines: number;\n fromLine?: number;\n toLine?: number;\n};\n\ntype ImageReadToolOutput = {\n kind: \"image\";\n path: string;\n name: string;\n mediaType: string;\n sizeBytes: number;\n};\n\ntype FileReadToolOutput = {\n kind: \"file\";\n path: string;\n name: string;\n mediaType: string;\n sizeBytes: number;\n};\n\ntype BinaryReadToolOutput = {\n kind: \"binary\";\n path: string;\n name: string;\n mediaType: string;\n sizeBytes: number;\n unsupported: true;\n};\n\ntype ReadToolError = { error: string };\n\ntype ReadToolOutput =\n | TextReadToolOutput\n | ImageReadToolOutput\n | FileReadToolOutput\n | BinaryReadToolOutput\n | ReadToolError;\n\ntype ReadToolInput = {\n path: string;\n offset?: number;\n limit?: number;\n};\n\nexport interface ReadToolOptions {\n ops: ReadOperations;\n}\n\nexport function createReadTool(options: ReadToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Read a workspace file. Text files return line-numbered content. \" +\n \"Images and PDFs are passed to capable models as file content. \" +\n \"Use offset and limit for large text files. Returns null if the file does not exist.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file\"),\n offset: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(\"1-indexed line number to start reading from\"),\n limit: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(\"Number of lines to read\")\n }),\n execute: async ({\n path,\n offset,\n limit\n }: ReadToolInput): Promise<ReadToolOutput> => {\n const stat = await ops.stat(path);\n if (!stat) {\n return { error: `File not found: ${path}` };\n }\n if (stat.type === \"directory\") {\n return { error: `${path} is a directory, not a file` };\n }\n\n const mediaType = await detectWorkspaceMediaType({ ops, path, stat });\n\n if (mediaType.startsWith(\"image/\")) {\n return {\n kind: \"image\",\n path,\n name: stat.name,\n mediaType,\n sizeBytes: stat.size\n };\n }\n\n if (mediaType === \"application/pdf\") {\n return {\n kind: \"file\",\n path,\n name: stat.name,\n mediaType,\n sizeBytes: stat.size\n };\n }\n\n if (!isTextMediaType(mediaType)) {\n return {\n kind: \"binary\",\n path,\n name: stat.name,\n mediaType,\n sizeBytes: stat.size,\n unsupported: true\n };\n }\n\n return readTextWithLineNumbers({ ops, path, offset, limit });\n },\n toModelOutput: async ({\n input,\n output\n }: {\n input: unknown;\n output: unknown;\n }) => {\n const replayOutput: unknown = output;\n\n if (!isRecord(replayOutput)) {\n return { type: \"text\", value: String(replayOutput) };\n }\n\n if (typeof replayOutput.error === \"string\") {\n return { type: \"error-text\", value: replayOutput.error };\n }\n\n if (typeof replayOutput.content === \"string\") {\n return { type: \"text\", value: replayOutput.content };\n }\n\n if (replayOutput.kind === \"binary\") {\n return {\n type: \"json\",\n value: toJSONValue(replayOutput)\n };\n }\n\n if (!isModelFileReadOutput(replayOutput)) {\n return {\n type: \"json\",\n value: toJSONValue(replayOutput)\n };\n }\n\n if (!isReadToolInput(input)) {\n return {\n type: \"json\",\n value: toJSONValue(replayOutput)\n };\n }\n\n const bytes = await ops.readFileBytes(input.path);\n if (bytes === null) {\n return {\n type: \"error-text\",\n value: `Could not read file bytes: ${input.path}`\n };\n }\n if (bytes.byteLength > MAX_MODEL_FILE_BYTES) {\n return {\n type: \"error-text\",\n value:\n `Read ${replayOutput.path} (${replayOutput.mediaType}, ${formatSize(bytes.byteLength)}), ` +\n `but it exceeds the ${formatSize(MAX_MODEL_FILE_BYTES)} inline model output limit.`\n };\n }\n\n const data = uint8ArrayToBase64(bytes);\n const note = `Read ${replayOutput.path} (${replayOutput.mediaType}, ${formatSize(bytes.byteLength)}).`;\n\n if (replayOutput.kind === \"image\") {\n return {\n type: \"content\",\n value: [\n { type: \"text\", text: note },\n { type: \"image-data\", data, mediaType: replayOutput.mediaType }\n ]\n };\n }\n\n return {\n type: \"content\",\n value: [\n { type: \"text\", text: note },\n {\n type: \"file-data\",\n data,\n mediaType: replayOutput.mediaType,\n filename: replayOutput.name\n }\n ]\n };\n }\n });\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isModelFileReadOutput(\n value: Record<string, unknown>\n): value is ImageReadToolOutput | FileReadToolOutput {\n return (\n (value.kind === \"image\" || value.kind === \"file\") &&\n typeof value.path === \"string\" &&\n typeof value.name === \"string\" &&\n typeof value.mediaType === \"string\"\n );\n}\n\nfunction isReadToolInput(value: unknown): value is ReadToolInput {\n return isRecord(value) && typeof value.path === \"string\";\n}\n\nfunction toJSONValue(value: unknown): JSONValue {\n try {\n const json = JSON.stringify(value);\n return json === undefined ? null : (JSON.parse(json) as JSONValue);\n } catch {\n return String(value);\n }\n}\n\nfunction readTextWithLineNumbers({\n ops,\n path,\n offset,\n limit\n}: {\n ops: ReadOperations;\n path: string;\n offset?: number;\n limit?: number;\n}): Promise<TextReadToolOutput | ReadToolError> {\n return Promise.resolve(ops.readFile(path)).then((content) => {\n if (content === null) {\n return { error: `Could not read file: ${path}` };\n }\n\n const allLines = content.split(\"\\n\");\n const totalLines = allLines.length;\n\n // Apply offset/limit\n const startLine = offset ? offset - 1 : 0;\n const endLine = limit ? startLine + limit : allLines.length;\n const lines = allLines.slice(startLine, endLine);\n\n // Format with line numbers, truncate long lines\n const numbered = lines.map((line, i) => {\n const lineNum = startLine + i + 1;\n const truncated =\n line.length > MAX_LINE_LENGTH\n ? line.slice(0, MAX_LINE_LENGTH) + \"... (truncated)\"\n : line;\n return `${lineNum}\\t${truncated}`;\n });\n\n // Truncate if too many lines\n let output: string;\n if (numbered.length > MAX_LINES) {\n output =\n numbered.slice(0, MAX_LINES).join(\"\\n\") +\n `\\n... (${numbered.length - MAX_LINES} more lines truncated)`;\n } else {\n output = numbered.join(\"\\n\");\n }\n\n const result: TextReadToolOutput = {\n path,\n content: output,\n totalLines\n };\n\n if (offset || limit) {\n result.fromLine = startLine + 1;\n result.toLine = Math.min(endLine, totalLines);\n }\n\n return result;\n });\n}\n\nasync function detectWorkspaceMediaType({\n ops,\n path,\n stat\n}: {\n ops: ReadOperations;\n path: string;\n stat: FileInfo;\n}): Promise<string> {\n const statMime = normalizeMediaType(stat.mimeType);\n if (statMime && !isGenericMediaType(statMime)) {\n return statMime;\n }\n\n const bytes = await ops.readFileBytes(path);\n if (bytes === null) {\n return statMime || \"application/octet-stream\";\n }\n\n const sniffed = sniffMediaType(bytes);\n if (sniffed) {\n return sniffed;\n }\n\n return looksLikeText(bytes) ? \"text/plain\" : \"application/octet-stream\";\n}\n\nfunction normalizeMediaType(mediaType: string | undefined): string | null {\n const normalized = mediaType?.split(\";\")[0]?.trim().toLowerCase();\n return normalized || null;\n}\n\nfunction isGenericMediaType(mediaType: string): boolean {\n return (\n mediaType === \"application/octet-stream\" ||\n mediaType === \"binary/octet-stream\"\n );\n}\n\nfunction isTextMediaType(mediaType: string): boolean {\n return (\n mediaType.startsWith(\"text/\") ||\n mediaType === \"application/json\" ||\n mediaType === \"application/javascript\" ||\n mediaType === \"application/typescript\" ||\n mediaType === \"application/xml\" ||\n mediaType === \"application/x-javascript\" ||\n mediaType.endsWith(\"+json\") ||\n mediaType.endsWith(\"+xml\")\n );\n}\n\nfunction sniffMediaType(bytes: Uint8Array): string | null {\n if (startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) {\n return \"image/png\";\n }\n if (startsWith(bytes, [0xff, 0xd8, 0xff])) {\n return \"image/jpeg\";\n }\n if (startsWithAscii(bytes, \"GIF87a\") || startsWithAscii(bytes, \"GIF89a\")) {\n return \"image/gif\";\n }\n if (startsWithAscii(bytes, \"RIFF\") && asciiAt(bytes, 8, 12) === \"WEBP\") {\n return \"image/webp\";\n }\n if (startsWithAscii(bytes, \"%PDF-\")) {\n return \"application/pdf\";\n }\n if (looksLikeSvg(bytes)) {\n return \"image/svg+xml\";\n }\n return null;\n}\n\nfunction startsWith(bytes: Uint8Array, prefix: number[]): boolean {\n if (bytes.length < prefix.length) return false;\n return prefix.every((byte, index) => bytes[index] === byte);\n}\n\nfunction startsWithAscii(bytes: Uint8Array, prefix: string): boolean {\n return asciiAt(bytes, 0, prefix.length) === prefix;\n}\n\nfunction asciiAt(bytes: Uint8Array, start: number, end: number): string {\n return String.fromCharCode(...bytes.subarray(start, end));\n}\n\nfunction looksLikeSvg(bytes: Uint8Array): boolean {\n const prefix = new TextDecoder()\n .decode(bytes.subarray(0, Math.min(bytes.length, 512)))\n .trimStart()\n .toLowerCase();\n return prefix.startsWith(\"<svg\") || prefix.includes(\"<svg\");\n}\n\nfunction looksLikeText(bytes: Uint8Array): boolean {\n if (bytes.length === 0) return true;\n if (bytes.includes(0)) return false;\n\n const text = new TextDecoder().decode(bytes.subarray(0, 4096));\n if (text.length === 0) return true;\n\n let replacementChars = 0;\n for (const char of text) {\n if (char === \"\\uFFFD\") {\n replacementChars++;\n }\n }\n return replacementChars / text.length < 0.01;\n}\n\nfunction uint8ArrayToBase64(bytes: Uint8Array): string {\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.length; i += chunkSize) {\n binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));\n }\n return btoa(binary);\n}\n\n// ── Write ───────────────────────────────────────────────────────────\n\nexport interface WriteToolOptions {\n ops: WriteOperations;\n}\n\nexport function createWriteTool(options: WriteToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Write content to a file. Creates the file if it does not exist, \" +\n \"overwrites if it does. Parent directories are created automatically.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file\"),\n content: z.string().describe(\"Content to write to the file\")\n }),\n execute: async ({ path, content }) => {\n // Ensure parent directory exists\n const parent = path.replace(/\\/[^/]+$/, \"\");\n if (parent && parent !== \"/\") {\n await ops.mkdir(parent, { recursive: true });\n }\n\n await ops.writeFile(path, content);\n\n const lines = content.split(\"\\n\").length;\n return {\n path,\n bytesWritten: new TextEncoder().encode(content).byteLength,\n lines\n };\n }\n });\n}\n\n// ── Edit ────────────────────────────────────────────────────────────\n\nexport interface EditToolOptions {\n ops: EditOperations;\n}\n\nexport function createEditTool(options: EditToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Make a targeted edit to a file by replacing an exact string match. \" +\n \"Provide the old_string to find and new_string to replace it with. \" +\n \"The old_string must match exactly (including whitespace and indentation). \" +\n \"Use an empty old_string with new_string to create a new file.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file\"),\n old_string: z\n .string()\n .describe(\n \"Exact text to find and replace. Empty string to create a new file.\"\n ),\n new_string: z.string().describe(\"Replacement text\")\n }),\n execute: async ({ path, old_string, new_string }) => {\n // Create new file\n if (old_string === \"\") {\n const existing = await ops.readFile(path);\n if (existing !== null) {\n return {\n error:\n \"File already exists. Provide old_string to edit, or use the write tool to overwrite.\"\n };\n }\n await ops.writeFile(path, new_string);\n return {\n path,\n created: true,\n lines: new_string.split(\"\\n\").length\n };\n }\n\n // Edit existing file\n const content = await ops.readFile(path);\n if (content === null) {\n return { error: `File not found: ${path}` };\n }\n\n // Count occurrences\n const occurrences = countOccurrences(content, old_string);\n if (occurrences === 0) {\n // Try fuzzy match — normalize whitespace and look again\n const fuzzyResult = fuzzyReplace(content, old_string, new_string);\n if (fuzzyResult === \"ambiguous\") {\n return {\n error:\n \"old_string matches multiple locations after whitespace normalization. \" +\n \"Include more surrounding context to make the match unique.\"\n };\n }\n if (fuzzyResult !== null) {\n await ops.writeFile(path, fuzzyResult);\n return {\n path,\n replaced: true,\n fuzzyMatch: true,\n lines: fuzzyResult.split(\"\\n\").length\n };\n }\n\n return {\n error:\n \"old_string not found in file. Make sure it matches exactly, \" +\n \"including whitespace and indentation. Read the file first to verify.\"\n };\n }\n\n if (occurrences > 1) {\n return {\n error:\n `old_string appears ${occurrences} times in the file. ` +\n \"Include more surrounding context to make the match unique.\"\n };\n }\n\n const newContent = content.replace(old_string, new_string);\n await ops.writeFile(path, newContent);\n\n return {\n path,\n replaced: true,\n lines: newContent.split(\"\\n\").length\n };\n }\n });\n}\n\nfunction countOccurrences(text: string, search: string): number {\n let count = 0;\n let pos = 0;\n while (true) {\n const idx = text.indexOf(search, pos);\n if (idx === -1) break;\n count++;\n pos = idx + 1;\n }\n return count;\n}\n\n/**\n * Fuzzy replacement: normalize whitespace in both the file content\n * and the search string, find the match, then replace the corresponding\n * region in the original content.\n */\nfunction fuzzyReplace(\n content: string,\n oldStr: string,\n newStr: string\n): string | \"ambiguous\" | null {\n const normalizedContent = normalizeWhitespace(content);\n const normalizedSearch = normalizeWhitespace(oldStr);\n\n if (!normalizedSearch) return null;\n\n const idx = normalizedContent.indexOf(normalizedSearch);\n if (idx === -1) return null;\n\n // Check for multiple fuzzy matches\n const secondIdx = normalizedContent.indexOf(\n normalizedSearch,\n idx + normalizedSearch.length\n );\n if (secondIdx !== -1) return \"ambiguous\";\n\n // Map the normalized index back to the original content.\n // Walk both strings in parallel to find the original start/end.\n const originalStart = mapToOriginal(content, idx);\n const originalEnd = mapToOriginal(content, idx + normalizedSearch.length);\n\n return content.slice(0, originalStart) + newStr + content.slice(originalEnd);\n}\n\nfunction normalizeWhitespace(s: string): string {\n return s.replace(/[ \\t]+/g, \" \").replace(/\\r\\n/g, \"\\n\");\n}\n\n/**\n * Map a position in the normalized string back to the original string.\n * Walks both strings char-by-char, skipping extra whitespace in the original.\n */\nfunction mapToOriginal(original: string, normalizedPos: number): number {\n let ni = 0;\n let oi = 0;\n\n while (ni < normalizedPos && oi < original.length) {\n const oc = original[oi];\n if (oc === \"\\r\" && original[oi + 1] === \"\\n\") {\n // \\r\\n in original maps to \\n in normalized\n oi += 2;\n ni += 1;\n } else if (oc === \" \" || oc === \"\\t\") {\n // Consume a run of spaces/tabs in original → single space in normalized\n oi++;\n while (\n oi < original.length &&\n (original[oi] === \" \" || original[oi] === \"\\t\")\n ) {\n oi++;\n }\n ni++;\n } else {\n oi++;\n ni++;\n }\n }\n\n return oi;\n}\n\n// ── List ────────────────────────────────────────────────────────────\n\nexport interface ListToolOptions {\n ops: ListOperations;\n}\n\nexport function createListTool(options: ListToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"List files and directories in a given path. \" +\n \"Returns names, types, and sizes for each entry.\",\n inputSchema: z.object({\n path: z\n .string()\n .default(\"/\")\n .describe(\"Absolute path to the directory to list\"),\n limit: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .optional()\n .describe(\"Maximum number of entries to return (default: 200)\"),\n offset: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe(\"Number of entries to skip (for pagination)\")\n }),\n execute: async ({ path, limit, offset }) => {\n const maxEntries = limit ?? 200;\n const entries = await ops.readDir(path, {\n limit: maxEntries,\n offset: offset ?? 0\n });\n\n const formatted = entries.map((entry) => {\n const suffix = entry.type === \"directory\" ? \"/\" : \"\";\n const sizeStr =\n entry.type === \"file\" ? ` (${formatSize(entry.size)})` : \"\";\n return `${entry.name}${suffix}${sizeStr}`;\n });\n\n return {\n path,\n count: entries.length,\n entries: formatted\n };\n }\n });\n}\n\nfunction formatSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n// ── Find ────────────────────────────────────────────────────────────\n\nexport interface FindToolOptions {\n ops: FindOperations;\n}\n\nexport function createFindTool(options: FindToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Find files matching a glob pattern. \" +\n \"Supports standard glob syntax: * matches any file, ** matches directories recursively, \" +\n \"? matches a single character. Returns matching file paths with types and sizes.\",\n inputSchema: z.object({\n pattern: z\n .string()\n .describe(\n 'Glob pattern to match (e.g. \"**/*.ts\", \"src/**/*.test.ts\", \"*.md\")'\n )\n }),\n execute: async ({ pattern }) => {\n const matches = await ops.glob(pattern);\n\n const MAX_RESULTS = 200;\n const truncated = matches.length > MAX_RESULTS;\n const results = matches.slice(0, MAX_RESULTS);\n\n const formatted = results.map((entry) => {\n const suffix = entry.type === \"directory\" ? \"/\" : \"\";\n return `${entry.path}${suffix}`;\n });\n\n const result: Record<string, unknown> = {\n pattern,\n count: matches.length,\n files: formatted\n };\n\n if (truncated) {\n result.truncated = true;\n result.showing = MAX_RESULTS;\n }\n\n return result;\n }\n });\n}\n\n// ── Grep ────────────────────────────────────────────────────────────\n\nconst MAX_MATCHES = 200;\nconst MAX_FILE_SIZE = 1_048_576; // 1 MB — skip files larger than this in grep\n\nexport interface GrepToolOptions {\n ops: GrepOperations;\n}\n\nexport function createGrepTool(options: GrepToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Search file contents using a regular expression or fixed string. \" +\n \"Returns matching lines with file paths and line numbers. \" +\n \"Searches all files matching the include glob, or all files if not specified.\",\n inputSchema: z.object({\n query: z.string().describe(\"Search pattern (regex or fixed string)\"),\n include: z\n .string()\n .optional()\n .describe(\n 'Glob pattern to filter files (e.g. \"**/*.ts\"). Defaults to \"**/*\"'\n ),\n fixedString: z\n .boolean()\n .optional()\n .describe(\"If true, treat query as a literal string instead of regex\"),\n caseSensitive: z\n .boolean()\n .optional()\n .describe(\"If true, search is case-sensitive (default: false)\"),\n contextLines: z\n .number()\n .int()\n .min(0)\n .max(10)\n .optional()\n .describe(\"Number of context lines around each match (default: 0)\")\n }),\n execute: async ({\n query,\n include,\n fixedString,\n caseSensitive,\n contextLines\n }) => {\n const pattern = include ?? \"**/*\";\n const allFiles = await ops.glob(pattern);\n const files = allFiles.filter((f: { type: string }) => f.type === \"file\");\n\n let regex: RegExp;\n try {\n const escaped = fixedString ? escapeRegex(query) : query;\n regex = new RegExp(escaped, caseSensitive ? \"g\" : \"gi\");\n } catch {\n return { error: `Invalid regex: ${query}` };\n }\n\n const ctx = contextLines ?? 0;\n const matches: Array<{\n file: string;\n line: number;\n text: string;\n context?: string[];\n }> = [];\n let totalMatches = 0;\n let filesSearched = 0;\n let filesWithMatches = 0;\n\n let filesSkipped = 0;\n\n for (const file of files) {\n if (totalMatches >= MAX_MATCHES) break;\n\n // Skip files larger than 1 MB to avoid memory blowup\n if (file.size > MAX_FILE_SIZE) {\n filesSkipped++;\n continue;\n }\n\n const content = await ops.readFile(file.path);\n if (content === null) continue;\n filesSearched++;\n\n const lines = content.split(\"\\n\");\n let fileHasMatch = false;\n\n for (let i = 0; i < lines.length; i++) {\n if (totalMatches >= MAX_MATCHES) break;\n\n regex.lastIndex = 0;\n if (regex.test(lines[i])) {\n if (!fileHasMatch) {\n fileHasMatch = true;\n filesWithMatches++;\n }\n totalMatches++;\n\n const match: {\n file: string;\n line: number;\n text: string;\n context?: string[];\n } = {\n file: file.path,\n line: i + 1,\n text: lines[i]\n };\n\n if (ctx > 0) {\n const start = Math.max(0, i - ctx);\n const end = Math.min(lines.length, i + ctx + 1);\n match.context = lines.slice(start, end).map((l, j) => {\n const lineNum = start + j + 1;\n const marker = lineNum === i + 1 ? \">\" : \" \";\n return `${marker} ${lineNum}\\t${l}`;\n });\n }\n\n matches.push(match);\n }\n }\n }\n\n const result: Record<string, unknown> = {\n query,\n filesSearched,\n filesWithMatches,\n totalMatches,\n matches: matches.map((m) => {\n if (m.context) {\n return {\n file: m.file,\n line: m.line,\n context: m.context.join(\"\\n\")\n };\n }\n return `${m.file}:${m.line}: ${m.text}`;\n })\n };\n\n if (totalMatches >= MAX_MATCHES) {\n result.truncated = true;\n }\n if (filesSkipped > 0) {\n result.filesSkipped = filesSkipped;\n result.note = `${filesSkipped} file(s) skipped (larger than 1 MB)`;\n }\n\n return result;\n }\n });\n}\n\nfunction escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n// ── Delete ──────────────────────────────────────────────────────────\n\nexport interface DeleteToolOptions {\n ops: DeleteOperations;\n}\n\nexport function createDeleteTool(options: DeleteToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Delete a file or directory. \" +\n \"Set recursive to true to remove non-empty directories.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file or directory\"),\n recursive: z\n .boolean()\n .optional()\n .describe(\"If true, remove directories and their contents recursively\")\n }),\n execute: async ({ path, recursive }) => {\n await ops.rm(path, { recursive, force: true });\n return { deleted: path };\n }\n });\n}\n"],"mappings":";;;AA+EA,SAAS,iBAAiB,IAAmC;CAC3D,OAAO;EACL,WAAW,SAAS,GAAG,SAAS,KAAK;EACrC,gBAAgB,SAAS,GAAG,cAAc,KAAK;EAC/C,OAAO,SAAS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AAE,OAAO;GACpB,MAAM,EAAE,QAAQ,CAAC,SAAS,yCAAyC;GACnE,WAAW,EACR,SAAS,CACT,UAAU,CACV,SAAS,6DAA6D;GAC1E,CAAC;EACF,SAAS,OAAO,EAAE,MAAM,gBAAgB;GACtC,MAAM,IAAI,GAAG,MAAM;IAAE;IAAW,OAAO;IAAM,CAAC;GAC9C,OAAO,EAAE,SAAS,MAAM;;EAE3B,CAAC"}
package/package.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "tools"
10
10
  ],
11
11
  "type": "module",
12
- "version": "0.5.2",
12
+ "version": "0.6.0",
13
13
  "license": "MIT",
14
14
  "repository": {
15
15
  "directory": "packages/think",
@@ -22,13 +22,13 @@
22
22
  },
23
23
  "devDependencies": {
24
24
  "@cloudflare/shell": "^0.3.6",
25
- "ai": "^6.0.174",
26
- "zod": "^4.4.2"
25
+ "ai": "^6.0.180",
26
+ "zod": "^4.4.3"
27
27
  },
28
28
  "peerDependencies": {
29
29
  "@cloudflare/codemode": ">=0.3.4 <1.0.0",
30
30
  "@cloudflare/shell": ">=0.3.4 <1.0.0",
31
- "agents": ">=0.12.1 <1.0.0",
31
+ "agents": ">=0.12.4 <1.0.0",
32
32
  "ai": "^6.0.0",
33
33
  "zod": "^4.0.0"
34
34
  },