@cloudflare/think 0.20.1 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"manager-Cb3DNZgp.js","names":[],"sources":["../src/extensions/manager.ts"],"sourcesContent":["/**\n * ExtensionManager — loads, manages, and exposes tools from extension Workers.\n *\n * Extensions are sandboxed Workers created via WorkerLoader. Each extension\n * declares tools (with JSON Schema inputs) and permissions. The manager:\n *\n * 1. Wraps extension source in a Worker module with describe/execute RPC\n * 2. Loads it via WorkerLoader with permission-gated bindings\n * 3. Discovers tools via describe() RPC call\n * 4. Exposes them as AI SDK tools via getTools()\n *\n * Extension source format — a JS object expression defining tools:\n *\n * ```js\n * ({\n * greet: {\n * description: \"Greet someone\",\n * parameters: { name: { type: \"string\" } },\n * required: [\"name\"],\n * execute: async (args, host) => `Hello, ${args.name}!`\n * }\n * })\n * ```\n *\n * The `host` parameter in execute is provided via `env.host` — a loopback\n * binding that resolves the parent agent and delegates workspace operations\n * (gated by permissions). See HostBridgeLoopback.\n */\n\nimport { tool, jsonSchema } from \"ai\";\nimport type { ToolSet } from \"ai\";\nimport type {\n ExtensionManifest,\n ExtensionPermissions,\n ExtensionInfo,\n ExtensionToolDescriptor\n} from \"./types\";\n\n/**\n * Sanitize a name for use as a tool name prefix.\n * Replaces any non-alphanumeric characters with underscores and\n * collapses consecutive underscores.\n */\nexport function sanitizeName(name: string): string {\n if (!name || name.trim().length === 0) {\n throw new Error(\"Extension name must not be empty\");\n }\n return name\n .replace(/[^a-zA-Z0-9]/g, \"_\")\n .replace(/_+/g, \"_\")\n .replace(/^_|_$/g, \"\");\n}\n\ninterface ExtensionEntrypoint {\n describe(): Promise<string>;\n manifest(): Promise<string>;\n execute(toolName: string, argsJson: string): Promise<string>;\n hook(name: string, ctxProxy: unknown): Promise<string>;\n}\n\ninterface LoadedExtension {\n manifest: ExtensionManifest;\n tools: ExtensionToolDescriptor[];\n hooks: string[];\n entrypoint: ExtensionEntrypoint;\n}\n\n/** Shape persisted to DO storage for each extension. */\ninterface PersistedExtension {\n manifest: ExtensionManifest;\n source: string;\n}\n\nconst STORAGE_PREFIX = \"ext:\";\n\nexport interface ExtensionManagerOptions {\n /** WorkerLoader binding for creating sandboxed extension Workers. */\n loader: WorkerLoader;\n /**\n * Durable Object storage for persisting extensions across hibernation.\n * If provided, loaded extensions survive DO restarts. Call `restore()`\n * on each turn to rebuild in-memory state from storage.\n */\n storage?: DurableObjectStorage;\n /**\n * Factory that creates a loopback Fetcher for workspace access, given\n * an extension's declared permissions. The returned binding is injected\n * into the extension worker's `env.host`.\n *\n * If not provided, extensions receive no host binding (workspace tools\n * will get `null` for the host parameter).\n *\n * Typically wired up using HostBridgeLoopback via `ctx.exports`:\n * ```typescript\n * createHostBinding: (permissions, ownContextLabels) =>\n * ctx.exports.HostBridgeLoopback({\n * props: { agentClassName: \"ChatSession\", agentId: ctx.id.toString(), permissions, ownContextLabels }\n * })\n * ```\n */\n createHostBinding?: (\n permissions: ExtensionPermissions,\n ownContextLabels: string[]\n ) => Fetcher;\n}\n\nexport class ExtensionManager {\n #loader: WorkerLoader;\n #storage: DurableObjectStorage | null;\n #createHostBinding:\n | ((\n permissions: ExtensionPermissions,\n ownContextLabels: string[]\n ) => Fetcher)\n | null;\n #extensions = new Map<string, LoadedExtension>();\n #restored = false;\n #onUnload:\n | ((name: string, contextLabels: string[]) => void | Promise<void>)\n | null = null;\n\n constructor(options: ExtensionManagerOptions) {\n this.#loader = options.loader;\n this.#storage = options.storage ?? null;\n this.#createHostBinding = options.createHostBinding ?? null;\n }\n\n /**\n * Load an extension from source code.\n *\n * The source is a JS object expression defining tools. Each tool has\n * `description`, `parameters` (JSON Schema properties), optional\n * `required` array, and an `execute` async function.\n *\n * @returns Summary of the loaded extension including discovered tools.\n */\n /**\n * Restore extensions from DO storage after hibernation.\n *\n * Idempotent — skips extensions already in memory. Call this at the\n * start of each chat turn (e.g. in onChatMessage before getTools).\n */\n async restore(): Promise<void> {\n if (this.#restored || !this.#storage) return;\n this.#restored = true;\n\n const entries = await this.#storage.list<PersistedExtension>({\n prefix: STORAGE_PREFIX\n });\n\n for (const persisted of entries.values()) {\n if (this.#extensions.has(persisted.manifest.name)) continue;\n await this.#loadInternal(persisted.manifest, persisted.source);\n }\n }\n\n async load(\n manifest: ExtensionManifest,\n source: string\n ): Promise<ExtensionInfo> {\n if (this.#extensions.has(manifest.name)) {\n throw new Error(\n `Extension \"${manifest.name}\" is already loaded. Unload it first.`\n );\n }\n\n const info = await this.#loadInternal(manifest, source);\n\n // Persist to storage so it survives hibernation\n if (this.#storage) {\n await this.#storage.put<PersistedExtension>(\n `${STORAGE_PREFIX}${manifest.name}`,\n { manifest, source }\n );\n }\n\n return info;\n }\n\n async #loadInternal(\n manifest: ExtensionManifest,\n source: string\n ): Promise<ExtensionInfo> {\n const workerModule = wrapExtensionSource(source);\n const permissions = manifest.permissions ?? {};\n\n // Build env bindings for the dynamic worker. Inject a loopback\n // Fetcher as env.host when the extension declares ANY permission\n // that requires host access (workspace, context, messages, session).\n const workerEnv: Record<string, Fetcher> = {};\n const needsHost =\n (permissions.workspace ?? \"none\") !== \"none\" ||\n permissions.context?.read !== undefined ||\n permissions.context?.write !== undefined ||\n (permissions.messages ?? \"none\") !== \"none\" ||\n permissions.session?.sendMessage ||\n permissions.session?.metadata;\n if (this.#createHostBinding && needsHost) {\n const prefix = sanitizeName(manifest.name);\n const ownLabels = (manifest.context ?? []).map(\n (c) => `${prefix}_${c.label}`\n );\n workerEnv.host = this.#createHostBinding(permissions, ownLabels);\n }\n\n const worker = this.#loader.get(\n `ext-${manifest.name}-${manifest.version}-${Date.now()}`,\n () => ({\n compatibilityDate: \"2025-06-01\",\n compatibilityFlags: [\"nodejs_compat\"],\n mainModule: \"extension.js\",\n modules: { \"extension.js\": workerModule },\n globalOutbound: permissions.network?.length ? undefined : null,\n ...(Object.keys(workerEnv).length > 0 ? { env: workerEnv } : {})\n })\n );\n\n const entrypoint = worker.getEntrypoint() as unknown as ExtensionEntrypoint;\n\n // Discover tools and hooks via RPC\n const descriptorsJson = await entrypoint.describe();\n const tools = JSON.parse(descriptorsJson) as ExtensionToolDescriptor[];\n\n let hooks: string[] = [];\n try {\n const manifestJson = await entrypoint.manifest();\n const runtimeManifest = JSON.parse(manifestJson) as {\n hooks?: string[];\n };\n hooks = runtimeManifest.hooks ?? [];\n } catch {\n // Legacy extensions may not have manifest() — treat as no hooks\n }\n\n this.#extensions.set(manifest.name, {\n manifest,\n tools,\n hooks,\n entrypoint\n });\n\n return toExtensionInfo(manifest, tools);\n }\n\n /**\n * Unload an extension, removing its tools from the agent.\n * If an onUnload callback is registered, it fires with the\n * extension's namespaced context labels so the caller can\n * remove context blocks from the Session.\n */\n async unload(name: string): Promise<boolean> {\n const ext = this.#extensions.get(name);\n if (!ext) return false;\n\n const removed = this.#extensions.delete(name);\n if (removed && this.#storage) {\n await this.#storage.delete(`${STORAGE_PREFIX}${name}`);\n }\n\n if (removed && this.#onUnload) {\n const prefix = sanitizeName(name);\n const contextLabels = (ext.manifest.context ?? []).map(\n (c) => `${prefix}_${c.label}`\n );\n await this.#onUnload(name, contextLabels);\n }\n\n return removed;\n }\n\n /**\n * Register a callback invoked when an extension is unloaded.\n * Think uses this to remove the extension's context blocks from Session.\n */\n onUnload(\n cb: (name: string, contextLabels: string[]) => void | Promise<void>\n ): void {\n this.#onUnload = cb;\n }\n\n /**\n * Get the namespaced context labels for all loaded extensions\n * that declare context blocks in their manifests.\n */\n getContextLabels(): Array<{ extName: string; label: string }> {\n const result: Array<{ extName: string; label: string }> = [];\n for (const ext of this.#extensions.values()) {\n if (!ext.manifest.context) continue;\n const prefix = sanitizeName(ext.manifest.name);\n for (const ctx of ext.manifest.context) {\n result.push({\n extName: ext.manifest.name,\n label: `${prefix}_${ctx.label}`\n });\n }\n }\n return result;\n }\n\n /**\n * Get extension manifest by name.\n */\n getManifest(name: string): ExtensionManifest | null {\n return this.#extensions.get(name)?.manifest ?? null;\n }\n\n /**\n * Get extensions that subscribe to a specific hook, in load order.\n */\n getHookSubscribers(\n hookName: string\n ): Array<{ name: string; entrypoint: ExtensionEntrypoint }> {\n const result: Array<{ name: string; entrypoint: ExtensionEntrypoint }> = [];\n for (const ext of this.#extensions.values()) {\n if (ext.hooks.includes(hookName)) {\n result.push({ name: ext.manifest.name, entrypoint: ext.entrypoint });\n }\n }\n return result;\n }\n\n /**\n * List all loaded extensions.\n */\n list(): ExtensionInfo[] {\n return [...this.#extensions.values()].map((ext) =>\n toExtensionInfo(ext.manifest, ext.tools)\n );\n }\n\n /**\n * Get AI SDK tools from all loaded extensions.\n *\n * Tool names are prefixed with the sanitized extension name to avoid\n * collisions: e.g. extension \"github\" with tool \"create_pr\" → \"github_create_pr\".\n */\n getTools(): ToolSet {\n const tools: ToolSet = {};\n\n for (const ext of this.#extensions.values()) {\n const prefix = sanitizeName(ext.manifest.name);\n\n for (const descriptor of ext.tools) {\n const toolName = `${prefix}_${descriptor.name}`;\n\n tools[toolName] = tool({\n description: `[${ext.manifest.name}] ${descriptor.description}`,\n inputSchema: jsonSchema(\n descriptor.inputSchema as Record<string, unknown>\n ),\n execute: async (args: Record<string, unknown>) => {\n if (!this.#extensions.has(ext.manifest.name)) {\n throw new Error(\n `Extension \"${ext.manifest.name}\" has been unloaded. Tool \"${toolName}\" is no longer available.`\n );\n }\n const resultJson = await ext.entrypoint.execute(\n descriptor.name,\n JSON.stringify(args)\n );\n const parsed = JSON.parse(resultJson) as {\n result?: unknown;\n error?: string;\n };\n if (parsed.error) throw new Error(parsed.error);\n return parsed.result;\n }\n });\n }\n }\n\n return tools;\n }\n}\n\nfunction toExtensionInfo(\n manifest: ExtensionManifest,\n tools: ExtensionToolDescriptor[]\n): ExtensionInfo {\n const prefix = sanitizeName(manifest.name);\n return {\n name: manifest.name,\n version: manifest.version,\n description: manifest.description,\n tools: tools.map((t) => `${prefix}_${t.name}`),\n contextLabels: (manifest.context ?? []).map((c) => `${prefix}_${c.label}`),\n permissions: manifest.permissions ?? {}\n };\n}\n\n/**\n * Wrap an extension source in a Worker module that exposes\n * describe(), execute(), manifest(), and hook RPC methods.\n *\n * Source format: `({ tools: {...}, hooks: {...} })`\n * Both `tools` and `hooks` are optional.\n */\nfunction wrapExtensionSource(source: string): string {\n return `import { WorkerEntrypoint } from \"cloudflare:workers\";\n\nconst __ext = (${source});\nif (__ext && typeof __ext === \"object\" && !(\"tools\" in __ext) && !(\"hooks\" in __ext)) {\n throw new Error(\n \"Invalid extension source format. Expected { tools: {...}, hooks: {...} } \" +\n \"but got a flat object. Wrap your tools in a 'tools' key.\"\n );\n}\nconst __tools = __ext.tools || {};\nconst __hooks = __ext.hooks || {};\n\nexport default class Extension extends WorkerEntrypoint {\n describe() {\n const descriptors = [];\n for (const [name, def] of Object.entries(__tools)) {\n descriptors.push({\n name,\n description: def.description || name,\n inputSchema: {\n type: \"object\",\n properties: def.parameters || {},\n required: def.required || []\n }\n });\n }\n return JSON.stringify(descriptors);\n }\n\n manifest() {\n return JSON.stringify({\n hooks: Object.keys(__hooks)\n });\n }\n\n async execute(toolName, argsJson) {\n const def = __tools[toolName];\n if (!def || !def.execute) {\n return JSON.stringify({ error: \"Unknown tool: \" + toolName });\n }\n try {\n const args = JSON.parse(argsJson);\n const result = await def.execute(args, this.env.host ?? null);\n return JSON.stringify({ result });\n } catch (err) {\n return JSON.stringify({ error: err.message || String(err) });\n }\n }\n\n async hook(name, ctxSnapshot) {\n const fn = __hooks[name];\n if (!fn) return JSON.stringify({ skipped: true });\n try {\n // Hook handlers receive (ctxSnapshot, host) — symmetric with tool\n // executes. \\`host\\` is null when the extension was loaded without\n // host-requiring permissions or when the worker entry point doesn't\n // re-export HostBridgeLoopback.\n const result = await fn(ctxSnapshot, this.env.host ?? null);\n return JSON.stringify({ result: result ?? {} });\n } catch (err) {\n return JSON.stringify({ error: err.message || String(err) });\n }\n }\n}\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;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M,SAAS;EACf,SAAS,SAAS;EAClB,aAAa,SAAS;EACtB,OAAO,MAAM,KAAK,MAAM,GAAG,OAAO,GAAG,EAAE,MAAM;EAC7C,gBAAgB,SAAS,WAAW,CAAC,EAAA,CAAG,KAAK,MAAM,GAAG,OAAO,GAAG,EAAE,OAAO;EACzE,aAAa,SAAS,eAAe,CAAC;CACxC;AACF;;;;;;;;AASA,SAAS,oBAAoB,QAAwB;CACnD,OAAO;;iBAEQ,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DxB"}
1
+ {"version":3,"file":"manager-BubfmA3q.js","names":[],"sources":["../src/extensions/manager.ts"],"sourcesContent":["/**\n * ExtensionManager — loads, manages, and exposes tools from extension Workers.\n *\n * Extensions are sandboxed Workers created via WorkerLoader. Each extension\n * declares tools (with JSON Schema inputs) and permissions. The manager:\n *\n * 1. Wraps extension source in a Worker module with describe/execute RPC\n * 2. Loads it via WorkerLoader with permission-gated bindings\n * 3. Discovers tools via describe() RPC call\n * 4. Exposes them as AI SDK tools via getTools()\n *\n * Extension source format — a JS object expression defining tools:\n *\n * ```js\n * ({\n * greet: {\n * description: \"Greet someone\",\n * parameters: { name: { type: \"string\" } },\n * required: [\"name\"],\n * execute: async (args, host) => `Hello, ${args.name}!`\n * }\n * })\n * ```\n *\n * The `host` parameter in execute is provided via `env.host` — a loopback\n * binding that resolves the parent agent and delegates workspace operations\n * (gated by permissions). See HostBridgeLoopback.\n */\n\nimport { tool, jsonSchema } from \"ai\";\nimport type { ToolSet } from \"ai\";\nimport type {\n ExtensionManifest,\n ExtensionPermissions,\n ExtensionInfo,\n ExtensionToolDescriptor\n} from \"./types\";\n\n/**\n * Sanitize a name for use as a tool name prefix.\n * Replaces any non-alphanumeric characters with underscores and\n * collapses consecutive underscores.\n */\nexport function sanitizeName(name: string): string {\n if (!name || name.trim().length === 0) {\n throw new Error(\"Extension name must not be empty\");\n }\n return name\n .replace(/[^a-zA-Z0-9]/g, \"_\")\n .replace(/_+/g, \"_\")\n .replace(/^_|_$/g, \"\");\n}\n\ninterface ExtensionEntrypoint {\n describe(): Promise<string>;\n manifest(): Promise<string>;\n execute(toolName: string, argsJson: string): Promise<string>;\n hook(name: string, ctxProxy: unknown): Promise<string>;\n}\n\ninterface LoadedExtension {\n manifest: ExtensionManifest;\n tools: ExtensionToolDescriptor[];\n hooks: string[];\n entrypoint: ExtensionEntrypoint;\n}\n\n/** Shape persisted to DO storage for each extension. */\ninterface PersistedExtension {\n manifest: ExtensionManifest;\n source: string;\n}\n\nconst STORAGE_PREFIX = \"ext:\";\n\nexport interface ExtensionManagerOptions {\n /** WorkerLoader binding for creating sandboxed extension Workers. */\n loader: WorkerLoader;\n /**\n * Durable Object storage for persisting extensions across hibernation.\n * If provided, loaded extensions survive DO restarts. Call `restore()`\n * on each turn to rebuild in-memory state from storage.\n */\n storage?: DurableObjectStorage;\n /**\n * Factory that creates a loopback Fetcher for workspace access, given\n * an extension's declared permissions. The returned binding is injected\n * into the extension worker's `env.host`.\n *\n * If not provided, extensions receive no host binding (workspace tools\n * will get `null` for the host parameter).\n *\n * Typically wired up using HostBridgeLoopback via `ctx.exports`:\n * ```typescript\n * createHostBinding: (permissions, ownContextLabels) =>\n * ctx.exports.HostBridgeLoopback({\n * props: { agentClassName: \"ChatSession\", agentId: ctx.id.toString(), permissions, ownContextLabels }\n * })\n * ```\n */\n createHostBinding?: (\n permissions: ExtensionPermissions,\n ownContextLabels: string[]\n ) => Fetcher;\n}\n\nexport class ExtensionManager {\n #loader: WorkerLoader;\n #storage: DurableObjectStorage | null;\n #createHostBinding:\n | ((\n permissions: ExtensionPermissions,\n ownContextLabels: string[]\n ) => Fetcher)\n | null;\n #extensions = new Map<string, LoadedExtension>();\n #restored = false;\n #onUnload:\n | ((name: string, contextLabels: string[]) => void | Promise<void>)\n | null = null;\n\n constructor(options: ExtensionManagerOptions) {\n this.#loader = options.loader;\n this.#storage = options.storage ?? null;\n this.#createHostBinding = options.createHostBinding ?? null;\n }\n\n /**\n * Load an extension from source code.\n *\n * The source is a JS object expression defining tools. Each tool has\n * `description`, `parameters` (JSON Schema properties), optional\n * `required` array, and an `execute` async function.\n *\n * @returns Summary of the loaded extension including discovered tools.\n */\n /**\n * Restore extensions from DO storage after hibernation.\n *\n * Idempotent — skips extensions already in memory. Call this at the\n * start of each chat turn (e.g. in onChatMessage before getTools).\n */\n async restore(): Promise<void> {\n if (this.#restored || !this.#storage) return;\n this.#restored = true;\n\n const entries = await this.#storage.list<PersistedExtension>({\n prefix: STORAGE_PREFIX\n });\n\n for (const persisted of entries.values()) {\n if (this.#extensions.has(persisted.manifest.name)) continue;\n await this.#loadInternal(persisted.manifest, persisted.source);\n }\n }\n\n async load(\n manifest: ExtensionManifest,\n source: string\n ): Promise<ExtensionInfo> {\n if (this.#extensions.has(manifest.name)) {\n throw new Error(\n `Extension \"${manifest.name}\" is already loaded. Unload it first.`\n );\n }\n\n const info = await this.#loadInternal(manifest, source);\n\n // Persist to storage so it survives hibernation\n if (this.#storage) {\n await this.#storage.put<PersistedExtension>(\n `${STORAGE_PREFIX}${manifest.name}`,\n { manifest, source }\n );\n }\n\n return info;\n }\n\n async #loadInternal(\n manifest: ExtensionManifest,\n source: string\n ): Promise<ExtensionInfo> {\n const workerModule = wrapExtensionSource(source);\n const permissions = manifest.permissions ?? {};\n\n // Build env bindings for the dynamic worker. Inject a loopback\n // Fetcher as env.host when the extension declares ANY permission\n // that requires host access (workspace, context, messages, session).\n const workerEnv: Record<string, Fetcher> = {};\n const needsHost =\n (permissions.workspace ?? \"none\") !== \"none\" ||\n permissions.context?.read !== undefined ||\n permissions.context?.write !== undefined ||\n (permissions.messages ?? \"none\") !== \"none\" ||\n permissions.session?.sendMessage ||\n permissions.session?.metadata;\n if (this.#createHostBinding && needsHost) {\n const prefix = sanitizeName(manifest.name);\n const ownLabels = (manifest.context ?? []).map(\n (c) => `${prefix}_${c.label}`\n );\n workerEnv.host = this.#createHostBinding(permissions, ownLabels);\n }\n\n const worker = this.#loader.get(\n `ext-${manifest.name}-${manifest.version}-${Date.now()}`,\n () => ({\n compatibilityDate: \"2025-06-01\",\n compatibilityFlags: [\"nodejs_compat\"],\n mainModule: \"extension.js\",\n modules: { \"extension.js\": workerModule },\n globalOutbound: permissions.network?.length ? undefined : null,\n ...(Object.keys(workerEnv).length > 0 ? { env: workerEnv } : {})\n })\n );\n\n const entrypoint = worker.getEntrypoint() as unknown as ExtensionEntrypoint;\n\n // Discover tools and hooks via RPC\n const descriptorsJson = await entrypoint.describe();\n const tools = JSON.parse(descriptorsJson) as ExtensionToolDescriptor[];\n\n let hooks: string[] = [];\n try {\n const manifestJson = await entrypoint.manifest();\n const runtimeManifest = JSON.parse(manifestJson) as {\n hooks?: string[];\n };\n hooks = runtimeManifest.hooks ?? [];\n } catch {\n // Legacy extensions may not have manifest() — treat as no hooks\n }\n\n this.#extensions.set(manifest.name, {\n manifest,\n tools,\n hooks,\n entrypoint\n });\n\n return toExtensionInfo(manifest, tools);\n }\n\n /**\n * Unload an extension, removing its tools from the agent.\n * If an onUnload callback is registered, it fires with the\n * extension's namespaced context labels so the caller can\n * remove context blocks from the Session.\n */\n async unload(name: string): Promise<boolean> {\n const ext = this.#extensions.get(name);\n if (!ext) return false;\n\n const removed = this.#extensions.delete(name);\n if (removed && this.#storage) {\n await this.#storage.delete(`${STORAGE_PREFIX}${name}`);\n }\n\n if (removed && this.#onUnload) {\n const prefix = sanitizeName(name);\n const contextLabels = (ext.manifest.context ?? []).map(\n (c) => `${prefix}_${c.label}`\n );\n await this.#onUnload(name, contextLabels);\n }\n\n return removed;\n }\n\n /**\n * Register a callback invoked when an extension is unloaded.\n * Think uses this to remove the extension's context blocks from Session.\n */\n onUnload(\n cb: (name: string, contextLabels: string[]) => void | Promise<void>\n ): void {\n this.#onUnload = cb;\n }\n\n /**\n * Get the namespaced context labels for all loaded extensions\n * that declare context blocks in their manifests.\n */\n getContextLabels(): Array<{ extName: string; label: string }> {\n const result: Array<{ extName: string; label: string }> = [];\n for (const ext of this.#extensions.values()) {\n if (!ext.manifest.context) continue;\n const prefix = sanitizeName(ext.manifest.name);\n for (const ctx of ext.manifest.context) {\n result.push({\n extName: ext.manifest.name,\n label: `${prefix}_${ctx.label}`\n });\n }\n }\n return result;\n }\n\n /**\n * Get extension manifest by name.\n */\n getManifest(name: string): ExtensionManifest | null {\n return this.#extensions.get(name)?.manifest ?? null;\n }\n\n /**\n * Get extensions that subscribe to a specific hook, in load order.\n */\n getHookSubscribers(\n hookName: string\n ): Array<{ name: string; entrypoint: ExtensionEntrypoint }> {\n const result: Array<{ name: string; entrypoint: ExtensionEntrypoint }> = [];\n for (const ext of this.#extensions.values()) {\n if (ext.hooks.includes(hookName)) {\n result.push({ name: ext.manifest.name, entrypoint: ext.entrypoint });\n }\n }\n return result;\n }\n\n /**\n * List all loaded extensions.\n */\n list(): ExtensionInfo[] {\n return [...this.#extensions.values()].map((ext) =>\n toExtensionInfo(ext.manifest, ext.tools)\n );\n }\n\n /**\n * Get AI SDK tools from all loaded extensions.\n *\n * Tool names are prefixed with the sanitized extension name to avoid\n * collisions: e.g. extension \"github\" with tool \"create_pr\" → \"github_create_pr\".\n */\n getTools(): ToolSet {\n const tools: ToolSet = {};\n\n for (const ext of this.#extensions.values()) {\n const prefix = sanitizeName(ext.manifest.name);\n\n for (const descriptor of ext.tools) {\n const toolName = `${prefix}_${descriptor.name}`;\n\n tools[toolName] = tool({\n description: `[${ext.manifest.name}] ${descriptor.description}`,\n inputSchema: jsonSchema(\n descriptor.inputSchema as Record<string, unknown>\n ),\n execute: async (args: Record<string, unknown>) => {\n if (!this.#extensions.has(ext.manifest.name)) {\n throw new Error(\n `Extension \"${ext.manifest.name}\" has been unloaded. Tool \"${toolName}\" is no longer available.`\n );\n }\n const resultJson = await ext.entrypoint.execute(\n descriptor.name,\n JSON.stringify(args)\n );\n const parsed = JSON.parse(resultJson) as {\n result?: unknown;\n error?: string;\n };\n if (parsed.error) throw new Error(parsed.error);\n return parsed.result;\n }\n });\n }\n }\n\n return tools;\n }\n}\n\nfunction toExtensionInfo(\n manifest: ExtensionManifest,\n tools: ExtensionToolDescriptor[]\n): ExtensionInfo {\n const prefix = sanitizeName(manifest.name);\n return {\n name: manifest.name,\n version: manifest.version,\n description: manifest.description,\n tools: tools.map((t) => `${prefix}_${t.name}`),\n contextLabels: (manifest.context ?? []).map((c) => `${prefix}_${c.label}`),\n permissions: manifest.permissions ?? {}\n };\n}\n\n/**\n * Wrap an extension source in a Worker module that exposes\n * describe(), execute(), manifest(), and hook RPC methods.\n *\n * Source format: `({ tools: {...}, hooks: {...} })`\n * Both `tools` and `hooks` are optional.\n */\nfunction wrapExtensionSource(source: string): string {\n return `import { WorkerEntrypoint } from \"cloudflare:workers\";\n\nconst __ext = (${source});\nif (__ext && typeof __ext === \"object\" && !(\"tools\" in __ext) && !(\"hooks\" in __ext)) {\n throw new Error(\n \"Invalid extension source format. Expected { tools: {...}, hooks: {...} } \" +\n \"but got a flat object. Wrap your tools in a 'tools' key.\"\n );\n}\nconst __tools = __ext.tools || {};\nconst __hooks = __ext.hooks || {};\n\nexport default class Extension extends WorkerEntrypoint {\n describe() {\n const descriptors = [];\n for (const [name, def] of Object.entries(__tools)) {\n descriptors.push({\n name,\n description: def.description || name,\n inputSchema: {\n type: \"object\",\n properties: def.parameters || {},\n required: def.required || []\n }\n });\n }\n return JSON.stringify(descriptors);\n }\n\n manifest() {\n return JSON.stringify({\n hooks: Object.keys(__hooks)\n });\n }\n\n async execute(toolName, argsJson) {\n const def = __tools[toolName];\n if (!def || !def.execute) {\n return JSON.stringify({ error: \"Unknown tool: \" + toolName });\n }\n try {\n const args = JSON.parse(argsJson);\n const result = await def.execute(args, this.env.host ?? null);\n return JSON.stringify({ result });\n } catch (err) {\n return JSON.stringify({ error: err.message || String(err) });\n }\n }\n\n async hook(name, ctxSnapshot) {\n const fn = __hooks[name];\n if (!fn) return JSON.stringify({ skipped: true });\n try {\n // Hook handlers receive (ctxSnapshot, host) — symmetric with tool\n // executes. \\`host\\` is null when the extension was loaded without\n // host-requiring permissions or when the worker entry point doesn't\n // re-export HostBridgeLoopback.\n const result = await fn(ctxSnapshot, this.env.host ?? null);\n return JSON.stringify({ result: result ?? {} });\n } catch (err) {\n return JSON.stringify({ error: err.message || String(err) });\n }\n }\n}\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,SAAgB,aAAa,MAAsB;CACjD,IAAI,CAAC,QAAQ,KAAK,KAAK,CAAC,CAAC,WAAW,GAClC,MAAM,IAAI,MAAM,kCAAkC;CAEpD,OAAO,KACJ,QAAQ,iBAAiB,GAAG,CAAC,CAC7B,QAAQ,OAAO,GAAG,CAAC,CACnB,QAAQ,UAAU,EAAE;AACzB;AAsBA,MAAM,iBAAiB;;;;;;;;AAiCvB,IAAa,mBAAb,MAA8B;CAe5B,YAAY,SAAkC;;;;;gEANhC,IAAI,IAA6B,CAAA;8CACnC,KAAA;8CAGD,IAAA;EAGT,uBAAA,SAAA,MAAe,QAAQ,MAAA;EACvB,uBAAA,UAAA,MAAgB,QAAQ,WAAW,IAAA;EACnC,uBAAA,oBAAA,MAA0B,QAAQ,qBAAqB,IAAA;CACzD;;;;;;;;;;;;;;;;CAiBA,MAAM,UAAyB;EAC7B,IAAA,uBAAA,WAAI,IAAA,KAAkB,CAAA,uBAAA,UAAC,IAAA,GAAe;EACtC,uBAAA,WAAA,MAAiB,IAAA;EAEjB,MAAM,UAAU,MAAA,uBAAA,UAAM,IAAA,CAAA,CAAc,KAAyB,EAC3D,QAAQ,eACV,CAAC;EAED,KAAK,MAAM,aAAa,QAAQ,OAAO,GAAG;GACxC,IAAA,uBAAA,aAAI,IAAA,CAAA,CAAiB,IAAI,UAAU,SAAS,IAAI,GAAG;GACnD,MAAA,kBAAA,yBAAM,MAAA,aAAA,CAAA,CAAA,KAAA,MAAmB,UAAU,UAAU,UAAU,MAAM;EAC/D;CAC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C,QAAQ,CAER;CAEA,uBAAA,aAAA,IAAA,CAAA,CAAiB,IAAI,SAAS,MAAM;EAClC;EACA;EACA;EACA;CACF,CAAC;CAED,OAAO,gBAAgB,UAAU,KAAK;AACxC;AAqIF,SAAS,gBACP,UACA,OACe;CACf,MAAM,SAAS,aAAa,SAAS,IAAI;CACzC,OAAO;EACL,MAAM,SAAS;EACf,SAAS,SAAS;EAClB,aAAa,SAAS;EACtB,OAAO,MAAM,KAAK,MAAM,GAAG,OAAO,GAAG,EAAE,MAAM;EAC7C,gBAAgB,SAAS,WAAW,CAAC,EAAA,CAAG,KAAK,MAAM,GAAG,OAAO,GAAG,EAAE,OAAO;EACzE,aAAa,SAAS,eAAe,CAAC;CACxC;AACF;;;;;;;;AASA,SAAS,oBAAoB,QAAwB;CACnD,OAAO;;iBAEQ,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DxB"}
@@ -58,7 +58,7 @@ import {
58
58
  x as resolveSelfMention,
59
59
  y as idempotencyKeyForEvent,
60
60
  z as TextStreamCallbackOptions
61
- } from "../index-CmhSKa6U.js";
61
+ } from "../index-Cjq_e9F2.js";
62
62
  export {
63
63
  type ChannelSpeakerLabel,
64
64
  type ChatSdkMessengerEventInput,
@@ -2,7 +2,7 @@ import {
2
2
  R as TextStreamCallback,
3
3
  c as MessengerDefinition,
4
4
  n as ChatSdkMessengerOptions
5
- } from "../index-CmhSKa6U.js";
5
+ } from "../index-Cjq_e9F2.js";
6
6
  import { TelegramAdapterConfig } from "@chat-adapter/telegram";
7
7
 
8
8
  //#region src/messengers/telegram.d.ts
package/dist/think.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- import { $n as messengerChannel, $t as RunTurnWait, An as TurnConfig, At as ChunkContext, Bn as action, Bt as MessageMetadataCallback, Cn as ThinkSubmissionInspection, Ct as ChatRecoveryConfig, D as DeliveryKind, Dn as ToolCallContext, Dt as ChatRecoveryProgressContext, En as ThinkWallClockSchedule, Et as ChatRecoveryOptions, Fn as TurnTrigger, Ft as ExtensionConfig, Gn as ChannelContext, Gt as PrepareStepResult, Hn as isAction, Ht as PendingApproval, In as TypedToolCall, It as FiberContext, Jn as ChannelDeliverySurface, Jt as ResolvedChatRecoveryConfig, Kn as ChannelDefinition, Kt as RejectExecutionOptions, Ln as TypedToolResult, Lt as FiberRecoveryContext, Mn as TurnInput, Mt as ContextOverflowConfig, Nn as TurnInputMessages, Nt as DeleteSubmissionsOptions, O as DeliveryTag, On as ToolCallDecision, Ot as ChatResponseResult, Pn as TurnResult, Pt as DeliverNoticeOptions, Qn as ThinkChannels, Qt as RunTurnSubmit, Rn as WaitForSubmissionOptions, Rt as ListSubmissionsOptions, Sn as ThinkScheduledTasks, St as ChatOptions, Tn as ThinkTime, Tt as ChatRecoveryExhaustedContext, Un as skills, Ut as PrepareStepContext, Vn as defaultContextOverflowClassifier, Vt as OnStartDegradation, Wn as ChannelCapabilities, Wt as PrepareStepFunction, Xn as ChannelKind, Xt as RunTurnOptions, Yn as ChannelIngress, Yt as RunTurnBase, Zn as NormalizedChannelDefinition, Zt as RunTurnStream, _n as ThinkModel, _t as AddMessagesOptions, an as SkillWorkspaceSeedOptions, bn as ThinkScheduledTaskContext, bt as ChatErrorContext, cn as StepResult, ct as ActionApprovalPolicy, dn as StreamableResult, dt as ActionConfig, en as SaveMessagesOptions, er as MediaEvictionConfig, fn as SubmitMessagesOptions, ft as ActionContext, gn as ThinkIntervalSchedule, gt as ActiveTurn, hn as Think, ht as ActionPermissionSpec, in as SkillSource, ir as ThinkSession, jn as TurnContext, jt as ChunkPart, kn as ToolCallResultContext, kt as ChatStartEvent, ln as StopCondition, lt as ActionAuthorizationContext, mn as TextStreamPart, mt as ActionKind, nn as SessionMessage, nr as CompactionErrorHandler, on as StepConfig, ot as Action, pn as SubmitMessagesResult, pt as ActionIdempotencyKey, qn as ChannelDeliveryPolicy, qt as ReplyAttachment, rn as SkillRunContext, rr as SessionContextOptions, sn as StepContext, st as ActionApprovalDescriptor, tn as SaveMessagesResult, tr as CompactAfterOptions, un as StreamCallback, ut as ActionAuthorizationDecision, vn as ThinkModelId, vt as CancelSubmissionResult, wn as ThinkSubmissionStatus, wt as ChatRecoveryContext, xn as ThinkScheduledTaskSchedule, xt as ChatInterruptedInfo, yn as ThinkScheduledTask, yt as ChatErrorClassification, zn as Workspace, zt as MessageConcurrency } from "./index-CmhSKa6U.js";
2
- import { h as WorkspaceLike } from "./workspace-CNeXc2vl.js";
3
- import { a as FetchResponseMode, i as FetchRedirectPolicy, n as FetchBindingTarget, o as FetchResult, r as FetchErrorCode, s as FetchToolEvent, t as CreateFetchToolsOptions } from "./fetch-By3eIQ-a.js";
4
- export { Action, ActionApprovalDescriptor, ActionApprovalPolicy, ActionAuthorizationContext, ActionAuthorizationDecision, ActionConfig, ActionContext, ActionIdempotencyKey, ActionKind, ActionPermissionSpec, ActiveTurn, AddMessagesOptions, CancelSubmissionResult, type ChannelCapabilities, type ChannelContext, type ChannelDefinition, type ChannelDeliveryPolicy, type ChannelDeliverySurface, type ChannelIngress, type ChannelKind, ChatErrorClassification, ChatErrorContext, ChatInterruptedInfo, ChatOptions, type ChatRecoveryConfig, type ChatRecoveryContext, type ChatRecoveryExhaustedContext, type ChatRecoveryOptions, type ChatRecoveryProgressContext, type ChatResponseResult, ChatStartEvent, ChunkContext, ChunkPart, type CompactAfterOptions, type CompactionErrorHandler, ContextOverflowConfig, type CreateFetchToolsOptions, DeleteSubmissionsOptions, DeliverNoticeOptions, type DeliveryKind, type DeliveryTag, ExtensionConfig, type FetchBindingTarget, type FetchErrorCode, type FetchRedirectPolicy, type FetchResponseMode, type FetchResult, type FetchToolEvent, type FiberContext, type FiberRecoveryContext, ListSubmissionsOptions, type MediaEvictionConfig, type MessageConcurrency, MessageMetadataCallback, type NormalizedChannelDefinition, OnStartDegradation, PendingApproval, PrepareStepContext, type PrepareStepFunction, type PrepareStepResult, RejectExecutionOptions, ReplyAttachment, type ResolvedChatRecoveryConfig, RunTurnBase, RunTurnOptions, RunTurnStream, RunTurnSubmit, RunTurnWait, type SaveMessagesOptions, type SaveMessagesResult, ThinkSession as Session, ThinkSession, type SessionContextOptions, type SessionMessage, type SkillRunContext, type SkillSource, type SkillWorkspaceSeedOptions, StepConfig, StepContext, type StepResult, type StopCondition, StreamCallback, StreamableResult, SubmitMessagesOptions, SubmitMessagesResult, type TextStreamPart, Think, type ThinkChannels, ThinkIntervalSchedule, ThinkModel, ThinkModelId, ThinkScheduledTask, ThinkScheduledTaskContext, ThinkScheduledTaskSchedule, ThinkScheduledTasks, ThinkSubmissionInspection, ThinkSubmissionStatus, ThinkTime, ThinkWallClockSchedule, ToolCallContext, ToolCallDecision, ToolCallResultContext, TurnConfig, TurnContext, TurnInput, TurnInputMessages, TurnResult, TurnTrigger, type TypedToolCall, type TypedToolResult, WaitForSubmissionOptions, Workspace, type WorkspaceLike, action, defaultContextOverflowClassifier, isAction, messengerChannel, skills };
1
+ import { $n as MediaEvictionConfig, $t as RunTurnWait, An as TurnConfig, At as ChunkContext, Bn as defaultContextOverflowClassifier, Bt as MessageMetadataCallback, Cn as ThinkSubmissionInspection, Ct as ChatRecoveryConfig, D as DeliveryKind, Dn as ToolCallContext, Dt as ChatRecoveryProgressContext, En as ThinkWallClockSchedule, Et as ChatRecoveryOptions, Fn as TurnTrigger, Ft as ExtensionConfig, Gn as ChannelDefinition, Gt as PrepareStepResult, Hn as skills, Ht as PendingApproval, In as TypedToolCall, It as FiberContext, Jn as ChannelIngress, Jt as ResolvedChatRecoveryConfig, Kn as ChannelDeliveryPolicy, Kt as RejectExecutionOptions, Ln as TypedToolResult, Lt as FiberRecoveryContext, Mn as TurnInput, Mt as ContextOverflowConfig, Nn as TurnInputMessages, Nt as DeleteSubmissionsOptions, O as DeliveryTag, On as ToolCallDecision, Ot as ChatResponseResult, Pn as TurnResult, Pt as DeliverNoticeOptions, Qn as messengerChannel, Qt as RunTurnSubmit, Rn as WaitForSubmissionOptions, Rt as ListSubmissionsOptions, Sn as ThinkScheduledTasks, St as ChatOptions, Tn as ThinkTime, Tt as ChatRecoveryExhaustedContext, Un as ChannelCapabilities, Ut as PrepareStepContext, Vn as isAction, Vt as OnStartDegradation, Wn as ChannelContext, Wt as PrepareStepFunction, Xn as NormalizedChannelDefinition, Xt as RunTurnOptions, Yn as ChannelKind, Yt as RunTurnBase, Zn as ThinkChannels, Zt as RunTurnStream, _n as ThinkModel, _t as AddMessagesOptions, an as SkillWorkspaceSeedOptions, bn as ThinkScheduledTaskContext, bt as ChatErrorContext, cn as StepResult, ct as ActionApprovalPolicy, dn as StreamableResult, dt as ActionConfig, en as SaveMessagesOptions, er as CompactAfterOptions, fn as SubmitMessagesOptions, ft as ActionContext, gn as ThinkIntervalSchedule, gt as ActiveTurn, hn as Think, ht as ActionPermissionSpec, in as SkillSource, jn as TurnContext, jt as ChunkPart, kn as ToolCallResultContext, kt as ChatStartEvent, ln as StopCondition, lt as ActionAuthorizationContext, mn as TextStreamPart, mt as ActionKind, nn as SessionMessage, nr as SessionContextOptions, on as StepConfig, ot as Action, pn as SubmitMessagesResult, pt as ActionIdempotencyKey, qn as ChannelDeliverySurface, qt as ReplyAttachment, rn as SkillRunContext, rr as ThinkSession, sn as StepContext, st as ActionApprovalDescriptor, tn as SaveMessagesResult, tr as CompactionErrorHandler, un as StreamCallback, ut as ActionAuthorizationDecision, vn as ThinkModelId, vt as CancelSubmissionResult, wn as ThinkSubmissionStatus, wt as ChatRecoveryContext, xn as ThinkScheduledTaskSchedule, xt as ChatInterruptedInfo, yn as ThinkScheduledTask, yt as ChatErrorClassification, zn as action, zt as MessageConcurrency } from "./index-Cjq_e9F2.js";
2
+ import { a as FetchResponseMode, d as lazyWorkspace, i as FetchRedirectPolicy, l as ThinkWorkspace, n as FetchBindingTarget, o as FetchResult, r as FetchErrorCode, s as FetchToolEvent, t as CreateFetchToolsOptions, u as ThinkWorkspaceFilesystem } from "./fetch-C7s1mpgg.js";
3
+ export { Action, ActionApprovalDescriptor, ActionApprovalPolicy, ActionAuthorizationContext, ActionAuthorizationDecision, ActionConfig, ActionContext, ActionIdempotencyKey, ActionKind, ActionPermissionSpec, ActiveTurn, AddMessagesOptions, CancelSubmissionResult, type ChannelCapabilities, type ChannelContext, type ChannelDefinition, type ChannelDeliveryPolicy, type ChannelDeliverySurface, type ChannelIngress, type ChannelKind, ChatErrorClassification, ChatErrorContext, ChatInterruptedInfo, ChatOptions, type ChatRecoveryConfig, type ChatRecoveryContext, type ChatRecoveryExhaustedContext, type ChatRecoveryOptions, type ChatRecoveryProgressContext, type ChatResponseResult, ChatStartEvent, ChunkContext, ChunkPart, type CompactAfterOptions, type CompactionErrorHandler, ContextOverflowConfig, type CreateFetchToolsOptions, DeleteSubmissionsOptions, DeliverNoticeOptions, type DeliveryKind, type DeliveryTag, ExtensionConfig, type FetchBindingTarget, type FetchErrorCode, type FetchRedirectPolicy, type FetchResponseMode, type FetchResult, type FetchToolEvent, type FiberContext, type FiberRecoveryContext, ListSubmissionsOptions, type MediaEvictionConfig, type MessageConcurrency, MessageMetadataCallback, type NormalizedChannelDefinition, OnStartDegradation, PendingApproval, PrepareStepContext, type PrepareStepFunction, type PrepareStepResult, RejectExecutionOptions, ReplyAttachment, type ResolvedChatRecoveryConfig, RunTurnBase, RunTurnOptions, RunTurnStream, RunTurnSubmit, RunTurnWait, type SaveMessagesOptions, type SaveMessagesResult, ThinkSession as Session, ThinkSession, type SessionContextOptions, type SessionMessage, type SkillRunContext, type SkillSource, type SkillWorkspaceSeedOptions, StepConfig, StepContext, type StepResult, type StopCondition, StreamCallback, StreamableResult, SubmitMessagesOptions, SubmitMessagesResult, type TextStreamPart, Think, type ThinkChannels, ThinkIntervalSchedule, ThinkModel, ThinkModelId, ThinkScheduledTask, ThinkScheduledTaskContext, ThinkScheduledTaskSchedule, ThinkScheduledTasks, ThinkSubmissionInspection, ThinkSubmissionStatus, ThinkTime, ThinkWallClockSchedule, type ThinkWorkspace, type ThinkWorkspaceFilesystem, ToolCallContext, ToolCallDecision, ToolCallResultContext, TurnConfig, TurnContext, TurnInput, TurnInputMessages, TurnResult, TurnTrigger, type TypedToolCall, type TypedToolResult, WaitForSubmissionOptions, action, defaultContextOverflowClassifier, isAction, lazyWorkspace, messengerChannel, skills };
package/dist/think.js CHANGED
@@ -1,6 +1,6 @@
1
- import { a as _assertClassBrand, i as _classPrivateFieldGet2, n as sanitizeName, o as _classPrivateFieldInitSpec, r as _classPrivateFieldSet2, s as _classPrivateMethodInitSpec, t as ExtensionManager } from "./manager-Cb3DNZgp.js";
2
- import { createWorkspaceTools } from "./tools/workspace.js";
3
- import { createFetchTools } from "./tools/fetch.js";
1
+ import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, r as _assertClassBrand, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-DwGJfC3w.js";
2
+ import { n as sanitizeName, r as _classPrivateMethodInitSpec, t as ExtensionManager } from "./manager-BubfmA3q.js";
3
+ import { i as resolveWorkspacePath, n as WorkspaceFiles, r as lazyWorkspace, t as createFetchTools } from "./fetch-9f1p8UrI.js";
4
4
  import { truncatePausedExecutionOutput } from "./tools/execute.js";
5
5
  import { _ as MESSENGER_REPLY_FIBER_NAME, n as ThinkMessengerRuntime, t as DEFAULT_MESSENGER_CONCURRENCY } from "./chat-sdk-BEjKXjCm.js";
6
6
  import "./messengers/index.js";
@@ -17,7 +17,8 @@ import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext, __DO_NOT_USE_WILL_BREAK__
17
17
  import { AbortRegistry, AgentToolProgressEmitter, AgentToolStreamProgressThrottle, AutoContinuationController, CHAT_MESSAGE_TYPES, CHAT_RECOVERY_INCIDENT_KEY_PREFIX, CHAT_RECOVERY_PROGRESS_KEY, CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS, CHAT_RECOVERY_TASK_NAME, ChatRecoveryEngine, ChatStreamStalledError, ContinuationState, MAX_BOUND_PARAMS, PreStreamTurns, ResumableStream, ResumeHandshake, StreamAccumulator, SubmitConcurrencyController, TIMED_OUT, TurnQueue, aiSdkRecoveryCodec, applyToolUpdate, awaitWithDeadline, buildChatRecoveringFrame, buildInClauseStrings, chatRecoveryBackoffSeconds, chatRecoveryTaskRunOptions, classifyAgentToolChildRecovery, clearChatTerminal, clientResolvableToolNames, createChatFiberSnapshot, createChatRecoveryTaskDefinition, createChatStreams, createChatTurnTaskDefinition, createToolsFromClientSchemas, crossMessageToolResultUpdate, dispatchChatRecoveryToHandoff, drainInteractionApplies, enforceRowSizeLimit, hasIncompleteToolBatch, interceptAgentToolBroadcast, isDurableObjectResetError, isLateToolInputChunk, isPositionlessAgentToolChunk, iterateWithStallWatchdog, lateToolInputForwardChunks, listActiveChatRecoveryIncidents, normalizeToolInput, originMessageIds, parseProtocolMessage, partAwaitsClientInteraction, pausedExecutionUpdate, pendingChatTerminal, persistReconstructedOrphan, readChatRecoveryProgress, reconcileMessages, recordChatTerminal, repairInterruptedToolParts, resolveChatRecoveryConfig, retryAfterSeconds, runChatRecoveryExhaustion, sanitizeMessage, setChatRecovering, sweepStaleChatRecoveryIncidents, toolApprovalUpdate, toolPartHasSettledResult, toolResultUpdate, truncateOlderMessages, truncateOlderToolResults, unwrapChatFiberSnapshot, withOriginMessageIds, wrapChatFiberSnapshot } from "agents/chat";
18
18
  import { Sessions, isCompactionMessage } from "agents/sessions";
19
19
  import { AgentContextProvider, ContextBlocks } from "agents/context";
20
- import { Workspace, Workspace as Workspace$1 } from "@cloudflare/shell";
20
+ import { Workspace } from "@cloudflare/computer";
21
+ import { createAITools } from "@cloudflare/computer/tools/ai-sdk";
21
22
  //#region src/session.ts
22
23
  var _handle = /* @__PURE__ */ new WeakMap();
23
24
  var _context = /* @__PURE__ */ new WeakMap();
@@ -408,7 +409,7 @@ function extensionFor(mediaType) {
408
409
  }
409
410
  /** Workspace path for the n-th value evicted from a message. */
410
411
  function evictedFilePath(messageId, index, mediaType) {
411
- return `/attachments/evicted/${messageId}-${index}.${extensionFor(mediaType)}`;
412
+ return `/workspace/attachments/evicted/${messageId}-${index}.${extensionFor(mediaType)}`;
412
413
  }
413
414
  //#endregion
414
415
  //#region src/channels/index.ts
@@ -649,10 +650,6 @@ function mediaEvictionCutoff(messageCount, keepRecentMessages, step) {
649
650
  return Math.max(0, messageCount - truncationKeepRecent(messageCount, safeStep) - stepsBack * safeStep);
650
651
  }
651
652
  const DEFAULT_ACTION_TIMEOUT_MS = 3e4;
652
- /** Whether a workspace can receive raw bytes, which skills projection needs. */
653
- function hasWriteFileBytes(workspace) {
654
- return typeof workspace.writeFileBytes === "function";
655
- }
656
653
  const ACTION_OUTPUT_MAX_CHARS = 2e4;
657
654
  const MAX_REPLY_ATTACHMENTS_PER_TURN = 32;
658
655
  const ACTION_LEDGER_SWEEP_INTERVAL_MS = 3600 * 1e3;
@@ -760,6 +757,14 @@ function keepResolvedPauses(incoming, serverMessages) {
760
757
  };
761
758
  });
762
759
  }
760
+ /**
761
+ * Whether a workspace is a Computer `Workspace` this agent owns, as opposed
762
+ * to a client for one another Durable Object owns. Checked by shape so a
763
+ * second copy of `@cloudflare/computer` in the bundle still matches.
764
+ */
765
+ function isLocalWorkspace(workspace) {
766
+ return "ready" in workspace && typeof workspace.ready === "function" && "stub" in workspace && typeof workspace.stub === "function";
767
+ }
763
768
  const ACTION_PENDING_SWEEP_INTERVAL_MS = 3600 * 1e3;
764
769
  const ACTION_PENDING_LAST_SWEPT_KEY = "cf_think_action_pending_approvals:last_swept_at";
765
770
  /** Prefix for durable-pause action execution ids (vs codemode execution ids). */
@@ -1126,20 +1131,29 @@ function parseDeclaredTaskScheduleUnchecked(rawSchedule, taskTimezone, defaultTi
1126
1131
  }
1127
1132
  throw new Error(`Unsupported schedule DSL "${rawSchedule}"`);
1128
1133
  }
1134
+ const zonedPartsFormatters = /* @__PURE__ */ new Map();
1135
+ function getZonedPartsFormatter(timezone) {
1136
+ let formatter = zonedPartsFormatters.get(timezone);
1137
+ if (!formatter) {
1138
+ formatter = new Intl.DateTimeFormat("en-US", {
1139
+ timeZone: timezone,
1140
+ calendar: "iso8601",
1141
+ numberingSystem: "latn",
1142
+ weekday: "short",
1143
+ year: "numeric",
1144
+ month: "2-digit",
1145
+ day: "2-digit",
1146
+ hour: "2-digit",
1147
+ minute: "2-digit",
1148
+ second: "2-digit",
1149
+ hourCycle: "h23"
1150
+ });
1151
+ zonedPartsFormatters.set(timezone, formatter);
1152
+ }
1153
+ return formatter;
1154
+ }
1129
1155
  function getZonedParts(date, timezone) {
1130
- const parts = new Intl.DateTimeFormat("en-US", {
1131
- timeZone: timezone,
1132
- calendar: "iso8601",
1133
- numberingSystem: "latn",
1134
- weekday: "short",
1135
- year: "numeric",
1136
- month: "2-digit",
1137
- day: "2-digit",
1138
- hour: "2-digit",
1139
- minute: "2-digit",
1140
- second: "2-digit",
1141
- hourCycle: "h23"
1142
- }).formatToParts(date);
1156
+ const parts = getZonedPartsFormatter(timezone).formatToParts(date);
1143
1157
  const part = (type) => parts.find((entry) => entry.type === type)?.value ?? "";
1144
1158
  return {
1145
1159
  year: Number(part("year")),
@@ -1559,13 +1573,11 @@ var Think = class Think extends Agent {
1559
1573
  _classPrivateFieldInitSpec(this, _contextBlocks, void 0);
1560
1574
  this._cachedMessages = [];
1561
1575
  this._onStartDegradations = [];
1562
- this.workspaceBash = true;
1563
1576
  this.fetchTools = false;
1564
1577
  this._repairApprovalRespondedThisTurn = false;
1565
1578
  this._mediaEvictionRunning = false;
1566
1579
  this._mediaEvictionPending = false;
1567
1580
  this._mediaEvictionAppendsDuringPass = 0;
1568
- this._warnedEvictionUnsupported = false;
1569
1581
  this._mediaEvictionFruitless = null;
1570
1582
  this._lastHydration = null;
1571
1583
  this._warnedHydrationWindowed = false;
@@ -1665,10 +1677,7 @@ var Think = class Think extends Agent {
1665
1677
  const _onStart = this.onStart.bind(this);
1666
1678
  const startThink = async (props, update) => {
1667
1679
  await withAgentSpan(this, "initialize_think_session", "startup", { "cloudflare.agents.component": "think" }, async () => {
1668
- if (!this.workspace) this.workspace = new Workspace$1({
1669
- sql: this.ctx.storage.sql,
1670
- name: () => this.name
1671
- });
1680
+ if (!this.workspace) this.workspace = new Workspace({ storage: this.ctx.storage });
1672
1681
  this.session = await this.configureSession(new ThinkSession(this.sessions.session(), () => this.context));
1673
1682
  _classPrivateFieldSet2(_contextBlocks, this, new ContextBlocks([...await this.configureContext(), ...this.session.internal_takePendingContext()], this.session.internal_promptStore() ?? _assertClassBrand(_Think_brand, this, _contextProvider).call(this, "_system_prompt"), (label) => _assertClassBrand(_Think_brand, this, _contextProvider).call(this, label)));
1674
1683
  await _classPrivateFieldGet2(_contextBlocks, this).load();
@@ -1991,14 +2000,7 @@ var Think = class Think extends Agent {
1991
2000
  backlogRemains: false
1992
2001
  };
1993
2002
  try {
1994
- const writeFileBytes = this.workspace.writeFileBytes?.bind(this.workspace);
1995
- if (!writeFileBytes) {
1996
- if (!this._warnedEvictionUnsupported) {
1997
- this._warnedEvictionUnsupported = true;
1998
- console.warn("[Think] mediaEviction is enabled but the configured workspace does not implement writeFileBytes; media eviction is a no-op for this agent.");
1999
- }
2000
- return null;
2001
- }
2003
+ const files = new WorkspaceFiles(this.workspace);
2002
2004
  const stats = await this.session.getHistoryRowStats();
2003
2005
  const aged = stats.slice(0, mediaEvictionCutoff(stats.length, config.keepRecentMessages, this.truncationStep));
2004
2006
  let processed = 0;
@@ -2015,7 +2017,7 @@ var Think = class Think extends Agent {
2015
2017
  minPartBytes: config.minPartBytes,
2016
2018
  write: async (index, bytes, mediaType) => {
2017
2019
  const path = evictedFilePath(message.id, index, mediaType);
2018
- await writeFileBytes(path, bytes, mediaType ?? "application/octet-stream");
2020
+ await files.write(path, bytes);
2019
2021
  return path;
2020
2022
  }
2021
2023
  });
@@ -2823,7 +2825,11 @@ var Think = class Think extends Agent {
2823
2825
  */
2824
2826
  _dispatchChatRecovery(callback, data, detached) {
2825
2827
  return dispatchChatRecoveryToHandoff({
2826
- detached,
2828
+ detached: (onTurnStarted) => this._chatRecoveryEngine().runRecoveryAttempt({
2829
+ callback,
2830
+ data,
2831
+ run: () => detached(onTurnStarted)
2832
+ }),
2827
2833
  track: (turn) => this.lifecycle.trackAlarmWork(turn),
2828
2834
  redefer: (dedupeKey) => this._enqueueChatRecovery(callback, data ?? {}, "redefer", CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS, dedupeKey),
2829
2835
  onDetachedError: (error) => console.error(`[Think] ${callback} dispatch failed`, error)
@@ -2993,7 +2999,7 @@ var Think = class Think extends Agent {
2993
2999
  "read",
2994
3000
  "write",
2995
3001
  "edit",
2996
- "list",
3002
+ "ls",
2997
3003
  "find",
2998
3004
  "grep",
2999
3005
  "delete"
@@ -3122,14 +3128,6 @@ var Think = class Think extends Agent {
3122
3128
  async _configureSkillWorkspace(registry) {
3123
3129
  if (this.skillWorkspace === false) return;
3124
3130
  const workspace = this.workspace;
3125
- if (!hasWriteFileBytes(workspace)) {
3126
- const warning = "skillWorkspace is enabled but the configured workspace does not implement writeFileBytes; skills stay source-backed.";
3127
- if (!this._loggedSkillWarnings.has(warning)) {
3128
- this._loggedSkillWarnings.add(warning);
3129
- console.warn(`[think] ${warning}`);
3130
- }
3131
- return;
3132
- }
3133
3131
  try {
3134
3132
  const key = "skillsWorkspaceFingerprint";
3135
3133
  if (this._configGet(key) === registry.fingerprint) {
@@ -3776,7 +3774,7 @@ var Think = class Think extends Agent {
3776
3774
  const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : 1e4;
3777
3775
  await this.mcp.waitForConnections({ timeout });
3778
3776
  }
3779
- const workspaceTools = createWorkspaceTools(this.workspace, { bash: this.workspaceBash });
3777
+ const workspaceTools = createAITools({ workspace: this.workspace });
3780
3778
  const fetchToolSet = this.fetchTools ? createFetchTools({
3781
3779
  ...this.fetchTools,
3782
3780
  workspace: this.workspace,
@@ -4652,18 +4650,34 @@ var Think = class Think extends Agent {
4652
4650
  const { createChunkSnapshot } = await import("./hook-proxy-DY2sBNa0.js");
4653
4651
  await this._dispatchExtensionObservation("onChunk", createChunkSnapshot(event));
4654
4652
  }
4653
+ /**
4654
+ * Hand out an RPC stub to this agent's Workspace. `getWorkspace(stub)`
4655
+ * from `@cloudflare/computer` calls it to reach the Workspace from
4656
+ * another Worker or Durable Object, and the Worker shell backend calls it
4657
+ * so its isolate can reach back into the Workspace.
4658
+ *
4659
+ * Only a Workspace this agent owns can hand out a stub; a client for
4660
+ * another object's Workspace cannot.
4661
+ */
4662
+ async __getWorkspaceStub() {
4663
+ await this.__unsafe_ensureInitialized();
4664
+ const workspace = this.workspace;
4665
+ if (!isLocalWorkspace(workspace)) throw new Error("[Think] This agent's workspace belongs to another Durable Object, so it cannot hand out a Workspace stub.");
4666
+ await workspace.ready();
4667
+ return workspace.stub();
4668
+ }
4655
4669
  async _hostReadFile(path) {
4656
4670
  await this.__unsafe_ensureInitialized();
4657
- return await this.workspace.readFile(path) ?? null;
4671
+ return new WorkspaceFiles(this.workspace).readText(resolveWorkspacePath(path));
4658
4672
  }
4659
4673
  async _hostWriteFile(path, content) {
4660
4674
  await this.__unsafe_ensureInitialized();
4661
- await this.workspace.writeFile(path, content);
4675
+ await new WorkspaceFiles(this.workspace).write(resolveWorkspacePath(path), content);
4662
4676
  }
4663
4677
  async _hostDeleteFile(path) {
4664
4678
  await this.__unsafe_ensureInitialized();
4665
4679
  try {
4666
- await this.workspace.rm(path);
4680
+ await new WorkspaceFiles(this.workspace).remove(resolveWorkspacePath(path));
4667
4681
  return true;
4668
4682
  } catch {
4669
4683
  return false;
@@ -4671,11 +4685,11 @@ var Think = class Think extends Agent {
4671
4685
  }
4672
4686
  async _hostListFiles(dir) {
4673
4687
  await this.__unsafe_ensureInitialized();
4674
- return (await this.workspace.readDir(dir)).map((e) => ({
4688
+ return (await new WorkspaceFiles(this.workspace).list(resolveWorkspacePath(dir))).map((e) => ({
4675
4689
  name: e.name,
4676
4690
  type: e.type,
4677
- size: e.size ?? 0,
4678
- path: e.path ?? `${dir}/${e.name}`
4691
+ size: e.size,
4692
+ path: e.path
4679
4693
  }));
4680
4694
  }
4681
4695
  async _hostGetContext(label) {
@@ -9604,6 +9618,7 @@ var Think = class Think extends Agent {
9604
9618
  isAwaitingClientInteraction: () => this.hasPendingInteraction(),
9605
9619
  listActiveIncidents: async () => (await listActiveChatRecoveryIncidents(this.ctx.storage)).map(({ incident }) => incident),
9606
9620
  putIncident: (key, incident) => this.ctx.storage.put(key, incident),
9621
+ syncStorage: () => this.ctx.storage.sync(),
9607
9622
  deleteIncident: async (key) => {
9608
9623
  await this.ctx.storage.delete(key);
9609
9624
  },
@@ -9707,7 +9722,8 @@ var Think = class Think extends Agent {
9707
9722
  requestId: input.requestId,
9708
9723
  recoveryRootRequestId,
9709
9724
  latestUserMessageId,
9710
- recoveryKind
9725
+ recoveryKind,
9726
+ trigger: "stalled"
9711
9727
  });
9712
9728
  const partialText = input.partialParts.filter((p) => p.type === "text").map((p) => p.text).join("");
9713
9729
  if (exhausted) {
@@ -10176,49 +10192,15 @@ var Think = class Think extends Agent {
10176
10192
  return this._exhaustRecoveryGiveUp(callback, data, "stable_timeout");
10177
10193
  }
10178
10194
  /**
10179
- * Apply the tight OOM-retry budget to a recovery error (#1825). Invoked from
10180
- * `_handleRecoveryCallbackError`, i.e. for an OOM that is *thrown* out of a
10181
- * recovery turn (typically from recovery bookkeeping or storage/SQL ops that
10182
- * reject with the memory-limit-reset message after an isolate reset). An OOM
10183
- * that surfaces as a returned `error` result means `continueLastTurn` already
10184
- * terminalized the turn (client error frame + `onError`), so it is NOT routed
10185
- * here — re-driving a terminalized turn would be wasteful and risk a second
10186
- * terminal signal. `error` may be an Error or a wrapper with a `cause` chain.
10187
- *
10188
- * The reliable terminator is the begin-path (`evaluateChatRecoveryIncident`),
10189
- * which seals once `oomAttempts` exceeds the budget; that runs before the
10190
- * memory-heavy turn, in the low-memory window where writes succeed. This
10191
- * method's job is to persist `oomAttempts` (small writes) so the begin path
10192
- * can act on it, and to schedule a delayed re-run while under budget.
10193
- *
10194
- * Returns `true` when the error was an OOM and this method owns the outcome:
10195
- * - under budget → a delayed re-run was scheduled (best-effort: a transient
10196
- * spike may clear);
10197
- * - over budget (or untrackable, or the bookkeeping itself OOMed) →
10198
- * terminalized via the give-up path with `reason="out_of_memory"`.
10199
- * Returns `false` for non-OOM errors so the caller proceeds normally.
10200
- */
10201
- async _handleRecoveryOom(callback, data, error) {
10202
- if (!isDurableObjectMemoryLimitReset(error)) return false;
10203
- let decision = "exhausted";
10204
- try {
10205
- decision = await this._chatRecoveryEngine().recordOomAndDecide({
10206
- incidentId: data?.incidentId,
10207
- callback,
10208
- data,
10209
- maxOomRetries: this._resolveChatRecoveryConfig().maxOomRetries
10210
- });
10211
- } catch (bookkeepingError) {
10212
- console.error("[Think] failed to record OOM recovery attempt; terminalizing", bookkeepingError);
10213
- decision = "exhausted";
10214
- }
10215
- if (decision === "exhausted") await this._exhaustRecoveryGiveUp(callback, data, "out_of_memory");
10216
- return true;
10217
- }
10218
- /**
10219
10195
  * Handle an error thrown by `_chatRecoveryContinue` / `_chatRecoveryRetry`
10220
10196
  * after the incident was opened.
10221
10197
  *
10198
+ * - A Durable Object memory-limit reset is re-thrown with no bookkeeping.
10199
+ * The isolate is condemned: its storage calls reject and unconfirmed
10200
+ * writes are discarded, so nothing written here would survive (#2613).
10201
+ * The attempt's `attemptsInFlight` entry stays behind, and the next
10202
+ * attempt counts it against `maxInterruptedAttempts` before running
10203
+ * anything heavy.
10222
10204
  * - A platform transient (`isPlatformTransientError` from `agents` — a
10223
10205
  * deploy code-update reset / script supersede, a `retryable`-flagged
10224
10206
  * platform error, or "Network connection lost.", looking through wrappers
@@ -10243,7 +10225,7 @@ var Think = class Think extends Agent {
10243
10225
  * send something new).
10244
10226
  */
10245
10227
  async _handleRecoveryCallbackError(callback, data, error) {
10246
- if (await this._handleRecoveryOom(callback, data, error)) return;
10228
+ if (isDurableObjectMemoryLimitReset(error)) throw error;
10247
10229
  if (isPlatformTransientError(error)) {
10248
10230
  const message = error instanceof Error ? error.message : String(error);
10249
10231
  const incidentId = data?.incidentId;
@@ -11304,6 +11286,6 @@ for (const method of [
11304
11286
  Think.prototype.rejectExecution
11305
11287
  ]) callable()(method, void 0);
11306
11288
  //#endregion
11307
- export { ThinkSession as Session, ThinkSession, Think, Workspace, action, defaultContextOverflowClassifier, isAction, messengerChannel, skills };
11289
+ export { ThinkSession as Session, ThinkSession, Think, action, defaultContextOverflowClassifier, isAction, lazyWorkspace, messengerChannel, skills };
11308
11290
 
11309
11291
  //# sourceMappingURL=think.js.map