@cloudflare/think 0.1.2 → 0.2.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.
@@ -14,14 +14,14 @@ function _assertClassBrand(e, 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.122.0/helpers/classPrivateFieldGet2.js
18
- function _classPrivateFieldGet2(s, a) {
19
- return s.get(_assertClassBrand(s, a));
20
- }
21
- //#endregion
22
17
  //#region \0@oxc-project+runtime@0.122.0/helpers/classPrivateFieldSet2.js
23
18
  function _classPrivateFieldSet2(s, a, r) {
24
19
  return s.set(_assertClassBrand(s, a), r), r;
25
20
  }
26
21
  //#endregion
27
- export { _checkPrivateRedeclaration as a, _classPrivateFieldInitSpec as i, _classPrivateFieldGet2 as n, _assertClassBrand as r, _classPrivateFieldSet2 as t };
22
+ //#region \0@oxc-project+runtime@0.122.0/helpers/classPrivateFieldGet2.js
23
+ function _classPrivateFieldGet2(s, a) {
24
+ return s.get(_assertClassBrand(s, a));
25
+ }
26
+ //#endregion
27
+ export { _checkPrivateRedeclaration as a, _classPrivateFieldInitSpec as i, _classPrivateFieldSet2 as n, _assertClassBrand as r, _classPrivateFieldGet2 as t };
@@ -1,5 +1,5 @@
1
- import { r as _assertClassBrand } from "../classPrivateFieldSet2-D-GfNNJe.js";
2
- import { r as _classPrivateMethodInitSpec, t as ExtensionManager } from "../manager-UjPxAz2E.js";
1
+ import { r as _assertClassBrand } from "../classPrivateFieldGet2-B0jG-d4Z.js";
2
+ import { r as _classPrivateMethodInitSpec, t as ExtensionManager } from "../manager-BY5AZLVa.js";
3
3
  import { WorkerEntrypoint } from "cloudflare:workers";
4
4
  //#region src/extensions/host-bridge.ts
5
5
  /**
@@ -1,4 +1,4 @@
1
- import { a as _checkPrivateRedeclaration, i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, r as _assertClassBrand, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-D-GfNNJe.js";
1
+ import { a as _checkPrivateRedeclaration, i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, r as _assertClassBrand, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-B0jG-d4Z.js";
2
2
  import { jsonSchema, tool } from "ai";
3
3
  //#region \0@oxc-project+runtime@0.122.0/helpers/classPrivateMethodInitSpec.js
4
4
  function _classPrivateMethodInitSpec(e, a) {
@@ -215,4 +215,4 @@ export default class Extension extends WorkerEntrypoint {
215
215
  //#endregion
216
216
  export { sanitizeName as n, _classPrivateMethodInitSpec as r, ExtensionManager as t };
217
217
 
218
- //# sourceMappingURL=manager-UjPxAz2E.js.map
218
+ //# sourceMappingURL=manager-BY5AZLVa.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"manager-UjPxAz2E.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,uB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AAgB,CAAC,IAAI,SAAS,MAAM;EAAE;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-BY5AZLVa.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,KAA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AoE3C,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"}
package/dist/think.d.ts CHANGED
@@ -1,26 +1,17 @@
1
1
  import { LanguageModel, ModelMessage, ToolSet, UIMessage } from "ai";
2
- import { Agent } from "agents";
3
2
  import {
4
- FiberCompleteContext,
3
+ Agent,
5
4
  FiberContext,
6
- FiberMethods,
7
- FiberMethods as FiberMethods$1,
8
5
  FiberRecoveryContext,
9
- FiberState
10
- } from "agents/experimental/forever";
11
- import { ClientToolSchema } from "agents/chat";
6
+ FiberRecoveryContext as FiberRecoveryContext$1
7
+ } from "agents";
8
+ import { ClientToolSchema, MessagePart } from "agents/chat";
9
+ import {
10
+ Session,
11
+ Session as Session$1
12
+ } from "agents/experimental/memory/session";
12
13
 
13
14
  //#region src/think.d.ts
14
- type ThinkBaseConstructor = {
15
- new <
16
- Env extends Cloudflare.Env = Cloudflare.Env,
17
- State = unknown,
18
- Props extends Record<string, unknown> = Record<string, unknown>
19
- >(
20
- ctx: DurableObjectState,
21
- env: Env
22
- ): Agent<Env, State, Props> & FiberMethods$1;
23
- };
24
15
  /**
25
16
  * Callback interface for streaming chat events from a Think sub-agent.
26
17
  *
@@ -54,8 +45,75 @@ interface ChatMessageOptions {
54
45
  tools?: ToolSet;
55
46
  /** Client-provided tool schemas for dynamic tool registration. */
56
47
  clientTools?: ClientToolSchema[];
48
+ /** Whether this is a continuation turn (auto-continue after tool result, recovery).
49
+ * Explicitly set to `false` for initial turns and `true` for continuations. */
50
+ continuation?: boolean;
51
+ /** Custom body fields from the client request. Persisted across hibernation. */
52
+ body?: Record<string, unknown>;
57
53
  }
58
- declare const Think_base: ThinkBaseConstructor;
54
+ /**
55
+ * Result returned by `saveMessages()` and `continueLastTurn()`.
56
+ */
57
+ type SaveMessagesResult = {
58
+ requestId: string;
59
+ status: "completed" | "skipped";
60
+ };
61
+ /**
62
+ * Context passed to `onChatRecovery` when an interrupted chat stream
63
+ * is detected after DO restart.
64
+ */
65
+ type ChatRecoveryContext = {
66
+ streamId: string;
67
+ requestId: string;
68
+ partialText: string;
69
+ partialParts: MessagePart[];
70
+ recoveryData: unknown | null;
71
+ messages: UIMessage[];
72
+ lastBody?: Record<string, unknown>;
73
+ lastClientTools?: ClientToolSchema[];
74
+ };
75
+ /**
76
+ * Options returned from `onChatRecovery` to control recovery behavior.
77
+ */
78
+ type ChatRecoveryOptions = {
79
+ persist?: boolean;
80
+ continue?: boolean;
81
+ };
82
+ /**
83
+ * Controls how overlapping user submit requests behave while another
84
+ * chat turn is already active or queued.
85
+ *
86
+ * - `"queue"` (default) — queue every submit and process them in order.
87
+ * - `"latest"` — keep only the latest overlapping submit; superseded submits
88
+ * still persist their user messages, but do not start their own model turn.
89
+ * - `"merge"` — like latest, but all overlapping user messages remain in
90
+ * the conversation history. The model sees them all in one turn.
91
+ * - `"drop"` — ignore overlapping submits entirely (messages not persisted).
92
+ * - `{ strategy: "debounce" }` — trailing-edge latest with a quiet window.
93
+ *
94
+ * Only applies to `submit-message` requests. Regenerations, tool
95
+ * continuations, approvals, clears, `saveMessages`, and `continueLastTurn`
96
+ * keep their existing serialized behavior.
97
+ */
98
+ type MessageConcurrency =
99
+ | "queue"
100
+ | "latest"
101
+ | "merge"
102
+ | "drop"
103
+ | {
104
+ strategy: "debounce";
105
+ debounceMs?: number;
106
+ };
107
+ /**
108
+ * Result passed to `onChatResponse` after a chat turn completes.
109
+ */
110
+ type ChatResponseResult = {
111
+ message: UIMessage;
112
+ requestId: string;
113
+ continuation: boolean;
114
+ status: "completed" | "error" | "aborted";
115
+ error?: string;
116
+ };
59
117
  /**
60
118
  * An opinionated chat agent base class.
61
119
  *
@@ -64,17 +122,8 @@ declare const Think_base: ThinkBaseConstructor;
64
122
  declare class Think<
65
123
  Env extends Cloudflare.Env = Cloudflare.Env,
66
124
  Config = Record<string, unknown>
67
- > extends Think_base<Env> {
125
+ > extends Agent<Env> {
68
126
  #private;
69
- /** In-memory messages for the current conversation. Authoritative after load. */
70
- messages: UIMessage[];
71
- /**
72
- * Enable durable fiber recovery on start. Set to `true` to
73
- * automatically recover interrupted fibers when the DO restarts.
74
- *
75
- * @experimental
76
- */
77
- fibers: boolean;
78
127
  /**
79
128
  * Wait for MCP server connections to be ready before calling
80
129
  * `onChatMessage`. When enabled, `this.mcp.getAITools()` returns
@@ -89,58 +138,121 @@ declare class Think<
89
138
  timeout: number;
90
139
  };
91
140
  /**
92
- * Maximum number of messages to keep in storage.
93
- * When exceeded, oldest messages are deleted after each persist.
94
- * Set to `undefined` (default) for no limit.
141
+ * Controls how overlapping user submit requests behave while another
142
+ * chat turn is already active or queued.
95
143
  *
96
- * This controls storage only — it does not affect what's sent to the LLM.
97
- * Use `pruneMessages()` in `assembleContext()` to control LLM context.
144
+ * @default "queue"
98
145
  */
99
- maxPersistedMessages: number | undefined;
100
- private _persistedMessageCache;
101
- private _storageReady;
102
- private _abortControllers;
146
+ messageConcurrency: MessageConcurrency;
147
+ /**
148
+ * When true, chat turns are wrapped in `runFiber` for durable execution.
149
+ * Enables `onChatRecovery` hook and `this.stash()` during streaming.
150
+ */
151
+ unstable_chatRecovery: boolean;
152
+ static readonly CHAT_FIBER_NAME = "__cf_internal_chat_turn";
153
+ /** The conversation session — messages, context, compaction, search. */
154
+ session: Session$1;
155
+ constructor(ctx: DurableObjectState, env: Env);
156
+ /**
157
+ * Conversation history. Computed from the active session.
158
+ * Always fresh — reads from Session's tree-structured storage.
159
+ */
160
+ get messages(): UIMessage[];
161
+ private _aborts;
103
162
  private _turnQueue;
104
163
  private _resumableStream;
105
164
  private _pendingResumeConnections;
106
165
  private _lastClientTools;
166
+ private _lastBody;
107
167
  private _continuation;
108
168
  private _continuationTimer;
109
- private _ensureConfigTable;
169
+ private _insideResponseHook;
170
+ private _pendingInteractionPromise;
171
+ private _submitSequence;
172
+ private _latestOverlappingSubmitSequence;
173
+ private _activeDebounceTimer;
174
+ private _activeDebounceResolve;
175
+ private static MESSAGE_DEBOUNCE_MS;
110
176
  /**
111
177
  * Persist a typed configuration object.
112
- * Stored in SQLite so it survives restarts and hibernation.
178
+ * Stored in Session's assistant_config table — survives restarts and hibernation.
113
179
  */
114
180
  configure(config: Config): void;
115
181
  /**
116
182
  * Read the persisted configuration, or null if never configured.
117
183
  */
118
184
  getConfig(): Config | null;
119
- onStart(): void;
185
+ private _configSet;
186
+ private _configGet;
187
+ private _configDelete;
188
+ private _sessionId;
120
189
  /**
121
190
  * Return the language model to use for inference.
122
191
  * Must be overridden by subclasses that rely on the default
123
192
  * `onChatMessage` implementation (the agentic loop).
124
193
  */
125
194
  getModel(): LanguageModel;
126
- /** Return the system prompt for the assistant. */
195
+ /**
196
+ * Return the system prompt for the assistant.
197
+ * Used as fallback when no context blocks are configured via `configureSession`.
198
+ */
127
199
  getSystemPrompt(): string;
128
200
  /** Return the tools available to the assistant. */
129
201
  getTools(): ToolSet;
130
202
  /** Return the maximum number of tool-call steps per turn. */
131
203
  getMaxSteps(): number;
132
204
  /**
133
- * Assemble the model messages from the current conversation history.
134
- * Override to customize context assembly (e.g. inject memory,
135
- * project context, or apply compaction).
205
+ * Configure the session. Called once during `onStart`.
206
+ * Override to add context blocks, compaction, search, skills.
207
+ *
208
+ * The base session is pre-created with `Session.create(this)`.
209
+ * Return it with builder methods chained.
210
+ *
211
+ * Async is supported — use it to read configuration from KV, D1,
212
+ * or R2 before setting up context blocks.
213
+ *
214
+ * @example
215
+ * ```typescript
216
+ * configureSession(session: Session) {
217
+ * return session
218
+ * .withContext("memory", { description: "Learned facts", maxTokens: 2000 })
219
+ * .withCachedPrompt();
220
+ * }
221
+ * ```
222
+ *
223
+ * @example Async configuration from KV
224
+ * ```typescript
225
+ * async configureSession(session: Session) {
226
+ * const config = await this.env.KV.get("agent-config", "json");
227
+ * return session
228
+ * .withContext("memory", { maxTokens: config.memoryTokens })
229
+ * .withCachedPrompt();
230
+ * }
231
+ * ```
232
+ */
233
+ configureSession(session: Session$1): Session$1 | Promise<Session$1>;
234
+ /**
235
+ * Assemble context for the LLM from the current session state.
236
+ *
237
+ * Default implementation:
238
+ * 1. Freezes the system prompt from context blocks (falls back to getSystemPrompt())
239
+ * 2. Gets history from session
240
+ * 3. Applies read-time truncation (old tool outputs, long text)
241
+ * 4. Converts to model messages with tool call pruning
242
+ *
243
+ * Returns { system, messages } so the caller has both.
136
244
  */
137
- assembleContext(): Promise<ModelMessage[]>;
245
+ assembleContext(): Promise<{
246
+ system: string;
247
+ messages: ModelMessage[];
248
+ }>;
138
249
  /**
139
250
  * Handle a chat turn and return the streaming result.
140
251
  *
141
252
  * The default implementation runs the agentic loop:
142
- * 1. Assemble context from `this.messages`
143
- * 2. Call `streamText` with the model, system prompt, tools, and step limit
253
+ * 1. Merge tools: getTools() + clientTools + session context tools + options.tools
254
+ * 2. Assemble context (system prompt + messages) from session state
255
+ * 3. Call `streamText` with the model, system prompt, tools, and step limit
144
256
  *
145
257
  * Override for full control over inference.
146
258
  *
@@ -148,6 +260,17 @@ declare class Think<
148
260
  * return value satisfies this interface.
149
261
  */
150
262
  onChatMessage(options?: ChatMessageOptions): Promise<StreamableResult>;
263
+ /**
264
+ * Called after a chat turn completes and the assistant message has been
265
+ * persisted. The turn lock is released before this hook runs, so it is
266
+ * safe to call other methods from inside.
267
+ *
268
+ * Fires for all turn completion paths: WebSocket chat requests,
269
+ * sub-agent RPC, and auto-continuation.
270
+ *
271
+ * Override for logging, chaining, analytics, usage tracking.
272
+ */
273
+ onChatResponse(_result: ChatResponseResult): void | Promise<void>;
151
274
  /**
152
275
  * Handle an error that occurred during a chat turn.
153
276
  * Override to customize error handling (e.g. logging, metrics).
@@ -169,30 +292,115 @@ declare class Think<
169
292
  ): Promise<void>;
170
293
  /** Get the conversation history as UIMessage[]. */
171
294
  getMessages(): UIMessage[];
172
- /** Clear all messages from storage and memory. */
295
+ /** Clear all messages from storage. */
173
296
  clearMessages(): void;
297
+ /**
298
+ * Inject messages and trigger a model turn — without a WebSocket request.
299
+ *
300
+ * Use for scheduled responses, webhook-triggered turns, proactive agents,
301
+ * or chaining from `onChatResponse`.
302
+ *
303
+ * Accepts static messages or a callback that derives messages from the
304
+ * current state (useful when multiple calls queue up — the callback runs
305
+ * with the latest messages when the turn actually starts).
306
+ *
307
+ * @example Scheduled follow-up
308
+ * ```typescript
309
+ * async onScheduled() {
310
+ * await this.saveMessages([{
311
+ * id: crypto.randomUUID(),
312
+ * role: "user",
313
+ * parts: [{ type: "text", text: "Time for your daily summary." }]
314
+ * }]);
315
+ * }
316
+ * ```
317
+ *
318
+ * @example Function form
319
+ * ```typescript
320
+ * await this.saveMessages((current) => [
321
+ * ...current,
322
+ * { id: crypto.randomUUID(), role: "user", parts: [{ type: "text", text: "Continue." }] }
323
+ * ]);
324
+ * ```
325
+ */
326
+ saveMessages(
327
+ messages:
328
+ | UIMessage[]
329
+ | ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>)
330
+ ): Promise<SaveMessagesResult>;
331
+ /**
332
+ * Run a new LLM call following the last assistant message.
333
+ *
334
+ * The model sees the full conversation (including the last assistant
335
+ * response) and generates a new response. The new response is persisted
336
+ * as a separate assistant message. Building block for chat recovery
337
+ * (Phase 4), "generate more" buttons, and self-correction.
338
+ *
339
+ * Note: this creates a new message, not an append to the existing one.
340
+ * True continuation-as-append (chunk rewriting) is planned for Phase 4.
341
+ *
342
+ * Returns early with `status: "skipped"` if there is no assistant message
343
+ * to continue from.
344
+ */
345
+ protected continueLastTurn(
346
+ body?: Record<string, unknown>
347
+ ): Promise<SaveMessagesResult>;
348
+ /**
349
+ * Override to apply custom transformations to messages before they are
350
+ * persisted to Session storage. Runs after the built-in sanitization
351
+ * (OpenAI metadata stripping, row size enforcement) but before
352
+ * `session.appendMessage` / `session.updateMessage`.
353
+ *
354
+ * Use for redacting PII, stripping internal metadata, or custom compaction.
355
+ */
356
+ protected sanitizeMessageForPersistence(message: UIMessage): UIMessage;
174
357
  private _setupProtocolHandlers;
175
- private _handleProtocol;
358
+ private _handleProtocolEvent;
359
+ private _handleStreamResumeRequest;
360
+ private _handleStreamResumeAck;
176
361
  private _handleChatRequest;
362
+ /**
363
+ * Abort the active turn, invalidate queued turns, and reset
364
+ * concurrency/continuation state. Call this when intercepting
365
+ * clear events or implementing custom reset logic.
366
+ *
367
+ * Does NOT clear messages, streams, or persisted state —
368
+ * only turn execution state.
369
+ */
370
+ protected resetTurnState(): void;
177
371
  private _handleClear;
178
- private _handleCancel;
179
372
  private _streamResult;
180
- private _initStorage;
181
- private _loadMessages;
182
- private _appendMessage;
183
- private _upsertMessage;
184
- private _clearMessages;
185
- private _deleteMessages;
373
+ private _persistAssistantMessage;
186
374
  private _persistClientTools;
187
375
  private _restoreClientTools;
188
- private _persistAssistantMessage;
189
- private _rebuildPersistenceCache;
190
- private _enforceMaxPersistedMessages;
376
+ private _persistBody;
377
+ private _restoreBody;
191
378
  private _applyToolResult;
192
379
  private _applyToolApproval;
380
+ private _applyToolUpdateToMessages;
381
+ protected hasPendingInteraction(): boolean;
382
+ protected waitUntilStable(options?: { timeout?: number }): Promise<boolean>;
383
+ private _awaitWithDeadline;
384
+ private _messageHasPendingInteraction;
385
+ protected _handleInternalFiberRecovery(
386
+ ctx: FiberRecoveryContext$1
387
+ ): Promise<boolean>;
388
+ protected onChatRecovery(
389
+ _ctx: ChatRecoveryContext
390
+ ): Promise<ChatRecoveryOptions>;
391
+ _chatRecoveryContinue(data?: { targetAssistantId?: string }): Promise<void>;
392
+ private _getPartialStreamText;
393
+ private _normalizeMessageConcurrency;
394
+ private _getSubmitConcurrencyDecision;
395
+ private _isSupersededSubmit;
396
+ private _waitForTimestamp;
397
+ private _cancelActiveDebounce;
398
+ private _completeSkippedRequest;
399
+ private _rollbackDroppedSubmit;
193
400
  private _scheduleAutoContinuation;
194
401
  private _fireAutoContinuation;
195
402
  private _activateDeferredContinuation;
403
+ private _fireResponseHook;
196
404
  private _notifyStreamResuming;
197
405
  private _persistOrphanedStream;
198
406
  private _broadcastChat;
@@ -203,11 +411,14 @@ declare class Think<
203
411
  export {
204
412
  ChatMessageOptions,
205
413
  ChatOptions,
206
- type FiberCompleteContext,
414
+ ChatRecoveryContext,
415
+ ChatRecoveryOptions,
416
+ ChatResponseResult,
207
417
  type FiberContext,
208
- type FiberMethods,
209
418
  type FiberRecoveryContext,
210
- type FiberState,
419
+ MessageConcurrency,
420
+ SaveMessagesResult,
421
+ Session,
211
422
  StreamCallback,
212
423
  StreamableResult,
213
424
  Think