agents 0.28.0 → 0.29.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/dist/{agent-routing-QDcchcQP.d.ts → agent-routing-CDbpVjYq.d.ts} +18 -8
- package/dist/agent-routing.d.ts +1 -1
- package/dist/agent-tool-types.d.ts +1 -1
- package/dist/{agent-tools-DHL2XI7u.d.ts → agent-tools-C8DH8Yii.d.ts} +2 -2
- package/dist/agent-tools.d.ts +1 -1
- package/dist/{ai-ahruGw7e.d.ts → ai-iXw0uOGj.d.ts} +3 -3
- package/dist/{ai-sdk-Bdsf6mSA.js → ai-sdk-DRPh2rRa.js} +218 -132
- package/dist/ai-sdk-DRPh2rRa.js.map +1 -0
- package/dist/browser/ai.d.ts +1 -1
- package/dist/browser/ai.js +2 -2
- package/dist/browser/index.d.ts +8 -8
- package/dist/browser/index.js +3 -3
- package/dist/browser/tools/ai-sdk.d.ts +2 -2
- package/dist/browser/tools/ai-sdk.js +1 -1
- package/dist/browser/tools/pi.d.ts +1 -1
- package/dist/browser/tools/pi.js +3 -3
- package/dist/browser/tools/pi.js.map +1 -1
- package/dist/browser/tools/tanstack-ai.d.ts +2 -2
- package/dist/browser/tools/tanstack-ai.js +1 -1
- package/dist/{browser-CEdNlsaD.js → browser-DccPw_wW.js} +130 -79
- package/dist/browser-DccPw_wW.js.map +1 -0
- package/dist/{browser-D30VlpcA.d.ts → browser-DlXhSAdf.d.ts} +41 -37
- package/dist/{browser-tool-4iomavs_.js → browser-tool-B1mhifin.js} +3 -3
- package/dist/{browser-tool-4iomavs_.js.map → browser-tool-B1mhifin.js.map} +1 -1
- package/dist/{browser-tool-vtrPOV8e.d.ts → browser-tool-Cxjk5sgG.d.ts} +2 -2
- package/dist/chat/index.d.ts +143 -71
- package/dist/chat/index.js +269 -110
- package/dist/chat/index.js.map +1 -1
- package/dist/chat-sdk/index.d.ts +1 -1
- package/dist/chat-sdk/index.js +1 -1
- package/dist/cli.js +33 -33
- package/dist/{client-BGIQKJhX.d.ts → client-C27CtRZr.d.ts} +2 -2
- package/dist/client.d.ts +1 -1
- package/dist/{connector-DEXzVoaY.d.ts → connector-20DJ6p4k.d.ts} +2 -2
- package/dist/{connector-CtZylXdk.js → connector-DAXBOIIi.js} +2 -2
- package/dist/{connector-CtZylXdk.js.map → connector-DAXBOIIi.js.map} +1 -1
- package/dist/experimental/channels/web/index.js +1 -1
- package/dist/{handler-stateless-VvrWSAVA.js → handler-stateless-Bly_nSH3.js} +12 -3
- package/dist/handler-stateless-Bly_nSH3.js.map +1 -0
- package/dist/harness/container/index.js +1 -1
- package/dist/harness/container/index.js.map +1 -1
- package/dist/harness/opencode/index.d.ts +182 -6
- package/dist/harness/opencode/index.js +354 -23
- package/dist/harness/opencode/index.js.map +1 -1
- package/dist/harness/pi/index.d.ts +13 -5
- package/dist/harness/pi/index.js +8 -214
- package/dist/harness/pi/index.js.map +1 -1
- package/dist/{images-Ce9SCu3X.js → images-xaDv2Fqe.js} +662 -152
- package/dist/images-xaDv2Fqe.js.map +1 -0
- package/dist/index-DCxk3OSJ.d.ts +378 -0
- package/dist/{index-kbSUIer3.d.ts → index-iv9FTXX9.d.ts} +80 -112
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/{input-schema-D2QAtHZH.js → input-schema-B0Etuo-o.js} +2 -2
- package/dist/{input-schema-D2QAtHZH.js.map → input-schema-B0Etuo-o.js.map} +1 -1
- package/dist/lifecycle/index.js +1 -1
- package/dist/{lifecycle-DGorpAmA.js → lifecycle-ClT4DmF2.js} +11 -3
- package/dist/lifecycle-ClT4DmF2.js.map +1 -0
- package/dist/mcp/client/index.d.ts +1 -1
- package/dist/mcp/index.d.ts +1 -1
- package/dist/mcp/index.js +17 -3
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/server/index.js +1 -1
- package/dist/models/ai-sdk/index.d.ts +31 -326
- package/dist/models/ai-sdk/index.js +1 -1
- package/dist/models/opencode/index.d.ts +25 -13
- package/dist/models/opencode/index.js +16 -11
- package/dist/models/opencode/index.js.map +1 -1
- package/dist/models/pi-ai/index.d.ts +17 -13
- package/dist/models/pi-ai/index.js +89 -36
- package/dist/models/pi-ai/index.js.map +1 -1
- package/dist/react.d.ts +2 -2
- package/dist/routing/index.d.ts +1 -1
- package/dist/serializable.d.ts +1 -1
- package/dist/{session-store-DoPY12xM.d.ts → session-store-_IK6dV-w.d.ts} +14 -2
- package/dist/{session-store-Do4xkDcf.js → session-store-yvwq1f9x.js} +55 -2
- package/dist/session-store-yvwq1f9x.js.map +1 -0
- package/dist/{settings-C45hDliX.js → settings-Dk2il2Hf.js} +10 -4
- package/dist/settings-Dk2il2Hf.js.map +1 -0
- package/dist/skills/index.d.ts +22 -28
- package/dist/skills/index.js +183 -143
- package/dist/skills/index.js.map +1 -1
- package/dist/{src-CQxJFv4l.js → src-6lr7MtM_.js} +3 -3
- package/dist/src-6lr7MtM_.js.map +1 -0
- package/dist/sub-routing.d.ts +1 -1
- package/dist/{tool-cQRkwSZZ.js → tool-DkT_DJBm.js} +2 -2
- package/dist/tool-DkT_DJBm.js.map +1 -0
- package/dist/transport-CPh7YGiw.d.ts +623 -0
- package/dist/voice/index.d.ts +1 -1
- package/dist/web/fetch/tools/pi.js +2 -2
- package/dist/web/fetch/tools/pi.js.map +1 -1
- package/dist/web/search/index.js +1 -1
- package/dist/web/search/tools/ai-sdk.js +2 -2
- package/dist/web/search/tools/pi.js +3 -3
- package/dist/web/search/tools/pi.js.map +1 -1
- package/dist/web/search/tools/tanstack-ai.js +2 -2
- package/dist/websockets/index.js +1 -1
- package/dist/{websockets-C3zy8YR0.js → websockets-CqxnntmE.js} +2 -2
- package/dist/{websockets-C3zy8YR0.js.map → websockets-CqxnntmE.js.map} +1 -1
- package/dist/workflow-types.d.ts +1 -1
- package/dist/workflows.d.ts +1 -1
- package/dist/workflows.js +1 -1
- package/docs/browse-the-web.md +1 -1
- package/docs/chat-agents.md +19 -18
- package/docs/harnesses/pi.md +47 -18
- package/docs/mcp-client.md +1 -1
- package/docs/mcp-servers.md +1 -1
- package/docs/models-pi-ai.md +70 -17
- package/docs/models.md +219 -152
- package/package.json +14 -14
- package/dist/ai-sdk-Bdsf6mSA.js.map +0 -1
- package/dist/browser-CEdNlsaD.js.map +0 -1
- package/dist/handler-stateless-VvrWSAVA.js.map +0 -1
- package/dist/images-Ce9SCu3X.js.map +0 -1
- package/dist/lifecycle-DGorpAmA.js.map +0 -1
- package/dist/session-store-Do4xkDcf.js.map +0 -1
- package/dist/settings-C45hDliX.js.map +0 -1
- package/dist/settings-NgGwF7Qt.d.ts +0 -331
- package/dist/src-CQxJFv4l.js.map +0 -1
- package/dist/tool-cQRkwSZZ.js.map +0 -1
- package/dist/transport-k2mFrtL8.d.ts +0 -200
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"tool-cQRkwSZZ.js","names":[],"sources":["../src/web/search/contract.ts","../src/web/search/source.ts","../src/web/search/tool.ts"],"sourcesContent":["/**\n * The `web_search` tool contract: its name, what it tells the model, what the\n * model passes in, what comes back, and how results are rendered for the\n * model. Shared by every executor of the tool — the harness-executed\n * adapters in `agents/websearch/*` today, and a gateway-executed variant in\n * `agents/models/*` once AI Gateway server tools ship — so a `web_search` call\n * looks the same in a transcript whoever ran it.\n */\n\n/**\n * The tool's name, as the model calls it and as it appears in transcripts.\n * `web_search` is the name models know from Anthropic's and OpenAI's built-in\n * search tools.\n */\nexport const WEB_SEARCH_TOOL_NAME = \"web_search\";\n\n/** The default number of results when the model doesn't ask for a count. */\nexport const DEFAULT_WEB_SEARCH_LIMIT = 5;\n\n/** The most results one search can return; the API rejects more. */\nexport const MAX_WEB_SEARCH_LIMIT = 10;\n\n/** The longest query the API accepts, in characters. */\nexport const MAX_WEB_SEARCH_QUERY_LENGTH = 1024;\n\n/**\n * Per-result description length in the model's view, in characters. Provider\n * descriptions run to ~8,000 characters (Ceramic returns page text), which at\n * ten results is 80 KB of context per search. The full text stays in the\n * host-side output.\n */\nexport const DEFAULT_WEB_SEARCH_DESCRIPTION_CHARS = 600;\n\n/*\n * These are type aliases, not interfaces: pi stores tool details as strict\n * JSON, and only aliases satisfy its `JsonValue` index signature.\n */\n\n/** What the model says when it wants a search. */\nexport type WebSearchToolInput = {\n /** The search query. */\n query: string;\n /** How many results to return, 1–10. Defaults to the host's `limit`. */\n limit?: number;\n};\n\n/**\n * One search result. `url` and `title` are always present; the rest only\n * when the provider returns them (Exa adds `imageUrl` and\n * `lastModifiedDate`, Linkup adds `faviconUrl`, Ceramic adds neither).\n */\nexport type WebSearchResult = {\n url: string;\n title: string;\n /** A snippet or extract of the page. Length and style vary by provider. */\n description?: string;\n /** ISO 8601 timestamp of the page's last modification. */\n lastModifiedDate?: string;\n imageUrl?: string;\n faviconUrl?: string;\n};\n\n/** The Web Search API's response: results plus request metadata. */\nexport type WebSearchResponse = {\n items: WebSearchResult[];\n metadata: {\n /** The query as the provider saw it. */\n query: string;\n /** AI Gateway request id, for the gateway log. */\n requestId: string;\n /** Provider latency in milliseconds. */\n latencyMs: number;\n };\n};\n\n/**\n * What one `web_search` run produces for the host: the full API response and\n * which provider served it. The model sees {@link renderWebSearchResults}\n * of this.\n */\nexport type WebSearchToolOutput = WebSearchResponse & {\n /** The provider that ran the search, when the source knows. */\n provider?: string;\n};\n\nexport const WEB_SEARCH_TOOL_DESCRIPTION = [\n \"Search the public web. Returns up to `limit` results, each with a URL, a title, and a short description of the page.\",\n \"Use it for current events, facts you're unsure of, documentation, and anything that may have changed since your training.\",\n \"There is no next page: for more or different results, search again with a rephrased query.\",\n \"Results are discovery only: to read a page, fetch its URL with `web_fetch` if it is available.\"\n].join(\" \");\n\nexport interface RenderWebSearchResultsOptions {\n /**\n * Trim each description to this many characters in the model's view.\n * Defaults to {@link DEFAULT_WEB_SEARCH_DESCRIPTION_CHARS}; `Infinity`\n * disables trimming.\n */\n maxDescriptionChars?: number;\n}\n\n/**\n * Render search results as the text the model reads: one numbered block per\n * result, descriptions trimmed and whitespace collapsed.\n */\nexport function renderWebSearchResults(\n response: WebSearchResponse,\n options: RenderWebSearchResultsOptions = {}\n): string {\n const maxChars =\n options.maxDescriptionChars ?? DEFAULT_WEB_SEARCH_DESCRIPTION_CHARS;\n if (response.items.length === 0) {\n return `No results for \"${response.metadata.query}\". Try a broader or rephrased query.`;\n }\n const blocks = response.items.map((item, index) => {\n const lines = [`${index + 1}. ${item.title.trim() || item.url}`, item.url];\n const description = compactDescription(item.description, maxChars);\n if (description) lines.push(description);\n if (item.lastModifiedDate) lines.push(`Modified: ${item.lastModifiedDate}`);\n return lines.join(\"\\n\");\n });\n return [\n `${response.items.length} result${response.items.length === 1 ? \"\" : \"s\"} for \"${response.metadata.query}\":`,\n \"\",\n blocks.join(\"\\n\\n\")\n ].join(\"\\n\");\n}\n\nfunction compactDescription(\n description: string | undefined,\n maxChars: number\n): string | undefined {\n if (!description) return undefined;\n const compact = description.replace(/\\s+/g, \" \").trim();\n if (!compact) return undefined;\n if (compact.length <= maxChars) return compact;\n const cut = compact.slice(0, Math.max(0, maxChars - 1));\n // Back off to the last word boundary, unless that loses too much.\n const space = cut.lastIndexOf(\" \");\n const end = space >= cut.length - WORD_BOUNDARY_BACKOFF ? space : cut.length;\n return `${cut.slice(0, end).trimEnd()}…`;\n}\n\n/** How far truncation backs off to end on a whole word. */\nconst WORD_BOUNDARY_BACKOFF = 20;\n","/**\n * Where searches run. A {@link WebSearchSource} turns a query into a\n * {@link WebSearchResponse}; the tool core is written against it, so the\n * same tool works over the Workers AI binding, the HTTP API, or a fake in\n * tests.\n */\nimport { DEFAULT_GATEWAY_ID } from \"../../models/core/settings\";\nimport { abortable } from \"../abortable\";\nimport {\n DEFAULT_WEB_SEARCH_LIMIT,\n MAX_WEB_SEARCH_LIMIT,\n MAX_WEB_SEARCH_QUERY_LENGTH,\n type WebSearchResponse,\n type WebSearchResult\n} from \"./contract\";\n\n/**\n * Search providers behind the Cloudflare Web Search API. `ceramic` is the\n * platform default and the cheapest; `exa` and `linkup` cost more and, in our\n * testing, ranked announcement-style queries noticeably better. Pricing and\n * data-retention terms are in the Web Search docs.\n */\nexport type WebSearchProvider = \"ceramic\" | \"exa\" | \"linkup\";\n\n/** One search request as a source receives it. */\nexport interface WebSearchRequest {\n /** 1–1024 characters. */\n query: string;\n /** 1–10. Defaults to 5. */\n limit?: number;\n}\n\n/** Per-call options a source receives alongside the request. */\nexport interface WebSearchCallOptions {\n /** Abort the search. A source should reject with the signal's reason. */\n signal?: AbortSignal;\n}\n\n/**\n * Runs searches. The tool core calls `search` and renders what comes back.\n * An object rather than a bare function so a wrapper (caching, logging)\n * keeps `provider` by spreading the source it wraps.\n */\nexport interface WebSearchSource {\n search(\n request: WebSearchRequest,\n options?: WebSearchCallOptions\n ): Promise<WebSearchResponse>;\n /**\n * The provider this source searches with, when known. Informational:\n * recorded on the tool's host output.\n */\n readonly provider?: WebSearchProvider;\n}\n\n/** Options shared by the AI-binding and HTTP sources. */\nexport interface WebSearchGatewayOptions {\n /** AI Gateway id. Defaults to `\"default\"`, which Cloudflare creates on first use. */\n gateway?: string;\n /**\n * Which provider runs the search. Host-chosen; the model never picks.\n * Defaults to the platform default (`ceramic`).\n */\n provider?: WebSearchProvider;\n /**\n * The BYOK key alias on the gateway to bill the provider with. When set\n * and no such key exists the request fails rather than falling back to\n * AI Gateway credits. When omitted, a key under the `default` alias is\n * used if one exists, otherwise credits.\n */\n byokAlias?: string;\n}\n\n/** A search over the Workers AI binding (`env.AI.websearch`). */\nexport interface AIWebSearchOptions extends WebSearchGatewayOptions {\n /** The Workers AI binding. Requires `\"ai\": { \"binding\": \"AI\" }` in wrangler.jsonc. */\n binding: Ai;\n}\n\n/**\n * `Ai.websearch` as `@cloudflare/workers-types` ≥ 5.20260812.1 declares it.\n * This repo can't take that version yet — it breaks `@types/node`'s\n * `Buffer` (cloudflare/workerd#7026) — so the method is spelled out here\n * and the binding is viewed through it. Drop once the repo bumps.\n */\ninterface AiWebSearchBinding {\n websearch(request: {\n gatewayId: string;\n query: string;\n limit?: number;\n provider?: string;\n byokAlias?: string;\n }): Promise<Response>;\n}\n\n/**\n * Search through the Workers AI binding. The Worker's own account and the\n * named gateway are billed.\n */\nexport function createAIWebSearch(\n options: AIWebSearchOptions\n): WebSearchSource {\n validateGatewayOptions(options);\n const binding = options.binding as unknown as AiWebSearchBinding;\n const search: WebSearchSource[\"search\"] = async (input, call = {}) => {\n const request = validateRequest(input);\n if (typeof binding.websearch !== \"function\") {\n throw new WebSearchError(\n \"This Workers runtime has no env.AI.websearch(). Web search needs workerd 1.20260924.1 or later; see https://github.com/cloudflare/agents/blob/main/docs/agents/search-the-web.md.\",\n {\n status: 501,\n code: \"web_search_unsupported_runtime\",\n retryable: false\n }\n );\n }\n // Do not start a billed search for a call that is already cancelled.\n call.signal?.throwIfAborted();\n // The binding takes no signal, so an abort stops waiting for it.\n const response = await abortable(\n binding.websearch({\n gatewayId: options.gateway ?? DEFAULT_GATEWAY_ID,\n query: request.query,\n limit: request.limit,\n provider: options.provider,\n byokAlias: options.byokAlias\n }),\n call.signal\n );\n return readResponse(response, request.query);\n };\n return { search, provider: options.provider };\n}\n\n/** A search over the HTTP API, from any runtime with `fetch`. */\nexport interface HTTPWebSearchOptions extends WebSearchGatewayOptions {\n /** The Cloudflare account the gateway belongs to. */\n accountId: string;\n /** An API token with `Workers AI: Read` and `AI Gateway: Read` on that account. */\n apiToken: string;\n /** Override for tests. Defaults to the global `fetch`. */\n fetch?: typeof fetch;\n /** API origin. Defaults to `https://api.cloudflare.com`. */\n baseUrl?: string;\n}\n\n/**\n * Search through `POST /accounts/{account_id}/ai/websearch`. Use this\n * outside Workers, or to search through a gateway in another account.\n */\nexport function createHTTPWebSearch(\n options: HTTPWebSearchOptions\n): WebSearchSource {\n validateGatewayOptions(options);\n const doFetch = options.fetch ?? fetch;\n const baseUrl = (options.baseUrl ?? \"https://api.cloudflare.com\").replace(\n /\\/+$/,\n \"\"\n );\n const url = `${baseUrl}/client/v4/accounts/${encodeURIComponent(options.accountId)}/ai/websearch/`;\n const search: WebSearchSource[\"search\"] = async (input, call = {}) => {\n const request = validateRequest(input);\n const response = await doFetch(url, {\n method: \"POST\",\n signal: call.signal,\n headers: {\n Authorization: `Bearer ${options.apiToken}`,\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n query: request.query,\n limit: request.limit,\n provider: options.provider,\n byokAlias: options.byokAlias,\n options: { gateway: { id: options.gateway ?? DEFAULT_GATEWAY_ID } }\n })\n });\n return readResponse(response, request.query);\n };\n return { search, provider: options.provider };\n}\n\n/** The API's pattern for `byokAlias`. */\nconst BYOK_ALIAS_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;\n\n/** Host configuration errors are programming errors: throw when building. */\nfunction validateGatewayOptions(options: WebSearchGatewayOptions): void {\n if (\n options.byokAlias !== undefined &&\n !BYOK_ALIAS_PATTERN.test(options.byokAlias)\n ) {\n throw new RangeError(\n `byokAlias must be 1–64 letters, digits, \"_\" or \"-\"; got ${JSON.stringify(options.byokAlias)}.`\n );\n }\n}\n\n/**\n * Error codes a {@link WebSearchError} carries. The `web_search_*` codes the\n * API returns pass through as-is; failures without one get a code from the\n * HTTP status, so every error has a code to branch on.\n */\nexport type WebSearchErrorCode =\n /** No AI Gateway credits and no provider key for the search. */\n | \"web_search_payment_required\"\n /** `byokAlias` names a key the gateway does not have. */\n | \"web_search_byok_not_configured\"\n /** The query, limit, or provider was rejected. */\n | \"invalid_web_search_input\"\n /** The gateway does not exist or is not set up. */\n | \"web_search_gateway_not_configured\"\n /** The API token or binding is not allowed to search. */\n | \"web_search_unauthorized\"\n /** Too many searches; retry later. */\n | \"web_search_rate_limited\"\n /** The search took longer than the tool's `timeoutMs`. */\n | \"web_search_timeout\"\n /** The API or the provider failed. */\n | \"web_search_unavailable\"\n /** The Workers runtime has no `env.AI.websearch()`. */\n | \"web_search_unsupported_runtime\"\n /** A code the API added after this release. */\n | (string & {});\n\n/** Why a search failed, with what the API said. */\nexport class WebSearchError extends Error {\n override readonly name = \"WebSearchError\";\n readonly status: number;\n readonly code: WebSearchErrorCode;\n /** Whether retrying the same search might succeed. */\n readonly retryable: boolean;\n /** AI Gateway's id for the failed request, for the gateway log. */\n readonly requestId?: string;\n /** The Cloudflare API's numeric error code, when it gave one. */\n readonly apiCode?: number;\n\n constructor(\n message: string,\n details: {\n status: number;\n code: WebSearchErrorCode;\n retryable?: boolean;\n requestId?: string;\n apiCode?: number;\n cause?: unknown;\n }\n ) {\n super(message, { cause: details.cause });\n this.status = details.status;\n this.code = details.code;\n this.retryable = details.retryable ?? isRetryableStatus(details.status);\n this.requestId = details.requestId;\n this.apiCode = details.apiCode;\n }\n}\n\n/** Check a request against the API's limits and fill in the default limit. */\nfunction validateRequest(\n request: WebSearchRequest\n): Required<WebSearchRequest> {\n const query = request.query.trim();\n const limit = request.limit ?? DEFAULT_WEB_SEARCH_LIMIT;\n if (query.length === 0) {\n throw new WebSearchError(\"Query must not be empty.\", {\n status: 400,\n code: \"invalid_web_search_input\"\n });\n }\n if (query.length > MAX_WEB_SEARCH_QUERY_LENGTH) {\n throw new WebSearchError(\n `Query must be at most ${MAX_WEB_SEARCH_QUERY_LENGTH} characters.`,\n { status: 400, code: \"invalid_web_search_input\" }\n );\n }\n if (!Number.isInteger(limit) || limit < 1 || limit > MAX_WEB_SEARCH_LIMIT) {\n throw new WebSearchError(\n `Limit must be an integer from 1 to ${MAX_WEB_SEARCH_LIMIT}.`,\n { status: 400, code: \"invalid_web_search_input\" }\n );\n }\n return { query, limit };\n}\n\nasync function readResponse(\n response: Response,\n query: string\n): Promise<WebSearchResponse> {\n const text = await response.text();\n let body: unknown;\n try {\n body = JSON.parse(text);\n } catch {\n body = undefined;\n }\n if (!response.ok) throw toWebSearchError(response.status, body, text);\n const result = toWebSearchResponse(body, query);\n if (!result) {\n // A success status with a body that is not a search response is an\n // upstream fault, likely transient, not a reason to stop searching.\n throw new WebSearchError(\n `Web search returned HTTP ${response.status} without search results${text ? `: ${text.slice(0, 200)}` : \"\"}.`,\n {\n status: response.status,\n code: \"web_search_unavailable\",\n retryable: true\n }\n );\n }\n return result;\n}\n\n/**\n * Read a 200 body into a {@link WebSearchResponse}, tolerating what a beta\n * API and three providers might send: items without a URL are dropped, a\n * missing title falls back to the URL, unknown or mistyped fields are left\n * out, and missing metadata gets defaults. Only a body with no `items`\n * array is rejected.\n */\nfunction toWebSearchResponse(\n body: unknown,\n query: string\n): WebSearchResponse | undefined {\n if (!isRecord(body) || !Array.isArray(body.items)) return undefined;\n const items: WebSearchResult[] = [];\n for (const item of body.items as unknown[]) {\n if (!isRecord(item)) continue;\n const url = asString(item.url)?.trim();\n if (!url) continue;\n const result: WebSearchResult = {\n url,\n title: asString(item.title)?.trim() || url\n };\n for (const key of OPTIONAL_RESULT_FIELDS) {\n const value = asString(item[key]);\n if (value !== undefined) result[key] = value;\n }\n items.push(result);\n }\n const metadata = isRecord(body.metadata) ? body.metadata : {};\n return {\n items,\n metadata: {\n query: asString(metadata.query) ?? query,\n requestId: asString(metadata.requestId) ?? \"\",\n latencyMs: typeof metadata.latencyMs === \"number\" ? metadata.latencyMs : 0\n }\n };\n}\n\nconst OPTIONAL_RESULT_FIELDS = [\n \"description\",\n \"lastModifiedDate\",\n \"imageUrl\",\n \"faviconUrl\"\n] as const satisfies readonly (keyof WebSearchResult)[];\n\n/**\n * The API fails in three shapes. Gateway-native:\n * `{ ok: false, error: { category, code, status, retryable, gatewayRequestId } }`.\n * Request validation, the Cloudflare envelope with issue details:\n * `{ success: false, errors: [{ code: 7000, message }], messages: [{ message, path }] }`.\n * Gateway configuration (`AiGatewayError`):\n * `{ success: false, error: [{ code: 2001, message }], message, description }`.\n */\nfunction toWebSearchError(\n status: number,\n body: unknown,\n text: string\n): WebSearchError {\n if (isRecord(body)) {\n const error = body.error;\n if (isRecord(error) && typeof error.code === \"string\") {\n const errorStatus =\n typeof error.status === \"number\" ? error.status : status;\n return new WebSearchError(describeCode(error.code, errorStatus), {\n status: errorStatus,\n code: error.code,\n retryable:\n typeof error.retryable === \"boolean\" ? error.retryable : undefined,\n requestId: asString(error.gatewayRequestId)\n });\n }\n const envelope: unknown[] = Array.isArray(body.errors)\n ? body.errors\n : Array.isArray(error)\n ? error\n : [];\n const entries = envelope.filter(isRecord);\n const issues: unknown[] = Array.isArray(body.messages) ? body.messages : [];\n const message =\n [\n ...entries.map((entry) => asString(entry.message)),\n ...issues.map(describeIssue)\n ]\n .filter((m): m is string => Boolean(m))\n .join(\"; \") || asString(body.message);\n if (message) {\n const apiCode = entries\n .map((entry) => entry.code)\n .find((code): code is number => typeof code === \"number\");\n return new WebSearchError(message, {\n status,\n code: codeForApiError(apiCode, status),\n apiCode\n });\n }\n }\n return new WebSearchError(\n `Web search failed with HTTP ${status}${text ? `: ${text.slice(0, 200)}` : \"\"}.`,\n { status, code: codeForStatus(status) }\n );\n}\n\nfunction codeForApiError(\n apiCode: number | undefined,\n status: number\n): WebSearchErrorCode {\n switch (apiCode) {\n case 7000:\n return \"invalid_web_search_input\";\n case 2001:\n return \"web_search_gateway_not_configured\";\n default:\n return codeForStatus(status);\n }\n}\n\nfunction codeForStatus(status: number): WebSearchErrorCode {\n if (status === 400) return \"invalid_web_search_input\";\n if (status === 401 || status === 403) return \"web_search_unauthorized\";\n if (status === 402) return \"web_search_payment_required\";\n if (status === 429) return \"web_search_rate_limited\";\n return \"web_search_unavailable\";\n}\n\nfunction isRetryableStatus(status: number): boolean {\n return status === 429 || status >= 500;\n}\n\nfunction describeCode(code: string, status: number): string {\n switch (code) {\n case \"web_search_payment_required\":\n return \"Web search is unavailable: the AI Gateway has no credits and no provider key for this search. Top up AI Gateway credits or store a BYOK key for the provider.\";\n case \"web_search_byok_not_configured\":\n return \"Web search is unavailable: the requested BYOK key alias is not configured on the gateway.\";\n case \"invalid_web_search_input\":\n return \"The API rejected the request: check the query (1–1024 characters), limit (1–10), and provider (ceramic, exa, or linkup).\";\n default:\n return `Web search failed (${code}, HTTP ${status}).`;\n }\n}\n\nfunction describeIssue(issue: unknown): string | undefined {\n if (!isRecord(issue)) return undefined;\n const message = asString(issue.message);\n if (!message) return undefined;\n const path = Array.isArray(issue.path) ? issue.path.join(\".\") : \"\";\n return path ? `${path}: ${message}` : message;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction asString(value: unknown): string | undefined {\n return typeof value === \"string\" ? value : undefined;\n}\n","/**\n * The harness-neutral core of the `web_search` tool, shared by the pi\n * (`agents/websearch/pi`), AI SDK (`agents/websearch/ai-sdk`), and TanStack\n * AI (`agents/websearch/tanstack-ai`) adapters. Internal — not an entry point.\n */\nimport {\n DEFAULT_WEB_SEARCH_LIMIT,\n MAX_WEB_SEARCH_LIMIT,\n WEB_SEARCH_TOOL_DESCRIPTION,\n WEB_SEARCH_TOOL_NAME,\n renderWebSearchResults,\n type WebSearchResponse,\n type WebSearchToolInput,\n type WebSearchToolOutput\n} from \"./contract\";\nimport { abortable } from \"../abortable\";\nimport {\n WebSearchError,\n createAIWebSearch,\n type AIWebSearchOptions,\n type WebSearchSource\n} from \"./source\";\n\n/** Search through the Workers AI binding; the tool builds the source. */\nexport type WebSearchToolBindingOptions = AIWebSearchOptions & {\n source?: never;\n};\n\n/**\n * Search through a source you built. Gateway, provider, and billing belong\n * to the source, so the binding options are not accepted here.\n */\nexport type WebSearchToolSourceOptions = {\n /** Where searches run, instead of the Workers AI binding. */\n source: WebSearchSource;\n binding?: never;\n gateway?: never;\n provider?: never;\n byokAlias?: never;\n};\n\n/**\n * Options every `web_search` tool adapter accepts. Invalid values throw a\n * `RangeError` when the tool is created.\n */\nexport type WebSearchToolOptions = (\n | WebSearchToolBindingOptions\n | WebSearchToolSourceOptions\n) & {\n /**\n * Results per search when the model doesn't ask for a count, and the most\n * it gets when it asks for more. An integer from 1 to 10; defaults to 5.\n */\n limit?: number;\n /** Replaces the default tool description. */\n description?: string;\n /**\n * Per-result description length in the model's view. A positive integer;\n * defaults to 600 characters. `Infinity` passes descriptions through whole.\n */\n maxDescriptionChars?: number;\n /**\n * Give up on a search after this many milliseconds, as a retryable\n * `web_search_timeout` failure. A positive integer; defaults to 30 seconds.\n */\n timeoutMs?: number;\n};\n\n/** The default for {@link WebSearchToolOptions.timeoutMs}. */\nexport const DEFAULT_WEB_SEARCH_TIMEOUT_MS = 30_000;\n\n/**\n * What one run returns to the adapter: the host output, and the model's\n * text. On failure, `error` is the source's error, with the API's detail for\n * the host, and `text` is what the model should read instead.\n */\nexport type WebSearchToolRun =\n | { ok: true; output: WebSearchToolOutput; text: string }\n | { ok: false; error: WebSearchError; text: string };\n\nexport interface WebSearchToolCore {\n name: typeof WEB_SEARCH_TOOL_NAME;\n description: string;\n /** The host's `limit`: the default and the cap for the model's `limit`. */\n limit: number;\n /** Render a search's output as the text the model reads. */\n render(output: WebSearchResponse): string;\n /**\n * Run one search. Aborting `signal` rejects with its reason rather than\n * producing a failed run, so the harness sees a cancelled call.\n */\n run(\n input: WebSearchToolInput,\n options?: { signal?: AbortSignal }\n ): Promise<WebSearchToolRun>;\n}\n\nexport function createWebSearchToolCore(\n options: WebSearchToolOptions\n): WebSearchToolCore {\n const limit = options.limit ?? DEFAULT_WEB_SEARCH_LIMIT;\n const timeoutMs = options.timeoutMs ?? DEFAULT_WEB_SEARCH_TIMEOUT_MS;\n const { maxDescriptionChars } = options;\n if (!Number.isInteger(limit) || limit < 1 || limit > MAX_WEB_SEARCH_LIMIT) {\n throw new RangeError(\n `limit must be an integer from 1 to ${MAX_WEB_SEARCH_LIMIT}; got ${limit}.`\n );\n }\n if (\n maxDescriptionChars !== undefined &&\n maxDescriptionChars !== Infinity &&\n !(Number.isInteger(maxDescriptionChars) && maxDescriptionChars > 0)\n ) {\n throw new RangeError(\n `maxDescriptionChars must be a positive integer or Infinity; got ${maxDescriptionChars}.`\n );\n }\n if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) {\n throw new RangeError(\n `timeoutMs must be a positive integer; got ${timeoutMs}.`\n );\n }\n const source =\n options.source === undefined ? createAIWebSearch(options) : options.source;\n const provider = source.provider;\n const render = (output: WebSearchResponse) =>\n renderWebSearchResults(output, { maxDescriptionChars });\n\n return {\n name: WEB_SEARCH_TOOL_NAME,\n description: options.description ?? WEB_SEARCH_TOOL_DESCRIPTION,\n limit,\n render,\n async run(input, { signal } = {}) {\n signal?.throwIfAborted();\n const request = {\n query: input.query,\n limit: Math.min(clampLimit(input.limit ?? limit), limit)\n };\n const timeout = AbortSignal.timeout(timeoutMs);\n const searchSignal = signal\n ? AbortSignal.any([signal, timeout])\n : timeout;\n try {\n // Race the source too: a custom source may ignore the signal, and\n // the deadline must still end the call.\n const response = await abortable(\n source.search(request, { signal: searchSignal }),\n searchSignal\n );\n const output: WebSearchToolOutput = provider\n ? { ...response, provider }\n : response;\n return {\n ok: true,\n output,\n text: render(response)\n };\n } catch (cause) {\n if (signal?.aborted) throw signal.reason;\n const error = toToolError(cause, timeout.aborted, timeoutMs);\n return { ok: false, error, text: describeFailureForModel(error) };\n }\n }\n };\n}\n\n/**\n * The error a throwing adapter (AI SDK, TanStack AI) raises for a failed\n * run. Those frameworks show the model the error's `message`, so it carries\n * the model's text; the source's error, with the API's detail, is `cause`.\n */\nexport function toolFailure(\n run: Extract<WebSearchToolRun, { ok: false }>\n): WebSearchError {\n const { error } = run;\n return new WebSearchError(run.text, {\n status: error.status,\n code: error.code,\n retryable: error.retryable,\n requestId: error.requestId,\n apiCode: error.apiCode,\n cause: error\n });\n}\n\nfunction toToolError(\n cause: unknown,\n timedOut: boolean,\n timeoutMs: number\n): WebSearchError {\n if (timedOut) {\n return new WebSearchError(`Web search timed out after ${timeoutMs} ms.`, {\n status: 504,\n code: \"web_search_timeout\",\n retryable: true,\n cause\n });\n }\n if (cause instanceof WebSearchError) return cause;\n return new WebSearchError(\n cause instanceof Error ? cause.message : String(cause),\n { status: 500, code: \"web_search_unavailable\", retryable: true, cause }\n );\n}\n\n/**\n * What the model reads when a search fails: whether to retry, change the\n * query, or carry on without search. The operator's detail (credits, keys,\n * gateway setup) stays on the error for the host.\n */\nfunction describeFailureForModel(error: WebSearchError): string {\n if (error.code === \"invalid_web_search_input\") {\n return `Web search rejected the query (${error.message.replace(/\\.$/, \"\")}). Fix the query and try again.`;\n }\n if (error.retryable) {\n return `Web search failed temporarily (${error.code}). You may retry once.`;\n }\n return `Web search is unavailable here (${error.code}). Do not retry; answer without it and say that web search was unavailable.`;\n}\n\n/** The model's `limit`, made an integer from 1 to 10. */\nfunction clampLimit(value: number): number {\n if (!Number.isFinite(value)) return DEFAULT_WEB_SEARCH_LIMIT;\n return Math.min(MAX_WEB_SEARCH_LIMIT, Math.max(1, Math.trunc(value)));\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAcA,MAAa,uBAAuB;;AAGpC,MAAa,2BAA2B;;AAGxC,MAAa,uBAAuB;;AAGpC,MAAa,8BAA8B;;;;;;;AAQ3C,MAAa,uCAAuC;AAsDpD,MAAa,8BAA8B;CACzC;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,GAAG;;;;;AAeV,SAAgB,uBACd,UACA,UAAyC,CAAC,GAClC;CACR,MAAM,WACJ,QAAQ,uBAAA;CACV,IAAI,SAAS,MAAM,WAAW,GAC5B,OAAO,mBAAmB,SAAS,SAAS,MAAM;CAEpD,MAAM,SAAS,SAAS,MAAM,KAAK,MAAM,UAAU;EACjD,MAAM,QAAQ,CAAC,GAAG,QAAQ,EAAE,IAAI,KAAK,MAAM,KAAK,KAAK,KAAK,OAAO,KAAK,GAAG;EACzE,MAAM,cAAc,mBAAmB,KAAK,aAAa,QAAQ;EACjE,IAAI,aAAa,MAAM,KAAK,WAAW;EACvC,IAAI,KAAK,kBAAkB,MAAM,KAAK,aAAa,KAAK,kBAAkB;EAC1E,OAAO,MAAM,KAAK,IAAI;CACxB,CAAC;CACD,OAAO;EACL,GAAG,SAAS,MAAM,OAAO,SAAS,SAAS,MAAM,WAAW,IAAI,KAAK,IAAI,QAAQ,SAAS,SAAS,MAAM;EACzG;EACA,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E;EACF;CACF;AACF;;;;;;AAOA,SAAgB,YACd,KACgB;CAChB,MAAM,EAAE,UAAU;CAClB,OAAO,IAAI,eAAe,IAAI,MAAM;EAClC,QAAQ,MAAM;EACd,MAAM,MAAM;EACZ,WAAW,MAAM;EACjB,WAAW,MAAM;EACjB,SAAS,MAAM;EACf,OAAO;CACT,CAAC;AACH;AAEA,SAAS,YACP,OACA,UACA,WACgB;CAChB,IAAI,UACF,OAAO,IAAI,eAAe,8BAA8B,UAAU,OAAO;EACvE,QAAQ;EACR,MAAM;EACN,WAAW;EACX;CACF,CAAC;CAEH,IAAI,iBAAiB,gBAAgB,OAAO;CAC5C,OAAO,IAAI,eACT,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GACrD;EAAE,QAAQ;EAAK,MAAM;EAA0B,WAAW;EAAM;CAAM,CACxE;AACF;;;;;;AAOA,SAAS,wBAAwB,OAA+B;CAC9D,IAAI,MAAM,SAAS,4BACjB,OAAO,kCAAkC,MAAM,QAAQ,QAAQ,OAAO,EAAE,EAAE;CAE5E,IAAI,MAAM,WACR,OAAO,kCAAkC,MAAM,KAAK;CAEtD,OAAO,mCAAmC,MAAM,KAAK;AACvD;;AAGA,SAAS,WAAW,OAAuB;CACzC,IAAI,CAAC,OAAO,SAAS,KAAK,GAAG,OAAA;CAC7B,OAAO,KAAK,IAAA,IAA0B,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,CAAC,CAAC;AACtE"}
|
|
@@ -1,200 +0,0 @@
|
|
|
1
|
-
import { a as ResolvedGateway } from "./settings-NgGwF7Qt.js";
|
|
2
|
-
|
|
3
|
-
//#region src/models/core/errors.d.ts
|
|
4
|
-
/**
|
|
5
|
-
* Coarse classification of a failed Cloudflare AI call.
|
|
6
|
-
*
|
|
7
|
-
* @experimental This surface is experimental and may change.
|
|
8
|
-
*/
|
|
9
|
-
type CloudflareAIErrorCode =
|
|
10
|
-
| "auth"
|
|
11
|
-
| "rate-limit"
|
|
12
|
-
| "not-found"
|
|
13
|
-
| "bad-request"
|
|
14
|
-
| "provider-error"
|
|
15
|
-
| "gateway-error"
|
|
16
|
-
| "unknown";
|
|
17
|
-
/**
|
|
18
|
-
* One leg of a {@link CloudflareAIError} fallback chain.
|
|
19
|
-
*
|
|
20
|
-
* @experimental This surface is experimental and may change.
|
|
21
|
-
*/
|
|
22
|
-
interface CloudflareAIAttempt {
|
|
23
|
-
/** The model id that was tried. */
|
|
24
|
-
model: string;
|
|
25
|
-
/** The error that leg failed with. */
|
|
26
|
-
error: unknown;
|
|
27
|
-
}
|
|
28
|
-
/**
|
|
29
|
-
* Error thrown for every failed Cloudflare AI call, whether it came back as a
|
|
30
|
-
* non-2xx `Response` or as a thrown Workers AI binding error. Framework
|
|
31
|
-
* modules wrap it into their own error type at their boundary (the AI SDK
|
|
32
|
-
* module into an `APICallError`, so `ai`'s retry loop honours
|
|
33
|
-
* {@link CloudflareAIError.isRetryable}).
|
|
34
|
-
*
|
|
35
|
-
* @experimental This surface is experimental and may change.
|
|
36
|
-
*/
|
|
37
|
-
declare class CloudflareAIError extends Error {
|
|
38
|
-
/** HTTP status, when the failure carried one. */
|
|
39
|
-
readonly status: number | undefined;
|
|
40
|
-
/** Coarse classification used for routing and fallback decisions. */
|
|
41
|
-
readonly code: CloudflareAIErrorCode;
|
|
42
|
-
/** `cf-aig-log-id` of the failed request, when the response carried one. */
|
|
43
|
-
readonly logId: string | undefined;
|
|
44
|
-
/** The model id that produced this error. */
|
|
45
|
-
readonly model: string;
|
|
46
|
-
/** Which binding path the request went down, for error reporting. */
|
|
47
|
-
readonly url: string;
|
|
48
|
-
/** The request body that failed. */
|
|
49
|
-
readonly requestBodyValues: unknown;
|
|
50
|
-
/** Response headers, when there was a response. */
|
|
51
|
-
readonly responseHeaders: Record<string, string> | undefined;
|
|
52
|
-
/** Raw response body text, when there was a response. */
|
|
53
|
-
readonly responseBody: string | undefined;
|
|
54
|
-
/** Whether a retry is worth attempting. */
|
|
55
|
-
readonly isRetryable: boolean;
|
|
56
|
-
/** Parsed error envelope, or other structured detail. */
|
|
57
|
-
readonly data: unknown;
|
|
58
|
-
/** Every leg tried, when this error ends a fallback chain. */
|
|
59
|
-
readonly attempts: CloudflareAIAttempt[] | undefined;
|
|
60
|
-
readonly cause: unknown;
|
|
61
|
-
constructor(options: {
|
|
62
|
-
message: string;
|
|
63
|
-
model: string;
|
|
64
|
-
url: string;
|
|
65
|
-
requestBodyValues: unknown;
|
|
66
|
-
status?: number;
|
|
67
|
-
code: CloudflareAIErrorCode;
|
|
68
|
-
logId?: string;
|
|
69
|
-
responseHeaders?: Record<string, string>;
|
|
70
|
-
responseBody?: string;
|
|
71
|
-
isRetryable?: boolean;
|
|
72
|
-
data?: unknown;
|
|
73
|
-
cause?: unknown;
|
|
74
|
-
attempts?: CloudflareAIAttempt[];
|
|
75
|
-
});
|
|
76
|
-
}
|
|
77
|
-
//#endregion
|
|
78
|
-
//#region src/models/core/gateway-providers.d.ts
|
|
79
|
-
/**
|
|
80
|
-
* The AI Gateway provider table: which gateway provider slug a vendor's own
|
|
81
|
-
* base URL belongs to, and what the universal request's `endpoint` is for a
|
|
82
|
-
* given upstream URL.
|
|
83
|
-
*
|
|
84
|
-
* This is platform knowledge, not vendor knowledge — the gateway publishes the
|
|
85
|
-
* list, and every entry here appears in `AIGatewayProviders` from
|
|
86
|
-
* `@cloudflare/workers-types`. Nothing about a vendor's wire format, model ids
|
|
87
|
-
* or capabilities lives here: the vendor's own provider package builds the
|
|
88
|
-
* request, and this table only says where it goes.
|
|
89
|
-
*
|
|
90
|
-
* Adapted from `@cloudflare/ai-gateway-provider`'s `providers.ts`.
|
|
91
|
-
*
|
|
92
|
-
* @experimental This surface is experimental and may change.
|
|
93
|
-
*/
|
|
94
|
-
/**
|
|
95
|
-
* The gateway provider slugs this table maps onto. A subset of the ambient
|
|
96
|
-
* `AIGatewayProviders` union; {@link GatewayProviderNameCheck} keeps it one.
|
|
97
|
-
*
|
|
98
|
-
* @experimental This surface is experimental and may change.
|
|
99
|
-
*/
|
|
100
|
-
declare const GATEWAY_PROVIDER_NAMES: readonly [
|
|
101
|
-
"workers-ai",
|
|
102
|
-
"anthropic",
|
|
103
|
-
"openai",
|
|
104
|
-
"azure-openai",
|
|
105
|
-
"google-ai-studio",
|
|
106
|
-
"google-vertex-ai",
|
|
107
|
-
"grok",
|
|
108
|
-
"mistral",
|
|
109
|
-
"perplexity-ai",
|
|
110
|
-
"replicate",
|
|
111
|
-
"groq",
|
|
112
|
-
"deepseek",
|
|
113
|
-
"openrouter",
|
|
114
|
-
"cerebras",
|
|
115
|
-
"cohere",
|
|
116
|
-
"huggingface",
|
|
117
|
-
"aws-bedrock",
|
|
118
|
-
"elevenlabs",
|
|
119
|
-
"cartesia"
|
|
120
|
-
];
|
|
121
|
-
/**
|
|
122
|
-
* A gateway provider slug.
|
|
123
|
-
*
|
|
124
|
-
* @experimental This surface is experimental and may change.
|
|
125
|
-
*/
|
|
126
|
-
type GatewayProviderName = (typeof GATEWAY_PROVIDER_NAMES)[number];
|
|
127
|
-
//#endregion
|
|
128
|
-
//#region src/models/core/transport.d.ts
|
|
129
|
-
/** One request on the Cloudflare run path. */
|
|
130
|
-
interface TransportRequest {
|
|
131
|
-
/** Model id — Workers AI slug or catalog `<author>/<model>`. */
|
|
132
|
-
model: string;
|
|
133
|
-
/** The provider-shaped request body (`input` on the run path). */
|
|
134
|
-
input: Record<string, unknown>;
|
|
135
|
-
/** Gateway options for this request. */
|
|
136
|
-
gateway: ResolvedGateway;
|
|
137
|
-
/** Extra request headers, merged last. */
|
|
138
|
-
headers: Record<string, string>;
|
|
139
|
-
/** Abort signal, forwarded to the binding or to `fetch`. */
|
|
140
|
-
signal?: AbortSignal;
|
|
141
|
-
}
|
|
142
|
-
/**
|
|
143
|
-
* One request on the universal AI Gateway path: a vendor's own request, routed
|
|
144
|
-
* by the gateway to that vendor. The body is the vendor's, untouched — nothing
|
|
145
|
-
* here knows the vendor's wire format.
|
|
146
|
-
*
|
|
147
|
-
* @experimental This surface is experimental and may change.
|
|
148
|
-
*/
|
|
149
|
-
interface UniversalRequest {
|
|
150
|
-
/** The gateway provider slug the request is routed to. */
|
|
151
|
-
provider: GatewayProviderName | string;
|
|
152
|
-
/** The vendor path the gateway appends to that provider's base URL. */
|
|
153
|
-
endpoint: string;
|
|
154
|
-
/** The vendor's own request headers, minus its credential header. */
|
|
155
|
-
headers: Record<string, string>;
|
|
156
|
-
/** The vendor's request body, verbatim. */
|
|
157
|
-
query: unknown;
|
|
158
|
-
/** Gateway options for this request. */
|
|
159
|
-
gateway: ResolvedGateway;
|
|
160
|
-
/** Extra headers merged last, outside the vendor's own set. */
|
|
161
|
-
extraHeaders?: Record<string, string>;
|
|
162
|
-
/** Abort signal, forwarded to the binding or to `fetch`. */
|
|
163
|
-
signal?: AbortSignal;
|
|
164
|
-
}
|
|
165
|
-
/**
|
|
166
|
-
* The single code path both backends implement. Always resolves to a raw
|
|
167
|
-
* `Response`, so streaming and non-streaming calls share one path and nothing
|
|
168
|
-
* is buffered on the caller's behalf.
|
|
169
|
-
*
|
|
170
|
-
* @experimental This surface is experimental and may change.
|
|
171
|
-
*/
|
|
172
|
-
interface Transport {
|
|
173
|
-
/** A stable identifier for the endpoint, used in error reporting. */
|
|
174
|
-
readonly url: string;
|
|
175
|
-
run(request: TransportRequest): Promise<Response>;
|
|
176
|
-
/**
|
|
177
|
-
* Sends a vendor's own request through the gateway's universal endpoint.
|
|
178
|
-
* Always resolves to the vendor's raw `Response`, error responses included:
|
|
179
|
-
* only the gateway's own failures (a missing gateway, an unpaid account) are
|
|
180
|
-
* lifted into a {@link CloudflareAIError}, because the vendor's provider
|
|
181
|
-
* knows how to read its own errors and we do not.
|
|
182
|
-
*/
|
|
183
|
-
universal(request: UniversalRequest): Promise<Response>;
|
|
184
|
-
/**
|
|
185
|
-
* A log id read off the backend itself when the response carried none. The
|
|
186
|
-
* Workers AI binding exposes the last gateway log id as a mutable property,
|
|
187
|
-
* so it is captured per response rather than read late.
|
|
188
|
-
*/
|
|
189
|
-
logIdFallback(response: Response): string | undefined;
|
|
190
|
-
}
|
|
191
|
-
//#endregion
|
|
192
|
-
export {
|
|
193
|
-
CloudflareAIError as a,
|
|
194
|
-
CloudflareAIAttempt as i,
|
|
195
|
-
GATEWAY_PROVIDER_NAMES as n,
|
|
196
|
-
CloudflareAIErrorCode as o,
|
|
197
|
-
GatewayProviderName as r,
|
|
198
|
-
Transport as t
|
|
199
|
-
};
|
|
200
|
-
//# sourceMappingURL=transport-k2mFrtL8.d.ts.map
|