agents 0.32.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/README.md +1 -1
  2. package/dist/{agent-routing-vVMA7m8Y.d.ts → agent-routing-BSoZzNiP.d.ts} +537 -373
  3. package/dist/agent-routing.d.ts +1 -1
  4. package/dist/agent-tool-types.d.ts +1 -1
  5. package/dist/{agent-tools-gGXXkf1z.d.ts → agent-tools-Be-hpRpH.d.ts} +2 -2
  6. package/dist/agent-tools.d.ts +1 -1
  7. package/dist/{ai-sdk-Kon40i0q.js → ai-sdk-CRMlEBX7.js} +75 -44
  8. package/dist/ai-sdk-CRMlEBX7.js.map +1 -0
  9. package/dist/browser/ai.js +2 -3
  10. package/dist/browser/ai.js.map +1 -1
  11. package/dist/browser/index.d.ts +33 -21
  12. package/dist/browser/index.js +937 -4
  13. package/dist/browser/index.js.map +1 -0
  14. package/dist/browser/tools/ai-sdk.d.ts +4 -4
  15. package/dist/browser/tools/ai-sdk.js +9 -3
  16. package/dist/browser/tools/ai-sdk.js.map +1 -1
  17. package/dist/browser/tools/pi.d.ts +11 -8
  18. package/dist/browser/tools/pi.js +58 -11
  19. package/dist/browser/tools/pi.js.map +1 -1
  20. package/dist/browser/tools/tanstack-ai.d.ts +4 -4
  21. package/dist/browser/tools/tanstack-ai.js +3 -3
  22. package/dist/browser/tools/tanstack-ai.js.map +1 -1
  23. package/dist/{browser-D9RNpJuT.d.ts → browser-C9T74n4c.d.ts} +302 -95
  24. package/dist/browser-tool-DOqT1oSD.js +360 -0
  25. package/dist/browser-tool-DOqT1oSD.js.map +1 -0
  26. package/dist/{browser-tool-BhjCcNVE.d.ts → browser-tool-DxAYQY9T.d.ts} +2 -2
  27. package/dist/capability-DBAKc6UZ.js.map +1 -1
  28. package/dist/{capability-runner-BiVUtjqC.d.ts → capability-runner-uFOdSANC.d.ts} +3 -2
  29. package/dist/chat/index.d.ts +37 -6
  30. package/dist/chat/index.js +39 -3
  31. package/dist/chat/index.js.map +1 -1
  32. package/dist/chat/react.js +1 -0
  33. package/dist/chat/react.js.map +1 -1
  34. package/dist/chat-sdk/index.d.ts +3 -3
  35. package/dist/chat-sdk/index.js +1 -1
  36. package/dist/cli.js +62 -60
  37. package/dist/client-CkT8voRY.js +3740 -0
  38. package/dist/client-CkT8voRY.js.map +1 -0
  39. package/dist/{client-eSfgYvd3.d.ts → client-DqS6oequ.d.ts} +2 -2
  40. package/dist/client.d.ts +1 -1
  41. package/dist/{connector-CM-uuxKM.js → connector-Bphz6wIw.js} +414 -3
  42. package/dist/connector-Bphz6wIw.js.map +1 -0
  43. package/dist/{conversations-FjHDRZyD.d.ts → conversations-CoAYNW_q.d.ts} +4 -4
  44. package/dist/{current-agent-CKgT5d1O.d.ts → current-agent-DShbQHDO.d.ts} +24 -3
  45. package/dist/current-agent-DhoDkSnH.js.map +1 -1
  46. package/dist/{do-oauth-client-provider-DtNqv7oj.d.ts → do-oauth-client-provider-BsT8-vtd.d.ts} +22 -2
  47. package/dist/{durable-object-lifecycle-DOI_bzCH.d.ts → durable-object-lifecycle-CRCA6O0W.d.ts} +2 -2
  48. package/dist/experimental/channels/index.d.ts +2 -2
  49. package/dist/experimental/channels/web/index.d.ts +2 -2
  50. package/dist/experimental/channels/web/index.js +1 -1
  51. package/dist/{gateway-BFO6vRDn.d.ts → gateway-Dz8zyZBJ.d.ts} +2 -2
  52. package/dist/harness/ai-sdk/index.d.ts +2 -2
  53. package/dist/harness/container/index.d.ts +2 -2
  54. package/dist/harness/container/index.js +1 -1
  55. package/dist/harness/container/index.js.map +1 -1
  56. package/dist/harness/opencode/index.d.ts +1 -1
  57. package/dist/harness/pi/index.d.ts +200 -37
  58. package/dist/harness/pi/index.js +202 -100
  59. package/dist/harness/pi/index.js.map +1 -1
  60. package/dist/harness/think/index.d.ts +2 -2
  61. package/dist/{images-CfuRCjwq.js → images-D4gtE06D.js} +119 -27
  62. package/dist/images-D4gtE06D.js.map +1 -0
  63. package/dist/{index-8k4qsX1T.d.ts → index-BXVgv6tp.d.ts} +4 -4
  64. package/dist/{index-BEL3ZV-s.d.ts → index-Cs7Ed9la.d.ts} +2 -2
  65. package/dist/{index-CBt8oRJt.d.ts → index-XiZxauMU.d.ts} +3 -3
  66. package/dist/index.d.ts +21 -21
  67. package/dist/index.js +2 -2
  68. package/dist/{input-schema-BQykTEp_.js → input-schema-D6GilRXI.js} +3 -3
  69. package/dist/input-schema-D6GilRXI.js.map +1 -0
  70. package/dist/{input-schema-B0Etuo-o.js → input-schema-y8W5bOdM.js} +3 -3
  71. package/dist/input-schema-y8W5bOdM.js.map +1 -0
  72. package/dist/internal_context.d.ts +1 -1
  73. package/dist/lifecycle/index.d.ts +3 -3
  74. package/dist/lifecycle/index.js +1 -1
  75. package/dist/{lifecycle-v1rKHV2C.js → lifecycle-CB5Dmtrt.js} +126 -38
  76. package/dist/lifecycle-CB5Dmtrt.js.map +1 -0
  77. package/dist/mcp/client/do-oauth-client-provider.d.ts +1 -1
  78. package/dist/mcp/client/do-oauth-client-provider.js +45 -2
  79. package/dist/mcp/client/do-oauth-client-provider.js.map +1 -1
  80. package/dist/mcp/client/index.d.ts +42 -36
  81. package/dist/mcp/client/index.js +2 -2
  82. package/dist/mcp/index.d.ts +16 -16
  83. package/dist/mcp/index.js +2 -2
  84. package/dist/models/ai-sdk/index.d.ts +9 -5
  85. package/dist/models/ai-sdk/index.js +1 -1
  86. package/dist/models/opencode/index.d.ts +3 -3
  87. package/dist/models/opencode/index.js +2 -2
  88. package/dist/models/opencode/index.js.map +1 -1
  89. package/dist/models/pi-ai/index.d.ts +4 -4
  90. package/dist/models/pi-ai/index.js +64 -170
  91. package/dist/models/pi-ai/index.js.map +1 -1
  92. package/dist/{options-CiIsJHXR.d.ts → options-CiXaymmZ.d.ts} +2 -2
  93. package/dist/queue/index.d.ts +1 -1
  94. package/dist/queue/index.js +1 -1
  95. package/dist/{queue-CcIjVYTE.js → queue-B_wl6K0Z.js} +24 -5
  96. package/dist/queue-B_wl6K0Z.js.map +1 -0
  97. package/dist/react.d.ts +2 -2
  98. package/dist/routing/index.d.ts +2 -2
  99. package/dist/{scheduler-BCLESHSC.d.ts → scheduler-CTpR0Ct0.d.ts} +2 -2
  100. package/dist/{scheduler-FIHv2-kJ.js → scheduler-DGNEmxQR.js} +2 -1
  101. package/dist/scheduler-DGNEmxQR.js.map +1 -0
  102. package/dist/schedules/index.d.ts +1 -1
  103. package/dist/schedules/index.js +1 -1
  104. package/dist/serializable.d.ts +1 -1
  105. package/dist/{session-7CDgVE0z.js → session-CRY0bGiI.js} +423 -411
  106. package/dist/session-CRY0bGiI.js.map +1 -0
  107. package/dist/sessions/index.d.ts +1 -1
  108. package/dist/{settings-Dk2il2Hf.js → settings-D2F_qONv.js} +11 -2
  109. package/dist/settings-D2F_qONv.js.map +1 -0
  110. package/dist/{src-DoGNJ4Ud.js → src-BO1FdLK1.js} +145 -86
  111. package/dist/src-BO1FdLK1.js.map +1 -0
  112. package/dist/state/index.d.ts +1 -1
  113. package/dist/streams/index.d.ts +1 -1
  114. package/dist/{streams-vrCtbUIn.d.ts → streams-CAZxZBDg.d.ts} +2 -2
  115. package/dist/sub-routing.d.ts +12 -12
  116. package/dist/tasks/index.d.ts +1 -1
  117. package/dist/tasks/index.js +1 -1
  118. package/dist/{tasks-BN_5AWqI.js → tasks-Cf_UfEO4.js} +2 -1
  119. package/dist/{tasks-BN_5AWqI.js.map → tasks-Cf_UfEO4.js.map} +1 -1
  120. package/dist/{tasks-E89KdwkS.d.ts → tasks-Cs8ilctE.d.ts} +2 -2
  121. package/dist/{tool-DkT_DJBm.js → tool-CmAGY6Fo.js} +24 -3
  122. package/dist/tool-CmAGY6Fo.js.map +1 -0
  123. package/dist/{tool-CxKsvxjm.js → tool-Kxcj8_22.js} +24 -4
  124. package/dist/tool-Kxcj8_22.js.map +1 -0
  125. package/dist/{tool-helpers-BI7ifO2S.js → tool-helpers-F3_Wy2YX.js} +2 -2
  126. package/dist/{tool-helpers-BI7ifO2S.js.map → tool-helpers-F3_Wy2YX.js.map} +1 -1
  127. package/dist/{transport-5moD2pW5.d.ts → transport-hV8AW4Bv.d.ts} +45 -12
  128. package/dist/voice/index.d.ts +2 -2
  129. package/dist/web/fetch/index.js +1 -1
  130. package/dist/web/fetch/tools/ai-sdk.js +2 -2
  131. package/dist/web/fetch/tools/pi.d.ts +9 -7
  132. package/dist/web/fetch/tools/pi.js +31 -7
  133. package/dist/web/fetch/tools/pi.js.map +1 -1
  134. package/dist/web/fetch/tools/tanstack-ai.js +2 -2
  135. package/dist/web/search/index.js +1 -1
  136. package/dist/web/search/tools/ai-sdk.js +2 -2
  137. package/dist/web/search/tools/pi.d.ts +9 -4
  138. package/dist/web/search/tools/pi.js +27 -11
  139. package/dist/web/search/tools/pi.js.map +1 -1
  140. package/dist/web/search/tools/tanstack-ai.js +2 -2
  141. package/dist/websockets/index.d.ts +2 -2
  142. package/dist/websockets/index.js +1 -1
  143. package/dist/{websockets-C6SJtWCJ.js → websockets-W4uhRg4-.js} +68 -5
  144. package/dist/websockets-W4uhRg4-.js.map +1 -0
  145. package/dist/workflow-types.d.ts +1 -1
  146. package/dist/workflows.d.ts +1 -1
  147. package/docs/agent-class.md +30 -4
  148. package/docs/browse-the-web.md +50 -3
  149. package/docs/chat-agents.md +13 -10
  150. package/docs/client-tools-continuation.md +1 -1
  151. package/docs/codemode.md +1 -1
  152. package/docs/configuration.md +6 -3
  153. package/docs/cross-domain-authentication.md +1 -1
  154. package/docs/fetch-the-web.md +20 -0
  155. package/docs/harnesses/pi.md +242 -33
  156. package/docs/harnesses/think.md +1 -1
  157. package/docs/http-websockets.md +40 -32
  158. package/docs/human-in-the-loop.md +2 -2
  159. package/docs/lifecycle.md +56 -0
  160. package/docs/mcp-client.md +104 -7
  161. package/docs/models-pi-ai.md +24 -10
  162. package/docs/models.md +42 -17
  163. package/docs/resumable-streaming.md +1 -1
  164. package/docs/retries.md +3 -6
  165. package/docs/search-the-web.md +10 -0
  166. package/docs/voice.md +1 -1
  167. package/package.json +16 -9
  168. package/dist/ai-sdk-Kon40i0q.js.map +0 -1
  169. package/dist/browser-1eUbPvC2.js +0 -931
  170. package/dist/browser-1eUbPvC2.js.map +0 -1
  171. package/dist/browser-tool-DRan7Lk6.js +0 -497
  172. package/dist/browser-tool-DRan7Lk6.js.map +0 -1
  173. package/dist/client-DMWujQJ1.js +0 -2325
  174. package/dist/client-DMWujQJ1.js.map +0 -1
  175. package/dist/connector-CM-uuxKM.js.map +0 -1
  176. package/dist/images-CfuRCjwq.js.map +0 -1
  177. package/dist/input-schema-B0Etuo-o.js.map +0 -1
  178. package/dist/input-schema-BQykTEp_.js.map +0 -1
  179. package/dist/lifecycle-v1rKHV2C.js.map +0 -1
  180. package/dist/queue-CcIjVYTE.js.map +0 -1
  181. package/dist/scheduler-FIHv2-kJ.js.map +0 -1
  182. package/dist/session-7CDgVE0z.js.map +0 -1
  183. package/dist/settings-Dk2il2Hf.js.map +0 -1
  184. package/dist/src-DoGNJ4Ud.js.map +0 -1
  185. package/dist/tool-CxKsvxjm.js.map +0 -1
  186. package/dist/tool-DkT_DJBm.js.map +0 -1
  187. package/dist/websockets-C6SJtWCJ.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"connector-CM-uuxKM.js","names":[],"sources":["../src/browser/quick-actions.ts","../src/browser/connector-validation.ts","../src/browser/connector.ts"],"sourcesContent":["import { BrowserRenderingError } from \"./browser-run\";\n\n/**\n * A Browser Run binding that supports [Quick Actions](https://developers.cloudflare.com/browser-run/quick-actions/).\n *\n * This is the `quickAction()` surface of the `BrowserRun` binding generated by\n * `wrangler types`. Quick Actions are stateless one-shot tasks (screenshot,\n * PDF, markdown, structured extraction, …) — no session, no token, just the\n * binding.\n *\n * Requires a Worker `compatibility_date` of `2026-03-24` or later, and\n * `remote: true` on the browser binding for local `wrangler dev`.\n */\nexport interface QuickActionBinding {\n // `options: unknown` (declared as a method, so parameters are checked\n // bivariantly) lets the real `BrowserRun` binding — whose `quickAction` is a\n // set of per-action typed overloads — satisfy this structural type.\n quickAction(action: string, options: unknown): Promise<Response>;\n}\n\n/** The Quick Action endpoints exposed by Browser Run. */\nexport type QuickAction =\n | \"content\"\n | \"screenshot\"\n | \"pdf\"\n | \"markdown\"\n | \"snapshot\"\n | \"scrape\"\n | \"json\"\n | \"links\"\n | \"crawl\";\n\ntype GotoOptions = {\n waitUntil?: \"load\" | \"domcontentloaded\" | \"networkidle0\" | \"networkidle2\";\n timeout?: number;\n};\n\n/** Options accepted by every Quick Action endpoint. */\nexport interface QuickActionCommonOptions {\n gotoOptions?: GotoOptions;\n viewport?: { width: number; height: number; deviceScaleFactor?: number };\n cookies?: unknown[];\n authenticate?: { username: string; password: string };\n setExtraHTTPHeaders?: Record<string, string>;\n userAgent?: string;\n /** Regex strings for requests to drop before render (e.g. `[\"/\\\\.css$/\"]`). */\n rejectRequestPattern?: string[];\n}\n\n/**\n * The page a Quick Action operates on: a `url` to load, or raw `html` to\n * render. Exactly one is required.\n */\nexport type QuickActionPage =\n | ({ url: string; html?: never } & QuickActionCommonOptions)\n | ({ html: string; url?: never } & QuickActionCommonOptions);\n\n/** Input for the AI-powered `/json` extraction endpoint. */\nexport type QuickActionExtractInput = QuickActionPage & {\n /** Natural-language instruction for what to extract. */\n prompt?: string;\n /** A JSON Schema describing the desired output shape. */\n response_format?: { type: \"json_schema\"; json_schema: unknown };\n /** Bring-your-own model(s), tried in order, for extraction. */\n custom_ai?: { model: string; authorization: string }[];\n};\n\n/** Input for the `/scrape` endpoint. */\nexport type QuickActionScrapeInput = QuickActionPage & {\n elements: { selector: string }[];\n};\n\n/** Input for the `/screenshot` endpoint. */\nexport type QuickActionScreenshotInput = QuickActionPage & {\n screenshotOptions?: Record<string, unknown>;\n selector?: string;\n};\n\n/** Binary output (screenshot or PDF) with its reported content type. */\nexport interface QuickActionBinary {\n data: Uint8Array;\n contentType: string;\n}\n\n/** Any Quick Action input accepted by the typed helpers. */\nexport type QuickActionInput =\n | QuickActionPage\n | QuickActionExtractInput\n | QuickActionScrapeInput\n | QuickActionScreenshotInput;\n\n/** Elements matched by one selector via `/scrape`. */\nexport interface QuickActionScrapeResult {\n selector: string;\n results: {\n html: string;\n text: string;\n width: number;\n height: number;\n top: number;\n left: number;\n attributes: { name: string; value: string }[];\n }[];\n}\n\n/** Result of a `/snapshot` request: rendered HTML plus a base64 screenshot. */\nexport interface QuickActionSnapshot {\n /** HTML content of the page. */\n content: string;\n /** Base64-encoded screenshot image. */\n screenshot: string;\n}\n\n/**\n * Run a Quick Action and return the raw {@link Response} from the binding.\n *\n * Most callers want a typed helper ({@link browserMarkdown},\n * {@link browserExtract}, …) instead; reach for this only when you need an\n * endpoint or option not yet wrapped. The per-action overloads type `params`\n * against the action when it is a string literal (e.g. `\"json\"` requires a\n * {@link QuickActionExtractInput}); any {@link QuickActionInput} is accepted\n * otherwise.\n *\n * @deprecated Quick Actions are deprecated and won't change. Use\n * `browserTool` to drive a browser, the `web_fetch` tool from\n * `agents/webfetch` to read a page, or call the binding's\n * `quickAction()` directly.\n */\nexport function runQuickAction(\n browser: QuickActionBinding,\n action: \"json\",\n params: QuickActionExtractInput\n): Promise<Response>;\n/**\n * @deprecated Quick Actions are deprecated and won't change. Use\n * `browserTool` to drive a browser, the `web_fetch` tool from\n * `agents/webfetch` to read a page, or call the binding's\n * `quickAction()` directly.\n */\nexport function runQuickAction(\n browser: QuickActionBinding,\n action: \"scrape\",\n params: QuickActionScrapeInput\n): Promise<Response>;\n/**\n * @deprecated Quick Actions are deprecated and won't change. Use\n * `browserTool` to drive a browser, the `web_fetch` tool from\n * `agents/webfetch` to read a page, or call the binding's\n * `quickAction()` directly.\n */\nexport function runQuickAction(\n browser: QuickActionBinding,\n action: \"screenshot\",\n params: QuickActionScreenshotInput\n): Promise<Response>;\n/**\n * @deprecated Quick Actions are deprecated and won't change. Use\n * `browserTool` to drive a browser, the `web_fetch` tool from\n * `agents/webfetch` to read a page, or call the binding's\n * `quickAction()` directly.\n */\nexport function runQuickAction(\n browser: QuickActionBinding,\n action: QuickAction,\n params: QuickActionInput\n): Promise<Response>;\nexport function runQuickAction(\n browser: QuickActionBinding,\n action: QuickAction,\n params: QuickActionInput\n): Promise<Response> {\n return browser.quickAction(action, params);\n}\n\n/** Build an error that includes the service's explanation, if the body has one. */\nasync function quickActionError(\n action: QuickAction,\n response: Response\n): Promise<BrowserRenderingError> {\n let detail = \"\";\n try {\n const text = await response.text();\n try {\n const body = JSON.parse(text) as {\n errors?: { message?: string }[];\n rawAiResponse?: string;\n };\n const messages = (body.errors ?? [])\n .map((e) => e.message)\n .filter((m): m is string => Boolean(m));\n if (messages.length > 0) detail = `: ${messages.join(\"; \")}`;\n else if (body.rawAiResponse) detail = `: ${body.rawAiResponse}`;\n else if (text) detail = `: ${text.slice(0, 200)}`;\n } catch {\n if (text) detail = `: ${text.slice(0, 200)}`;\n }\n } catch {\n // Body unreadable — fall back to the status code alone.\n }\n return new BrowserRenderingError(\n `Browser Run ${action} failed (${response.status})${detail}`,\n response.status\n );\n}\n\nasync function quickActionJson<T>(\n browser: QuickActionBinding,\n action: QuickAction,\n params: QuickActionInput\n): Promise<T> {\n const response = await runQuickAction(browser, action, params);\n if (!response.ok) throw await quickActionError(action, response);\n const payload = (await response.json()) as {\n success?: boolean;\n result?: T;\n errors?: { message?: string }[];\n };\n if (payload.success === false || payload.result === undefined) {\n const messages = (payload.errors ?? [])\n .map((e) => e.message)\n .filter((m): m is string => Boolean(m));\n throw new BrowserRenderingError(\n `Browser Run ${action} returned no result${messages.length > 0 ? `: ${messages.join(\"; \")}` : \"\"}`,\n response.status\n );\n }\n return payload.result;\n}\n\nasync function quickActionBinary(\n browser: QuickActionBinding,\n action: QuickAction,\n params: QuickActionInput\n): Promise<QuickActionBinary> {\n const response = await runQuickAction(browser, action, params);\n if (!response.ok) throw await quickActionError(action, response);\n const buffer = await response.arrayBuffer();\n return {\n data: new Uint8Array(buffer),\n contentType:\n response.headers.get(\"content-type\") ?? \"application/octet-stream\"\n };\n}\n\n/**\n * Fetch a page's fully rendered HTML via `/content`.\n *\n * @deprecated Quick Actions are deprecated and won't change. Use\n * `browserTool` to drive a browser, the `web_fetch` tool from\n * `agents/webfetch` to read a page, or call the binding's\n * `quickAction()` directly.\n */\nexport function browserContent(\n browser: QuickActionBinding,\n input: QuickActionPage\n): Promise<string> {\n return quickActionJson<string>(browser, \"content\", input);\n}\n\n/**\n * Convert a page (or raw HTML) to Markdown via `/markdown`.\n *\n * @deprecated Quick Actions are deprecated and won't change. Use\n * `browserTool` to drive a browser, the `web_fetch` tool from\n * `agents/webfetch` to read a page, or call the binding's\n * `quickAction()` directly.\n */\nexport function browserMarkdown(\n browser: QuickActionBinding,\n input: QuickActionPage\n): Promise<string> {\n return quickActionJson<string>(browser, \"markdown\", input);\n}\n\n/**\n * Extract structured data from a page with AI via `/json`. Provide a `prompt`,\n * a `response_format` JSON Schema, or both.\n *\n * @deprecated Quick Actions are deprecated and won't change. Use\n * `browserTool` to drive a browser, the `web_fetch` tool from\n * `agents/webfetch` to read a page, or call the binding's\n * `quickAction()` directly.\n */\nexport function browserExtract<T = unknown>(\n browser: QuickActionBinding,\n input: QuickActionExtractInput\n): Promise<T> {\n return quickActionJson<T>(browser, \"json\", input);\n}\n\n/**\n * Retrieve every link on a page via `/links`.\n *\n * @deprecated Quick Actions are deprecated and won't change. Use\n * `browserTool` to drive a browser, the `web_fetch` tool from\n * `agents/webfetch` to read a page, or call the binding's\n * `quickAction()` directly.\n */\nexport function browserLinks(\n browser: QuickActionBinding,\n input: QuickActionPage\n): Promise<string[]> {\n return quickActionJson<string[]>(browser, \"links\", input);\n}\n\n/**\n * Scrape specific elements (by CSS selector) via `/scrape`.\n *\n * @deprecated Quick Actions are deprecated and won't change. Use\n * `browserTool` to drive a browser, the `web_fetch` tool from\n * `agents/webfetch` to read a page, or call the binding's\n * `quickAction()` directly.\n */\nexport function browserScrape(\n browser: QuickActionBinding,\n input: QuickActionScrapeInput\n): Promise<QuickActionScrapeResult[]> {\n return quickActionJson<QuickActionScrapeResult[]>(browser, \"scrape\", input);\n}\n\n/**\n * Capture rendered HTML plus a base64 screenshot in one request via `/snapshot`.\n *\n * @deprecated Quick Actions are deprecated and won't change. Use\n * `browserTool` to drive a browser, the `web_fetch` tool from\n * `agents/webfetch` to read a page, or call the binding's\n * `quickAction()` directly.\n */\nexport function browserSnapshot(\n browser: QuickActionBinding,\n input: QuickActionPage\n): Promise<QuickActionSnapshot> {\n return quickActionJson<QuickActionSnapshot>(browser, \"snapshot\", input);\n}\n\n/**\n * Render a screenshot via `/screenshot`. Returns the raw bytes and their\n * content type — by default a PNG (`image/png`). Note that passing\n * `screenshotOptions.encoding: \"base64\"` makes the service return a `text/plain`\n * data-URI string instead of binary, which this helper hands back verbatim.\n *\n * @deprecated Quick Actions are deprecated and won't change. Use\n * `browserTool` to drive a browser, the `web_fetch` tool from\n * `agents/webfetch` to read a page, or call the binding's\n * `quickAction()` directly.\n */\nexport function browserScreenshot(\n browser: QuickActionBinding,\n input: QuickActionScreenshotInput\n): Promise<QuickActionBinary> {\n return quickActionBinary(browser, \"screenshot\", input);\n}\n\n/**\n * Render a PDF via `/pdf`. Returns the PDF bytes.\n *\n * @deprecated Quick Actions are deprecated and won't change. Use\n * `browserTool` to drive a browser, the `web_fetch` tool from\n * `agents/webfetch` to read a page, or call the binding's\n * `quickAction()` directly.\n */\nexport function browserPdf(\n browser: QuickActionBinding,\n input: QuickActionPage\n): Promise<QuickActionBinary> {\n return quickActionBinary(browser, \"pdf\", input);\n}\n","import { Validator, type OutputUnit, type Schema } from \"@cfworker/json-schema\";\nimport type { ConnectorTool } from \"@cloudflare/codemode\";\n\nfunction formatToolValidationError(\n connector: string,\n tool: string,\n errors: OutputUnit[]\n): string {\n // A failing property emits both a generic parent `properties` error and a\n // specific child error. Prefer the latter so the model sees what to fix.\n const specific = errors.filter((error) => error.keyword !== \"properties\");\n const relevant = specific.length > 0 ? specific : errors;\n const details = relevant.map((error) => {\n const location = error.instanceLocation\n .replace(/^#\\/?/, \"\")\n .replaceAll(\"~1\", \"/\")\n .replaceAll(\"~0\", \"~\")\n .replaceAll(\"/\", \".\");\n return `${location ? ` at ${location}` : \"\"}: ${error.error}`;\n });\n return `Invalid arguments for ${connector}.${tool}${details.join(\";\")}`;\n}\n\n/**\n * Validate a connector tool's arguments against its input schema before it\n * runs, so the model gets a precise error instead of a failure deep inside\n * browser work. An omitted argument counts as `{}`: argumentless tools are\n * documented as `cdp.spec()`.\n */\nexport function validateConnectorArgs(\n connector: string,\n name: string,\n tool: ConnectorTool\n): ConnectorTool {\n if (!tool.inputSchema) return tool;\n\n // Both types describe draft-7 schemas, but @cfworker's `Schema` type is\n // narrower than JSONSchema7 around boolean subschemas.\n const schema = tool.inputSchema as unknown as Schema;\n const validator = new Validator(schema, \"7\", false);\n return {\n ...tool,\n execute: async (args, ctx) => {\n const input = args === undefined ? {} : args;\n const result = validator.validate(input);\n if (!result.valid) {\n throw new Error(\n formatToolValidationError(connector, name, result.errors)\n );\n }\n return await tool.execute(input, ctx);\n }\n };\n}\n","import {\n CodemodeConnector,\n type ConnectorTool,\n type ConnectorTools,\n type ExecutionEndStatus,\n type PassEndStatus,\n type ToolExecuteContext\n} from \"@cloudflare/codemode\";\nimport {\n CDP_METHOD_NOT_FOUND,\n CdpConnection,\n CdpProtocolError,\n connectUrl\n} from \"./cdp-connection\";\nimport { validateConnectorArgs } from \"./connector-validation\";\nimport {\n connectBrowser,\n connectBrowserSession,\n createBrowserSession,\n deleteBrowserSession,\n listBrowserTargets,\n BrowserRenderingError,\n type BrowserBinding,\n type BrowserSessionInfo,\n type BrowserTargetInfo\n} from \"./browser-run\";\nimport {\n applyLiveViewMode,\n LIVE_VIEW_URL_TTL_MS,\n createLiveView,\n type BrowserLiveView,\n type BrowserLiveViewUrl,\n type LiveViewMode\n} from \"./live-view\";\nimport { loadCdpSpec, type SearchableCdpSpec } from \"./spec\";\nimport type {\n BrowserSessionStore,\n StoredBrowserSession\n} from \"./session-store\";\nimport { DEFAULT_SWEEP_IDLE_MS } from \"./session-store\";\n\n/**\n * Browser session lifecycle for the connector (binding-backed only).\n *\n * @deprecated Part of `BrowserConnector`, which is deprecated.\n */\nexport interface BrowserConnectorSessionOptions {\n /**\n * - `\"one-shot\"` (default) — one Browser Run session per codemode\n * execution, deleted when the execution ends.\n * - `\"reuse\"` — all executions share one stored session under `key`.\n * - `\"dynamic\"` — per-execution sessions by default; the model can call\n * `cdp.startSession()` to promote the current session into the shared\n * slot so later executions reuse it.\n */\n mode?: \"one-shot\" | \"reuse\" | \"dynamic\";\n /** Logical owner key for the shared (reuse/promoted) session. Default `\"default\"`. */\n key?: string;\n /** Browser Run inactivity timeout. Browser Run currently caps this server-side. */\n keepAliveMs?: number;\n /**\n * Opt into Browser Run [session recording](https://developers.cloudflare.com/browser-run/features/session-recording/)\n * for sessions this connector creates: an rrweb capture of everything the\n * agent did, finalized when the session closes. Retrieve it afterward with\n * {@link getBrowserRecording} using the session id from\n * {@link BrowserConnector.liveView}/`sessionInfo()`.\n */\n recording?: boolean;\n /**\n * Select the browser engine. Defaults to Chromium. Kitesurf is scoped to\n * one CDP WebSocket, so it supports only one-shot execution without\n * pause/resume, Live View, recording, or keep-alive.\n */\n browser?: \"kitesurf\";\n}\n\n/**\n * Options for {@link BrowserConnector}.\n *\n * @deprecated Part of `BrowserConnector`, which is deprecated.\n */\nexport type BrowserConnectorOptions = (\n | {\n /** Browser Rendering binding (Fetcher) — used in production. */\n browser: BrowserBinding;\n /**\n * Durable store for Browser Run session ids. Required with the binding:\n * a session must survive a pause (approval) and resume on a fresh\n * instance, so its id cannot live in connector memory.\n */\n store: BrowserSessionStore;\n session?: BrowserConnectorSessionOptions;\n cdpUrl?: never;\n cdpHeaders?: never;\n }\n | {\n /**\n * CDP base URL override (e.g. http://localhost:9222). The browser is\n * externally managed: no Browser Run sessions are created or deleted,\n * and session modes don't apply.\n */\n cdpUrl: string;\n /** Headers to send with CDP URL discovery requests (e.g. Access headers). */\n cdpHeaders?: Record<string, string>;\n browser?: never;\n store?: never;\n session?: never;\n }\n) & {\n /** CDP command timeout in milliseconds (default: 10000). */\n timeout?: number;\n};\n\n/**\n * Options for {@link BrowserConnector.sweep}.\n *\n * @deprecated Part of `BrowserConnector`, which is deprecated.\n */\nexport interface BrowserConnectorSweepOptions {\n /**\n * Close the shared (reuse/promoted) session when idle for at least this\n * many milliseconds. Defaults to the connector's `keepAliveMs`, or\n * {@link DEFAULT_SWEEP_IDLE_MS}.\n */\n maxIdleMs?: number;\n /**\n * Close *per-execution* sessions when idle for at least this many\n * milliseconds. Defaults to {@link DEFAULT_EXEC_SWEEP_IDLE_MS} (24h) —\n * deliberately at least as long as the codemode runtime's default paused\n * TTL, so a run awaiting approval is normally expired (and disposed) by\n * `expirePaused` before the sweep backstop ever touches its browser.\n */\n maxExecIdleMs?: number;\n}\n\n/**\n * What {@link BrowserConnector.sweep} reclaimed.\n *\n * @deprecated Part of `BrowserConnector`, which is deprecated.\n */\nexport interface BrowserConnectorSweepResult {\n /** Store keys (and their Browser Run session ids) closed by this sweep. */\n swept: Array<{ key: string; sessionId: string }>;\n}\n\nexport type {\n BrowserLiveView,\n BrowserLiveViewTarget,\n BrowserLiveViewUrl,\n LiveViewMode\n} from \"./live-view\";\n\nconst EXEC_KEY_PREFIX = \"cdp:exec:\";\n/**\n * Prefix of the synthetic session id stored for a Kitesurf execution: the\n * connection is scoped to its execution, so the entry is a marker rather than\n * a Browser Run session that can be reconnected to or deleted.\n */\nconst KITESURF_SESSION_PREFIX = \"kitesurf:\";\nconst REUSE_KEY_PREFIX = \"cdp:reuse:\";\n\n/**\n * Default idle window before {@link BrowserConnector.sweep} reclaims a\n * per-execution session. Matches the codemode runtime's default paused TTL\n * (24h): an execution paused for approval keeps its browser until the run\n * itself is expired.\n *\n * @deprecated Part of `BrowserConnector`, which is deprecated.\n */\nexport const DEFAULT_EXEC_SWEEP_IDLE_MS = 24 * 60 * 60 * 1000;\n\n/**\n * Minimum interval between `updatedAt` bumps on a per-execution store entry.\n * Touching on every CDP call would write-amplify; once a minute is enough to\n * keep an active or recently-resumed execution out of sweep range.\n */\nconst EXEC_TOUCH_INTERVAL_MS = 60 * 1000;\n\nfunction isMissingBrowserSession(error: unknown): boolean {\n // Browser Run uses 404 for unknown ids and 410 after keep_alive expiry.\n return (\n error instanceof BrowserRenderingError &&\n (error.status === 404 || error.status === 410)\n );\n}\n\ninterface CachedSocket {\n session: CdpConnection;\n /** Browser Run session id the socket is attached to (undefined for cdpUrl). */\n browserSessionId?: string;\n /**\n * Live CDP session id per attach handle, valid for this socket only.\n * Rebuilt lazily after a reconnect (sockets are per-pass).\n */\n attached: Map<string, string>;\n}\n\n/**\n * `cdp.attachToTarget` returns `{ sessionId: \"target:<targetId>\" }` — a stable\n * handle instead of the raw CDP session id. (The object shape mirrors the real\n * `Target.attachToTarget` response, which is what models reach for.) Raw ids\n * are connection-scoped: a run that pauses\n * for approval resumes on a fresh WebSocket where the old id is invalid, and\n * the durable replay log would otherwise pin the stale value. The handle is a\n * pure function of the target, so replayed code computes identical arguments,\n * and `send` resolves it to a live session id on the current socket —\n * re-attaching lazily after a reconnect.\n */\nconst ATTACH_HANDLE_PREFIX = \"target:\";\n\n/**\n * Codemode connector exposing a live browser over the Chrome DevTools\n * Protocol as the `cdp` global.\n *\n * Per-execution resources are keyed by the codemode `executionId`:\n *\n * - The Browser Run session id is stored durably under `cdp:exec:<id>`, so a\n * run that pauses for approval reconnects to the *same* browser when it\n * resumes — even on a fresh instance.\n * - The CDP WebSocket is per-pass: `onPassEnd` disconnects it (a paused run\n * holds no socket), and the next pass reconnects from the stored id.\n * - `disposeExecution` deletes the session unless it was promoted to the\n * shared slot via `cdp.startSession()` (dynamic mode).\n *\n * Locks on the session store are held only around store reads/writes, never\n * across network calls to Browser Run or while a socket is open.\n *\n * @deprecated Use `browserTool` from `agents/browser/ai-sdk`,\n * `agents/browser/tanstack-ai` or `agents/browser/pi`. See\n * https://github.com/cloudflare/agents/blob/main/docs/agents/browse-the-web.md#persistent-browser\n */\nexport class BrowserConnector extends CodemodeConnector {\n #options: BrowserConnectorOptions;\n #sockets = new Map<string, CachedSocket>();\n #connecting = new Map<string, Promise<CdpConnection>>();\n\n constructor(\n ctx: DurableObjectState | ExecutionContext,\n options: BrowserConnectorOptions\n ) {\n super(ctx, {});\n if (!options.cdpUrl && !options.browser) {\n throw new Error(\n \"BrowserConnector requires either 'browser' (Fetcher binding) or 'cdpUrl'\"\n );\n }\n if (options.browser && !options.store) {\n throw new Error(\n \"BrowserConnector requires 'store' when using the Browser Rendering binding\"\n );\n }\n if (options.session?.browser === \"kitesurf\") {\n if (\n options.session.mode !== undefined &&\n options.session.mode !== \"one-shot\"\n ) {\n throw new Error('Kitesurf only supports session mode \"one-shot\"');\n }\n if (options.session.keepAliveMs) {\n throw new Error(\"Kitesurf does not support keepAliveMs\");\n }\n if (options.session.recording) {\n throw new Error(\"Kitesurf does not support session recording\");\n }\n }\n this.#options = options;\n }\n\n name(): string {\n return \"cdp\";\n }\n\n protected instructions(): string {\n const mode = this.#mode();\n const lines = [\n \"Issue CDP calls sequentially — never in parallel (no Promise.all): call order is recorded for durable replay.\",\n \"cdp.send returns the CDP method result directly, not the outer JSON-RPC envelope: Target.createTarget returns { targetId }, Runtime.evaluate returns { result: { value } }, and Page.captureScreenshot returns { data }.\",\n \"Browser-/Target-scoped commands (Target.createTarget, Target.getTargets) need no sessionId. Page-scoped commands (Page.navigate, Runtime.evaluate) require one: `const { sessionId } = await cdp.attachToTarget({ targetId });` then pass it to every page-scoped send. Use this helper instead of sending Target.attachToTarget manually.\",\n \"Write large textual outputs such as page dumps to a file or workspace and pass around small references. For screenshots, follow the host tool's documented screenshot result format.\",\n \"If a command fails or times out, check cdp.getDebugLog() for recent protocol traffic.\"\n ];\n if (this.#isKitesurf()) {\n lines.push(\n \"Kitesurf implements a subset of CDP and does not expose protocol discovery.\",\n \"Kitesurf is scoped to this connection. Complete the whole browser task in one execution and do not pause for approval: the browser cannot reconnect when execution resumes.\",\n \"Kitesurf Page.navigate may resolve before layout and paint. Before a screenshot: call Page.enable; navigate; poll Runtime.evaluate with returnByValue: true until result.value reports document.readyState === 'complete' and non-empty body text; then wait 1000ms before Page.captureScreenshot. Do not capture if readiness fails.\"\n );\n } else {\n lines.push(\n \"Use cdp.spec() to look up commands, their parameters, events, and types when unsure.\",\n \"When a step needs a human (login, MFA, CAPTCHA, sensitive input), call cdp.getLiveViewUrl() to get a link they can open to control the browser live — surface it, then make an approval-gated call so the run pauses until they're done.\"\n );\n }\n if (mode === \"one-shot\") {\n lines.push(\n \"The browser session lasts for this execution only and is closed when it ends.\"\n );\n } else if (mode === \"reuse\") {\n lines.push(\n \"The browser session is shared and persists across executions — tabs and state you leave behind will still be there next time.\"\n );\n } else {\n lines.push(\n \"The browser session is one-shot by default. If browser state must persist after this execution (e.g. a logged-in page), call cdp.startSession() to keep it alive for later executions.\"\n );\n }\n return lines.join(\"\\n\");\n }\n\n protected override tool(name: string, tool: ConnectorTool): ConnectorTool {\n return validateConnectorArgs(this.name(), name, tool);\n }\n\n protected tools(): ConnectorTools {\n const tools: ConnectorTools = {\n send: {\n description:\n \"Send a CDP command and return its method result directly (the outer JSON-RPC envelope is removed). Page-scoped commands require a sessionId — pass the handle returned by attachToTarget.\",\n inputSchema: {\n type: \"object\",\n properties: {\n method: {\n type: \"string\",\n description: 'CDP method, e.g. \"Target.createTarget\"'\n },\n params: {\n type: \"object\",\n description: \"CDP command parameters\"\n },\n sessionId: {\n type: \"string\",\n description:\n \"Session handle from attachToTarget, for page-scoped commands\"\n },\n timeoutMs: {\n type: \"number\",\n description: \"Per-command timeout override in milliseconds\"\n }\n },\n required: [\"method\"]\n },\n execute: async (args, ctx) => {\n const { method, params, sessionId, timeoutMs } = args as {\n method: string;\n params?: unknown;\n sessionId?: string;\n timeoutMs?: number;\n };\n const executionId = this.#executionId(ctx);\n const socket = await this.#socket(executionId);\n const resolved = await this.#resolveSessionHandle(\n executionId,\n sessionId\n );\n try {\n return await socket.send(method, params, {\n sessionId: resolved,\n timeoutMs\n });\n } catch (err) {\n // \"Method wasn't found\" is almost always one of two model\n // mistakes. Teach the fix instead of leaving a bare protocol\n // error: either the method is actually an event (events can't be\n // sent), or a page-scoped command went to the browser-level\n // session because no sessionId was passed.\n if (\n err instanceof CdpProtocolError &&\n err.code === CDP_METHOD_NOT_FOUND\n ) {\n if (await this.#isSpecEvent(method)) {\n throw new Error(\n `${err.message}. '${method}' is a CDP *event*, not a ` +\n `command — it cannot be called via cdp.send. To wait for ` +\n `page state, poll instead (e.g. Runtime.evaluate of ` +\n `document.readyState until \"complete\").`\n );\n }\n if (!sessionId) {\n throw new Error(\n `${err.message}. Page-scoped commands need a sessionId: ` +\n `const { sessionId } = await cdp.attachToTarget({ targetId }); ` +\n `then pass sessionId to cdp.send.`\n );\n }\n }\n throw err;\n }\n }\n },\n\n attachToTarget: {\n description: this.#isKitesurf()\n ? \"Attach to a target (tab) and return { sessionId } to pass to page-scoped send calls for this connection.\"\n : \"Attach to a target (tab) and return { sessionId } — a stable session handle to pass as sessionId in page-scoped send calls. The handle stays valid across pauses/resumes.\",\n inputSchema: {\n type: \"object\",\n properties: {\n targetId: {\n type: \"string\",\n description: \"Target id from Target.createTarget/getTargets\"\n },\n timeoutMs: { type: \"number\" }\n },\n required: [\"targetId\"]\n },\n outputSchema: {\n type: \"object\",\n properties: {\n sessionId: {\n type: \"string\",\n description: this.#isKitesurf()\n ? \"Session handle for page-scoped send calls on this connection\"\n : \"Stable session handle for page-scoped send calls (valid across pauses/resumes)\"\n }\n },\n required: [\"sessionId\"]\n },\n execute: async (args, ctx) => {\n const { targetId, timeoutMs } = args as {\n targetId: string;\n timeoutMs?: number;\n };\n const executionId = this.#executionId(ctx);\n await this.#attach(executionId, targetId, timeoutMs);\n return { sessionId: `${ATTACH_HANDLE_PREFIX}${targetId}` };\n }\n },\n\n spec: {\n description:\n \"Return the searchable Chrome DevTools Protocol spec: domains with their commands (parameters and returns), events, and types. Use it to find a method and exactly how to call it.\",\n replay: \"reexecute\",\n inputSchema: { type: \"object\", properties: {} },\n execute: async (): Promise<SearchableCdpSpec> => {\n if (this.#isKitesurf()) {\n throw new Error(\n \"Kitesurf does not expose a CDP protocol specification\"\n );\n }\n return loadCdpSpec(this.#options);\n }\n },\n\n getDebugLog: {\n description:\n \"Return recent CDP protocol traffic (sends, receives, warnings) for this execution's connection — useful to diagnose failures and timeouts.\",\n replay: \"reexecute\",\n inputSchema: {\n type: \"object\",\n properties: {\n limit: {\n type: \"number\",\n description: \"Max entries to return (default 50)\"\n }\n }\n },\n execute: async (args, ctx) => {\n const { limit } = (args ?? {}) as { limit?: number };\n const socket = await this.#socket(this.#executionId(ctx));\n return socket.getDebugLog(limit);\n }\n },\n\n clearDebugLog: {\n description: \"Clear the CDP debug log for this execution's connection.\",\n inputSchema: { type: \"object\", properties: {} },\n execute: async (_args, ctx) => {\n const socket = await this.#socket(this.#executionId(ctx));\n socket.clearDebugLog();\n return null;\n }\n }\n };\n\n if (this.#isKitesurf()) {\n delete tools.spec;\n } else {\n tools.getLiveViewUrl = {\n description:\n \"Return a Live View URL for a tab — a link a human can open in a \" +\n \"browser to watch and control this session in real time. Use it \" +\n \"for human-in-the-loop steps (login, MFA, CAPTCHA, sensitive \" +\n \"input): get the URL, surface it to the user, then make a call \" +\n \"that pauses for approval so they can act before the run \" +\n \"continues. The URL is valid for ~5 minutes.\",\n replay: \"reexecute\",\n inputSchema: {\n type: \"object\",\n properties: {\n targetId: {\n type: \"string\",\n description:\n \"Target (tab) id to view; defaults to the first open page\"\n },\n mode: {\n type: \"string\",\n enum: [\"tab\", \"devtools\"],\n description:\n \"tab = standalone interactive page view (best for handoff); \" +\n \"devtools = full DevTools inspector panel\"\n }\n }\n },\n execute: async (args, ctx) => {\n const { targetId, mode } = (args ?? {}) as {\n targetId?: string;\n mode?: LiveViewMode;\n };\n return this.#liveViewUrl(this.#executionId(ctx), { targetId, mode });\n }\n };\n }\n\n const mode = this.#mode();\n if (mode === \"reuse\" || mode === \"dynamic\") {\n tools.startSession = {\n description:\n mode === \"dynamic\"\n ? \"Promote the current browser session into the shared slot so it persists after this execution. Later executions reuse it. Returns the session info.\"\n : \"Ensure the shared browser session exists and return its info.\",\n inputSchema: { type: \"object\", properties: {} },\n execute: async (_args, ctx) =>\n this.#startSession(this.#executionId(ctx))\n };\n tools.sessionInfo = {\n description:\n \"Return info about the shared browser session (id and open targets), or null when none exists.\",\n replay: \"reexecute\",\n inputSchema: { type: \"object\", properties: {} },\n execute: async () => (await this.sessionInfo()) ?? null\n };\n tools.closeSession = {\n description:\n \"Close the shared browser session, discarding its tabs and state.\",\n inputSchema: { type: \"object\", properties: {} },\n execute: async (_args, ctx) => {\n await this.#closeReusableFor(this.#executionId(ctx));\n return null;\n }\n };\n tools.resetSession = {\n description:\n \"Close the shared browser session and start a fresh one. Returns the new session info.\",\n inputSchema: { type: \"object\", properties: {} },\n execute: async (_args, ctx) =>\n this.#resetSession(this.#executionId(ctx))\n };\n }\n\n return tools;\n }\n\n // ---------------------------------------------------------------------\n // Lifecycle hooks\n // ---------------------------------------------------------------------\n\n /**\n * A pass is over (completed, errored, or paused awaiting approval) — drop\n * the CDP socket. The Browser Run session itself stays alive; a resume\n * reconnects from the durably stored session id.\n */\n override async onPassEnd(\n executionId: string,\n status: PassEndStatus\n ): Promise<void> {\n this.#dropSocket(executionId);\n if (!this.#isKitesurf() || status !== \"paused\") return;\n\n const key = this.#execKey(executionId);\n const lock = await this.#store.acquireLock(key);\n try {\n const stored = await this.#store.get(key);\n // Only a Kitesurf marker is gone with its connection; a session left by\n // an earlier Chromium run is still live and must stay reclaimable.\n if (stored?.sessionId.startsWith(KITESURF_SESSION_PREFIX)) {\n await this.#store.set(key, { ...stored, closedAt: Date.now() });\n }\n } finally {\n await lock.release();\n }\n }\n\n /**\n * The execution is terminal — delete its Browser Run session unless it was\n * promoted to the shared slot via `cdp.startSession()`.\n */\n override async disposeExecution(\n executionId: string,\n _status: ExecutionEndStatus\n ): Promise<void> {\n this.#dropSocket(executionId);\n if (!this.#options.browser) return;\n\n if (this.#isKitesurf()) {\n const key = this.#execKey(executionId);\n const lock = await this.#store.acquireLock(key);\n // An entry written before the connector was switched to Kitesurf still\n // holds a real Browser Run session that has to be closed.\n let stale: StoredBrowserSession | undefined;\n try {\n const stored = await this.#store.get(key);\n if (\n stored &&\n stored.closedAt === undefined &&\n !stored.sessionId.startsWith(KITESURF_SESSION_PREFIX)\n ) {\n stale = stored;\n }\n await this.#store.delete(key);\n } finally {\n await lock.release();\n }\n if (stale) {\n try {\n await deleteBrowserSession(this.#options.browser, stale.sessionId);\n } catch (error) {\n console.warn(\n `[agents/browser] Failed to delete Browser Run session ${stale.sessionId} for execution ${executionId}`,\n error\n );\n }\n }\n return;\n }\n\n const store = this.#options.store;\n const execKey = this.#execKey(executionId);\n const lock = await store.acquireLock(execKey);\n // Decide and update storage under the lock; the Browser Rendering delete\n // happens after release (locks wrap storage only).\n let toClose: StoredBrowserSession | undefined;\n try {\n const stored = await store.get(execKey);\n if (!stored) return;\n\n let promoted = false;\n if (this.#mode() === \"dynamic\") {\n const shared = await store.get(this.#reuseKey());\n promoted = shared?.sessionId === stored.sessionId;\n }\n\n if (!promoted && stored.closedAt === undefined) {\n toClose = stored;\n }\n await store.delete(execKey);\n } finally {\n await lock.release();\n }\n\n if (toClose) {\n try {\n await deleteBrowserSession(this.#options.browser, toClose.sessionId);\n } catch (error) {\n console.warn(\n `[agents/browser] Failed to delete Browser Run session ${toClose.sessionId} for execution ${executionId}`,\n error\n );\n }\n }\n }\n\n // ---------------------------------------------------------------------\n // Host-side helpers — for callables and scheduled tasks on the agent.\n // ---------------------------------------------------------------------\n\n /** Info about the shared (reuse/promoted) session, if one exists. */\n async sessionInfo(): Promise<BrowserSessionInfo | undefined> {\n if (!this.#options.browser || this.#isKitesurf()) return undefined;\n const store = this.#options.store;\n const key = this.#reuseKey();\n const lock = await store.acquireLock(key);\n let stored: StoredBrowserSession | undefined;\n try {\n stored = await store.get(key);\n } finally {\n await lock.release();\n }\n if (!stored) return undefined;\n try {\n return {\n sessionId: stored.sessionId,\n targets: await listBrowserTargets(\n this.#options.browser,\n stored.sessionId\n )\n };\n } catch (error) {\n if (isMissingBrowserSession(error)) {\n await this.#deleteStoredEntry(key, stored.sessionId);\n return undefined;\n }\n throw error;\n }\n }\n\n /**\n * Live View URLs for the shared (reuse/promoted) session's tabs, or\n * `undefined` when no shared session exists. Each URL opens an interactive,\n * real-time view of the browser — surface them in your UI (or send them via\n * Slack/email) to let a human watch or take over a running session\n * (human-in-the-loop). URLs are valid for ~5 minutes; call again for fresh\n * ones. Only meaningful with the Browser Rendering binding in\n * `reuse`/`dynamic` mode.\n */\n async liveView(options?: {\n mode?: LiveViewMode;\n }): Promise<BrowserLiveView | undefined> {\n const info = await this.sessionInfo();\n if (!info) return undefined;\n return createLiveView(info.sessionId, info.targets ?? [], options?.mode);\n }\n\n /** Close the shared (reuse/promoted) session, if one exists. */\n async closeSession(): Promise<void> {\n if (!this.#options.browser || this.#isKitesurf()) return;\n await this.#closeStoredSession(this.#reuseKey());\n }\n\n /**\n * Close stored sessions (shared and per-execution) idle past the threshold.\n * Per-execution entries normally die with `disposeExecution` (or the\n * codemode runtime's `expirePaused`); the sweep is the backstop for crashed\n * hosts. Call it from a recurring alarm/scheduled task.\n *\n * Active executions bump their entry's `updatedAt` on use, so only runs\n * idle past `maxExecIdleMs` (default 24h) are reclaimed. A swept\n * per-execution entry is kept as a tombstone (`closedAt`) rather than\n * deleted, so a later resume fails with a clear \"session expired\" error\n * instead of silently continuing in a fresh browser; tombstones are\n * deleted once they age past the threshold again.\n *\n * Kitesurf entries are reclaimed the same way, minus the Browser Run\n * delete: their stored id is a synthetic per-execution marker, not a\n * session, and the connection died with the execution.\n */\n async sweep(\n options?: BrowserConnectorSweepOptions\n ): Promise<BrowserConnectorSweepResult> {\n if (!this.#options.browser) return { swept: [] };\n const browser = this.#options.browser;\n const store = this.#options.store;\n const maxIdleMs =\n options?.maxIdleMs ??\n this.#options.session?.keepAliveMs ??\n DEFAULT_SWEEP_IDLE_MS;\n const maxExecIdleMs = options?.maxExecIdleMs ?? DEFAULT_EXEC_SWEEP_IDLE_MS;\n\n const keys = new Set<string>([this.#reuseKey()]);\n if (store.list) {\n for (const key of (await store.list(\"cdp:\")).keys()) {\n keys.add(key);\n }\n }\n\n const swept: Array<{ key: string; sessionId: string }> = [];\n for (const key of keys) {\n const isExec = key.startsWith(EXEC_KEY_PREFIX);\n const idleMs = isExec ? maxExecIdleMs : maxIdleMs;\n const lock = await store.acquireLock(key);\n let toClose: StoredBrowserSession | undefined;\n try {\n const stored = await store.get(key);\n if (!stored) continue;\n const now = Date.now();\n if (stored.closedAt !== undefined) {\n // Tombstone from a previous sweep — its session is already gone.\n // Drop it once it has aged past the threshold again.\n if (now - stored.closedAt >= idleMs) await store.delete(key);\n continue;\n }\n if (now - stored.updatedAt < idleMs) continue;\n if (isExec) {\n await store.set(key, { ...stored, closedAt: now });\n } else {\n await store.delete(key);\n }\n toClose = stored;\n } finally {\n await lock.release();\n }\n // Kitesurf entries hold a synthetic marker rather than a Browser Run\n // session id: the connection died with its execution, so there is\n // nothing remote to close. Entries written before the connector was\n // reconfigured still need their session deleted, so this is decided per\n // entry rather than from the current options.\n if (!toClose.sessionId.startsWith(KITESURF_SESSION_PREFIX)) {\n try {\n await deleteBrowserSession(browser, toClose.sessionId);\n } catch (error) {\n console.warn(\n `[agents/browser] Sweep failed to delete Browser Run session ${toClose.sessionId}`,\n error\n );\n }\n }\n swept.push({ key, sessionId: toClose.sessionId });\n }\n return { swept };\n }\n\n // ---------------------------------------------------------------------\n // Session + socket resolution\n // ---------------------------------------------------------------------\n\n #isKitesurf(): boolean {\n return this.#options.session?.browser === \"kitesurf\";\n }\n\n #mode(): \"one-shot\" | \"reuse\" | \"dynamic\" {\n return this.#options.session?.mode ?? \"one-shot\";\n }\n\n #execKey(executionId: string): string {\n return `${EXEC_KEY_PREFIX}${executionId}`;\n }\n\n #reuseKey(): string {\n return `${REUSE_KEY_PREFIX}${this.#options.session?.key ?? \"default\"}`;\n }\n\n #executionId(ctx?: ToolExecuteContext): string {\n if (!ctx?.executionId) {\n throw new Error(\n \"BrowserConnector requires an execution context — use it through createCodemodeRuntime\"\n );\n }\n return ctx.executionId;\n }\n\n #dropSocket(executionId: string): void {\n const cached = this.#sockets.get(executionId);\n if (!cached) return;\n this.#sockets.delete(executionId);\n cached.session.disconnect();\n }\n\n /** Attach the current socket to a target, caching the live CDP session id. */\n async #attach(\n executionId: string,\n targetId: string,\n timeoutMs?: number\n ): Promise<string> {\n const socket = await this.#socket(executionId);\n const cached = this.#sockets.get(executionId);\n const handle = `${ATTACH_HANDLE_PREFIX}${targetId}`;\n const existing = cached?.attached.get(handle);\n if (existing) return existing;\n const live = await socket.attachToTarget(targetId, { timeoutMs });\n cached?.attached.set(handle, live);\n return live;\n }\n\n /**\n * List the current tabs (targets) for this execution's browser, including\n * their `devtoolsFrontendUrl` (the Live View link). For the binding this is\n * the current Browser Run session; for an externally-managed `cdpUrl` it is\n * the standard CDP `/json/list`.\n */\n async #liveTargets(executionId: string): Promise<BrowserTargetInfo[]> {\n if (this.#options.cdpUrl) {\n const endpoint = new URL(\"/json/list\", this.#options.cdpUrl).toString();\n const response = await fetch(endpoint, {\n headers: this.#options.cdpHeaders\n });\n if (!response.ok) {\n throw new Error(\n `Failed to list targets at ${endpoint}: ${response.status}`\n );\n }\n const payload = (await response.json()) as unknown;\n return Array.isArray(payload) ? (payload as BrowserTargetInfo[]) : [];\n }\n\n const browser = this.#options.browser;\n if (!browser) throw new Error(\"BrowserConnector has no browser binding\");\n if (this.#isKitesurf()) {\n throw new Error(\"Kitesurf does not support Browser Run Live View\");\n }\n // Ensure a session + socket exist, then read the resolved Browser Run id.\n await this.#socket(executionId);\n const sessionId = this.#sockets.get(executionId)?.browserSessionId;\n if (!sessionId) return [];\n return listBrowserTargets(browser, sessionId);\n }\n\n /** Build a Live View URL for one tab in this execution's browser. */\n async #liveViewUrl(\n executionId: string,\n options: { targetId?: string; mode?: LiveViewMode }\n ): Promise<BrowserLiveViewUrl> {\n const targets = await this.#liveTargets(executionId);\n const target = options.targetId\n ? targets.find((candidate) => candidate.id === options.targetId)\n : (targets.find(\n (candidate) =>\n candidate.type === \"page\" && candidate.devtoolsFrontendUrl\n ) ?? targets.find((candidate) => candidate.devtoolsFrontendUrl));\n\n if (!target) {\n throw new Error(\n options.targetId\n ? `No target ${options.targetId} found. List tabs with Target.getTargets or open one with Target.createTarget.`\n : \"No browser tab is open yet. Create one (Target.createTarget) before requesting a Live View URL.\"\n );\n }\n if (!target.devtoolsFrontendUrl) {\n throw new Error(\n `Target ${target.id} has no Live View URL (devtoolsFrontendUrl). Live View needs the Browser Rendering binding.`\n );\n }\n\n return {\n url: applyLiveViewMode(target.devtoolsFrontendUrl, options.mode),\n targetId: target.id,\n expiresInMs: LIVE_VIEW_URL_TTL_MS\n };\n }\n\n /**\n * Resolve a model-facing session handle to the live CDP session id on the\n * current socket, re-attaching lazily after a reconnect. Raw CDP session\n * ids (from manual Target.attachToTarget sends) pass through untouched.\n */\n /**\n * True when `method` is a CDP *event* (e.g. `Page.loadEventFired`) rather\n * than a command. Used only on the `send` failure path to produce a better\n * error; any spec-loading failure just means no extra hint.\n */\n async #isSpecEvent(method: string): Promise<boolean> {\n try {\n if (this.#isKitesurf()) return false;\n const spec = await loadCdpSpec(this.#options);\n const domain = method.split(\".\")[0];\n return spec.domains.some(\n (d) => d.name === domain && d.events.some((e) => e.event === method)\n );\n } catch {\n return false;\n }\n }\n\n async #resolveSessionHandle(\n executionId: string,\n sessionId?: string\n ): Promise<string | undefined> {\n if (!sessionId?.startsWith(ATTACH_HANDLE_PREFIX)) return sessionId;\n const targetId = sessionId.slice(ATTACH_HANDLE_PREFIX.length);\n return this.#attach(executionId, targetId);\n }\n\n /**\n * Get or open the CDP socket for an execution. Concurrent calls for the\n * same execution (model code that ignores the \"sequential calls\" rule and\n * uses Promise.all) share one in-flight connect instead of racing and\n * leaking the loser's WebSocket.\n */\n #socket(executionId: string): Promise<CdpConnection> {\n const inFlight = this.#connecting.get(executionId);\n if (inFlight) return inFlight;\n const promise = this.#socketInner(executionId).finally(() => {\n if (this.#connecting.get(executionId) === promise) {\n this.#connecting.delete(executionId);\n }\n });\n this.#connecting.set(executionId, promise);\n return promise;\n }\n\n async #socketInner(executionId: string): Promise<CdpConnection> {\n if (this.#options.cdpUrl) {\n const cached = this.#sockets.get(executionId);\n if (cached) return cached.session;\n const session = await connectUrl(this.#options.cdpUrl, {\n timeoutMs: this.#options.timeout,\n headers: this.#options.cdpHeaders\n });\n this.#sockets.set(executionId, { session, attached: new Map() });\n return session;\n }\n\n const browser = this.#options.browser;\n if (!browser) throw new Error(\"BrowserConnector has no browser binding\");\n\n if (this.#isKitesurf()) {\n const cached = this.#sockets.get(executionId);\n if (cached) return cached.session;\n\n const key = this.#execKey(executionId);\n const lock = await this.#store.acquireLock(key);\n try {\n if (await this.#store.get(key)) {\n throw new Error(\n \"Kitesurf's connection was closed and cannot be resumed; start a new execution\"\n );\n }\n const now = Date.now();\n await this.#store.set(key, {\n sessionId: `${KITESURF_SESSION_PREFIX}${crypto.randomUUID()}`,\n createdAt: now,\n updatedAt: now\n });\n } finally {\n await lock.release();\n }\n\n try {\n const session = await connectBrowser(browser, {\n browser: \"kitesurf\",\n timeoutMs: this.#options.timeout\n });\n this.#sockets.set(executionId, { session, attached: new Map() });\n return session;\n } catch (error) {\n const failed = await this.#readStored(key);\n if (failed) await this.#deleteStoredEntry(key, failed.sessionId);\n throw error;\n }\n }\n\n const stored = await this.#resolveSession(executionId);\n const cached = this.#sockets.get(executionId);\n if (cached?.browserSessionId === stored.sessionId) {\n return cached.session;\n }\n if (cached) this.#dropSocket(executionId);\n\n const session = await connectBrowserSession(browser, stored.sessionId, {\n timeoutMs: this.#options.timeout\n });\n this.#sockets.set(executionId, {\n session,\n browserSessionId: stored.sessionId,\n attached: new Map()\n });\n return session;\n }\n\n /**\n * Resolve the Browser Run session for an execution:\n *\n * - An existing `cdp:exec:<id>` entry wins. If its session is gone (e.g.\n * expired while the run was paused), the run fails with a clear error\n * rather than silently continuing in a fresh browser.\n * - In `reuse` mode the shared session is used (created if missing).\n * - In `dynamic` mode an alive shared session is used; otherwise a fresh\n * per-execution session is created.\n * - In `one-shot` mode a fresh per-execution session is created.\n */\n async #resolveSession(executionId: string): Promise<StoredBrowserSession> {\n const browser = this.#options.browser;\n if (!browser) throw new Error(\"BrowserConnector has no browser binding\");\n const mode = this.#mode();\n const execKey = this.#execKey(executionId);\n\n if (mode === \"reuse\") {\n return this.#ensureStoredSession(this.#reuseKey());\n }\n\n // one-shot / dynamic: a session this execution already opened wins.\n const existing = await this.#readStored(execKey);\n if (existing) {\n if (existing.closedAt === undefined && (await this.#isAlive(existing))) {\n // Keep the entry fresh so the sweep backstop never reclaims an\n // active (or recently resumed) execution's session.\n if (Date.now() - existing.updatedAt >= EXEC_TOUCH_INTERVAL_MS) {\n await this.#touchStored(execKey, existing);\n }\n return existing;\n }\n await this.#deleteStoredEntry(execKey, existing.sessionId);\n throw new Error(\n `Browser session ${existing.sessionId} expired or was swept while this execution was paused — the run cannot continue. Start a new execution.`\n );\n }\n\n if (mode === \"dynamic\") {\n const shared = await this.#readStored(this.#reuseKey());\n if (shared) {\n if (await this.#isAlive(shared)) {\n await this.#touchStored(this.#reuseKey(), shared);\n return shared;\n }\n await this.#deleteStoredEntry(this.#reuseKey(), shared.sessionId);\n }\n }\n\n // Create a fresh per-execution session. The Browser Rendering call\n // happens outside the store lock; the lock only guards the commit, so\n // two concurrent tool calls for the same execution don't double-create\n // (the loser's session is deleted).\n return this.#createAndCommit(execKey);\n }\n\n /**\n * Get the stored session under `key`, validating and creating as needed.\n *\n * Network calls (the liveness probe, session creation) happen OUTSIDE the\n * store lock — locks wrap storage only, so a hung Browser Rendering call\n * can't serialize every other operation on this key. The lock is\n * re-acquired to commit, with a sessionId re-check to detect a concurrent\n * swap; on a swap the new entry is re-validated from the top.\n */\n async #ensureStoredSession(key: string): Promise<StoredBrowserSession> {\n const browser = this.#options.browser;\n if (!browser) throw new Error(\"BrowserConnector has no browser binding\");\n const store = this.#store;\n\n for (let attempt = 0; attempt < 3; attempt++) {\n const existing = await store.get(key);\n if (!existing) return this.#createAndCommit(key);\n\n const alive = await this.#isAlive(existing);\n const lock = await store.acquireLock(key);\n try {\n const current = await store.get(key);\n if (current?.sessionId !== existing.sessionId) {\n // Entry was swapped while we probed — validate the new one.\n continue;\n }\n if (alive) {\n const refreshed = { ...current, updatedAt: Date.now() };\n await store.set(key, refreshed);\n return refreshed;\n }\n await store.delete(key);\n } finally {\n await lock.release();\n }\n // Dead entry deleted — the next iteration creates a fresh session.\n }\n throw new Error(\n `Browser session entry ${key} kept changing concurrently — retry`\n );\n }\n\n /**\n * Create a Browser Run session (outside any lock) and commit it under\n * `key`. If a concurrent caller committed first, their entry wins and the\n * redundant session is deleted best-effort.\n */\n async #createAndCommit(key: string): Promise<StoredBrowserSession> {\n const browser = this.#options.browser;\n if (!browser) throw new Error(\"BrowserConnector has no browser binding\");\n const store = this.#store;\n\n const info = await createBrowserSession(browser, {\n keepAliveMs: this.#options.session?.keepAliveMs,\n recording: this.#options.session?.recording\n });\n const now = Date.now();\n const stored: StoredBrowserSession = {\n sessionId: info.sessionId,\n createdAt: now,\n updatedAt: now\n };\n\n const lock = await store.acquireLock(key);\n let winner: StoredBrowserSession | undefined;\n try {\n const raced = await store.get(key);\n if (raced) {\n winner = raced;\n } else {\n await store.set(key, stored);\n }\n } finally {\n await lock.release();\n }\n\n if (winner) {\n try {\n await deleteBrowserSession(browser, stored.sessionId);\n } catch (error) {\n console.warn(\n `[agents/browser] Failed to delete redundant Browser Run session ${stored.sessionId}`,\n error\n );\n }\n return winner;\n }\n return stored;\n }\n\n async #isAlive(stored: StoredBrowserSession): Promise<boolean> {\n const browser = this.#options.browser;\n if (!browser) return false;\n try {\n await listBrowserTargets(browser, stored.sessionId);\n return true;\n } catch (error) {\n if (isMissingBrowserSession(error)) return false;\n throw error;\n }\n }\n\n // ---------------------------------------------------------------------\n // Session tools (reuse/dynamic)\n // ---------------------------------------------------------------------\n\n async #startSession(executionId: string): Promise<BrowserSessionInfo> {\n const browser = this.#options.browser;\n if (!browser) {\n throw new Error(\"startSession requires the Browser Rendering binding\");\n }\n const store = this.#options.store;\n const reuseKey = this.#reuseKey();\n\n if (this.#mode() === \"dynamic\") {\n // Promote this execution's session into the shared slot, if it has one.\n const exec = await this.#readStored(this.#execKey(executionId));\n if (exec && exec.closedAt === undefined) {\n const lock = await store.acquireLock(reuseKey);\n let replaced: StoredBrowserSession | undefined;\n try {\n const shared = await store.get(reuseKey);\n if (shared?.sessionId !== exec.sessionId) {\n replaced = shared;\n await store.set(reuseKey, { ...exec, updatedAt: Date.now() });\n }\n } finally {\n await lock.release();\n }\n if (replaced) {\n try {\n await deleteBrowserSession(browser, replaced.sessionId);\n } catch (error) {\n console.warn(\n `[agents/browser] Failed to delete replaced Browser Run session ${replaced.sessionId}`,\n error\n );\n }\n }\n return {\n sessionId: exec.sessionId,\n targets: await listBrowserTargets(browser, exec.sessionId)\n };\n }\n }\n\n const stored = await this.#ensureStoredSession(reuseKey);\n return {\n sessionId: stored.sessionId,\n targets: await listBrowserTargets(browser, stored.sessionId)\n };\n }\n\n async #resetSession(executionId: string): Promise<BrowserSessionInfo> {\n const browser = this.#options.browser;\n if (!browser) {\n throw new Error(\"resetSession requires the Browser Rendering binding\");\n }\n await this.#closeReusableFor(executionId);\n const stored = await this.#ensureStoredSession(this.#reuseKey());\n return {\n sessionId: stored.sessionId,\n targets: await listBrowserTargets(browser, stored.sessionId)\n };\n }\n\n /**\n * Close the shared session from inside an execution. If this execution's\n * socket is attached to that session, drop it first.\n */\n async #closeReusableFor(executionId: string): Promise<void> {\n const reuseKey = this.#reuseKey();\n const stored = await this.#readStored(reuseKey);\n if (!stored) return;\n const cached = this.#sockets.get(executionId);\n if (cached?.browserSessionId === stored.sessionId) {\n this.#dropSocket(executionId);\n }\n await this.#closeStoredSession(reuseKey);\n // In reuse mode the execution continues against a fresh shared session on\n // the next send. In dynamic mode the exec entry (if any) still points at\n // the closed session; clear it so the next send fails loudly instead of\n // silently targeting a deleted browser.\n const exec = await this.#readStored(this.#execKey(executionId));\n if (exec?.sessionId === stored.sessionId) {\n await this.#deleteStoredEntry(this.#execKey(executionId), exec.sessionId);\n }\n }\n\n // ---------------------------------------------------------------------\n // Store access — locks held only around the store operation itself.\n // ---------------------------------------------------------------------\n\n get #store(): BrowserSessionStore {\n const store = this.#options.store;\n if (!store) {\n throw new Error(\n \"BrowserConnector session storage requires the Browser Rendering binding\"\n );\n }\n return store;\n }\n\n async #readStored(key: string): Promise<StoredBrowserSession | undefined> {\n const store = this.#store;\n const lock = await store.acquireLock(key);\n try {\n return await store.get(key);\n } finally {\n await lock.release();\n }\n }\n\n async #writeStored(key: string, value: StoredBrowserSession): Promise<void> {\n const store = this.#store;\n const lock = await store.acquireLock(key);\n try {\n await store.set(key, value);\n } finally {\n await lock.release();\n }\n }\n\n async #touchStored(key: string, value: StoredBrowserSession): Promise<void> {\n await this.#writeStored(key, { ...value, updatedAt: Date.now() });\n }\n\n /** Delete the store entry only if it still points at `sessionId`. */\n async #deleteStoredEntry(key: string, sessionId: string): Promise<void> {\n const store = this.#store;\n const lock = await store.acquireLock(key);\n try {\n const current = await store.get(key);\n if (current?.sessionId === sessionId) {\n await store.delete(key);\n }\n } finally {\n await lock.release();\n }\n }\n\n /** Delete the stored entry under `key` and its Browser Run session. */\n async #closeStoredSession(key: string): Promise<void> {\n const browser = this.#options.browser;\n if (!browser) return;\n const store = this.#options.store;\n const lock = await store.acquireLock(key);\n let stored: StoredBrowserSession | undefined;\n try {\n stored = await store.get(key);\n if (stored) await store.delete(key);\n } finally {\n await lock.release();\n }\n if (stored) {\n await deleteBrowserSession(browser, stored.sessionId);\n }\n }\n}\n"],"mappings":";;;;;;AAsKA,SAAg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AAM,MAAM,IAAI,GAAG;EAC5B,IAAI,QAAQ,MAAM,MAAM,OAAO,GAAG;CACpC,UAAU;EACR,MAAM,KAAK,QAAQ;CACrB;CACA,IAAI,QACF,MAAM,qBAAqB,SAAS,OAAO,SAAS;AAExD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"images-CfuRCjwq.js","names":["isRecord","isRecord","stripEchoSuffix","isRecord"],"sources":["../src/models/core/catalog.ts","../src/models/core/errors.ts","../src/models/core/resume.ts","../src/models/core/transport.ts","../src/models/core/gateway-providers.ts","../src/models/core/chat-completions/quirks.ts","../src/models/core/chat-completions/request.ts","../src/models/core/chat-completions/response.ts","../src/models/core/chat-completions/anthropic-stream.ts","../src/models/core/chat-completions/stream.ts","../src/models/core/sse.ts","../src/models/core/images.ts"],"sourcesContent":["/**\n * Keys of the ambient `AiModels` interface (from `@cloudflare/workers-types`)\n * whose model type extends `T`. Kept in step with the installed workers-types\n * version rather than hand-maintained here.\n */\ntype WorkersAIModelIdsExtending<T> = {\n [K in keyof AiModels]: AiModels[K] extends T ? K : never;\n}[keyof AiModels];\n\n/** The `inputs` shape a catalog entry declares. */\ntype InputsOf<K extends keyof AiModels> = AiModels[K] extends {\n inputs: infer I;\n}\n ? I\n : never;\n\n/** The `postProcessedOutputs` shape a catalog entry declares. */\ntype OutputsOf<K extends keyof AiModels> = AiModels[K] extends {\n postProcessedOutputs: infer O;\n}\n ? O\n : never;\n\n/**\n * Catalog keys whose input takes a required `messages` array — every current\n * chat model. Newer entries get their own generated class rather than\n * extending `BaseAiTextGeneration`, so the base-class arm alone misses them.\n */\ntype ChatCatalogId = {\n [K in keyof AiModels]: Extract<\n InputsOf<K>,\n { messages: unknown }\n > extends never\n ? never\n : K;\n}[keyof AiModels];\n\n/**\n * Catalog keys that take text and answer with embedding vectors. Both halves\n * matter: the input test alone also matches translation, classification and\n * speech models, which take `text` but return something else entirely.\n */\ntype EmbeddingCatalogId = {\n [K in keyof AiModels]: Extract<InputsOf<K>, { text: unknown }> extends never\n ? never\n : Extract<OutputsOf<K>, { data?: number[][] }> extends never\n ? never\n : K;\n}[keyof AiModels];\n\n/**\n * Catalog keys that take audio to transcribe. The `audio` key is required on\n * every speech-recognition input and on no other input shape, so the test is\n * exact rather than heuristic.\n */\ntype TranscriptionCatalogId = {\n [K in keyof AiModels]: Extract<InputsOf<K>, { audio: unknown }> extends never\n ? never\n : K;\n}[keyof AiModels];\n\n/**\n * Catalog keys that score a list of contexts against a query — rerankers.\n * `contexts` is required on exactly those inputs.\n */\ntype RerankingCatalogId = {\n [K in keyof AiModels]: Extract<\n InputsOf<K>,\n { contexts: unknown }\n > extends never\n ? never\n : K;\n}[keyof AiModels];\n\n/**\n * A Workers AI model id.\n *\n * Workers AI is the one catalog this package keeps up with, so this is the\n * only id shape it accepts: `@cf/<author>/<model>`. Autocomplete covers the\n * text-generation catalog from the installed `@cloudflare/workers-types`; the\n * template arm keeps every other `@cf/` slug assignable, because the catalog\n * lives server-side and moves independently of these types.\n *\n * Third-party models are not ids here — they are model objects built by their\n * own provider package and routed through AI Gateway.\n */\nexport type WorkersAIModelId =\n // `Extract` is the runtime guard written as a type: the ambient catalog also\n // lists `@hf/...` ids, which `ai()` rejects, so they must not be suggested.\n | Extract<\n | ChatCatalogId\n | Exclude<\n WorkersAIModelIdsExtending<BaseAiTextGeneration>,\n WorkersAIModelIdsExtending<BaseAiTextToImage>\n >,\n `@cf/${string}`\n >\n // `& {}` keeps the literal arms out of the template's shadow: without it\n // TypeScript reduces every suggested id into `@cf/${string}` and stops\n // autocompleting them, exactly as `(string & {})` does elsewhere here.\n | (`@cf/${string}` & {});\n\n/**\n * An AI Gateway dynamic route, by name: `dynamic/<route>`.\n *\n * A dynamic route is configured on the gateway — which models it tries, in\n * which order, with what rate limits or budgets — and called through the\n * Workers AI run path like a model. It answers in the OpenAI chat-completions\n * shape whatever model served it, so it is a language model only.\n */\nexport type DynamicRouteId = `dynamic/${string}`;\n\n/**\n * Whether an id names an AI Gateway dynamic route: `dynamic/` and a route\n * name after it.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function isDynamicRouteId(modelId: string): modelId is DynamicRouteId {\n return modelId.startsWith(\"dynamic/\") && modelId.length > \"dynamic/\".length;\n}\n\n/**\n * Whether an id names a Workers AI model, served by Workers AI itself rather\n * than by AI Gateway's `/run`.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function isWorkersAIId(modelId: string): boolean {\n return modelId.startsWith(\"@cf/\") || modelId.startsWith(\"@hf/\");\n}\n\n/**\n * A model from the AI Gateway catalog, by its catalog id:\n * `<author>/<model>`, such as `openai/gpt-5.5`,\n * `anthropic/claude-opus-4.8` or `cloudflare/auto`.\n *\n * The catalog id is the gateway's own spelling, which can differ from the\n * vendor's (`claude-opus-4.8`, not `claude-opus-4-8`). It runs on\n * `env.AI.run`, where AI Gateway's `/run` engine picks the provider, converts\n * the request, and bills through Unified Billing or a key stored on the\n * gateway.\n */\nexport type CatalogModelId = `${string}/${string}`;\n\n/**\n * Whether an id names an AI Gateway catalog model: an author and a model,\n * neither empty, and none of the other id namespaces (`@cf/`, `@hf/`,\n * `dynamic/`).\n *\n * @experimental This surface is experimental and may change.\n */\nexport function isCatalogModelId(modelId: string): modelId is CatalogModelId {\n if (modelId.startsWith(\"@\") || modelId.startsWith(\"dynamic/\")) return false;\n const slash = modelId.indexOf(\"/\");\n return slash > 0 && slash < modelId.length - 1;\n}\n\n/**\n * Whether a string names a language model that runs on `env.AI.run`: a\n * Workers AI id or an AI Gateway dynamic route.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function isRunPathLanguageModelId(modelId: string): boolean {\n return modelId.startsWith(\"@cf/\") || isDynamicRouteId(modelId);\n}\n\n/**\n * A text-embedding model id accepted by `ai.embedding()`.\n *\n * The modality methods are Workers AI only — there is no vendor route for them\n * — so, like {@link WorkersAIModelId}, they take `@cf/` ids and nothing else.\n */\nexport type CloudflareEmbeddingModelId =\n | Extract<\n EmbeddingCatalogId | WorkersAIModelIdsExtending<BaseAiTextEmbeddings>,\n `@cf/${string}`\n >\n | (`@cf/${string}` & {});\n\n/**\n * Workers AI text-to-image ids that the generated `AiModels` entries do not\n * classify as {@link BaseAiTextToImage} — the newer partner models get their\n * own generated class instead. Curated for autocomplete only; the catalog\n * lives server-side and any slug is accepted.\n *\n * The FLUX.2 family (`flux-2-dev`, `flux-2-klein-4b`, `flux-2-klein-9b`) is\n * deliberately absent, for the reason {@link UnsupportedTranscriptionId}\n * records for the Deepgram recognisers: its generated input takes a required\n * `multipart` object body (`{ multipart: { body, contentType } }`) and no\n * `prompt`, which the JSON run path cannot carry — live, the run path answers\n * `400 Bad input: required properties at \"/\" are 'multipart'`. Suggesting an\n * id that always 400s is worse than not suggesting it.\n */\nexport type KnownImageModelId =\n | \"@cf/black-forest-labs/flux-1-schnell\"\n | \"@cf/leonardo/lucid-origin\"\n | \"@cf/leonardo/phoenix-1.0\";\n\n/**\n * An image model id accepted by `ai.image()`.\n */\nexport type CloudflareImageModelId =\n | Extract<\n WorkersAIModelIdsExtending<BaseAiTextToImage> | KnownImageModelId,\n `@cf/${string}`\n >\n | (`@cf/${string}` & {});\n\n/**\n * Workers AI text-to-speech ids without a {@link BaseAiTextToSpeech} entry.\n * Curated for autocomplete only.\n */\nexport type KnownSpeechModelId =\n | \"@cf/deepgram/aura-1\"\n | \"@cf/deepgram/aura-2-en\"\n | \"@cf/deepgram/aura-2-es\";\n\n/**\n * A text-to-speech model id accepted by `ai.speech()`.\n */\nexport type CloudflareSpeechModelId =\n | Extract<\n WorkersAIModelIdsExtending<BaseAiTextToSpeech> | KnownSpeechModelId,\n `@cf/${string}`\n >\n | (`@cf/${string}` & {});\n\n/**\n * Deepgram's Flux takes websocket connections only. It stays out of the\n * suggested arm, and the transcription model answers a clear error for it.\n */\ntype UnsupportedTranscriptionId = \"@cf/deepgram/flux\";\n\n/**\n * A speech-recognition model id accepted by `ai.transcription()`.\n *\n * Deepgram's Flux (`@cf/deepgram/flux`) is deliberately not suggested: it\n * takes websocket connections only, so this provider answers a clear error\n * for it rather than a 400.\n */\nexport type CloudflareTranscriptionModelId =\n | Extract<\n | Exclude<TranscriptionCatalogId, UnsupportedTranscriptionId>\n | Exclude<\n WorkersAIModelIdsExtending<BaseAiAutomaticSpeechRecognition>,\n UnsupportedTranscriptionId\n >,\n `@cf/${string}`\n >\n | (`@cf/${string}` & {});\n\n/**\n * A reranking model id accepted by `ai.reranking()`.\n */\nexport type CloudflareRerankingModelId =\n | Extract<RerankingCatalogId, `@cf/${string}`>\n | (`@cf/${string}` & {});\n\n/** `true` when `Id` is in the literal (autocompleted) arm of `T`. */\ntype Suggests<T, Id extends string> =\n Extract<T, Id> extends never ? false : true;\n\n/**\n * Compile-time guard: the repo-standard models must stay in the literal arms,\n * so a `@cloudflare/workers-types` bump that reshapes the catalog cannot\n * silently drop them into the `(string & {})` arm and stop suggesting them.\n * `tsc` fails on this alias if any of them stops being autocompleted.\n *\n * @internal\n */\nexport type CatalogAutocompleteCheck<\n T extends [true, true, true, true, true, true, true, true, true] = [\n Suggests<WorkersAIModelId, \"@cf/zai-org/glm-4.7-flash\">,\n Suggests<WorkersAIModelId, \"@cf/meta/llama-3.3-70b-instruct-fp8-fast\">,\n Suggests<CloudflareEmbeddingModelId, \"@cf/baai/bge-base-en-v1.5\">,\n Suggests<CloudflareEmbeddingModelId, \"@cf/google/embeddinggemma-300m\">,\n Suggests<CloudflareImageModelId, \"@cf/black-forest-labs/flux-1-schnell\">,\n Suggests<\n CloudflareImageModelId,\n \"@cf/stabilityai/stable-diffusion-xl-base-1.0\"\n >,\n Suggests<CloudflareSpeechModelId, \"@cf/deepgram/aura-1\">,\n Suggests<\n CloudflareTranscriptionModelId,\n \"@cf/openai/whisper-large-v3-turbo\"\n >,\n Suggests<CloudflareRerankingModelId, \"@cf/baai/bge-reranker-base\">\n ]\n> = T;\n","/**\n * Coarse classification of a failed Cloudflare AI call.\n */\nexport type CloudflareAIErrorCode =\n | \"auth\"\n | \"rate-limit\"\n | \"not-found\"\n | \"bad-request\"\n | \"provider-error\"\n | \"gateway-error\"\n | \"unknown\";\n\n/**\n * One leg of a {@link CloudflareAIError} fallback chain.\n */\nexport interface CloudflareAIAttempt {\n /** The model id that was tried. */\n model: string;\n /** The error that leg failed with. */\n error: unknown;\n}\n\n/**\n * Error thrown for every failed Cloudflare AI call, whether it came back as a\n * non-2xx `Response` or as a thrown Workers AI binding error. Framework\n * modules wrap it into their own error type at their boundary (the AI SDK\n * module into an `APICallError`, so `ai`'s retry loop honours\n * {@link CloudflareAIError.isRetryable}).\n */\nexport class CloudflareAIError extends Error {\n /** HTTP status, when the failure carried one. */\n readonly status: number | undefined;\n /** Coarse classification used for routing and fallback decisions. */\n readonly code: CloudflareAIErrorCode;\n /** `cf-aig-log-id` of the failed request, when the response carried one. */\n readonly logId: string | undefined;\n /** The model id that produced this error. */\n readonly model: string;\n /** Which binding path the request went down, for error reporting. */\n readonly url: string;\n /** The request body that failed. */\n readonly requestBodyValues: unknown;\n /** Response headers, when there was a response. */\n readonly responseHeaders: Record<string, string> | undefined;\n /** Raw response body text, when there was a response. */\n readonly responseBody: string | undefined;\n /** Whether a retry is worth attempting. */\n readonly isRetryable: boolean;\n /** Parsed error envelope, or other structured detail. */\n readonly data: unknown;\n /** Every leg tried, when this error ends a fallback chain. */\n readonly attempts: CloudflareAIAttempt[] | undefined;\n override readonly cause: unknown;\n\n constructor(options: {\n message: string;\n model: string;\n url: string;\n requestBodyValues: unknown;\n status?: number;\n code: CloudflareAIErrorCode;\n logId?: string;\n responseHeaders?: Record<string, string>;\n responseBody?: string;\n isRetryable?: boolean;\n data?: unknown;\n cause?: unknown;\n attempts?: CloudflareAIAttempt[];\n }) {\n super(options.message);\n this.name = \"CloudflareAIError\";\n this.status = options.status;\n this.code = options.code;\n this.logId = options.logId;\n this.model = options.model;\n this.url = options.url;\n this.requestBodyValues = options.requestBodyValues;\n this.responseHeaders = options.responseHeaders;\n this.responseBody = options.responseBody;\n this.isRetryable = options.isRetryable ?? isRetryableStatus(options.status);\n this.data = options.data;\n this.cause = options.cause;\n this.attempts = options.attempts;\n }\n}\n\n/**\n * Whether a status is worth retrying. Missing status means a transport-level\n * failure (connection reset, DNS, abort-adjacent), which is retryable.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function isRetryableStatus(status: number | undefined): boolean {\n if (status === undefined) return true;\n return status === 408 || status === 409 || status === 429 || status >= 500;\n}\n\n/**\n * Classifies an HTTP status into a {@link CloudflareAIErrorCode}. The\n * `AiGatewayError` envelope name catches gateway-level statuses that are not\n * otherwise meaningful (notably 402 \"insufficient balance\").\n */\nexport function classifyStatus(\n status: number | undefined,\n envelopeName?: string\n): CloudflareAIErrorCode {\n if (status === 401 || status === 403) return \"auth\";\n if (status === 429) return \"rate-limit\";\n if (status === 404) return \"not-found\";\n if (status === 400 || status === 422) return \"bad-request\";\n if (status !== undefined && status >= 500) return \"provider-error\";\n if (envelopeName === \"AiGatewayError\") return \"gateway-error\";\n return \"unknown\";\n}\n\n/**\n * Workers AI binding error codes that map onto an HTTP status.\n *\n * @see https://developers.cloudflare.com/workers-ai/platform/errors/\n */\nconst BINDING_CODE_STATUS: Record<number, number> = {\n 3003: 400,\n 3006: 413,\n 3007: 408,\n 3008: 408,\n 3023: 403,\n 3036: 429,\n 3039: 400,\n 3040: 429,\n 3041: 403,\n 3042: 404,\n 5004: 400,\n 5005: 405,\n 5007: 400,\n 5016: 403,\n 5018: 403,\n 5019: 405\n};\n\n/** Abort-shaped errors must propagate untouched so callers can detect them. */\nexport function isAbortError(error: unknown): boolean {\n const name =\n error instanceof Error || error instanceof DOMException\n ? error.name\n : undefined;\n return (\n name === \"AbortError\" ||\n name === \"ResponseAborted\" ||\n name === \"TimeoutError\"\n );\n}\n\nfunction messageOf(error: unknown): string {\n if (typeof error === \"string\") return error;\n if (error instanceof Error) return error.message;\n if (error !== null && typeof error === \"object\" && \"message\" in error) {\n const message = (error as { message: unknown }).message;\n if (typeof message === \"string\") return message;\n }\n return String(error);\n}\n\n/**\n * Extracts a Workers AI internal error code from a thrown binding error. The\n * binding reports codes inside the message text (`\"3040: Capacity temporarily\n * exceeded\"`) rather than as a status, so only known codes are accepted — an\n * unrelated leading number must not be misread as a code.\n */\nfunction bindingErrorCode(error: unknown): number | undefined {\n if (error !== null && typeof error === \"object\" && \"code\" in error) {\n const code = (error as { code: unknown }).code;\n if (typeof code === \"number\" && code in BINDING_CODE_STATUS) return code;\n }\n const matches = messageOf(error).matchAll(/\\b(\\d{3,5})\\s*:/g);\n for (const match of matches) {\n const code = Number(match[1]);\n if (code in BINDING_CODE_STATUS) return code;\n }\n return undefined;\n}\n\n/**\n * Normalizes a thrown Workers AI binding error into a {@link CloudflareAIError}.\n * Abort errors and errors that are already {@link CloudflareAIError}s pass through.\n */\nexport function normalizeThrownError(\n error: unknown,\n context: {\n model: string;\n url: string;\n requestBodyValues: unknown;\n }\n): unknown {\n if (isAbortError(error)) return error;\n if (error instanceof CloudflareAIError) return error;\n\n const code = bindingErrorCode(error);\n const status = code === undefined ? undefined : BINDING_CODE_STATUS[code];\n return new CloudflareAIError({\n cause: error,\n code: classifyStatus(status),\n data: code === undefined ? undefined : { code },\n // A recognised code decides for itself. Everything else is not worth\n // retrying: the binding is the only backend, so a throw with no status is\n // a programming error rather than a transport failure, and re-running it\n // on every fallback leg helps nobody.\n isRetryable: status === undefined ? false : isRetryableStatus(status),\n message: messageOf(error),\n model: context.model,\n requestBodyValues: context.requestBodyValues,\n status,\n url: context.url\n });\n}\n","/**\n * Resuming a streamed `/run` answer that dropped mid-way.\n *\n * AI Gateway's Run Durable Object keeps every SSE event of a streamed run and\n * names the run in `cf-aig-run-id`. The binding can replay the stream from any\n * event index:\n *\n * ```ts\n * env.AI.fetch(`https://workers-binding.ai/ai-gateway/gateways/${id}/run/${runId}/resume?from=${n}`)\n * ```\n *\n * The run keeps going on the gateway after the client is gone, so a replay\n * from the right index continues the same answer rather than starting a new\n * one. This wrapper makes that transparent: it reads the original body, and\n * when a read fails it reconnects to the resume route and keeps feeding the\n * same consumer, which never sees the break.\n *\n * The one subtlety is alignment. `from` counts complete SSE events, so the\n * wrapper only ever passes complete events on and holds back a trailing\n * partial one. After a drop the partial is discarded and the replay starts at\n * the count of events already delivered: no byte is duplicated or lost.\n *\n * @experimental This surface is experimental and may change.\n */\n\nimport { CloudflareAIError } from \"./errors\";\n\n/** Where a resumed stream reconnects. The transport supplies it. */\nexport type ResumeFetch = (\n from: number,\n signal: AbortSignal | undefined\n) => Promise<Response>;\n\n/** What {@link resumableBody} needs to keep a stream going. */\nexport interface ResumableBodyOptions {\n /** The original response body. */\n initial: ReadableStream<Uint8Array>;\n /** Fetches the replay from an event index. */\n resume: ResumeFetch;\n /** The model, for error reporting. */\n model: string;\n /** The binding path, for error reporting. */\n url: string;\n /**\n * The call's abort signal. An abort, like a consumer cancelling the stream,\n * never reconnects.\n */\n signal?: AbortSignal;\n /** Reconnects allowed before giving up. Defaults to 5. */\n maxReconnects?: number;\n}\n\nconst EMPTY = new Uint8Array(0);\n\nfunction concat(a: Uint8Array, b: Uint8Array): Uint8Array {\n const out = new Uint8Array(a.length + b.length);\n out.set(a, 0);\n out.set(b, a.length);\n return out;\n}\n\n/** Index just past the last `\\n\\n` in `buffer`, or -1 when none is complete. */\nfunction lastEventBoundary(buffer: Uint8Array): number {\n for (let i = buffer.length - 2; i >= 0; i--) {\n if (buffer[i] === 0x0a && buffer[i + 1] === 0x0a) return i + 2;\n }\n return -1;\n}\n\n/** Complete SSE events in `buffer`: `\\n\\n` terminators, counted once each. */\nfunction countEvents(buffer: Uint8Array): number {\n let count = 0;\n for (let i = 0; i + 1 < buffer.length; i++) {\n if (buffer[i] === 0x0a && buffer[i + 1] === 0x0a) {\n count++;\n i++;\n }\n }\n return count;\n}\n\n/**\n * Wraps a streamed `/run` body so a dropped connection resumes from the last\n * complete event. Errors once the replay buffer has expired (404), when a\n * replay fails, or after `maxReconnects` drops.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function resumableBody(\n options: ResumableBodyOptions\n): ReadableStream<Uint8Array> {\n const maxReconnects = options.maxReconnects ?? 5;\n let delivered = 0;\n let pending: Uint8Array = EMPTY;\n let reconnects = 0;\n let cancelled = false;\n let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\n const stopped = () => cancelled || options.signal?.aborted === true;\n\n const failure = (\n message: string,\n extra: { status?: number; cause?: unknown } = {}\n ) =>\n new CloudflareAIError({\n code: \"provider-error\",\n isRetryable: false,\n message,\n model: options.model,\n requestBodyValues: undefined,\n url: options.url,\n ...extra\n });\n\n /** The replay from the events already delivered, or undefined after an error. */\n async function replay(\n controller: ReadableStreamDefaultController<Uint8Array>\n ): Promise<ReadableStream<Uint8Array> | undefined> {\n let response: Response;\n try {\n response = await options.resume(delivered, options.signal);\n } catch (error) {\n controller.error(\n failure(\n `The stream dropped at event ${delivered} and the resume request failed.`,\n {\n cause: error\n }\n )\n );\n return undefined;\n }\n if (response.status === 404) {\n controller.error(\n failure(\n `The stream dropped at event ${delivered}, and AI Gateway no longer holds the run to resume it.`,\n { status: 404 }\n )\n );\n return undefined;\n }\n if (!response.ok || response.body === null) {\n controller.error(\n failure(\n `The stream dropped at event ${delivered} and resuming it failed (${response.status}).`,\n {\n status: response.status\n }\n )\n );\n return undefined;\n }\n return response.body;\n }\n\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n let current = options.initial;\n for (;;) {\n reader = current.getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n if (pending.length > 0) controller.enqueue(pending);\n pending = EMPTY;\n controller.close();\n return;\n }\n if (value === undefined || value.length === 0) continue;\n pending = concat(pending, value);\n const boundary = lastEventBoundary(pending);\n if (boundary > 0) {\n const complete = pending.slice(0, boundary);\n controller.enqueue(complete);\n delivered += countEvents(complete);\n pending = pending.slice(boundary);\n }\n }\n } catch (error) {\n try {\n reader.releaseLock();\n } catch {\n // Already released.\n }\n // A cancel or an abort is the caller's decision, never a drop: an\n // abort reaches the consumer as the error it is.\n if (stopped()) {\n if (!cancelled) controller.error(error);\n return;\n }\n if (reconnects >= maxReconnects) {\n controller.error(\n failure(\n `The stream dropped ${reconnects + 1} times; giving up at event ${delivered}.`,\n {\n cause: error\n }\n )\n );\n return;\n }\n // The partial event is replayed whole from the boundary.\n pending = EMPTY;\n reconnects++;\n const body = await replay(controller);\n if (body === undefined) return;\n current = body;\n }\n }\n },\n cancel(reason) {\n cancelled = true;\n reader?.cancel(reason).catch(() => {\n // The upstream may already be closed.\n });\n }\n });\n}\n","import {\n CloudflareAIError,\n classifyStatus,\n normalizeThrownError\n} from \"./errors\";\nimport { isCatalogModelId, isWorkersAIId } from \"./catalog\";\nimport { type ResumeFetch, resumableBody } from \"./resume\";\nimport type { GatewayProviderName } from \"./gateway-providers\";\nimport type { AccountAccess, AISettings, ResolvedGateway } from \"./settings\";\n\n/** The reported `url` for a provider-native call made through the binding. */\nconst NATIVE_BINDING_URL = \"ai-gateway-binding-native\";\n\n/** The origin the binding's own `fetch` answers on. */\nconst BINDING_ORIGIN = \"https://workers-binding.ai\";\n\n/** The REST API's run path, for a model id reached with an account and token. */\nconst REST_API_ORIGIN = \"https://api.cloudflare.com/client/v4/accounts\";\n\n/** The provider-native path, for a model object reached with a token. */\nconst GATEWAY_ORIGIN = \"https://gateway.ai.cloudflare.com/v1\";\n\n/**\n * The `Ai` binding's `fetch`. The binding has one at runtime (workerd's\n * `ai-api.ts`), and aig-entry routes it, but `@cloudflare/workers-types` does\n * not declare it.\n */\ninterface FetchingBinding {\n fetch(input: string, init?: RequestInit): Promise<Response>;\n}\n\n/**\n * The shape of a run-path request body, and of its answer, for a model AI\n * Gateway's `/run` serves. A request in a model's native format is not\n * converted, streams included.\n *\n * @experimental This surface is experimental and may change.\n */\nexport type RunRequestFormat = \"chat-completions\" | \"messages\" | \"responses\";\n\n/** One request on the Cloudflare run path. */\nexport interface TransportRequest {\n /**\n * Model id — a Workers AI id, an AI Gateway catalog id\n * (`<author>/<model>`), or a dynamic route (`dynamic/<route>`).\n */\n model: string;\n /** The provider-shaped request body (`input` on the run path). */\n input: Record<string, unknown>;\n /**\n * The format `input` is in, and that the answer comes back in, for a model\n * AI Gateway's `/run` serves. Defaults to chat completions. A Workers AI\n * model's input is its own, so this is ignored for one.\n */\n format?: RunRequestFormat;\n /** Gateway options for this request. */\n gateway: ResolvedGateway;\n /** Extra request headers, merged last. */\n headers: Record<string, string>;\n /** Abort signal, forwarded to the binding or to `fetch`. */\n signal?: AbortSignal;\n /**\n * Audio for a Workers AI model that takes it as a raw body\n * (`audio: { body, contentType }`, as Deepgram's Nova-3 does). `input`\n * carries the model's other fields. The request goes to Workers AI\n * directly: AI Gateway does not accept the body.\n */\n audio?: RawAudio;\n}\n\n/** Audio bytes and their media type, sent as a request body of their own. */\nexport interface RawAudio {\n bytes: Uint8Array;\n contentType: string;\n}\n\n/**\n * A vendor's own request, sent to AI Gateway's provider-native path:\n * `{gateway}/{provider}/{endpoint}`. Nothing is converted on the way — the\n * method, headers and body are the vendor's — so the answer is the vendor's\n * own response, streams included.\n *\n * @experimental This surface is experimental and may change.\n */\nexport interface NativeRequest {\n /** The gateway provider slug, e.g. `anthropic`. */\n provider: GatewayProviderName | string;\n /** The vendor path after the provider slug, query string included. */\n endpoint: string;\n /** The HTTP method the vendor used. */\n method: string;\n /** The vendor's own request headers. */\n headers: Record<string, string>;\n /** The vendor's request body, untouched: JSON, multipart, or none. */\n body: BodyInit | null | undefined;\n /** Gateway options, sent as `cf-aig-*` headers. */\n gateway: ResolvedGateway;\n /** Abort signal, forwarded to the binding. */\n signal?: AbortSignal;\n}\n\n/**\n * The single code path both backends, the binding and HTTP, implement. Always\n * resolves to a raw `Response`, so streaming and non-streaming calls share one\n * path and nothing is buffered on the caller's behalf.\n *\n * @experimental This surface is experimental and may change.\n */\nexport interface Transport {\n /** A stable identifier for the endpoint, used in error reporting. */\n readonly url: string;\n run(request: TransportRequest): Promise<Response>;\n /**\n * Sends a vendor's own request to AI Gateway's provider-native path. It\n * resolves to the vendor's raw `Response`, error responses included: only\n * the gateway's own failures (a missing gateway, an unpaid account) are\n * lifted, by the caller, because the vendor's own code knows how to read\n * its errors and we do not.\n */\n native(request: NativeRequest): Promise<Response>;\n /**\n * A log id read off the backend itself when the response carried none. The\n * Workers AI binding exposes the last gateway log id as a mutable property,\n * so it is captured per response rather than read late.\n */\n logIdFallback(response: Response): string | undefined;\n}\n\n/**\n * Drops entries whose value is `undefined`. The AI SDK types call headers as\n * `Record<string, string | undefined>`, and an undefined value reaches the\n * binding as the string \"undefined\" rather than as an absent header.\n */\nexport function definedHeaders(\n headers: Record<string, string | undefined> | undefined\n): Record<string, string> {\n const result: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers ?? {})) {\n if (value !== undefined) result[key] = value;\n }\n return result;\n}\n\n/** Copies response headers into a plain object. */\nexport function headersToObject(headers: Headers): Record<string, string> {\n const result: Record<string, string> = {};\n headers.forEach((value, key) => {\n result[key] = value;\n });\n return result;\n}\n\n/**\n * Some run-path responses arrive bare and some wrapped in the Cloudflare API\n * envelope. Unwrap only when the envelope keys are actually present, so a\n * provider payload that happens to have a `result` field is left alone.\n */\nexport function unwrapEnvelope(\n value: unknown,\n context?: { model: string; url: string; status: number }\n): unknown {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n return value;\n }\n const record = value as Record<string, unknown>;\n // A failure envelope may carry no `result` at all, only its errors.\n const failed =\n record.success === false && firstEnvelopeError(record) !== undefined;\n if (failed || (\"success\" in record && \"result\" in record)) {\n if (record.success === true) return record.result;\n // A failure envelope can arrive with a 2xx status. Parsing it as a\n // provider payload would produce an empty result and no diagnostic.\n throw new CloudflareAIError({\n code: classifyStatus(\n context?.status,\n typeof record.name === \"string\" ? record.name : undefined\n ),\n data: value,\n message: errorMessageFrom(value, context?.status),\n model: context?.model ?? \"\",\n requestBodyValues: undefined,\n status: context?.status,\n url: context?.url ?? \"\"\n });\n }\n return value;\n}\n\nfunction firstEnvelopeError(\n record: Record<string, unknown>\n): { code?: unknown; message?: unknown } | undefined {\n // Live gateway responses use `error` (an array of one); the documented\n // Cloudflare envelope uses `errors`. Accept either.\n for (const key of [\"error\", \"errors\"]) {\n const value = record[key];\n if (Array.isArray(value) && value.length > 0) {\n const first = value[0];\n if (first !== null && typeof first === \"object\") {\n return first as { code?: unknown; message?: unknown };\n }\n }\n if (value !== null && typeof value === \"object\" && !Array.isArray(value)) {\n return value as { code?: unknown; message?: unknown };\n }\n }\n return undefined;\n}\n\n/**\n * Pulls a human message out of any of the error envelopes the platform emits:\n * the gateway envelope (`error: [{ code, message }]`), the Workers AI\n * validation envelope (`message`/`description` only), a bare\n * `{ error: \"...\" }`, and the \"Model ID missing\" internal error, which carries\n * only `description`.\n */\nexport function errorMessageFrom(\n body: unknown,\n status: number | undefined\n): string {\n const record =\n body !== null && typeof body === \"object\" && !Array.isArray(body)\n ? (body as Record<string, unknown>)\n : undefined;\n if (record !== undefined) {\n const envelope = firstEnvelopeError(record);\n if (typeof envelope?.message === \"string\") return envelope.message;\n if (typeof record.error === \"string\") return record.error;\n if (typeof record.message === \"string\") return record.message;\n if (typeof record.description === \"string\") return record.description;\n }\n if (typeof body === \"string\" && body !== \"\") return body;\n return `HTTP ${status ?? \"error\"}`;\n}\n\n/** Builds a {@link CloudflareAIError} from a non-2xx run-path response. */\nexport async function errorFromResponse(\n response: Response,\n context: { model: string; url: string; requestBodyValues: unknown }\n): Promise<CloudflareAIError> {\n const text = await response.text().catch(() => \"\");\n let body: unknown = text;\n try {\n body = text === \"\" ? undefined : JSON.parse(text);\n } catch {\n // Not JSON — the raw text is the best message we have.\n }\n const record =\n body !== null && typeof body === \"object\" && !Array.isArray(body)\n ? (body as Record<string, unknown>)\n : undefined;\n const envelopeName =\n typeof record?.name === \"string\" ? record.name : undefined;\n const headers = headersToObject(response.headers);\n return new CloudflareAIError({\n code: classifyStatus(response.status, envelopeName),\n data: body,\n logId: headers[\"cf-aig-log-id\"],\n message: errorMessageFrom(body, response.status),\n model: context.model,\n requestBodyValues: context.requestBodyValues,\n responseBody: text,\n responseHeaders: headers,\n status: response.status,\n url: context.url\n });\n}\n\n/**\n * The gateway options as the `cf-aig-*` request headers AI Gateway reads.\n * The provider-native path has no options object, so every option travels\n * this way; the names are the gateway's own.\n */\nfunction gatewayHeaders(gateway: ResolvedGateway): Record<string, string> {\n const headers: Record<string, string> = {};\n if (gateway.cacheTtl !== undefined) {\n headers[\"cf-aig-cache-ttl\"] = String(gateway.cacheTtl);\n }\n if (gateway.skipCache !== undefined) {\n headers[\"cf-aig-skip-cache\"] = String(gateway.skipCache);\n }\n if (gateway.cacheKey !== undefined) {\n headers[\"cf-aig-cache-key\"] = gateway.cacheKey;\n }\n if (gateway.metadata !== undefined) {\n headers[\"cf-aig-metadata\"] = JSON.stringify(gateway.metadata);\n }\n if (gateway.collectLog !== undefined) {\n headers[\"cf-aig-collect-log\"] = String(gateway.collectLog);\n }\n if (gateway.eventId !== undefined) {\n headers[\"cf-aig-event-id\"] = gateway.eventId;\n }\n if (gateway.requestTimeoutMs !== undefined) {\n headers[\"cf-aig-request-timeout\"] = String(gateway.requestTimeoutMs);\n }\n const retries = gateway.retries;\n if (retries?.maxAttempts !== undefined) {\n headers[\"cf-aig-max-attempts\"] = String(retries.maxAttempts);\n }\n if (retries?.retryDelayMs !== undefined) {\n headers[\"cf-aig-retry-delay\"] = String(retries.retryDelayMs);\n }\n if (retries?.backoff !== undefined) {\n headers[\"cf-aig-backoff\"] = retries.backoff;\n }\n if (gateway.byokAlias !== undefined) {\n headers[\"cf-aig-byok-alias\"] = gateway.byokAlias;\n }\n if (gateway.zdr !== undefined) headers[\"cf-aig-zdr\"] = String(gateway.zdr);\n return headers;\n}\n\n/**\n * The run path's gateway options, and the headers for the ones the binding's\n * `GatewayOptions` type does not define. Both transports use it: the binding\n * takes `gateway` as an options object, HTTP as `cf-aig-*` headers.\n *\n * `byokAlias` reaches `/run` as `cf-aig-byok-alias`, which `/run` reads for a\n * catalog model's stored key. `zdr` is left off: `/run` does not read it, so it\n * applies to provider-native requests only.\n */\nfunction runOptions(request: TransportRequest): {\n gateway: Omit<ResolvedGateway, \"byokAlias\" | \"zdr\">;\n headers: Record<string, string>;\n} {\n const { byokAlias, zdr: _zdr, ...gateway } = request.gateway;\n return {\n gateway,\n headers: {\n ...request.headers,\n ...(byokAlias !== undefined && isCatalogModelId(request.model)\n ? { \"cf-aig-byok-alias\": byokAlias }\n : {})\n }\n };\n}\n\n/**\n * The binding's resume route for the run a response names. Only called for a\n * response {@link withResume} has checked carries `cf-aig-run-id`.\n */\nfunction resumeUrl(\n gatewayId: string,\n response: Response,\n from: number\n): string {\n const runId = response.headers.get(\"cf-aig-run-id\") ?? \"\";\n return `${BINDING_ORIGIN}/ai-gateway/gateways/${encodeURIComponent(\n gatewayId\n )}/run/${encodeURIComponent(runId)}/resume?from=${from}`;\n}\n\n/**\n * A streamed `/run` answer that names its run (`cf-aig-run-id`) resumes from\n * the last complete event if the connection drops; see `resume.ts`. Anything\n * else — a JSON answer, an error, a Workers AI stream with no run id — is\n * returned as it is.\n */\nfunction withResume(\n response: Response,\n request: TransportRequest,\n resume: ResumeFetch\n): Response {\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (\n !response.ok ||\n response.body === null ||\n !contentType.includes(\"text/event-stream\") ||\n response.headers.get(\"cf-aig-run-id\") === null\n ) {\n return response;\n }\n return new Response(\n resumableBody({\n initial: response.body,\n model: request.model,\n resume,\n signal: request.signal,\n url: \"workers-ai-binding\"\n }),\n {\n headers: response.headers,\n status: response.status,\n statusText: response.statusText\n }\n );\n}\n\n/**\n * What `/run` calls each request format in the binding's `openaiEndpoint`\n * option, which `aig-entry` turns into `/run`'s `requestFormat`.\n */\nconst OPENAI_ENDPOINTS: Record<RunRequestFormat, string> = {\n \"chat-completions\": \"/v1/chat/completions\",\n messages: \"/v1/messages\",\n responses: \"/v1/responses\"\n};\n\n/**\n * Whether a parsed body is the gateway's own error envelope rather than a\n * vendor payload — `{ success: false, error: [{ code, message }] }`, named\n * `AiGatewayError`. The gateway answers this for its own failures (no such\n * gateway, unified billing unpaid, provider not configured); everything else\n * on this path is the vendor's own error, which the vendor's provider reads.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function isGatewayErrorEnvelope(json: unknown): boolean {\n if (json === null || typeof json !== \"object\" || Array.isArray(json)) {\n return false;\n }\n const record = json as Record<string, unknown>;\n if (record.name === \"AiGatewayError\") return true;\n if (record.success !== false) return false;\n const errors = record.error ?? record.errors;\n return (\n Array.isArray(errors) &&\n errors.some(\n (entry) =>\n entry !== null &&\n typeof entry === \"object\" &&\n typeof (entry as { message?: unknown }).message === \"string\"\n )\n );\n}\n\n/**\n * Builds a {@link CloudflareAIError} from the gateway's own error envelope, so\n * a gateway failure on the provider-native path classifies and retries exactly as\n * one on the Workers AI run path.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function errorFromGatewayEnvelope(\n body: unknown,\n context: {\n model: string;\n url: string;\n requestBodyValues: unknown;\n status?: number;\n responseHeaders?: Record<string, string>;\n responseBody?: string;\n }\n): CloudflareAIError {\n const record =\n body !== null && typeof body === \"object\" && !Array.isArray(body)\n ? (body as Record<string, unknown>)\n : undefined;\n return new CloudflareAIError({\n code: classifyStatus(\n context.status,\n typeof record?.name === \"string\" ? record.name : \"AiGatewayError\"\n ),\n data: body,\n logId: context.responseHeaders?.[\"cf-aig-log-id\"],\n message: errorMessageFrom(body, context.status),\n model: context.model,\n requestBodyValues: context.requestBodyValues,\n responseBody: context.responseBody,\n responseHeaders: context.responseHeaders,\n status: context.status,\n url: context.url\n });\n}\n\n/**\n * The `Ai` binding narrowed to the raw-response overload. The ambient\n * overloads pick their return type from the model id, and every catalog slug\n * lands on the `Record<string, unknown>` fallback, so the run-path signature\n * is stated explicitly here.\n */\ninterface RawResponseBinding {\n run(\n model: string,\n inputs: Record<string, unknown>,\n options: AiOptions & {\n returnRawResponse: true;\n /**\n * Not in `AiOptions`: the binding forwards every option, and\n * `aig-entry` maps this one onto `/run`'s `requestFormat`.\n */\n openaiEndpoint?: string;\n }\n ): Promise<Response>;\n}\n\n/** The keyless in-Worker backend: `env.AI.run(...)`. */\nfunction bindingTransport(binding: Ai): Transport {\n const raw = binding as unknown as RawResponseBinding;\n // `aiGatewayLogId` is a mutable property on the binding that every\n // concurrent `run` overwrites, so it is snapshotted against the response it\n // belongs to the moment that response arrives. A run that resolves while\n // another is mid-flight can still read the other's id; the window is one\n // microtask rather than the whole request.\n const logIds = new WeakMap<Response, string>();\n return {\n logIdFallback(response) {\n return logIds.get(response);\n },\n async run(request) {\n try {\n if (request.audio !== undefined) {\n // TODO: send this through the gateway once AI Gateway takes a stream\n // body; today the binding refuses one when `gateway` is set.\n return await raw.run(\n request.model,\n {\n ...request.input,\n audio: {\n body: new Response(new Uint8Array(request.audio.bytes)).body,\n contentType: request.audio.contentType\n }\n },\n {\n ...(Object.keys(request.headers).length > 0\n ? { extraHeaders: request.headers }\n : {}),\n returnRawResponse: true,\n signal: request.signal\n }\n );\n }\n // Called as a method, never detached: the binding reads private\n // fields and throws on a detached reference.\n const run = runOptions(request);\n const response = await raw.run(request.model, request.input, {\n ...(Object.keys(run.headers).length > 0\n ? { extraHeaders: run.headers }\n : {}),\n gateway: run.gateway,\n // A Workers AI id goes to Workers AI itself; any other id is served\n // by AI Gateway's `/run`, which reads the body and answers in the\n // format named here. Without it `/run` guesses the format from the\n // body and wraps an answer it cannot place in `{ state, result }`.\n ...(isWorkersAIId(request.model)\n ? {}\n : {\n openaiEndpoint:\n OPENAI_ENDPOINTS[request.format ?? \"chat-completions\"]\n }),\n returnRawResponse: true,\n signal: request.signal\n });\n const resumable = withResume(response, request, (from, signal) =>\n // The binding's own `fetch`; aig-entry serves the resume route for it.\n (binding as unknown as FetchingBinding).fetch(\n resumeUrl(run.gateway.id, response, from),\n { method: \"GET\", signal }\n )\n );\n const logId = binding.aiGatewayLogId;\n if (logId !== null && logId !== undefined) {\n logIds.set(resumable, logId);\n }\n return resumable;\n } catch (error) {\n // `returnRawResponse` resolves with a `Response` for upstream errors,\n // so a throw here means the binding itself failed (e.g. code 3040,\n // out of capacity).\n throw normalizeThrownError(error, {\n model: request.model,\n requestBodyValues: request.input,\n url: \"workers-ai-binding\"\n });\n }\n },\n async native(request) {\n try {\n // `fetch` is the binding's own and is called as a method: aig-entry\n // serves `/ai-gateway/gateways/{gateway}/{provider}/*` for it and\n // forwards the request to the provider-native path unchanged.\n return await (binding as unknown as FetchingBinding).fetch(\n `${BINDING_ORIGIN}/ai-gateway/gateways/${encodeURIComponent(\n request.gateway.id\n )}/${request.provider}/${request.endpoint}`,\n {\n body: request.body ?? null,\n headers: { ...request.headers, ...gatewayHeaders(request.gateway) },\n method: request.method,\n signal: request.signal\n }\n );\n } catch (error) {\n throw normalizeThrownError(error, {\n model: `${request.provider}/${request.endpoint}`,\n requestBodyValues: undefined,\n url: NATIVE_BINDING_URL\n });\n }\n },\n url: \"workers-ai-binding\"\n };\n}\n\n/**\n * Request headers with the credential set last. `Headers` matches names\n * case-insensitively, so a caller's `Authorization` is replaced rather than\n * sent alongside the token.\n */\nfunction withCredential(\n headers: Record<string, string>,\n name: \"authorization\" | \"cf-aig-authorization\",\n token: string\n): Headers {\n const result = new Headers(headers);\n result.set(name, `Bearer ${token}`);\n return result;\n}\n\n/**\n * A Workers AI answer as the binding returns it. The REST API wraps a JSON\n * answer in the `{ success, result }` envelope where the binding returns the\n * bare result, so a successful envelope is unwrapped; anything else is left\n * for the caller, as it is on the binding.\n */\nasync function bareWorkersAIAnswer(response: Response): Promise<Response> {\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (!response.ok || !contentType.includes(\"application/json\")) {\n return response;\n }\n const text = await response.text();\n let body: unknown;\n try {\n body = JSON.parse(text);\n } catch {\n body = undefined;\n }\n const record =\n body !== null && typeof body === \"object\" && !Array.isArray(body)\n ? (body as Record<string, unknown>)\n : undefined;\n const unwrapped =\n record?.success === true && \"result\" in record ? record.result : undefined;\n const headers = new Headers(response.headers);\n headers.delete(\"content-length\");\n return new Response(\n unwrapped === undefined ? text : JSON.stringify(unwrapped),\n { headers, status: response.status, statusText: response.statusText }\n );\n}\n\n/**\n * The HTTP backend, for an account id and API token. A model id goes to the\n * REST API, which serves it with the same `/run` call the binding makes: a\n * Workers AI id on `/ai/run/{model}` with its own input, any other id on the\n * endpoint for its request format with the model in the body. A model object\n * goes to the provider-native path on `gateway.ai.cloudflare.com`, exactly as\n * the binding's `fetch` forwards it.\n *\n * A dropped stream is not resumed: the binding has a resume route, but the\n * public one is not open to every gateway yet.\n */\nfunction httpTransport({ accountId, apiToken }: AccountAccess): Transport {\n const account = encodeURIComponent(accountId);\n const runBase = `${REST_API_ORIGIN}/${account}/ai`;\n /**\n * A raw audio body goes to Workers AI's own run route, with the model's\n * other fields as query parameters. TODO: send it through the gateway once\n * AI Gateway accepts the body; today the REST API answers `500` when\n * `cf-aig-gateway-id` is set.\n */\n async function runRawAudio(\n request: TransportRequest,\n audio: RawAudio\n ): Promise<Response> {\n const query = new URLSearchParams();\n for (const [key, value] of Object.entries(request.input)) {\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n query.set(key, String(value));\n }\n }\n const search = query.size > 0 ? `?${query}` : \"\";\n const url = `${runBase}/run/${request.model}${search}`;\n try {\n const response = await fetch(url, {\n body: new Uint8Array(audio.bytes),\n headers: withCredential(\n { ...request.headers, \"content-type\": audio.contentType },\n \"authorization\",\n apiToken\n ),\n method: \"POST\",\n signal: request.signal\n });\n return await bareWorkersAIAnswer(response);\n } catch (error) {\n throw normalizeThrownError(error, {\n model: request.model,\n requestBodyValues: request.input,\n url\n });\n }\n }\n\n return {\n logIdFallback() {\n return undefined;\n },\n async run(request) {\n if (request.audio !== undefined)\n return runRawAudio(request, request.audio);\n const workersAI = isWorkersAIId(request.model);\n const run = runOptions(request);\n const url = workersAI\n ? `${runBase}/run/${request.model}`\n : `${runBase}${OPENAI_ENDPOINTS[request.format ?? \"chat-completions\"]}`;\n try {\n const response = await fetch(url, {\n body: JSON.stringify(\n workersAI\n ? request.input\n : { ...request.input, model: request.model }\n ),\n headers: withCredential(\n {\n \"content-type\": \"application/json\",\n ...gatewayHeaders(run.gateway),\n \"cf-aig-gateway-id\": run.gateway.id,\n ...run.headers\n },\n \"authorization\",\n apiToken\n ),\n method: \"POST\",\n signal: request.signal\n });\n return workersAI ? await bareWorkersAIAnswer(response) : response;\n } catch (error) {\n throw normalizeThrownError(error, {\n model: request.model,\n requestBodyValues: request.input,\n url\n });\n }\n },\n async native(request) {\n const url = `${GATEWAY_ORIGIN}/${account}/${encodeURIComponent(\n request.gateway.id\n )}/${request.provider}/${request.endpoint}`;\n try {\n return await fetch(url, {\n body: request.body ?? null,\n // A stream body needs `duplex: \"half\"` in Node's fetch, which\n // rejects the request without it. workerd accepts it too.\n ...(request.body instanceof ReadableStream\n ? ({ duplex: \"half\" } as RequestInit)\n : {}),\n headers: withCredential(\n { ...request.headers, ...gatewayHeaders(request.gateway) },\n \"cf-aig-authorization\",\n apiToken\n ),\n method: request.method,\n signal: request.signal\n });\n } catch (error) {\n throw normalizeThrownError(error, {\n model: `${request.provider}/${request.endpoint}`,\n requestBodyValues: undefined,\n url\n });\n }\n },\n url: runBase\n };\n}\n\n/**\n * Builds the transport for a set of provider settings. The model id, not the\n * caller, decides the wire format; the transport only decides how the request\n * physically leaves the Worker.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function createTransport(settings: AISettings): Transport {\n if (settings.binding !== undefined) return bindingTransport(settings.binding);\n if (settings.accountId && settings.apiToken) return httpTransport(settings);\n throw new Error(\n \"createAI requires { binding } (the AI binding) or { accountId, apiToken }.\"\n );\n}\n","/**\n * The AI Gateway provider table: which gateway provider slug a vendor's own\n * base URL belongs to, and what the provider-native `endpoint` is for a\n * given upstream URL.\n *\n * This is platform knowledge, not vendor knowledge — the gateway publishes the\n * list, and every entry here appears in `AIGatewayProviders` from\n * `@cloudflare/workers-types`. Nothing about a vendor's wire format, model ids\n * or capabilities lives here: the vendor's own provider package builds the\n * request, and this table only says where it goes.\n *\n * Adapted from `@cloudflare/ai-gateway-provider`'s `providers.ts`.\n *\n * @experimental This surface is experimental and may change.\n */\n\n/**\n * The gateway provider slugs this table maps onto. A subset of the ambient\n * `AIGatewayProviders` union; {@link GatewayProviderNameCheck} keeps it one.\n */\nexport const GATEWAY_PROVIDER_NAMES = [\n \"workers-ai\",\n \"anthropic\",\n \"openai\",\n \"azure-openai\",\n \"google-ai-studio\",\n \"google-vertex-ai\",\n \"grok\",\n \"mistral\",\n \"perplexity-ai\",\n \"replicate\",\n \"groq\",\n \"deepseek\",\n \"openrouter\",\n \"cerebras\",\n \"cohere\",\n \"huggingface\",\n \"aws-bedrock\",\n \"elevenlabs\",\n \"cartesia\"\n] as const;\n\n/**\n * A gateway provider slug.\n */\nexport type GatewayProviderName = (typeof GATEWAY_PROVIDER_NAMES)[number];\n\n/**\n * Compile-time guard: every slug in this table must exist in the platform's\n * own provider union, so a workers-types bump that renames one fails `tsc`\n * here rather than at runtime with a 404 from the gateway.\n *\n * @internal\n */\nexport type GatewayProviderNameCheck<\n T extends AIGatewayProviders = GatewayProviderName\n> = T;\n\n/**\n * One row of the provider table.\n *\n * @experimental This surface is experimental and may change.\n */\nexport interface GatewayProvider {\n /** The gateway provider slug. */\n readonly name: GatewayProviderName;\n /** Matches the upstream host (`URL.host`), not the whole URL. */\n readonly host: RegExp;\n /**\n * Request headers carrying the vendor's own credential. They are stripped\n * before the request is handed to the gateway, which holds the real key\n * (unified billing or BYOK). Lowercase.\n */\n readonly authHeaders: readonly string[];\n /**\n * The provider-native `endpoint` for an upstream URL: everything after\n * the host, query string included, with the provider's fixed prefix removed.\n * `undefined` when the URL does not belong to this provider.\n */\n endpoint(url: string): string | undefined;\n}\n\n/** The default credential header; providers add their own on top. */\nconst AUTHORIZATION = [\"authorization\"] as const;\n\ninterface ProviderSpec {\n name: GatewayProviderName;\n host: RegExp;\n authHeaders?: readonly string[];\n /** A fixed path prefix stripped from the endpoint. */\n pathPrefix?: RegExp;\n /** A full replacement for the default path mapping. */\n endpoint?: (url: URL) => string | undefined;\n}\n\n/** Path after the host, leading slash removed, query string kept. */\nfunction pathOf(url: URL): string {\n return `${url.pathname.replace(/^\\/+/, \"\")}${url.search}`;\n}\n\nfunction buildProvider(spec: ProviderSpec): GatewayProvider {\n const map =\n spec.endpoint ??\n ((url: URL) => {\n const path = pathOf(url);\n return spec.pathPrefix === undefined\n ? path\n : path.replace(spec.pathPrefix, \"\");\n });\n return {\n authHeaders: spec.authHeaders ?? AUTHORIZATION,\n endpoint(url) {\n const parsed = parseUrl(url);\n if (parsed === undefined || !spec.host.test(parsed.host)) {\n return undefined;\n }\n return map(parsed);\n },\n host: spec.host,\n name: spec.name\n };\n}\n\nfunction parseUrl(url: string): URL | undefined {\n try {\n return new URL(url);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Azure names the deployment in the path; the gateway names it in the\n * endpoint as `<resource>/<deployment>/<rest>`.\n */\nfunction azureEndpoint(url: URL): string | undefined {\n const resource = /^([^.]+)\\.openai\\.azure\\.com$/.exec(url.host)?.[1];\n const rest = /^\\/openai\\/deployments\\/([^/]+)\\/(.+)$/.exec(url.pathname);\n if (resource === undefined || rest === null) return undefined;\n return `${resource}/${rest[1]}/${rest[2]}${url.search}`;\n}\n\n/**\n * Bedrock's region and service live in the host; the gateway wants them as the\n * first two endpoint segments.\n */\nfunction bedrockEndpoint(url: URL): string | undefined {\n const match = /^(bedrock[a-z0-9-]*)\\.([a-z0-9-]+)\\.amazonaws\\.com$/.exec(\n url.host\n );\n if (match === null) return undefined;\n return `${match[1]}/${match[2]}/${pathOf(url)}`;\n}\n\nconst SPECS: ProviderSpec[] = [\n {\n // Workers AI's own API host. `env.AI.run` is this package's path for\n // `@cf/` models; this row exists because the gateway lists the provider,\n // so a model object pointed at that host still resolves.\n host: /^api\\.cloudflare\\.com$/,\n name: \"workers-ai\",\n pathPrefix: /^client\\/v4\\/accounts\\/[^/]+\\/ai\\//\n },\n {\n authHeaders: [\"authorization\", \"x-api-key\"],\n host: /^api\\.anthropic\\.com$/,\n name: \"anthropic\"\n },\n { host: /^api\\.openai\\.com$/, name: \"openai\" },\n {\n authHeaders: [\"authorization\", \"api-key\"],\n endpoint: azureEndpoint,\n host: /^[^.]+\\.openai\\.azure\\.com$/,\n name: \"azure-openai\"\n },\n {\n authHeaders: [\"authorization\", \"x-goog-api-key\"],\n host: /^generativelanguage\\.googleapis\\.com$/,\n name: \"google-ai-studio\"\n },\n {\n host: /^(?:[a-z0-9-]+-)?aiplatform\\.googleapis\\.com$/,\n name: \"google-vertex-ai\"\n },\n { host: /^api\\.x\\.ai$/, name: \"grok\" },\n { host: /^api\\.mistral\\.ai$/, name: \"mistral\" },\n { host: /^api\\.perplexity\\.ai$/, name: \"perplexity-ai\" },\n { host: /^api\\.replicate\\.com$/, name: \"replicate\" },\n {\n host: /^api\\.groq\\.com$/,\n name: \"groq\",\n pathPrefix: /^openai\\/v1\\//\n },\n { host: /^api\\.deepseek\\.com$/, name: \"deepseek\" },\n {\n host: /^openrouter\\.ai$/,\n name: \"openrouter\",\n pathPrefix: /^api\\//\n },\n { host: /^api\\.cerebras\\.ai$/, name: \"cerebras\" },\n { host: /^api\\.cohere\\.(?:ai|com)$/, name: \"cohere\" },\n {\n host: /^(?:api-inference|router)\\.huggingface\\.co$/,\n name: \"huggingface\",\n pathPrefix: /^models\\//\n },\n {\n endpoint: bedrockEndpoint,\n host: /^bedrock.*\\.amazonaws\\.com$/,\n name: \"aws-bedrock\"\n },\n { host: /^api\\.elevenlabs\\.io$/, name: \"elevenlabs\" },\n { host: /^api\\.cartesia\\.ai$/, name: \"cartesia\" }\n];\n\n/**\n * The provider table, in declaration order. Hosts do not overlap, so the order\n * only decides which row a future overlapping host would win.\n *\n * @experimental This surface is experimental and may change.\n */\nexport const GATEWAY_PROVIDERS: readonly GatewayProvider[] =\n SPECS.map(buildProvider);\n\n/**\n * A vendor URL mapped onto the provider-native gateway request.\n *\n * @experimental This surface is experimental and may change.\n */\nexport interface ResolvedGatewayProvider {\n /** The gateway provider slug. */\n provider: GatewayProviderName;\n /** The universal request's `endpoint`. */\n endpoint: string;\n /** Request headers to strip before handing the request to the gateway. */\n authHeaders: readonly string[];\n}\n\n/**\n * The table row for a bare host (`api.anthropic.com`) or for anything a `URL`\n * can be built from. pi-ai models carry a `baseUrl` rather than a full request\n * URL, so both spellings resolve.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function gatewayProviderForHost(\n hostOrUrl: string\n): GatewayProvider | undefined {\n const host = parseUrl(hostOrUrl)?.host ?? hostOf(hostOrUrl);\n if (host === undefined) return undefined;\n return GATEWAY_PROVIDERS.find((provider) => provider.host.test(host));\n}\n\n/** Reads a host out of a bare host, `host/path` or `//host` spelling. */\nfunction hostOf(value: string): string | undefined {\n const host = value.replace(/^\\/\\//, \"\").split(\"/\")[0];\n return host === \"\" ? undefined : host;\n}\n\n/**\n * Maps a vendor request URL onto `{ provider, endpoint, authHeaders }` for the\n * universal gateway request, or `undefined` when the host is not a gateway\n * provider.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function resolveGatewayProvider(\n url: string\n): ResolvedGatewayProvider | undefined {\n const parsed = parseUrl(url);\n if (parsed === undefined) return undefined;\n for (const provider of GATEWAY_PROVIDERS) {\n if (!provider.host.test(parsed.host)) continue;\n const endpoint = provider.endpoint(url);\n if (endpoint === undefined) continue;\n return {\n authHeaders: provider.authHeaders,\n endpoint,\n provider: provider.name\n };\n }\n return undefined;\n}\n\n/**\n * {@link resolveGatewayProvider}, throwing a `TypeError` that names the host\n * and the provider list when the URL belongs to no gateway provider.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function requireGatewayProvider(url: string): ResolvedGatewayProvider {\n const resolved = resolveGatewayProvider(url);\n if (resolved !== undefined) return resolved;\n const host = parseUrl(url)?.host ?? url;\n throw new TypeError(\n `AI Gateway has no provider for ${host}. Requests are routed by host; the supported providers are ${GATEWAY_PROVIDER_NAMES.join(\", \")}.`\n );\n}\n\n/** The host a gateway-shaped base URL points at. */\nconst GATEWAY_HOST = \"gateway.ai.cloudflare.com\";\n\n/**\n * The provider slug of a gateway-shaped base URL —\n * `https://gateway.ai.cloudflare.com/v1/{account}/{gateway}/{slug}`. Generated\n * registries write models that way (pi-ai's Cloudflare AI Gateway catalog\n * leaves the account and gateway as literal placeholders), so the slug is\n * already in the path rather than implied by a vendor host. The account and\n * gateway segments are ignored: the binding has already chosen both.\n */\nfunction gatewayShapedSlug(url: URL): string | undefined {\n if (url.host !== GATEWAY_HOST) return undefined;\n const segments = url.pathname.split(\"/\").filter((part) => part !== \"\");\n if (segments[0] !== \"v1\" || segments.length < 4) return undefined;\n return segments[3];\n}\n\n/**\n * Whether a base URL is written in the gateway's own shape\n * (`https://gateway.ai.cloudflare.com/v1/{account}/{gateway}/{slug}`) rather\n * than as a vendor's. A generated Cloudflare registry writes models that way,\n * and the path after the slug is then the vendor's own, so a caller that\n * derives an endpoint from a base URL has to tell the two apart.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function isGatewayShapedUrl(url: string): boolean {\n return parseUrl(url)?.host === GATEWAY_HOST;\n}\n\nfunction isGatewayProviderName(slug: string): slug is GatewayProviderName {\n return (GATEWAY_PROVIDER_NAMES as readonly string[]).includes(slug);\n}\n\n/**\n * The gateway provider slug a model's base URL belongs to. Two spellings\n * resolve, because two kinds of registry write them:\n *\n * - a vendor's own base URL (`https://api.anthropic.com` → `anthropic`), which\n * is what a provider package configured for the vendor carries;\n * - a gateway-shaped base URL\n * (`https://gateway.ai.cloudflare.com/v1/{account}/{gateway}/anthropic` →\n * `anthropic`), which is what a generated Cloudflare registry carries.\n *\n * A base URL neither shape resolves is a wiring mistake rather than a request\n * failure, so it throws a `TypeError` naming what was not recognised.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function gatewaySlugForBaseUrl(baseUrl: string): GatewayProviderName {\n const url = parseUrl(baseUrl);\n const shaped = url === undefined ? undefined : gatewayShapedSlug(url);\n if (shaped !== undefined) {\n if (isGatewayProviderName(shaped)) return shaped;\n throw new TypeError(\n `AI Gateway has no provider \"${shaped}\" (from ${baseUrl}). The supported providers are ${GATEWAY_PROVIDER_NAMES.join(\", \")}.`\n );\n }\n const provider = gatewayProviderForHost(baseUrl);\n if (provider !== undefined) return provider.name;\n throw new TypeError(\n `AI Gateway has no provider for ${url?.host ?? baseUrl}. Requests are routed by the model's base URL; the supported providers are ${GATEWAY_PROVIDER_NAMES.join(\", \")}.`\n );\n}\n","/**\n * Where a Cloudflare catalog model departs from strict OpenAI chat\n * completions, and how. Every entry is backed by a live capture from the\n * conformance probes (`research/40-*.json`, `41-*.json`); the default for an\n * unknown id is strict OpenAI, so a new conformant model needs no code here.\n *\n * Framework-neutral: both the AI SDK and the pi-ai providers consult this.\n */\n\n/** A request feature that had to be changed or dropped for a model. */\nexport interface CompatWarning {\n feature: string;\n message: string;\n}\n\nexport interface ChatCompletionsQuirks {\n /** Which field carries the output-token cap. OpenAI's current models reject `max_tokens`. */\n maxTokensField: \"max_tokens\" | \"max_completion_tokens\";\n /**\n * How reasoning can be turned off. `chat-template` sends\n * `chat_template_kwargs.enable_thinking = false` (vLLM); `unsupported` drops\n * the request with a warning because the model keeps reasoning regardless.\n */\n reasoningOff: \"chat-template\" | \"unsupported\";\n /**\n * Which `reasoning_effort` levels the model accepts. `openai` is the full\n * set (`minimal` … `xhigh`); `basic` is `low | medium | high`, everything\n * else clamped.\n */\n reasoningEffortLevels: \"openai\" | \"basic\";\n /** Whether `chat_template_kwargs` is accepted at all. */\n chatTemplateKwargs: \"supported\" | \"unsupported\";\n /** Whether `response_format: json_schema` is accepted at all. */\n jsonSchema: \"supported\" | \"unsupported\";\n /** Whether the OpenAI-only `strict` flag belongs on the json_schema envelope. */\n jsonSchemaStrict: boolean;\n /**\n * `tool_choice: \"required\"`. `named-fallback` rewrites it to the single\n * named tool when there is exactly one (glm-4.7-flash answers 400 to\n * `required`, a gateway serialization bug), and drops it otherwise.\n */\n toolChoiceRequired: \"supported\" | \"named-fallback\";\n /** Whether image parts may reference a URL, or must carry inline bytes. */\n imageUrls: \"any\" | \"data-only\";\n /** Whether replayed assistant reasoning (`reasoning_content`) is accepted. */\n reasoningReplay: \"reasoning_content\" | \"drop\";\n /**\n * Whether a `user` turn may directly follow a `tool` turn. Mistral rejects\n * it (\"Unexpected role 'user' after role 'tool'\"), so an empty assistant\n * turn is inserted between them.\n */\n requiresAssistantAfterToolResult: boolean;\n /**\n * What the model accepts as a tool-call id. `alnum-9` is Mistral's rule:\n * exactly nine `[A-Za-z0-9]` characters, anything else is a 400.\n */\n toolCallIds: \"any\" | \"alnum-9\";\n /** A suffix the model echoes on its own id that callers never asked for. */\n modelEchoSuffix: string | undefined;\n /** Whether a replayed assistant turn may carry `content: null`. */\n nullAssistantContent: \"allowed\" | \"empty-string\";\n /**\n * Where the answer lands in a stream once reasoning has been turned off.\n * `reasoning` means the model's streaming parser mislabels the whole answer\n * as reasoning (its non-streaming body is fine), so the normalizer moves\n * those deltas back into `content`.\n */\n reasoningOffStreamLabel: \"content\" | \"reasoning\";\n}\n\nconst STRICT_OPENAI: ChatCompletionsQuirks = {\n chatTemplateKwargs: \"unsupported\",\n imageUrls: \"any\",\n jsonSchema: \"supported\",\n jsonSchemaStrict: false,\n // The field OpenAI's current models require; `max_tokens` is rejected by\n // `openai/gpt-5*` on `/run` (\"Use 'max_completion_tokens' instead\"), and\n // `/run` converts it for every other catalog model.\n maxTokensField: \"max_completion_tokens\",\n modelEchoSuffix: undefined,\n nullAssistantContent: \"allowed\",\n reasoningEffortLevels: \"basic\",\n reasoningOff: \"unsupported\",\n reasoningOffStreamLabel: \"content\",\n reasoningReplay: \"drop\",\n requiresAssistantAfterToolResult: false,\n toolCallIds: \"any\",\n toolChoiceRequired: \"supported\"\n};\n\n/** Workers AI's vLLM front end: what every `@cf/` model has in common. */\nconst WORKERS_AI: ChatCompletionsQuirks = {\n ...STRICT_OPENAI,\n chatTemplateKwargs: \"supported\",\n maxTokensField: \"max_tokens\",\n imageUrls: \"data-only\",\n nullAssistantContent: \"empty-string\",\n reasoningOff: \"chat-template\",\n reasoningReplay: \"reasoning_content\"\n};\n\n/**\n * Longest-prefix overrides. Keep each one evidence-backed (the capture that\n * proves it is named in the comment) and delete it when the platform fixes\n * the deviation.\n */\nconst OVERRIDES: [prefix: string, quirks: Partial<ChatCompletionsQuirks>][] = [\n // 40-demos-...-E1: `tool_choice: \"required\"` + tools → 400 pydantic parse error.\n [\"@cf/zai-org/glm-4.7-flash\", { toolChoiceRequired: \"named-fallback\" }],\n // 40-demos-kimi-k3-G3 / 40-matt-kimi-k2.7-code-G_ctk: enable_thinking=false\n // leaves reasoning on; nothing turns it off.\n [\"@cf/moonshotai/\", { reasoningOff: \"unsupported\" }],\n // 40-demos-gpt-oss-120b-G3: same.\n [\"@cf/openai/\", { reasoningOff: \"unsupported\" }],\n // 40-demos-...-F1/F2/G3/J1: \"chat_template is not supported for Mistral\n // tokenizers\", \"Unexpected role 'user' after role 'tool'\".\n // 40-matt-mistral-small-3.1-24b-instruct-J: \"Tool call id was call_1 but\n // must be a-z, A-Z, 0-9, with a length of 9.\"\n [\n \"@cf/mistralai/\",\n {\n chatTemplateKwargs: \"unsupported\",\n jsonSchema: \"unsupported\",\n reasoningOff: \"unsupported\",\n requiresAssistantAfterToolResult: true,\n toolCallIds: \"alnum-9\"\n }\n ],\n // 40-demos-gemma-4-26b-a4b-it-A: echoes \"@cf/google/gemma-4-26b-a4b-it-external\".\n [\"@cf/google/\", { modelEchoSuffix: \"-external\" }],\n // 41-matt-nemotron-3-120b-a12b-K_emoji / S_usage_s: with enable_thinking=false\n // every streamed token arrives as `delta.reasoning` and `content` stays\n // empty, while the non-streaming body (A0, 40-...-G_ctk) puts the same\n // answer in `content` with `reasoning: null`.\n [\"@cf/nvidia/nemotron-\", { reasoningOffStreamLabel: \"reasoning\" }]\n];\n\n/** The quirks for a catalog id: base profile plus the longest matching override. */\nexport function quirksFor(modelId: string): ChatCompletionsQuirks {\n const base = modelId.startsWith(\"@cf/\") ? WORKERS_AI : STRICT_OPENAI;\n let best: [string, Partial<ChatCompletionsQuirks>] | undefined;\n for (const entry of OVERRIDES) {\n if (\n modelId.startsWith(entry[0]) &&\n (best === undefined || entry[0].length > best[0].length)\n ) {\n best = entry;\n }\n }\n return best === undefined ? base : { ...base, ...best[1] };\n}\n\n/** Whether an id is a Workers AI model rather than a third-party catalog model. */\nexport function isWorkersAI(modelId: string): boolean {\n return modelId.startsWith(\"@cf/\");\n}\n","/**\n * Rewrites a strict OpenAI chat-completions request body into what a given\n * catalog model accepts. Frameworks build the strict body from their own\n * prompt types; everything Cloudflare- or vendor-specific happens here, once.\n *\n * The rewrite never throws: a feature the model cannot take is dropped and\n * reported as a {@link CompatWarning}.\n */\n\nimport { type CompatWarning, quirksFor } from \"./quirks\";\n\nexport interface PreparedRequest {\n body: Record<string, unknown>;\n warnings: CompatWarning[];\n /**\n * Whether the body turns the model's reasoning off through the chat\n * template. The stream normalizer needs this for models whose streaming\n * parser mislabels the answer once thinking is off.\n */\n reasoningOff: boolean;\n}\n\ntype Message = Record<string, unknown>;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction clampEffort(effort: string): string {\n if (effort === \"minimal\") return \"low\";\n if (effort === \"xhigh\") return \"high\";\n return effort;\n}\n\n/** Drops URL image parts (keeps inline data URLs) from a user message. */\nfunction stripImageUrls(message: Message, warnings: CompatWarning[]): Message {\n if (!Array.isArray(message.content)) return message;\n let dropped = 0;\n const content = message.content.filter((part) => {\n if (!isRecord(part) || part.type !== \"image_url\") return true;\n const image = isRecord(part.image_url) ? part.image_url : undefined;\n const url = typeof image?.url === \"string\" ? image.url : \"\";\n if (url.startsWith(\"data:\")) return true;\n dropped += 1;\n return false;\n });\n if (dropped > 0) {\n warnings.push({\n feature: \"image-url\",\n message: `Workers AI models need image bytes; ${dropped} image URL${dropped === 1 ? \" was\" : \"s were\"} dropped.`\n });\n }\n return { ...message, content };\n}\n\n/** Nine `[A-Za-z0-9]` characters: what Mistral accepts as a tool-call id. */\nconst CONFORMANT_TOOL_CALL_ID = /^[0-9A-Za-z]{9}$/;\n\nconst TOOL_CALL_ID_ALPHABET =\n \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n/**\n * A deterministic nine-character id for an original id: the same conversation\n * replayed twice produces the same ids, so a provider cache or a log stays\n * comparable. `salt` is bumped only to break a collision.\n */\nfunction hashedToolCallId(original: string, salt: number): string {\n let state = (0x811c9dc5 ^ salt) >>> 0;\n for (let index = 0; index < original.length; index += 1) {\n state = Math.imul(state ^ original.charCodeAt(index), 0x01000193) >>> 0;\n }\n let id = \"\";\n for (let index = 0; index < 9; index += 1) {\n state = Math.imul(state ^ (state >>> 15), 0x01000193) >>> 0;\n id += TOOL_CALL_ID_ALPHABET[state % TOOL_CALL_ID_ALPHABET.length];\n }\n return id;\n}\n\n/** Every tool-call id a message set mentions, in the order it mentions them. */\nfunction toolCallIdsIn(messages: unknown[]): string[] {\n const ids: string[] = [];\n const seen = new Set<string>();\n const add = (value: unknown) => {\n if (typeof value !== \"string\" || seen.has(value)) return;\n seen.add(value);\n ids.push(value);\n };\n for (const message of messages) {\n if (!isRecord(message)) continue;\n if (Array.isArray(message.tool_calls)) {\n for (const call of message.tool_calls) {\n if (isRecord(call)) add(call.id);\n }\n }\n add(message.tool_call_id);\n }\n return ids;\n}\n\n/**\n * Plans the rewrite: which ids have to change, and to what. Ids that already\n * conform are kept exactly as they are — including as reserved values, so a\n * rewritten id can never collide with one.\n */\nfunction planToolCallIds(messages: unknown[]): Map<string, string> {\n const plan = new Map<string, string>();\n const ids = toolCallIdsIn(messages);\n const taken = new Set(ids.filter((id) => CONFORMANT_TOOL_CALL_ID.test(id)));\n for (const id of ids) {\n if (taken.has(id)) continue;\n let replacement = hashedToolCallId(id, 0);\n for (let salt = 1; taken.has(replacement) && salt <= 64; salt += 1) {\n replacement = hashedToolCallId(id, salt);\n }\n taken.add(replacement);\n plan.set(id, replacement);\n }\n return plan;\n}\n\n/** Applies the plan to an assistant `tool_calls` turn or a `tool` result. */\nfunction rewriteToolCallIds(\n message: Message,\n plan: Map<string, string>\n): Message {\n let rewritten = message;\n if (Array.isArray(rewritten.tool_calls)) {\n rewritten = {\n ...rewritten,\n tool_calls: rewritten.tool_calls.map((call) => {\n if (!isRecord(call) || typeof call.id !== \"string\") return call;\n const replacement = plan.get(call.id);\n return replacement === undefined ? call : { ...call, id: replacement };\n })\n };\n }\n if (typeof rewritten.tool_call_id === \"string\") {\n const replacement = plan.get(rewritten.tool_call_id);\n if (replacement !== undefined) {\n rewritten = { ...rewritten, tool_call_id: replacement };\n }\n }\n return rewritten;\n}\n\n/**\n * Applies the model's quirks to a strict OpenAI chat-completions body.\n *\n * Conventions the strict body follows, which this function translates:\n * - `max_tokens` is the cap; it becomes `max_completion_tokens` where needed.\n * - `reasoning_effort: null` means \"turn reasoning off\".\n * - Replayed assistant reasoning sits in `reasoning_content`.\n * - `response_format.json_schema` is the OpenAI `{ name, schema }` envelope.\n * - `chat_template_kwargs` may be present; it is only meaningful on Workers AI.\n */\nexport function prepareChatCompletionsRequest(\n input: Record<string, unknown>,\n modelId: string\n): PreparedRequest {\n const quirks = quirksFor(modelId);\n const warnings: CompatWarning[] = [];\n const body: Record<string, unknown> = { ...input };\n\n // Output-token cap.\n if (\n quirks.maxTokensField === \"max_completion_tokens\" &&\n \"max_tokens\" in body\n ) {\n body.max_completion_tokens = body.max_tokens;\n delete body.max_tokens;\n }\n\n // Reasoning.\n if (\"reasoning_effort\" in body) {\n const effort = body.reasoning_effort;\n if (effort === null) {\n delete body.reasoning_effort;\n if (quirks.reasoningOff === \"chat-template\") {\n body.chat_template_kwargs = {\n ...(isRecord(body.chat_template_kwargs)\n ? body.chat_template_kwargs\n : {}),\n enable_thinking: false\n };\n } else {\n warnings.push({\n feature: \"reasoning-off\",\n message: `Reasoning cannot be turned off on ${modelId}; the request was sent with the model's default effort.`\n });\n }\n } else if (\n typeof effort === \"string\" &&\n quirks.reasoningEffortLevels === \"basic\"\n ) {\n body.reasoning_effort = clampEffort(effort);\n }\n }\n if (\n \"chat_template_kwargs\" in body &&\n quirks.chatTemplateKwargs === \"unsupported\"\n ) {\n delete body.chat_template_kwargs;\n warnings.push({\n feature: \"chat-template-kwargs\",\n message: `${modelId} does not take chat_template_kwargs; they were dropped.`\n });\n }\n\n // Structured output.\n if (isRecord(body.response_format)) {\n if (quirks.jsonSchema === \"unsupported\") {\n delete body.response_format;\n warnings.push({\n feature: \"response-format\",\n message: `${modelId} does not support response_format; the request was sent without it.`\n });\n } else if (\n body.response_format.type === \"json_schema\" &&\n isRecord(body.response_format.json_schema)\n ) {\n const { strict: _strict, ...envelope } = body.response_format.json_schema;\n body.response_format = {\n ...body.response_format,\n json_schema: quirks.jsonSchemaStrict\n ? { ...envelope, strict: true }\n : envelope\n };\n }\n }\n\n // Tools.\n if (\n body.tool_choice === \"required\" &&\n quirks.toolChoiceRequired === \"named-fallback\"\n ) {\n const tools = Array.isArray(body.tools) ? body.tools : [];\n const only =\n tools.length === 1 && isRecord(tools[0]) ? tools[0] : undefined;\n const name =\n only !== undefined &&\n isRecord(only.function) &&\n typeof only.function.name === \"string\"\n ? only.function.name\n : undefined;\n if (name !== undefined) {\n body.tool_choice = { function: { name }, type: \"function\" };\n } else {\n delete body.tool_choice;\n warnings.push({\n feature: \"tool-choice-required\",\n message: `${modelId} rejects tool_choice \"required\"; the model was left free to choose.`\n });\n }\n }\n\n // Messages.\n if (Array.isArray(body.messages)) {\n // Two passes: the ids are planned over the whole conversation first, so an\n // assistant turn and the tool result answering it are rewritten to the\n // same value however far apart they sit.\n const toolCallIds =\n quirks.toolCallIds === \"alnum-9\"\n ? planToolCallIds(body.messages)\n : new Map<string, string>();\n if (toolCallIds.size > 0) {\n warnings.push({\n feature: \"tool-call-id\",\n message: `${modelId} needs 9-character alphanumeric tool-call ids; ${toolCallIds.size} id${toolCallIds.size === 1 ? \" was\" : \"s were\"} rewritten.`\n });\n }\n const messages: Message[] = [];\n let previousRole: unknown;\n for (const entry of body.messages) {\n if (!isRecord(entry)) continue;\n let message: Message = entry;\n if (toolCallIds.size > 0) {\n message = rewriteToolCallIds(message, toolCallIds);\n }\n if (message.role === \"user\" && quirks.imageUrls === \"data-only\") {\n message = stripImageUrls(message, warnings);\n }\n if (\n message.role === \"assistant\" &&\n message.content === null &&\n quirks.nullAssistantContent === \"empty-string\"\n ) {\n // 41-demos-gpt-oss-120b-O_replay_null: a replayed assistant turn with\n // `content: null` is a 400 on Workers AI; `\"\"` is accepted everywhere.\n message = { ...message, content: \"\" };\n }\n if (message.role === \"assistant\" && \"reasoning_content\" in message) {\n if (quirks.reasoningReplay === \"drop\") {\n const { reasoning_content: _reasoning, ...rest } = message;\n message = rest;\n warnings.push({\n feature: \"assistant-reasoning\",\n message: `${modelId} has no field for replayed reasoning; the assistant reasoning was dropped.`\n });\n }\n }\n if (\n quirks.requiresAssistantAfterToolResult &&\n previousRole === \"tool\" &&\n message.role === \"user\"\n ) {\n messages.push({ content: \"\", role: \"assistant\" });\n }\n messages.push(message);\n previousRole = message.role;\n }\n body.messages = messages;\n }\n\n const reasoningOff =\n isRecord(body.chat_template_kwargs) &&\n body.chat_template_kwargs.enable_thinking === false;\n return { body, reasoningOff, warnings };\n}\n","/**\n * Normalizes a chat-completions response body from the run path into the\n * strict OpenAI `chat.completion` shape, so framework parsers never see\n * Workers AI's native envelope or its field spellings.\n */\n\nimport { quirksFor } from \"./quirks\";\n\ntype Record_ = Record<string, unknown>;\n\nfunction isRecord(value: unknown): value is Record_ {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/** Native `{ name, arguments: object }` → OpenAI `{ id, type, function }`. */\nexport function normalizeToolCall(\n entry: unknown,\n index: number\n): Record_ | undefined {\n if (!isRecord(entry)) return undefined;\n const fn = isRecord(entry.function) ? entry.function : undefined;\n const name =\n typeof fn?.name === \"string\"\n ? fn.name\n : typeof entry.name === \"string\"\n ? entry.name\n : undefined;\n if (name === undefined) return undefined;\n const rawArguments =\n fn !== undefined && \"arguments\" in fn ? fn.arguments : entry.arguments;\n const args =\n typeof rawArguments === \"string\"\n ? rawArguments\n : rawArguments === undefined || rawArguments === null\n ? \"{}\"\n : JSON.stringify(rawArguments);\n return {\n ...(typeof entry.index === \"number\" ? { index: entry.index } : { index }),\n ...(typeof entry.id === \"string\" ? { id: entry.id } : {}),\n function: { arguments: args, name },\n type: \"function\",\n ...(entry.extra_content !== undefined\n ? { extra_content: entry.extra_content }\n : {})\n };\n}\n\n/** Text as the model produced it; structured-output models may return an object. */\nfunction contentText(value: unknown): string | null {\n if (typeof value === \"string\") return value;\n if (value === null || value === undefined) return null;\n return JSON.stringify(value);\n}\n\nfunction stripEchoSuffix(model: unknown, modelId: string): unknown {\n const suffix = quirksFor(modelId).modelEchoSuffix;\n if (typeof model !== \"string\" || suffix === undefined) return model;\n return model.endsWith(suffix) ? model.slice(0, -suffix.length) : model;\n}\n\n/** Puts reasoning under `reasoning_content` whichever spelling the model used. */\nfunction normalizeMessage(message: Record_): Record_ {\n const out: Record_ = { ...message };\n const reasoning =\n typeof out.reasoning_content === \"string\" && out.reasoning_content !== \"\"\n ? out.reasoning_content\n : typeof out.reasoning === \"string\" && out.reasoning !== \"\"\n ? out.reasoning\n : undefined;\n delete out.reasoning;\n if (reasoning !== undefined) out.reasoning_content = reasoning;\n else delete out.reasoning_content;\n if (\"content\" in out) out.content = contentText(out.content);\n if (Array.isArray(out.tool_calls)) {\n const calls = out.tool_calls\n .map((call, index) => normalizeToolCall(call, index))\n .filter((call): call is Record_ => call !== undefined);\n if (calls.length > 0) out.tool_calls = calls;\n else delete out.tool_calls;\n }\n return out;\n}\n\n/**\n * Returns the body in the strict `chat.completion` shape. Already-OpenAI\n * bodies come back with their reasoning spelling unified and the echoed model\n * id cleaned; native Workers AI `{ response, tool_calls, usage }` bodies are\n * lifted into `choices[0]`.\n */\nexport function normalizeChatCompletion(\n body: unknown,\n modelId: string\n): Record_ {\n if (!isRecord(body)) return { choices: [] };\n if (Array.isArray(body.choices)) {\n const choices = body.choices.map((choice) => {\n if (!isRecord(choice)) return choice;\n const message = isRecord(choice.message)\n ? normalizeMessage(choice.message)\n : choice.message;\n const hasToolCalls =\n isRecord(message) &&\n Array.isArray(message.tool_calls) &&\n message.tool_calls.length > 0;\n return {\n ...choice,\n message,\n finish_reason:\n choice.finish_reason ?? (hasToolCalls ? \"tool_calls\" : \"stop\")\n };\n });\n return { ...body, choices, model: stripEchoSuffix(body.model, modelId) };\n }\n if (\"response\" in body || \"tool_calls\" in body) {\n const toolCalls = Array.isArray(body.tool_calls)\n ? body.tool_calls\n .map((call, index) => normalizeToolCall(call, index))\n .filter((call): call is Record_ => call !== undefined)\n : [];\n const { response, tool_calls: _toolCalls, usage, ...rest } = body;\n return {\n ...rest,\n choices: [\n {\n finish_reason:\n typeof body.finish_reason === \"string\"\n ? body.finish_reason\n : toolCalls.length > 0\n ? \"tool_calls\"\n : \"stop\",\n index: 0,\n message: {\n content: contentText(response),\n role: \"assistant\",\n ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {})\n }\n }\n ],\n model: stripEchoSuffix(body.model, modelId),\n ...(usage !== undefined ? { usage } : {})\n };\n }\n return body;\n}\n","/**\n * Translates an Anthropic Messages SSE stream into `chat.completion.chunk`\n * events.\n *\n * AI Gateway's `/run` converts a chat-completions request into a catalog\n * model's native format, and converts a non-streamed answer back. On its\n * legacy runtime it does not convert a stream back\n * (`compat/run-compat.ts`: \"a streaming legacy request gets the connector's\n * native stream format\"), so a streamed Claude catalog model answers in\n * Anthropic events even though chat completions was asked for. This bridges\n * that gap until the gateway converts streams; once it does, no Anthropic\n * event arrives and this code never runs.\n *\n * Detection is by shape: an event with a string `type` and no `choices` is an\n * Anthropic event. A chat-completions chunk always has `choices` and no\n * `type`, so a stream that is already chat completions passes untouched.\n */\n\ntype Record_ = Record<string, unknown>;\n\nfunction isRecord(value: unknown): value is Record_ {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/** Anthropic's stop reasons, as chat-completions finish reasons. */\nconst FINISH_REASONS: Record<string, string> = {\n end_turn: \"stop\",\n max_tokens: \"length\",\n pause_turn: \"stop\",\n refusal: \"content_filter\",\n stop_sequence: \"stop\",\n tool_use: \"tool_calls\"\n};\n\n/** Whether a parsed SSE payload is an Anthropic Messages event. */\nexport function isAnthropicEvent(event: Record_): boolean {\n return typeof event.type === \"string\" && !(\"choices\" in event);\n}\n\n/**\n * A stateful translator for one stream. Returns the chat-completions chunks\n * an Anthropic event becomes — possibly none — or `undefined` for an event\n * that is not Anthropic, which the caller handles as it is.\n */\nexport function createAnthropicStreamTranslator(): (\n event: Record_\n) => Record_[] | undefined {\n let id: string | undefined;\n let model: string | undefined;\n let inputTokens = 0;\n let outputTokens = 0;\n let cachedTokens = 0;\n // Content block index → tool-call index, for tool_use blocks.\n const toolIndexes = new Map<number, number>();\n\n const chunk = (delta: Record_, finishReason: string | null = null) => ({\n choices: [{ delta, finish_reason: finishReason, index: 0 }],\n ...(id === undefined ? {} : { id }),\n ...(model === undefined ? {} : { model }),\n object: \"chat.completion.chunk\"\n });\n\n return (event) => {\n if (!isAnthropicEvent(event)) return undefined;\n switch (event.type) {\n case \"message_start\": {\n const message = isRecord(event.message) ? event.message : {};\n if (typeof message.id === \"string\") id = message.id;\n if (typeof message.model === \"string\") model = message.model;\n const usage = isRecord(message.usage) ? message.usage : {};\n const cacheRead = Number(usage.cache_read_input_tokens ?? 0) || 0;\n const cacheWrite = Number(usage.cache_creation_input_tokens ?? 0) || 0;\n inputTokens =\n (Number(usage.input_tokens ?? 0) || 0) + cacheRead + cacheWrite;\n cachedTokens = cacheRead;\n outputTokens = Number(usage.output_tokens ?? 0) || 0;\n return [chunk({ role: \"assistant\" })];\n }\n case \"content_block_start\": {\n const block = isRecord(event.content_block) ? event.content_block : {};\n const index = Number(event.index ?? 0);\n if (block.type !== \"tool_use\") return [];\n const toolIndex = toolIndexes.size;\n toolIndexes.set(index, toolIndex);\n return [\n chunk({\n tool_calls: [\n {\n function: {\n arguments: \"\",\n name: typeof block.name === \"string\" ? block.name : \"\"\n },\n id: typeof block.id === \"string\" ? block.id : undefined,\n index: toolIndex,\n type: \"function\"\n }\n ]\n })\n ];\n }\n case \"content_block_delta\": {\n const delta = isRecord(event.delta) ? event.delta : {};\n if (delta.type === \"text_delta\" && typeof delta.text === \"string\") {\n return [chunk({ content: delta.text })];\n }\n if (\n delta.type === \"thinking_delta\" &&\n typeof delta.thinking === \"string\"\n ) {\n return [chunk({ reasoning_content: delta.thinking })];\n }\n if (\n delta.type === \"input_json_delta\" &&\n typeof delta.partial_json === \"string\"\n ) {\n const toolIndex = toolIndexes.get(Number(event.index ?? 0));\n if (toolIndex === undefined) return [];\n return [\n chunk({\n tool_calls: [\n {\n function: { arguments: delta.partial_json },\n index: toolIndex\n }\n ]\n })\n ];\n }\n // signature_delta and anything newer carry nothing chat completions\n // can express.\n return [];\n }\n case \"message_delta\": {\n const usage = isRecord(event.usage) ? event.usage : {};\n if (typeof usage.output_tokens === \"number\") {\n outputTokens = usage.output_tokens;\n }\n const delta = isRecord(event.delta) ? event.delta : {};\n const stop =\n typeof delta.stop_reason === \"string\" ? delta.stop_reason : undefined;\n if (stop === undefined) return [];\n return [chunk({}, FINISH_REASONS[stop] ?? \"stop\")];\n }\n case \"message_stop\":\n return [\n {\n choices: [],\n ...(id === undefined ? {} : { id }),\n ...(model === undefined ? {} : { model }),\n object: \"chat.completion.chunk\",\n usage: {\n completion_tokens: outputTokens,\n prompt_tokens: inputTokens,\n ...(cachedTokens > 0\n ? { prompt_tokens_details: { cached_tokens: cachedTokens } }\n : {}),\n total_tokens: inputTokens + outputTokens\n }\n }\n ];\n case \"error\": {\n const error = isRecord(event.error) ? event.error : {};\n return [\n {\n error: {\n message:\n typeof error.message === \"string\"\n ? error.message\n : \"The model's stream ended with an error.\",\n type: typeof error.type === \"string\" ? error.type : \"error\"\n }\n }\n ];\n }\n default:\n // ping, content_block_stop, and event types added later.\n return [];\n }\n };\n}\n","/**\n * Normalizes a chat-completions SSE stream from the run path into strict\n * OpenAI `chat.completion.chunk` events.\n *\n * Every Workers AI model streams the same three-part hybrid (live captures,\n * all families): OpenAI-shaped delta chunks that each carry a per-delta\n * `usage`, then a `choices: []` heartbeat, then a native\n * `{ response: \"\", usage }` tail with the cumulative usage, then `[DONE]`.\n * Some models also emit native `{ response: \"<text>\" }` deltas or top-level\n * `tool_calls`. After this transform a consumer sees only:\n *\n * - delta chunks without per-delta usage and with reasoning under\n * `reasoning_content`;\n * - at most one final `choices: []` chunk carrying the cumulative usage\n * (the OpenAI `stream_options.include_usage` shape);\n * - a `finish_reason` on some chunk before the end, synthesized when the\n * model finished cleanly without sending one;\n * - `[DONE]`.\n *\n * Input and output are SSE `data` payloads (strings), so it slots between the\n * SSE decoder and either framework's OpenAI chunk parser.\n */\n\nimport { createAnthropicStreamTranslator } from \"./anthropic-stream\";\nimport { isWorkersAI, quirksFor } from \"./quirks\";\nimport { normalizeToolCall } from \"./response\";\n\ntype Record_ = Record<string, unknown>;\n\nfunction isRecord(value: unknown): value is Record_ {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nconst NOISE_FIELDS = [\n \"p\",\n \"token_ids\",\n \"prompt_token_ids\",\n \"kv_transfer_params\"\n];\n\n/** Fields the run path adds to every chunk that mean nothing to a consumer. */\nfunction stripNoise(chunk: Record_): Record_ {\n const out = { ...chunk };\n for (const key of NOISE_FIELDS) delete out[key];\n return out;\n}\n\nfunction stripEchoSuffix(chunk: Record_, modelId: string): Record_ {\n const suffix = quirksFor(modelId).modelEchoSuffix;\n if (suffix === undefined || typeof chunk.model !== \"string\") return chunk;\n return chunk.model.endsWith(suffix)\n ? { ...chunk, model: chunk.model.slice(0, -suffix.length) }\n : chunk;\n}\n\nfunction normalizeDelta(delta: Record_, relabelReasoning: boolean): Record_ {\n const out: Record_ = { ...delta };\n const reasoning =\n typeof out.reasoning_content === \"string\" && out.reasoning_content !== \"\"\n ? out.reasoning_content\n : typeof out.reasoning === \"string\" && out.reasoning !== \"\"\n ? out.reasoning\n : undefined;\n delete out.reasoning;\n delete out.reasoning_content;\n if (reasoning !== undefined) {\n if (relabelReasoning) {\n // Reasoning is off, so these tokens are the answer (nemotron-3).\n out.content =\n (typeof out.content === \"string\" ? out.content : \"\") + reasoning;\n } else {\n out.reasoning_content = reasoning;\n }\n }\n if (Array.isArray(out.tool_calls)) {\n out.tool_calls = out.tool_calls.map((call, index) => {\n // Fragments and the null finalizer pass through untouched; only a\n // native complete call needs lifting into the OpenAI shape. A native\n // call names its tool at the top level, where no OpenAI fragment does,\n // and its arguments may be an object or already a string.\n if (!isRecord(call)) return call;\n const fn = isRecord(call.function) ? call.function : undefined;\n const args = fn !== undefined ? fn.arguments : call.arguments;\n const native = fn === undefined && typeof call.name === \"string\";\n return native || isRecord(args)\n ? (normalizeToolCall(call, index) ?? call)\n : call;\n });\n }\n return out;\n}\n\nexport interface StreamNormalizationOptions {\n /** Whether the request turned reasoning off (`PreparedRequest.reasoningOff`). */\n reasoningOff?: boolean;\n}\n\n/**\n * The transform. Backpressure is preserved: nothing is buffered except the\n * single pending usage chunk, which must wait for the tail.\n */\nexport function normalizeChatCompletionsStream(\n modelId: string,\n options: StreamNormalizationOptions = {}\n): TransformStream<string, string> {\n const quirks = quirksFor(modelId);\n const relabelReasoning =\n options.reasoningOff === true &&\n quirks.reasoningOffStreamLabel === \"reasoning\";\n let id: string | undefined;\n let model: string | undefined;\n let created: number | undefined;\n let sawFinishReason = false;\n let sawContent = false;\n let sawToolCalls = false;\n let sawDone = false;\n let finalUsage: unknown;\n let finalUsageTemplate: Record_ | undefined;\n // Workers AI stamps a per-delta usage on every content chunk and sends the\n // cumulative figure in its native tail; other vendors only ever put usage on\n // the final `choices: []` chunk, so theirs is left alone.\n const perDeltaUsage = isWorkersAI(modelId);\n const translateAnthropic = createAnthropicStreamTranslator();\n\n const envelope = (extra: Record_): Record_ => ({\n ...(id !== undefined ? { id } : {}),\n object: \"chat.completion.chunk\",\n ...(created !== undefined ? { created } : {}),\n ...(model !== undefined ? { model } : {}),\n ...extra\n });\n\n const emit = (\n controller: TransformStreamDefaultController<string>,\n chunk: Record_\n ) => {\n controller.enqueue(JSON.stringify(chunk));\n };\n\n const emitTail = (controller: TransformStreamDefaultController<string>) => {\n if (!sawFinishReason && sawDone && (sawContent || sawToolCalls)) {\n emit(\n controller,\n envelope({\n choices: [\n {\n delta: {},\n finish_reason: sawToolCalls ? \"tool_calls\" : \"stop\",\n index: 0\n }\n ]\n })\n );\n sawFinishReason = true;\n }\n if (finalUsage !== undefined) {\n emit(controller, {\n ...(finalUsageTemplate ?? envelope({})),\n choices: [],\n usage: finalUsage\n });\n finalUsage = undefined;\n }\n if (sawDone) controller.enqueue(\"[DONE]\");\n };\n\n /** Normalizes one chat-completions chunk (or native Workers AI event). */\n const handle = (\n parsed: Record_,\n controller: TransformStreamDefaultController<string>\n ): void => {\n const chunk = stripEchoSuffix(stripNoise(parsed), modelId);\n\n if (typeof chunk.id === \"string\") id ??= chunk.id;\n if (typeof chunk.model === \"string\") model ??= chunk.model;\n if (typeof chunk.created === \"number\") created ??= chunk.created;\n\n // An error payload passes through untouched for the consumer to surface;\n // it also ends the generation, so no finish reason is synthesized after it.\n if (isRecord(chunk.error)) {\n sawFinishReason = true;\n controller.enqueue(JSON.stringify(chunk));\n return;\n }\n\n if (Array.isArray(chunk.choices)) {\n if (chunk.choices.length === 0) {\n // Heartbeat, or OpenAI's own final usage chunk: hold the usage\n // until the end so exactly one usage chunk is emitted.\n if (isRecord(chunk.usage)) {\n finalUsage = chunk.usage;\n finalUsageTemplate = { ...chunk, usage: undefined };\n delete finalUsageTemplate.usage;\n }\n return;\n }\n const choices = chunk.choices.map((choice) => {\n if (!isRecord(choice)) return choice;\n if (typeof choice.finish_reason === \"string\") sawFinishReason = true;\n const delta = isRecord(choice.delta)\n ? normalizeDelta(choice.delta, relabelReasoning)\n : choice.delta;\n if (isRecord(delta)) {\n if (typeof delta.content === \"string\" && delta.content !== \"\")\n sawContent = true;\n if (typeof delta.reasoning_content === \"string\") sawContent = true;\n if (Array.isArray(delta.tool_calls) && delta.tool_calls.length > 0)\n sawToolCalls = true;\n }\n if (!perDeltaUsage) return { ...choice, delta };\n const { usage: _perDeltaUsage, ...rest } = choice;\n return { ...rest, delta };\n });\n if (perDeltaUsage) {\n // The cumulative figure comes with the native tail.\n const { usage: _usage, ...rest } = chunk;\n emit(controller, { ...rest, choices });\n } else {\n emit(controller, { ...chunk, choices });\n }\n return;\n }\n\n // Native Workers AI events.\n if (\"response\" in chunk || \"tool_calls\" in chunk) {\n const text = chunk.response;\n const hasText = typeof text === \"string\" && text !== \"\";\n const calls = Array.isArray(chunk.tool_calls)\n ? chunk.tool_calls\n .map((call, index) => normalizeToolCall(call, index))\n .filter((call): call is Record_ => call !== undefined)\n : [];\n if (hasText || calls.length > 0) {\n if (hasText) sawContent = true;\n if (calls.length > 0) sawToolCalls = true;\n emit(\n controller,\n envelope({\n choices: [\n {\n delta: {\n ...(hasText ? { content: text } : {}),\n ...(calls.length > 0 ? { tool_calls: calls } : {})\n },\n finish_reason: null,\n index: 0\n }\n ]\n })\n );\n }\n if (isRecord(chunk.usage)) {\n // The native tail: cumulative usage for the whole stream.\n finalUsage = chunk.usage;\n finalUsageTemplate = undefined;\n }\n if (typeof chunk.finish_reason === \"string\") {\n sawFinishReason = true;\n emit(\n controller,\n envelope({\n choices: [\n { delta: {}, finish_reason: chunk.finish_reason, index: 0 }\n ]\n })\n );\n }\n }\n };\n\n return new TransformStream<string, string>({\n flush(controller) {\n emitTail(controller);\n },\n transform(data, controller) {\n if (data === \"\") return;\n if (data === \"[DONE]\") {\n // Everything after the tail is emitted at flush, once.\n sawDone = true;\n return;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(data);\n } catch {\n // A malformed event is dropped rather than failing the stream.\n return;\n }\n if (!isRecord(parsed)) return;\n // A streamed Claude catalog model answers in Anthropic events; they\n // become chat-completions chunks first, then normalize like any other.\n for (const event of translateAnthropic(parsed) ?? [parsed]) {\n handle(event, controller);\n }\n }\n });\n}\n","/**\n * Decodes a `text/event-stream` byte stream into the `data` payload of each\n * event, as a `TransformStream` so the whole pipeline keeps backpressure and\n * nothing is ever buffered beyond the current event.\n *\n * Handles all three line terminators the SSE spec allows (LF, CRLF and a bare\n * CR), multi-line `data:` fields (joined with `\\n`, per the spec), comment\n * lines (`:` prefixed), and non-`data` fields (`event:`, `id:`, `retry:`),\n * which are ignored. A trailing event that the server never terminated with a\n * blank line is still flushed.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function sseDataStream(): TransformStream<Uint8Array, string> {\n const decoder = new TextDecoder();\n let buffer = \"\";\n let data: string[] = [];\n\n const flushEvent = (controller: TransformStreamDefaultController<string>) => {\n if (data.length === 0) return;\n controller.enqueue(data.join(\"\\n\"));\n data = [];\n };\n\n const consumeLine = (\n line: string,\n controller: TransformStreamDefaultController<string>\n ) => {\n if (line === \"\") {\n flushEvent(controller);\n return;\n }\n if (line.startsWith(\":\")) return;\n const colon = line.indexOf(\":\");\n const field = colon === -1 ? line : line.slice(0, colon);\n if (field !== \"data\") return;\n let value = colon === -1 ? \"\" : line.slice(colon + 1);\n if (value.startsWith(\" \")) value = value.slice(1);\n data.push(value);\n };\n\n /**\n * Consumes whole lines out of the buffer. A buffer ending in a lone `\\r` is\n * held back while more bytes may arrive, because the next byte decides\n * whether that `\\r` was a CRLF pair or a bare-CR terminator.\n */\n const drain = (\n controller: TransformStreamDefaultController<string>,\n final: boolean\n ) => {\n for (;;) {\n const match = /\\r\\n|[\\r\\n]/.exec(buffer);\n if (match === null) break;\n const end = match.index + match[0].length;\n if (!final && match[0] === \"\\r\" && end === buffer.length) break;\n consumeLine(buffer.slice(0, match.index), controller);\n buffer = buffer.slice(end);\n }\n };\n\n return new TransformStream<Uint8Array, string>({\n flush(controller) {\n buffer += decoder.decode();\n drain(controller, true);\n // A server that closed without a final blank line still owes us the\n // last event; emit whatever is left rather than dropping it.\n if (buffer !== \"\") {\n consumeLine(buffer, controller);\n buffer = \"\";\n }\n flushEvent(controller);\n },\n transform(chunk, controller) {\n buffer += decoder.decode(chunk, { stream: true });\n drain(controller, false);\n }\n });\n}\n","/**\n * Workers AI text-to-image requests and answers, shared by both framework\n * modules.\n *\n * Two things about this catalog are easy to get wrong in one module and right\n * in the other, so neither module owns them: the flux-1 models take a two-key\n * subset of the common input shape, and the media type of a JSON answer is in\n * the bytes rather than in the model name (flux-1-schnell answers JPEG while\n * every other model here answers PNG).\n *\n * @experimental This surface is experimental and may change.\n */\n\nimport type { CompatWarning } from \"./chat-completions\";\n\n/**\n * `flux-1-schnell` takes `{ prompt, steps }` and nothing else — no size, no\n * seed, no guidance. Sending those anyway would be silently ignored, so they\n * come back as warnings instead.\n *\n * @see https://developers.cloudflare.com/workers-ai/models/flux-1-schnell/\n */\nconst PROMPT_AND_STEPS_ONLY = /^@cf\\/black-forest-labs\\/flux-1/;\n\n/**\n * The generation knobs Workers AI text-to-image models share, in this\n * package's own spelling. Each module maps its own call options onto them.\n *\n * @experimental This surface is experimental and may change.\n */\nexport interface ImageGenerationSettings {\n width?: number;\n height?: number;\n /** Diffusion steps. Sent as `num_steps`, or `steps` on the flux-1 models. */\n steps?: number;\n /** Classifier-free guidance scale. */\n guidance?: number;\n /** How strongly img2img transforms the input image, between 0 and 1. */\n strength?: number;\n negativePrompt?: string;\n seed?: number;\n /**\n * Whether the caller has a source image to attach. The field it goes in\n * differs per module, so only the warning is decided here.\n */\n sourceImage?: boolean;\n /** Whether the caller has an inpainting mask to attach. */\n mask?: boolean;\n}\n\n/**\n * A run-path image body with the knobs the model could not take reported.\n *\n * @experimental This surface is experimental and may change.\n */\nexport interface BuiltImageRequest {\n input: Record<string, unknown>;\n warnings: CompatWarning[];\n /**\n * The model takes `{ prompt, steps }` only, so the caller must not attach a\n * source image or a mask either.\n */\n minimal: boolean;\n}\n\n/**\n * Builds the run-path body for a text-to-image model: `prompt`, `width`,\n * `height`, `num_steps`, `guidance`, `strength`, `negative_prompt` and `seed`,\n * or the flux-1 two-key subset with a warning for everything dropped.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function buildImageInput(\n modelId: string,\n prompt: string,\n settings: ImageGenerationSettings\n): BuiltImageRequest {\n const warnings: CompatWarning[] = [];\n const input: Record<string, unknown> = { prompt };\n\n if (PROMPT_AND_STEPS_ONLY.test(modelId)) {\n if (settings.steps !== undefined) input.steps = settings.steps;\n for (const [feature, value] of [\n [\"size\", settings.width ?? settings.height],\n [\"seed\", settings.seed],\n [\"guidance\", settings.guidance],\n [\"negativePrompt\", settings.negativePrompt],\n [\"strength\", settings.strength],\n [\"files\", settings.sourceImage === true ? true : undefined],\n [\"mask\", settings.mask === true ? true : undefined]\n ] as const) {\n if (value !== undefined) {\n warnings.push({\n feature,\n message: `${modelId} takes only a prompt and steps.`\n });\n }\n }\n return { input, minimal: true, warnings };\n }\n\n if (settings.width !== undefined) input.width = settings.width;\n if (settings.height !== undefined) input.height = settings.height;\n if (settings.seed !== undefined) input.seed = settings.seed;\n if (settings.steps !== undefined) input.num_steps = settings.steps;\n if (settings.guidance !== undefined) input.guidance = settings.guidance;\n if (settings.strength !== undefined) input.strength = settings.strength;\n if (settings.negativePrompt !== undefined) {\n input.negative_prompt = settings.negativePrompt;\n }\n return { input, minimal: false, warnings };\n}\n\nconst JPEG_PREFIX = \"/9j/\";\nconst PNG_PREFIX = \"iVBORw0KGgo\";\nconst WEBP_PREFIX = \"UklGR\";\nconst GIF_PREFIX = \"R0lGOD\";\n\n/**\n * Sniffs an image media type from the head of its base64. The bytes decide,\n * never the model name: `flux-1-schnell` answers JPEG where every other model\n * in this catalog answers PNG.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function imageMediaTypeOf(base64: string): string {\n if (base64.startsWith(JPEG_PREFIX)) return \"image/jpeg\";\n if (base64.startsWith(PNG_PREFIX)) return \"image/png\";\n if (base64.startsWith(W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tools/input-schema.ts"],"sourcesContent":["/**\n * The zod input schema shared by the AI SDK and TanStack AI adapters. Kept\n * out of the core so the pi adapter, which uses TypeBox, does not need zod.\n * Internal — not an entry point.\n */\nimport { z } from \"zod\";\nimport {\n MAX_WEB_SEARCH_QUERY_LENGTH,\n type WebSearchToolInput\n} from \"../contract\";\n\n/**\n * The model's input schema. The description tells the model the host's\n * `limit`; a larger value is not rejected (which would cost a validation\n * round trip) but capped by the core.\n */\nexport function webSearchInputSchema(maxLimit: number) {\n return z.object({\n query: z\n .string()\n .min(1)\n .max(MAX_WEB_SEARCH_QUERY_LENGTH)\n .describe(\"What to search for.\"),\n limit: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(`How many results to return (at most ${maxLimit}).`)\n }) satisfies z.ZodType<WebSearchToolInput>;\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,SAAgB,qBAAqB,UAAkB;CACrD,OAAO,EAAE,OAAO;EACd,OAAO,EACJ,OAAO,CAAC,CACR,IAAI,CAAC,CAAC,CACN,IAAI,2BAA2B,CAAC,CAChC,SAAS,qBAAqB;EACjC,OAAO,EACJ,OAAO,CAAC,CACR,IAAI,CAAC,CACL,IAAI,CAAC,CAAC,CACN,SAAS,CAAC,CACV,SAAS,uCAAuC,SAAS,GAAG;CACjE,CAAC;AACH"}