@cloudflare/think 0.0.2 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,14 +12,14 @@ Works as both a **top-level agent** (WebSocket chat protocol for browser clients
12
12
  import { Think } from "@cloudflare/think";
13
13
  import { createWorkersAI } from "workers-ai-provider";
14
14
  import { createWorkspaceTools } from "@cloudflare/think/tools/workspace";
15
- import { Workspace } from "agents/experimental/workspace";
15
+ import { Workspace } from "@cloudflare/shell";
16
16
 
17
17
  export class ChatSession extends Think<Env> {
18
- workspace = new Workspace(this);
18
+ workspace = new Workspace({ sql: this.ctx.storage.sql });
19
19
 
20
20
  getModel() {
21
21
  return createWorkersAI({ binding: this.env.AI })(
22
- "@cf/meta/llama-3.3-70b-instruct-fp8-fast"
22
+ "@cf/moonshotai/kimi-k2.5"
23
23
  );
24
24
  }
25
25
 
@@ -1,25 +1,25 @@
1
- //#region \0@oxc-project+runtime@0.115.0/helpers/checkPrivateRedeclaration.js
1
+ //#region \0@oxc-project+runtime@0.122.0/helpers/checkPrivateRedeclaration.js
2
2
  function _checkPrivateRedeclaration(e, t) {
3
3
  if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object");
4
4
  }
5
5
  //#endregion
6
- //#region \0@oxc-project+runtime@0.115.0/helpers/classPrivateFieldInitSpec.js
6
+ //#region \0@oxc-project+runtime@0.122.0/helpers/classPrivateFieldInitSpec.js
7
7
  function _classPrivateFieldInitSpec(e, t, a) {
8
8
  _checkPrivateRedeclaration(e, t), t.set(e, a);
9
9
  }
10
10
  //#endregion
11
- //#region \0@oxc-project+runtime@0.115.0/helpers/assertClassBrand.js
11
+ //#region \0@oxc-project+runtime@0.122.0/helpers/assertClassBrand.js
12
12
  function _assertClassBrand(e, t, n) {
13
13
  if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n;
14
14
  throw new TypeError("Private element is not present on this object");
15
15
  }
16
16
  //#endregion
17
- //#region \0@oxc-project+runtime@0.115.0/helpers/classPrivateFieldGet2.js
17
+ //#region \0@oxc-project+runtime@0.122.0/helpers/classPrivateFieldGet2.js
18
18
  function _classPrivateFieldGet2(s, a) {
19
19
  return s.get(_assertClassBrand(s, a));
20
20
  }
21
21
  //#endregion
22
- //#region \0@oxc-project+runtime@0.115.0/helpers/classPrivateFieldSet2.js
22
+ //#region \0@oxc-project+runtime@0.122.0/helpers/classPrivateFieldSet2.js
23
23
  function _classPrivateFieldSet2(s, a, r) {
24
24
  return s.set(_assertClassBrand(s, a), r), r;
25
25
  }
@@ -1,5 +1,5 @@
1
- import { a as _checkPrivateRedeclaration } from "./classPrivateFieldSet2-COLddhya.js";
2
- //#region \0@oxc-project+runtime@0.115.0/helpers/classPrivateMethodInitSpec.js
1
+ import { a as _checkPrivateRedeclaration } from "./classPrivateFieldSet2-q3BTMj1l.js";
2
+ //#region \0@oxc-project+runtime@0.122.0/helpers/classPrivateMethodInitSpec.js
3
3
  function _classPrivateMethodInitSpec(e, a) {
4
4
  _checkPrivateRedeclaration(e, a), a.add(e);
5
5
  }
@@ -1,6 +1,6 @@
1
- import { r as _assertClassBrand } from "../classPrivateFieldSet2-COLddhya.js";
2
- import { t as _classPrivateMethodInitSpec } from "../classPrivateMethodInitSpec-CdQXQy1O.js";
3
- import { t as ExtensionManager } from "../manager-DIV0gQf3.js";
1
+ import { r as _assertClassBrand } from "../classPrivateFieldSet2-q3BTMj1l.js";
2
+ import { t as _classPrivateMethodInitSpec } from "../classPrivateMethodInitSpec-CvUe57wu.js";
3
+ import { t as ExtensionManager } from "../manager-JX4H9C6S.js";
4
4
  import { WorkerEntrypoint } from "cloudflare:workers";
5
5
  //#region src/extensions/host-bridge.ts
6
6
  /**
@@ -1,5 +1,5 @@
1
- import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, r as _assertClassBrand, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-COLddhya.js";
2
- import { t as _classPrivateMethodInitSpec } from "./classPrivateMethodInitSpec-CdQXQy1O.js";
1
+ import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, r as _assertClassBrand, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-q3BTMj1l.js";
2
+ import { t as _classPrivateMethodInitSpec } from "./classPrivateMethodInitSpec-CvUe57wu.js";
3
3
  import { jsonSchema, tool } from "ai";
4
4
  //#region src/extensions/manager.ts
5
5
  /**
@@ -211,4 +211,4 @@ export default class Extension extends WorkerEntrypoint {
211
211
  //#endregion
212
212
  export { sanitizeName as n, ExtensionManager as t };
213
213
 
214
- //# sourceMappingURL=manager-DIV0gQf3.js.map
214
+ //# sourceMappingURL=manager-JX4H9C6S.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"manager-DIV0gQf3.js","names":[],"sources":["../src/extensions/manager.ts"],"sourcesContent":["/**\n * ExtensionManager — loads, manages, and exposes tools from extension Workers.\n *\n * Extensions are sandboxed Workers created via WorkerLoader. Each extension\n * declares tools (with JSON Schema inputs) and permissions. The manager:\n *\n * 1. Wraps extension source in a Worker module with describe/execute RPC\n * 2. Loads it via WorkerLoader with permission-gated bindings\n * 3. Discovers tools via describe() RPC call\n * 4. Exposes them as AI SDK tools via getTools()\n *\n * Extension source format — a JS object expression defining tools:\n *\n * ```js\n * ({\n * greet: {\n * description: \"Greet someone\",\n * parameters: { name: { type: \"string\" } },\n * required: [\"name\"],\n * execute: async (args, host) => `Hello, ${args.name}!`\n * }\n * })\n * ```\n *\n * The `host` parameter in execute is provided via `env.host` — a loopback\n * binding that resolves the parent agent and delegates workspace operations\n * (gated by permissions). See HostBridgeLoopback.\n */\n\nimport { tool, jsonSchema } from \"ai\";\nimport type { ToolSet } from \"ai\";\nimport type {\n ExtensionManifest,\n ExtensionPermissions,\n ExtensionInfo,\n ExtensionToolDescriptor\n} from \"./types\";\n\n/**\n * Sanitize a name for use as a tool name prefix.\n * Replaces any non-alphanumeric characters with underscores and\n * collapses consecutive underscores.\n */\nexport function sanitizeName(name: string): string {\n if (!name || name.trim().length === 0) {\n throw new Error(\"Extension name must not be empty\");\n }\n return name\n .replace(/[^a-zA-Z0-9]/g, \"_\")\n .replace(/_+/g, \"_\")\n .replace(/^_|_$/g, \"\");\n}\n\ninterface ExtensionEntrypoint {\n describe(): Promise<string>;\n execute(toolName: string, argsJson: string): Promise<string>;\n}\n\ninterface LoadedExtension {\n manifest: ExtensionManifest;\n tools: ExtensionToolDescriptor[];\n entrypoint: ExtensionEntrypoint;\n}\n\n/** Shape persisted to DO storage for each extension. */\ninterface PersistedExtension {\n manifest: ExtensionManifest;\n source: string;\n}\n\nconst STORAGE_PREFIX = \"ext:\";\n\nexport interface ExtensionManagerOptions {\n /** WorkerLoader binding for creating sandboxed extension Workers. */\n loader: WorkerLoader;\n /**\n * Durable Object storage for persisting extensions across hibernation.\n * If provided, loaded extensions survive DO restarts. Call `restore()`\n * on each turn to rebuild in-memory state from storage.\n */\n storage?: DurableObjectStorage;\n /**\n * Factory that creates a loopback Fetcher for workspace access, given\n * an extension's declared permissions. The returned binding is injected\n * into the extension worker's `env.host`.\n *\n * If not provided, extensions receive no host binding (workspace tools\n * will get `null` for the host parameter).\n *\n * Typically wired up using HostBridgeLoopback via `ctx.exports`:\n * ```typescript\n * createHostBinding: (permissions) =>\n * ctx.exports.HostBridgeLoopback({\n * props: { agentClassName: \"ChatSession\", agentId: ctx.id.toString(), permissions }\n * })\n * ```\n */\n createHostBinding?: (permissions: ExtensionPermissions) => Fetcher;\n}\n\nexport class ExtensionManager {\n #loader: WorkerLoader;\n #storage: DurableObjectStorage | null;\n #createHostBinding: ((permissions: ExtensionPermissions) => Fetcher) | null;\n #extensions = new Map<string, LoadedExtension>();\n #restored = false;\n\n constructor(options: ExtensionManagerOptions) {\n this.#loader = options.loader;\n this.#storage = options.storage ?? null;\n this.#createHostBinding = options.createHostBinding ?? null;\n }\n\n /**\n * Load an extension from source code.\n *\n * The source is a JS object expression defining tools. Each tool has\n * `description`, `parameters` (JSON Schema properties), optional\n * `required` array, and an `execute` async function.\n *\n * @returns Summary of the loaded extension including discovered tools.\n */\n /**\n * Restore extensions from DO storage after hibernation.\n *\n * Idempotent — skips extensions already in memory. Call this at the\n * start of each chat turn (e.g. in onChatMessage before getTools).\n */\n async restore(): Promise<void> {\n if (this.#restored || !this.#storage) return;\n this.#restored = true;\n\n const entries = await this.#storage.list<PersistedExtension>({\n prefix: STORAGE_PREFIX\n });\n\n for (const persisted of entries.values()) {\n if (this.#extensions.has(persisted.manifest.name)) continue;\n await this.#loadInternal(persisted.manifest, persisted.source);\n }\n }\n\n async load(\n manifest: ExtensionManifest,\n source: string\n ): Promise<ExtensionInfo> {\n if (this.#extensions.has(manifest.name)) {\n throw new Error(\n `Extension \"${manifest.name}\" is already loaded. Unload it first.`\n );\n }\n\n const info = await this.#loadInternal(manifest, source);\n\n // Persist to storage so it survives hibernation\n if (this.#storage) {\n await this.#storage.put<PersistedExtension>(\n `${STORAGE_PREFIX}${manifest.name}`,\n { manifest, source }\n );\n }\n\n return info;\n }\n\n async #loadInternal(\n manifest: ExtensionManifest,\n source: string\n ): Promise<ExtensionInfo> {\n const workerModule = wrapExtensionSource(source);\n const permissions = manifest.permissions ?? {};\n\n // Build env bindings for the dynamic worker. If a host binding\n // factory is configured and the extension declares workspace\n // access, inject a loopback Fetcher as env.host.\n const workerEnv: Record<string, Fetcher> = {};\n const wsLevel = permissions.workspace ?? \"none\";\n if (this.#createHostBinding && wsLevel !== \"none\") {\n workerEnv.host = this.#createHostBinding(permissions);\n }\n\n const worker = this.#loader.get(\n `ext-${manifest.name}-${manifest.version}-${Date.now()}`,\n () => ({\n compatibilityDate: \"2025-06-01\",\n compatibilityFlags: [\"nodejs_compat\"],\n mainModule: \"extension.js\",\n modules: { \"extension.js\": workerModule },\n globalOutbound: permissions.network?.length ? undefined : null,\n ...(Object.keys(workerEnv).length > 0 ? { env: workerEnv } : {})\n })\n );\n\n const entrypoint = worker.getEntrypoint() as unknown as ExtensionEntrypoint;\n\n // Discover tools via RPC\n const descriptorsJson = await entrypoint.describe();\n const tools = JSON.parse(descriptorsJson) as ExtensionToolDescriptor[];\n\n this.#extensions.set(manifest.name, { manifest, tools, entrypoint });\n\n return toExtensionInfo(manifest, tools);\n }\n\n /**\n * Unload an extension, removing its tools from the agent.\n */\n async unload(name: string): Promise<boolean> {\n const removed = this.#extensions.delete(name);\n if (removed && this.#storage) {\n await this.#storage.delete(`${STORAGE_PREFIX}${name}`);\n }\n return removed;\n }\n\n /**\n * List all loaded extensions.\n */\n list(): ExtensionInfo[] {\n return [...this.#extensions.values()].map((ext) =>\n toExtensionInfo(ext.manifest, ext.tools)\n );\n }\n\n /**\n * Get AI SDK tools from all loaded extensions.\n *\n * Tool names are prefixed with the sanitized extension name to avoid\n * collisions: e.g. extension \"github\" with tool \"create_pr\" → \"github_create_pr\".\n */\n getTools(): ToolSet {\n const tools: ToolSet = {};\n\n for (const ext of this.#extensions.values()) {\n const prefix = sanitizeName(ext.manifest.name);\n\n for (const descriptor of ext.tools) {\n const toolName = `${prefix}_${descriptor.name}`;\n\n tools[toolName] = tool({\n description: `[${ext.manifest.name}] ${descriptor.description}`,\n inputSchema: jsonSchema(\n descriptor.inputSchema as Record<string, unknown>\n ),\n execute: async (args: Record<string, unknown>) => {\n if (!this.#extensions.has(ext.manifest.name)) {\n throw new Error(\n `Extension \"${ext.manifest.name}\" has been unloaded. Tool \"${toolName}\" is no longer available.`\n );\n }\n const resultJson = await ext.entrypoint.execute(\n descriptor.name,\n JSON.stringify(args)\n );\n const parsed = JSON.parse(resultJson) as {\n result?: unknown;\n error?: string;\n };\n if (parsed.error) throw new Error(parsed.error);\n return parsed.result;\n }\n });\n }\n }\n\n return tools;\n }\n}\n\nfunction toExtensionInfo(\n manifest: ExtensionManifest,\n tools: ExtensionToolDescriptor[]\n): ExtensionInfo {\n const prefix = sanitizeName(manifest.name);\n return {\n name: manifest.name,\n version: manifest.version,\n description: manifest.description,\n tools: tools.map((t) => `${prefix}_${t.name}`),\n permissions: manifest.permissions ?? {}\n };\n}\n\n/**\n * Wrap an extension source (JS object expression) in a Worker module\n * that exposes describe() and execute() RPC methods.\n */\nfunction wrapExtensionSource(source: string): string {\n return `import { WorkerEntrypoint } from \"cloudflare:workers\";\n\nconst __tools = (${source});\n\nexport default class Extension extends WorkerEntrypoint {\n describe() {\n const descriptors = [];\n for (const [name, def] of Object.entries(__tools)) {\n descriptors.push({\n name,\n description: def.description || name,\n inputSchema: {\n type: \"object\",\n properties: def.parameters || {},\n required: def.required || []\n }\n });\n }\n return JSON.stringify(descriptors);\n }\n\n async execute(toolName, argsJson) {\n const def = __tools[toolName];\n if (!def || !def.execute) {\n return JSON.stringify({ error: \"Unknown tool: \" + toolName });\n }\n try {\n const args = JSON.parse(argsJson);\n const result = await def.execute(args, this.env.host ?? null);\n return JSON.stringify({ result });\n } catch (err) {\n return JSON.stringify({ error: err.message || String(err) });\n }\n }\n}\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,SAAgB,aAAa,MAAsB;AACjD,KAAI,CAAC,QAAQ,KAAK,MAAM,CAAC,WAAW,EAClC,OAAM,IAAI,MAAM,mCAAmC;AAErD,QAAO,KACJ,QAAQ,iBAAiB,IAAI,CAC7B,QAAQ,OAAO,IAAI,CACnB,QAAQ,UAAU,GAAG;;AAoB1B,MAAM,iBAAiB;;;;;;;AA8BvB,IAAa,mBAAb,MAA8B;CAO5B,YAAY,SAAkC;;mDANxB;oDACgB;8DACsC;gEAC9D,IAAI,KAA8B,CAAC;8CACrC,MAAM;AAGhB,yBAAA,SAAA,MAAe,QAAQ,OAAM;AAC7B,yBAAA,UAAA,MAAgB,QAAQ,WAAW,KAAI;AACvC,yBAAA,oBAAA,MAA0B,QAAQ,qBAAqB,KAAI;;;;;;;;;;;;;;;;;CAkB7D,MAAM,UAAyB;AAC7B,MAAA,uBAAA,WAAI,KAAc,IAAI,CAAA,uBAAA,UAAC,KAAa,CAAE;AACtC,yB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AAE;EAAU;EAAO;EAAY,CAAC;AAEpE,QAAO,gBAAgB,UAAU,MAAM;;AAoE3C,SAAS,gBACP,UACA,OACe;CACf,MAAM,SAAS,aAAa,SAAS,KAAK;AAC1C,QAAO;EACL,MAAM,SAAS;EACf,SAAS,SAAS;EAClB,aAAa,SAAS;EACtB,OAAO,MAAM,KAAK,MAAM,GAAG,OAAO,GAAG,EAAE,OAAO;EAC9C,aAAa,SAAS,eAAe,EAAE;EACxC;;;;;;AAOH,SAAS,oBAAoB,QAAwB;AACnD,QAAO;;mBAEU,OAAO"}
1
+ {"version":3,"file":"manager-JX4H9C6S.js","names":[],"sources":["../src/extensions/manager.ts"],"sourcesContent":["/**\n * ExtensionManager — loads, manages, and exposes tools from extension Workers.\n *\n * Extensions are sandboxed Workers created via WorkerLoader. Each extension\n * declares tools (with JSON Schema inputs) and permissions. The manager:\n *\n * 1. Wraps extension source in a Worker module with describe/execute RPC\n * 2. Loads it via WorkerLoader with permission-gated bindings\n * 3. Discovers tools via describe() RPC call\n * 4. Exposes them as AI SDK tools via getTools()\n *\n * Extension source format — a JS object expression defining tools:\n *\n * ```js\n * ({\n * greet: {\n * description: \"Greet someone\",\n * parameters: { name: { type: \"string\" } },\n * required: [\"name\"],\n * execute: async (args, host) => `Hello, ${args.name}!`\n * }\n * })\n * ```\n *\n * The `host` parameter in execute is provided via `env.host` — a loopback\n * binding that resolves the parent agent and delegates workspace operations\n * (gated by permissions). See HostBridgeLoopback.\n */\n\nimport { tool, jsonSchema } from \"ai\";\nimport type { ToolSet } from \"ai\";\nimport type {\n ExtensionManifest,\n ExtensionPermissions,\n ExtensionInfo,\n ExtensionToolDescriptor\n} from \"./types\";\n\n/**\n * Sanitize a name for use as a tool name prefix.\n * Replaces any non-alphanumeric characters with underscores and\n * collapses consecutive underscores.\n */\nexport function sanitizeName(name: string): string {\n if (!name || name.trim().length === 0) {\n throw new Error(\"Extension name must not be empty\");\n }\n return name\n .replace(/[^a-zA-Z0-9]/g, \"_\")\n .replace(/_+/g, \"_\")\n .replace(/^_|_$/g, \"\");\n}\n\ninterface ExtensionEntrypoint {\n describe(): Promise<string>;\n execute(toolName: string, argsJson: string): Promise<string>;\n}\n\ninterface LoadedExtension {\n manifest: ExtensionManifest;\n tools: ExtensionToolDescriptor[];\n entrypoint: ExtensionEntrypoint;\n}\n\n/** Shape persisted to DO storage for each extension. */\ninterface PersistedExtension {\n manifest: ExtensionManifest;\n source: string;\n}\n\nconst STORAGE_PREFIX = \"ext:\";\n\nexport interface ExtensionManagerOptions {\n /** WorkerLoader binding for creating sandboxed extension Workers. */\n loader: WorkerLoader;\n /**\n * Durable Object storage for persisting extensions across hibernation.\n * If provided, loaded extensions survive DO restarts. Call `restore()`\n * on each turn to rebuild in-memory state from storage.\n */\n storage?: DurableObjectStorage;\n /**\n * Factory that creates a loopback Fetcher for workspace access, given\n * an extension's declared permissions. The returned binding is injected\n * into the extension worker's `env.host`.\n *\n * If not provided, extensions receive no host binding (workspace tools\n * will get `null` for the host parameter).\n *\n * Typically wired up using HostBridgeLoopback via `ctx.exports`:\n * ```typescript\n * createHostBinding: (permissions) =>\n * ctx.exports.HostBridgeLoopback({\n * props: { agentClassName: \"ChatSession\", agentId: ctx.id.toString(), permissions }\n * })\n * ```\n */\n createHostBinding?: (permissions: ExtensionPermissions) => Fetcher;\n}\n\nexport class ExtensionManager {\n #loader: WorkerLoader;\n #storage: DurableObjectStorage | null;\n #createHostBinding: ((permissions: ExtensionPermissions) => Fetcher) | null;\n #extensions = new Map<string, LoadedExtension>();\n #restored = false;\n\n constructor(options: ExtensionManagerOptions) {\n this.#loader = options.loader;\n this.#storage = options.storage ?? null;\n this.#createHostBinding = options.createHostBinding ?? null;\n }\n\n /**\n * Load an extension from source code.\n *\n * The source is a JS object expression defining tools. Each tool has\n * `description`, `parameters` (JSON Schema properties), optional\n * `required` array, and an `execute` async function.\n *\n * @returns Summary of the loaded extension including discovered tools.\n */\n /**\n * Restore extensions from DO storage after hibernation.\n *\n * Idempotent — skips extensions already in memory. Call this at the\n * start of each chat turn (e.g. in onChatMessage before getTools).\n */\n async restore(): Promise<void> {\n if (this.#restored || !this.#storage) return;\n this.#restored = true;\n\n const entries = await this.#storage.list<PersistedExtension>({\n prefix: STORAGE_PREFIX\n });\n\n for (const persisted of entries.values()) {\n if (this.#extensions.has(persisted.manifest.name)) continue;\n await this.#loadInternal(persisted.manifest, persisted.source);\n }\n }\n\n async load(\n manifest: ExtensionManifest,\n source: string\n ): Promise<ExtensionInfo> {\n if (this.#extensions.has(manifest.name)) {\n throw new Error(\n `Extension \"${manifest.name}\" is already loaded. Unload it first.`\n );\n }\n\n const info = await this.#loadInternal(manifest, source);\n\n // Persist to storage so it survives hibernation\n if (this.#storage) {\n await this.#storage.put<PersistedExtension>(\n `${STORAGE_PREFIX}${manifest.name}`,\n { manifest, source }\n );\n }\n\n return info;\n }\n\n async #loadInternal(\n manifest: ExtensionManifest,\n source: string\n ): Promise<ExtensionInfo> {\n const workerModule = wrapExtensionSource(source);\n const permissions = manifest.permissions ?? {};\n\n // Build env bindings for the dynamic worker. If a host binding\n // factory is configured and the extension declares workspace\n // access, inject a loopback Fetcher as env.host.\n const workerEnv: Record<string, Fetcher> = {};\n const wsLevel = permissions.workspace ?? \"none\";\n if (this.#createHostBinding && wsLevel !== \"none\") {\n workerEnv.host = this.#createHostBinding(permissions);\n }\n\n const worker = this.#loader.get(\n `ext-${manifest.name}-${manifest.version}-${Date.now()}`,\n () => ({\n compatibilityDate: \"2025-06-01\",\n compatibilityFlags: [\"nodejs_compat\"],\n mainModule: \"extension.js\",\n modules: { \"extension.js\": workerModule },\n globalOutbound: permissions.network?.length ? undefined : null,\n ...(Object.keys(workerEnv).length > 0 ? { env: workerEnv } : {})\n })\n );\n\n const entrypoint = worker.getEntrypoint() as unknown as ExtensionEntrypoint;\n\n // Discover tools via RPC\n const descriptorsJson = await entrypoint.describe();\n const tools = JSON.parse(descriptorsJson) as ExtensionToolDescriptor[];\n\n this.#extensions.set(manifest.name, { manifest, tools, entrypoint });\n\n return toExtensionInfo(manifest, tools);\n }\n\n /**\n * Unload an extension, removing its tools from the agent.\n */\n async unload(name: string): Promise<boolean> {\n const removed = this.#extensions.delete(name);\n if (removed && this.#storage) {\n await this.#storage.delete(`${STORAGE_PREFIX}${name}`);\n }\n return removed;\n }\n\n /**\n * List all loaded extensions.\n */\n list(): ExtensionInfo[] {\n return [...this.#extensions.values()].map((ext) =>\n toExtensionInfo(ext.manifest, ext.tools)\n );\n }\n\n /**\n * Get AI SDK tools from all loaded extensions.\n *\n * Tool names are prefixed with the sanitized extension name to avoid\n * collisions: e.g. extension \"github\" with tool \"create_pr\" → \"github_create_pr\".\n */\n getTools(): ToolSet {\n const tools: ToolSet = {};\n\n for (const ext of this.#extensions.values()) {\n const prefix = sanitizeName(ext.manifest.name);\n\n for (const descriptor of ext.tools) {\n const toolName = `${prefix}_${descriptor.name}`;\n\n tools[toolName] = tool({\n description: `[${ext.manifest.name}] ${descriptor.description}`,\n inputSchema: jsonSchema(\n descriptor.inputSchema as Record<string, unknown>\n ),\n execute: async (args: Record<string, unknown>) => {\n if (!this.#extensions.has(ext.manifest.name)) {\n throw new Error(\n `Extension \"${ext.manifest.name}\" has been unloaded. Tool \"${toolName}\" is no longer available.`\n );\n }\n const resultJson = await ext.entrypoint.execute(\n descriptor.name,\n JSON.stringify(args)\n );\n const parsed = JSON.parse(resultJson) as {\n result?: unknown;\n error?: string;\n };\n if (parsed.error) throw new Error(parsed.error);\n return parsed.result;\n }\n });\n }\n }\n\n return tools;\n }\n}\n\nfunction toExtensionInfo(\n manifest: ExtensionManifest,\n tools: ExtensionToolDescriptor[]\n): ExtensionInfo {\n const prefix = sanitizeName(manifest.name);\n return {\n name: manifest.name,\n version: manifest.version,\n description: manifest.description,\n tools: tools.map((t) => `${prefix}_${t.name}`),\n permissions: manifest.permissions ?? {}\n };\n}\n\n/**\n * Wrap an extension source (JS object expression) in a Worker module\n * that exposes describe() and execute() RPC methods.\n */\nfunction wrapExtensionSource(source: string): string {\n return `import { WorkerEntrypoint } from \"cloudflare:workers\";\n\nconst __tools = (${source});\n\nexport default class Extension extends WorkerEntrypoint {\n describe() {\n const descriptors = [];\n for (const [name, def] of Object.entries(__tools)) {\n descriptors.push({\n name,\n description: def.description || name,\n inputSchema: {\n type: \"object\",\n properties: def.parameters || {},\n required: def.required || []\n }\n });\n }\n return JSON.stringify(descriptors);\n }\n\n async execute(toolName, argsJson) {\n const def = __tools[toolName];\n if (!def || !def.execute) {\n return JSON.stringify({ error: \"Unknown tool: \" + toolName });\n }\n try {\n const args = JSON.parse(argsJson);\n const result = await def.execute(args, this.env.host ?? null);\n return JSON.stringify({ result });\n } catch (err) {\n return JSON.stringify({ error: err.message || String(err) });\n }\n }\n}\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,SAAgB,aAAa,MAAsB;AACjD,KAAI,CAAC,QAAQ,KAAK,MAAM,CAAC,WAAW,EAClC,OAAM,IAAI,MAAM,mCAAmC;AAErD,QAAO,KACJ,QAAQ,iBAAiB,IAAI,CAC7B,QAAQ,OAAO,IAAI,CACnB,QAAQ,UAAU,GAAG;;AAoB1B,MAAM,iBAAiB;;;;;;;AA8BvB,IAAa,mBAAb,MAA8B;CAO5B,YAAY,SAAkC;;mDANxB;oDACgB;8DACsC;gEAC9D,IAAI,KAA8B,CAAC;8CACrC,MAAM;AAGhB,yBAAA,SAAA,MAAe,QAAQ,OAAM;AAC7B,yBAAA,UAAA,MAAgB,QAAQ,WAAW,KAAI;AACvC,yBAAA,oBAAA,MAA0B,QAAQ,qBAAqB,KAAI;;;;;;;;;;;;;;;;;CAkB7D,MAAM,UAAyB;AAC7B,MAAA,uBAAA,WAAI,KAAc,IAAI,CAAA,uBAAA,UAAC,KAAa,CAAE;AACtC,yBAAA,WAAA,MAAiB,KAAI;EAErB,MAAM,UAAU,MAAA,uBAAA,UAAM,KAAa,CAAC,KAAyB,EAC3D,QAAQ,gBACT,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AM,SAAS,aAAa,SAAS,KAAK;AAC1C,QAAO;EACL,MAAM,SAAS;EACf,SAAS,SAAS;EAClB,aAAa,SAAS;EACtB,OAAO,MAAM,KAAK,MAAM,GAAG,OAAO,GAAG,EAAE,OAAO;EAC9C,aAAa,SAAS,eAAe,EAAE;EACxC;;;;;;AAOH,SAAS,oBAAoB,QAAwB;AACnD,QAAO;;mBAEU,OAAO"}
package/dist/think.d.ts CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  FiberRecoveryContext,
10
10
  FiberState
11
11
  } from "agents/experimental/forever";
12
- import { Workspace } from "agents/experimental/workspace";
12
+ import { Workspace } from "@cloudflare/shell";
13
13
 
14
14
  //#region src/think.d.ts
15
15
  type ThinkBaseConstructor = {
@@ -153,12 +153,14 @@ declare class Think<
153
153
  _hostReadFile(path: string): Promise<string | null>;
154
154
  _hostWriteFile(path: string, content: string): Promise<void>;
155
155
  _hostDeleteFile(path: string): Promise<boolean>;
156
- _hostListFiles(dir: string): Array<{
157
- name: string;
158
- type: string;
159
- size: number;
160
- path: string;
161
- }>;
156
+ _hostListFiles(dir: string): Promise<
157
+ Array<{
158
+ name: string;
159
+ type: string;
160
+ size: number;
161
+ path: string;
162
+ }>
163
+ >;
162
164
  /**
163
165
  * Assemble the model messages from the current conversation history.
164
166
  * Override to customize context assembly (e.g. inject memory,
package/dist/think.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { t as SessionManager } from "./session-C6ZU_1zM.js";
2
2
  import { applyChunkToParts } from "./message-builder.js";
3
- import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-COLddhya.js";
3
+ import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-q3BTMj1l.js";
4
4
  import { convertToModelMessages, pruneMessages, stepCountIs, streamText } from "ai";
5
5
  import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
6
6
  import { withFibers } from "agents/experimental/forever";
@@ -254,7 +254,7 @@ var Think = class extends ThinkBase {
254
254
  if (!ws) throw new Error("No workspace available on this agent");
255
255
  return ws.deleteFile(path);
256
256
  }
257
- _hostListFiles(dir) {
257
+ async _hostListFiles(dir) {
258
258
  const ws = this.getWorkspace();
259
259
  if (!ws) throw new Error("No workspace available on this agent");
260
260
  return ws.readDir(dir);
package/dist/think.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"think.js","names":["agentContext"],"sources":["../src/sanitize.ts","../src/think.ts"],"sourcesContent":["/**\n * Message sanitization and row-size enforcement utilities.\n *\n * Shared by Think to ensure persistence\n * hygiene: stripping ephemeral provider metadata and compacting\n * oversized messages before writing to SQLite.\n */\n\nimport type { ProviderMetadata, ReasoningUIPart, UIMessage } from \"ai\";\n\n/** Shared encoder for UTF-8 byte length measurement */\nconst textEncoder = new TextEncoder();\n\n/** Maximum serialized message size before compaction (bytes). 1.8MB with headroom below SQLite's 2MB limit. */\nconst ROW_MAX_BYTES = 1_800_000;\n\n/** Measure UTF-8 byte length of a string. */\nfunction byteLength(s: string): number {\n return textEncoder.encode(s).byteLength;\n}\n\n/**\n * Sanitize a message for persistence by removing ephemeral provider-specific\n * data that should not be stored or sent back in subsequent requests.\n *\n * 1. Strips OpenAI ephemeral fields (itemId, reasoningEncryptedContent)\n * 2. Filters truly empty reasoning parts (no text, no remaining providerMetadata)\n */\nexport function sanitizeMessage(message: UIMessage): UIMessage {\n // Strip OpenAI-specific ephemeral data from all parts\n const strippedParts = message.parts.map((part) => {\n let sanitizedPart = part;\n\n if (\n \"providerMetadata\" in sanitizedPart &&\n sanitizedPart.providerMetadata &&\n typeof sanitizedPart.providerMetadata === \"object\" &&\n \"openai\" in sanitizedPart.providerMetadata\n ) {\n sanitizedPart = stripOpenAIMetadata(sanitizedPart, \"providerMetadata\");\n }\n\n if (\n \"callProviderMetadata\" in sanitizedPart &&\n sanitizedPart.callProviderMetadata &&\n typeof sanitizedPart.callProviderMetadata === \"object\" &&\n \"openai\" in sanitizedPart.callProviderMetadata\n ) {\n sanitizedPart = stripOpenAIMetadata(\n sanitizedPart,\n \"callProviderMetadata\"\n );\n }\n\n return sanitizedPart;\n }) as UIMessage[\"parts\"];\n\n // Filter out reasoning parts that are truly empty\n const sanitizedParts = strippedParts.filter((part) => {\n if (part.type === \"reasoning\") {\n const reasoningPart = part as ReasoningUIPart;\n if (!reasoningPart.text || reasoningPart.text.trim() === \"\") {\n if (\n \"providerMetadata\" in reasoningPart &&\n reasoningPart.providerMetadata &&\n typeof reasoningPart.providerMetadata === \"object\" &&\n Object.keys(reasoningPart.providerMetadata).length > 0\n ) {\n return true;\n }\n return false;\n }\n }\n return true;\n });\n\n return { ...message, parts: sanitizedParts };\n}\n\n/**\n * Strip OpenAI-specific ephemeral fields from a metadata object.\n */\nfunction stripOpenAIMetadata<T extends UIMessage[\"parts\"][number]>(\n part: T,\n metadataKey: \"providerMetadata\" | \"callProviderMetadata\"\n): T {\n const metadata = (part as Record<string, unknown>)[metadataKey] as {\n openai?: Record<string, unknown>;\n [key: string]: unknown;\n };\n\n if (!metadata?.openai) return part;\n\n const {\n itemId: _itemId,\n reasoningEncryptedContent: _rec,\n ...restOpenai\n } = metadata.openai;\n\n const hasOtherOpenaiFields = Object.keys(restOpenai).length > 0;\n const { openai: _openai, ...restMetadata } = metadata;\n\n let newMetadata: ProviderMetadata | undefined;\n if (hasOtherOpenaiFields) {\n newMetadata = { ...restMetadata, openai: restOpenai } as ProviderMetadata;\n } else if (Object.keys(restMetadata).length > 0) {\n newMetadata = restMetadata as ProviderMetadata;\n }\n\n const { [metadataKey]: _oldMeta, ...restPart } = part as Record<\n string,\n unknown\n >;\n\n if (newMetadata) {\n return { ...restPart, [metadataKey]: newMetadata } as T;\n }\n return restPart as T;\n}\n\n/**\n * Enforce SQLite row size limits by compacting tool outputs and text parts\n * when a serialized message exceeds the safety threshold (1.8MB).\n *\n * Compaction strategy:\n * 1. Compact tool outputs over 1KB (replace with summary)\n * 2. If still too big, truncate text parts from oldest to newest\n */\nexport function enforceRowSizeLimit(message: UIMessage): UIMessage {\n let json = JSON.stringify(message);\n let size = byteLength(json);\n if (size <= ROW_MAX_BYTES) return message;\n\n if (message.role !== \"assistant\") {\n return truncateTextParts(message);\n }\n\n // Pass 1: compact tool outputs\n const compactedParts = message.parts.map((part) => {\n if (\n \"output\" in part &&\n \"toolCallId\" in part &&\n \"state\" in part &&\n part.state === \"output-available\"\n ) {\n const outputJson = JSON.stringify((part as { output: unknown }).output);\n if (outputJson.length > 1000) {\n return {\n ...part,\n output:\n \"This tool output was too large to persist in storage \" +\n `(${outputJson.length} bytes). ` +\n \"If the user asks about this data, suggest re-running the tool. \" +\n `Preview: ${outputJson.slice(0, 500)}...`\n };\n }\n }\n return part;\n }) as UIMessage[\"parts\"];\n\n let result: UIMessage = { ...message, parts: compactedParts };\n\n json = JSON.stringify(result);\n size = byteLength(json);\n if (size <= ROW_MAX_BYTES) return result;\n\n // Pass 2: truncate text parts\n return truncateTextParts(result);\n}\n\n/**\n * Truncate text parts to fit within the row size limit.\n */\nfunction truncateTextParts(message: UIMessage): UIMessage {\n const parts = [...message.parts];\n\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n if (part.type === \"text\" && \"text\" in part) {\n const text = (part as { text: string }).text;\n if (text.length > 1000) {\n parts[i] = {\n ...part,\n text:\n `[Text truncated for storage (${text.length} chars). ` +\n `First 500 chars: ${text.slice(0, 500)}...]`\n } as UIMessage[\"parts\"][number];\n\n const candidate = { ...message, parts };\n if (byteLength(JSON.stringify(candidate)) <= ROW_MAX_BYTES) {\n break;\n }\n }\n }\n }\n\n return { ...message, parts };\n}\n","/**\n * Think — a unified Agent base class for chat sessions.\n *\n * Works as both a **top-level agent** (speaking the `cf_agent_chat_*`\n * WebSocket protocol to browser clients) and a **sub-agent** (called\n * via `chat()` over RPC from a parent agent).\n *\n * Each instance gets its own SQLite storage and runs the full chat\n * lifecycle:\n * store user message → assemble context → call LLM → stream events → persist response\n *\n * Uses SessionManager for message persistence, giving you branching and\n * compaction support for free.\n *\n * Override points:\n * - getModel() — return the LanguageModel to use\n * - getSystemPrompt() — return the system prompt\n * - getTools() — return the ToolSet for the agentic loop\n * - getMaxSteps() — max tool-call rounds per turn (default: 10)\n * - assembleContext() — customize context assembly from this.messages\n * - onChatMessage() — full control over inference (override the agentic loop)\n * - onChatError() — customize error handling\n *\n * Production features:\n * - WebSocket chat protocol (compatible with useAgentChat / useChat)\n * - Multi-session management (create, switch, list, delete, rename)\n * - Sub-agent RPC streaming via StreamCallback\n * - Abort/cancel support via AbortSignal\n * - Error handling with partial message persistence\n * - Message sanitization (strips OpenAI ephemeral metadata)\n * - Row size enforcement (compacts large tool outputs)\n * - Configurable storage bounds (maxPersistedMessages)\n * - Incremental persistence (skips unchanged messages)\n * - Richer input (accepts UIMessage or string)\n *\n * @experimental Requires the `\"experimental\"` compatibility flag.\n *\n * @example\n * ```typescript\n * import { Think } from \"@cloudflare/think\";\n * import { createWorkersAI } from \"workers-ai-provider\";\n * import { createWorkspaceTools } from \"@cloudflare/think/tools/workspace\";\n * import { Workspace } from \"agents/experimental/workspace\";\n *\n * export class ChatSession extends Think<Env> {\n * workspace = new Workspace(this);\n *\n * getModel() {\n * return createWorkersAI({ binding: this.env.AI })(\"@cf/meta/llama-3.3-70b-instruct-fp8-fast\");\n * }\n *\n * getTools() {\n * return createWorkspaceTools(this.workspace);\n * }\n * }\n * ```\n */\n\nimport type { LanguageModel, ModelMessage, ToolSet, UIMessage } from \"ai\";\nimport {\n convertToModelMessages,\n pruneMessages,\n stepCountIs,\n streamText\n} from \"ai\";\nimport {\n Agent,\n __DO_NOT_USE_WILL_BREAK__agentContext as agentContext\n} from \"agents\";\nimport type { Connection, WSMessage } from \"agents\";\nimport type { Workspace } from \"agents/experimental/workspace\";\nimport { withFibers } from \"agents/experimental/forever\";\nimport type { FiberMethods } from \"agents/experimental/forever\";\nimport { SessionManager } from \"./session/index\";\nimport type { Session } from \"./session/index\";\nimport { applyChunkToParts } from \"./message-builder\";\nimport type { StreamChunkData } from \"./message-builder\";\nimport { sanitizeMessage, enforceRowSizeLimit } from \"./sanitize\";\n\nexport type { Session } from \"./session/index\";\nexport type {\n FiberState,\n FiberRecoveryContext,\n FiberContext,\n FiberCompleteContext,\n FiberMethods\n} from \"agents/experimental/forever\";\n\n// ── Fiber base class ──────────────────────────────────────────────────\n// Think extends withFibers(Agent) so fiber methods (spawnFiber, etc.)\n// are always available on the prototype. The `fibers` flag controls\n// whether interrupted fibers are recovered on start.\n//\n// The type cast preserves Agent's generic constructor while adding\n// FiberMethods to the instance type, avoiding unsafe interface merging.\ntype ThinkBaseConstructor = {\n new <\n Env extends Cloudflare.Env = Cloudflare.Env,\n State = unknown,\n Props extends Record<string, unknown> = Record<string, unknown>\n >(\n ctx: DurableObjectState,\n env: Env\n ): Agent<Env, State, Props> & FiberMethods;\n};\n\nconst ThinkBase = withFibers(Agent) as unknown as ThinkBaseConstructor;\n\n// ── Wire protocol constants ────────────────────────────────────────\n// These string values are wire-compatible with @cloudflare/ai-chat's\n// MessageType enum. Defined locally to avoid a circular dependency.\nconst MSG_CHAT_MESSAGES = \"cf_agent_chat_messages\";\nconst MSG_CHAT_REQUEST = \"cf_agent_use_chat_request\";\nconst MSG_CHAT_RESPONSE = \"cf_agent_use_chat_response\";\nconst MSG_CHAT_CLEAR = \"cf_agent_chat_clear\";\nconst MSG_CHAT_CANCEL = \"cf_agent_chat_request_cancel\";\n\n/**\n * Callback interface for streaming chat events from a Think.\n *\n * Designed to work across the sub-agent RPC boundary — implement as\n * an RpcTarget in the parent agent and pass to `chat()`.\n *\n * Methods may return a Promise for async RPC callbacks.\n */\nexport interface StreamCallback {\n /** Called for each UIMessageChunk event during streaming. */\n onEvent(json: string): void | Promise<void>;\n /** Called when the stream completes successfully (not called on abort). */\n onDone(): void | Promise<void>;\n /** Called when an error occurs during streaming. */\n onError?(error: string): void | Promise<void>;\n}\n\n/**\n * Minimal interface for the result of `onChatMessage()`.\n * Must provide a `toUIMessageStream()` method that returns an\n * async-iterable stream of UI message chunks.\n *\n * The AI SDK's `streamText()` result satisfies this interface.\n */\nexport interface StreamableResult {\n toUIMessageStream(): AsyncIterable<unknown>;\n}\n\n/**\n * Options for a chat turn (sub-agent RPC entry point).\n */\nexport interface ChatOptions {\n /** AbortSignal — fires when the caller wants to cancel the turn. */\n signal?: AbortSignal;\n /** Extra tools to merge with getTools() for this turn only. */\n tools?: ToolSet;\n}\n\n/**\n * Options passed to the onChatMessage handler.\n */\nexport interface ChatMessageOptions {\n /** AbortSignal for cancelling the request */\n signal?: AbortSignal;\n /** Extra tools to merge with getTools() for this turn only. */\n tools?: ToolSet;\n}\n\n/**\n * A unified Agent base class for chat sessions.\n *\n * Works as both a top-level agent (WebSocket chat protocol) and a\n * sub-agent (RPC streaming via `chat()`).\n *\n * @experimental Requires the `\"experimental\"` compatibility flag.\n */\nexport class Think<\n Env extends Cloudflare.Env = Cloudflare.Env,\n Config = Record<string, unknown>\n> extends (ThinkBase as ThinkBaseConstructor)<Env> {\n /** Session manager — persistence layer with branching and compaction. */\n sessions!: SessionManager;\n\n /** In-memory messages for the current conversation. Authoritative after load. */\n messages: UIMessage[] = [];\n\n /**\n * Enable durable fiber recovery on start. Set to `true` to\n * automatically recover interrupted fibers when the DO restarts.\n *\n * Fiber methods (`spawnFiber()`, `stashFiber()`, etc.) are always\n * available — this flag only controls automatic recovery.\n *\n * @experimental\n */\n fibers = false;\n\n /**\n * Maximum number of messages to keep in storage per session.\n * When exceeded, oldest messages are deleted after each persist.\n * Set to `undefined` (default) for no limit.\n *\n * This controls storage only — it does not affect what's sent to the LLM.\n * Use `pruneMessages()` in `assembleContext()` to control LLM context.\n */\n maxPersistedMessages: number | undefined = undefined;\n\n /**\n * Cache of last-persisted JSON for each message ID.\n * Used for incremental persistence: skip SQL writes for unchanged messages.\n * @internal\n */\n private _persistedMessageCache: Map<string, string> = new Map();\n\n private _sessionId: string | null = null;\n private _abortControllers = new Map<string, AbortController>();\n private _clearGeneration = 0;\n\n // ── Dynamic config ──────────────────────────────────────────────\n\n #configTableReady = false;\n #configCache: Config | null = null;\n\n private _ensureConfigTable(): void {\n if (this.#configTableReady) return;\n this.sql`\n CREATE TABLE IF NOT EXISTS _think_config (\n key TEXT PRIMARY KEY, value TEXT NOT NULL\n )\n `;\n this.#configTableReady = true;\n }\n\n /**\n * Persist a typed configuration object.\n * Stored in SQLite so it survives restarts and hibernation.\n */\n configure(config: Config): void {\n this._ensureConfigTable();\n const json = JSON.stringify(config);\n this.sql`\n INSERT OR REPLACE INTO _think_config (key, value) VALUES ('config', ${json})\n `;\n this.#configCache = config;\n }\n\n /**\n * Read the persisted configuration, or null if never configured.\n */\n getConfig(): Config | null {\n if (this.#configCache) return this.#configCache;\n this._ensureConfigTable();\n const rows = this.sql<{ value: string }>`\n SELECT value FROM _think_config WHERE key = 'config'\n `;\n if (rows.length > 0) {\n this.#configCache = JSON.parse(rows[0].value) as Config;\n return this.#configCache;\n }\n return null;\n }\n\n onStart() {\n this.sessions = new SessionManager(this, {\n exec: (query, ...values) => {\n this.ctx.storage.sql.exec(query, ...values);\n }\n });\n const existing = this.sessions.list();\n if (existing.length > 0) {\n this._sessionId = existing[0].id;\n this.messages = this.sessions.getHistory(this._sessionId);\n this._rebuildPersistenceCache();\n }\n this._setupProtocolHandlers();\n\n if (this.fibers) {\n void this.checkFibers();\n }\n }\n\n // ── Override points ──────────────────────────────────────────────\n\n /**\n * Return the language model to use for inference.\n * Must be overridden by subclasses that rely on the default\n * `onChatMessage` implementation (the agentic loop).\n */\n getModel(): LanguageModel {\n throw new Error(\n \"Override getModel() to return a LanguageModel, or override onChatMessage() for full control.\"\n );\n }\n\n /**\n * Return the system prompt for the assistant.\n * Override to customize instructions.\n */\n getSystemPrompt(): string {\n return \"You are a helpful assistant.\";\n }\n\n /**\n * Return the tools available to the assistant.\n * Override to provide workspace tools, custom tools, etc.\n */\n getTools(): ToolSet {\n return {};\n }\n\n /**\n * Return the maximum number of tool-call steps per turn.\n */\n getMaxSteps(): number {\n return 10;\n }\n\n /**\n * Return the workspace instance for this session, or null if none.\n *\n * Override in subclasses that create a Workspace. Used by\n * HostBridgeLoopback to provide workspace access to extension Workers.\n */\n getWorkspace(): Workspace | null {\n return null;\n }\n\n // ── Workspace proxy methods (called by HostBridgeLoopback via RPC) ──\n\n async _hostReadFile(path: string): Promise<string | null> {\n const ws = this.getWorkspace();\n if (!ws) throw new Error(\"No workspace available on this agent\");\n return ws.readFile(path);\n }\n\n async _hostWriteFile(path: string, content: string): Promise<void> {\n const ws = this.getWorkspace();\n if (!ws) throw new Error(\"No workspace available on this agent\");\n await ws.writeFile(path, content);\n }\n\n async _hostDeleteFile(path: string): Promise<boolean> {\n const ws = this.getWorkspace();\n if (!ws) throw new Error(\"No workspace available on this agent\");\n return ws.deleteFile(path);\n }\n\n _hostListFiles(\n dir: string\n ): Array<{ name: string; type: string; size: number; path: string }> {\n const ws = this.getWorkspace();\n if (!ws) throw new Error(\"No workspace available on this agent\");\n return ws.readDir(dir);\n }\n\n /**\n * Assemble the model messages from the current conversation history.\n * Override to customize context assembly (e.g. inject memory,\n * project context, or apply compaction).\n */\n async assembleContext(): Promise<ModelMessage[]> {\n return pruneMessages({\n messages: await convertToModelMessages(this.messages),\n toolCalls: \"before-last-2-messages\"\n });\n }\n\n /**\n * Handle a chat turn and return the streaming result.\n *\n * The default implementation runs the agentic loop:\n * 1. Assemble context from `this.messages`\n * 2. Call `streamText` with the model, system prompt, tools, and step limit\n *\n * Override for full control over inference (e.g. different models per turn,\n * RAG pipelines, routing to specialized sub-agents, etc.).\n *\n * When this is called, `this.messages` already contains the user's\n * latest message persisted to the current session.\n *\n * @returns A result with `toUIMessageStream()` — AI SDK's `streamText()`\n * return value satisfies this interface.\n */\n async onChatMessage(options?: ChatMessageOptions): Promise<StreamableResult> {\n const baseTools = this.getTools();\n const tools = options?.tools\n ? { ...baseTools, ...options.tools }\n : baseTools;\n return streamText({\n model: this.getModel(),\n system: this.getSystemPrompt(),\n messages: await this.assembleContext(),\n tools,\n stopWhen: stepCountIs(this.getMaxSteps()),\n abortSignal: options?.signal\n });\n }\n\n /**\n * Handle an error that occurred during a chat turn.\n * Override to customize error handling (e.g. logging, metrics).\n *\n * @param error The error that occurred\n * @returns The error (or a wrapped version) to propagate\n */\n onChatError(error: unknown): unknown {\n return error;\n }\n\n // ── Sub-agent RPC entry point ───────────────────────────────────\n\n /**\n * Run a chat turn: persist the user message, run the agentic loop,\n * stream UIMessageChunk events via callback, and persist the\n * assistant's response.\n *\n * On error or abort, the partial assistant message is still persisted\n * so the user doesn't lose context.\n *\n * @param userMessage The user's message (string or UIMessage for multi-modal)\n * @param callback Streaming callback (typically an RpcTarget from the parent)\n * @param options Optional chat options (e.g. AbortSignal)\n */\n async chat(\n userMessage: string | UIMessage,\n callback: StreamCallback,\n options?: ChatOptions\n ): Promise<void> {\n // Ensure a session exists\n if (!this._sessionId) {\n const session = this.sessions.create(\"default\");\n this._sessionId = session.id;\n }\n\n // Persist user message\n const userMsg: UIMessage =\n typeof userMessage === \"string\"\n ? {\n id: crypto.randomUUID(),\n role: \"user\",\n parts: [{ type: \"text\", text: userMessage }]\n }\n : userMessage;\n\n this.sessions.append(this._sessionId, userMsg);\n this.messages = this.sessions.getHistory(this._sessionId);\n\n // Build assistant message from stream chunks\n const assistantMsg: UIMessage = {\n id: crypto.randomUUID(),\n role: \"assistant\",\n parts: []\n };\n\n try {\n // Run the agentic loop (or custom override)\n const result = await this.onChatMessage({\n signal: options?.signal,\n tools: options?.tools\n });\n\n // Stream UIMessageChunk events via callback\n let aborted = false;\n for await (const chunk of result.toUIMessageStream()) {\n if (options?.signal?.aborted) {\n aborted = true;\n break;\n }\n applyChunkToParts(\n assistantMsg.parts,\n chunk as unknown as StreamChunkData\n );\n await callback.onEvent(JSON.stringify(chunk));\n }\n\n // Persist assistant message (sanitized + size-enforced)\n this._persistAssistantMessage(assistantMsg);\n\n // Only signal completion if not aborted\n if (!aborted) {\n await callback.onDone();\n }\n } catch (error) {\n // Persist partial assistant message so context isn't lost\n if (assistantMsg.parts.length > 0) {\n this._persistAssistantMessage(assistantMsg);\n }\n\n const wrapped = this.onChatError(error);\n const errorMessage =\n wrapped instanceof Error ? wrapped.message : String(wrapped);\n\n if (callback.onError) {\n await callback.onError(errorMessage);\n } else {\n // Re-throw if no error callback — caller must handle it\n throw wrapped;\n }\n }\n }\n\n // ── Session management ─────────────────────────────────────────\n\n getSessions(): Session[] {\n return this.sessions.list();\n }\n\n createSession(name: string): Session {\n const session = this.sessions.create(name);\n this._sessionId = session.id;\n this.messages = [];\n this._broadcastMessages();\n return session;\n }\n\n switchSession(sessionId: string): UIMessage[] {\n const session = this.sessions.get(sessionId);\n if (!session) {\n throw new Error(`Session not found: ${sessionId}`);\n }\n this._sessionId = sessionId;\n this.messages = this.sessions.getHistory(sessionId);\n this._broadcastMessages();\n return this.messages;\n }\n\n deleteSession(sessionId: string): void {\n const session = this.sessions.get(sessionId);\n if (!session) {\n throw new Error(`Session not found: ${sessionId}`);\n }\n this.sessions.delete(sessionId);\n if (this._sessionId === sessionId) {\n this._sessionId = null;\n this.messages = [];\n this._broadcastMessages();\n }\n }\n\n renameSession(sessionId: string, name: string): void {\n const session = this.sessions.get(sessionId);\n if (!session) {\n throw new Error(`Session not found: ${sessionId}`);\n }\n this.sessions.rename(sessionId, name);\n }\n\n getCurrentSessionId(): string | null {\n return this._sessionId;\n }\n\n // ── Message access ───────────────────────────────────────────────\n\n /**\n * Get the current session info, or null if no session exists yet.\n */\n getSession(): Session | null {\n if (!this._sessionId) return null;\n return this.sessions.get(this._sessionId);\n }\n\n /**\n * Get the conversation history as UIMessage[].\n */\n getHistory(): UIMessage[] {\n if (!this._sessionId) return [];\n return this.sessions.getHistory(this._sessionId);\n }\n\n /**\n * Get the total message count for this session.\n */\n getMessageCount(): number {\n if (!this._sessionId) return 0;\n return this.sessions.getMessageCount(this._sessionId);\n }\n\n /**\n * Clear all messages from this session (preserves the session itself).\n */\n clearMessages(): void {\n if (!this._sessionId) return;\n this.sessions.clearMessages(this._sessionId);\n this.messages = [];\n this._persistedMessageCache.clear();\n }\n\n // ── WebSocket protocol ──────────────────────────────────────────\n\n /**\n * Wrap onMessage and onRequest to intercept the chat protocol.\n * Unrecognized messages are forwarded to the user's handlers.\n * @internal\n */\n private _setupProtocolHandlers() {\n const _onMessage = this.onMessage.bind(this);\n this.onMessage = async (connection: Connection, message: WSMessage) => {\n if (typeof message === \"string\") {\n try {\n const data = JSON.parse(message) as Record<string, unknown>;\n if (await this._handleProtocol(connection, data)) return;\n } catch {\n // Not JSON — fall through to user handler\n }\n }\n return _onMessage(connection, message);\n };\n\n const _onRequest = this.onRequest.bind(this);\n this.onRequest = async (request: Request) => {\n const url = new URL(request.url);\n if (\n url.pathname === \"/get-messages\" ||\n url.pathname.endsWith(\"/get-messages\")\n ) {\n const sessionId = url.searchParams.get(\"sessionId\");\n if (sessionId) {\n const session = this.sessions.get(sessionId);\n if (!session) {\n return Response.json(\n { error: \"Session not found\" },\n { status: 404 }\n );\n }\n return Response.json(this.sessions.getHistory(sessionId));\n }\n return Response.json(this.messages);\n }\n return _onRequest(request);\n };\n }\n\n /**\n * Route an incoming WebSocket message to the appropriate handler.\n * Returns true if the message was handled by the protocol.\n * @internal\n */\n private async _handleProtocol(\n connection: Connection,\n data: Record<string, unknown>\n ): Promise<boolean> {\n const type = data.type as string;\n\n if (type === MSG_CHAT_REQUEST) {\n const init = data.init as { method?: string; body?: string } | undefined;\n if (init?.method === \"POST\") {\n await this._handleChatRequest(connection, data);\n return true;\n }\n }\n\n if (type === MSG_CHAT_CLEAR) {\n this._handleClear();\n return true;\n }\n\n if (type === MSG_CHAT_CANCEL) {\n this._handleCancel(data.id as string);\n return true;\n }\n\n return false;\n }\n\n /**\n * Handle CF_AGENT_USE_CHAT_REQUEST:\n * 1. Parse incoming messages\n * 2. Ensure a session exists\n * 3. Persist user messages to session\n * 4. Call onChatMessage\n * 5. Stream response back to clients\n * 6. Persist assistant message to session\n * @internal\n */\n private async _handleChatRequest(\n connection: Connection,\n data: Record<string, unknown>\n ) {\n const init = data.init as { body?: string };\n if (!init?.body) return;\n\n let parsed: { messages?: UIMessage[] };\n try {\n parsed = JSON.parse(init.body) as { messages?: UIMessage[] };\n } catch {\n return;\n }\n\n const incomingMessages = parsed.messages;\n if (!Array.isArray(incomingMessages)) return;\n\n // Ensure a session exists\n if (!this._sessionId) {\n const session = this.sessions.create(\"New Chat\");\n this._sessionId = session.id;\n }\n\n // Persist incoming messages to session (idempotent via INSERT OR IGNORE)\n this.sessions.appendAll(this._sessionId, incomingMessages);\n\n // Reload from session (authoritative)\n this.messages = this.sessions.getHistory(this._sessionId);\n\n // Broadcast updated messages to other connections\n this._broadcastMessages([connection.id]);\n\n // Set up abort controller\n const requestId = data.id as string;\n const abortController = new AbortController();\n this._abortControllers.set(requestId, abortController);\n\n try {\n await this.keepAliveWhile(async () => {\n const result = await agentContext.run(\n { agent: this, connection, request: undefined, email: undefined },\n () =>\n this.onChatMessage({\n signal: abortController.signal\n })\n );\n\n if (result) {\n await this._streamResult(requestId, result, abortController.signal);\n } else {\n this._broadcast({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"No response was generated.\",\n done: true\n });\n }\n });\n } catch (error) {\n this._broadcast({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: error instanceof Error ? error.message : \"Error\",\n done: true,\n error: true\n });\n } finally {\n this._abortControllers.delete(requestId);\n }\n }\n\n /**\n * Handle CF_AGENT_CHAT_CLEAR: abort streams, clear current session messages.\n * @internal\n */\n private _handleClear() {\n for (const controller of this._abortControllers.values()) {\n controller.abort();\n }\n this._abortControllers.clear();\n\n if (this._sessionId) {\n this.sessions.clearMessages(this._sessionId);\n }\n\n this.messages = [];\n this._persistedMessageCache.clear();\n this._clearGeneration++;\n this._broadcast({ type: MSG_CHAT_CLEAR });\n }\n\n /**\n * Handle CF_AGENT_CHAT_REQUEST_CANCEL: abort a specific request.\n * @internal\n */\n private _handleCancel(requestId: string) {\n const controller = this._abortControllers.get(requestId);\n if (controller) {\n controller.abort();\n }\n }\n\n /**\n * Iterate a StreamableResult, broadcast chunks to clients,\n * build a UIMessage, and persist it to the session.\n * @internal\n */\n private async _streamResult(\n requestId: string,\n result: StreamableResult,\n abortSignal?: AbortSignal\n ) {\n const clearGen = this._clearGeneration;\n\n const message: UIMessage = {\n id: crypto.randomUUID(),\n role: \"assistant\",\n parts: []\n };\n\n let doneSent = false;\n\n try {\n for await (const chunk of result.toUIMessageStream()) {\n if (abortSignal?.aborted) break;\n\n const data = chunk as StreamChunkData;\n\n // Build UIMessage from stream events\n const handled = applyChunkToParts(message.parts, data);\n\n if (!handled) {\n // Handle metadata events that applyChunkToParts doesn't cover\n switch (data.type) {\n case \"start\": {\n if (data.messageId != null) {\n message.id = data.messageId;\n }\n if (data.messageMetadata != null) {\n message.metadata = message.metadata\n ? { ...message.metadata, ...data.messageMetadata }\n : data.messageMetadata;\n }\n break;\n }\n case \"finish\":\n case \"message-metadata\": {\n if (data.messageMetadata != null) {\n message.metadata = message.metadata\n ? { ...message.metadata, ...data.messageMetadata }\n : data.messageMetadata;\n }\n break;\n }\n case \"error\": {\n this._broadcast({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: data.errorText ?? JSON.stringify(data),\n done: false,\n error: true\n });\n continue;\n }\n }\n }\n\n // Broadcast chunk to clients\n this._broadcast({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: JSON.stringify(chunk),\n done: false\n });\n }\n\n this._broadcast({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true\n });\n doneSent = true;\n } catch (error) {\n if (!doneSent) {\n this._broadcast({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: error instanceof Error ? error.message : \"Stream error\",\n done: true,\n error: true\n });\n doneSent = true;\n }\n } finally {\n if (!doneSent) {\n this._broadcast({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true\n });\n }\n }\n\n // Persist the assistant message to the session (sanitized + size-enforced).\n // Skip if a clear happened during this stream (clearGeneration changed).\n // Wrapped in try-catch: the stream done message was already sent above,\n // so a persistence error must not propagate to the outer catch (which\n // would broadcast a second done message).\n if (\n message.parts.length > 0 &&\n this._sessionId &&\n this._clearGeneration === clearGen\n ) {\n try {\n this._persistAssistantMessage(message);\n this._broadcastMessages();\n } catch (e) {\n console.error(\"Failed to persist assistant message:\", e);\n }\n }\n }\n\n // ── Persistence internals ────────────────────────────────────────\n\n /**\n * Persist an assistant message with sanitization, size enforcement,\n * and incremental persistence.\n * @internal\n */\n private _persistAssistantMessage(msg: UIMessage): void {\n if (!this._sessionId) return;\n\n const sanitized = sanitizeMessage(msg);\n const safe = enforceRowSizeLimit(sanitized);\n const json = JSON.stringify(safe);\n\n // Skip SQL write if unchanged (incremental persistence)\n if (this._persistedMessageCache.get(safe.id) !== json) {\n this.sessions.upsert(this._sessionId, safe);\n this._persistedMessageCache.set(safe.id, json);\n }\n\n // Enforce storage bounds\n if (this.maxPersistedMessages != null) {\n this._enforceMaxPersistedMessages();\n }\n\n this.messages = this.sessions.getHistory(this._sessionId);\n }\n\n /**\n * Rebuild the persistence cache from current messages.\n * Called on startup to enable incremental persistence.\n * @internal\n */\n private _rebuildPersistenceCache(): void {\n this._persistedMessageCache.clear();\n for (const msg of this.messages) {\n this._persistedMessageCache.set(msg.id, JSON.stringify(msg));\n }\n }\n\n /**\n * Delete oldest messages on the current branch when count exceeds\n * maxPersistedMessages. Uses path-based count (not total across all\n * branches) and individual deletes to preserve branch structure.\n * @internal\n */\n private _enforceMaxPersistedMessages(): void {\n if (this.maxPersistedMessages == null || !this._sessionId) return;\n\n // Use current branch history, not total message count across all branches\n const history = this.sessions.getHistory(this._sessionId);\n if (history.length <= this.maxPersistedMessages) return;\n\n const excess = history.length - this.maxPersistedMessages;\n const toRemove = history.slice(0, excess);\n\n // Delete individual messages — preserves branch structure\n this.sessions.deleteMessages(toRemove.map((m) => m.id));\n for (const msg of toRemove) {\n this._persistedMessageCache.delete(msg.id);\n }\n }\n\n /**\n * Broadcast a JSON message to all connected clients.\n * @internal\n */\n private _broadcast(message: Record<string, unknown>, exclude?: string[]) {\n this.broadcast(JSON.stringify(message), exclude);\n }\n\n /**\n * Broadcast the current message list to all connected clients.\n * @internal\n */\n private _broadcastMessages(exclude?: string[]) {\n this._broadcast(\n { type: MSG_CHAT_MESSAGES, messages: this.messages },\n exclude\n );\n }\n}\n"],"mappings":";;;;;;;;AAWA,MAAM,cAAc,IAAI,aAAa;;AAGrC,MAAM,gBAAgB;;AAGtB,SAAS,WAAW,GAAmB;AACrC,QAAO,YAAY,OAAO,EAAE,CAAC;;;;;;;;;AAU/B,SAAgB,gBAAgB,SAA+B;CA8B7D,MAAM,iBA5BgB,QAAQ,MAAM,KAAK,SAAS;EAChD,IAAI,gBAAgB;AAEpB,MACE,sBAAsB,iBACtB,cAAc,oBACd,OAAO,cAAc,qBAAqB,YAC1C,YAAY,cAAc,iBAE1B,iBAAgB,oBAAoB,eAAe,mBAAmB;AAGxE,MACE,0BAA0B,iBAC1B,cAAc,wBACd,OAAO,cAAc,yBAAyB,YAC9C,YAAY,cAAc,qBAE1B,iBAAgB,oBACd,eACA,uBACD;AAGH,SAAO;GACP,CAGmC,QAAQ,SAAS;AACpD,MAAI,KAAK,SAAS,aAAa;GAC7B,MAAM,gBAAgB;AACtB,OAAI,CAAC,cAAc,QAAQ,cAAc,KAAK,MAAM,KAAK,IAAI;AAC3D,QACE,sBAAsB,iBACtB,cAAc,oBACd,OAAO,cAAc,qBAAqB,YAC1C,OAAO,KAAK,cAAc,iBAAiB,CAAC,SAAS,EAErD,QAAO;AAET,WAAO;;;AAGX,SAAO;GACP;AAEF,QAAO;EAAE,GAAG;EAAS,OAAO;EAAgB;;;;;AAM9C,SAAS,oBACP,MACA,aACG;CACH,MAAM,WAAY,KAAiC;AAKnD,KAAI,CAAC,UAAU,OAAQ,QAAO;CAE9B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AAO,SAChB,MAAK,uBAAuB,OAAO,IAAI,GAAG;;;;;;CAQ9C,WAAmB,SAAkC,SAAoB;AACvE,OAAK,UAAU,KAAK,UAAU,QAAQ,EAAE,QAAQ;;;;;;CAOlD,mBAA2B,SAAoB;AAC7C,OAAK,WACH;GAAE,MAAM;GAAmB,UAAU,KAAK;GAAU,EACpD,QACD"}
1
+ {"version":3,"file":"think.js","names":["agentContext"],"sources":["../src/sanitize.ts","../src/think.ts"],"sourcesContent":["/**\n * Message sanitization and row-size enforcement utilities.\n *\n * Shared by Think to ensure persistence\n * hygiene: stripping ephemeral provider metadata and compacting\n * oversized messages before writing to SQLite.\n */\n\nimport type { ProviderMetadata, ReasoningUIPart, UIMessage } from \"ai\";\n\n/** Shared encoder for UTF-8 byte length measurement */\nconst textEncoder = new TextEncoder();\n\n/** Maximum serialized message size before compaction (bytes). 1.8MB with headroom below SQLite's 2MB limit. */\nconst ROW_MAX_BYTES = 1_800_000;\n\n/** Measure UTF-8 byte length of a string. */\nfunction byteLength(s: string): number {\n return textEncoder.encode(s).byteLength;\n}\n\n/**\n * Sanitize a message for persistence by removing ephemeral provider-specific\n * data that should not be stored or sent back in subsequent requests.\n *\n * 1. Strips OpenAI ephemeral fields (itemId, reasoningEncryptedContent)\n * 2. Filters truly empty reasoning parts (no text, no remaining providerMetadata)\n */\nexport function sanitizeMessage(message: UIMessage): UIMessage {\n // Strip OpenAI-specific ephemeral data from all parts\n const strippedParts = message.parts.map((part) => {\n let sanitizedPart = part;\n\n if (\n \"providerMetadata\" in sanitizedPart &&\n sanitizedPart.providerMetadata &&\n typeof sanitizedPart.providerMetadata === \"object\" &&\n \"openai\" in sanitizedPart.providerMetadata\n ) {\n sanitizedPart = stripOpenAIMetadata(sanitizedPart, \"providerMetadata\");\n }\n\n if (\n \"callProviderMetadata\" in sanitizedPart &&\n sanitizedPart.callProviderMetadata &&\n typeof sanitizedPart.callProviderMetadata === \"object\" &&\n \"openai\" in sanitizedPart.callProviderMetadata\n ) {\n sanitizedPart = stripOpenAIMetadata(\n sanitizedPart,\n \"callProviderMetadata\"\n );\n }\n\n return sanitizedPart;\n }) as UIMessage[\"parts\"];\n\n // Filter out reasoning parts that are truly empty\n const sanitizedParts = strippedParts.filter((part) => {\n if (part.type === \"reasoning\") {\n const reasoningPart = part as ReasoningUIPart;\n if (!reasoningPart.text || reasoningPart.text.trim() === \"\") {\n if (\n \"providerMetadata\" in reasoningPart &&\n reasoningPart.providerMetadata &&\n typeof reasoningPart.providerMetadata === \"object\" &&\n Object.keys(reasoningPart.providerMetadata).length > 0\n ) {\n return true;\n }\n return false;\n }\n }\n return true;\n });\n\n return { ...message, parts: sanitizedParts };\n}\n\n/**\n * Strip OpenAI-specific ephemeral fields from a metadata object.\n */\nfunction stripOpenAIMetadata<T extends UIMessage[\"parts\"][number]>(\n part: T,\n metadataKey: \"providerMetadata\" | \"callProviderMetadata\"\n): T {\n const metadata = (part as Record<string, unknown>)[metadataKey] as {\n openai?: Record<string, unknown>;\n [key: string]: unknown;\n };\n\n if (!metadata?.openai) return part;\n\n const {\n itemId: _itemId,\n reasoningEncryptedContent: _rec,\n ...restOpenai\n } = metadata.openai;\n\n const hasOtherOpenaiFields = Object.keys(restOpenai).length > 0;\n const { openai: _openai, ...restMetadata } = metadata;\n\n let newMetadata: ProviderMetadata | undefined;\n if (hasOtherOpenaiFields) {\n newMetadata = { ...restMetadata, openai: restOpenai } as ProviderMetadata;\n } else if (Object.keys(restMetadata).length > 0) {\n newMetadata = restMetadata as ProviderMetadata;\n }\n\n const { [metadataKey]: _oldMeta, ...restPart } = part as Record<\n string,\n unknown\n >;\n\n if (newMetadata) {\n return { ...restPart, [metadataKey]: newMetadata } as T;\n }\n return restPart as T;\n}\n\n/**\n * Enforce SQLite row size limits by compacting tool outputs and text parts\n * when a serialized message exceeds the safety threshold (1.8MB).\n *\n * Compaction strategy:\n * 1. Compact tool outputs over 1KB (replace with summary)\n * 2. If still too big, truncate text parts from oldest to newest\n */\nexport function enforceRowSizeLimit(message: UIMessage): UIMessage {\n let json = JSON.stringify(message);\n let size = byteLength(json);\n if (size <= ROW_MAX_BYTES) return message;\n\n if (message.role !== \"assistant\") {\n return truncateTextParts(message);\n }\n\n // Pass 1: compact tool outputs\n const compactedParts = message.parts.map((part) => {\n if (\n \"output\" in part &&\n \"toolCallId\" in part &&\n \"state\" in part &&\n part.state === \"output-available\"\n ) {\n const outputJson = JSON.stringify((part as { output: unknown }).output);\n if (outputJson.length > 1000) {\n return {\n ...part,\n output:\n \"This tool output was too large to persist in storage \" +\n `(${outputJson.length} bytes). ` +\n \"If the user asks about this data, suggest re-running the tool. \" +\n `Preview: ${outputJson.slice(0, 500)}...`\n };\n }\n }\n return part;\n }) as UIMessage[\"parts\"];\n\n let result: UIMessage = { ...message, parts: compactedParts };\n\n json = JSON.stringify(result);\n size = byteLength(json);\n if (size <= ROW_MAX_BYTES) return result;\n\n // Pass 2: truncate text parts\n return truncateTextParts(result);\n}\n\n/**\n * Truncate text parts to fit within the row size limit.\n */\nfunction truncateTextParts(message: UIMessage): UIMessage {\n const parts = [...message.parts];\n\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n if (part.type === \"text\" && \"text\" in part) {\n const text = (part as { text: string }).text;\n if (text.length > 1000) {\n parts[i] = {\n ...part,\n text:\n `[Text truncated for storage (${text.length} chars). ` +\n `First 500 chars: ${text.slice(0, 500)}...]`\n } as UIMessage[\"parts\"][number];\n\n const candidate = { ...message, parts };\n if (byteLength(JSON.stringify(candidate)) <= ROW_MAX_BYTES) {\n break;\n }\n }\n }\n }\n\n return { ...message, parts };\n}\n","/**\n * Think — a unified Agent base class for chat sessions.\n *\n * Works as both a **top-level agent** (speaking the `cf_agent_chat_*`\n * WebSocket protocol to browser clients) and a **sub-agent** (called\n * via `chat()` over RPC from a parent agent).\n *\n * Each instance gets its own SQLite storage and runs the full chat\n * lifecycle:\n * store user message → assemble context → call LLM → stream events → persist response\n *\n * Uses SessionManager for message persistence, giving you branching and\n * compaction support for free.\n *\n * Override points:\n * - getModel() — return the LanguageModel to use\n * - getSystemPrompt() — return the system prompt\n * - getTools() — return the ToolSet for the agentic loop\n * - getMaxSteps() — max tool-call rounds per turn (default: 10)\n * - assembleContext() — customize context assembly from this.messages\n * - onChatMessage() — full control over inference (override the agentic loop)\n * - onChatError() — customize error handling\n *\n * Production features:\n * - WebSocket chat protocol (compatible with useAgentChat / useChat)\n * - Multi-session management (create, switch, list, delete, rename)\n * - Sub-agent RPC streaming via StreamCallback\n * - Abort/cancel support via AbortSignal\n * - Error handling with partial message persistence\n * - Message sanitization (strips OpenAI ephemeral metadata)\n * - Row size enforcement (compacts large tool outputs)\n * - Configurable storage bounds (maxPersistedMessages)\n * - Incremental persistence (skips unchanged messages)\n * - Richer input (accepts UIMessage or string)\n *\n * @experimental Requires the `\"experimental\"` compatibility flag.\n *\n * @example\n * ```typescript\n * import { Think } from \"@cloudflare/think\";\n * import { createWorkersAI } from \"workers-ai-provider\";\n * import { createWorkspaceTools } from \"@cloudflare/think/tools/workspace\";\n * import { Workspace } from \"@cloudflare/shell\";\n *\n * export class ChatSession extends Think<Env> {\n * workspace = new Workspace({ sql: this.ctx.storage.sql, name: () => this.name });\n *\n * getModel() {\n * return createWorkersAI({ binding: this.env.AI })(\"@cf/moonshotai/kimi-k2.5\");\n * }\n *\n * getTools() {\n * return createWorkspaceTools(this.workspace);\n * }\n * }\n * ```\n */\n\nimport type { LanguageModel, ModelMessage, ToolSet, UIMessage } from \"ai\";\nimport {\n convertToModelMessages,\n pruneMessages,\n stepCountIs,\n streamText\n} from \"ai\";\nimport {\n Agent,\n __DO_NOT_USE_WILL_BREAK__agentContext as agentContext\n} from \"agents\";\nimport type { Connection, WSMessage } from \"agents\";\nimport type { Workspace } from \"@cloudflare/shell\";\nimport { withFibers } from \"agents/experimental/forever\";\nimport type { FiberMethods } from \"agents/experimental/forever\";\nimport { SessionManager } from \"./session/index\";\nimport type { Session } from \"./session/index\";\nimport { applyChunkToParts } from \"./message-builder\";\nimport type { StreamChunkData } from \"./message-builder\";\nimport { sanitizeMessage, enforceRowSizeLimit } from \"./sanitize\";\n\nexport type { Session } from \"./session/index\";\nexport type {\n FiberState,\n FiberRecoveryContext,\n FiberContext,\n FiberCompleteContext,\n FiberMethods\n} from \"agents/experimental/forever\";\n\n// ── Fiber base class ──────────────────────────────────────────────────\n// Think extends withFibers(Agent) so fiber methods (spawnFiber, etc.)\n// are always available on the prototype. The `fibers` flag controls\n// whether interrupted fibers are recovered on start.\n//\n// The type cast preserves Agent's generic constructor while adding\n// FiberMethods to the instance type, avoiding unsafe interface merging.\ntype ThinkBaseConstructor = {\n new <\n Env extends Cloudflare.Env = Cloudflare.Env,\n State = unknown,\n Props extends Record<string, unknown> = Record<string, unknown>\n >(\n ctx: DurableObjectState,\n env: Env\n ): Agent<Env, State, Props> & FiberMethods;\n};\n\nconst ThinkBase = withFibers(Agent) as unknown as ThinkBaseConstructor;\n\n// ── Wire protocol constants ────────────────────────────────────────\n// These string values are wire-compatible with @cloudflare/ai-chat's\n// MessageType enum. Defined locally to avoid a circular dependency.\nconst MSG_CHAT_MESSAGES = \"cf_agent_chat_messages\";\nconst MSG_CHAT_REQUEST = \"cf_agent_use_chat_request\";\nconst MSG_CHAT_RESPONSE = \"cf_agent_use_chat_response\";\nconst MSG_CHAT_CLEAR = \"cf_agent_chat_clear\";\nconst MSG_CHAT_CANCEL = \"cf_agent_chat_request_cancel\";\n\n/**\n * Callback interface for streaming chat events from a Think.\n *\n * Designed to work across the sub-agent RPC boundary — implement as\n * an RpcTarget in the parent agent and pass to `chat()`.\n *\n * Methods may return a Promise for async RPC callbacks.\n */\nexport interface StreamCallback {\n /** Called for each UIMessageChunk event during streaming. */\n onEvent(json: string): void | Promise<void>;\n /** Called when the stream completes successfully (not called on abort). */\n onDone(): void | Promise<void>;\n /** Called when an error occurs during streaming. */\n onError?(error: string): void | Promise<void>;\n}\n\n/**\n * Minimal interface for the result of `onChatMessage()`.\n * Must provide a `toUIMessageStream()` method that returns an\n * async-iterable stream of UI message chunks.\n *\n * The AI SDK's `streamText()` result satisfies this interface.\n */\nexport interface StreamableResult {\n toUIMessageStream(): AsyncIterable<unknown>;\n}\n\n/**\n * Options for a chat turn (sub-agent RPC entry point).\n */\nexport interface ChatOptions {\n /** AbortSignal — fires when the caller wants to cancel the turn. */\n signal?: AbortSignal;\n /** Extra tools to merge with getTools() for this turn only. */\n tools?: ToolSet;\n}\n\n/**\n * Options passed to the onChatMessage handler.\n */\nexport interface ChatMessageOptions {\n /** AbortSignal for cancelling the request */\n signal?: AbortSignal;\n /** Extra tools to merge with getTools() for this turn only. */\n tools?: ToolSet;\n}\n\n/**\n * A unified Agent base class for chat sessions.\n *\n * Works as both a top-level agent (WebSocket chat protocol) and a\n * sub-agent (RPC streaming via `chat()`).\n *\n * @experimental Requires the `\"experimental\"` compatibility flag.\n */\nexport class Think<\n Env extends Cloudflare.Env = Cloudflare.Env,\n Config = Record<string, unknown>\n> extends (ThinkBase as ThinkBaseConstructor)<Env> {\n /** Session manager — persistence layer with branching and compaction. */\n sessions!: SessionManager;\n\n /** In-memory messages for the current conversation. Authoritative after load. */\n messages: UIMessage[] = [];\n\n /**\n * Enable durable fiber recovery on start. Set to `true` to\n * automatically recover interrupted fibers when the DO restarts.\n *\n * Fiber methods (`spawnFiber()`, `stashFiber()`, etc.) are always\n * available — this flag only controls automatic recovery.\n *\n * @experimental\n */\n fibers = false;\n\n /**\n * Maximum number of messages to keep in storage per session.\n * When exceeded, oldest messages are deleted after each persist.\n * Set to `undefined` (default) for no limit.\n *\n * This controls storage only — it does not affect what's sent to the LLM.\n * Use `pruneMessages()` in `assembleContext()` to control LLM context.\n */\n maxPersistedMessages: number | undefined = undefined;\n\n /**\n * Cache of last-persisted JSON for each message ID.\n * Used for incremental persistence: skip SQL writes for unchanged messages.\n * @internal\n */\n private _persistedMessageCache: Map<string, string> = new Map();\n\n private _sessionId: string | null = null;\n private _abortControllers = new Map<string, AbortController>();\n private _clearGeneration = 0;\n\n // ── Dynamic config ──────────────────────────────────────────────\n\n #configTableReady = false;\n #configCache: Config | null = null;\n\n private _ensureConfigTable(): void {\n if (this.#configTableReady) return;\n this.sql`\n CREATE TABLE IF NOT EXISTS _think_config (\n key TEXT PRIMARY KEY, value TEXT NOT NULL\n )\n `;\n this.#configTableReady = true;\n }\n\n /**\n * Persist a typed configuration object.\n * Stored in SQLite so it survives restarts and hibernation.\n */\n configure(config: Config): void {\n this._ensureConfigTable();\n const json = JSON.stringify(config);\n this.sql`\n INSERT OR REPLACE INTO _think_config (key, value) VALUES ('config', ${json})\n `;\n this.#configCache = config;\n }\n\n /**\n * Read the persisted configuration, or null if never configured.\n */\n getConfig(): Config | null {\n if (this.#configCache) return this.#configCache;\n this._ensureConfigTable();\n const rows = this.sql<{ value: string }>`\n SELECT value FROM _think_config WHERE key = 'config'\n `;\n if (rows.length > 0) {\n this.#configCache = JSON.parse(rows[0].value) as Config;\n return this.#configCache;\n }\n return null;\n }\n\n onStart() {\n this.sessions = new SessionManager(this, {\n exec: (query, ...values) => {\n this.ctx.storage.sql.exec(query, ...values);\n }\n });\n const existing = this.sessions.list();\n if (existing.length > 0) {\n this._sessionId = existing[0].id;\n this.messages = this.sessions.getHistory(this._sessionId);\n this._rebuildPersistenceCache();\n }\n this._setupProtocolHandlers();\n\n if (this.fibers) {\n void this.checkFibers();\n }\n }\n\n // ── Override points ──────────────────────────────────────────────\n\n /**\n * Return the language model to use for inference.\n * Must be overridden by subclasses that rely on the default\n * `onChatMessage` implementation (the agentic loop).\n */\n getModel(): LanguageModel {\n throw new Error(\n \"Override getModel() to return a LanguageModel, or override onChatMessage() for full control.\"\n );\n }\n\n /**\n * Return the system prompt for the assistant.\n * Override to customize instructions.\n */\n getSystemPrompt(): string {\n return \"You are a helpful assistant.\";\n }\n\n /**\n * Return the tools available to the assistant.\n * Override to provide workspace tools, custom tools, etc.\n */\n getTools(): ToolSet {\n return {};\n }\n\n /**\n * Return the maximum number of tool-call steps per turn.\n */\n getMaxSteps(): number {\n return 10;\n }\n\n /**\n * Return the workspace instance for this session, or null if none.\n *\n * Override in subclasses that create a Workspace. Used by\n * HostBridgeLoopback to provide workspace access to extension Workers.\n */\n getWorkspace(): Workspace | null {\n return null;\n }\n\n // ── Workspace proxy methods (called by HostBridgeLoopback via RPC) ──\n\n async _hostReadFile(path: string): Promise<string | null> {\n const ws = this.getWorkspace();\n if (!ws) throw new Error(\"No workspace available on this agent\");\n return ws.readFile(path);\n }\n\n async _hostWriteFile(path: string, content: string): Promise<void> {\n const ws = this.getWorkspace();\n if (!ws) throw new Error(\"No workspace available on this agent\");\n await ws.writeFile(path, content);\n }\n\n async _hostDeleteFile(path: string): Promise<boolean> {\n const ws = this.getWorkspace();\n if (!ws) throw new Error(\"No workspace available on this agent\");\n return ws.deleteFile(path);\n }\n\n async _hostListFiles(\n dir: string\n ): Promise<\n Array<{ name: string; type: string; size: number; path: string }>\n > {\n const ws = this.getWorkspace();\n if (!ws) throw new Error(\"No workspace available on this agent\");\n return ws.readDir(dir);\n }\n\n /**\n * Assemble the model messages from the current conversation history.\n * Override to customize context assembly (e.g. inject memory,\n * project context, or apply compaction).\n */\n async assembleContext(): Promise<ModelMessage[]> {\n return pruneMessages({\n messages: await convertToModelMessages(this.messages),\n toolCalls: \"before-last-2-messages\"\n });\n }\n\n /**\n * Handle a chat turn and return the streaming result.\n *\n * The default implementation runs the agentic loop:\n * 1. Assemble context from `this.messages`\n * 2. Call `streamText` with the model, system prompt, tools, and step limit\n *\n * Override for full control over inference (e.g. different models per turn,\n * RAG pipelines, routing to specialized sub-agents, etc.).\n *\n * When this is called, `this.messages` already contains the user's\n * latest message persisted to the current session.\n *\n * @returns A result with `toUIMessageStream()` — AI SDK's `streamText()`\n * return value satisfies this interface.\n */\n async onChatMessage(options?: ChatMessageOptions): Promise<StreamableResult> {\n const baseTools = this.getTools();\n const tools = options?.tools\n ? { ...baseTools, ...options.tools }\n : baseTools;\n return streamText({\n model: this.getModel(),\n system: this.getSystemPrompt(),\n messages: await this.assembleContext(),\n tools,\n stopWhen: stepCountIs(this.getMaxSteps()),\n abortSignal: options?.signal\n });\n }\n\n /**\n * Handle an error that occurred during a chat turn.\n * Override to customize error handling (e.g. logging, metrics).\n *\n * @param error The error that occurred\n * @returns The error (or a wrapped version) to propagate\n */\n onChatError(error: unknown): unknown {\n return error;\n }\n\n // ── Sub-agent RPC entry point ───────────────────────────────────\n\n /**\n * Run a chat turn: persist the user message, run the agentic loop,\n * stream UIMessageChunk events via callback, and persist the\n * assistant's response.\n *\n * On error or abort, the partial assistant message is still persisted\n * so the user doesn't lose context.\n *\n * @param userMessage The user's message (string or UIMessage for multi-modal)\n * @param callback Streaming callback (typically an RpcTarget from the parent)\n * @param options Optional chat options (e.g. AbortSignal)\n */\n async chat(\n userMessage: string | UIMessage,\n callback: StreamCallback,\n options?: ChatOptions\n ): Promise<void> {\n // Ensure a session exists\n if (!this._sessionId) {\n const session = this.sessions.create(\"default\");\n this._sessionId = session.id;\n }\n\n // Persist user message\n const userMsg: UIMessage =\n typeof userMessage === \"string\"\n ? {\n id: crypto.randomUUID(),\n role: \"user\",\n parts: [{ type: \"text\", text: userMessage }]\n }\n : userMessage;\n\n this.sessions.append(this._sessionId, userMsg);\n this.messages = this.sessions.getHistory(this._sessionId);\n\n // Build assistant message from stream chunks\n const assistantMsg: UIMessage = {\n id: crypto.randomUUID(),\n role: \"assistant\",\n parts: []\n };\n\n try {\n // Run the agentic loop (or custom override)\n const result = await this.onChatMessage({\n signal: options?.signal,\n tools: options?.tools\n });\n\n // Stream UIMessageChunk events via callback\n let aborted = false;\n for await (const chunk of result.toUIMessageStream()) {\n if (options?.signal?.aborted) {\n aborted = true;\n break;\n }\n applyChunkToParts(\n assistantMsg.parts,\n chunk as unknown as StreamChunkData\n );\n await callback.onEvent(JSON.stringify(chunk));\n }\n\n // Persist assistant message (sanitized + size-enforced)\n this._persistAssistantMessage(assistantMsg);\n\n // Only signal completion if not aborted\n if (!aborted) {\n await callback.onDone();\n }\n } catch (error) {\n // Persist partial assistant message so context isn't lost\n if (assistantMsg.parts.length > 0) {\n this._persistAssistantMessage(assistantMsg);\n }\n\n const wrapped = this.onChatError(error);\n const errorMessage =\n wrapped instanceof Error ? wrapped.message : String(wrapped);\n\n if (callback.onError) {\n await callback.onError(errorMessage);\n } else {\n // Re-throw if no error callback — caller must handle it\n throw wrapped;\n }\n }\n }\n\n // ── Session management ─────────────────────────────────────────\n\n getSessions(): Session[] {\n return this.sessions.list();\n }\n\n createSession(name: string): Session {\n const session = this.sessions.create(name);\n this._sessionId = session.id;\n this.messages = [];\n this._broadcastMessages();\n return session;\n }\n\n switchSession(sessionId: string): UIMessage[] {\n const session = this.sessions.get(sessionId);\n if (!session) {\n throw new Error(`Session not found: ${sessionId}`);\n }\n this._sessionId = sessionId;\n this.messages = this.sessions.getHistory(sessionId);\n this._broadcastMessages();\n return this.messages;\n }\n\n deleteSession(sessionId: string): void {\n const session = this.sessions.get(sessionId);\n if (!session) {\n throw new Error(`Session not found: ${sessionId}`);\n }\n this.sessions.delete(sessionId);\n if (this._sessionId === sessionId) {\n this._sessionId = null;\n this.messages = [];\n this._broadcastMessages();\n }\n }\n\n renameSession(sessionId: string, name: string): void {\n const session = this.sessions.get(sessionId);\n if (!session) {\n throw new Error(`Session not found: ${sessionId}`);\n }\n this.sessions.rename(sessionId, name);\n }\n\n getCurrentSessionId(): string | null {\n return this._sessionId;\n }\n\n // ── Message access ───────────────────────────────────────────────\n\n /**\n * Get the current session info, or null if no session exists yet.\n */\n getSession(): Session | null {\n if (!this._sessionId) return null;\n return this.sessions.get(this._sessionId);\n }\n\n /**\n * Get the conversation history as UIMessage[].\n */\n getHistory(): UIMessage[] {\n if (!this._sessionId) return [];\n return this.sessions.getHistory(this._sessionId);\n }\n\n /**\n * Get the total message count for this session.\n */\n getMessageCount(): number {\n if (!this._sessionId) return 0;\n return this.sessions.getMessageCount(this._sessionId);\n }\n\n /**\n * Clear all messages from this session (preserves the session itself).\n */\n clearMessages(): void {\n if (!this._sessionId) return;\n this.sessions.clearMessages(this._sessionId);\n this.messages = [];\n this._persistedMessageCache.clear();\n }\n\n // ── WebSocket protocol ──────────────────────────────────────────\n\n /**\n * Wrap onMessage and onRequest to intercept the chat protocol.\n * Unrecognized messages are forwarded to the user's handlers.\n * @internal\n */\n private _setupProtocolHandlers() {\n const _onMessage = this.onMessage.bind(this);\n this.onMessage = async (connection: Connection, message: WSMessage) => {\n if (typeof message === \"string\") {\n try {\n const data = JSON.parse(message) as Record<string, unknown>;\n if (await this._handleProtocol(connection, data)) return;\n } catch {\n // Not JSON — fall through to user handler\n }\n }\n return _onMessage(connection, message);\n };\n\n const _onRequest = this.onRequest.bind(this);\n this.onRequest = async (request: Request) => {\n const url = new URL(request.url);\n if (\n url.pathname === \"/get-messages\" ||\n url.pathname.endsWith(\"/get-messages\")\n ) {\n const sessionId = url.searchParams.get(\"sessionId\");\n if (sessionId) {\n const session = this.sessions.get(sessionId);\n if (!session) {\n return Response.json(\n { error: \"Session not found\" },\n { status: 404 }\n );\n }\n return Response.json(this.sessions.getHistory(sessionId));\n }\n return Response.json(this.messages);\n }\n return _onRequest(request);\n };\n }\n\n /**\n * Route an incoming WebSocket message to the appropriate handler.\n * Returns true if the message was handled by the protocol.\n * @internal\n */\n private async _handleProtocol(\n connection: Connection,\n data: Record<string, unknown>\n ): Promise<boolean> {\n const type = data.type as string;\n\n if (type === MSG_CHAT_REQUEST) {\n const init = data.init as { method?: string; body?: string } | undefined;\n if (init?.method === \"POST\") {\n await this._handleChatRequest(connection, data);\n return true;\n }\n }\n\n if (type === MSG_CHAT_CLEAR) {\n this._handleClear();\n return true;\n }\n\n if (type === MSG_CHAT_CANCEL) {\n this._handleCancel(data.id as string);\n return true;\n }\n\n return false;\n }\n\n /**\n * Handle CF_AGENT_USE_CHAT_REQUEST:\n * 1. Parse incoming messages\n * 2. Ensure a session exists\n * 3. Persist user messages to session\n * 4. Call onChatMessage\n * 5. Stream response back to clients\n * 6. Persist assistant message to session\n * @internal\n */\n private async _handleChatRequest(\n connection: Connection,\n data: Record<string, unknown>\n ) {\n const init = data.init as { body?: string };\n if (!init?.body) return;\n\n let parsed: { messages?: UIMessage[] };\n try {\n parsed = JSON.parse(init.body) as { messages?: UIMessage[] };\n } catch {\n return;\n }\n\n const incomingMessages = parsed.messages;\n if (!Array.isArray(incomingMessages)) return;\n\n // Ensure a session exists\n if (!this._sessionId) {\n const session = this.sessions.create(\"New Chat\");\n this._sessionId = session.id;\n }\n\n // Persist incoming messages to session (idempotent via INSERT OR IGNORE)\n this.sessions.appendAll(this._sessionId, incomingMessages);\n\n // Reload from session (authoritative)\n this.messages = this.sessions.getHistory(this._sessionId);\n\n // Broadcast updated messages to other connections\n this._broadcastMessages([connection.id]);\n\n // Set up abort controller\n const requestId = data.id as string;\n const abortController = new AbortController();\n this._abortControllers.set(requestId, abortController);\n\n try {\n await this.keepAliveWhile(async () => {\n const result = await agentContext.run(\n { agent: this, connection, request: undefined, email: undefined },\n () =>\n this.onChatMessage({\n signal: abortController.signal\n })\n );\n\n if (result) {\n await this._streamResult(requestId, result, abortController.signal);\n } else {\n this._broadcast({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"No response was generated.\",\n done: true\n });\n }\n });\n } catch (error) {\n this._broadcast({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: error instanceof Error ? error.message : \"Error\",\n done: true,\n error: true\n });\n } finally {\n this._abortControllers.delete(requestId);\n }\n }\n\n /**\n * Handle CF_AGENT_CHAT_CLEAR: abort streams, clear current session messages.\n * @internal\n */\n private _handleClear() {\n for (const controller of this._abortControllers.values()) {\n controller.abort();\n }\n this._abortControllers.clear();\n\n if (this._sessionId) {\n this.sessions.clearMessages(this._sessionId);\n }\n\n this.messages = [];\n this._persistedMessageCache.clear();\n this._clearGeneration++;\n this._broadcast({ type: MSG_CHAT_CLEAR });\n }\n\n /**\n * Handle CF_AGENT_CHAT_REQUEST_CANCEL: abort a specific request.\n * @internal\n */\n private _handleCancel(requestId: string) {\n const controller = this._abortControllers.get(requestId);\n if (controller) {\n controller.abort();\n }\n }\n\n /**\n * Iterate a StreamableResult, broadcast chunks to clients,\n * build a UIMessage, and persist it to the session.\n * @internal\n */\n private async _streamResult(\n requestId: string,\n result: StreamableResult,\n abortSignal?: AbortSignal\n ) {\n const clearGen = this._clearGeneration;\n\n const message: UIMessage = {\n id: crypto.randomUUID(),\n role: \"assistant\",\n parts: []\n };\n\n let doneSent = false;\n\n try {\n for await (const chunk of result.toUIMessageStream()) {\n if (abortSignal?.aborted) break;\n\n const data = chunk as StreamChunkData;\n\n // Build UIMessage from stream events\n const handled = applyChunkToParts(message.parts, data);\n\n if (!handled) {\n // Handle metadata events that applyChunkToParts doesn't cover\n switch (data.type) {\n case \"start\": {\n if (data.messageId != null) {\n message.id = data.messageId;\n }\n if (data.messageMetadata != null) {\n message.metadata = message.metadata\n ? { ...message.metadata, ...data.messageMetadata }\n : data.messageMetadata;\n }\n break;\n }\n case \"finish\":\n case \"message-metadata\": {\n if (data.messageMetadata != null) {\n message.metadata = message.metadata\n ? { ...message.metadata, ...data.messageMetadata }\n : data.messageMetadata;\n }\n break;\n }\n case \"error\": {\n this._broadcast({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: data.errorText ?? JSON.stringify(data),\n done: false,\n error: true\n });\n continue;\n }\n }\n }\n\n // Broadcast chunk to clients\n this._broadcast({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: JSON.stringify(chunk),\n done: false\n });\n }\n\n this._broadcast({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true\n });\n doneSent = true;\n } catch (error) {\n if (!doneSent) {\n this._broadcast({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: error instanceof Error ? error.message : \"Stream error\",\n done: true,\n error: true\n });\n doneSent = true;\n }\n } finally {\n if (!doneSent) {\n this._broadcast({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true\n });\n }\n }\n\n // Persist the assistant message to the session (sanitized + size-enforced).\n // Skip if a clear happened during this stream (clearGeneration changed).\n // Wrapped in try-catch: the stream done message was already sent above,\n // so a persistence error must not propagate to the outer catch (which\n // would broadcast a second done message).\n if (\n message.parts.length > 0 &&\n this._sessionId &&\n this._clearGeneration === clearGen\n ) {\n try {\n this._persistAssistantMessage(message);\n this._broadcastMessages();\n } catch (e) {\n console.error(\"Failed to persist assistant message:\", e);\n }\n }\n }\n\n // ── Persistence internals ────────────────────────────────────────\n\n /**\n * Persist an assistant message with sanitization, size enforcement,\n * and incremental persistence.\n * @internal\n */\n private _persistAssistantMessage(msg: UIMessage): void {\n if (!this._sessionId) return;\n\n const sanitized = sanitizeMessage(msg);\n const safe = enforceRowSizeLimit(sanitized);\n const json = JSON.stringify(safe);\n\n // Skip SQL write if unchanged (incremental persistence)\n if (this._persistedMessageCache.get(safe.id) !== json) {\n this.sessions.upsert(this._sessionId, safe);\n this._persistedMessageCache.set(safe.id, json);\n }\n\n // Enforce storage bounds\n if (this.maxPersistedMessages != null) {\n this._enforceMaxPersistedMessages();\n }\n\n this.messages = this.sessions.getHistory(this._sessionId);\n }\n\n /**\n * Rebuild the persistence cache from current messages.\n * Called on startup to enable incremental persistence.\n * @internal\n */\n private _rebuildPersistenceCache(): void {\n this._persistedMessageCache.clear();\n for (const msg of this.messages) {\n this._persistedMessageCache.set(msg.id, JSON.stringify(msg));\n }\n }\n\n /**\n * Delete oldest messages on the current branch when count exceeds\n * maxPersistedMessages. Uses path-based count (not total across all\n * branches) and individual deletes to preserve branch structure.\n * @internal\n */\n private _enforceMaxPersistedMessages(): void {\n if (this.maxPersistedMessages == null || !this._sessionId) return;\n\n // Use current branch history, not total message count across all branches\n const history = this.sessions.getHistory(this._sessionId);\n if (history.length <= this.maxPersistedMessages) return;\n\n const excess = history.length - this.maxPersistedMessages;\n const toRemove = history.slice(0, excess);\n\n // Delete individual messages — preserves branch structure\n this.sessions.deleteMessages(toRemove.map((m) => m.id));\n for (const msg of toRemove) {\n this._persistedMessageCache.delete(msg.id);\n }\n }\n\n /**\n * Broadcast a JSON message to all connected clients.\n * @internal\n */\n private _broadcast(message: Record<string, unknown>, exclude?: string[]) {\n this.broadcast(JSON.stringify(message), exclude);\n }\n\n /**\n * Broadcast the current message list to all connected clients.\n * @internal\n */\n private _broadcastMessages(exclude?: string[]) {\n this._broadcast(\n { type: MSG_CHAT_MESSAGES, messages: this.messages },\n exclude\n );\n }\n}\n"],"mappings":";;;;;;;;AAWA,MAAM,cAAc,IAAI,aAAa;;AAGrC,MAAM,gBAAgB;;AAGtB,SAAS,WAAW,GAAmB;AACrC,QAAO,YAAY,OAAO,EAAE,CAAC;;;;;;;;;AAU/B,SAAgB,gBAAgB,SAA+B;CA8B7D,MAAM,iBA5BgB,QAAQ,MAAM,KAAK,SAAS;EAChD,IAAI,gBAAgB;AAEpB,MACE,sBAAsB,iBACtB,cAAc,oBACd,OAAO,cAAc,qBAAqB,YAC1C,YAAY,cAAc,iBAE1B,iBAAgB,oBAAoB,eAAe,mBAAmB;AAGxE,MACE,0BAA0B,iBAC1B,cAAc,wBACd,OAAO,cAAc,yBAAyB,YAC9C,YAAY,cAAc,qBAE1B,iBAAgB,oBACd,eACA,uBACD;AAGH,SAAO;GACP,CAGmC,QAAQ,SAAS;AACpD,MAAI,KAAK,SAAS,aAAa;GAC7B,MAAM,gBAAgB;AACtB,OAAI,CAAC,cAAc,QAAQ,cAAc,KAAK,MAAM,KAAK,IAAI;AAC3D,QACE,sBAAsB,iBACtB,cAAc,oBACd,OAAO,cAAc,qBAAqB,YAC1C,OAAO,KAAK,cAAc,iBAAiB,CAAC,SAAS,EAErD,QAAO;AAET,WAAO;;;AAGX,SAAO;GACP;AAEF,QAAO;EAAE,GAAG;EAAS,OAAO;EAAgB;;;;;AAM9C,SAAS,oBACP,MACA,aACG;CACH,MAAM,WAAY,KAAiC;AAKnD,KAAI,CAAC,UAAU,OAAQ,QAAO;CAE9B,MAAM,EACJ,QAAQ,SACR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BAAuB,OAAO,IAAI,GAAG;;;;;;CAQ9C,WAAmB,SAAkC,SAAoB;AACvE,OAAK,UAAU,KAAK,UAAU,QAAQ,EAAE,QAAQ;;;;;;CAOlD,mBAA2B,SAAoB;AAC7C,OAAK,WACH;GAAE,MAAM;GAAmB,UAAU,KAAK;GAAU,EACpD,QACD"}
@@ -1,17 +1,47 @@
1
- import * as ai from "ai";
1
+ import * as _$ai from "ai";
2
2
  import { ToolSet } from "ai";
3
- import { Executor } from "@cloudflare/codemode";
3
+ import * as _$_cloudflare_codemode_ai0 from "@cloudflare/codemode/ai";
4
+ import { Executor, ToolProvider } from "@cloudflare/codemode";
5
+ import { StateBackend } from "@cloudflare/shell";
4
6
 
5
7
  //#region src/tools/execute.d.ts
6
8
  interface CreateExecuteToolOptions {
7
9
  /**
8
- * The tools available inside the sandboxed code.
9
- * These are exposed as `codemode.toolName(args)` in the sandbox.
10
+ * The tools available inside the sandboxed code as `codemode.*`.
10
11
  *
11
- * Typically this is the workspace tools from `createWorkspaceTools()`,
12
+ * Typically the workspace tools from `createWorkspaceTools()`,
12
13
  * but can include any AI SDK tools with `execute` functions.
13
14
  */
14
15
  tools: ToolSet;
16
+ /**
17
+ * Optional StateBackend to expose as `state.*` inside the sandbox.
18
+ *
19
+ * When provided, the sandbox has both `codemode.*` tool calls and
20
+ * the full `state.*` filesystem API (readFile, writeFile, glob,
21
+ * searchFiles, replaceInFiles, planEdits, etc.).
22
+ *
23
+ * This is the preferred way to give the LLM rich filesystem access:
24
+ * use individual workspace tools for simple one-shot operations,
25
+ * and `state.*` for coordinated multi-file work.
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * import { createWorkspaceStateBackend } from "@cloudflare/shell";
30
+ *
31
+ * createExecuteTool({
32
+ * tools: myDomainTools,
33
+ * state: createWorkspaceStateBackend(this.workspace),
34
+ * loader: this.env.LOADER,
35
+ * });
36
+ * // sandbox: codemode.myTool() AND state.readFile() AND state.planEdits()
37
+ * ```
38
+ */
39
+ state?: StateBackend;
40
+ /**
41
+ * Additional tool providers for the sandbox beyond the default tools and state.
42
+ * Each provider adds a named namespace alongside `codemode.*` and `state.*`.
43
+ */
44
+ providers?: ToolProvider[];
15
45
  /**
16
46
  * The executor that runs the generated code.
17
47
  *
@@ -57,48 +87,53 @@ interface CreateExecuteToolOptions {
57
87
  * Code runs in an isolated Worker via `DynamicWorkerExecutor` — external
58
88
  * network access is blocked by default.
59
89
  *
90
+ * Pass `state` to also expose the full `state.*` filesystem API alongside
91
+ * `codemode.*`:
92
+ *
60
93
  * @example
61
94
  * ```ts
62
95
  * import { createWorkspaceTools, createExecuteTool } from "@cloudflare/think";
96
+ * import { createWorkspaceStateBackend } from "@cloudflare/shell";
63
97
  *
64
98
  * getTools() {
65
99
  * const workspaceTools = createWorkspaceTools(this.workspace);
100
+ * const backend = createWorkspaceStateBackend(this.workspace);
66
101
  * return {
67
102
  * ...workspaceTools,
68
103
  * execute: createExecuteTool({
69
- * tools: workspaceTools,
104
+ * tools: myDomainTools, // codemode.* — non-filesystem tools
105
+ * state: backend, // state.* — full filesystem API
70
106
  * loader: this.env.LOADER,
71
107
  * }),
72
108
  * };
73
109
  * }
74
110
  * ```
75
111
  *
76
- * @example Using a custom executor
112
+ * @example Tools only (no filesystem in sandbox)
113
+ * ```ts
114
+ * createExecuteTool({
115
+ * tools: myTools,
116
+ * loader: this.env.LOADER,
117
+ * });
118
+ * ```
119
+ *
120
+ * @example Custom executor
77
121
  * ```ts
78
122
  * import { DynamicWorkerExecutor } from "@cloudflare/codemode";
79
123
  *
80
124
  * const executor = new DynamicWorkerExecutor({
81
125
  * loader: this.env.LOADER,
82
126
  * timeout: 60000,
83
- * globalOutbound: this.env.OUTBOUND,
84
127
  * });
85
128
  *
86
- * getTools() {
87
- * return {
88
- * execute: createExecuteTool({ tools: myTools, executor }),
89
- * };
90
- * }
129
+ * createExecuteTool({ tools: myTools, executor });
91
130
  * ```
92
131
  */
93
- declare function createExecuteTool(options: CreateExecuteToolOptions): ai.Tool<
94
- {
95
- code: string;
96
- },
97
- {
98
- code: string;
99
- result: unknown;
100
- logs?: string[];
101
- }
132
+ declare function createExecuteTool(
133
+ options: CreateExecuteToolOptions
134
+ ): _$ai.Tool<
135
+ _$_cloudflare_codemode_ai0.CodeInput,
136
+ _$_cloudflare_codemode_ai0.CodeOutput
102
137
  >;
103
138
  //#endregion
104
139
  export { CreateExecuteToolOptions, createExecuteTool };
@@ -1,5 +1,6 @@
1
1
  import { createCodeTool } from "@cloudflare/codemode/ai";
2
2
  import { DynamicWorkerExecutor } from "@cloudflare/codemode";
3
+ import { stateToolsFromBackend } from "@cloudflare/shell/workers";
3
4
  //#region src/tools/execute.ts
4
5
  /**
5
6
  * Create a code execution tool that lets the LLM write and run JavaScript
@@ -9,41 +10,50 @@ import { DynamicWorkerExecutor } from "@cloudflare/codemode";
9
10
  * Code runs in an isolated Worker via `DynamicWorkerExecutor` — external
10
11
  * network access is blocked by default.
11
12
  *
13
+ * Pass `state` to also expose the full `state.*` filesystem API alongside
14
+ * `codemode.*`:
15
+ *
12
16
  * @example
13
17
  * ```ts
14
18
  * import { createWorkspaceTools, createExecuteTool } from "@cloudflare/think";
19
+ * import { createWorkspaceStateBackend } from "@cloudflare/shell";
15
20
  *
16
21
  * getTools() {
17
22
  * const workspaceTools = createWorkspaceTools(this.workspace);
23
+ * const backend = createWorkspaceStateBackend(this.workspace);
18
24
  * return {
19
25
  * ...workspaceTools,
20
26
  * execute: createExecuteTool({
21
- * tools: workspaceTools,
27
+ * tools: myDomainTools, // codemode.* — non-filesystem tools
28
+ * state: backend, // state.* — full filesystem API
22
29
  * loader: this.env.LOADER,
23
30
  * }),
24
31
  * };
25
32
  * }
26
33
  * ```
27
34
  *
28
- * @example Using a custom executor
35
+ * @example Tools only (no filesystem in sandbox)
36
+ * ```ts
37
+ * createExecuteTool({
38
+ * tools: myTools,
39
+ * loader: this.env.LOADER,
40
+ * });
41
+ * ```
42
+ *
43
+ * @example Custom executor
29
44
  * ```ts
30
45
  * import { DynamicWorkerExecutor } from "@cloudflare/codemode";
31
46
  *
32
47
  * const executor = new DynamicWorkerExecutor({
33
48
  * loader: this.env.LOADER,
34
49
  * timeout: 60000,
35
- * globalOutbound: this.env.OUTBOUND,
36
50
  * });
37
51
  *
38
- * getTools() {
39
- * return {
40
- * execute: createExecuteTool({ tools: myTools, executor }),
41
- * };
42
- * }
52
+ * createExecuteTool({ tools: myTools, executor });
43
53
  * ```
44
54
  */
45
55
  function createExecuteTool(options) {
46
- const { tools, description } = options;
56
+ const { tools, description, state } = options;
47
57
  let executor;
48
58
  if (options.executor) executor = options.executor;
49
59
  else if (options.loader) executor = new DynamicWorkerExecutor({
@@ -52,8 +62,10 @@ function createExecuteTool(options) {
52
62
  globalOutbound: options.globalOutbound
53
63
  });
54
64
  else throw new Error("createExecuteTool requires either an `executor` or a `loader` (WorkerLoader binding).");
65
+ const providers = [{ tools }, ...options.providers ?? []];
66
+ if (state) providers.push(stateToolsFromBackend(state));
55
67
  return createCodeTool({
56
- tools,
68
+ tools: providers,
57
69
  executor,
58
70
  description
59
71
  });
@@ -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 } from \"@cloudflare/codemode\";\n\nexport interface CreateExecuteToolOptions {\n /**\n * The tools available inside the sandboxed code.\n * These are exposed as `codemode.toolName(args)` in the sandbox.\n *\n * Typically this is the workspace tools from `createWorkspaceTools()`,\n * but can include any AI SDK tools with `execute` functions.\n */\n tools: ToolSet;\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 * @example\n * ```ts\n * import { createWorkspaceTools, createExecuteTool } from \"@cloudflare/think\";\n *\n * getTools() {\n * const workspaceTools = createWorkspaceTools(this.workspace);\n * return {\n * ...workspaceTools,\n * execute: createExecuteTool({\n * tools: workspaceTools,\n * loader: this.env.LOADER,\n * }),\n * };\n * }\n * ```\n *\n * @example Using a 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 * globalOutbound: this.env.OUTBOUND,\n * });\n *\n * getTools() {\n * return {\n * execute: createExecuteTool({ tools: myTools, executor }),\n * };\n * }\n * ```\n */\nexport function createExecuteTool(options: CreateExecuteToolOptions) {\n const { tools, description } = 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 return createCodeTool({ tools, executor, description });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkGA,SAAgB,kBAAkB,SAAmC;CACnE,MAAM,EAAE,OAAO,gBAAgB;CAE/B,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;AAGH,QAAO,eAAe;EAAE;EAAO;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;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"}
@@ -2,7 +2,7 @@ import {
2
2
  r as ExtensionManager,
3
3
  s as ExtensionPermissions
4
4
  } from "../index-BlcvIdWK.js";
5
- import * as ai from "ai";
5
+ import * as _$ai from "ai";
6
6
 
7
7
  //#region src/tools/extensions.d.ts
8
8
  interface ExtensionToolsOptions {
@@ -30,7 +30,7 @@ interface ExtensionToolsOptions {
30
30
  * ```
31
31
  */
32
32
  declare function createExtensionTools(options: ExtensionToolsOptions): {
33
- load_extension: ai.Tool<
33
+ load_extension: _$ai.Tool<
34
34
  {
35
35
  name: string;
36
36
  version: string;
@@ -48,7 +48,7 @@ declare function createExtensionTools(options: ExtensionToolsOptions): {
48
48
  message: string;
49
49
  }
50
50
  >;
51
- list_extensions: ai.Tool<
51
+ list_extensions: _$ai.Tool<
52
52
  Record<string, never>,
53
53
  {
54
54
  count: number;
@@ -1,4 +1,4 @@
1
- import { n as sanitizeName } from "../manager-DIV0gQf3.js";
1
+ import { n as sanitizeName } from "../manager-JX4H9C6S.js";
2
2
  import { tool } from "ai";
3
3
  import { z } from "zod";
4
4
  //#region src/tools/extensions.ts
@@ -1,5 +1,5 @@
1
- import * as ai from "ai";
2
- import { FileInfo, Workspace } from "agents/experimental/workspace";
1
+ import * as _$ai from "ai";
2
+ import { FileInfo, Workspace } from "@cloudflare/shell";
3
3
 
4
4
  //#region src/tools/workspace.d.ts
5
5
  interface ReadOperations {
@@ -48,11 +48,11 @@ interface GrepOperations {
48
48
  * Create a complete set of AI SDK tools backed by a Workspace instance.
49
49
  *
50
50
  * ```ts
51
- * import { Workspace } from "agents/experimental/workspace";
51
+ * import { Workspace } from "@cloudflare/shell";
52
52
  * import { createWorkspaceTools } from "@cloudflare/think";
53
53
  *
54
54
  * class MyAgent extends Agent<Env> {
55
- * workspace = new Workspace(this);
55
+ * workspace = new Workspace({ sql: this.ctx.storage.sql, name: () => this.name });
56
56
  *
57
57
  * async onChatMessage() {
58
58
  * const tools = createWorkspaceTools(this.workspace);
@@ -63,7 +63,7 @@ interface GrepOperations {
63
63
  * ```
64
64
  */
65
65
  declare function createWorkspaceTools(workspace: Workspace): {
66
- read: ai.Tool<
66
+ read: _$ai.Tool<
67
67
  {
68
68
  path: string;
69
69
  offset?: number | undefined;
@@ -71,7 +71,7 @@ declare function createWorkspaceTools(workspace: Workspace): {
71
71
  },
72
72
  Record<string, unknown>
73
73
  >;
74
- write: ai.Tool<
74
+ write: _$ai.Tool<
75
75
  {
76
76
  path: string;
77
77
  content: string;
@@ -82,7 +82,7 @@ declare function createWorkspaceTools(workspace: Workspace): {
82
82
  lines: number;
83
83
  }
84
84
  >;
85
- edit: ai.Tool<
85
+ edit: _$ai.Tool<
86
86
  {
87
87
  path: string;
88
88
  old_string: string;
@@ -121,7 +121,7 @@ declare function createWorkspaceTools(workspace: Workspace): {
121
121
  fuzzyMatch?: undefined;
122
122
  }
123
123
  >;
124
- list: ai.Tool<
124
+ list: _$ai.Tool<
125
125
  {
126
126
  path: string;
127
127
  limit?: number | undefined;
@@ -133,13 +133,13 @@ declare function createWorkspaceTools(workspace: Workspace): {
133
133
  entries: string[];
134
134
  }
135
135
  >;
136
- find: ai.Tool<
136
+ find: _$ai.Tool<
137
137
  {
138
138
  pattern: string;
139
139
  },
140
140
  Record<string, unknown>
141
141
  >;
142
- grep: ai.Tool<
142
+ grep: _$ai.Tool<
143
143
  {
144
144
  query: string;
145
145
  include?: string | undefined;
@@ -149,7 +149,7 @@ declare function createWorkspaceTools(workspace: Workspace): {
149
149
  },
150
150
  Record<string, unknown>
151
151
  >;
152
- delete: ai.Tool<
152
+ delete: _$ai.Tool<
153
153
  {
154
154
  path: string;
155
155
  recursive?: boolean | undefined;
@@ -162,7 +162,7 @@ declare function createWorkspaceTools(workspace: Workspace): {
162
162
  interface ReadToolOptions {
163
163
  ops: ReadOperations;
164
164
  }
165
- declare function createReadTool(options: ReadToolOptions): ai.Tool<
165
+ declare function createReadTool(options: ReadToolOptions): _$ai.Tool<
166
166
  {
167
167
  path: string;
168
168
  offset?: number | undefined;
@@ -173,7 +173,7 @@ declare function createReadTool(options: ReadToolOptions): ai.Tool<
173
173
  interface WriteToolOptions {
174
174
  ops: WriteOperations;
175
175
  }
176
- declare function createWriteTool(options: WriteToolOptions): ai.Tool<
176
+ declare function createWriteTool(options: WriteToolOptions): _$ai.Tool<
177
177
  {
178
178
  path: string;
179
179
  content: string;
@@ -187,7 +187,7 @@ declare function createWriteTool(options: WriteToolOptions): ai.Tool<
187
187
  interface EditToolOptions {
188
188
  ops: EditOperations;
189
189
  }
190
- declare function createEditTool(options: EditToolOptions): ai.Tool<
190
+ declare function createEditTool(options: EditToolOptions): _$ai.Tool<
191
191
  {
192
192
  path: string;
193
193
  old_string: string;
@@ -229,7 +229,7 @@ declare function createEditTool(options: EditToolOptions): ai.Tool<
229
229
  interface ListToolOptions {
230
230
  ops: ListOperations;
231
231
  }
232
- declare function createListTool(options: ListToolOptions): ai.Tool<
232
+ declare function createListTool(options: ListToolOptions): _$ai.Tool<
233
233
  {
234
234
  path: string;
235
235
  limit?: number | undefined;
@@ -244,7 +244,7 @@ declare function createListTool(options: ListToolOptions): ai.Tool<
244
244
  interface FindToolOptions {
245
245
  ops: FindOperations;
246
246
  }
247
- declare function createFindTool(options: FindToolOptions): ai.Tool<
247
+ declare function createFindTool(options: FindToolOptions): _$ai.Tool<
248
248
  {
249
249
  pattern: string;
250
250
  },
@@ -253,7 +253,7 @@ declare function createFindTool(options: FindToolOptions): ai.Tool<
253
253
  interface GrepToolOptions {
254
254
  ops: GrepOperations;
255
255
  }
256
- declare function createGrepTool(options: GrepToolOptions): ai.Tool<
256
+ declare function createGrepTool(options: GrepToolOptions): _$ai.Tool<
257
257
  {
258
258
  query: string;
259
259
  include?: string | undefined;
@@ -266,7 +266,7 @@ declare function createGrepTool(options: GrepToolOptions): ai.Tool<
266
266
  interface DeleteToolOptions {
267
267
  ops: DeleteOperations;
268
268
  }
269
- declare function createDeleteTool(options: DeleteToolOptions): ai.Tool<
269
+ declare function createDeleteTool(options: DeleteToolOptions): _$ai.Tool<
270
270
  {
271
271
  path: string;
272
272
  recursive?: boolean | undefined;
@@ -38,11 +38,11 @@ function workspaceGrepOps(ws) {
38
38
  * Create a complete set of AI SDK tools backed by a Workspace instance.
39
39
  *
40
40
  * ```ts
41
- * import { Workspace } from "agents/experimental/workspace";
41
+ * import { Workspace } from "@cloudflare/shell";
42
42
  * import { createWorkspaceTools } from "@cloudflare/think";
43
43
  *
44
44
  * class MyAgent extends Agent<Env> {
45
- * workspace = new Workspace(this);
45
+ * workspace = new Workspace({ sql: this.ctx.storage.sql, name: () => this.name });
46
46
  *
47
47
  * async onChatMessage() {
48
48
  * const tools = createWorkspaceTools(this.workspace);
@@ -1 +1 @@
1
- {"version":3,"file":"workspace.js","names":[],"sources":["../../src/tools/workspace.ts"],"sourcesContent":["import type { Workspace, FileInfo } from \"agents/experimental/workspace\";\nimport { tool } from \"ai\";\nimport { z } from \"zod\";\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 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: Workspace): ReadOperations {\n return {\n readFile: (path) => ws.readFile(path),\n stat: (path) => ws.stat(path)\n };\n}\n\nfunction workspaceWriteOps(ws: Workspace): 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: Workspace): EditOperations {\n return {\n readFile: (path) => ws.readFile(path),\n writeFile: (path, content) => ws.writeFile(path, content)\n };\n}\n\nfunction workspaceListOps(ws: Workspace): ListOperations {\n return {\n readDir: (dir, opts) => ws.readDir(dir, opts)\n };\n}\n\nfunction workspaceFindOps(ws: Workspace): FindOperations {\n return {\n glob: (pattern) => ws.glob(pattern)\n };\n}\n\nfunction workspaceDeleteOps(ws: Workspace): DeleteOperations {\n return {\n rm: (path, opts) => ws.rm(path, opts)\n };\n}\n\nfunction workspaceGrepOps(ws: Workspace): 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 instance.\n *\n * ```ts\n * import { Workspace } from \"agents/experimental/workspace\";\n * import { createWorkspaceTools } from \"@cloudflare/think\";\n *\n * class MyAgent extends Agent<Env> {\n * workspace = new Workspace(this);\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: Workspace) {\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;\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 the contents of a file. Returns the file content with line numbers. \" +\n \"Use offset and limit for large 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 }) => {\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 content = await ops.readFile(path);\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: Record<string, unknown> = {\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}\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":";;;AAgDA,SAAS,iBAAiB,IAA+B;AACvD,QAAO;EACL,WAAW,SAAS,GAAG,SAAS,KAAK;EACrC,OAAO,SAAS,GAAG,KAAK,KAAK;EAC9B;;AAGH,SAAS,kBAAkB,IAAgC;AACzD,QAAO;EACL,YAAY,MAAM,YAAY,GAAG,UAAU,MAAM,QAAQ;EACzD,QAAQ,MAAM,SAAS,GAAG,MAAM,MAAM,KAAK;EAC5C;;AAGH,SAAS,iBAAiB,IAA+B;AACvD,QAAO;EACL,WAAW,SAAS,GAAG,SAAS,KAAK;EACrC,YAAY,MAAM,YAAY,GAAG,UAAU,MAAM,QAAQ;EAC1D;;AAGH,SAAS,iBAAiB,IAA+B;AACvD,QAAO,EACL,UAAU,KAAK,SAAS,GAAG,QAAQ,KAAK,KAAK,EAC9C;;AAGH,SAAS,iBAAiB,IAA+B;AACvD,QAAO,EACL,OAAO,YAAY,GAAG,KAAK,QAAQ,EACpC;;AAGH,SAAS,mBAAmB,IAAiC;AAC3D,QAAO,EACL,KAAK,M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E,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 { tool } from \"ai\";\nimport { z } from \"zod\";\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 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: Workspace): ReadOperations {\n return {\n readFile: (path) => ws.readFile(path),\n stat: (path) => ws.stat(path)\n };\n}\n\nfunction workspaceWriteOps(ws: Workspace): 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: Workspace): EditOperations {\n return {\n readFile: (path) => ws.readFile(path),\n writeFile: (path, content) => ws.writeFile(path, content)\n };\n}\n\nfunction workspaceListOps(ws: Workspace): ListOperations {\n return {\n readDir: (dir, opts) => ws.readDir(dir, opts)\n };\n}\n\nfunction workspaceFindOps(ws: Workspace): FindOperations {\n return {\n glob: (pattern) => ws.glob(pattern)\n };\n}\n\nfunction workspaceDeleteOps(ws: Workspace): DeleteOperations {\n return {\n rm: (path, opts) => ws.rm(path, opts)\n };\n}\n\nfunction workspaceGrepOps(ws: Workspace): 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 instance.\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: Workspace) {\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;\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 the contents of a file. Returns the file content with line numbers. \" +\n \"Use offset and limit for large 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 }) => {\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 content = await ops.readFile(path);\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: Record<string, unknown> = {\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}\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":";;;AAgDA,SAAS,iBAAiB,IAA+B;AACvD,QAAO;EACL,WAAW,SAAS,GAAG,SAAS,KAAK;EACrC,OAAO,SAAS,GAAG,KAAK,KAAK;EAC9B;;AAGH,SAAS,kBAAkB,IAAgC;AACzD,QAAO;EACL,YAAY,MAAM,YAAY,GAAG,UAAU,MAAM,QAAQ;EACzD,QAAQ,MAAM,SAAS,GAAG,MAAM,MAAM,KAAK;EAC5C;;AAGH,SAAS,iBAAiB,IAA+B;AACvD,QAAO;EACL,WAAW,SAAS,GAAG,SAAS,KAAK;EACrC,YAAY,MAAM,YAAY,GAAG,UAAU,MAAM,QAAQ;EAC1D;;AAGH,SAAS,iBAAiB,IAA+B;AACvD,QAAO,EACL,UAAU,KAAK,SAAS,GAAG,QAAQ,KAAK,KAAK,EAC9C;;AAGH,SAAS,iBAAiB,IAA+B;AACvD,QAAO,EACL,OAAO,YAAY,GAAG,KAAK,QAAQ,EACpC;;AAGH,SAAS,mBAAmB,IAAiC;AAC3D,QAAO,EACL,KAAK,MAAM,SAAS,GAAG,GAAG,MAAM,KAAK,EACtC;;AAGH,SAAS,iBAAiB,IAA+B;AACvD,QAAO;EACL,OAAO,YAAY,GAAG,KAAK,QAAQ;EACnC,WAAW,SAAS,GAAG,SAAS,KAAK;EACtC;;;;;;;;;;;;;;;;;;;;AAqBH,SAAgB,qBAAqB,WAAsB;AAC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AS,MAAM;;EAE3B,CAAC"}
package/dist/transport.js CHANGED
@@ -1,5 +1,5 @@
1
- import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, r as _assertClassBrand, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-COLddhya.js";
2
- import { t as _classPrivateMethodInitSpec } from "./classPrivateMethodInitSpec-CdQXQy1O.js";
1
+ import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, r as _assertClassBrand, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-q3BTMj1l.js";
2
+ import { t as _classPrivateMethodInitSpec } from "./classPrivateMethodInitSpec-CvUe57wu.js";
3
3
  //#region src/transport.ts
4
4
  /**
5
5
  * Extract the text content from a UIMessage's parts.
package/package.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "tools"
10
10
  ],
11
11
  "type": "module",
12
- "version": "0.0.2",
12
+ "version": "0.1.1",
13
13
  "license": "MIT",
14
14
  "repository": {
15
15
  "directory": "packages/think",
@@ -21,23 +21,20 @@
21
21
  "url": "https://github.com/cloudflare/agents/issues"
22
22
  },
23
23
  "devDependencies": {
24
- "@cloudflare/shell": "^0.0.2",
25
- "ai": "^6.0.116",
24
+ "@cloudflare/shell": "^0.3.0",
25
+ "ai": "^6.0.141",
26
26
  "zod": "^4.3.6"
27
27
  },
28
28
  "peerDependencies": {
29
- "@cloudflare/codemode": "^0.2.1",
30
- "@cloudflare/shell": "^0.0.2",
31
- "agents": "^0.7.7",
29
+ "@cloudflare/codemode": "^0.3.2",
30
+ "@cloudflare/shell": "^0.3.0",
31
+ "agents": "^0.8.7",
32
32
  "ai": "^6.0.0",
33
- "zod": "^3.25.0 || ^4.0.0"
33
+ "zod": "^4.0.0"
34
34
  },
35
35
  "peerDependenciesMeta": {
36
36
  "@cloudflare/codemode": {
37
37
  "optional": true
38
- },
39
- "@cloudflare/shell": {
40
- "optional": true
41
38
  }
42
39
  },
43
40
  "exports": {