@cloudflare/think 0.23.0 → 0.25.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.
Files changed (49) hide show
  1. package/README.md +30 -40
  2. package/dist/{chat-sdk-BEjKXjCm.js → chat-sdk-4Nu96eDX.js} +375 -256
  3. package/dist/chat-sdk-4Nu96eDX.js.map +1 -0
  4. package/dist/extensions/index.d.ts +30 -72
  5. package/dist/extensions/index.js +45 -47
  6. package/dist/extensions/index.js.map +1 -1
  7. package/dist/{fetch-DO3uQ9py.js → fetch-BbYxtlff.js} +10 -2
  8. package/dist/fetch-BbYxtlff.js.map +1 -0
  9. package/dist/manager-B3rcb_6p.js +493 -0
  10. package/dist/manager-B3rcb_6p.js.map +1 -0
  11. package/dist/manager-CWGumyKi.d.ts +3391 -0
  12. package/dist/messengers/index.d.ts +54 -66
  13. package/dist/messengers/index.js +2 -2
  14. package/dist/messengers/telegram.d.ts +4 -4
  15. package/dist/messengers/telegram.js +1 -1
  16. package/dist/think.d.ts +2 -2
  17. package/dist/think.js +8493 -10725
  18. package/dist/think.js.map +1 -1
  19. package/dist/tools/browser.d.ts +1 -1
  20. package/dist/tools/browser.js +1 -1
  21. package/dist/tools/browser.js.map +1 -1
  22. package/dist/tools/execute.d.ts +2 -2
  23. package/dist/tools/execute.js +2 -2
  24. package/dist/tools/execute.js.map +1 -1
  25. package/dist/tools/extensions.d.ts +1 -1
  26. package/dist/tools/extensions.js +1 -1
  27. package/dist/tools/fetch.js +1 -1
  28. package/dist/workflows.d.ts +5 -2
  29. package/docs/actions.md +12 -0
  30. package/docs/channels.md +10 -4
  31. package/docs/client-tools.md +57 -27
  32. package/docs/context.md +92 -0
  33. package/docs/getting-started.md +4 -4
  34. package/docs/index.md +112 -52
  35. package/docs/lifecycle-hooks.md +10 -21
  36. package/docs/multi-chat.md +6 -6
  37. package/docs/programmatic-submissions.md +28 -10
  38. package/docs/sub-agents.md +45 -51
  39. package/docs/tools.md +41 -15
  40. package/docs/workflows.md +5 -4
  41. package/package.json +15 -10
  42. package/dist/chat-sdk-BEjKXjCm.js.map +0 -1
  43. package/dist/fetch-DO3uQ9py.js.map +0 -1
  44. package/dist/hook-proxy-DY2sBNa0.js +0 -117
  45. package/dist/hook-proxy-DY2sBNa0.js.map +0 -1
  46. package/dist/index-DDnny6kt.d.ts +0 -5847
  47. package/dist/manager-BubfmA3q.js +0 -313
  48. package/dist/manager-BubfmA3q.js.map +0 -1
  49. package/dist/manager-rze95KCk.d.ts +0 -235
@@ -0,0 +1 @@
1
+ {"version":3,"file":"manager-B3rcb_6p.js","names":["ExtensionManager","ExtensionCore"],"sources":["../src/extensions/released.ts","../src/extensions/manager.ts"],"sourcesContent":["/**\n * Think's released extension format, on the one extension core\n * (`agents/internal`): the `{ tools, hooks }` source an extension is\n * written in, as an extension function the core's runtime runs; the\n * released hooks (`beforeTurn`, `beforeToolCall`, `afterToolCall`,\n * `onStepFinish`, `onChunk`) and how they combine; and the JSON snapshot\n * each one sends, which an extension's hook code reads.\n *\n * @internal\n */\nimport type { HookHandler, HookRules } from \"agents/internal\";\nimport type { ThinkModel, TurnConfig, TurnContext } from \"../turn-types\";\n\n/**\n * Best-effort JSON-safe normalization. Strips functions, AbortSignals,\n * symbols, and replaces `Error` instances with `{ name, message, stack }`.\n * Falls back to `String(value)` for anything that won't round-trip.\n */\nfunction jsonSafe(value: unknown, depth = 0): unknown {\n if (depth > 6) return undefined;\n if (value === null || value === undefined) return value;\n const t = typeof value;\n if (t === \"string\" || t === \"number\" || t === \"boolean\") return value;\n if (t === \"bigint\") return String(value);\n if (t === \"function\" || t === \"symbol\") return undefined;\n if (value instanceof Error) {\n return { name: value.name, message: value.message, stack: value.stack };\n }\n if (Array.isArray(value)) return value.map((v) => jsonSafe(v, depth + 1));\n if (t === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n // Skip non-cloneable hosts like AbortSignal which carry event listeners.\n if (v instanceof AbortSignal) continue;\n const safe = jsonSafe(v, depth + 1);\n if (safe !== undefined) out[k] = safe;\n }\n return out;\n }\n try {\n return String(value);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Serializable snapshot of TurnContext.\n * Passed to extension Workers during beforeTurn hook dispatch.\n * Plain data — no methods, no functions, no classes.\n */\ninterface TurnContextSnapshot {\n system: string;\n toolNames: string[];\n messageCount: number;\n continuation: boolean;\n body?: Record<string, unknown>;\n modelId: string;\n requestId?: string;\n trigger?: string;\n}\n\n/**\n * Create a serializable snapshot from a TurnContext.\n *\n * Pass `model` when `beforeTurn` already overrode it: `ctx.model` lazily\n * resolves the default model, which may need an AI binding the turn never uses.\n */\nexport function createTurnContextSnapshot(\n ctx: TurnContext,\n model: ThinkModel = ctx.model\n): TurnContextSnapshot {\n return {\n system: ctx.system,\n toolNames: Object.keys(ctx.tools),\n messageCount: ctx.messages.length,\n continuation: ctx.continuation,\n body: ctx.body,\n modelId:\n typeof model === \"string\"\n ? model\n : (((model as unknown as Record<string, unknown>).modelId as string) ??\n \"unknown\"),\n ...(ctx.requestId !== undefined && { requestId: ctx.requestId }),\n ...(ctx.trigger !== undefined && { trigger: ctx.trigger })\n };\n}\n\n// ── Per-tool / per-step / per-chunk snapshots ─────────────────────────\n// These are observation-only snapshots — extensions cannot return data\n// that influences the turn (block/substitute/cancel etc.). Keep the\n// payloads small; extensions that need richer state should subscribe\n// to `beforeTurn` (which gives them the full TurnContextSnapshot) and\n// stash references there.\n\n/** Snapshot for the `beforeToolCall` hook. */\ninterface ToolCallStartSnapshot {\n toolName: string;\n toolCallId: string;\n input: unknown;\n stepNumber: number | undefined;\n dynamic?: boolean;\n}\n\n/** Snapshot for the `afterToolCall` hook. */\ninterface ToolCallFinishSnapshot {\n toolName: string;\n toolCallId: string;\n input: unknown;\n stepNumber: number | undefined;\n durationMs: number;\n success: boolean;\n output?: unknown;\n /** Normalized error: `{ name, message, stack }` for Error instances, otherwise `String(error)`. */\n error?: unknown;\n dynamic?: boolean;\n}\n\n/** Snapshot for the `onStepFinish` hook. */\ninterface StepFinishSnapshot {\n stepNumber: number;\n finishReason: string;\n text: string;\n reasoningText: string | undefined;\n toolCallCount: number;\n toolResultCount: number;\n usage:\n | {\n inputTokens: number | undefined;\n outputTokens: number | undefined;\n totalTokens: number | undefined;\n reasoningTokens: number | undefined;\n cachedInputTokens: number | undefined;\n }\n | undefined;\n /** Provider-specific metadata (e.g. Anthropic cache accounting). */\n providerMetadata: Record<string, unknown> | undefined;\n}\n\n/** Snapshot for the `onChunk` hook. High-frequency — keep minimal. */\ninterface ChunkSnapshot {\n type: string;\n text?: string;\n toolName?: string;\n toolCallId?: string;\n}\n\nexport function createToolCallStartSnapshot(event: {\n toolCall: {\n toolName: string;\n toolCallId: string;\n input?: unknown;\n dynamic?: boolean;\n };\n stepNumber: number | undefined;\n}): ToolCallStartSnapshot {\n return {\n toolName: event.toolCall.toolName,\n toolCallId: event.toolCall.toolCallId,\n input: jsonSafe(event.toolCall.input),\n stepNumber: event.stepNumber,\n ...(event.toolCall.dynamic !== undefined\n ? { dynamic: event.toolCall.dynamic }\n : {})\n };\n}\n\nexport function createToolCallFinishSnapshot(event: {\n toolCall: {\n toolName: string;\n toolCallId: string;\n input?: unknown;\n dynamic?: boolean;\n };\n stepNumber: number | undefined;\n durationMs: number;\n success: boolean;\n output?: unknown;\n error?: unknown;\n}): ToolCallFinishSnapshot {\n return {\n toolName: event.toolCall.toolName,\n toolCallId: event.toolCall.toolCallId,\n input: jsonSafe(event.toolCall.input),\n stepNumber: event.stepNumber,\n durationMs: event.durationMs,\n success: event.success,\n ...(event.success\n ? { output: jsonSafe(event.output) }\n : { error: jsonSafe(event.error) }),\n ...(event.toolCall.dynamic !== undefined\n ? { dynamic: event.toolCall.dynamic }\n : {})\n };\n}\n\nexport function createStepFinishSnapshot(event: {\n stepNumber: number;\n finishReason: string;\n text: string;\n reasoningText: string | undefined;\n toolCalls: ReadonlyArray<unknown>;\n toolResults: ReadonlyArray<unknown>;\n usage?: {\n inputTokens?: number;\n outputTokens?: number;\n totalTokens?: number;\n reasoningTokens?: number;\n cachedInputTokens?: number;\n };\n providerMetadata?: Record<string, unknown>;\n}): StepFinishSnapshot {\n return {\n stepNumber: event.stepNumber,\n finishReason: event.finishReason,\n text: event.text,\n reasoningText: event.reasoningText,\n toolCallCount: event.toolCalls.length,\n toolResultCount: event.toolResults.length,\n usage: event.usage\n ? {\n inputTokens: event.usage.inputTokens,\n outputTokens: event.usage.outputTokens,\n totalTokens: event.usage.totalTokens,\n reasoningTokens:\n (\n event.usage as {\n outputTokenDetails?: { reasoningTokens?: number };\n reasoningTokens?: number;\n }\n ).outputTokenDetails?.reasoningTokens ??\n (event.usage as { reasoningTokens?: number }).reasoningTokens,\n cachedInputTokens:\n (\n event.usage as {\n inputTokenDetails?: { cacheReadTokens?: number };\n cachedInputTokens?: number;\n }\n ).inputTokenDetails?.cacheReadTokens ??\n (event.usage as { cachedInputTokens?: number }).cachedInputTokens\n }\n : undefined,\n providerMetadata: event.providerMetadata as\n | Record<string, unknown>\n | undefined\n };\n}\n\nexport function createChunkSnapshot(event: {\n chunk: { type: string; [key: string]: unknown };\n}): ChunkSnapshot {\n const c = event.chunk;\n const snapshot: ChunkSnapshot = { type: c.type };\n // text-delta / reasoning-delta carry `text`\n if (typeof c.text === \"string\") snapshot.text = c.text;\n // tool-related chunks carry tool identifiers\n if (typeof c.toolName === \"string\") snapshot.toolName = c.toolName;\n if (typeof c.toolCallId === \"string\") snapshot.toolCallId = c.toolCallId;\n return snapshot;\n}\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\ntype TurnSnapshot = ReturnType<typeof createTurnContextSnapshot>;\n\n/**\n * The released hooks, with the snapshot each extension is sent. Only the\n * snapshot crosses to the extension; `beforeTurn`'s `config` is the fold's\n * starting point and stays here.\n *\n * @internal\n */\nexport type ReleasedHooks = {\n beforeTurn: [{ snapshot: TurnSnapshot; config: TurnConfig }, TurnConfig];\n beforeToolCall: [unknown, void];\n afterToolCall: [unknown, void];\n onStepFinish: [unknown, void];\n onChunk: [unknown, void];\n};\n\n/** @internal */\nexport type ReleasedHookName = keyof ReleasedHooks;\n\n/**\n * `TurnConfig` fields an extension's `beforeTurn` may set, last write wins.\n * `model` and `tools` are not among them: a sandboxed extension cannot send a\n * `LanguageModel` or an AI SDK tool over RPC. It uses `activeTools` instead.\n */\nconst EXTENSION_SCALAR_CONFIG_KEYS = [\n \"system\",\n \"messages\",\n \"activeTools\",\n \"toolChoice\",\n \"maxSteps\",\n \"sendReasoning\",\n \"maxOutputTokens\",\n \"temperature\",\n \"topP\",\n \"topK\",\n \"presencePenalty\",\n \"frequencyPenalty\",\n \"stopSequences\",\n \"seed\",\n \"maxRetries\",\n \"timeout\"\n] as const satisfies ReadonlyArray<keyof TurnConfig>;\n\nasync function guarded<C, R>(\n hook: ReleasedHookName,\n handler: HookHandler<C, R>,\n context: C,\n timeoutMs: number\n): Promise<R | undefined> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n handler(context),\n new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(`Hook timeout: ${handler.extension}`)),\n timeoutMs\n );\n })\n ]);\n } catch (error) {\n console.warn(\n `[Think] Extension \"${handler.extension}\" ${hook} failed:`,\n error instanceof Error ? error.message : error\n );\n return undefined;\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n\n/**\n * How the released hooks combine, with `timeoutMs` per call.\n *\n * @internal\n */\nexport function releasedHookRules(\n timeoutMs: () => number\n): HookRules<ReleasedHooks> {\n const observeEach =\n (hook: ReleasedHookName) =>\n async (\n context: unknown,\n handlers: readonly HookHandler<unknown, void>[]\n ): Promise<void> => {\n for (const handler of handlers) {\n await guarded(hook, handler, context, timeoutMs());\n }\n };\n return {\n async beforeTurn({ snapshot: first, config }, handlers) {\n if (handlers.length === 0) return config;\n let snapshot = first;\n const accumulated: TurnConfig = { ...config };\n for (const handler of handlers) {\n const changes = await guarded(\n \"beforeTurn\",\n handler,\n { snapshot, config: accumulated },\n timeoutMs()\n );\n if (!changes) continue;\n const writable = accumulated as Record<string, unknown>;\n for (const key of EXTENSION_SCALAR_CONFIG_KEYS) {\n const value = changes[key];\n if (value !== undefined) writable[key] = value;\n }\n if (changes.headers !== undefined) {\n accumulated.headers = {\n ...(accumulated.headers ?? {}),\n ...changes.headers\n };\n }\n if (changes.providerOptions !== undefined) {\n accumulated.providerOptions = {\n ...(accumulated.providerOptions ?? {}),\n ...changes.providerOptions\n };\n }\n // The next extension sees this one's changes.\n if (accumulated.system !== undefined) {\n snapshot = { ...snapshot, system: accumulated.system };\n }\n if (accumulated.activeTools !== undefined) {\n snapshot = { ...snapshot, toolNames: accumulated.activeTools };\n }\n }\n return accumulated;\n },\n beforeToolCall: observeEach(\"beforeToolCall\"),\n afterToolCall: observeEach(\"afterToolCall\"),\n onStepFinish: observeEach(\"onStepFinish\"),\n onChunk: observeEach(\"onChunk\")\n };\n}\n\n/**\n * Wrap a released extension source (`({ tools: {...}, hooks: {...} })`,\n * both optional) as the extension function the runtime runs: each tool\n * set as `<prefix>_<name>` with its JSON Schema, each hook subscribed.\n * A tool's `execute` and a hook get `(input, host)`, `host` being\n * `env.host` or null.\n */\nexport function wrapExtensionSource(source: string, name: string): string {\n const prefix = JSON.stringify(sanitizeName(name));\n return `import { env } 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 || {};\nconst __name = ${JSON.stringify(name)};\nconst __host = () => env.host ?? null;\n\nexport default (ctx) => {\n ctx.tools.transform((tools) => {\n for (const [tool, def] of Object.entries(__tools)) {\n tools.set(${prefix} + \"_\" + tool, {\n description: \"[\" + __name + \"] \" + (def.description || tool),\n inputSchema: {\n type: \"object\",\n properties: def.parameters || {},\n required: def.required || []\n },\n execute: async (args) => {\n if (!def.execute) throw new Error(\"Unknown tool: \" + tool);\n return def.execute(args, __host());\n }\n });\n }\n });\n for (const [hook, fn] of Object.entries(__hooks)) {\n ctx.on(hook, async (snapshot) => {\n const result = await fn(snapshot, __host());\n return hook === \"beforeTurn\" ? (result ?? {}) : undefined;\n });\n }\n};\n`;\n}\n","/**\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 * Each loaded Worker is an extension handle of the extension core\n * (`agents/internal`), which builds the tools and runs the hooks.\n *\n * Extension source format — a JS object expression with `tools` and\n * `hooks`:\n *\n * ```js\n * ({\n * tools: {\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 *\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 */\nimport type { ToolSet } from \"ai\";\nimport {\n ExtensionManager as ExtensionCore,\n loadInWorker,\n toolsOf,\n type ToolEntry,\n type WorkerExtensionHandle\n} from \"agents/internal\";\nimport {\n releasedHookRules,\n sanitizeName,\n wrapExtensionSource,\n type ReleasedHooks\n} from \"./released\";\nimport type {\n ExtensionManifest,\n ExtensionPermissions,\n ExtensionInfo\n} from \"./types\";\n\nexport { sanitizeName };\n\ninterface LoadedExtension {\n manifest: ExtensionManifest;\n handle: WorkerExtensionHandle<ReleasedHooks>;\n /** Its tools, as it built them at load: a released extension's are fixed. */\n entries: readonly (readonly [string, ToolEntry])[];\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 * Identifies the agent that `createHostBinding` binds to (for example\n * `${className}:${ctx.id}`). It is part of the Dynamic Worker id of\n * extensions that receive `env.host`, so a cached worker is never shared\n * with another agent. Without it, such extensions get a fresh id per\n * manager instance.\n */\n workerIdScope?: string;\n}\n\n/** Host binding factories whose bindings are `HostBridgeLoopback`s. */\nconst GATEWAYS = new WeakSet<object>();\n\n/**\n * Mark `createHostBinding` as making `HostBridgeLoopback` bindings, which\n * also enforce an extension's network hosts.\n *\n * @internal\n */\nexport function asNetworkGateway<F extends object>(createHostBinding: F): F {\n GATEWAYS.add(createHostBinding);\n return createHostBinding;\n}\n\nconst DEFAULT_HOOK_TIMEOUT_MS = 5000;\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 #workerIdScope: string;\n #extensions = new Map<string, LoadedExtension>();\n readonly #core: ExtensionCore<ReleasedHooks>;\n #restored = false;\n #warnedContextType = false;\n #warnedNetwork = 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 this.#workerIdScope = options.workerIdScope ?? crypto.randomUUID();\n this.#core = new ExtensionCore(\n releasedHookRules(() => this.#hookTimeoutMs())\n );\n }\n\n #hookTimeoutMs: () => number = () => DEFAULT_HOOK_TIMEOUT_MS;\n\n /**\n * @internal The extension core these extensions run on, with the agent's\n * hook timeout per call from now on.\n */\n coreFor(timeoutMs: () => number): ExtensionCore<ReleasedHooks> {\n this.#hookTimeoutMs = timeoutMs;\n return this.#core;\n }\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 /**\n * Load an extension from source code.\n *\n * The source is a JS object expression with `tools` and `hooks`. Each\n * tool has `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 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 if (\n !this.#warnedContextType &&\n manifest.context?.some((block) => block.type !== undefined)\n ) {\n this.#warnedContextType = true;\n console.warn(\n `[Think] Extension \"${manifest.name}\": a context block's \\`type\\` is ignored. An extension writes its blocks with host.setContext(), which its context.write permission governs.`\n );\n }\n const workerModule = wrapExtensionSource(source, manifest.name);\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 prefix = sanitizeName(manifest.name);\n const ownLabels = (manifest.context ?? []).map(\n (c) => `${prefix}_${c.label}`\n );\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 // The listed hosts are enforced by HostBridgeLoopback's `fetch`, which\n // the Worker's fetch() goes through. Only a binding Think created is\n // known to be one; an app's own `createHostBinding` may serve the host\n // operations alone, so its Worker keeps the agent's network, as does\n // one with no binding at all.\n const needsNetwork = (permissions.network?.length ?? 0) > 0;\n const gateway =\n needsNetwork &&\n this.#createHostBinding !== null &&\n GATEWAYS.has(this.#createHostBinding);\n const binding =\n this.#createHostBinding && (needsHost || gateway)\n ? this.#createHostBinding(permissions, ownLabels)\n : undefined;\n if (binding && needsHost) workerEnv.host = binding;\n\n // No network unless it lists hosts: through the gateway that enforces\n // them, else (with a warning) the agent's own.\n let network: Fetcher | \"inherit\" | undefined;\n if (needsNetwork) {\n network = gateway && binding ? binding : \"inherit\";\n if (!gateway && !this.#warnedNetwork) {\n this.#warnedNetwork = true;\n console.warn(\n `[Think] Extension \"${manifest.name}\": its network hosts are not enforced, so it can reach any host. They are enforced only through the host binding Think creates when the Worker entry re-exports HostBridgeLoopback.`\n );\n }\n }\n\n // A cached Worker keeps the env and network it was created with, so an\n // id whose Worker carries the host binding also covers the agent and the\n // context labels that binding was made for.\n const worker = await loadInWorker<ReleasedHooks>(this.#loader, {\n name: manifest.name,\n module: workerModule,\n ...(Object.keys(workerEnv).length > 0 && { env: workerEnv }),\n ...(network !== undefined && { network }),\n scope: {\n version: manifest.version,\n permissions,\n ...(binding && {\n hostScope: this.#workerIdScope,\n ownContextLabels: ownLabels\n })\n },\n // A released extension's tools are fixed when it loads.\n buildOnce: true,\n // A released tool gets its arguments and the host, never the\n // transcript.\n withoutTranscript: true\n });\n const handle = releasedHandle(worker);\n const entries = (await handle.build(NO_DRAFTS, { session: \"\" })).tools;\n this.#core.load(manifest.name, Promise.resolve(handle));\n this.#extensions.set(manifest.name, { manifest, handle, entries });\n\n return toExtensionInfo(manifest, entries);\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 this.#core.unload(name);\n ext.handle.unload();\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 * Removed: Think calls each loaded extension's hooks itself, on every\n * turn. Throws an error that says so; delete the call.\n */\n getHookSubscribers(_hookName: string): never {\n throw new Error(\n \"ExtensionManager.getHookSubscribers() was removed: Think calls each loaded extension's hooks itself on every turn, so delete the call and the code that called the hooks it returned.\"\n );\n }\n\n /**\n * List all loaded extensions.\n */\n list(): ExtensionInfo[] {\n return [...this.#extensions.values()].map((ext) =>\n toExtensionInfo(ext.manifest, ext.entries)\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 loaded = [...this.#extensions.values()];\n // Each released extension offers the tools it described at load, so\n // the build is the extensions' entries in load order.\n return toolsOf<ReleasedHooks>(\n loaded.flatMap(({ entries }) => entries),\n new Map(loaded.map(({ manifest, handle }) => [manifest.name, handle])),\n \"\"\n );\n }\n}\n\nconst NO_DRAFTS = { tools: [], prompt: [] };\n\n/**\n * A released extension's Worker as the core reaches it: `beforeTurn` sends\n * only the snapshot (the config it folds stays here; it holds a model that\n * can't cross), and nothing asks it for approval.\n *\n * @internal\n */\nexport function releasedHandle(\n worker: WorkerExtensionHandle<ReleasedHooks>\n): WorkerExtensionHandle<ReleasedHooks> {\n return {\n ...worker,\n needsApproval: async () => false,\n hook: async (name, context) =>\n worker.hook(\n name,\n // SAFETY: the Worker's `beforeTurn` handler takes the snapshot.\n (name === \"beforeTurn\"\n ? (context as ReleasedHooks[\"beforeTurn\"][0]).snapshot\n : context) as never\n )\n };\n}\n\nfunction toExtensionInfo(\n manifest: ExtensionManifest,\n entries: readonly (readonly [string, ToolEntry])[]\n): ExtensionInfo {\n const prefix = sanitizeName(manifest.name);\n return {\n name: manifest.name,\n version: manifest.version,\n description: manifest.description,\n tools: entries.map(([name]) => name),\n contextLabels: (manifest.context ?? []).map((c) => `${prefix}_${c.label}`),\n permissions: manifest.permissions ?? {}\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAkBA,SAAS,SAAS,OAAgB,QAAQ,GAAY;CACpD,IAAI,QAAQ,GAAG,OAAO,KAAA;CACtB,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;CAClD,MAAM,IAAI,OAAO;CACjB,IAAI,MAAM,YAAY,MAAM,YAAY,MAAM,WAAW,OAAO;CAChE,IAAI,MAAM,UAAU,OAAO,OAAO,KAAK;CACvC,IAAI,MAAM,cAAc,MAAM,UAAU,OAAO,KAAA;CAC/C,IAAI,iBAAiB,OACnB,OAAO;EAAE,MAAM,MAAM;EAAM,SAAS,MAAM;EAAS,OAAO,MAAM;CAAM;CAExE,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,MAAM,KAAK,MAAM,SAAS,GAAG,QAAQ,CAAC,CAAC;CACxE,IAAI,MAAM,UAAU;EAClB,MAAM,MAA+B,CAAC;EACtC,KAAK,MAAM,CAAC,GAAG,MAAM,OAAO,QAAQ,KAAgC,GAAG;GAErE,IAAI,aAAa,aAAa;GAC9B,MAAM,OAAO,SAAS,GAAG,QAAQ,CAAC;GAClC,IAAI,SAAS,KAAA,GAAW,IAAI,KAAK;EACnC;EACA,OAAO;CACT;CACA,IAAI;EACF,OAAO,OAAO,KAAK;CACrB,QAAQ;EACN;CACF;AACF;;;;;;;AAwBA,SA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