@cloudflare/think 0.24.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.
- package/README.md +18 -26
- package/dist/{chat-sdk-BEjKXjCm.js → chat-sdk-4Nu96eDX.js} +375 -256
- package/dist/chat-sdk-4Nu96eDX.js.map +1 -0
- package/dist/extensions/index.d.ts +30 -72
- package/dist/extensions/index.js +45 -47
- package/dist/extensions/index.js.map +1 -1
- package/dist/{fetch-DO3uQ9py.js → fetch-BbYxtlff.js} +10 -2
- package/dist/fetch-BbYxtlff.js.map +1 -0
- package/dist/manager-B3rcb_6p.js +493 -0
- package/dist/manager-B3rcb_6p.js.map +1 -0
- package/dist/manager-CWGumyKi.d.ts +3391 -0
- package/dist/messengers/index.d.ts +54 -66
- package/dist/messengers/index.js +2 -2
- package/dist/messengers/telegram.d.ts +4 -4
- package/dist/messengers/telegram.js +1 -1
- package/dist/think.d.ts +2 -2
- package/dist/think.js +8493 -10759
- package/dist/think.js.map +1 -1
- package/dist/tools/extensions.d.ts +1 -1
- package/dist/tools/extensions.js +1 -1
- package/dist/tools/fetch.js +1 -1
- package/dist/workflows.d.ts +5 -2
- package/docs/actions.md +12 -0
- package/docs/channels.md +10 -4
- package/docs/client-tools.md +57 -27
- package/docs/context.md +92 -0
- package/docs/getting-started.md +2 -2
- package/docs/index.md +109 -49
- package/docs/lifecycle-hooks.md +10 -21
- package/docs/multi-chat.md +5 -5
- package/docs/programmatic-submissions.md +28 -10
- package/docs/sub-agents.md +45 -51
- package/docs/tools.md +31 -3
- package/docs/workflows.md +4 -3
- package/package.json +13 -8
- package/dist/chat-sdk-BEjKXjCm.js.map +0 -1
- package/dist/fetch-DO3uQ9py.js.map +0 -1
- package/dist/hook-proxy-DY2sBNa0.js +0 -117
- package/dist/hook-proxy-DY2sBNa0.js.map +0 -1
- package/dist/index-DIQ9oY1t.d.ts +0 -5864
- package/dist/manager-CtXhU1fK.d.ts +0 -243
- package/dist/manager-sfWIcYJT.js +0 -333
- package/dist/manager-sfWIcYJT.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fetch-BbYxtlff.js","names":[],"sources":["../src/workspace-files.ts","../src/tools/fetch.ts"],"sourcesContent":["import type { Workspace } from \"@cloudflare/computer\";\nimport type { CreateAIToolsOptions } from \"@cloudflare/computer/tools/ai-sdk\";\n\n/**\n * The filesystem methods Think uses, from `@cloudflare/computer`'s\n * `workspace.fs`.\n */\nexport type ThinkWorkspaceFilesystem = Pick<\n Workspace[\"fs\"],\n | \"readFile\"\n | \"writeFile\"\n | \"mkdir\"\n | \"rm\"\n | \"stat\"\n | \"readdir\"\n | \"find\"\n | \"grep\"\n>;\n\n/** The parts of a Workspace the `@cloudflare/computer` tools use besides `fs`. */\ntype ToolsWorkspace = CreateAIToolsOptions[\"workspace\"];\n\n/**\n * The Workspace a Think agent works in.\n *\n * A `Workspace` from `@cloudflare/computer` satisfies this, and so does the\n * client `getWorkspace(stub)` returns for a Workspace owned by another\n * Durable Object. Think reads and writes through `workspace.fs`. The\n * `@cloudflare/computer` tools also use `runtime` for `exec` and `assets`\n * for `publish` when the Workspace has them.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport type ThinkWorkspace = {\n /** The Workspace filesystem. */\n readonly fs: ThinkWorkspaceFilesystem;\n} & Partial<Pick<ToolsWorkspace, \"runtime\" | \"sessionId\" | \"assets\">>;\n\n/** One file, directory, or symlink in a Workspace. */\ntype WorkspaceEntry = {\n /** Absolute path. */\n readonly path: string;\n /** Last path segment. */\n readonly name: string;\n /** Entry kind. */\n readonly type: \"file\" | \"directory\" | \"symlink\";\n /** Size in bytes. `0` for directories. */\n readonly size: number;\n /** Last modification time in milliseconds since the epoch. */\n readonly updatedAt: number;\n};\n\n/** Directory Computer's backends and tools treat as the working root. */\nexport const WORKSPACE_ROOT = \"/workspace\";\n\n/**\n * Resolve a path against {@link WORKSPACE_ROOT}. Absolute paths pass\n * through; relative ones, such as an extension's `notes/today.md`, land\n * under `/workspace`.\n *\n * @param path - Absolute or root-relative path.\n * @returns An absolute path.\n */\nexport function resolveWorkspacePath(path: string): string {\n if (path.startsWith(\"/\")) return path;\n const relative = path.replace(/^\\.\\//, \"\");\n return relative === \"\" || relative === \".\"\n ? WORKSPACE_ROOT\n : `${WORKSPACE_ROOT}/${relative}`;\n}\n\nconst TEXT_ENCODER = new TextEncoder();\nconst TEXT_DECODER = new TextDecoder();\n\n/**\n * Think's file operations over a {@link ThinkWorkspace}.\n *\n * Translates the Workspace's node-style filesystem into the shape Think's\n * internals use: missing files read as `null` instead of rejecting with\n * `ENOENT`, writes create their parent directories, and listings return\n * {@link WorkspaceEntry} values.\n *\n * @internal\n */\nexport class WorkspaceFiles {\n readonly #fs: ThinkWorkspaceFilesystem;\n\n /**\n * @param workspace - The Workspace to operate on.\n */\n constructor(workspace: ThinkWorkspace) {\n this.#fs = workspace.fs;\n }\n\n /**\n * Read a file as UTF-8 text.\n *\n * @param path - Absolute file path.\n * @returns The text, or `null` when the file does not exist.\n */\n async readText(path: string): Promise<string | null> {\n const bytes = await this.readBytes(path);\n return bytes === null ? null : TEXT_DECODER.decode(bytes);\n }\n\n /**\n * Read a file's bytes.\n *\n * @param path - Absolute file path.\n * @returns The bytes, or `null` when the file does not exist.\n */\n async readBytes(path: string): Promise<Uint8Array | null> {\n try {\n return await drain(await this.#fs.readFile(path));\n } catch (error) {\n if (isNotFound(error)) return null;\n throw error;\n }\n }\n\n /**\n * Write a file, creating missing parent directories.\n *\n * @param path - Absolute file path.\n * @param content - Text, written as UTF-8, or bytes.\n */\n async write(path: string, content: string | Uint8Array): Promise<void> {\n const parent = parentDirectory(path);\n if (parent !== \"/\") await this.#fs.mkdir(parent, { recursive: true });\n await this.#fs.writeFile(\n path,\n typeof content === \"string\" ? TEXT_ENCODER.encode(content) : content\n );\n }\n\n /**\n * Remove a file or directory.\n *\n * @param path - Absolute path.\n * @param options - `recursive` removes a non-empty directory; `force`\n * accepts a missing path.\n */\n async remove(\n path: string,\n options?: { recursive?: boolean; force?: boolean }\n ): Promise<void> {\n await this.#fs.rm(path, options);\n }\n\n /**\n * List a directory's entries in name order.\n *\n * @param path - Absolute directory path.\n * @param options - Page size and start.\n * @returns The entries on the requested page.\n */\n async list(\n path: string,\n options?: { limit?: number; offset?: number }\n ): Promise<WorkspaceEntry[]> {\n const entries = await this.#fs.readdir(path, options);\n return entries.map((entry) => ({\n path: joinPath(path, entry.name),\n name: entry.name,\n type: entry.isDirectory\n ? \"directory\"\n : entry.isSymbolicLink\n ? \"symlink\"\n : \"file\",\n size: entry.size,\n updatedAt: entry.mtime\n }));\n }\n}\n\nasync function drain(stream: ReadableStream<Uint8Array>): Promise<Uint8Array> {\n const parts: Uint8Array[] = [];\n let total = 0;\n for await (const part of stream) {\n parts.push(part);\n total += part.byteLength;\n }\n if (parts.length === 1 && parts[0]) return parts[0];\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const part of parts) {\n bytes.set(part, offset);\n offset += part.byteLength;\n }\n return bytes;\n}\n\nfunction isNotFound(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n error.code === \"ENOENT\"\n );\n}\n\nfunction parentDirectory(path: string): string {\n const index = path.lastIndexOf(\"/\");\n return index <= 0 ? \"/\" : path.slice(0, index);\n}\n\nfunction joinPath(directory: string, name: string): string {\n return directory.endsWith(\"/\")\n ? `${directory}${name}`\n : `${directory}/${name}`;\n}\n\n/**\n * Whether a workspace is a Computer `Workspace` this agent owns, as opposed\n * to a client for one another Durable Object owns. Checked by shape so a\n * second copy of `@cloudflare/computer` in the bundle still matches.\n */\nexport function isLocalWorkspace(\n workspace: ThinkWorkspace\n): workspace is ThinkWorkspace & Pick<Workspace, \"ready\" | \"stub\"> {\n return (\n \"ready\" in workspace &&\n typeof workspace.ready === \"function\" &&\n \"stub\" in workspace &&\n typeof workspace.stub === \"function\"\n );\n}\n","import type { JSONValue, ToolSet } from \"ai\";\nimport { tool } from \"ai\";\nimport { isPrivateOrLocalHost } from \"agents/webfetch\";\nimport { z } from \"zod\";\nimport { WorkspaceFiles, type ThinkWorkspace } from \"../workspace-files\";\n\n// ── Public types ──────────────────────────────────────────────────\n//\n// A conservative, opt-in HTTP read capability for Think agents. It is\n// deliberately read-only (GET), allowlisted, and bounded. It is NOT a\n// general-purpose HTTP client and NOT an SSRF primitive — mutations and\n// rendered-page automation live elsewhere (explicit actions, Browser Run).\n//\n// @experimental The API surface may change before stabilizing.\n\nexport type FetchResponseMode = \"text\" | \"json\" | \"auto\" | \"workspace\";\nexport type FetchRedirectPolicy = \"allowlisted\" | \"same-origin\" | \"none\";\n\nexport type FetchErrorCode =\n | \"disallowed_url\"\n | \"disallowed_redirect\"\n | \"timeout\"\n | \"aborted\"\n | \"non_2xx\"\n | \"unsupported_content_type\"\n | \"invalid_json\"\n | \"too_large\"\n | \"request_failed\";\n\nexport type FetchResult =\n | {\n ok: true;\n status: number;\n finalUrl: string;\n contentType: string;\n bytes: number;\n truncated: boolean;\n response: \"text\" | \"json\" | \"workspace\";\n body?: string;\n json?: JSONValue;\n path?: string;\n }\n | {\n ok: false;\n code: FetchErrorCode;\n status?: number;\n finalUrl?: string;\n message: string;\n };\n\nexport interface FetchToolEvent {\n tool: string;\n ok: boolean;\n requestedUrl: string;\n finalUrl?: string;\n status?: number;\n bytes?: number;\n truncated?: boolean;\n response?: FetchResponseMode;\n code?: FetchErrorCode;\n}\n\nexport interface FetchBindingTarget {\n /** The service binding / Fetcher requests are routed through. */\n binding: Fetcher;\n /** Documented purpose — surfaced in the generated tool description. */\n description?: string;\n /**\n * Allowlist for this target. Entries starting with `/` match the request\n * pathname (e.g. `/v1/docs/**`); entries starting with `http(s)://` match\n * the full canonical URL.\n */\n allowlist: string[];\n /** Fixed, server-side headers. Never settable by the model, never echoed. */\n headers?: Record<string, string>;\n /** Base URL used to resolve relative paths. Defaults to `https://binding.local`. */\n baseUrl?: string;\n}\n\nexport interface CreateFetchToolsOptions {\n /**\n * Allowlist for the generic public `fetch_url` tool. Entries are absolute\n * URL/origin/path globs (e.g. `https://developers.cloudflare.com/**`). When\n * omitted/empty, `fetch_url` is not registered.\n */\n allowlist?: string[];\n /**\n * Named binding targets. Each entry generates a `fetch_<name>` tool with the\n * binding, allowlist, and fixed headers baked in.\n */\n bindings?: Record<string, FetchBindingTarget>;\n /** Hard download cap in bytes. Default 1_000_000. */\n maxBytes?: number;\n /** Model-facing text truncation in characters. Default 24_000. */\n maxModelChars?: number;\n /** Allow large/binary bodies to spill to a workspace file. Default false. */\n spillToWorkspace?: boolean;\n /** Workspace used for `response: \"workspace\"` / spill. */\n workspace?: ThinkWorkspace;\n /** Per-request timeout in ms. Default 10_000. */\n timeoutMs?: number;\n /** Default response handling. Default `\"auto\"`. */\n response?: FetchResponseMode;\n /** Redirect policy. Default `\"allowlisted\"`. */\n followRedirects?: FetchRedirectPolicy;\n /** Header names the model may set. Default `[\"accept\", \"accept-language\", \"range\"]`. */\n modelHeaderAllowlist?: string[];\n /**\n * Default `Accept` header sent when neither the binding's fixed headers nor\n * the model already set one. Defaults to a markdown-first, weighted value so\n * content-negotiating endpoints return clean markdown/plain text/JSON instead\n * of HTML. Set to `\"\"` to send no default `Accept` header.\n */\n defaultAccept?: string;\n /** Observability hook. Fires once per fetch (success or failure/block). */\n onEvent?: (event: FetchToolEvent) => void;\n}\n\nconst DEFAULT_MAX_BYTES = 1_000_000;\nconst DEFAULT_MAX_MODEL_CHARS = 24_000;\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MODEL_HEADER_ALLOWLIST = [\"accept\", \"accept-language\", \"range\"];\n// Markdown-first, but still accepts everything (`*/*;q=0.1`) so a strict\n// content-negotiating server never answers 406.\nconst DEFAULT_ACCEPT =\n \"text/markdown, text/plain;q=0.9, application/json;q=0.8, text/html;q=0.5, */*;q=0.1\";\nconst MAX_REDIRECTS = 5;\n\ninterface ResolvedConfig {\n maxBytes: number;\n maxModelChars: number;\n spillToWorkspace: boolean;\n workspace?: ThinkWorkspace;\n timeoutMs: number;\n response: FetchResponseMode;\n followRedirects: FetchRedirectPolicy;\n modelHeaderAllowlist: Set<string>;\n defaultAccept: string;\n onEvent?: (event: FetchToolEvent) => void;\n}\n\ninterface CompiledPattern {\n scope: \"path\" | \"url\";\n re: RegExp;\n}\n\ninterface ResolvedTarget {\n kind: \"public\" | \"binding\";\n binding?: Fetcher;\n allowlist: CompiledPattern[];\n fixedHeaders: Record<string, string>;\n baseUrl: string;\n}\n\n/**\n * Create the Think fetch tools.\n *\n * Returns a generic `fetch_url` tool (when a public `allowlist` is configured)\n * plus one `fetch_<name>` tool per configured binding target. Throws when no\n * allowlist and no bindings are configured, so a misconfiguration fails loudly\n * instead of silently registering nothing.\n *\n * @example\n * ```ts\n * createFetchTools({\n * allowlist: [\"https://developers.cloudflare.com/**\"],\n * bindings: {\n * docsApi: { binding: env.DOCS_API, allowlist: [\"/v1/docs/**\"] }\n * }\n * });\n * ```\n */\nexport function createFetchTools(options: CreateFetchToolsOptions): ToolSet {\n const publicAllowlist = (options.allowlist ?? []).filter(\n (entry) => entry.length > 0\n );\n const bindings = options.bindings ?? {};\n const bindingNames = Object.keys(bindings);\n\n if (publicAllowlist.length === 0 && bindingNames.length === 0) {\n throw new Error(\n \"createFetchTools requires a non-empty `allowlist` or at least one `bindings` target.\"\n );\n }\n\n const config: ResolvedConfig = {\n maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES,\n maxModelChars: options.maxModelChars ?? DEFAULT_MAX_MODEL_CHARS,\n spillToWorkspace: options.spillToWorkspace ?? false,\n workspace: options.workspace,\n timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n response: options.response ?? \"auto\",\n followRedirects: options.followRedirects ?? \"allowlisted\",\n modelHeaderAllowlist: new Set(\n (options.modelHeaderAllowlist ?? DEFAULT_MODEL_HEADER_ALLOWLIST).map(\n (name) => name.toLowerCase()\n )\n ),\n defaultAccept: options.defaultAccept ?? DEFAULT_ACCEPT,\n onEvent: options.onEvent\n };\n\n const tools: ToolSet = {};\n\n if (publicAllowlist.length > 0) {\n const target: ResolvedTarget = {\n kind: \"public\",\n allowlist: publicAllowlist.map(compilePattern),\n fixedHeaders: {},\n baseUrl: \"\"\n };\n tools.fetch_url = tool({\n description:\n \"Fetch an allowlisted public URL over HTTP(S) (read-only GET). \" +\n \"Returns the response body as text or JSON, or spills large/binary \" +\n \"bodies to a workspace file. The URL must be on the configured \" +\n \"allowlist; disallowed or private-network URLs are rejected.\",\n inputSchema: z.object({\n url: z\n .string()\n .describe(\"Absolute http(s) URL to fetch. Must be allowlisted.\"),\n response: responseModeSchema,\n headers: headersSchema\n }),\n execute: (input: FetchUrlInput, opts) =>\n runFetch({\n toolName: \"fetch_url\",\n target,\n config,\n requested: input.url,\n responseOverride: input.response,\n modelHeaders: input.headers,\n abortSignal: opts?.abortSignal\n }),\n toModelOutput: ({ output }) => toModelOutput(output as FetchResult)\n });\n }\n\n for (const name of bindingNames) {\n const def = bindings[name];\n const toolName = `fetch_${sanitizeName(name)}`;\n const target: ResolvedTarget = {\n kind: \"binding\",\n binding: def.binding,\n allowlist: def.allowlist.map(compilePattern),\n fixedHeaders: def.headers ?? {},\n baseUrl: def.baseUrl ?? \"https://binding.local\"\n };\n const purpose = def.description ? ` ${def.description}` : \"\";\n tools[toolName] = tool({\n description:\n `Fetch a read-only resource from the \"${name}\" service binding.${purpose} ` +\n \"Provide a path (or an allowlisted absolute URL). Requests are routed \" +\n \"through the configured binding with fixed server-side headers.\",\n inputSchema: z.object({\n path: z\n .string()\n .describe(\n \"Path (e.g. /v1/docs/search) or an allowlisted absolute URL.\"\n ),\n response: responseModeSchema,\n headers: headersSchema\n }),\n execute: (input: FetchBindingInput, opts) =>\n runFetch({\n toolName,\n target,\n config,\n requested: input.path,\n responseOverride: input.response,\n modelHeaders: input.headers,\n abortSignal: opts?.abortSignal\n }),\n toModelOutput: ({ output }) => toModelOutput(output as FetchResult)\n });\n }\n\n return tools;\n}\n\nconst responseModeSchema = z\n .enum([\"text\", \"json\", \"auto\", \"workspace\"])\n .optional()\n .describe(\n \"How to handle the response body. Defaults to the configured mode.\"\n );\n\nconst headersSchema = z\n .record(z.string(), z.string())\n .optional()\n .describe(\"Optional request headers; only safe read headers are honored.\");\n\ninterface FetchUrlInput {\n url: string;\n response?: FetchResponseMode;\n headers?: Record<string, string>;\n}\n\ninterface FetchBindingInput {\n path: string;\n response?: FetchResponseMode;\n headers?: Record<string, string>;\n}\n\ninterface RunFetchArgs {\n toolName: string;\n target: ResolvedTarget;\n config: ResolvedConfig;\n requested: string;\n responseOverride?: FetchResponseMode;\n modelHeaders?: Record<string, string>;\n abortSignal?: AbortSignal;\n}\n\nasync function runFetch(args: RunFetchArgs): Promise<FetchResult> {\n const { toolName, config, requested } = args;\n const result = await runFetchInner(args);\n if (config.onEvent) {\n try {\n config.onEvent(\n result.ok\n ? {\n tool: toolName,\n ok: true,\n requestedUrl: requested,\n finalUrl: result.finalUrl,\n status: result.status,\n bytes: result.bytes,\n truncated: result.truncated,\n response: result.response\n }\n : {\n tool: toolName,\n ok: false,\n requestedUrl: requested,\n finalUrl: result.finalUrl,\n status: result.status,\n code: result.code\n }\n );\n } catch {\n // Observability must never break a tool call.\n }\n }\n return result;\n}\n\nasync function runFetchInner(args: RunFetchArgs): Promise<FetchResult> {\n const { target, config, requested, responseOverride, modelHeaders } = args;\n\n // Resolve the requested string into an absolute URL.\n const rawUrl =\n target.kind === \"binding\" && !/^https?:\\/\\//i.test(requested)\n ? resolveAgainstBase(requested, target.baseUrl)\n : requested;\n if (rawUrl === null) {\n return { ok: false, code: \"disallowed_url\", message: \"Invalid path.\" };\n }\n\n const normalized = normalizeRequestUrl(rawUrl);\n if (\"error\" in normalized) {\n return { ok: false, code: \"disallowed_url\", message: normalized.error };\n }\n const url = normalized.url;\n\n if (target.kind === \"public\" && isPrivateOrLocalHost(url.hostname)) {\n return {\n ok: false,\n code: \"disallowed_url\",\n message: `Refusing to fetch a private or local address: ${url.hostname}`\n };\n }\n\n if (!matchesAllowlist(url, target.allowlist)) {\n return {\n ok: false,\n code: \"disallowed_url\",\n message: `URL is not on the allowlist: ${url.toString()}`\n };\n }\n\n const responseMode = responseOverride ?? config.response;\n const safeModelHeaders = filterModelHeaders(\n modelHeaders,\n config.modelHeaderAllowlist\n );\n\n return executeRequest({\n target,\n config,\n initialUrl: url,\n responseMode,\n fixedHeaders: target.fixedHeaders,\n modelHeaders: safeModelHeaders,\n abortSignal: args.abortSignal\n });\n}\n\ninterface ExecuteRequestArgs {\n target: ResolvedTarget;\n config: ResolvedConfig;\n initialUrl: URL;\n responseMode: FetchResponseMode;\n fixedHeaders: Record<string, string>;\n modelHeaders: Record<string, string>;\n abortSignal?: AbortSignal;\n}\n\nasync function executeRequest(args: ExecuteRequestArgs): Promise<FetchResult> {\n const { target, config, initialUrl, responseMode } = args;\n const method = \"GET\";\n\n const controller = new AbortController();\n const onAbort = () => controller.abort();\n if (args.abortSignal) {\n if (args.abortSignal.aborted) controller.abort();\n else args.abortSignal.addEventListener(\"abort\", onAbort, { once: true });\n }\n const timer = setTimeout(() => controller.abort(), config.timeoutMs);\n\n const initialOrigin = initialUrl.origin;\n let currentUrl = initialUrl;\n let headers: Record<string, string> = applyDefaultAccept(\n mergeHeaders(args.fixedHeaders, args.modelHeaders),\n config.defaultAccept\n );\n\n try {\n for (let hop = 0; ; hop++) {\n if (hop > MAX_REDIRECTS) {\n return {\n ok: false,\n code: \"request_failed\",\n finalUrl: currentUrl.toString(),\n message: \"Too many redirects.\"\n };\n }\n\n const res = await doFetch(\n target,\n currentUrl,\n method,\n headers,\n controller.signal\n );\n\n if (isRedirect(res.status)) {\n const location = res.headers.get(\"location\");\n if (location) {\n const redirectOutcome = resolveRedirect({\n target,\n config,\n location,\n currentUrl,\n initialOrigin\n });\n if (\"error\" in redirectOutcome) {\n discardBody(res);\n return {\n ok: false,\n code: \"disallowed_redirect\",\n status: res.status,\n finalUrl: currentUrl.toString(),\n message: redirectOutcome.error\n };\n }\n // We're following the redirect; drop the 3xx body before the next hop.\n discardBody(res);\n // Strip credentials/headers on cross-origin hops, but keep a safe\n // default Accept so the next hop still negotiates for clean content.\n if (redirectOutcome.url.origin !== currentUrl.origin) {\n headers = applyDefaultAccept({}, config.defaultAccept);\n }\n currentUrl = redirectOutcome.url;\n continue;\n }\n }\n\n if (res.status < 200 || res.status >= 300) {\n discardBody(res);\n return {\n ok: false,\n code: \"non_2xx\",\n status: res.status,\n finalUrl: currentUrl.toString(),\n message: `HTTP ${res.status}`\n };\n }\n\n return finalizeResponse({\n res,\n config,\n responseMode,\n finalUrl: currentUrl.toString()\n });\n }\n } catch (error) {\n if (controller.signal.aborted) {\n const aborted = args.abortSignal?.aborted ?? false;\n return {\n ok: false,\n code: aborted ? \"aborted\" : \"timeout\",\n finalUrl: currentUrl.toString(),\n message: aborted ? \"Request aborted.\" : \"Request timed out.\"\n };\n }\n return {\n ok: false,\n code: \"request_failed\",\n finalUrl: currentUrl.toString(),\n message: errorMessage(error)\n };\n } finally {\n clearTimeout(timer);\n args.abortSignal?.removeEventListener(\"abort\", onAbort);\n }\n}\n\n/**\n * Cancel a response body we won't read (non-2xx, blocked/followed redirects)\n * so the underlying connection isn't left dangling.\n */\nfunction discardBody(res: Response): void {\n res.body?.cancel().catch(() => {});\n}\n\nfunction doFetch(\n target: ResolvedTarget,\n url: URL,\n method: string,\n headers: Record<string, string>,\n signal: AbortSignal\n): Promise<Response> {\n const init: RequestInit = {\n method,\n headers,\n redirect: \"manual\",\n signal\n };\n if (target.kind === \"binding\" && target.binding) {\n return target.binding.fetch(url.toString(), init);\n }\n return fetch(url.toString(), init);\n}\n\ninterface ResolveRedirectArgs {\n target: ResolvedTarget;\n config: ResolvedConfig;\n location: string;\n currentUrl: URL;\n initialOrigin: string;\n}\n\nfunction resolveRedirect(\n args: ResolveRedirectArgs\n): { url: URL } | { error: string } {\n const { target, config, location, currentUrl, initialOrigin } = args;\n if (config.followRedirects === \"none\") {\n return { error: \"Redirects are disabled.\" };\n }\n\n let next: URL;\n try {\n next = new URL(location, currentUrl);\n } catch {\n return { error: \"Invalid redirect target.\" };\n }\n if (next.protocol !== \"http:\" && next.protocol !== \"https:\") {\n return { error: \"Redirect to a non-http(s) URL is not allowed.\" };\n }\n if (next.username || next.password) {\n return { error: \"Redirect to a URL with credentials is not allowed.\" };\n }\n\n // Bindings are a transport, not a generic client: never redirect off-origin.\n if (target.kind === \"binding\" && next.origin !== currentUrl.origin) {\n return { error: \"Cross-origin redirects are not allowed for bindings.\" };\n }\n\n if (target.kind === \"public\" && isPrivateOrLocalHost(next.hostname)) {\n return {\n error: `Redirect to a private or local address: ${next.hostname}`\n };\n }\n\n if (config.followRedirects === \"same-origin\") {\n if (next.origin !== initialOrigin) {\n return { error: \"Redirect escaped the original origin.\" };\n }\n } else if (config.followRedirects === \"allowlisted\") {\n if (!matchesAllowlist(next, target.allowlist)) {\n return { error: \"Redirect target is not on the allowlist.\" };\n }\n }\n\n return { url: next };\n}\n\ninterface FinalizeArgs {\n res: Response;\n config: ResolvedConfig;\n responseMode: FetchResponseMode;\n finalUrl: string;\n}\n\nasync function finalizeResponse(args: FinalizeArgs): Promise<FetchResult> {\n const { res, config, responseMode, finalUrl } = args;\n const contentType = (res.headers.get(\"content-type\") ?? \"\")\n .split(\";\")[0]\n .trim()\n .toLowerCase();\n\n const { bytes, capped } = await readCapped(res, config.maxBytes);\n const mode = resolveResponseMode(responseMode, contentType, config);\n\n // An empty body (204, HEAD-like, or a content-less 2xx) is a successful\n // empty-text read, not an unsupported content type.\n if (bytes.byteLength === 0 && mode !== \"workspace\") {\n return {\n ok: true,\n status: res.status,\n finalUrl,\n contentType,\n bytes: 0,\n truncated: false,\n response: \"text\",\n body: \"\"\n };\n }\n\n if (mode === \"unsupported\") {\n return {\n ok: false,\n code: \"unsupported_content_type\",\n finalUrl,\n message: `Unsupported content type: ${contentType || \"unknown\"}. Use response: \"workspace\" to store it.`\n };\n }\n\n if (mode === \"workspace\") {\n return spillToWorkspace({\n bytes,\n capped,\n contentType,\n finalUrl,\n status: res.status,\n config\n });\n }\n\n const text = new TextDecoder().decode(bytes);\n\n if (mode === \"json\") {\n if (capped) {\n return {\n ok: false,\n code: \"too_large\",\n finalUrl,\n message: `Response exceeded the ${config.maxBytes} byte cap and cannot be parsed as JSON. Use response: \"workspace\".`\n };\n }\n try {\n const json = JSON.parse(text) as JSONValue;\n return {\n ok: true,\n status: res.status,\n finalUrl,\n contentType,\n bytes: bytes.byteLength,\n truncated: false,\n response: \"json\",\n json\n };\n } catch {\n return {\n ok: false,\n code: \"invalid_json\",\n finalUrl,\n message: \"Response body is not valid JSON.\"\n };\n }\n }\n\n const { value, truncated: textTruncated } = truncateText(\n text,\n config.maxModelChars\n );\n return {\n ok: true,\n status: res.status,\n finalUrl,\n contentType,\n bytes: bytes.byteLength,\n truncated: capped || textTruncated,\n response: \"text\",\n body: value\n };\n}\n\ninterface SpillArgs {\n bytes: Uint8Array;\n capped: boolean;\n contentType: string;\n finalUrl: string;\n status: number;\n config: ResolvedConfig;\n}\n\nasync function spillToWorkspace(args: SpillArgs): Promise<FetchResult> {\n const { bytes, capped, contentType, finalUrl, status, config } = args;\n const ws = config.workspace;\n if (!ws) {\n return {\n ok: false,\n code: \"unsupported_content_type\",\n finalUrl,\n message:\n 'response: \"workspace\" requires a workspace, but none is configured.'\n };\n }\n\n const path = `/workspace/fetched/${Date.now()}-${randomToken()}.${extensionFor(contentType)}`;\n try {\n await new WorkspaceFiles(ws).write(path, bytes);\n } catch (error) {\n return {\n ok: false,\n code: \"request_failed\",\n finalUrl,\n message: `Failed to write workspace file: ${errorMessage(error)}`\n };\n }\n\n return {\n ok: true,\n status,\n finalUrl,\n contentType,\n bytes: bytes.byteLength,\n truncated: capped,\n response: \"workspace\",\n path\n };\n}\n\nasync function readCapped(\n res: Response,\n maxBytes: number\n): Promise<{ bytes: Uint8Array; capped: boolean }> {\n const body = res.body;\n if (!body) return { bytes: new Uint8Array(0), capped: false };\n\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n let capped = false;\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (!value) continue;\n if (total + value.byteLength > maxBytes) {\n const remaining = Math.max(0, maxBytes - total);\n if (remaining > 0) chunks.push(value.slice(0, remaining));\n total += remaining;\n capped = true;\n await reader.cancel().catch(() => {});\n break;\n }\n chunks.push(value);\n total += value.byteLength;\n }\n\n const out = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n out.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return { bytes: out, capped };\n}\n\ntype ResolvedResponseMode = \"text\" | \"json\" | \"workspace\" | \"unsupported\";\n\nfunction resolveResponseMode(\n mode: FetchResponseMode,\n contentType: string,\n config: ResolvedConfig\n): ResolvedResponseMode {\n if (mode === \"text\") return \"text\";\n if (mode === \"json\") return \"json\";\n if (mode === \"workspace\") return \"workspace\";\n\n // auto\n if (isJsonContentType(contentType)) return \"json\";\n if (isTextualContentType(contentType)) return \"text\";\n if (config.spillToWorkspace && config.workspace) return \"workspace\";\n return \"unsupported\";\n}\n\n// ── Allowlist + URL helpers ───────────────────────────────────────\n\nfunction normalizeRequestUrl(raw: string): { url: URL } | { error: string } {\n let url: URL;\n try {\n url = new URL(raw);\n } catch {\n return { error: \"Invalid URL.\" };\n }\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n return { error: \"Only http(s) URLs are allowed.\" };\n }\n if (url.username || url.password) {\n return { error: \"URLs with embedded credentials are not allowed.\" };\n }\n return { url };\n}\n\nfunction resolveAgainstBase(pathOrUrl: string, baseUrl: string): string | null {\n try {\n return new URL(pathOrUrl, baseUrl).toString();\n } catch {\n return null;\n }\n}\n\n/**\n * A bare origin (`https://example.com`, no path) is treated as the origin and\n * everything under it, since the canonical URL always has at least a `/` path.\n * Patterns with an explicit path are matched literally unless they include\n * globs.\n */\nfunction normalizeAllowlistPattern(pattern: string): string {\n if (/^https?:\\/\\/[^/]+$/i.test(pattern)) return `${pattern}/**`;\n return pattern;\n}\n\n/**\n * Compile an allowlist pattern once at config time so we don't rebuild a\n * `RegExp` on every request. Path-only patterns (`/v1/**`) match against the\n * URL pathname; everything else matches against the canonical origin+path.\n */\nfunction compilePattern(pattern: string): CompiledPattern {\n const normalized = normalizeAllowlistPattern(pattern);\n return {\n scope: normalized.startsWith(\"/\") ? \"path\" : \"url\",\n re: globToRegExp(normalized)\n };\n}\n\nfunction canonicalForMatch(url: URL): string {\n const host = url.hostname.replace(/\\.$/, \"\");\n const port = url.port ? `:${url.port}` : \"\";\n return `${url.protocol}//${host}${port}${url.pathname}`;\n}\n\nfunction matchesAllowlist(url: URL, patterns: CompiledPattern[]): boolean {\n const canonical = canonicalForMatch(url);\n for (const pattern of patterns) {\n const subject = pattern.scope === \"path\" ? url.pathname : canonical;\n if (pattern.re.test(subject)) return true;\n }\n return false;\n}\n\nfunction globToRegExp(glob: string): RegExp {\n let re = \"\";\n for (let i = 0; i < glob.length; i++) {\n const c = glob[i];\n if (c === \"*\") {\n if (glob[i + 1] === \"*\") {\n re += \".*\";\n i++;\n } else {\n re += \"[^/]*\";\n }\n } else if (\"\\\\^$.|?+()[]{}\".includes(c)) {\n re += `\\\\${c}`;\n } else {\n re += c;\n }\n }\n return new RegExp(`^${re}$`);\n}\n\n/**\n * Merge fixed (server-side) and model headers into a lowercased-key map. Fixed\n * headers win, so the model can never override a binding's configured header,\n * and case-only duplicates (`Accept` vs `accept`) can't both be sent.\n */\nfunction mergeHeaders(\n fixed: Record<string, string>,\n model: Record<string, string>\n): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [name, value] of Object.entries(model)) {\n out[name.toLowerCase()] = value;\n }\n for (const [name, value] of Object.entries(fixed)) {\n out[name.toLowerCase()] = value;\n }\n return out;\n}\n\nfunction applyDefaultAccept(\n headers: Record<string, string>,\n defaultAccept: string\n): Record<string, string> {\n if (!defaultAccept) return headers;\n const hasAccept = Object.keys(headers).some(\n (name) => name.toLowerCase() === \"accept\"\n );\n if (hasAccept) return headers;\n return { ...headers, accept: defaultAccept };\n}\n\nfunction filterModelHeaders(\n headers: Record<string, string> | undefined,\n allowlist: Set<string>\n): Record<string, string> {\n if (!headers) return {};\n const out: Record<string, string> = {};\n for (const [name, value] of Object.entries(headers)) {\n if (allowlist.has(name.toLowerCase())) out[name] = value;\n }\n return out;\n}\n\n// ── Content-type helpers ──────────────────────────────────────────\n\nfunction isJsonContentType(contentType: string): boolean {\n return (\n contentType === \"application/json\" ||\n contentType.endsWith(\"+json\") ||\n contentType === \"text/json\"\n );\n}\n\nfunction isTextualContentType(contentType: string): boolean {\n if (contentType.length === 0) return false;\n if (contentType.startsWith(\"text/\")) return true;\n if (isJsonContentType(contentType)) return true;\n return (\n contentType === \"application/xml\" ||\n contentType === \"application/javascript\" ||\n contentType === \"application/x-www-form-urlencoded\"\n );\n}\n\nfunction extensionFor(contentType: string): string {\n if (isJsonContentType(contentType)) return \"json\";\n if (contentType === \"text/html\") return \"html\";\n if (contentType.includes(\"xml\")) return \"xml\";\n if (contentType.startsWith(\"text/\")) return \"txt\";\n if (contentType === \"application/pdf\") return \"pdf\";\n if (contentType.startsWith(\"image/\")) {\n return contentType.slice(\"image/\".length).split(\"+\")[0] || \"img\";\n }\n return \"bin\";\n}\n\nfunction truncateText(\n value: string,\n maxChars: number\n): { value: string; truncated: boolean } {\n if (value.length <= maxChars) return { value, truncated: false };\n return {\n value: `${value.slice(0, maxChars)}\\n... (truncated ${value.length - maxChars} chars)`,\n truncated: true\n };\n}\n\nfunction isRedirect(status: number): boolean {\n return (\n status === 301 ||\n status === 302 ||\n status === 303 ||\n status === 307 ||\n status === 308\n );\n}\n\nfunction sanitizeName(name: string): string {\n return name.replace(/[^a-zA-Z0-9_]/g, \"_\");\n}\n\nfunction randomToken(): string {\n return Math.random().toString(36).slice(2, 10);\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n// ── Model output mapping ──────────────────────────────────────────\n\nfunction toModelOutput(\n output: FetchResult\n):\n | { type: \"text\"; value: string }\n | { type: \"error-text\"; value: string }\n | { type: \"json\"; value: JSONValue } {\n if (!output.ok) {\n return { type: \"error-text\", value: output.message };\n }\n if (output.response === \"json\") {\n return {\n type: \"json\",\n value: {\n status: output.status,\n finalUrl: output.finalUrl,\n contentType: output.contentType,\n json: output.json ?? null\n }\n };\n }\n if (output.response === \"workspace\") {\n return {\n type: \"text\",\n value:\n `Fetched ${output.finalUrl} (${output.contentType || \"unknown\"}, ` +\n `${output.bytes} bytes${output.truncated ? \", truncated\" : \"\"}) ` +\n `and saved to ${output.path}.`\n };\n }\n const prefix = `Fetched ${output.finalUrl} (HTTP ${output.status}, ${output.contentType || \"unknown\"}${output.truncated ? \", truncated\" : \"\"}):\\n\\n`;\n return { type: \"text\", value: prefix + (output.body ?? \"\") };\n}\n"],"mappings":";;;;;;AAqDA,MAAa,iBAAiB;;;;;;;;;AAU9B,SAAgB,qBAAqB,MAAsB;CACzD,IAAI,KAAK,WAAW,GAAG,GAAG,OAAO;CACjC,MAAM,WAAW,KAAK,QAAQ,SAAS,EAAE;CACzC,OAAO,aAAa,MAAM,aAAa,MACnC,iBACA,GAAG,eAAe,GAAG;AAC3B;AAEA,MAAM,eAAe,IAAI,YAAY;AACrC,MAAM,eAAe,IAAI,YAAY;;;;;;;;;;;;AAYrC,IAAa,iBAAb,MAA4B;;;;CAM1B,YAAY,WAA2B;;EACrC,uBAAA,KAAA,MAAW,UAAU,EAAA;CACvB;;;;;;;CAQA,MAAM,SAAS,MAAsC;EACnD,MAAM,QAAQ,MAAM,KAAK,UAAU,IAAI;EACvC,OAAO,UAAU,OAAO,OAAO,aAAa,OAAO,KAAK;CAC1D;;;;;;;CAQA,MAAM,UAAU,MAA0C;EACxD,IAAI;GACF,OAAO,MAAM,MAAM,MAAA,uBAAA,KAAM,IAAA,CAAA,CAAS,SAAS,IAAI,CAAC;EAClD,SAAS,OAAO;GACd,IAAI,WAAW,KAAK,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X,WAAW,OACX,WAAW;AAEf;AAEA,SAAS,aAAa,MAAsB;CAC1C,OAAO,KAAK,QAAQ,kBAAkB,GAAG;AAC3C;AAEA,SAAS,cAAsB;CAC7B,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,GAAG,EAAE;AAC/C;AAEA,SAAS,aAAa,OAAwB;CAC5C,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;AAIA,SAAS,cACP,QAIqC;CACrC,IAAI,CAAC,OAAO,IACV,OAAO;EAAE,MAAM;EAAc,OAAO,OAAO;CAAQ;CAErD,IAAI,OAAO,aAAa,QACtB,OAAO;EACL,MAAM;EACN,OAAO;GACL,QAAQ,OAAO;GACf,UAAU,OAAO;GACjB,aAAa,OAAO;GACpB,MAAM,OAAO,QAAQ;EACvB;CACF;CAEF,IAAI,OAAO,aAAa,aACtB,OAAO;EACL,MAAM;EACN,OACE,WAAW,OAAO,SAAS,IAAI,OAAO,eAAe,UAAU,IAC5D,OAAO,MAAM,QAAQ,OAAO,YAAY,gBAAgB,GAAG,iBAC9C,OAAO,KAAK;CAChC;CAGF,OAAO;EAAE,MAAM;EAAQ,OAAO,WADJ,OAAO,SAAS,SAAS,OAAO,OAAO,IAAI,OAAO,eAAe,YAAY,OAAO,YAAY,gBAAgB,GAAG,WACrG,OAAO,QAAQ;CAAI;AAC7D"}
|
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
import { a as _checkPrivateRedeclaration, i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, r as _assertClassBrand, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-DwGJfC3w.js";
|
|
2
|
+
import { ExtensionManager, loadInWorker, toolsOf } from "agents/internal";
|
|
3
|
+
//#region \0@oxc-project+runtime@0.137.0/helpers/esm/classPrivateMethodInitSpec.js
|
|
4
|
+
function _classPrivateMethodInitSpec(e, a) {
|
|
5
|
+
_checkPrivateRedeclaration(e, a), a.add(e);
|
|
6
|
+
}
|
|
7
|
+
//#endregion
|
|
8
|
+
//#region src/extensions/released.ts
|
|
9
|
+
/**
|
|
10
|
+
* Best-effort JSON-safe normalization. Strips functions, AbortSignals,
|
|
11
|
+
* symbols, and replaces `Error` instances with `{ name, message, stack }`.
|
|
12
|
+
* Falls back to `String(value)` for anything that won't round-trip.
|
|
13
|
+
*/
|
|
14
|
+
function jsonSafe(value, depth = 0) {
|
|
15
|
+
if (depth > 6) return void 0;
|
|
16
|
+
if (value === null || value === void 0) return value;
|
|
17
|
+
const t = typeof value;
|
|
18
|
+
if (t === "string" || t === "number" || t === "boolean") return value;
|
|
19
|
+
if (t === "bigint") return String(value);
|
|
20
|
+
if (t === "function" || t === "symbol") return void 0;
|
|
21
|
+
if (value instanceof Error) return {
|
|
22
|
+
name: value.name,
|
|
23
|
+
message: value.message,
|
|
24
|
+
stack: value.stack
|
|
25
|
+
};
|
|
26
|
+
if (Array.isArray(value)) return value.map((v) => jsonSafe(v, depth + 1));
|
|
27
|
+
if (t === "object") {
|
|
28
|
+
const out = {};
|
|
29
|
+
for (const [k, v] of Object.entries(value)) {
|
|
30
|
+
if (v instanceof AbortSignal) continue;
|
|
31
|
+
const safe = jsonSafe(v, depth + 1);
|
|
32
|
+
if (safe !== void 0) out[k] = safe;
|
|
33
|
+
}
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
try {
|
|
37
|
+
return String(value);
|
|
38
|
+
} catch {
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Create a serializable snapshot from a TurnContext.
|
|
44
|
+
*
|
|
45
|
+
* Pass `model` when `beforeTurn` already overrode it: `ctx.model` lazily
|
|
46
|
+
* resolves the default model, which may need an AI binding the turn never uses.
|
|
47
|
+
*/
|
|
48
|
+
function createTurnContextSnapshot(ctx, model = ctx.model) {
|
|
49
|
+
return {
|
|
50
|
+
system: ctx.system,
|
|
51
|
+
toolNames: Object.keys(ctx.tools),
|
|
52
|
+
messageCount: ctx.messages.length,
|
|
53
|
+
continuation: ctx.continuation,
|
|
54
|
+
body: ctx.body,
|
|
55
|
+
modelId: typeof model === "string" ? model : model.modelId ?? "unknown",
|
|
56
|
+
...ctx.requestId !== void 0 && { requestId: ctx.requestId },
|
|
57
|
+
...ctx.trigger !== void 0 && { trigger: ctx.trigger }
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
function createToolCallStartSnapshot(event) {
|
|
61
|
+
return {
|
|
62
|
+
toolName: event.toolCall.toolName,
|
|
63
|
+
toolCallId: event.toolCall.toolCallId,
|
|
64
|
+
input: jsonSafe(event.toolCall.input),
|
|
65
|
+
stepNumber: event.stepNumber,
|
|
66
|
+
...event.toolCall.dynamic !== void 0 ? { dynamic: event.toolCall.dynamic } : {}
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
function createToolCallFinishSnapshot(event) {
|
|
70
|
+
return {
|
|
71
|
+
toolName: event.toolCall.toolName,
|
|
72
|
+
toolCallId: event.toolCall.toolCallId,
|
|
73
|
+
input: jsonSafe(event.toolCall.input),
|
|
74
|
+
stepNumber: event.stepNumber,
|
|
75
|
+
durationMs: event.durationMs,
|
|
76
|
+
success: event.success,
|
|
77
|
+
...event.success ? { output: jsonSafe(event.output) } : { error: jsonSafe(event.error) },
|
|
78
|
+
...event.toolCall.dynamic !== void 0 ? { dynamic: event.toolCall.dynamic } : {}
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
function createStepFinishSnapshot(event) {
|
|
82
|
+
return {
|
|
83
|
+
stepNumber: event.stepNumber,
|
|
84
|
+
finishReason: event.finishReason,
|
|
85
|
+
text: event.text,
|
|
86
|
+
reasoningText: event.reasoningText,
|
|
87
|
+
toolCallCount: event.toolCalls.length,
|
|
88
|
+
toolResultCount: event.toolResults.length,
|
|
89
|
+
usage: event.usage ? {
|
|
90
|
+
inputTokens: event.usage.inputTokens,
|
|
91
|
+
outputTokens: event.usage.outputTokens,
|
|
92
|
+
totalTokens: event.usage.totalTokens,
|
|
93
|
+
reasoningTokens: event.usage.outputTokenDetails?.reasoningTokens ?? event.usage.reasoningTokens,
|
|
94
|
+
cachedInputTokens: event.usage.inputTokenDetails?.cacheReadTokens ?? event.usage.cachedInputTokens
|
|
95
|
+
} : void 0,
|
|
96
|
+
providerMetadata: event.providerMetadata
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
function createChunkSnapshot(event) {
|
|
100
|
+
const c = event.chunk;
|
|
101
|
+
const snapshot = { type: c.type };
|
|
102
|
+
if (typeof c.text === "string") snapshot.text = c.text;
|
|
103
|
+
if (typeof c.toolName === "string") snapshot.toolName = c.toolName;
|
|
104
|
+
if (typeof c.toolCallId === "string") snapshot.toolCallId = c.toolCallId;
|
|
105
|
+
return snapshot;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Sanitize a name for use as a tool name prefix.
|
|
109
|
+
* Replaces any non-alphanumeric characters with underscores and
|
|
110
|
+
* collapses consecutive underscores.
|
|
111
|
+
*/
|
|
112
|
+
function sanitizeName(name) {
|
|
113
|
+
if (!name || name.trim().length === 0) throw new Error("Extension name must not be empty");
|
|
114
|
+
return name.replace(/[^a-zA-Z0-9]/g, "_").replace(/_+/g, "_").replace(/^_|_$/g, "");
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* `TurnConfig` fields an extension's `beforeTurn` may set, last write wins.
|
|
118
|
+
* `model` and `tools` are not among them: a sandboxed extension cannot send a
|
|
119
|
+
* `LanguageModel` or an AI SDK tool over RPC. It uses `activeTools` instead.
|
|
120
|
+
*/
|
|
121
|
+
const EXTENSION_SCALAR_CONFIG_KEYS = [
|
|
122
|
+
"system",
|
|
123
|
+
"messages",
|
|
124
|
+
"activeTools",
|
|
125
|
+
"toolChoice",
|
|
126
|
+
"maxSteps",
|
|
127
|
+
"sendReasoning",
|
|
128
|
+
"maxOutputTokens",
|
|
129
|
+
"temperature",
|
|
130
|
+
"topP",
|
|
131
|
+
"topK",
|
|
132
|
+
"presencePenalty",
|
|
133
|
+
"frequencyPenalty",
|
|
134
|
+
"stopSequences",
|
|
135
|
+
"seed",
|
|
136
|
+
"maxRetries",
|
|
137
|
+
"timeout"
|
|
138
|
+
];
|
|
139
|
+
async function guarded(hook, handler, context, timeoutMs) {
|
|
140
|
+
let timer;
|
|
141
|
+
try {
|
|
142
|
+
return await Promise.race([handler(context), new Promise((_, reject) => {
|
|
143
|
+
timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`Hook timeout: ${handler.extension}`)), timeoutMs);
|
|
144
|
+
})]);
|
|
145
|
+
} catch (error) {
|
|
146
|
+
console.warn(`[Think] Extension "${handler.extension}" ${hook} failed:`, error instanceof Error ? error.message : error);
|
|
147
|
+
return;
|
|
148
|
+
} finally {
|
|
149
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* How the released hooks combine, with `timeoutMs` per call.
|
|
154
|
+
*
|
|
155
|
+
* @internal
|
|
156
|
+
*/
|
|
157
|
+
function releasedHookRules(timeoutMs) {
|
|
158
|
+
const observeEach = (hook) => async (context, handlers) => {
|
|
159
|
+
for (const handler of handlers) await guarded(hook, handler, context, timeoutMs());
|
|
160
|
+
};
|
|
161
|
+
return {
|
|
162
|
+
async beforeTurn({ snapshot: first, config }, handlers) {
|
|
163
|
+
if (handlers.length === 0) return config;
|
|
164
|
+
let snapshot = first;
|
|
165
|
+
const accumulated = { ...config };
|
|
166
|
+
for (const handler of handlers) {
|
|
167
|
+
const changes = await guarded("beforeTurn", handler, {
|
|
168
|
+
snapshot,
|
|
169
|
+
config: accumulated
|
|
170
|
+
}, timeoutMs());
|
|
171
|
+
if (!changes) continue;
|
|
172
|
+
const writable = accumulated;
|
|
173
|
+
for (const key of EXTENSION_SCALAR_CONFIG_KEYS) {
|
|
174
|
+
const value = changes[key];
|
|
175
|
+
if (value !== void 0) writable[key] = value;
|
|
176
|
+
}
|
|
177
|
+
if (changes.headers !== void 0) accumulated.headers = {
|
|
178
|
+
...accumulated.headers ?? {},
|
|
179
|
+
...changes.headers
|
|
180
|
+
};
|
|
181
|
+
if (changes.providerOptions !== void 0) accumulated.providerOptions = {
|
|
182
|
+
...accumulated.providerOptions ?? {},
|
|
183
|
+
...changes.providerOptions
|
|
184
|
+
};
|
|
185
|
+
if (accumulated.system !== void 0) snapshot = {
|
|
186
|
+
...snapshot,
|
|
187
|
+
system: accumulated.system
|
|
188
|
+
};
|
|
189
|
+
if (accumulated.activeTools !== void 0) snapshot = {
|
|
190
|
+
...snapshot,
|
|
191
|
+
toolNames: accumulated.activeTools
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
return accumulated;
|
|
195
|
+
},
|
|
196
|
+
beforeToolCall: observeEach("beforeToolCall"),
|
|
197
|
+
afterToolCall: observeEach("afterToolCall"),
|
|
198
|
+
onStepFinish: observeEach("onStepFinish"),
|
|
199
|
+
onChunk: observeEach("onChunk")
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Wrap a released extension source (`({ tools: {...}, hooks: {...} })`,
|
|
204
|
+
* both optional) as the extension function the runtime runs: each tool
|
|
205
|
+
* set as `<prefix>_<name>` with its JSON Schema, each hook subscribed.
|
|
206
|
+
* A tool's `execute` and a hook get `(input, host)`, `host` being
|
|
207
|
+
* `env.host` or null.
|
|
208
|
+
*/
|
|
209
|
+
function wrapExtensionSource(source, name) {
|
|
210
|
+
const prefix = JSON.stringify(sanitizeName(name));
|
|
211
|
+
return `import { env } from "cloudflare:workers";
|
|
212
|
+
|
|
213
|
+
const __ext = (${source});
|
|
214
|
+
if (__ext && typeof __ext === "object" && !("tools" in __ext) && !("hooks" in __ext)) {
|
|
215
|
+
throw new Error(
|
|
216
|
+
"Invalid extension source format. Expected { tools: {...}, hooks: {...} } " +
|
|
217
|
+
"but got a flat object. Wrap your tools in a 'tools' key."
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
const __tools = __ext.tools || {};
|
|
221
|
+
const __hooks = __ext.hooks || {};
|
|
222
|
+
const __name = ${JSON.stringify(name)};
|
|
223
|
+
const __host = () => env.host ?? null;
|
|
224
|
+
|
|
225
|
+
export default (ctx) => {
|
|
226
|
+
ctx.tools.transform((tools) => {
|
|
227
|
+
for (const [tool, def] of Object.entries(__tools)) {
|
|
228
|
+
tools.set(${prefix} + "_" + tool, {
|
|
229
|
+
description: "[" + __name + "] " + (def.description || tool),
|
|
230
|
+
inputSchema: {
|
|
231
|
+
type: "object",
|
|
232
|
+
properties: def.parameters || {},
|
|
233
|
+
required: def.required || []
|
|
234
|
+
},
|
|
235
|
+
execute: async (args) => {
|
|
236
|
+
if (!def.execute) throw new Error("Unknown tool: " + tool);
|
|
237
|
+
return def.execute(args, __host());
|
|
238
|
+
}
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
});
|
|
242
|
+
for (const [hook, fn] of Object.entries(__hooks)) {
|
|
243
|
+
ctx.on(hook, async (snapshot) => {
|
|
244
|
+
const result = await fn(snapshot, __host());
|
|
245
|
+
return hook === "beforeTurn" ? (result ?? {}) : undefined;
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
`;
|
|
250
|
+
}
|
|
251
|
+
//#endregion
|
|
252
|
+
//#region src/extensions/manager.ts
|
|
253
|
+
const STORAGE_PREFIX = "ext:";
|
|
254
|
+
/** Host binding factories whose bindings are `HostBridgeLoopback`s. */
|
|
255
|
+
const GATEWAYS = /* @__PURE__ */ new WeakSet();
|
|
256
|
+
/**
|
|
257
|
+
* Mark `createHostBinding` as making `HostBridgeLoopback` bindings, which
|
|
258
|
+
* also enforce an extension's network hosts.
|
|
259
|
+
*
|
|
260
|
+
* @internal
|
|
261
|
+
*/
|
|
262
|
+
function asNetworkGateway(createHostBinding) {
|
|
263
|
+
GATEWAYS.add(createHostBinding);
|
|
264
|
+
return createHostBinding;
|
|
265
|
+
}
|
|
266
|
+
const DEFAULT_HOOK_TIMEOUT_MS = 5e3;
|
|
267
|
+
var _loader = /* @__PURE__ */ new WeakMap();
|
|
268
|
+
var _storage = /* @__PURE__ */ new WeakMap();
|
|
269
|
+
var _createHostBinding = /* @__PURE__ */ new WeakMap();
|
|
270
|
+
var _workerIdScope = /* @__PURE__ */ new WeakMap();
|
|
271
|
+
var _extensions = /* @__PURE__ */ new WeakMap();
|
|
272
|
+
var _core = /* @__PURE__ */ new WeakMap();
|
|
273
|
+
var _restored = /* @__PURE__ */ new WeakMap();
|
|
274
|
+
var _warnedContextType = /* @__PURE__ */ new WeakMap();
|
|
275
|
+
var _warnedNetwork = /* @__PURE__ */ new WeakMap();
|
|
276
|
+
var _onUnload = /* @__PURE__ */ new WeakMap();
|
|
277
|
+
var _hookTimeoutMs = /* @__PURE__ */ new WeakMap();
|
|
278
|
+
var _ExtensionManager_brand = /* @__PURE__ */ new WeakSet();
|
|
279
|
+
var ExtensionManager$1 = class {
|
|
280
|
+
constructor(options) {
|
|
281
|
+
_classPrivateMethodInitSpec(this, _ExtensionManager_brand);
|
|
282
|
+
_classPrivateFieldInitSpec(this, _loader, void 0);
|
|
283
|
+
_classPrivateFieldInitSpec(this, _storage, void 0);
|
|
284
|
+
_classPrivateFieldInitSpec(this, _createHostBinding, void 0);
|
|
285
|
+
_classPrivateFieldInitSpec(this, _workerIdScope, void 0);
|
|
286
|
+
_classPrivateFieldInitSpec(this, _extensions, /* @__PURE__ */ new Map());
|
|
287
|
+
_classPrivateFieldInitSpec(this, _core, void 0);
|
|
288
|
+
_classPrivateFieldInitSpec(this, _restored, false);
|
|
289
|
+
_classPrivateFieldInitSpec(this, _warnedContextType, false);
|
|
290
|
+
_classPrivateFieldInitSpec(this, _warnedNetwork, false);
|
|
291
|
+
_classPrivateFieldInitSpec(this, _onUnload, null);
|
|
292
|
+
_classPrivateFieldInitSpec(this, _hookTimeoutMs, () => DEFAULT_HOOK_TIMEOUT_MS);
|
|
293
|
+
_classPrivateFieldSet2(_loader, this, options.loader);
|
|
294
|
+
_classPrivateFieldSet2(_storage, this, options.storage ?? null);
|
|
295
|
+
_classPrivateFieldSet2(_createHostBinding, this, options.createHostBinding ?? null);
|
|
296
|
+
_classPrivateFieldSet2(_workerIdScope, this, options.workerIdScope ?? crypto.randomUUID());
|
|
297
|
+
_classPrivateFieldSet2(_core, this, new ExtensionManager(releasedHookRules(() => _classPrivateFieldGet2(_hookTimeoutMs, this).call(this))));
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* @internal The extension core these extensions run on, with the agent's
|
|
301
|
+
* hook timeout per call from now on.
|
|
302
|
+
*/
|
|
303
|
+
coreFor(timeoutMs) {
|
|
304
|
+
_classPrivateFieldSet2(_hookTimeoutMs, this, timeoutMs);
|
|
305
|
+
return _classPrivateFieldGet2(_core, this);
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Restore extensions from DO storage after hibernation.
|
|
309
|
+
*
|
|
310
|
+
* Idempotent — skips extensions already in memory. Call this at the
|
|
311
|
+
* start of each chat turn (e.g. in onChatMessage before getTools).
|
|
312
|
+
*/
|
|
313
|
+
async restore() {
|
|
314
|
+
if (_classPrivateFieldGet2(_restored, this) || !_classPrivateFieldGet2(_storage, this)) return;
|
|
315
|
+
_classPrivateFieldSet2(_restored, this, true);
|
|
316
|
+
const entries = await _classPrivateFieldGet2(_storage, this).list({ prefix: STORAGE_PREFIX });
|
|
317
|
+
for (const persisted of entries.values()) {
|
|
318
|
+
if (_classPrivateFieldGet2(_extensions, this).has(persisted.manifest.name)) continue;
|
|
319
|
+
await _assertClassBrand(_ExtensionManager_brand, this, _loadInternal).call(this, persisted.manifest, persisted.source);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Load an extension from source code.
|
|
324
|
+
*
|
|
325
|
+
* The source is a JS object expression with `tools` and `hooks`. Each
|
|
326
|
+
* tool has `description`, `parameters` (JSON Schema properties), optional
|
|
327
|
+
* `required` array, and an `execute` async function.
|
|
328
|
+
*
|
|
329
|
+
* @returns Summary of the loaded extension including discovered tools.
|
|
330
|
+
*/
|
|
331
|
+
async load(manifest, source) {
|
|
332
|
+
if (_classPrivateFieldGet2(_extensions, this).has(manifest.name)) throw new Error(`Extension "${manifest.name}" is already loaded. Unload it first.`);
|
|
333
|
+
const info = await _assertClassBrand(_ExtensionManager_brand, this, _loadInternal).call(this, manifest, source);
|
|
334
|
+
if (_classPrivateFieldGet2(_storage, this)) await _classPrivateFieldGet2(_storage, this).put(`${STORAGE_PREFIX}${manifest.name}`, {
|
|
335
|
+
manifest,
|
|
336
|
+
source
|
|
337
|
+
});
|
|
338
|
+
return info;
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Unload an extension, removing its tools from the agent.
|
|
342
|
+
* If an onUnload callback is registered, it fires with the
|
|
343
|
+
* extension's namespaced context labels so the caller can
|
|
344
|
+
* remove context blocks from the Session.
|
|
345
|
+
*/
|
|
346
|
+
async unload(name) {
|
|
347
|
+
const ext = _classPrivateFieldGet2(_extensions, this).get(name);
|
|
348
|
+
if (!ext) return false;
|
|
349
|
+
const removed = _classPrivateFieldGet2(_extensions, this).delete(name);
|
|
350
|
+
_classPrivateFieldGet2(_core, this).unload(name);
|
|
351
|
+
ext.handle.unload();
|
|
352
|
+
if (removed && _classPrivateFieldGet2(_storage, this)) await _classPrivateFieldGet2(_storage, this).delete(`${STORAGE_PREFIX}${name}`);
|
|
353
|
+
if (removed && _classPrivateFieldGet2(_onUnload, this)) {
|
|
354
|
+
const prefix = sanitizeName(name);
|
|
355
|
+
const contextLabels = (ext.manifest.context ?? []).map((c) => `${prefix}_${c.label}`);
|
|
356
|
+
await _classPrivateFieldGet2(_onUnload, this).call(this, name, contextLabels);
|
|
357
|
+
}
|
|
358
|
+
return removed;
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Register a callback invoked when an extension is unloaded.
|
|
362
|
+
* Think uses this to remove the extension's context blocks from Session.
|
|
363
|
+
*/
|
|
364
|
+
onUnload(cb) {
|
|
365
|
+
_classPrivateFieldSet2(_onUnload, this, cb);
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* Get the namespaced context labels for all loaded extensions
|
|
369
|
+
* that declare context blocks in their manifests.
|
|
370
|
+
*/
|
|
371
|
+
getContextLabels() {
|
|
372
|
+
const result = [];
|
|
373
|
+
for (const ext of _classPrivateFieldGet2(_extensions, this).values()) {
|
|
374
|
+
if (!ext.manifest.context) continue;
|
|
375
|
+
const prefix = sanitizeName(ext.manifest.name);
|
|
376
|
+
for (const ctx of ext.manifest.context) result.push({
|
|
377
|
+
extName: ext.manifest.name,
|
|
378
|
+
label: `${prefix}_${ctx.label}`
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
return result;
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Get extension manifest by name.
|
|
385
|
+
*/
|
|
386
|
+
getManifest(name) {
|
|
387
|
+
return _classPrivateFieldGet2(_extensions, this).get(name)?.manifest ?? null;
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* Removed: Think calls each loaded extension's hooks itself, on every
|
|
391
|
+
* turn. Throws an error that says so; delete the call.
|
|
392
|
+
*/
|
|
393
|
+
getHookSubscribers(_hookName) {
|
|
394
|
+
throw new Error("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.");
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* List all loaded extensions.
|
|
398
|
+
*/
|
|
399
|
+
list() {
|
|
400
|
+
return [..._classPrivateFieldGet2(_extensions, this).values()].map((ext) => toExtensionInfo(ext.manifest, ext.entries));
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* Get AI SDK tools from all loaded extensions.
|
|
404
|
+
*
|
|
405
|
+
* Tool names are prefixed with the sanitized extension name to avoid
|
|
406
|
+
* collisions: e.g. extension "github" with tool "create_pr" → "github_create_pr".
|
|
407
|
+
*/
|
|
408
|
+
getTools() {
|
|
409
|
+
const loaded = [..._classPrivateFieldGet2(_extensions, this).values()];
|
|
410
|
+
return toolsOf(loaded.flatMap(({ entries }) => entries), new Map(loaded.map(({ manifest, handle }) => [manifest.name, handle])), "");
|
|
411
|
+
}
|
|
412
|
+
};
|
|
413
|
+
async function _loadInternal(manifest, source) {
|
|
414
|
+
if (!_classPrivateFieldGet2(_warnedContextType, this) && manifest.context?.some((block) => block.type !== void 0)) {
|
|
415
|
+
_classPrivateFieldSet2(_warnedContextType, this, true);
|
|
416
|
+
console.warn(`[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.`);
|
|
417
|
+
}
|
|
418
|
+
const workerModule = wrapExtensionSource(source, manifest.name);
|
|
419
|
+
const permissions = manifest.permissions ?? {};
|
|
420
|
+
const workerEnv = {};
|
|
421
|
+
const prefix = sanitizeName(manifest.name);
|
|
422
|
+
const ownLabels = (manifest.context ?? []).map((c) => `${prefix}_${c.label}`);
|
|
423
|
+
const needsHost = (permissions.workspace ?? "none") !== "none" || permissions.context?.read !== void 0 || permissions.context?.write !== void 0 || (permissions.messages ?? "none") !== "none" || permissions.session?.sendMessage || permissions.session?.metadata;
|
|
424
|
+
const needsNetwork = (permissions.network?.length ?? 0) > 0;
|
|
425
|
+
const gateway = needsNetwork && _classPrivateFieldGet2(_createHostBinding, this) !== null && GATEWAYS.has(_classPrivateFieldGet2(_createHostBinding, this));
|
|
426
|
+
const binding = _classPrivateFieldGet2(_createHostBinding, this) && (needsHost || gateway) ? _classPrivateFieldGet2(_createHostBinding, this).call(this, permissions, ownLabels) : void 0;
|
|
427
|
+
if (binding && needsHost) workerEnv.host = binding;
|
|
428
|
+
let network;
|
|
429
|
+
if (needsNetwork) {
|
|
430
|
+
network = gateway && binding ? binding : "inherit";
|
|
431
|
+
if (!gateway && !_classPrivateFieldGet2(_warnedNetwork, this)) {
|
|
432
|
+
_classPrivateFieldSet2(_warnedNetwork, this, true);
|
|
433
|
+
console.warn(`[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.`);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
const handle = releasedHandle(await loadInWorker(_classPrivateFieldGet2(_loader, this), {
|
|
437
|
+
name: manifest.name,
|
|
438
|
+
module: workerModule,
|
|
439
|
+
...Object.keys(workerEnv).length > 0 && { env: workerEnv },
|
|
440
|
+
...network !== void 0 && { network },
|
|
441
|
+
scope: {
|
|
442
|
+
version: manifest.version,
|
|
443
|
+
permissions,
|
|
444
|
+
...binding && {
|
|
445
|
+
hostScope: _classPrivateFieldGet2(_workerIdScope, this),
|
|
446
|
+
ownContextLabels: ownLabels
|
|
447
|
+
}
|
|
448
|
+
},
|
|
449
|
+
buildOnce: true,
|
|
450
|
+
withoutTranscript: true
|
|
451
|
+
}));
|
|
452
|
+
const entries = (await handle.build(NO_DRAFTS, { session: "" })).tools;
|
|
453
|
+
_classPrivateFieldGet2(_core, this).load(manifest.name, Promise.resolve(handle));
|
|
454
|
+
_classPrivateFieldGet2(_extensions, this).set(manifest.name, {
|
|
455
|
+
manifest,
|
|
456
|
+
handle,
|
|
457
|
+
entries
|
|
458
|
+
});
|
|
459
|
+
return toExtensionInfo(manifest, entries);
|
|
460
|
+
}
|
|
461
|
+
const NO_DRAFTS = {
|
|
462
|
+
tools: [],
|
|
463
|
+
prompt: []
|
|
464
|
+
};
|
|
465
|
+
/**
|
|
466
|
+
* A released extension's Worker as the core reaches it: `beforeTurn` sends
|
|
467
|
+
* only the snapshot (the config it folds stays here; it holds a model that
|
|
468
|
+
* can't cross), and nothing asks it for approval.
|
|
469
|
+
*
|
|
470
|
+
* @internal
|
|
471
|
+
*/
|
|
472
|
+
function releasedHandle(worker) {
|
|
473
|
+
return {
|
|
474
|
+
...worker,
|
|
475
|
+
needsApproval: async () => false,
|
|
476
|
+
hook: async (name, context) => worker.hook(name, name === "beforeTurn" ? context.snapshot : context)
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
function toExtensionInfo(manifest, entries) {
|
|
480
|
+
const prefix = sanitizeName(manifest.name);
|
|
481
|
+
return {
|
|
482
|
+
name: manifest.name,
|
|
483
|
+
version: manifest.version,
|
|
484
|
+
description: manifest.description,
|
|
485
|
+
tools: entries.map(([name]) => name),
|
|
486
|
+
contextLabels: (manifest.context ?? []).map((c) => `${prefix}_${c.label}`),
|
|
487
|
+
permissions: manifest.permissions ?? {}
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
//#endregion
|
|
491
|
+
export { createToolCallFinishSnapshot as a, sanitizeName as c, createStepFinishSnapshot as i, _classPrivateMethodInitSpec as l, asNetworkGateway as n, createToolCallStartSnapshot as o, createChunkSnapshot as r, createTurnContextSnapshot as s, ExtensionManager$1 as t };
|
|
492
|
+
|
|
493
|
+
//# sourceMappingURL=manager-B3rcb_6p.js.map
|