agents 0.30.0 → 0.31.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 (130) hide show
  1. package/README.md +4 -2
  2. package/dist/{agent-routing-CDbpVjYq.d.ts → agent-routing-wS1TimZ_.d.ts} +64 -603
  3. package/dist/agent-routing.d.ts +1 -1
  4. package/dist/agent-tool-types.d.ts +1 -1
  5. package/dist/{agent-tools-C8DH8Yii.d.ts → agent-tools-Bamxxb6Y.d.ts} +2 -2
  6. package/dist/agent-tools.d.ts +1 -1
  7. package/dist/{ai-iXw0uOGj.d.ts → ai-CDn3Abax.d.ts} +30 -4
  8. package/dist/{ai-sdk-DRPh2rRa.js → ai-sdk-Kon40i0q.js} +2 -36
  9. package/dist/ai-sdk-Kon40i0q.js.map +1 -0
  10. package/dist/ai-sdk-hW3vntnk.d.ts +72 -0
  11. package/dist/browser/ai.d.ts +1 -1
  12. package/dist/browser/ai.js +16 -3
  13. package/dist/browser/ai.js.map +1 -1
  14. package/dist/browser/index.d.ts +64 -16
  15. package/dist/browser/index.js +4 -4
  16. package/dist/browser/tools/ai-sdk.d.ts +7 -70
  17. package/dist/browser/tools/ai-sdk.js +4 -4
  18. package/dist/browser/tools/ai-sdk.js.map +1 -1
  19. package/dist/browser/tools/pi.d.ts +9 -15
  20. package/dist/browser/tools/pi.js +6 -14
  21. package/dist/browser/tools/pi.js.map +1 -1
  22. package/dist/browser/tools/tanstack-ai.d.ts +46 -23
  23. package/dist/browser/tools/tanstack-ai.js +8 -4
  24. package/dist/browser/tools/tanstack-ai.js.map +1 -1
  25. package/dist/{browser-DccPw_wW.js → browser-1eUbPvC2.js} +413 -14
  26. package/dist/browser-1eUbPvC2.js.map +1 -0
  27. package/dist/{browser-DlXhSAdf.d.ts → browser-D9RNpJuT.d.ts} +254 -20
  28. package/dist/browser-tool-BhjCcNVE.d.ts +71 -0
  29. package/dist/browser-tool-lGnvEBLJ.js +497 -0
  30. package/dist/browser-tool-lGnvEBLJ.js.map +1 -0
  31. package/dist/capability-id-B3J8Nok_.js +13 -0
  32. package/dist/capability-id-B3J8Nok_.js.map +1 -0
  33. package/dist/chat/index.d.ts +2 -2
  34. package/dist/chat-sdk/index.d.ts +3 -3
  35. package/dist/chat-sdk/index.js +1 -1
  36. package/dist/client-4OlMIJx-.js.map +1 -1
  37. package/dist/{client-BnYbNT3z.js → client-DMWujQJ1.js} +68 -244
  38. package/dist/client-DMWujQJ1.js.map +1 -0
  39. package/dist/{client-C27CtRZr.d.ts → client-wn4-yqGz.d.ts} +9 -7
  40. package/dist/client.d.ts +1 -1
  41. package/dist/{connector-DAXBOIIi.js → connector-CM-uuxKM.js} +96 -8
  42. package/dist/connector-CM-uuxKM.js.map +1 -0
  43. package/dist/{connector-20DJ6p4k.d.ts → connector-DZ71EjE-.d.ts} +109 -9
  44. package/dist/experimental/webmcp.js +1 -1
  45. package/dist/{handler-stateless-Bly_nSH3.js → handler-stateless-B5hU3dxK.js} +35 -2
  46. package/dist/handler-stateless-B5hU3dxK.js.map +1 -0
  47. package/dist/{handler-stateless-DxYpJ_XF.d.ts → handler-stateless-C90kD5_R.d.ts} +3 -47
  48. package/dist/harness/container/index.d.ts +15 -15
  49. package/dist/harness/opencode/index.js.map +1 -1
  50. package/dist/harness/pi/index.d.ts +7 -3
  51. package/dist/harness/pi/index.js +46 -15
  52. package/dist/harness/pi/index.js.map +1 -1
  53. package/dist/harness/think/index.d.ts +2 -1
  54. package/dist/{images-xaDv2Fqe.js → images-CfuRCjwq.js} +1 -5
  55. package/dist/images-CfuRCjwq.js.map +1 -0
  56. package/dist/{index-DCxk3OSJ.d.ts → index-8k4qsX1T.d.ts} +2 -28
  57. package/dist/index.d.ts +14 -14
  58. package/dist/index.js +2 -2
  59. package/dist/internal-hosts-Kfp5A392.d.ts +230 -0
  60. package/dist/internal-kmw70xwR.js.map +1 -1
  61. package/dist/invoker-BC1SZ3q1.js +26 -0
  62. package/dist/invoker-BC1SZ3q1.js.map +1 -0
  63. package/dist/invoker-DoLFPJZV.d.ts +21 -0
  64. package/dist/mcp/client/index.d.ts +15 -1
  65. package/dist/mcp/client/index.js +2 -2
  66. package/dist/mcp/client/x402.d.ts +7 -5
  67. package/dist/mcp/client/x402.js +34 -1
  68. package/dist/mcp/client/x402.js.map +1 -1
  69. package/dist/mcp/index.d.ts +561 -27
  70. package/dist/mcp/index.js +180 -3
  71. package/dist/mcp/index.js.map +1 -1
  72. package/dist/mcp/server/index.d.ts +1 -1
  73. package/dist/mcp/server/index.js +1 -1
  74. package/dist/models/ai-sdk/index.d.ts +2 -2
  75. package/dist/models/ai-sdk/index.js +1 -1
  76. package/dist/models/opencode/index.d.ts +2 -2
  77. package/dist/models/opencode/index.js +1 -1
  78. package/dist/models/pi-ai/index.d.ts +3 -28
  79. package/dist/models/pi-ai/index.js +31 -16
  80. package/dist/models/pi-ai/index.js.map +1 -1
  81. package/dist/protocol-BEgrJYC5.d.ts +29 -29
  82. package/dist/react.d.ts +2 -2
  83. package/dist/routing/index.d.ts +1 -1
  84. package/dist/serializable.d.ts +1 -1
  85. package/dist/{session-store-yvwq1f9x.js → session-7CDgVE0z.js} +455 -33
  86. package/dist/session-7CDgVE0z.js.map +1 -0
  87. package/dist/{session-store-_IK6dV-w.d.ts → session-store-B7Ca-u1t.d.ts} +8 -1
  88. package/dist/settings-Dk2il2Hf.js.map +1 -1
  89. package/dist/{src-DfLzdwlK.js → src-BGolXG_H.js} +18 -2
  90. package/dist/src-BGolXG_H.js.map +1 -0
  91. package/dist/sub-routing.d.ts +12 -12
  92. package/dist/tool-CTp72Jb_.d.ts +10 -10
  93. package/dist/tool-DoVberpN.d.ts +22 -22
  94. package/dist/tool-helpers-BodWi4gd.js +256 -0
  95. package/dist/tool-helpers-BodWi4gd.js.map +1 -0
  96. package/dist/{transport-CPh7YGiw.d.ts → transport-5moD2pW5.d.ts} +1 -43
  97. package/dist/types-D2naO3rA.d.ts +49 -0
  98. package/dist/voice/index.d.ts +1 -1
  99. package/dist/workflow-types.d.ts +1 -1
  100. package/dist/workflows.d.ts +1 -1
  101. package/dist/workflows.js +1 -1
  102. package/docs/browse-the-web.md +247 -413
  103. package/docs/get-current-agent.md +4 -7
  104. package/docs/harnesses/pi.md +28 -28
  105. package/docs/human-in-the-loop.md +3 -7
  106. package/docs/index.md +6 -6
  107. package/docs/mcp-client.md +4 -28
  108. package/docs/mcp-servers.md +137 -411
  109. package/docs/mcp-transports.md +30 -289
  110. package/docs/models-pi-ai.md +9 -11
  111. package/docs/models.md +1 -8
  112. package/docs/routing.md +0 -2
  113. package/docs/securing-mcp-servers.md +120 -304
  114. package/package.json +8 -3
  115. package/dist/ai-sdk-DRPh2rRa.js.map +0 -1
  116. package/dist/browser-DccPw_wW.js.map +0 -1
  117. package/dist/browser-tool-B1mhifin.js +0 -616
  118. package/dist/browser-tool-B1mhifin.js.map +0 -1
  119. package/dist/browser-tool-Cxjk5sgG.d.ts +0 -92
  120. package/dist/client-BnYbNT3z.js.map +0 -1
  121. package/dist/connector-DAXBOIIi.js.map +0 -1
  122. package/dist/handler-stateless-Bly_nSH3.js.map +0 -1
  123. package/dist/images-xaDv2Fqe.js.map +0 -1
  124. package/dist/invoker-CG0_p_Wq.d.ts +0 -20
  125. package/dist/invoker-CHMnoxIA.js +0 -57
  126. package/dist/invoker-CHMnoxIA.js.map +0 -1
  127. package/dist/session-store-yvwq1f9x.js.map +0 -1
  128. package/dist/src-DfLzdwlK.js.map +0 -1
  129. package/dist/tool-helpers-O5BDVEAY.js +0 -58
  130. package/dist/tool-helpers-O5BDVEAY.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"ai-sdk-DRPh2rRa.js","names":["CoreCloudflareAIError","coreErrorFromGatewayEnvelope","coreUnwrapEnvelope","coreErrorFromResponse","createCoreTransport","unsupported","exhaustive"],"sources":["../src/models/ai-sdk/errors.ts","../src/models/ai-sdk/settings.ts","../src/models/ai-sdk/transport.ts","../src/models/ai-sdk/models/fallback.ts","../src/models/ai-sdk/wires/shared.ts","../src/models/ai-sdk/models/embedding.ts","../src/models/ai-sdk/wires/chat-completions.ts","../src/models/ai-sdk/models/language.ts","../src/models/ai-sdk/models/gateway.ts","../src/models/ai-sdk/models/modality.ts","../src/models/ai-sdk/models/image.ts","../src/models/ai-sdk/models/reranking.ts","../src/models/ai-sdk/models/speech.ts","../src/models/ai-sdk/models/transcription.ts","../src/models/ai-sdk/index.ts"],"sourcesContent":["import { APICallError } from \"@ai-sdk/provider\";\nimport {\n isCatalogModelId,\n isDynamicRouteId,\n isRunPathLanguageModelId\n} from \"../core/catalog\";\nimport {\n type CloudflareAIAttempt,\n type CloudflareAIErrorCode,\n CloudflareAIError as CoreCloudflareAIError,\n isRetryableStatus,\n normalizeThrownError as normalizeCoreError\n} from \"../core/errors\";\n\nexport {\n classifyStatus,\n isAbortError,\n isRetryableStatus,\n type CloudflareAIAttempt,\n type CloudflareAIErrorCode\n} from \"../core/errors\";\n\n/**\n * The error a string that names no model this provider runs produces.\n * Language models take Workers AI ids, AI Gateway catalog ids and dynamic\n * routes; the modality methods take Workers AI ids only.\n */\nexport function notAModelId(\n modelId: string,\n accepts: \"language\" | \"workers-ai\"\n): TypeError {\n return new TypeError(\n accepts === \"language\"\n ? `\"${modelId}\" is not a model id this provider knows. Use a Workers AI id (\"@cf/zai-org/glm-4.7-flash\"), an AI Gateway catalog id (\"<author>/<model>\", e.g. \"openai/gpt-5.5\" or \"anthropic/claude-opus-4.8\"), or a dynamic route (\"dynamic/<route>\").`\n : `\"${modelId}\" is not a Workers AI model id. The embedding, image, speech, transcription and reranking methods take Workers AI ids, which start with \"@cf/\".`\n );\n}\n\n/**\n * The gate for the modality methods — embedding, image, speech,\n * transcription, reranking — and their fallback legs: a Workers AI id and\n * nothing else. Catalog models and dynamic routes are chat models here.\n */\nexport function requireWorkersAIId<Id extends string>(modelId: Id): Id {\n if (isDynamicRouteId(modelId)) {\n throw new TypeError(\n `\"${modelId}\" is an AI Gateway dynamic route, and a dynamic route is a chat model: it answers in the chat-completions shape. Use it as ai(\"${modelId}\"); the embedding, image, speech, transcription and reranking methods take \"@cf/\" ids.`\n );\n }\n if (!modelId.startsWith(\"@cf/\")) throw notAModelId(modelId, \"workers-ai\");\n return modelId;\n}\n\n/** Whether a string names a language model: any of the three id kinds. */\nfunction isLanguageModelId(modelId: string): boolean {\n return isRunPathLanguageModelId(modelId) || isCatalogModelId(modelId);\n}\n\n/**\n * The gate every string that names a language model passes through, wherever\n * it enters the module: `ai(\"…\")`, a per-model fallback leg, or a leg read\n * out of the per-call `providerOptions.cloudflare` bag. All three kinds run on\n * `env.AI.run`. Thrown at the line that supplied the id rather than at the\n * request it would have made.\n */\nexport function requireLanguageModelId<Id extends string>(modelId: Id): Id {\n if (!isLanguageModelId(modelId)) throw notAModelId(modelId, \"language\");\n return modelId;\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.\n *\n * Extends the AI SDK's `APICallError` so `ai`'s built-in retry loop honours\n * {@link CloudflareAIError.isRetryable} without any extra wiring.\n *\n * @experimental This surface is experimental and may change.\n */\nexport class CloudflareAIError extends APICallError {\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 /** Every leg tried, when this error ends a fallback chain. */\n readonly attempts: CloudflareAIAttempt[] | undefined;\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({\n cause: options.cause,\n data: options.data,\n isRetryable: options.isRetryable ?? isRetryableStatus(options.status),\n message: options.message,\n requestBodyValues: options.requestBodyValues,\n responseBody: options.responseBody,\n responseHeaders: options.responseHeaders,\n statusCode: options.status,\n url: options.url\n });\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.attempts = options.attempts;\n }\n\n /** Lifts the framework-neutral core error into the AI SDK error type. */\n static fromCore(error: CoreCloudflareAIError): CloudflareAIError {\n return new CloudflareAIError({\n attempts: error.attempts,\n cause: error.cause,\n code: error.code,\n data: error.data,\n isRetryable: error.isRetryable,\n logId: error.logId,\n message: error.message,\n model: error.model,\n requestBodyValues: error.requestBodyValues,\n responseBody: error.responseBody,\n responseHeaders: error.responseHeaders,\n status: error.status,\n url: error.url\n });\n }\n}\n\n/**\n * Converts whatever the core transport threw into what AI SDK callers expect:\n * core errors become {@link CloudflareAIError}s; everything else passes\n * through untouched.\n */\nexport function toAISDKError(error: unknown): unknown {\n return error instanceof CoreCloudflareAIError\n ? CloudflareAIError.fromCore(error)\n : error;\n}\n\n/**\n * Normalizes a thrown Workers AI binding error into a {@link CloudflareAIError}.\n * Abort errors and errors that are already `APICallError`s pass through.\n */\nexport function normalizeThrownError(\n error: unknown,\n context: Parameters<typeof normalizeCoreError>[1]\n): unknown {\n if (APICallError.isInstance(error)) return error;\n return toAISDKError(normalizeCoreError(error, context));\n}\n","import type {\n LanguageModelV4,\n LanguageModelV4CallOptions,\n SharedV4ProviderOptions\n} from \"@ai-sdk/provider\";\nimport type {\n CatalogModelId,\n DynamicRouteId,\n WorkersAIModelId\n} from \"../core/catalog\";\nimport {\n type ModelOptions as CoreModelOptions,\n PROVIDER_OPTIONS_KEY,\n parseModelOptions\n} from \"../core/settings\";\nimport { requireLanguageModelId, requireWorkersAIId } from \"./errors\";\n\nexport {\n DEFAULT_GATEWAY_ID,\n PROVIDER_OPTIONS_KEY,\n gatewayLayerOf,\n mergeModelOptions,\n parseModelOptions,\n resolveOptions,\n type AISettings,\n type GatewayOptions,\n type ProviderGatewaySettings,\n type ResolvedGateway,\n type ResolvedOptions\n} from \"../core/settings\";\n\n/**\n * A language model id: a Workers AI id, an AI Gateway catalog id\n * (`<author>/<model>`), or a dynamic route (`dynamic/<route>`). All three run\n * on `env.AI.run`.\n *\n * @experimental This surface is experimental and may change.\n */\nexport type CloudflareLanguageModelId =\n | WorkersAIModelId\n | DynamicRouteId\n | (CatalogModelId & {});\n\n/**\n * One leg of a fallback chain: a language model id, or any AI SDK language\n * model — which is routed through AI Gateway like `ai(model)`.\n *\n * @experimental This surface is experimental and may change.\n */\nexport type FallbackLeg = CloudflareLanguageModelId | LanguageModelV4;\n\n/**\n * Per-model and per-call options: the framework-neutral options, with the\n * fallback leg type this module accepts.\n *\n * @experimental This surface is experimental and may change.\n */\nexport type ModelOptions = CoreModelOptions<FallbackLeg>;\n\n/**\n * Which key authenticates a vendor model object routed through AI Gateway.\n *\n * @experimental This surface is experimental and may change.\n */\nexport interface VendorKeyOptions {\n /**\n * `\"gateway\"` (the default) strips the key the vendor's provider put on the\n * request, so the gateway supplies one: Unified Billing, or a BYOK key\n * stored on the gateway. `\"request\"` forwards that key to the vendor, for a\n * key you hold yourself, e.g. `createAnthropic({ apiKey: env.ANTHROPIC_KEY })`.\n *\n * It belongs to the model it is set on, so a fallback leg keeps its own.\n */\n vendorKey?: \"gateway\" | \"request\";\n}\n\n/**\n * The options accepted next to a model object — `ai(anthropic(\"…\"), { … })`.\n * {@link ModelOptions} plus {@link VendorKeyOptions.vendorKey}; the\n * Workers-AI-only knobs (`reasoningEffort`, `chatTemplateKwargs`) are ignored\n * with a warning.\n *\n * @experimental This surface is experimental and may change.\n */\nexport type GatewayModelOptions = ModelOptions & VendorKeyOptions;\n\n/**\n * The options `ai.routed()` takes: the gateway options, `headers`,\n * `sessionAffinity` and `vendorKey`.\n *\n * A routed embedding, image, speech or transcription model is the vendor's\n * own, and only its transport is ours — there is no chain to fall back through\n * and no Workers AI reasoning knob to apply. They are absent from the type\n * rather than dropped at runtime, so the mistake is a compile error naming the\n * option.\n *\n * @experimental This surface is experimental and may change.\n */\nexport type RoutedModelOptions = Omit<\n ModelOptions,\n \"fallback\" | \"reasoningEffort\" | \"chatTemplateKwargs\"\n> &\n VendorKeyOptions;\n\n/**\n * The options the Workers-AI-only methods take — `ai.embedding`, `ai.image`,\n * `ai.speech`, `ai.transcription`, `ai.reranking`.\n *\n * Their fallback legs are ids: those models run through the Workers AI run\n * path, which resolves a leg by id, so a model object would type-check and\n * then be silently dropped.\n *\n * @experimental This surface is experimental and may change.\n */\nexport type ModalityOptions = CoreModelOptions<WorkersAIModelId>;\n\n/**\n * The fallback legs for one call, in the caller's order. Precedence matches\n * the rest of the option merge: a per-call list replaces the per-model one\n * rather than extending it.\n */\nexport function fallbackLegs(\n model: ModelOptions | undefined,\n call: ModelOptions | undefined\n): FallbackLeg[] {\n return call?.fallback ?? model?.fallback ?? [];\n}\n\n/**\n * Reads per-call options out of AI SDK `providerOptions.cloudflare`.\n *\n * This is the one place the untyped per-call bag enters the module, so it is\n * where the \"`@cf/` ids only\" rule is enforced for the fallback legs a caller\n * wrote there: `parseModelOptions` is framework-neutral and drops rather than\n * throws, and no type ever sees that JSON. A vendor id in a leg would\n * otherwise reach `env.AI.run` — the path a vendor model must never take.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function parseCallOptions(\n providerOptions: SharedV4ProviderOptions | undefined\n): ModelOptions | undefined {\n const options = parseModelOptions(providerOptions?.[PROVIDER_OPTIONS_KEY]);\n for (const leg of options?.fallback ?? []) requireLanguageModelId(leg);\n return options;\n}\n\n/**\n * Per-call options for the modality models — embedding, image, speech,\n * transcription, reranking. The same bag as {@link parseCallOptions}, but a\n * fallback leg must be a Workers AI id: a dynamic route answers in the\n * chat-completions shape, which none of those models can read.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function parseModalityCallOptions(\n providerOptions: SharedV4ProviderOptions | undefined\n): ModalityOptions | undefined {\n const options = parseModelOptions(providerOptions?.[PROVIDER_OPTIONS_KEY]);\n for (const leg of options?.fallback ?? []) requireWorkersAIId(leg);\n return options;\n}\n\n/**\n * The options each model this provider built was built with.\n *\n * A `WeakMap` rather than a field: `createAI` needs to read a leg's own bag\n * back when it layers a fallback chain's gateway options over it, and that is\n * this module's business rather than part of any model's public shape.\n */\nconst MODEL_OPTIONS = new WeakMap<object, GatewayModelOptions>();\n\n/** Records the options a model of this provider was built with. */\nexport function rememberOptions(\n model: object,\n options: GatewayModelOptions | undefined\n): void {\n if (options !== undefined) MODEL_OPTIONS.set(model, options);\n}\n\n/** The options a model of this provider was built with, if it is one. */\nexport function optionsOf(model: unknown): GatewayModelOptions | undefined {\n return model !== null && typeof model === \"object\"\n ? MODEL_OPTIONS.get(model)\n : undefined;\n}\n\n/**\n * The per-call options a fallback leg is asked with: everything the caller\n * sent, minus the fallback list itself.\n *\n * Every leg here is a model object, so a leg that read the same\n * `providerOptions.cloudflare.fallback` would build the whole chain again —\n * once per leg, each of those re-expanding in turn. The rest of the per-call\n * bag stays, so a leg still honours a per-call `cacheTtl` or gateway id.\n */\nexport function withoutCallFallback(\n options: LanguageModelV4CallOptions\n): LanguageModelV4CallOptions {\n const providerOptions = options.providerOptions;\n const ours = providerOptions?.[PROVIDER_OPTIONS_KEY];\n if (ours === undefined || !(\"fallback\" in ours)) return options;\n const bag = { ...ours };\n delete bag.fallback;\n return {\n ...options,\n providerOptions: { ...providerOptions, [PROVIDER_OPTIONS_KEY]: bag }\n };\n}\n","import type { AISettings } from \"../core/settings\";\nimport {\n type Transport as CoreTransport,\n createTransport as createCoreTransport,\n errorFromGatewayEnvelope as coreErrorFromGatewayEnvelope,\n errorFromResponse as coreErrorFromResponse,\n unwrapEnvelope as coreUnwrapEnvelope\n} from \"../core/transport\";\nimport { CloudflareAIError, toAISDKError } from \"./errors\";\n\nexport {\n definedHeaders,\n errorMessageFrom,\n headersToObject,\n isGatewayErrorEnvelope,\n type NativeRequest,\n type TransportRequest\n} from \"../core/transport\";\n\n/**\n * The typed AI SDK error for the gateway's own error envelope — a missing\n * gateway, an unpaid account — on the provider-native path.\n */\nexport function errorFromGatewayEnvelope(\n body: unknown,\n context: Parameters<typeof coreErrorFromGatewayEnvelope>[1]\n): CloudflareAIError {\n return CloudflareAIError.fromCore(\n coreErrorFromGatewayEnvelope(body, context)\n );\n}\n\n/**\n * The transport this module uses: the run path for a model id, and the\n * provider-native path for a vendor's own model object, through the binding\n * or over HTTP.\n *\n * @experimental This surface is experimental and may change.\n */\nexport type Transport = CoreTransport;\n\n/**\n * Unwraps the Cloudflare `{ success, result }` envelope, throwing an AI SDK\n * {@link CloudflareAIError} for a failed envelope.\n */\nexport function unwrapEnvelope(\n value: unknown,\n context?: Parameters<typeof coreUnwrapEnvelope>[1]\n): unknown {\n try {\n return coreUnwrapEnvelope(value, context);\n } catch (error) {\n throw toAISDKError(error);\n }\n}\n\n/** The typed AI SDK error for a non-2xx response. */\nexport async function errorFromResponse(\n response: Response,\n context: Parameters<typeof coreErrorFromResponse>[1]\n): Promise<CloudflareAIError> {\n return CloudflareAIError.fromCore(\n await coreErrorFromResponse(response, context)\n );\n}\n\n/**\n * Builds the transport for a set of provider settings, with every failure\n * lifted into the AI SDK error type.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function createTransport(settings: AISettings): Transport {\n const inner = createCoreTransport(settings);\n return {\n logIdFallback: (response) => inner.logIdFallback(response),\n async native(request) {\n try {\n return await inner.native(request);\n } catch (error) {\n throw toAISDKError(error);\n }\n },\n async run(request) {\n try {\n return await inner.run(request);\n } catch (error) {\n throw toAISDKError(error);\n }\n },\n url: inner.url\n };\n}\n","/**\n * Client-side fallback across models: the primary is tried first, then each\n * fallback in order, when a call fails before producing output. Shared by the\n * language and embedding models.\n */\n\nimport {\n APICallError,\n type LanguageModelV4StreamPart,\n type LanguageModelV4StreamResult\n} from \"@ai-sdk/provider\";\nimport {\n classifyStatus,\n CloudflareAIError,\n isAbortError,\n type CloudflareAIAttempt\n} from \"../errors\";\n\n/** One leg of a fallback chain: a name for reporting, and how to run it. */\nexport interface FallbackAttempt<T> {\n /** The model id reported for this leg in errors and attempt lists. */\n model: string;\n run(): PromiseLike<T>;\n}\n\n/**\n * Runs each leg in order until one answers. Legs may be anything — a model id\n * this provider owns, or a whole other `LanguageModelV4` — because a leg is\n * only ever a name and a thunk here.\n */\nexport async function withFallbackLegs<T>(\n legs: FallbackAttempt<T>[],\n url: string\n): Promise<T> {\n const attempts: CloudflareAIAttempt[] = [];\n let lastError: unknown;\n for (const leg of legs) {\n try {\n return await leg.run();\n } catch (error) {\n if (isAbortError(error)) throw error;\n attempts.push({ error, model: leg.model });\n lastError = error;\n }\n }\n if (attempts.length <= 1) throw lastError;\n throw fallbackError(lastError, attempts, url);\n}\n\n/**\n * The parts a stream emits before it has said anything: protocol preamble\n * that every leg would repeat. Anything else is output the caller has seen,\n * after which the leg is committed and a later failure is its own.\n */\nconst PREAMBLE_PARTS = new Set<LanguageModelV4StreamPart[\"type\"]>([\n \"stream-start\",\n \"response-metadata\",\n \"text-start\",\n \"reasoning-start\",\n \"tool-input-start\",\n \"raw\"\n]);\n\n/**\n * {@link withFallbackLegs} for streams. A 2xx that then fails before any\n * output — an `error` part, an error finish, or a broken body — is still a\n * failed leg, so the next one is tried; the preamble the failed leg sent is\n * dropped and the answering leg's own is delivered instead. Once a leg has\n * produced output it is the answer, failures and all.\n */\nexport async function withStreamFallbackLegs(\n legs: FallbackAttempt<LanguageModelV4StreamResult>[],\n url: string\n): Promise<LanguageModelV4StreamResult> {\n if (legs.length <= 1) return withFallbackLegs(legs, url);\n const attempts: CloudflareAIAttempt[] = [];\n let lastError: unknown;\n for (const leg of legs) {\n let result: LanguageModelV4StreamResult;\n try {\n result = await leg.run();\n } catch (error) {\n if (isAbortError(error)) throw error;\n attempts.push({ error, model: leg.model });\n lastError = error;\n continue;\n }\n const reader = result.stream.getReader();\n const preamble: LanguageModelV4StreamPart[] = [];\n let failure: unknown;\n let committed = false;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n committed = true;\n break;\n }\n if (value.type === \"error\") {\n failure = value.error;\n break;\n }\n if (value.type === \"finish\" && value.finishReason.unified === \"error\") {\n failure = streamFailure(leg.model, url, value.finishReason.raw);\n break;\n }\n preamble.push(value);\n if (!PREAMBLE_PARTS.has(value.type)) {\n committed = true;\n break;\n }\n }\n } catch (error) {\n if (isAbortError(error)) throw error;\n failure = error;\n }\n if (!committed) {\n await reader.cancel().catch(() => undefined);\n attempts.push({ error: failure, model: leg.model });\n lastError = failure;\n continue;\n }\n return { ...result, stream: resumed(preamble, reader) };\n }\n if (attempts.length <= 1) throw lastError;\n throw fallbackError(lastError, attempts, url);\n}\n\n/** The parts already read, then the rest of the stream, as one stream. */\nfunction resumed<T>(\n head: T[],\n reader: ReadableStreamDefaultReader<T>\n): ReadableStream<T> {\n return new ReadableStream<T>({\n cancel(reason) {\n return reader.cancel(reason);\n },\n async pull(controller) {\n const { done, value } = await reader.read();\n if (done) controller.close();\n else controller.enqueue(value);\n },\n start(controller) {\n for (const part of head) controller.enqueue(part);\n }\n });\n}\n\n/** A stream that ended in an error finish before it produced anything. */\nfunction streamFailure(\n model: string,\n url: string,\n raw: string | undefined\n): CloudflareAIError {\n return new CloudflareAIError({\n code: \"provider-error\",\n isRetryable: false,\n message: `The stream from ${model} ended in an error before producing any output${raw === undefined ? \"\" : ` (${raw})`}.`,\n model,\n requestBodyValues: undefined,\n url\n });\n}\n\nexport async function withFallback<T>(\n primary: string,\n fallback: string[],\n url: string,\n run: (modelId: string) => Promise<T>\n): Promise<T> {\n return withFallbackLegs(\n [primary, ...fallback].map((modelId) => ({\n model: modelId,\n run: () => run(modelId)\n })),\n url\n );\n}\n\n/** Rebuilds the last error with the whole attempt chain attached. */\nfunction fallbackError(\n lastError: unknown,\n attempts: CloudflareAIAttempt[],\n url: string\n): unknown {\n const models = attempts.map((attempt) => attempt.model).join(\", \");\n if (lastError instanceof CloudflareAIError) {\n return new CloudflareAIError({\n attempts,\n cause: lastError,\n code: lastError.code,\n data: lastError.data,\n isRetryable: lastError.isRetryable,\n logId: lastError.logId,\n message: `All models failed (${models}). Last error: ${lastError.message}`,\n model: lastError.model,\n requestBodyValues: lastError.requestBodyValues,\n responseBody: lastError.responseBody,\n responseHeaders: lastError.responseHeaders,\n status: lastError.status,\n url: lastError.url\n });\n }\n if (APICallError.isInstance(lastError)) {\n // A routed vendor leg fails with the vendor's own error: its status, body\n // and retryability are the facts of the failure and travel with the chain.\n return new CloudflareAIError({\n attempts,\n cause: lastError,\n code: classifyStatus(lastError.statusCode),\n isRetryable: lastError.isRetryable,\n message: `All models failed (${models}). Last error: ${lastError.message}`,\n model: attempts.at(-1)?.model ?? \"\",\n requestBodyValues: lastError.requestBodyValues,\n responseBody: lastError.responseBody,\n responseHeaders: lastError.responseHeaders,\n status: lastError.statusCode,\n url: lastError.url\n });\n }\n return new CloudflareAIError({\n attempts,\n cause: lastError,\n code: \"unknown\",\n // Nothing here says the failure was transport-level, and re-running a\n // chain that already failed on every leg only burns the retry budget.\n isRetryable: false,\n message: `All models failed (${models}). Last error: ${String(lastError)}`,\n model: attempts.at(-1)?.model ?? \"\",\n requestBodyValues: undefined,\n url\n });\n}\n","import type {\n LanguageModelV4Content,\n LanguageModelV4FinishReason,\n LanguageModelV4StreamPart,\n LanguageModelV4Usage,\n SharedV4Warning\n} from \"@ai-sdk/provider\";\n\n/** A request body plus whatever the conversion had to drop. */\nexport interface WireRequest {\n body: Record<string, unknown>;\n warnings: SharedV4Warning[];\n /** Chat completions only: the body turns reasoning off via the chat template. */\n reasoningOff?: boolean;\n}\n\n/** A fully parsed non-streaming response, in AI SDK terms. */\nexport interface WireGeneration {\n content: LanguageModelV4Content[];\n finishReason: LanguageModelV4FinishReason;\n usage: LanguageModelV4Usage;\n responseId: string | undefined;\n responseModelId: string | undefined;\n timestamp: Date | undefined;\n}\n\n/** Turns each SSE `data:` payload into AI SDK stream parts. */\nexport type WireStreamParser = TransformStream<\n string,\n LanguageModelV4StreamPart\n>;\n\n/** Usage with every field unknown — the shape callers can always fall back to. */\nexport function emptyUsage(): LanguageModelV4Usage {\n return {\n inputTokens: {\n cacheRead: undefined,\n cacheWrite: undefined,\n noCache: undefined,\n total: undefined\n },\n outputTokens: { reasoning: undefined, text: undefined, total: undefined }\n };\n}\n\n/** A fresh id for a stream part or a tool call the provider did not name. */\nexport function newId(): string {\n return crypto.randomUUID();\n}\n\nconst BASE64_CHUNK = 0x8000;\n\n/** Base64-encodes bytes without blowing the argument limit on large files. */\nexport function toBase64(data: Uint8Array | string): string {\n if (typeof data === \"string\") return data;\n let binary = \"\";\n for (let offset = 0; offset < data.length; offset += BASE64_CHUNK) {\n binary += String.fromCharCode(\n ...data.subarray(offset, offset + BASE64_CHUNK)\n );\n }\n return btoa(binary);\n}\n\n/** Reads a record field without widening everything to `any`. */\nexport function record(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/** Reads an array field, or `undefined` when it is not one. */\nexport function array(value: unknown): unknown[] | undefined {\n return Array.isArray(value) ? value : undefined;\n}\n\n/** Reads a string field, or `undefined` when it is not one. */\nexport function text(value: unknown): string | undefined {\n return typeof value === \"string\" ? value : undefined;\n}\n\n/** Reads a number field, or `undefined` when it is not one. */\nexport function count(value: unknown): number | undefined {\n return typeof value === \"number\" ? value : undefined;\n}\n\n/** The finish reason used when a provider ends a stream without saying why. */\nexport function defaultFinishReason(): LanguageModelV4FinishReason {\n return { raw: undefined, unified: \"stop\" };\n}\n","import {\n TooManyEmbeddingValuesForCallError,\n type EmbeddingModelV4,\n type EmbeddingModelV4CallOptions,\n type EmbeddingModelV4Result\n} from \"@ai-sdk/provider\";\nimport {\n parseModalityCallOptions,\n resolveOptions,\n type ModelOptions\n} from \"../settings\";\nimport {\n definedHeaders,\n errorFromResponse,\n headersToObject,\n unwrapEnvelope,\n type Transport\n} from \"../transport\";\nimport { withFallback } from \"./fallback\";\nimport type { LanguageModelConfig } from \"./language\";\nimport { array, count, record } from \"../wires/shared\";\nimport { requireWorkersAIId } from \"../errors\";\n\n/**\n * Workers AI batches up to this many strings per embedding call.\n *\n * @see https://developers.cloudflare.com/workers-ai/platform/limits/\n */\nconst MAX_EMBEDDINGS_PER_CALL = 3000;\n\n/**\n * An `EmbeddingModelV4` over the Workers AI text-embedding catalog. The run\n * path takes `{ text: string[] }` and answers `{ data, shape, usage }`,\n * sometimes inside the Cloudflare envelope.\n *\n * @experimental This surface is experimental and may change.\n */\nexport class CloudflareEmbeddingModel implements EmbeddingModelV4 {\n readonly specificationVersion = \"v4\" as const;\n readonly provider = \"cloudflare\";\n readonly modelId: string;\n readonly maxEmbeddingsPerCall = MAX_EMBEDDINGS_PER_CALL;\n readonly supportsParallelCalls = true;\n\n readonly #config: LanguageModelConfig;\n readonly #options: ModelOptions | undefined;\n\n constructor(\n modelId: string,\n options: ModelOptions | undefined,\n config: LanguageModelConfig\n ) {\n // A leg written as a string is a Workers AI id, and nothing else: the\n // same gate the language models apply, at the line that wrote the leg.\n options?.fallback?.forEach((leg) => {\n if (typeof leg === \"string\") requireWorkersAIId(leg);\n });\n this.modelId = modelId;\n this.#options = options;\n this.#config = config;\n }\n\n async doEmbed(\n options: EmbeddingModelV4CallOptions\n ): Promise<EmbeddingModelV4Result> {\n if (options.values.length > MAX_EMBEDDINGS_PER_CALL) {\n throw new TooManyEmbeddingValuesForCallError({\n maxEmbeddingsPerCall: MAX_EMBEDDINGS_PER_CALL,\n modelId: this.modelId,\n provider: this.provider,\n values: options.values\n });\n }\n\n const resolved = resolveOptions(\n this.#config.providerGateway,\n this.#options,\n parseModalityCallOptions(options.providerOptions)\n );\n const input = { text: options.values };\n const transport: Transport = this.#config.transport;\n return withFallback(\n this.modelId,\n resolved.fallback,\n transport.url,\n async (modelId) => {\n const response = await transport.run({\n gateway: resolved.gateway,\n headers: {\n // The AI SDK types these as `string | undefined`; an undefined\n // value must not reach the binding as the string \"undefined\".\n ...definedHeaders(options.headers),\n ...resolved.headers,\n ...(resolved.sessionAffinity === undefined\n ? {}\n : { \"x-session-affinity\": resolved.sessionAffinity })\n },\n input,\n model: modelId,\n signal: options.abortSignal\n });\n if (!response.ok) {\n throw await errorFromResponse(response, {\n model: modelId,\n requestBodyValues: input,\n url: transport.url\n });\n }\n\n const body =\n record(\n unwrapEnvelope(await response.json(), {\n model: modelId,\n status: response.status,\n url: transport.url\n })\n ) ?? {};\n const embeddings = (array(body.data) ?? []).map((row) =>\n (array(row) ?? []).filter(\n (value): value is number => typeof value === \"number\"\n )\n );\n const tokens = count(record(body.usage)?.prompt_tokens);\n return {\n embeddings,\n response: { headers: headersToObject(response.headers) },\n ...(tokens === undefined ? {} : { usage: { tokens } }),\n warnings: []\n };\n }\n );\n }\n}\n","/**\n * The OpenAI chat-completions wire, in AI SDK terms.\n *\n * This module only maps AI SDK prompts and call options onto a strict OpenAI\n * chat-completions body, and strict OpenAI responses and chunks back onto AI\n * SDK content. Everything Cloudflare or a vendor does differently — Workers\n * AI's native events, its field spellings, per-family limits — is absorbed\n * once in `core/chat-completions`, before the request leaves and before the\n * response arrives here.\n */\n\nimport type {\n JSONObject,\n JSONSchema7,\n LanguageModelV4CallOptions,\n LanguageModelV4Content,\n LanguageModelV4FinishReason,\n LanguageModelV4Message,\n LanguageModelV4Prompt,\n LanguageModelV4StreamPart,\n LanguageModelV4ToolResultOutput,\n LanguageModelV4Usage,\n SharedV4ProviderMetadata,\n SharedV4ProviderOptions,\n SharedV4Warning\n} from \"@ai-sdk/provider\";\nimport {\n type CompatWarning,\n normalizeChatCompletion,\n prepareChatCompletionsRequest\n} from \"../../core/chat-completions\";\nimport { PROVIDER_OPTIONS_KEY } from \"../settings\";\nimport {\n array,\n count,\n defaultFinishReason,\n emptyUsage,\n newId,\n record,\n text,\n toBase64,\n type WireGeneration,\n type WireRequest,\n type WireStreamParser\n} from \"./shared\";\n\n/**\n * What a request needs beyond the AI SDK call options.\n *\n * @experimental This surface is experimental and may change.\n */\nexport interface OpenAIWireContext {\n /** The catalog id; the compat layer keys its quirks off it. */\n modelId: string;\n stream: boolean;\n reasoningEffort: \"low\" | \"medium\" | \"high\" | null | undefined;\n chatTemplateKwargs: Record<string, unknown> | undefined;\n}\n\ntype ContentPart =\n | { type: \"text\"; text: string }\n | { type: \"image_url\"; image_url: { url: string } };\n\nfunction fullMediaType(mediaType: string): string {\n // A bare top-level segment (\"image\") is legal in the AI SDK but not in a\n // data URL, so pick a concrete subtype rather than emitting a broken URL.\n return mediaType.includes(\"/\") ? mediaType : `${mediaType}/jpeg`;\n}\n\nfunction unsupported(feature: string, details: string): SharedV4Warning {\n return { details, feature, type: \"unsupported\" };\n}\n\n/** A compat-layer warning in the AI SDK's warning shape. */\nfunction fromCompat(warning: CompatWarning): SharedV4Warning {\n return unsupported(warning.feature, warning.message);\n}\n\n/**\n * Gemini 3 signs each assistant turn and each function call with an opaque\n * `extra_content.google.thought_signature`, and rejects a function call\n * replayed in the same turn without it. Nothing here reads the payload: it is\n * carried out as provider metadata and put back verbatim on the next turn.\n *\n * `extraContent` is the signature of the assistant message; `toolExtraContent`\n * is the one that belongs to an individual `tool_calls[i]` entry.\n */\nfunction extraContentMetadata(fields: {\n extraContent?: unknown;\n toolExtraContent?: unknown;\n}): { providerMetadata: SharedV4ProviderMetadata } | Record<string, never> {\n const metadata: Record<string, unknown> = {};\n const message = record(fields.extraContent);\n const tool = record(fields.toolExtraContent);\n if (message !== undefined) metadata.extraContent = message;\n if (tool !== undefined) metadata.toolExtraContent = tool;\n if (Object.keys(metadata).length === 0) return {};\n return {\n providerMetadata: {\n [PROVIDER_OPTIONS_KEY]: metadata as JSONObject\n }\n };\n}\n\n/** Reads back what {@link extraContentMetadata} stored on a replayed part. */\nfunction storedExtraContent(\n options: SharedV4ProviderOptions | undefined,\n key: \"extraContent\" | \"toolExtraContent\"\n): Record<string, unknown> | undefined {\n return record(options?.[PROVIDER_OPTIONS_KEY]?.[key]);\n}\n\nfunction toolResultText(\n output: LanguageModelV4ToolResultOutput,\n warnings: SharedV4Warning[]\n): string {\n switch (output.type) {\n case \"text\":\n case \"error-text\":\n return output.value;\n case \"json\":\n case \"error-json\":\n return JSON.stringify(output.value);\n case \"execution-denied\":\n return output.reason ?? \"The user denied this tool call.\";\n case \"content\": {\n const dropped = output.value.filter((part) => part.type !== \"text\");\n if (dropped.length > 0) {\n // A tool result travels as one string on this wire, so anything that\n // is not text is lost rather than silently mangled into \"\".\n warnings.push(\n unsupported(\n \"tool-result-part\",\n `Tool result parts of type ${[\n ...new Set(dropped.map((part) => part.type))\n ].join(\n \", \"\n )} cannot be sent on the chat-completions wire and were dropped.`\n )\n );\n }\n return output.value\n .map((part) => (part.type === \"text\" ? part.text : \"\"))\n .filter((part) => part !== \"\")\n .join(\"\\n\");\n }\n default: {\n const exhaustive: never = output;\n return String(exhaustive);\n }\n }\n}\n\nfunction userContent(\n message: Extract<LanguageModelV4Message, { role: \"user\" }>,\n warnings: SharedV4Warning[]\n): string | ContentPart[] {\n const parts: ContentPart[] = [];\n let onlyText = true;\n for (const part of message.content) {\n if (part.type === \"text\") {\n parts.push({ text: part.text, type: \"text\" });\n continue;\n }\n const isImage =\n part.mediaType === \"image\" || part.mediaType.startsWith(\"image/\");\n if (!isImage) {\n warnings.push(\n unsupported(\n \"file-part\",\n `Files of type ${part.mediaType} are not supported on this wire and were dropped.`\n )\n );\n continue;\n }\n if (part.data.type === \"data\") {\n onlyText = false;\n parts.push({\n image_url: {\n url: `data:${fullMediaType(part.mediaType)};base64,${toBase64(part.data.data)}`\n },\n type: \"image_url\"\n });\n continue;\n }\n if (part.data.type === \"url\") {\n onlyText = false;\n parts.push({\n image_url: { url: part.data.url.toString() },\n type: \"image_url\"\n });\n continue;\n }\n warnings.push(\n unsupported(\n \"file-part\",\n \"Only inline data and URL images are supported; the file was dropped.\"\n )\n );\n }\n if (onlyText) {\n return parts\n .map((part) => (part.type === \"text\" ? part.text : \"\"))\n .join(\"\");\n }\n return parts;\n}\n\nfunction convertPrompt(\n prompt: LanguageModelV4Prompt,\n warnings: SharedV4Warning[]\n): Record<string, unknown>[] {\n const messages: Record<string, unknown>[] = [];\n for (const message of prompt) {\n switch (message.role) {\n case \"system\":\n messages.push({ content: message.content, role: \"system\" });\n break;\n case \"user\":\n messages.push({\n content: userContent(message, warnings),\n role: \"user\"\n });\n break;\n case \"assistant\": {\n let content = \"\";\n let reasoning = \"\";\n let extraContent: Record<string, unknown> | undefined;\n const toolCalls: Record<string, unknown>[] = [];\n for (const part of message.content) {\n extraContent ??= storedExtraContent(\n part.providerOptions,\n \"extraContent\"\n );\n if (part.type === \"text\") content += part.text;\n else if (part.type === \"reasoning\") reasoning += part.text;\n else if (part.type === \"tool-call\") {\n const toolExtra = storedExtraContent(\n part.providerOptions,\n \"toolExtraContent\"\n );\n toolCalls.push({\n function: {\n arguments:\n typeof part.input === \"string\"\n ? part.input\n : JSON.stringify(part.input ?? {}),\n name: part.toolName\n },\n id: part.toolCallId,\n type: \"function\",\n ...(toolExtra === undefined ? {} : { extra_content: toolExtra })\n });\n } else {\n warnings.push(\n unsupported(\n \"assistant-part\",\n `Assistant \"${part.type}\" parts cannot be replayed on the chat-completions wire and were dropped.`\n )\n );\n }\n }\n messages.push({\n content,\n // Replayed reasoning travels as `reasoning_content`; the compat\n // layer drops it for models that have no such field.\n ...(reasoning !== \"\" ? { reasoning_content: reasoning } : {}),\n ...(extraContent === undefined\n ? {}\n : { extra_content: extraContent }),\n ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),\n role: \"assistant\"\n });\n break;\n }\n case \"tool\":\n for (const part of message.content) {\n if (part.type !== \"tool-result\") {\n warnings.push(\n unsupported(\n \"tool-part\",\n `Tool \"${part.type}\" parts are not carried on the chat-completions wire and were dropped.`\n )\n );\n continue;\n }\n messages.push({\n content: toolResultText(part.output, warnings),\n name: part.toolName,\n role: \"tool\",\n tool_call_id: part.toolCallId\n });\n }\n break;\n default: {\n const exhaustive: never = message;\n throw new Error(`Unsupported message role: ${String(exhaustive)}`);\n }\n }\n }\n return messages;\n}\n\n/** Folds the AI SDK's schema description into the schema itself. */\nfunction foldSchema(\n schema: JSONSchema7,\n description: string | undefined\n): JSONSchema7 {\n if (description === undefined || schema.description !== undefined) {\n return schema;\n }\n return { ...schema, description };\n}\n\nfunction responseFormat(\n options: LanguageModelV4CallOptions\n): Record<string, unknown> | undefined {\n const format = options.responseFormat;\n if (format === undefined || format.type !== \"json\") return undefined;\n if (format.schema === undefined) return { type: \"json_object\" };\n return {\n json_schema: {\n name: format.name ?? \"response\",\n schema: foldSchema(format.schema, format.description),\n // The compat layer keeps `strict` only for vendors that implement it.\n strict: true\n },\n type: \"json_schema\"\n };\n}\n\nfunction toolFields(\n options: LanguageModelV4CallOptions,\n warnings: SharedV4Warning[]\n): Record<string, unknown> {\n const tools: Record<string, unknown>[] = [];\n for (const tool of options.tools ?? []) {\n if (tool.type !== \"function\") {\n warnings.push(\n unsupported(\n \"provider-tool\",\n `Provider tool \"${tool.name}\" is not available through the Cloudflare run path.`\n )\n );\n continue;\n }\n tools.push({\n function: {\n description: tool.description,\n name: tool.name,\n parameters: tool.inputSchema\n },\n type: \"function\"\n });\n }\n if (tools.length === 0) return {};\n\n const choice = options.toolChoice;\n let toolChoice: unknown;\n switch (choice?.type) {\n case undefined:\n break;\n case \"auto\":\n toolChoice = \"auto\";\n break;\n case \"none\":\n toolChoice = \"none\";\n break;\n case \"required\":\n toolChoice = \"required\";\n break;\n case \"tool\":\n toolChoice = { function: { name: choice.toolName }, type: \"function\" };\n break;\n default: {\n const exhaustive: never = choice;\n throw new Error(`Unsupported tool choice: ${String(exhaustive)}`);\n }\n }\n return {\n tools,\n ...(toolChoice === undefined ? {} : { tool_choice: toolChoice })\n };\n}\n\n/**\n * The strict-body spelling of the reasoning request: an effort level, or\n * `null` for \"off\". The compat layer turns `null` into whatever the model\n * understands, or warns when nothing does.\n */\nfunction reasoningEffortField(\n options: LanguageModelV4CallOptions,\n context: OpenAIWireContext\n): Record<string, unknown> {\n if (context.reasoningEffort !== undefined) {\n return { reasoning_effort: context.reasoningEffort };\n }\n const reasoning = options.reasoning;\n if (reasoning === undefined || reasoning === \"provider-default\") return {};\n if (reasoning === \"none\") return { reasoning_effort: null };\n return { reasoning_effort: reasoning };\n}\n\n/**\n * Builds a strict OpenAI chat-completions body from AI SDK call options and\n * runs it through the compat layer for the target model.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function buildOpenAIRequest(\n options: LanguageModelV4CallOptions,\n context: OpenAIWireContext\n): WireRequest {\n const warnings: SharedV4Warning[] = [];\n\n if (options.topK !== undefined) {\n warnings.push(\n unsupported(\"topK\", \"topK is not part of the chat-completions API.\")\n );\n }\n\n const format = responseFormat(options);\n const strict: Record<string, unknown> = {\n messages: convertPrompt(options.prompt, warnings),\n ...(options.maxOutputTokens === undefined\n ? {}\n : { max_tokens: options.maxOutputTokens }),\n ...(options.temperature === undefined\n ? {}\n : { temperature: options.temperature }),\n ...(options.topP === undefined ? {} : { top_p: options.topP }),\n ...(options.stopSequences === undefined ||\n options.stopSequences.length === 0\n ? {}\n : { stop: options.stopSequences }),\n ...(options.seed === undefined ? {} : { seed: options.seed }),\n ...(options.frequencyPenalty === undefined\n ? {}\n : { frequency_penalty: options.frequencyPenalty }),\n ...(options.presencePenalty === undefined\n ? {}\n : { presence_penalty: options.presencePenalty }),\n ...(format === undefined ? {} : { response_format: format }),\n ...toolFields(options, warnings),\n ...reasoningEffortField(options, context),\n ...(context.chatTemplateKwargs === undefined\n ? {}\n : { chat_template_kwargs: context.chatTemplateKwargs }),\n // Usage on a stream only arrives when asked for, in a final\n // `choices: []` chunk; the compat layer makes every model look that way.\n ...(context.stream\n ? { stream: true, stream_options: { include_usage: true } }\n : {})\n };\n const prepared = prepareChatCompletionsRequest(strict, context.modelId);\n return {\n body: prepared.body,\n reasoningOff: prepared.reasoningOff,\n warnings: [...warnings, ...prepared.warnings.map(fromCompat)]\n };\n}\n\nfunction mapFinishReason(raw: unknown): LanguageModelV4FinishReason {\n const value = text(raw);\n switch (value) {\n case \"stop\":\n return { raw: value, unified: \"stop\" };\n case \"length\":\n return { raw: value, unified: \"length\" };\n case \"tool_calls\":\n case \"function_call\":\n return { raw: value, unified: \"tool-calls\" };\n case \"content_filter\":\n return { raw: value, unified: \"content-filter\" };\n case \"error\":\n return { raw: value, unified: \"error\" };\n default:\n return value === undefined\n ? defaultFinishReason()\n : { raw: value, unified: \"other\" };\n }\n}\n\nfunction mapUsage(raw: unknown): LanguageModelV4Usage {\n const usage = record(raw);\n if (usage === undefined) return emptyUsage();\n const promptTokens = count(usage.prompt_tokens);\n const cacheRead = count(record(usage.prompt_tokens_details)?.cached_tokens);\n const reasoningTokens = count(\n record(usage.completion_tokens_details)?.reasoning_tokens\n );\n const completionTokens = count(usage.completion_tokens);\n const totalTokens = count(usage.total_tokens);\n // Google counts reasoning outside `completion_tokens` (live: prompt 6 +\n // completion 3 + reasoning 57 = total 66), so taking `completion_tokens` as\n // the output total under-reports every reasoning token. OpenAI and Workers\n // AI both satisfy prompt + completion = total, so the derived figure agrees\n // with theirs.\n const outputTotal =\n totalTokens !== undefined && promptTokens !== undefined\n ? Math.max(completionTokens ?? 0, totalTokens - promptTokens)\n : completionTokens;\n return {\n inputTokens: {\n cacheRead,\n // The OpenAI usage shape carries no cache-write signal.\n cacheWrite: undefined,\n // A vendor that reports no cache-read detail at all (Google is one)\n // still knows its prompt total, and every one of those tokens was\n // uncached — reporting `undefined` there loses a number we have.\n noCache:\n promptTokens === undefined\n ? undefined\n : Math.max(0, promptTokens - (cacheRead ?? 0)),\n total: promptTokens\n },\n outputTokens: {\n reasoning: reasoningTokens,\n text: undefined,\n total: outputTotal\n },\n raw: usage as JSONObject\n };\n}\n\nfunction toolCallsFrom(\n raw: unknown,\n /** Message-level `extra_content`, when no text part could carry it. */\n messageExtra: unknown\n): LanguageModelV4Content[] {\n const calls = array(raw) ?? [];\n const content: LanguageModelV4Content[] = [];\n for (const entry of calls) {\n const call = record(entry);\n if (call === undefined) continue;\n const fn = record(call.function);\n const name = text(fn?.name);\n if (name === undefined) continue;\n content.push({\n input: text(fn?.arguments) ?? \"{}\",\n toolCallId: text(call.id) ?? newId(),\n toolName: name,\n type: \"tool-call\",\n ...extraContentMetadata({\n // Only the first call carries the message-level signature, so a\n // replayed turn puts exactly one back.\n extraContent: content.length === 0 ? messageExtra : undefined,\n toolExtraContent: call.extra_content\n })\n });\n }\n return content;\n}\n\n/**\n * Parses a non-streaming response. The body is normalized to the strict\n * `chat.completion` shape first, so only `choices[0].message` is read.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function parseOpenAIGeneration(\n json: unknown,\n modelId: string\n): WireGeneration {\n const body = normalizeChatCompletion(json, modelId);\n const choice = record(array(body.choices)?.[0]);\n const message = record(choice?.message);\n const content: LanguageModelV4Content[] = [];\n\n const reasoning = text(message?.reasoning_content);\n if (reasoning !== undefined && reasoning !== \"\") {\n content.push({ text: reasoning, type: \"reasoning\" });\n }\n\n const answer = text(message?.content);\n const messageExtra = message?.extra_content;\n if (answer !== undefined && answer !== \"\") {\n content.push({\n text: answer,\n type: \"text\",\n ...extraContentMetadata({ extraContent: messageExtra })\n });\n }\n\n content.push(\n ...toolCallsFrom(\n message?.tool_calls,\n answer === undefined || answer === \"\" ? messageExtra : undefined\n )\n );\n\n const created = count(body.created);\n return {\n content,\n finishReason: mapFinishReason(choice?.finish_reason),\n responseId: text(body.id),\n responseModelId: text(body.model),\n timestamp: created === undefined ? undefined : new Date(created * 1000),\n usage: mapUsage(body.usage)\n };\n}\n\ninterface ToolCallState {\n id: string;\n name: string;\n input: string;\n closed: boolean;\n /** This call's own `extra_content`, when the vendor signs each call. */\n extraContent: unknown;\n}\n\n/**\n * Streams strict OpenAI `chat.completion.chunk` events into AI SDK stream\n * parts. Tool calls arrive either as incremental `arguments` fragments closed\n * by a null-finalization chunk, or as one delta with the complete arguments\n * string; both are handled. Usage is read from whichever chunk carries it.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function openAIStreamParser(): WireStreamParser {\n const toolCalls = new Map<number, ToolCallState>();\n let lastToolIndex: number | undefined;\n let textId: string | undefined;\n let reasoningId: string | undefined;\n let usage = emptyUsage();\n let finishReason: LanguageModelV4FinishReason | undefined;\n let sentMetadata = false;\n let receivedDone = false;\n let receivedEvent = false;\n /** Message-level `extra_content` (Gemini's thought signature). */\n let messageExtra: unknown;\n let messageExtraClaimed = false;\n let textEverOpened = false;\n\n type Controller = TransformStreamDefaultController<LanguageModelV4StreamPart>;\n\n /**\n * The message signature belongs on whichever part replays the message: the\n * text block when there is one, otherwise the first tool call.\n */\n const claimMessageExtra = (): unknown => {\n if (messageExtraClaimed) return undefined;\n messageExtraClaimed = true;\n return messageExtra;\n };\n\n const closeReasoning = (controller: Controller) => {\n if (reasoningId === undefined) return;\n controller.enqueue({ id: reasoningId, type: \"reasoning-end\" });\n reasoningId = undefined;\n };\n\n const closeText = (controller: Controller) => {\n if (textId === undefined) return;\n controller.enqueue({\n id: textId,\n type: \"text-end\",\n ...extraContentMetadata({ extraContent: claimMessageExtra() })\n });\n textId = undefined;\n };\n\n const closeToolCall = (index: number, controller: Controller) => {\n const state = toolCalls.get(index);\n if (state === undefined || state.closed) return;\n state.closed = true;\n controller.enqueue({ id: state.id, type: \"tool-input-end\" });\n controller.enqueue({\n input: state.input,\n toolCallId: state.id,\n toolName: state.name,\n type: \"tool-call\",\n ...extraContentMetadata({\n extraContent: textEverOpened ? undefined : claimMessageExtra(),\n toolExtraContent: state.extraContent\n })\n });\n };\n\n const emitToolDeltas = (raw: unknown, controller: Controller) => {\n const deltas = array(raw);\n if (deltas === undefined) return;\n for (const entry of deltas) {\n const call = record(entry);\n if (call === undefined) continue;\n const fn = record(call.function);\n const name = text(fn?.name);\n const input = text(fn?.arguments);\n const id = text(call.id);\n const rawIndex = count(call.index);\n\n // The null-finalization sentinel carries no id, no name, no arguments\n // and — crucially — no index, which is what tells it apart from an\n // ordinary empty argument fragment that some vLLM tool parsers emit\n // between real fragments.\n if (\n rawIndex === undefined &&\n id === undefined &&\n (name === undefined || name === \"\") &&\n (input === undefined || input === \"\")\n ) {\n if (lastToolIndex !== undefined)\n closeToolCall(lastToolIndex, controller);\n continue;\n }\n\n // Text and reasoning blocks close before a tool call opens, so the\n // stream never has two kinds of block open at once.\n closeReasoning(controller);\n closeText(controller);\n\n const index = rawIndex ?? lastToolIndex ?? 0;\n let state = toolCalls.get(index);\n // A fragment for an index that was already finalized cannot be reopened\n // without emitting a delta after its `tool-input-end`; drop it.\n if (state?.closed === true) continue;\n if (state === undefined) {\n if (lastToolIndex !== undefined && lastToolIndex !== index) {\n closeToolCall(lastToolIndex, controller);\n }\n state = {\n closed: false,\n extraContent: call.extra_content,\n id: id ?? newId(),\n input: \"\",\n name: name ?? \"\"\n };\n toolCalls.set(index, state);\n lastToolIndex = index;\n controller.enqueue({\n id: state.id,\n toolName: state.name,\n type: \"tool-input-start\"\n });\n } else {\n if (name !== undefined && state.name === \"\") state.name = name;\n state.extraContent ??= call.extra_content;\n }\n if (input !== undefined && input !== \"\") {\n state.input += input;\n controller.enqueue({\n delta: input,\n id: state.id,\n type: \"tool-input-delta\"\n });\n }\n }\n };\n\n return new TransformStream<string, LanguageModelV4StreamPart>({\n flush(controller) {\n for (const index of toolCalls.keys()) closeToolCall(index, controller);\n closeReasoning(controller);\n closeText(controller);\n if (finishReason === undefined) {\n finishReason =\n receivedEvent && !receivedDone\n ? { raw: \"stream-truncated\", unified: \"error\" }\n : defaultFinishReason();\n }\n controller.enqueue({ finishReason, type: \"finish\", usage });\n },\n transform(data, controller) {\n if (data === \"\") return;\n if (data === \"[DONE]\") {\n receivedDone = true;\n return;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(data);\n } catch {\n // A malformed event must not kill a stream that is otherwise fine.\n return;\n }\n const chunk = record(parsed);\n if (chunk === undefined) return;\n receivedEvent = true;\n\n // A 200 SSE stream can still carry an upstream failure (content policy,\n // a rate limit hit mid-generation) as an `error` payload and then close.\n // Surfacing it beats finishing with empty text and no diagnostic.\n const failure = record(chunk.error);\n if (failure !== undefined) {\n closeReasoning(controller);\n closeText(controller);\n controller.enqueue({ error: failure, type: \"error\" });\n finishReason = {\n raw: text(failure.type) ?? \"error\",\n unified: \"error\"\n };\n return;\n }\n\n if (!sentMetadata) {\n const created = count(chunk.created);\n const id = text(chunk.id);\n const modelId = text(chunk.model);\n if (id !== undefined || modelId !== undefined) {\n sentMetadata = true;\n controller.enqueue({\n id,\n modelId,\n timestamp:\n created === undefined ? undefined : new Date(created * 1000),\n type: \"response-metadata\"\n });\n }\n }\n\n if (record(chunk.usage) !== undefined) usage = mapUsage(chunk.usage);\n\n const choice = record(array(chunk.choices)?.[0]);\n const delta = record(choice?.delta);\n if (delta !== undefined) {\n messageExtra ??= record(delta.extra_content);\n const reasoning = text(delta.reasoning_content);\n if (reasoning !== undefined && reasoning !== \"\") {\n if (reasoningId === undefined) {\n reasoningId = newId();\n controller.enqueue({ id: reasoningId, type: \"reasoning-start\" });\n }\n controller.enqueue({\n delta: reasoning,\n id: reasoningId,\n type: \"reasoning-delta\"\n });\n }\n const content = text(delta.content);\n if (content !== undefined && content !== \"\") {\n closeReasoning(controller);\n if (textId === undefined) {\n textId = newId();\n textEverOpened = true;\n controller.enqueue({ id: textId, type: \"text-start\" });\n }\n controller.enqueue({\n delta: content,\n id: textId,\n type: \"text-delta\"\n });\n }\n emitToolDeltas(delta.tool_calls, controller);\n }\n\n if (text(choice?.finish_reason) !== undefined) {\n finishReason = mapFinishReason(choice?.finish_reason);\n }\n }\n });\n}\n","import type {\n JSONObject,\n LanguageModelV4,\n LanguageModelV4CallOptions,\n LanguageModelV4Content,\n LanguageModelV4GenerateResult,\n LanguageModelV4StreamPart,\n LanguageModelV4StreamResult,\n SharedV4ProviderMetadata,\n SharedV4Warning\n} from \"@ai-sdk/provider\";\nimport { CloudflareAIError, requireLanguageModelId } from \"../errors\";\nimport {\n fallbackLegs,\n rememberOptions,\n parseCallOptions,\n PROVIDER_OPTIONS_KEY,\n resolveOptions,\n withoutCallFallback,\n type FallbackLeg,\n type ModelOptions,\n type ProviderGatewaySettings,\n type ResolvedOptions\n} from \"../settings\";\nimport { normalizeChatCompletionsStream } from \"../../core/chat-completions\";\nimport { sseDataStream } from \"../../core/sse\";\nimport {\n definedHeaders,\n errorFromResponse,\n headersToObject,\n unwrapEnvelope,\n type Transport\n} from \"../transport\";\nimport {\n buildOpenAIRequest,\n openAIStreamParser,\n parseOpenAIGeneration\n} from \"../wires/chat-completions\";\nimport { newId, type WireGeneration } from \"../wires/shared\";\nimport {\n withFallbackLegs,\n type FallbackAttempt,\n withStreamFallbackLegs\n} from \"./fallback\";\n\n/**\n * Typed observability attached to every result under\n * `providerMetadata.cloudflare`, so consumers never have to walk response\n * objects looking for a gateway log id.\n *\n * @experimental This surface is experimental and may change.\n */\nexport interface CloudflareMetadata {\n /** The model that actually answered — the fallback leg, when one was used. */\n model: string;\n /** The gateway id the request went through. Absent when none handled it. */\n gateway?: string;\n /**\n * The gateway provider slug, for a vendor's model object sent to the\n * provider-native path. Absent for a model id.\n */\n provider?: string;\n /** `cf-aig-log-id`, or the binding's last log id. */\n logId?: string;\n /** `cf-aig-event-id` — correlates the requests of one gateway event. */\n eventId?: string;\n /** `cf-aig-request-id` — the gateway's id for this request. */\n requestId?: string;\n /** `cf-aig-trace-id` — the trace this request belongs to. */\n traceId?: string;\n /** `cf-aig-run-id`, when the gateway sends one. */\n runId?: string;\n /** `cf-aig-cache-status`, e.g. `HIT` or `MISS`. */\n cacheStatus?: string;\n /** `cf-aig-step` — which step of a gateway route answered. */\n step?: number;\n}\n\n/** Everything a language model needs from the provider that created it. */\nexport interface LanguageModelConfig {\n transport: Transport;\n /**\n * The provider-wide gateway defaults, in any of the spellings `createAI`\n * takes: a bare id, a `gateway` object, or the whole settings object with\n * the flat gateway keys on it.\n */\n providerGateway: string | ProviderGatewaySettings | undefined;\n}\n\nfunction callHeaders(\n options: LanguageModelV4CallOptions,\n resolved: ResolvedOptions\n): Record<string, string> {\n const headers = definedHeaders(options.headers);\n Object.assign(headers, resolved.headers);\n if (resolved.sessionAffinity !== undefined) {\n headers[\"x-session-affinity\"] = resolved.sessionAffinity;\n }\n return headers;\n}\n\n/**\n * Builds the `providerMetadata.cloudflare` block every model in this module\n * attaches to its result. Shared with the non-language models in\n * `models/modality.ts`.\n */\nexport function cloudflareMetadata(\n model: string,\n gateway: string | undefined,\n response: Response,\n transport: Transport,\n provider?: string\n): SharedV4ProviderMetadata {\n const headers = response.headers;\n const rawStep = headers.get(\"cf-aig-step\");\n const step = rawStep === null ? Number.NaN : Number(rawStep);\n const metadata: CloudflareMetadata = {\n ...(gateway === undefined ? {} : { gateway }),\n model,\n ...(provider === undefined ? {} : { provider }),\n ...(Number.isNaN(step) ? {} : { step })\n };\n for (const [field, header] of [\n [\"cacheStatus\", \"cf-aig-cache-status\"],\n [\"eventId\", \"cf-aig-event-id\"],\n [\"requestId\", \"cf-aig-request-id\"],\n [\"runId\", \"cf-aig-run-id\"],\n [\"traceId\", \"cf-aig-trace-id\"]\n ] as const) {\n const value = headers.get(header);\n if (value !== null) metadata[field] = value;\n }\n const logId =\n headers.get(\"cf-aig-log-id\") ?? transport.logIdFallback(response);\n if (logId !== undefined && logId !== null) metadata.logId = logId;\n return { [PROVIDER_OPTIONS_KEY]: metadata as unknown as JSONObject };\n}\n\ninterface BuiltRequest {\n body: Record<string, unknown>;\n warnings: SharedV4Warning[];\n /** The body turns reasoning off via the chat template. */\n reasoningOff?: boolean;\n}\n\nfunction buildRequest(\n modelId: string,\n options: LanguageModelV4CallOptions,\n resolved: ResolvedOptions,\n stream: boolean\n): BuiltRequest {\n return buildOpenAIRequest(options, {\n chatTemplateKwargs: resolved.chatTemplateKwargs,\n modelId,\n reasoningEffort: resolved.reasoningEffort,\n stream\n });\n}\n\n/**\n * Prepends the single `stream-start` part and stamps `providerMetadata` onto\n * the `finish` part. A `TransformStream` rather than a manual enqueue so the\n * pipeline keeps its backpressure and error propagation.\n */\nfunction decorateStream(\n warnings: SharedV4Warning[],\n providerMetadata: SharedV4ProviderMetadata\n): TransformStream<LanguageModelV4StreamPart, LanguageModelV4StreamPart> {\n let started = false;\n const start = (\n controller: TransformStreamDefaultController<LanguageModelV4StreamPart>\n ) => {\n if (started) return;\n started = true;\n controller.enqueue({ type: \"stream-start\", warnings });\n };\n return new TransformStream({\n flush(controller) {\n // A stream that produced nothing still owes the caller a stream-start.\n start(controller);\n },\n transform(part, controller) {\n start(controller);\n controller.enqueue(\n part.type === \"finish\" ? { ...part, providerMetadata } : part\n );\n }\n });\n}\n\n/**\n * Replays an already-complete generation as a stream. Workers AI sometimes\n * answers a `stream: true` request with a plain JSON body; degrading\n * gracefully beats failing the call.\n */\nfunction oneShotStream(\n generation: WireGeneration\n): ReadableStream<LanguageModelV4StreamPart> {\n return new ReadableStream<LanguageModelV4StreamPart>({\n start(controller) {\n if (\n generation.responseId !== undefined ||\n generation.responseModelId !== undefined\n ) {\n controller.enqueue({\n id: generation.responseId,\n modelId: generation.responseModelId,\n timestamp: generation.timestamp,\n type: \"response-metadata\"\n });\n }\n for (const part of generation.content) {\n emitContent(part, controller);\n }\n controller.enqueue({\n finishReason: generation.finishReason,\n type: \"finish\",\n usage: generation.usage\n });\n controller.close();\n }\n });\n}\n\nfunction emitContent(\n part: LanguageModelV4Content,\n controller: ReadableStreamDefaultController<LanguageModelV4StreamPart>\n): void {\n switch (part.type) {\n case \"text\": {\n const id = newId();\n controller.enqueue({ id, type: \"text-start\" });\n controller.enqueue({ delta: part.text, id, type: \"text-delta\" });\n controller.enqueue({\n id,\n type: \"text-end\",\n ...(part.providerMetadata === undefined\n ? {}\n : { providerMetadata: part.providerMetadata })\n });\n break;\n }\n case \"reasoning\": {\n const id = newId();\n controller.enqueue({ id, type: \"reasoning-start\" });\n controller.enqueue({ delta: part.text, id, type: \"reasoning-delta\" });\n controller.enqueue({\n id,\n type: \"reasoning-end\",\n ...(part.providerMetadata === undefined\n ? {}\n : { providerMetadata: part.providerMetadata })\n });\n break;\n }\n case \"tool-call\": {\n controller.enqueue({\n id: part.toolCallId,\n toolName: part.toolName,\n type: \"tool-input-start\"\n });\n controller.enqueue({\n delta: part.input,\n id: part.toolCallId,\n type: \"tool-input-delta\"\n });\n controller.enqueue({ id: part.toolCallId, type: \"tool-input-end\" });\n controller.enqueue(part);\n break;\n }\n default:\n controller.enqueue(part);\n }\n}\n\n/**\n * A `LanguageModelV4` backed by the Cloudflare run path. The model id decides\n * the wire format; nothing about transport or wire format reaches user land.\n *\n * @experimental This surface is experimental and may change.\n */\nexport class CloudflareLanguageModel implements LanguageModelV4 {\n readonly specificationVersion = \"v4\" as const;\n readonly provider = \"cloudflare\";\n readonly modelId: string;\n readonly supportedUrls: Record<string, RegExp[]>;\n\n readonly #config: LanguageModelConfig;\n readonly #options: ModelOptions | undefined;\n\n constructor(\n modelId: string,\n options: ModelOptions | undefined,\n config: LanguageModelConfig\n ) {\n this.modelId = modelId;\n this.#options = options;\n this.#config = config;\n rememberOptions(this, options);\n // Workers AI takes image bytes inline; it fetches no URL on our behalf.\n this.supportedUrls = {};\n }\n\n async doGenerate(\n options: LanguageModelV4CallOptions\n ): Promise<LanguageModelV4GenerateResult> {\n const call = parseCallOptions(options.providerOptions);\n const resolved = this.#resolve(call);\n const legOptions = withoutCallFallback(options);\n return this.#withFallback(\n call,\n (model) => model.doGenerate(legOptions),\n async (modelId) => {\n const request = buildRequest(modelId, options, resolved, false);\n const response = await this.#send(modelId, request, options, resolved);\n const raw = await this.#readBody(modelId, request, response);\n const generation = parseOpenAIGeneration(raw, modelId);\n return {\n content: generation.content,\n finishReason: generation.finishReason,\n providerMetadata: cloudflareMetadata(\n modelId,\n resolved.gateway.id,\n response,\n this.#config.transport\n ),\n request: { body: request.body },\n response: {\n headers: headersToObject(response.headers),\n id: generation.responseId,\n modelId: generation.responseModelId ?? modelId,\n timestamp: generation.timestamp\n },\n usage: generation.usage,\n warnings: request.warnings\n };\n }\n );\n }\n\n async doStream(\n options: LanguageModelV4CallOptions\n ): Promise<LanguageModelV4StreamResult> {\n const call = parseCallOptions(options.providerOptions);\n const resolved = this.#resolve(call);\n const legOptions = withoutCallFallback(options);\n return this.#withFallback(\n call,\n (model) => model.doStream(legOptions),\n async (modelId) => {\n const request = buildRequest(modelId, options, resolved, true);\n const response = await this.#send(modelId, request, options, resolved);\n const providerMetadata = cloudflareMetadata(\n modelId,\n resolved.gateway.id,\n response,\n this.#config.transport\n );\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n const decorate = decorateStream(request.warnings, providerMetadata);\n\n let parts: ReadableStream<LanguageModelV4StreamPart>;\n if (!contentType.includes(\"event-stream\") || response.body === null) {\n const raw = await this.#readBody(modelId, request, response);\n parts = oneShotStream(parseOpenAIGeneration(raw, modelId));\n } else {\n parts = response.body\n .pipeThrough(sseDataStream())\n // Strict OpenAI chunks only: the compat layer absorbs Workers AI's\n // native events, heartbeats and per-delta usage.\n .pipeThrough(\n normalizeChatCompletionsStream(modelId, {\n reasoningOff: request.reasoningOff\n })\n )\n .pipeThrough(openAIStreamParser());\n }\n\n return {\n request: { body: request.body },\n response: { headers: headersToObject(response.headers) },\n stream: parts.pipeThrough(decorate)\n };\n },\n \"stream\"\n );\n }\n\n /**\n * Reads a 2xx body as JSON and unwraps the Cloudflare envelope. A 2xx that\n * is not JSON at all is a provider failure, not a caller bug, so it comes\n * back as a {@link CloudflareAIError} rather than a bare `SyntaxError`.\n */\n async #readBody(\n modelId: string,\n request: BuiltRequest,\n response: Response\n ): Promise<unknown> {\n let json: unknown;\n try {\n json = await response.json();\n } catch (error) {\n throw new CloudflareAIError({\n cause: error,\n code: \"provider-error\",\n isRetryable: false,\n message: `The model answered ${response.status} with a body that is not JSON.`,\n model: modelId,\n requestBodyValues: request.body,\n status: response.status,\n url: this.#config.transport.url\n });\n }\n return unwrapEnvelope(json, {\n model: modelId,\n status: response.status,\n url: this.#config.transport.url\n });\n }\n\n #resolve(call: ModelOptions | undefined): ResolvedOptions {\n return resolveOptions(this.#config.providerGateway, this.#options, call);\n }\n\n async #send(\n modelId: string,\n request: BuiltRequest,\n options: LanguageModelV4CallOptions,\n resolved: ResolvedOptions\n ): Promise<Response> {\n const response = await this.#config.transport.run({\n format: \"chat-completions\",\n gateway: resolved.gateway,\n headers: callHeaders(options, resolved),\n input: request.body,\n model: modelId,\n signal: options.abortSignal\n });\n if (!response.ok) {\n throw await errorFromResponse(response, {\n model: modelId,\n requestBodyValues: request.body,\n url: this.#config.transport.url\n });\n }\n return response;\n }\n\n /**\n * Runs this model, then each fallback leg in order. A leg named by id runs\n * through this same pipeline; a leg that is a model object — a vendor model\n * `ai()` already wrapped, or another provider's — is asked directly, so a\n * chain can mix Workers AI with anything the AI SDK can reach.\n */\n #withFallback<T>(\n call: ModelOptions | undefined,\n runLeg: (model: LanguageModelV4) => PromiseLike<T>,\n runSelf: (modelId: string) => Promise<T>,\n mode: \"generate\" | \"stream\" = \"generate\"\n ): Promise<T> {\n const legs: FallbackLeg[] = fallbackLegs(this.#options, call);\n const chain = (attempts: FallbackAttempt<T>[]): Promise<T> =>\n mode === \"stream\"\n ? (withStreamFallbackLegs(\n attempts as FallbackAttempt<LanguageModelV4StreamResult>[],\n this.#config.transport.url\n ) as Promise<T>)\n : withFallbackLegs(attempts, this.#config.transport.url);\n return chain([\n { model: this.modelId, run: () => runSelf(this.modelId) },\n ...legs.map((leg) =>\n typeof leg === \"string\"\n ? // Belt and braces: `ai()` and the per-call bag both gate their\n // legs, and a vendor id must never reach `env.AI.run`. Checked\n // as the chain is built, so the throw is not swallowed as one\n // more failed leg.\n { model: requireLanguageModelId(leg), run: () => runSelf(leg) }\n : { model: leg.modelId, run: () => runLeg(leg) }\n )\n ]);\n }\n}\n","/**\n * Routing a vendor's own AI SDK model through AI Gateway's provider-native\n * path.\n *\n * Nothing here knows a vendor's wire format, ids, or capabilities. The user\n * builds the model with the vendor's own provider package; this module swaps\n * the `fetch` that model would have used for one that sends the very same\n * request — method, headers, body — to\n * `env.AI.fetch(\".../ai-gateway/gateways/{gateway}/{provider}/{endpoint}\")`,\n * and hands the vendor's answer straight back to the vendor's own parser.\n *\n * @experimental This surface is experimental and may change.\n */\n\nimport type {\n JSONArray,\n JSONObject,\n LanguageModelV4,\n LanguageModelV4CallOptions,\n LanguageModelV4GenerateResult,\n LanguageModelV4StreamPart,\n LanguageModelV4StreamResult,\n SharedV4ProviderMetadata,\n SharedV4ProviderOptions,\n SharedV4Warning\n} from \"@ai-sdk/provider\";\nimport {\n type ResolvedGatewayProvider,\n requireGatewayProvider\n} from \"../../core/gateway-providers\";\nimport { requireLanguageModelId } from \"../errors\";\nimport {\n fallbackLegs,\n rememberOptions,\n parseCallOptions,\n PROVIDER_OPTIONS_KEY,\n resolveOptions,\n withoutCallFallback,\n type FallbackLeg,\n type GatewayModelOptions,\n type ModelOptions,\n type ResolvedOptions,\n type RoutedModelOptions,\n type VendorKeyOptions\n} from \"../settings\";\nimport {\n errorFromGatewayEnvelope,\n headersToObject,\n isGatewayErrorEnvelope\n} from \"../transport\";\nimport {\n withFallbackLegs,\n type FallbackAttempt,\n withStreamFallbackLegs\n} from \"./fallback\";\nimport {\n cloudflareMetadata,\n CloudflareLanguageModel,\n type LanguageModelConfig\n} from \"./language\";\n\n/**\n * The options accepted beside a vendor model. Re-exported under the name the\n * module's public surface uses.\n *\n * @experimental This surface is experimental and may change.\n */\nexport type { GatewayModelOptions } from \"../settings\";\n\n/** Which key a routed request authenticates with; see {@link VendorKeyOptions}. */\ntype VendorKey = NonNullable<VendorKeyOptions[\"vendorKey\"]>;\n\n/** A model whose provider exposes the standard `config.fetch` setting. */\ninterface RoutableModel {\n config?: unknown;\n modelId?: unknown;\n provider?: unknown;\n}\n\n/** What one routed request reports back about how it travelled. */\ninterface RouteCapture {\n response?: Response;\n provider?: string;\n}\n\n/**\n * Throws unless a model's provider keeps its settings where every `@ai-sdk/*`\n * provider keeps them. Checked when the model is wrapped rather than when it\n * is called, so the mistake is reported at the line that made it.\n */\nfunction requireConfig(model: LanguageModelV4): Record<string, unknown> {\n const config = (model as RoutableModel).config;\n if (config === null || typeof config !== \"object\") {\n throw new TypeError(\n `The model \"${String((model as RoutableModel).modelId ?? \"unknown\")}\" from provider \"${String(\n (model as RoutableModel).provider ?? \"unknown\"\n )}\" has no \\`config\\` setting, so AI Gateway cannot take over its requests. Every \\`@ai-sdk/*\\` provider has one; a middleware-wrapped or hand-written model does not. Wrap the provider's own model first and apply middleware afterwards: wrapLanguageModel({ model: ai(anthropic(\"claude-opus-4-8\")), middleware }).`\n );\n }\n return config as Record<string, unknown>;\n}\n\n/**\n * A per-call copy of the upstream model whose `config.fetch` is ours. The\n * user's model object is never touched: it may be shared across requests, and\n * two concurrent calls must not see each other's transport.\n */\nfunction cloneWithFetch<T extends LanguageModelV4>(\n model: T,\n fetchImpl: typeof globalThis.fetch\n): T {\n const config = requireConfig(model);\n const clone = Object.create(Object.getPrototypeOf(model)) as T;\n Object.defineProperties(clone, Object.getOwnPropertyDescriptors(model));\n Object.defineProperty(clone, \"config\", {\n configurable: true,\n enumerable: true,\n value: { ...config, fetch: fetchImpl },\n writable: true\n });\n return clone;\n}\n\n/** The request URL, whichever of `fetch`'s two call shapes was used. */\nfunction requestUrl(input: RequestInfo | URL): string {\n if (typeof input === \"string\") return input;\n if (input instanceof URL) return input.href;\n return input.url;\n}\n\n/**\n * The body of either `fetch` call form: the `RequestInit`'s when one was\n * given, else the `Request`'s own, from a clone so the caller's object is\n * neither consumed nor mutated.\n */\nfunction requestBody(\n input: RequestInfo | URL,\n init: RequestInit | undefined\n): BodyInit | null | undefined {\n if (init?.body !== undefined) return init.body;\n // A clone's body streams through to the binding rather than being read\n // into memory first, so a large upload costs nothing extra here.\n if (input instanceof Request && input.body !== null) {\n return input.clone().body;\n }\n return undefined;\n}\n\n/** The method of either `fetch` call form. */\nfunction requestMethod(\n input: RequestInfo | URL,\n init: RequestInit | undefined\n): string {\n return init?.method ?? (input instanceof Request ? input.method : \"POST\");\n}\n\n/** The vendor model id out of a JSON body, for error reporting. */\nfunction modelOfBody(body: BodyInit | null | undefined): string | undefined {\n if (typeof body !== \"string\") return undefined;\n try {\n const parsed = JSON.parse(body) as unknown;\n return modelOf(parsed);\n } catch {\n return undefined;\n }\n}\n\n/**\n * The vendor's own request headers, minus the length of a body we are about\n * to re-serialize, and minus the vendor's credential unless the model asked\n * for it to be forwarded.\n */\nfunction forwardedHeaders(\n init: RequestInit | undefined,\n input: RequestInfo | URL,\n route: ResolvedGatewayProvider,\n vendorKey: VendorKey\n): Record<string, string> {\n const source =\n init?.headers ?? (input instanceof Request ? input.headers : undefined);\n const dropped = new Set([\n ...(vendorKey === \"request\" ? [] : route.authHeaders),\n \"content-length\"\n ]);\n const headers: Record<string, string> = {};\n new Headers(source).forEach((value, key) => {\n if (!dropped.has(key.toLowerCase())) headers[key] = value;\n });\n return headers;\n}\n\n/** A response whose body can be read again, for the vendor's error handler. */\nfunction replayed(response: Response, text: string): Response {\n const bodyless =\n response.status === 204 ||\n response.status === 205 ||\n response.status === 304;\n return new Response(bodyless ? null : text, {\n headers: response.headers,\n status: response.status,\n statusText: response.statusText\n });\n}\n\n/**\n * The `fetch` a routed model is given. It maps the vendor's URL onto a gateway\n * provider slug and endpoint and sends the request there unchanged, through\n * the binding; the answer is the vendor's own.\n */\nfunction routedFetch(context: {\n config: LanguageModelConfig;\n resolved: ResolvedOptions;\n capture: RouteCapture;\n signal: AbortSignal | undefined;\n vendorKey: VendorKey;\n}): typeof globalThis.fetch {\n const routed = async (\n input: RequestInfo | URL,\n init?: RequestInit\n ): Promise<Response> => {\n const url = requestUrl(input);\n const route = requireGatewayProvider(url);\n const body = requestBody(input, init);\n const { resolved } = context;\n const response = await context.config.transport.native({\n body,\n endpoint: route.endpoint,\n gateway: resolved.gateway,\n headers: {\n ...forwardedHeaders(init, input, route, context.vendorKey),\n ...resolved.headers,\n ...(resolved.sessionAffinity === undefined\n ? {}\n : { \"x-session-affinity\": resolved.sessionAffinity })\n },\n method: requestMethod(input, init),\n provider: route.provider,\n // The vendor puts the call's abort signal on the request it builds; the\n // call's own is the fallback for a provider that forgets to.\n signal:\n init?.signal ??\n (input instanceof Request ? input.signal : undefined) ??\n context.signal\n });\n context.capture.provider = route.provider;\n context.capture.response = response;\n // A vendor's own error is the vendor's to explain, and its provider knows\n // how; only the gateway's own failures are lifted here.\n if (response.ok) return response;\n const text = await response.text();\n let envelope: unknown;\n try {\n envelope = JSON.parse(text) as unknown;\n } catch {\n return replayed(response, text);\n }\n if (!isGatewayErrorEnvelope(envelope)) return replayed(response, text);\n throw errorFromGatewayEnvelope(envelope, {\n model: modelOfBody(body) ?? route.provider,\n requestBodyValues: undefined,\n responseBody: text,\n responseHeaders: headersToObject(response.headers),\n status: response.status,\n url: context.config.transport.url\n });\n };\n return routed as typeof globalThis.fetch;\n}\n\n/** The model id out of a vendor body, for error reporting. */\nfunction modelOf(query: unknown): string | undefined {\n if (query === null || typeof query !== \"object\") return undefined;\n const model = (query as { model?: unknown }).model;\n return typeof model === \"string\" ? model : undefined;\n}\n\n/** The call options a routed model sees: ours are read out and removed. */\nfunction withoutOurOptions(\n options: LanguageModelV4CallOptions\n): LanguageModelV4CallOptions {\n const providerOptions = options.providerOptions;\n if (\n providerOptions === undefined ||\n !(PROVIDER_OPTIONS_KEY in providerOptions)\n ) {\n return options;\n }\n const rest = { ...providerOptions };\n delete rest[PROVIDER_OPTIONS_KEY];\n return { ...options, providerOptions: rest };\n}\n\n/** Adds our metadata block without dropping the vendor's own keys. */\nfunction mergeMetadata(\n existing: SharedV4ProviderMetadata | undefined,\n ours: SharedV4ProviderMetadata\n): SharedV4ProviderMetadata {\n return { ...existing, ...ours };\n}\n\n/**\n * The same metadata, in the shape an image result's provider metadata takes.\n *\n * `ImageModelV4ProviderMetadata` is not the shared shape: every provider block\n * must carry an `images` array, one entry per generated image, and the AI SDK\n * spreads that array when it merges the calls a multi-image request fanned out\n * into. A block without one makes `generateImage` throw, and only the array's\n * entries survive that merge, so ours goes inside it.\n */\nfunction metadataFor(\n result: object,\n ours: SharedV4ProviderMetadata\n): SharedV4ProviderMetadata {\n const images = (result as { images?: unknown }).images;\n if (!Array.isArray(images)) return ours;\n const block = ours[PROVIDER_OPTIONS_KEY] as JSONObject;\n return {\n ...ours,\n [PROVIDER_OPTIONS_KEY]: {\n ...block,\n images: images.map(() => ({ ...block })) as JSONArray\n }\n };\n}\n\n/**\n * The Workers AI knobs a routed vendor model cannot honour. They are not\n * dropped silently: the vendor decides its own reasoning, so a caller who set\n * `reasoningEffort` here is asking for something that never leaves.\n */\nfunction ignoredWarnings(resolved: ResolvedOptions): SharedV4Warning[] {\n const warnings: SharedV4Warning[] = [];\n for (const [option, value] of [\n [\"reasoningEffort\", resolved.reasoningEffort],\n [\"chatTemplateKwargs\", resolved.chatTemplateKwargs]\n ] as const) {\n if (value === undefined) continue;\n warnings.push({\n details: `\\`${option}\\` is a Workers AI setting and does not apply to a model routed through AI Gateway; use the vendor's own reasoning options instead.`,\n feature: option,\n type: \"unsupported\"\n });\n }\n return warnings;\n}\n\n/**\n * The Workers AI knobs a routed non-language model was asked with, added to\n * the result's own `warnings` when it has one.\n *\n * Only the per-call `providerOptions.cloudflare` bag can carry them here —\n * {@link RoutedModelOptions} leaves them off the per-model type — and only\n * some v4 result shapes have somewhere to put a warning: image, speech,\n * transcription and reranking results do, an embedding result does not.\n */\nfunction routedWarnings(\n result: object,\n resolved: ResolvedOptions\n): { warnings?: SharedV4Warning[] } {\n const existing = (result as { warnings?: unknown }).warnings;\n if (!Array.isArray(existing)) return {};\n const warnings = ignoredWarnings(resolved);\n if (warnings.length === 0) return {};\n return { warnings: [...(existing as SharedV4Warning[]), ...warnings] };\n}\n\n/**\n * Stamps the finish part with `providerMetadata.cloudflare`, and adds our own\n * warnings to the `stream-start` the vendor emitted.\n */\nfunction stampStream(\n metadata: () => SharedV4ProviderMetadata,\n warnings: SharedV4Warning[]\n): TransformStream<LanguageModelV4StreamPart, LanguageModelV4StreamPart> {\n return new TransformStream({\n transform(part, controller) {\n if (part.type === \"finish\") {\n controller.enqueue({\n ...part,\n providerMetadata: mergeMetadata(part.providerMetadata, metadata())\n });\n return;\n }\n if (part.type === \"stream-start\" && warnings.length > 0) {\n controller.enqueue({\n ...part,\n warnings: [...part.warnings, ...warnings]\n });\n return;\n }\n controller.enqueue(part);\n }\n });\n}\n\n/**\n * A `LanguageModelV4` that is the user's own vendor model, routed through AI\n * Gateway. Generation, parsing, tool handling and error shapes stay the\n * vendor's; only the transport is Cloudflare's.\n *\n * @experimental This surface is experimental and may change.\n */\nexport class GatewayLanguageModel implements LanguageModelV4 {\n readonly specificationVersion = \"v4\" as const;\n\n readonly #model: LanguageModelV4;\n readonly #options: GatewayModelOptions | undefined;\n readonly #config: LanguageModelConfig;\n\n constructor(\n model: LanguageModelV4,\n options: GatewayModelOptions | undefined,\n config: LanguageModelConfig\n ) {\n // Fail where the mistake was made, not one call later.\n requireConfig(model);\n this.#model = model;\n this.#options = options;\n this.#config = config;\n rememberOptions(this, options);\n }\n\n /** The vendor's own provider name — `anthropic.messages`, `openai.responses`. */\n get provider(): string {\n return this.#model.provider;\n }\n\n /** The vendor's own id spelling, which the gateway requires verbatim. */\n get modelId(): string {\n return this.#model.modelId;\n }\n\n get supportedUrls(): LanguageModelV4[\"supportedUrls\"] {\n return this.#model.supportedUrls;\n }\n\n /** The model this wraps, for callers that need the vendor object back. */\n get model(): LanguageModelV4 {\n return this.#model;\n }\n\n async doGenerate(\n options: LanguageModelV4CallOptions\n ): Promise<LanguageModelV4GenerateResult> {\n const call = parseCallOptions(options.providerOptions);\n const resolved = this.#resolve(call);\n const upstream = withoutOurOptions(options);\n const legOptions = withoutCallFallback(options);\n return this.#withFallback(\n call,\n (leg) => leg.doGenerate(legOptions),\n async () => {\n const capture: RouteCapture = {};\n const clone = this.#route(resolved, capture, options.abortSignal);\n const result = await clone.doGenerate(upstream);\n const warnings = ignoredWarnings(resolved);\n return {\n ...result,\n providerMetadata: mergeMetadata(\n result.providerMetadata,\n this.#metadata(resolved, capture)\n ),\n response: this.#response(result.response, capture),\n warnings:\n warnings.length > 0\n ? [...result.warnings, ...warnings]\n : result.warnings\n };\n }\n );\n }\n\n async doStream(\n options: LanguageModelV4CallOptions\n ): Promise<LanguageModelV4StreamResult> {\n const call = parseCallOptions(options.providerOptions);\n const resolved = this.#resolve(call);\n const upstream = withoutOurOptions(options);\n const legOptions = withoutCallFallback(options);\n return this.#withFallback(\n call,\n (leg) => leg.doStream(legOptions),\n async () => {\n const capture: RouteCapture = {};\n const clone = this.#route(resolved, capture, options.abortSignal);\n const result = await clone.doStream(upstream);\n return {\n ...result,\n response: this.#response(result.response, capture),\n stream: result.stream.pipeThrough(\n stampStream(\n () => this.#metadata(resolved, capture),\n ignoredWarnings(resolved)\n )\n )\n };\n },\n \"stream\"\n );\n }\n\n #route(\n resolved: ResolvedOptions,\n capture: RouteCapture,\n signal: AbortSignal | undefined\n ): LanguageModelV4 {\n return cloneWithFetch(\n this.#model,\n routedFetch({\n capture,\n config: this.#config,\n resolved,\n signal,\n vendorKey: this.#options?.vendorKey ?? \"gateway\"\n })\n );\n }\n\n #resolve(call: ModelOptions | undefined): ResolvedOptions {\n return resolveOptions(this.#config.providerGateway, this.#options, call);\n }\n\n #metadata(\n resolved: ResolvedOptions,\n capture: RouteCapture\n ): SharedV4ProviderMetadata {\n const response = capture.response ?? new Response(null);\n return cloudflareMetadata(\n this.modelId,\n resolved.gateway.id,\n response,\n this.#config.transport,\n capture.provider\n );\n }\n\n #response<T extends { headers?: Record<string, string> } | undefined>(\n response: T,\n capture: RouteCapture\n ): T {\n if (capture.response === undefined) return response;\n const headers = headersToObject(capture.response.headers);\n return { ...response, headers: { ...response?.headers, ...headers } } as T;\n }\n\n /**\n * The vendor model first, then each fallback leg. A leg named by id is a\n * Workers AI model; a leg that is a model object is asked as it stands, so\n * `ai()` has already wrapped it if it needed wrapping.\n */\n #withFallback<T>(\n call: ModelOptions | undefined,\n runLeg: (model: LanguageModelV4) => PromiseLike<T>,\n run: () => Promise<T>,\n mode: \"generate\" | \"stream\" = \"generate\"\n ): Promise<T> {\n const legs: FallbackLeg[] = fallbackLegs(this.#options, call);\n if (legs.length === 0) return run();\n const chain = (attempts: FallbackAttempt<T>[]): Promise<T> =>\n mode === \"stream\"\n ? (withStreamFallbackLegs(\n attempts as FallbackAttempt<LanguageModelV4StreamResult>[],\n this.#config.transport.url\n ) as Promise<T>)\n : withFallbackLegs(attempts, this.#config.transport.url);\n return chain([\n { model: this.modelId, run },\n ...legs.map((leg) => {\n const model = typeof leg === \"string\" ? this.#workersAI(leg) : leg;\n return { model: model.modelId, run: () => runLeg(model) };\n })\n ]);\n }\n\n /** A Workers AI leg, carrying this model's gateway options but no chain. */\n #workersAI(modelId: string): LanguageModelV4 {\n return new CloudflareLanguageModel(\n // Belt and braces: `ai()` and the per-call bag both gate their legs, so\n // any other id can only arrive from a caller that built the model\n // some other way — and it must not reach `env.AI.run` either.\n requireLanguageModelId(modelId),\n { ...this.#options, fallback: undefined },\n this.#config\n );\n }\n}\n\n/** The per-call shape every v4 model method takes, in the parts we read. */\ninterface RoutedCall {\n abortSignal?: AbortSignal;\n providerOptions?: SharedV4ProviderOptions;\n}\n\n/**\n * Routes any other AI SDK v4 model the vendor built — embedding, image,\n * speech, transcription — through the same provider-native request. Only\n * `fetch` is swapped; every `do…` method stays the vendor's, and its result\n * gains `providerMetadata.cloudflare` when the result is an object that can\n * carry one.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function routed<T extends object>(\n model: T,\n options: RoutedModelOptions | undefined,\n config: LanguageModelConfig\n): T {\n requireConfig(model as LanguageModelV4);\n return new Proxy(model, {\n get(target, property, receiver) {\n const value: unknown = Reflect.get(target, property, receiver);\n if (\n typeof value !== \"function\" ||\n typeof property !== \"string\" ||\n !property.startsWith(\"do\")\n ) {\n return value;\n }\n return async (call: RoutedCall): Promise<unknown> => {\n const resolved = resolveOptions(\n config.providerGateway,\n options,\n parseCallOptions(call?.providerOptions)\n );\n // Our per-call bag is ours: read here, never handed on, exactly as the\n // language path does. A `fallback` written there is deliberately not\n // acted on — this proxy is modality-blind, so it cannot build a leg\n // for whatever kind of model it wraps, and the option is not on its\n // type. A vendor id inside one is still refused, as everywhere.\n const upstream =\n call?.providerOptions === undefined\n ? call\n : (withoutOurOptions(\n call as unknown as LanguageModelV4CallOptions\n ) as unknown as RoutedCall);\n const capture: RouteCapture = {};\n const clone = cloneWithFetch(\n target as LanguageModelV4,\n routedFetch({\n capture,\n config,\n resolved,\n signal: call?.abortSignal,\n vendorKey: options?.vendorKey ?? \"gateway\"\n })\n );\n const method = Reflect.get(clone, property) as (\n argument: RoutedCall\n ) => Promise<unknown>;\n const result = await method.call(clone, upstream);\n if (result === null || typeof result !== \"object\") return result;\n const existing = (result as { providerMetadata?: unknown })\n .providerMetadata;\n return {\n ...result,\n ...routedWarnings(result, resolved),\n providerMetadata: mergeMetadata(\n existing as SharedV4ProviderMetadata | undefined,\n metadataFor(\n result,\n cloudflareMetadata(\n String((target as RoutableModel).modelId ?? \"\"),\n resolved.gateway.id,\n capture.response ?? new Response(null),\n config.transport,\n capture.provider\n )\n )\n )\n };\n };\n }\n });\n}\n","/**\n * Shared plumbing for the non-language models — image, transcription, speech\n * and reranking. They differ only in the body they build and the answer they\n * read; everything between (option merging, gateway headers, fallback, error\n * mapping, envelope unwrapping, provider metadata) is the same call.\n */\n\nimport type {\n SharedV4ProviderMetadata,\n SharedV4ProviderOptions,\n SharedV4Warning\n} from \"@ai-sdk/provider\";\nimport { CloudflareAIError, requireWorkersAIId } from \"../errors\";\nimport {\n DEFAULT_GATEWAY_ID,\n parseModalityCallOptions,\n resolveOptions,\n type ModelOptions,\n type ResolvedGateway\n} from \"../settings\";\nimport type { RawAudio } from \"../../core/transport\";\nimport {\n definedHeaders,\n errorFromResponse,\n headersToObject,\n unwrapEnvelope\n} from \"../transport\";\nimport { withFallback } from \"./fallback\";\nimport { cloudflareMetadata, type LanguageModelConfig } from \"./language\";\n\nimport { toBase64 } from \"../wires/shared\";\n\nexport { toBase64 };\n\n/** Everything a non-language model needs from the provider that created it. */\nexport type ModalityConfig = LanguageModelConfig;\n\n/** A run-path body plus whatever the conversion had to drop. */\nexport interface ModalityRequest {\n input: Record<string, unknown>;\n /** Audio sent as a raw body, for a model that takes one. */\n audio?: RawAudio;\n warnings: SharedV4Warning[];\n}\n\n/** One call on a non-language model, before the wire body is built. */\nexport interface ModalityCall {\n /** The per-call options bag, read for `providerOptions.cloudflare`. */\n providerOptions: SharedV4ProviderOptions | undefined;\n /** Extra request headers from the call. */\n headers: Record<string, string | undefined> | undefined;\n abortSignal: AbortSignal | undefined;\n /**\n * Builds the body for one leg. Called once per fallback attempt, because\n * the body shape depends on which model ends up answering.\n */\n build(modelId: string): ModalityRequest;\n /**\n * Validates one leg's answer, throwing when it lacks what the modality\n * needs. Runs inside the fallback loop, so an incomplete answer moves on to\n * the next leg instead of failing the call.\n */\n check?(answer: ModalityAnswer): void;\n}\n\n/** What the run path answered, decoded by content type. */\nexport interface ModalityAnswer {\n /** The model that answered — the fallback leg, when one was used. */\n modelId: string;\n /** The body that was sent, for `request.body` on the result. */\n input: Record<string, unknown>;\n warnings: SharedV4Warning[];\n headers: Record<string, string>;\n providerMetadata: SharedV4ProviderMetadata;\n /** The parsed JSON body, envelope unwrapped, or `undefined` for bytes. */\n json: unknown;\n /** The raw body, for the models that answer with PNG or MP3 bytes. */\n bytes: Uint8Array | undefined;\n /** The response content type, without parameters. */\n mediaType: string;\n timestamp: Date;\n /** The endpoint that answered, for error reporting. */\n url: string;\n}\n\n/** Whether the caller set any gateway option, the id included. */\nfunction gatewayConfigured(gateway: ResolvedGateway): boolean {\n const { id, ...options } = gateway;\n return id !== DEFAULT_GATEWAY_ID || Object.keys(options).length > 0;\n}\n\n/** The `unsupported` warning shape, which every modality needs. */\nexport function unsupported(\n feature: string,\n details?: string\n): SharedV4Warning {\n return {\n feature,\n type: \"unsupported\",\n ...(details === undefined ? {} : { details })\n };\n}\n\n/** Decodes base64 into bytes; passes `Uint8Array` input straight through. */\nexport function toBytes(data: Uint8Array | string): Uint8Array {\n if (typeof data !== \"string\") return data;\n const binary = atob(data);\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index++) {\n bytes[index] = binary.charCodeAt(index);\n }\n return bytes;\n}\n\n/**\n * A model over the Cloudflare run path that is not a language model. Holds\n * the one call path all four modalities share; each subclass only builds a\n * body and reads an answer.\n *\n * @experimental This surface is experimental and may change.\n */\nexport abstract class CloudflareModalityModel {\n readonly specificationVersion = \"v4\" as const;\n readonly provider = \"cloudflare\";\n readonly modelId: string;\n\n readonly #config: ModalityConfig;\n readonly #options: ModelOptions | undefined;\n\n constructor(\n modelId: string,\n options: ModelOptions | undefined,\n config: ModalityConfig\n ) {\n // A leg written as a string is a Workers AI id, and nothing else: the\n // same gate the language models apply, at the line that wrote the leg.\n options?.fallback?.forEach((leg) => {\n if (typeof leg === \"string\") requireWorkersAIId(leg);\n });\n this.modelId = modelId;\n this.#options = options;\n this.#config = config;\n }\n\n /** The endpoint this model calls, for error reporting. */\n protected get endpoint(): string {\n return this.#config.transport.url;\n }\n\n /**\n * Sends one call, trying each fallback leg in turn, and decodes the answer\n * as JSON or as raw bytes depending on what the model sent back.\n */\n protected async send(call: ModalityCall): Promise<ModalityAnswer> {\n const resolved = resolveOptions(\n this.#config.providerGateway,\n this.#options,\n parseModalityCallOptions(call.providerOptions)\n );\n const transport = this.#config.transport;\n return withFallback(\n this.modelId,\n resolved.fallback,\n transport.url,\n async (modelId) => {\n const request = call.build(modelId);\n // A raw audio body goes to Workers AI directly (see the transport),\n // so no gateway handles it and the gateway options do not apply.\n const direct = request.audio !== undefined;\n const sent =\n request.audio === undefined\n ? request.input\n : {\n ...request.input,\n audio: {\n body: toBase64(request.audio.bytes),\n contentType: request.audio.contentType\n }\n };\n const warnings =\n direct && gatewayConfigured(resolved.gateway)\n ? [\n ...request.warnings,\n unsupported(\n \"gateway\",\n `${modelId} goes to Workers AI directly, so the gateway options do not apply.`\n )\n ]\n : request.warnings;\n const response = await transport.run({\n ...(request.audio === undefined ? {} : { audio: request.audio }),\n gateway: resolved.gateway,\n headers: {\n // The AI SDK types these as `string | undefined`; an undefined\n // value must not reach the binding as the string \"undefined\".\n ...definedHeaders(call.headers),\n ...resolved.headers,\n ...(resolved.sessionAffinity === undefined\n ? {}\n : { \"x-session-affinity\": resolved.sessionAffinity })\n },\n input: request.input,\n model: modelId,\n signal: call.abortSignal\n });\n if (!response.ok) {\n throw await errorFromResponse(response, {\n model: modelId,\n requestBodyValues: sent,\n url: transport.url\n });\n }\n\n const mediaType = (response.headers.get(\"content-type\") ?? \"\")\n .split(\";\")[0]\n .trim()\n .toLowerCase();\n const body = await this.#decode(response, modelId, sent, mediaType);\n const answer: ModalityAnswer = {\n headers: headersToObject(response.headers),\n input: sent,\n mediaType,\n modelId,\n providerMetadata: cloudflareMetadata(\n modelId,\n direct ? undefined : resolved.gateway.id,\n response,\n transport\n ),\n timestamp: new Date(),\n url: transport.url,\n warnings,\n ...body\n };\n call.check?.(answer);\n return answer;\n }\n );\n }\n\n /**\n * Reads a 2xx body. A JSON content type is parsed and unwrapped; anything\n * else is the model's own bytes (PNG, JPEG, MP3). A JSON content type with a\n * body that will not parse is a provider failure, not a caller bug, so it\n * comes back as a {@link CloudflareAIError} rather than a bare `SyntaxError`.\n */\n async #decode(\n response: Response,\n modelId: string,\n input: Record<string, unknown>,\n mediaType: string\n ): Promise<{ json: unknown; bytes: Uint8Array | undefined }> {\n if (!mediaType.includes(\"json\")) {\n return {\n bytes: new Uint8Array(await response.arrayBuffer()),\n json: undefined\n };\n }\n let json: unknown;\n try {\n json = await response.json();\n } catch (error) {\n throw new CloudflareAIError({\n cause: error,\n code: \"provider-error\",\n isRetryable: false,\n message: `The model answered ${response.status} with a body that is not JSON.`,\n model: modelId,\n requestBodyValues: input,\n status: response.status,\n url: this.#config.transport.url\n });\n }\n return {\n bytes: undefined,\n json: unwrapEnvelope(json, {\n model: modelId,\n status: response.status,\n url: this.#config.transport.url\n })\n };\n }\n}\n","/**\n * Image generation over the Cloudflare run path.\n *\n * Two answer shapes exist and the content type tells them apart: the diffusion\n * models stream raw bytes (`image/png`), while `flux-1-schnell` and the\n * Leonardo models answer JSON `{ image: \"<base64>\" }` — and flux's base64 is\n * JPEG, so nothing here infers a media type from the model name.\n */\n\nimport type {\n ImageModelV4,\n ImageModelV4CallOptions,\n ImageModelV4File,\n ImageModelV4ProviderMetadata,\n ImageModelV4Result,\n ImageModelV4Usage,\n JSONArray,\n JSONObject,\n SharedV4Warning\n} from \"@ai-sdk/provider\";\nimport { buildImageInput, imageMediaTypeOf } from \"../../core/images\";\nimport { CloudflareAIError } from \"../errors\";\nimport { PROVIDER_OPTIONS_KEY, type ModelOptions } from \"../settings\";\nimport { count, record, text } from \"../wires/shared\";\nimport {\n CloudflareModalityModel,\n toBase64,\n toBytes,\n unsupported,\n type ModalityAnswer,\n type ModalityConfig,\n type ModalityRequest\n} from \"./modality\";\n\n/** Generation knobs read from `providerOptions.cloudflare`. */\ninterface ImageOptions {\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 /** What to keep out of the image. */\n negativePrompt?: string;\n /** How strongly img2img transforms the input image, between 0 and 1. */\n strength?: number;\n}\n\nfunction imageOptions(\n providerOptions: ImageModelV4CallOptions[\"providerOptions\"]\n): ImageOptions {\n const raw = record(providerOptions?.[PROVIDER_OPTIONS_KEY]) ?? {};\n const negativePrompt = text(raw.negativePrompt);\n return {\n ...(count(raw.steps) === undefined ? {} : { steps: count(raw.steps) }),\n ...(count(raw.guidance) === undefined\n ? {}\n : { guidance: count(raw.guidance) }),\n ...(count(raw.strength) === undefined\n ? {}\n : { strength: count(raw.strength) }),\n ...(negativePrompt === undefined ? {} : { negativePrompt })\n };\n}\n\n/** `1024x768` → `{ width: 1024, height: 768 }`. */\nfunction parseSize(\n size: `${number}x${number}`\n): { width: number; height: number } | undefined {\n const [width, height] = size.split(\"x\").map(Number);\n return Number.isFinite(width) && Number.isFinite(height)\n ? { height, width }\n : undefined;\n}\n\n/** The base64 bytes of a file the caller passed for img2img or masking. */\nfunction fileData(file: ImageModelV4File): string | undefined {\n if (file.type === \"file\") return toBase64(file.data);\n return undefined;\n}\n\n/**\n * Builds the run-path body. The knobs and the flux-1 subset rule live in\n * `core/images.ts`, shared with the pi-ai module so the two cannot drift; the\n * AI SDK call options and the `files`/`mask` byte handling are mapped here.\n */\nexport function buildImageRequest(\n modelId: string,\n options: ImageModelV4CallOptions\n): ModalityRequest {\n const warnings: SharedV4Warning[] = [];\n const extra = imageOptions(options.providerOptions);\n if (options.prompt === undefined) {\n warnings.push({\n message: \"Cloudflare image models require a prompt; sent an empty one.\",\n type: \"other\"\n });\n }\n if (options.aspectRatio !== undefined) {\n warnings.push(\n unsupported(\"aspectRatio\", \"Use `size` instead: Workers AI takes pixels.\")\n );\n }\n\n let size: { width: number; height: number } | undefined;\n if (options.size !== undefined) {\n size = parseSize(options.size);\n if (size === undefined) {\n warnings.push(unsupported(\"size\", `Could not read \"${options.size}\".`));\n }\n }\n\n const built = buildImageInput(modelId, options.prompt ?? \"\", {\n ...(size === undefined ? {} : { height: size.height, width: size.width }),\n ...(options.seed === undefined ? {} : { seed: options.seed }),\n ...(extra.steps === undefined ? {} : { steps: extra.steps }),\n ...(extra.guidance === undefined ? {} : { guidance: extra.guidance }),\n ...(extra.strength === undefined ? {} : { strength: extra.strength }),\n ...(extra.negativePrompt === undefined\n ? {}\n : { negativePrompt: extra.negativePrompt }),\n ...(options.mask === undefined ? {} : { mask: true }),\n ...(options.files?.[0] === undefined ? {} : { sourceImage: true })\n });\n const input = built.input;\n for (const warning of built.warnings) {\n warnings.push(unsupported(warning.feature, warning.message));\n }\n if (built.minimal) return { input, warnings };\n\n const source = options.files?.[0];\n if (source !== undefined) {\n const data = fileData(source);\n if (data === undefined) {\n warnings.push(\n unsupported(\"files\", \"Image URLs are not supported; send the bytes.\")\n );\n } else {\n input.image_b64 = data;\n }\n if ((options.files?.length ?? 0) > 1) {\n warnings.push(\n unsupported(\"files\", \"Only the first image is used for img2img.\")\n );\n }\n }\n if (options.mask !== undefined) {\n const data = fileData(options.mask);\n if (data === undefined) {\n warnings.push(\n unsupported(\"mask\", \"Mask URLs are not supported; send the bytes.\")\n );\n } else {\n input.mask = Array.from(toBytes(data));\n }\n }\n return { input, warnings };\n}\n\n/** One generated image, in whichever shape the model answered with. */\ninterface GeneratedImage {\n base64: string | undefined;\n bytes: Uint8Array | undefined;\n mediaType: string;\n}\n\nfunction readImage(answer: ModalityAnswer): GeneratedImage {\n if (answer.bytes !== undefined) {\n return {\n base64: undefined,\n bytes: answer.bytes,\n mediaType: answer.mediaType === \"\" ? \"image/png\" : answer.mediaType\n };\n }\n const body = record(answer.json) ?? {};\n const base64 = text(body.image);\n if (base64 === undefined) {\n throw new CloudflareAIError({\n code: \"provider-error\",\n data: answer.json,\n isRetryable: false,\n message: \"The image model answered JSON without an `image` field.\",\n model: answer.modelId,\n requestBodyValues: answer.input,\n url: answer.url\n });\n }\n // The bytes decide the media type: flux-1-schnell answers with JPEG despite\n // every other model here answering with PNG.\n return { base64, bytes: undefined, mediaType: imageMediaTypeOf(base64) };\n}\n\nfunction imageUsage(json: unknown): ImageModelV4Usage | undefined {\n const usage = record(record(json)?.usage);\n if (usage === undefined) return undefined;\n return {\n inputTokens: count(usage.prompt_tokens),\n outputTokens: count(usage.completion_tokens),\n totalTokens: count(usage.total_tokens)\n };\n}\n\n/**\n * An `ImageModelV4` over the Cloudflare text-to-image catalog.\n *\n * The run path generates one image per call, so `maxImagesPerCall` is 1 and\n * `generateImage` fans a larger `n` out itself; a direct `doGenerate` with\n * `n > 1` is fanned out here instead.\n *\n * @experimental This surface is experimental and may change.\n */\nexport class CloudflareImageModel\n extends CloudflareModalityModel\n implements ImageModelV4\n{\n readonly maxImagesPerCall = 1;\n\n constructor(\n modelId: string,\n options: ModelOptions | undefined,\n config: ModalityConfig\n ) {\n super(modelId, options, config);\n }\n\n async doGenerate(\n options: ImageModelV4CallOptions\n ): Promise<ImageModelV4Result> {\n const wanted = Math.max(1, options.n);\n const answers = await Promise.all(\n Array.from({ length: wanted }, () =>\n this.send({\n abortSignal: options.abortSignal,\n build: (modelId) => buildImageRequest(modelId, options),\n check: (answer) => {\n readImage(answer);\n },\n headers: options.headers,\n providerOptions: options.providerOptions\n })\n )\n );\n\n const first = answers[0];\n const generated = answers.map(readImage);\n const images = generated.some((image) => image.base64 !== undefined)\n ? generated.map(\n (image) => image.base64 ?? toBase64(image.bytes as Uint8Array)\n )\n : generated.map((image) => image.bytes as Uint8Array);\n const usage = imageUsage(first.json);\n\n return {\n images,\n providerMetadata: {\n [PROVIDER_OPTIONS_KEY]: {\n ...(first.providerMetadata[PROVIDER_OPTIONS_KEY] as JSONObject),\n // `generateImage` merges the calls it fans out into by spreading\n // each block's `images` array, and only those entries survive. Each\n // carries its own answer's metadata, which may come from a different\n // fallback leg than the first image's.\n images: generated.map((image, index) => ({\n ...(answers[index]?.providerMetadata[\n PROVIDER_OPTIONS_KEY\n ] as JSONObject),\n mediaType: image.mediaType\n })) as JSONArray\n }\n } as ImageModelV4ProviderMetadata,\n response: {\n headers: first.headers,\n modelId: first.modelId,\n timestamp: first.timestamp\n },\n ...(usage === undefined ? {} : { usage }),\n warnings: first.warnings\n };\n }\n}\n","/**\n * Reranking over the Cloudflare run path.\n *\n * The BAAI rerankers take `{ query, contexts: [{ text }], top_k? }` and answer\n * `{ response: [{ id, score }] }`, where `id` is the index of the context in\n * the request — which is exactly the AI SDK's `ranking` shape once renamed.\n */\n\nimport type {\n JSONObject,\n RerankingModelV4,\n RerankingModelV4CallOptions,\n RerankingModelV4Result,\n SharedV4Warning\n} from \"@ai-sdk/provider\";\nimport type { ModelOptions } from \"../settings\";\nimport { array, count, record } from \"../wires/shared\";\nimport {\n CloudflareModalityModel,\n type ModalityConfig,\n type ModalityRequest\n} from \"./modality\";\n\n/** Builds the run-path body for one reranking leg. */\nexport function buildRerankingRequest(\n options: RerankingModelV4CallOptions\n): ModalityRequest {\n const warnings: SharedV4Warning[] = [];\n const documents =\n options.documents.type === \"text\"\n ? options.documents.values\n : options.documents.values.map((value) => JSON.stringify(value));\n if (options.documents.type === \"object\") {\n warnings.push({\n details: \"Object documents are sent as JSON text.\",\n feature: \"documents\",\n type: \"compatibility\"\n });\n }\n\n const input: Record<string, unknown> = {\n contexts: documents.map((value) => ({ text: value })),\n query: options.query\n };\n if (options.topN !== undefined) input.top_k = options.topN;\n return { input, warnings };\n}\n\n/**\n * A `RerankingModelV4` over the Workers AI reranker catalog.\n *\n * @experimental This surface is experimental and may change.\n */\nexport class CloudflareRerankingModel\n extends CloudflareModalityModel\n implements RerankingModelV4\n{\n constructor(\n modelId: string,\n options: ModelOptions | undefined,\n config: ModalityConfig\n ) {\n super(modelId, options, config);\n }\n\n async doRerank(\n options: RerankingModelV4CallOptions\n ): Promise<RerankingModelV4Result> {\n const answer = await this.send({\n abortSignal: options.abortSignal,\n build: () => buildRerankingRequest(options),\n headers: options.headers,\n providerOptions: options.providerOptions\n });\n\n const body = record(answer.json) ?? {};\n const ranking = (array(body.response) ?? []).flatMap((entry) => {\n const row = record(entry);\n const index = count(row?.id);\n const relevanceScore = count(row?.score);\n if (index === undefined || relevanceScore === undefined) return [];\n return [{ index, relevanceScore }];\n });\n // The live model already answers in descending score order; sorting makes\n // that a guarantee of this provider rather than of one model.\n ranking.sort((left, right) => right.relevanceScore - left.relevanceScore);\n\n return {\n providerMetadata: answer.providerMetadata as Record<string, JSONObject>,\n ranking,\n response: {\n body: answer.json,\n headers: answer.headers,\n modelId: answer.modelId,\n timestamp: answer.timestamp\n },\n warnings: answer.warnings\n };\n }\n}\n","/**\n * Text-to-speech over the Cloudflare run path.\n *\n * Deepgram's Aura models take `{ text, speaker?, encoding?, container? }` and\n * answer with raw MP3 bytes (`content-type: audio/mpeg`, verified live).\n * MeloTTS takes `{ prompt, lang? }` and answers with WAV, or with JSON\n * `{ audio: \"<base64>\" }` — so the content type decides, never the model id.\n */\n\nimport type {\n JSONObject,\n SharedV4Warning,\n SpeechModelV4,\n SpeechModelV4CallOptions,\n SpeechModelV4Result\n} from \"@ai-sdk/provider\";\nimport { CloudflareAIError } from \"../errors\";\nimport type { ModelOptions } from \"../settings\";\nimport { record, text } from \"../wires/shared\";\nimport {\n CloudflareModalityModel,\n unsupported,\n type ModalityAnswer,\n type ModalityConfig,\n type ModalityRequest\n} from \"./modality\";\n\n/**\n * MeloTTS is the odd one out: the prompt key is `prompt`, the language key is\n * `lang`, and there is no voice.\n *\n * @see https://developers.cloudflare.com/workers-ai/models/melotts/\n */\nconst MELOTTS = \"@cf/myshell-ai/melotts\";\n\n/**\n * Output encodings Aura accepts. `outputFormat` maps onto this; anything else\n * is warned about rather than sent, because the run path validates the enum.\n *\n * @see https://developers.cloudflare.com/workers-ai/models/aura-1/\n */\nconst AURA_ENCODINGS = new Set([\n \"linear16\",\n \"flac\",\n \"mulaw\",\n \"alaw\",\n \"mp3\",\n \"opus\",\n \"aac\"\n]);\n\n/** Builds the run-path body for one speech leg. */\nexport function buildSpeechRequest(\n modelId: string,\n options: SpeechModelV4CallOptions\n): ModalityRequest {\n const warnings: SharedV4Warning[] = [];\n if (options.speed !== undefined) {\n warnings.push(\n unsupported(\"speed\", \"Workers AI speech models do not take a speed.\")\n );\n }\n if (options.instructions !== undefined) {\n warnings.push(\n unsupported(\n \"instructions\",\n \"Workers AI speech models take text, not instructions.\"\n )\n );\n }\n\n if (modelId === MELOTTS) {\n const input: Record<string, unknown> = { prompt: options.text };\n if (options.language !== undefined) input.lang = options.language;\n if (options.voice !== undefined) {\n warnings.push(unsupported(\"voice\", `${MELOTTS} has a single voice.`));\n }\n if (options.outputFormat !== undefined) {\n warnings.push(\n unsupported(\"outputFormat\", `${MELOTTS} picks its own audio format.`)\n );\n }\n return { input, warnings };\n }\n\n const input: Record<string, unknown> = { text: options.text };\n if (options.voice !== undefined) input.speaker = options.voice;\n if (options.outputFormat !== undefined) {\n if (AURA_ENCODINGS.has(options.outputFormat)) {\n input.encoding = options.outputFormat;\n } else {\n warnings.push(\n unsupported(\n \"outputFormat\",\n `Expected one of ${[...AURA_ENCODINGS].join(\", \")}.`\n )\n );\n }\n }\n if (options.language !== undefined) {\n warnings.push(\n unsupported(\n \"language\",\n \"Aura picks its language from the model id, e.g. @cf/deepgram/aura-2-es.\"\n )\n );\n }\n return { input, warnings };\n}\n\n/**\n * The audio in one answer. Bytes stay bytes and base64 stays base64: the AI\n * SDK converts either way on demand, and converting here would only lose\n * fidelity.\n */\nfunction readAudio(answer: ModalityAnswer): string | Uint8Array {\n if (answer.bytes !== undefined) return answer.bytes;\n const body = record(answer.json) ?? {};\n const encoded = text(body.audio);\n if (encoded === undefined) {\n throw new CloudflareAIError({\n code: \"provider-error\",\n data: answer.json,\n isRetryable: false,\n message: \"The speech model answered JSON without an `audio` field.\",\n model: answer.modelId,\n requestBodyValues: answer.input,\n url: answer.url\n });\n }\n return encoded;\n}\n\n/**\n * A `SpeechModelV4` over the Workers AI text-to-speech catalog.\n *\n * @experimental This surface is experimental and may change.\n */\nexport class CloudflareSpeechModel\n extends CloudflareModalityModel\n implements SpeechModelV4\n{\n constructor(\n modelId: string,\n options: ModelOptions | undefined,\n config: ModalityConfig\n ) {\n super(modelId, options, config);\n }\n\n async doGenerate(\n options: SpeechModelV4CallOptions\n ): Promise<SpeechModelV4Result> {\n const answer = await this.send({\n abortSignal: options.abortSignal,\n build: (modelId) => buildSpeechRequest(modelId, options),\n check: (answer) => {\n readAudio(answer);\n },\n headers: options.headers,\n providerOptions: options.providerOptions\n });\n\n const audio = readAudio(answer);\n\n return {\n audio,\n providerMetadata: answer.providerMetadata as Record<string, JSONObject>,\n request: { body: answer.input },\n response: {\n headers: answer.headers,\n modelId: answer.modelId,\n timestamp: answer.timestamp\n },\n warnings: answer.warnings\n };\n }\n}\n","/**\n * Speech recognition over the Cloudflare run path.\n *\n * `whisper-large-v3-turbo` takes the audio as base64 (`{ audio: \"<base64>\" }`,\n * verified live); the two older whisper ids take it as an unsigned-byte array.\n * Deepgram's Nova-3 takes it as a raw body (`audio: { body, contentType }`),\n * which the transport sends as one, its other fields alongside. Flux takes\n * websocket connections only, so it is refused with a clear error.\n */\n\nimport type {\n JSONObject,\n SharedV4Warning,\n TranscriptionModelV4,\n TranscriptionModelV4CallOptions,\n TranscriptionModelV4Result\n} from \"@ai-sdk/provider\";\nimport { CloudflareAIError } from \"../errors\";\nimport { PROVIDER_OPTIONS_KEY, type ModelOptions } from \"../settings\";\nimport { array, count, record, text } from \"../wires/shared\";\nimport {\n CloudflareModalityModel,\n toBase64,\n toBytes,\n unsupported,\n type ModalityConfig,\n type ModalityRequest\n} from \"./modality\";\n\n/**\n * Whisper ids that take the audio as an unsigned-byte array rather than as\n * base64.\n *\n * @see https://developers.cloudflare.com/workers-ai/models/whisper/\n */\nconst BYTE_ARRAY_AUDIO = new Set([\n \"@cf/openai/whisper\",\n \"@cf/openai/whisper-tiny-en\"\n]);\n\n/**\n * Models that declare `audio: { body, contentType }`. JSON cannot carry that\n * body (base64 and byte arrays answer `400 required properties at '/audio' are\n * 'body,contentType'`), so the audio travels as a raw body.\n */\nconst RAW_AUDIO = new Set([\"@cf/deepgram/nova-3\"]);\n\n/** Deepgram's Flux answers `only supports websocket connections` over HTTP. */\nconst WEBSOCKET_ONLY = new Set([\"@cf/deepgram/flux\"]);\n\n/** Recognition knobs read from `providerOptions.cloudflare`. */\ninterface TranscriptionOptions {\n language?: string;\n /** `\"transcribe\"` (the default) or `\"translate\"`. */\n task?: string;\n /** Context for the model about what the audio contains. */\n initialPrompt?: string;\n /** Text prepended to the transcript to steer it. */\n prefix?: string;\n /** Run voice-activity detection before transcribing. */\n vadFilter?: boolean;\n}\n\nfunction transcriptionOptions(\n providerOptions: TranscriptionModelV4CallOptions[\"providerOptions\"]\n): TranscriptionOptions {\n const raw = record(providerOptions?.[PROVIDER_OPTIONS_KEY]) ?? {};\n const vadFilter = raw.vadFilter;\n return {\n ...(text(raw.language) === undefined\n ? {}\n : { language: text(raw.language) }),\n ...(text(raw.task) === undefined ? {} : { task: text(raw.task) }),\n ...(text(raw.initialPrompt) === undefined\n ? {}\n : { initialPrompt: text(raw.initialPrompt) }),\n ...(text(raw.prefix) === undefined ? {} : { prefix: text(raw.prefix) }),\n ...(typeof vadFilter === \"boolean\" ? { vadFilter } : {})\n };\n}\n\n/**\n * Builds the request for a raw-audio model: the audio as a raw body, and\n * `language` as a field. The whisper-only options have no equivalent there.\n */\nfunction buildRawAudioRequest(\n modelId: string,\n options: TranscriptionModelV4CallOptions,\n extra: TranscriptionOptions\n): ModalityRequest {\n const warnings: SharedV4Warning[] = [];\n for (const feature of [\n \"task\",\n \"initialPrompt\",\n \"prefix\",\n \"vadFilter\"\n ] as const) {\n if (extra[feature] !== undefined) {\n warnings.push(unsupported(feature, `${modelId} has no ${feature}.`));\n }\n }\n return {\n audio: { bytes: toBytes(options.audio), contentType: options.mediaType },\n input: extra.language === undefined ? {} : { language: extra.language },\n warnings\n };\n}\n\n/** Builds the run-path body for one leg. */\nexport function buildTranscriptionRequest(\n modelId: string,\n options: TranscriptionModelV4CallOptions\n): ModalityRequest {\n const warnings: SharedV4Warning[] = [];\n const extra = transcriptionOptions(options.providerOptions);\n if (RAW_AUDIO.has(modelId)) {\n return buildRawAudioRequest(modelId, options, extra);\n }\n const input: Record<string, unknown> = BYTE_ARRAY_AUDIO.has(modelId)\n ? { audio: Array.from(toBytes(options.audio)) }\n : { audio: toBase64(options.audio) };\n if (extra.language !== undefined) input.language = extra.language;\n if (extra.task !== undefined) input.task = extra.task;\n if (extra.initialPrompt !== undefined) {\n input.initial_prompt = extra.initialPrompt;\n }\n if (extra.prefix !== undefined) input.prefix = extra.prefix;\n if (extra.vadFilter !== undefined) input.vad_filter = extra.vadFilter;\n return { input, warnings };\n}\n\ninterface Segment {\n text: string;\n startSecond: number;\n endSecond: number;\n}\n\n/** What one transcription answer reads as, whichever family sent it. */\ninterface Transcript {\n text: string;\n segments: Segment[];\n language: string | undefined;\n durationInSeconds: number | undefined;\n}\n\n/** Reads a timed `{ text|word, start, end }` entry as a segment. */\nfunction timed(entry: unknown, textKeys: string[]): Segment[] {\n const item = record(entry);\n if (item === undefined) return [];\n const value = textKeys.map((key) => text(item[key])).find(Boolean);\n if (value === undefined) return [];\n return [\n {\n endSecond: count(item.end) ?? 0,\n startSecond: count(item.start) ?? 0,\n text: value\n }\n ];\n}\n\n/**\n * Reads a Deepgram answer: `results.channels[0].alternatives[0]`. Its\n * sentences are the segments when it sends paragraphs, and its words\n * otherwise.\n */\nfunction readDeepgram(body: Record<string, unknown>): Transcript {\n const channel = record(array(record(body.results)?.channels)?.[0]);\n const alternative = record(array(channel?.alternatives)?.[0]);\n const paragraphs = array(record(alternative?.paragraphs)?.paragraphs) ?? [];\n const sentences = paragraphs.flatMap(\n (paragraph) => array(record(paragraph)?.sentences) ?? []\n );\n const segments =\n sentences.length > 0\n ? sentences.flatMap((sentence) => timed(sentence, [\"text\"]))\n : (array(alternative?.words) ?? []).flatMap((word) =>\n timed(word, [\"punctuated_word\", \"word\"])\n );\n return {\n durationInSeconds: count(record(body.metadata)?.duration),\n language:\n text(array(alternative?.languages)?.[0]) ??\n text(channel?.detected_language),\n segments,\n text: text(alternative?.transcript) ?? \"\"\n };\n}\n\n/** Reads a whisper answer. */\nfunction readWhisper(body: Record<string, unknown>): Transcript {\n const info = record(body.transcription_info);\n return {\n durationInSeconds: count(info?.duration),\n language: text(info?.language),\n segments: readSegments(body),\n text: text(body.text) ?? \"\"\n };\n}\n\n/**\n * Reads segments out of a whisper answer. `segments` is what the large models\n * send; the smaller ones send only `words`, whose timings are the best segment\n * boundaries available.\n */\nfunction readSegments(body: Record<string, unknown>): Segment[] {\n const segments = array(body.segments);\n if (segments !== undefined) {\n return segments.flatMap((entry) => {\n const segment = record(entry);\n const value = text(segment?.text);\n if (segment === undefined || value === undefined) return [];\n return [\n {\n endSecond: count(segment.end) ?? 0,\n startSecond: count(segment.start) ?? 0,\n text: value\n }\n ];\n });\n }\n return (array(body.words) ?? []).flatMap((entry) => {\n const word = record(entry);\n const value = text(word?.word);\n if (word === undefined || value === undefined) return [];\n return [\n {\n endSecond: count(word.end) ?? 0,\n startSecond: count(word.start) ?? 0,\n text: value\n }\n ];\n });\n}\n\n/**\n * A `TranscriptionModelV4` over the Workers AI speech-recognition catalog.\n *\n * @experimental This surface is experimental and may change.\n */\nexport class CloudflareTranscriptionModel\n extends CloudflareModalityModel\n implements TranscriptionModelV4\n{\n constructor(\n modelId: string,\n options: ModelOptions | undefined,\n config: ModalityConfig\n ) {\n super(modelId, options, config);\n }\n\n async doGenerate(\n options: TranscriptionModelV4CallOptions\n ): Promise<TranscriptionModelV4Result> {\n const answer = await this.send({\n abortSignal: options.abortSignal,\n // Checked per leg, so an unsupported model is skipped without a request\n // and the next leg of a fallback chain still runs.\n build: (modelId) => {\n if (WEBSOCKET_ONLY.has(modelId)) {\n throw new CloudflareAIError({\n code: \"bad-request\",\n isRetryable: false,\n message:\n `${modelId} takes websocket connections only. Use ` +\n \"@cf/deepgram/nova-3 or @cf/openai/whisper-large-v3-turbo.\",\n model: modelId,\n requestBodyValues: undefined,\n url: this.endpoint\n });\n }\n return buildTranscriptionRequest(modelId, options);\n },\n headers: options.headers,\n providerOptions: options.providerOptions\n });\n\n const body = record(answer.json) ?? {};\n // The answer's shape decides how to read it, never the model id.\n const transcript =\n record(body.results) === undefined\n ? readWhisper(body)\n : readDeepgram(body);\n return {\n durationInSeconds: transcript.durationInSeconds,\n language: transcript.language,\n providerMetadata: answer.providerMetadata as Record<string, JSONObject>,\n request: { body: JSON.stringify(answer.input) },\n response: {\n body: answer.json,\n headers: answer.headers,\n modelId: answer.modelId,\n timestamp: answer.timestamp\n },\n segments: transcript.segments,\n text: transcript.text,\n warnings: answer.warnings\n };\n }\n}\n","/**\n * `agents/models/ai-sdk` — Cloudflare's AI SDK provider.\n *\n * Two call forms, through the `AI` binding or, with `{ accountId, apiToken }`,\n * over HTTP:\n *\n * 1. **A string** runs on `env.AI.run`: `ai(\"@cf/…\")` is a Workers AI model,\n * `ai(\"<author>/<model>\")` a model from the AI Gateway catalog in the\n * gateway's own spelling (`anthropic/claude-opus-4.8`), and\n * `ai(\"dynamic/<route>\")` a dynamic route on your gateway. Every one speaks\n * chat completions, so one request builder and one parser serve them all.\n * 2. **A vendor's own model**, `ai(anthropic(\"claude-opus-4-8\"))`, goes to AI\n * Gateway's provider-native path unchanged: the vendor's package builds the\n * request and parses the answer, and only the transport is ours.\n *\n * The gateway is an option, not a product: caching, logging, metadata,\n * timeouts and retries are options on the call, the `default` gateway is\n * created on first use, and Unified Billing means no vendor key.\n *\n * ```ts\n * import { createAI } from \"agents/models/ai-sdk\";\n * import { createAnthropic } from \"@ai-sdk/anthropic\";\n * import { generateText } from \"ai\";\n *\n * const ai = createAI({ binding: env.AI, id: \"prod\" });\n * const anthropic = createAnthropic({ apiKey: \"cloudflare\" });\n *\n * await generateText({ model: ai(\"anthropic/claude-opus-4.8\"), prompt: \"Hi\" });\n * await generateText({ model: ai(anthropic(\"claude-opus-4-8\")), prompt: \"Hi\" });\n * ```\n *\n * @experimental Everything exported here is experimental: the surface may\n * change in a minor release while the unified catalog settles.\n *\n * @module\n */\n\nimport type {\n EmbeddingModelV4,\n ImageModelV4,\n LanguageModelV4,\n RerankingModelV4,\n SpeechModelV4,\n TranscriptionModelV4\n} from \"@ai-sdk/provider\";\nimport type {\n CloudflareEmbeddingModelId,\n CloudflareImageModelId,\n CloudflareRerankingModelId,\n CloudflareSpeechModelId,\n CloudflareTranscriptionModelId\n} from \"../core/catalog\";\nimport { requireLanguageModelId } from \"./errors\";\nimport { CloudflareEmbeddingModel } from \"./models/embedding\";\nimport { GatewayLanguageModel, routed } from \"./models/gateway\";\nimport { CloudflareImageModel } from \"./models/image\";\nimport {\n CloudflareLanguageModel,\n type LanguageModelConfig\n} from \"./models/language\";\nimport { CloudflareRerankingModel } from \"./models/reranking\";\nimport { CloudflareSpeechModel } from \"./models/speech\";\nimport { CloudflareTranscriptionModel } from \"./models/transcription\";\nimport {\n gatewayLayerOf,\n mergeModelOptions,\n optionsOf,\n type AISettings,\n type CloudflareLanguageModelId,\n type FallbackLeg,\n type GatewayModelOptions,\n type ModalityOptions,\n type ModelOptions,\n type RoutedModelOptions\n} from \"./settings\";\nimport { createTransport } from \"./transport\";\n\nexport type {\n CatalogModelId,\n CloudflareEmbeddingModelId,\n CloudflareImageModelId,\n CloudflareRerankingModelId,\n CloudflareSpeechModelId,\n CloudflareTranscriptionModelId,\n DynamicRouteId,\n KnownImageModelId,\n KnownSpeechModelId,\n WorkersAIModelId\n} from \"../core/catalog\";\nexport {\n CloudflareAIError,\n type CloudflareAIAttempt,\n type CloudflareAIErrorCode\n} from \"./errors\";\nexport { GatewayLanguageModel } from \"./models/gateway\";\nexport type { CloudflareMetadata } from \"./models/language\";\nexport type {\n AISettings,\n CloudflareLanguageModelId,\n FallbackLeg,\n GatewayModelOptions,\n GatewayOptions,\n ModalityOptions,\n ModelOptions,\n ProviderGatewaySettings,\n RoutedModelOptions,\n VendorKeyOptions\n} from \"./settings\";\n\n/** Whether a value is a model object rather than a model id. */\nfunction isModel(value: unknown): value is LanguageModelV4 {\n return typeof value === \"object\" && value !== null;\n}\n\n/**\n * The provider `createAI` returns. Call it with a model id — a Workers AI id,\n * an AI Gateway catalog id, or a dynamic route — or with a model another\n * provider built.\n *\n * It satisfies `ProviderV4`, so it drops into\n * `createProviderRegistry({ cloudflare: ai })` and into\n * `globalThis.AI_SDK_DEFAULT_PROVIDER`, where the AI SDK resolves a bare\n * `model: \"@cf/…\"` or `\"openai/gpt-5.5\"` string through it.\n *\n * @experimental This surface is experimental and may change.\n */\nexport interface AI {\n /**\n * A language model: `@cf/…` (Workers AI), `<author>/<model>` (the AI\n * Gateway catalog, in its spelling), or `dynamic/<route>`.\n */\n (modelId: CloudflareLanguageModelId, options?: ModelOptions): LanguageModelV4;\n /**\n * Any AI SDK v4 language model, sent to AI Gateway's provider-native path\n * with its own request and parser.\n */\n (model: LanguageModelV4, options?: GatewayModelOptions): LanguageModelV4;\n /** The AI SDK provider specification this implements. */\n readonly specificationVersion: \"v4\";\n /** Same as calling the provider directly. */\n languageModel(\n modelId: CloudflareLanguageModelId,\n options?: ModelOptions\n ): LanguageModelV4;\n languageModel(\n model: LanguageModelV4,\n options?: GatewayModelOptions\n ): LanguageModelV4;\n /** The `ProviderV4` shape: a registry resolves models by string alone. */\n languageModel(modelId: string, options?: ModelOptions): LanguageModelV4;\n /**\n * Any other v4 model a vendor built — embedding, image, speech,\n * transcription — sent to AI Gateway's provider-native path with its own\n * code intact.\n */\n routed<T extends object>(model: T, options?: RoutedModelOptions): T;\n /** A text-embedding model from the Workers AI catalog. */\n embedding(\n modelId: CloudflareEmbeddingModelId,\n options?: ModalityOptions\n ): EmbeddingModelV4;\n /** Alias of {@link AI.embedding}, the `ProviderV4` method name. */\n embeddingModel(\n modelId: CloudflareEmbeddingModelId,\n options?: ModalityOptions\n ): EmbeddingModelV4;\n /**\n * Alias of {@link AI.embedding}.\n *\n * @deprecated `embeddingModel` is the `ProviderV4` name; this is the older\n * `ProviderV2`/`ProviderV3` spelling, kept for one release.\n */\n textEmbeddingModel(\n modelId: CloudflareEmbeddingModelId,\n options?: ModalityOptions\n ): EmbeddingModelV4;\n /** A text-to-image model from the Workers AI catalog. */\n image(\n modelId: CloudflareImageModelId,\n options?: ModalityOptions\n ): ImageModelV4;\n /** Alias of {@link AI.image}, the `ProviderV4` method name. */\n imageModel(\n modelId: CloudflareImageModelId,\n options?: ModalityOptions\n ): ImageModelV4;\n /** A speech-recognition model from the Workers AI catalog. */\n transcription(\n modelId: CloudflareTranscriptionModelId,\n options?: ModalityOptions\n ): TranscriptionModelV4;\n /** Alias of {@link AI.transcription}, the `ProviderV4` method name. */\n transcriptionModel(\n modelId: CloudflareTranscriptionModelId,\n options?: ModalityOptions\n ): TranscriptionModelV4;\n /** A text-to-speech model from the Workers AI catalog. */\n speech(\n modelId: CloudflareSpeechModelId,\n options?: ModalityOptions\n ): SpeechModelV4;\n /** Alias of {@link AI.speech}, the `ProviderV4` method name. */\n speechModel(\n modelId: CloudflareSpeechModelId,\n options?: ModalityOptions\n ): SpeechModelV4;\n /** A reranking model from the Workers AI catalog. */\n reranking(\n modelId: CloudflareRerankingModelId,\n options?: ModalityOptions\n ): RerankingModelV4;\n /** Alias of {@link AI.reranking}, the `ProviderV4` method name. */\n rerankingModel(\n modelId: CloudflareRerankingModelId,\n options?: ModalityOptions\n ): RerankingModelV4;\n}\n\n/**\n * Creates a provider over Workers AI and the AI Gateway catalog.\n *\n * A Workers AI id goes to Workers AI and a catalog id or dynamic route to AI\n * Gateway's `/run`, both on `env.AI.run`; a vendor's model object goes to AI\n * Gateway's provider-native path. With `{ accountId, apiToken }` instead of\n * `binding`, the same requests go to the REST API and to\n * `gateway.ai.cloudflare.com`. Gateway\n * options are flat (`id`, `cacheTtl`, …) or nested under `gateway`; per-model\n * options and per-call `providerOptions.cloudflare` override them in that\n * order.\n *\n * ```ts\n * const ai = createAI({ binding: env.AI, id: \"prod\", cacheTtl: 60 });\n *\n * ai(\"@cf/zai-org/glm-4.7-flash\");\n * ai(\"anthropic/claude-opus-4.8\", { fallback: [\"openai/gpt-5.5\"] });\n * ai.embedding(\"@cf/baai/bge-base-en-v1.5\");\n * ```\n *\n * @experimental This surface is experimental and may change.\n */\nexport function createAI(settings: AISettings): AI {\n const config: LanguageModelConfig = {\n providerGateway: settings,\n transport: createTransport(settings)\n };\n\n /**\n * Fallback legs are normalized once, here. A leg written as an id is gated\n * at the line that wrote it; a model object is routed like `ai(model)`.\n *\n * A leg inherits the chain's *gateway* options and nothing else. The rest of\n * the bag — `reasoningEffort`, `chatTemplateKwargs`, `headers`,\n * `sessionAffinity`, `vendorKey` — was written for the model it was written\n * on, and a leg that was configured with its own keeps every one of them.\n */\n const normalize = (\n options?: GatewayModelOptions\n ): GatewayModelOptions | undefined => {\n if (options?.fallback === undefined) return options;\n const inherited: ModelOptions = gatewayLayerOf(options);\n return {\n ...options,\n fallback: options.fallback.map((leg: FallbackLeg) =>\n typeof leg === \"string\"\n ? requireLanguageModelId(leg)\n : languageModel(leg, inherited)\n )\n };\n };\n\n function languageModel(\n model: CloudflareLanguageModelId | LanguageModelV4,\n options?: GatewayModelOptions\n ): LanguageModelV4 {\n const resolved = normalize(options);\n if (!isModel(model)) {\n return new CloudflareLanguageModel(\n requireLanguageModelId(model),\n resolved,\n config\n );\n }\n // Already ours: layer the options over the model's own rather than wrap it\n // a second time, so nothing it was configured with is dropped. The merged\n // bag's legs are normalized too, so a chain configured earlier moves with\n // the model onto the gateway named here.\n if (model instanceof CloudflareLanguageModel) {\n const merged = normalize(mergeModelOptions(optionsOf(model), resolved));\n return new CloudflareLanguageModel(model.modelId, merged, config);\n }\n if (model instanceof GatewayLanguageModel) {\n const merged = normalize(mergeModelOptions(optionsOf(model), resolved));\n return new GatewayLanguageModel(model.model, merged, config);\n }\n return new GatewayLanguageModel(model, resolved, config);\n }\n\n const embedding = (\n modelId: CloudflareEmbeddingModelId,\n options?: ModalityOptions\n ): EmbeddingModelV4 => new CloudflareEmbeddingModel(modelId, options, config);\n\n const image = (\n modelId: CloudflareImageModelId,\n options?: ModalityOptions\n ): ImageModelV4 => new CloudflareImageModel(modelId, options, config);\n\n const transcription = (\n modelId: CloudflareTranscriptionModelId,\n options?: ModalityOptions\n ): TranscriptionModelV4 =>\n new CloudflareTranscriptionModel(modelId, options, config);\n\n const speech = (\n modelId: CloudflareSpeechModelId,\n options?: ModalityOptions\n ): SpeechModelV4 => new CloudflareSpeechModel(modelId, options, config);\n\n const reranking = (\n modelId: CloudflareRerankingModelId,\n options?: ModalityOptions\n ): RerankingModelV4 => new CloudflareRerankingModel(modelId, options, config);\n\n const provider = (\n model: CloudflareLanguageModelId | LanguageModelV4,\n options?: GatewayModelOptions\n ): LanguageModelV4 => languageModel(model, options);\n\n return Object.assign(provider, {\n embedding,\n embeddingModel: embedding,\n image,\n imageModel: image,\n languageModel,\n reranking,\n rerankingModel: reranking,\n routed: <T extends object>(model: T, options?: RoutedModelOptions): T =>\n routed(model, options, config),\n specificationVersion: \"v4\" as const,\n speech,\n speechModel: speech,\n textEmbeddingModel: embedding,\n transcription,\n transcriptionModel: transcription\n }) as AI;\n}\n"],"mappings":";;;;;;;;;;;AA2BA,SAAgB,YACd,SACA,SACW;CACX,uBAAO,IAAI,UACT,YAAY,aACR,IAAI,QAAQ,4OACZ,IAAI,QAAQ,gJAClB;AACF;;;;;;AAOA,SAAgB,mBAAsC,SAAiB;CACrE,IAAI,iBAAiB,OAAO,GAC1B,MAAM,IAAI,UACR,IAAI,QAAQ,iIAAiI,QAAQ,uFACvJ;CAEF,IAAI,CAAC,QAAQ,WAAW,MAAM,GAAG,MAAM,YAAY,SAAS,YAAY;CACxE,OAAO;AACT;;AAGA,SAAS,kBAAkB,SAA0B;CACnD,OAAO,yBAAyB,OAAO,KAAK,iBAAiB,OAAO;AACtE;;;;;;;;AASA,SAAgB,uBAA0C,SAAiB;CACzE,IAAI,CAAC,kBAAkB,OAAO,GAAG,MAAM,YAAY,SAAS,UAAU;CACtE,OAAO;AACT;;;;;;;;;;AAWA,IAAa,oBAAb,MAAa,0BAA0B,aAAa;CAYlD,YAAY,SAcT;EACD,MAAM;GACJ,OAAO,QAAQ;GACf,MAAM,QAAQ;GACd,aAAa,QAAQ,eAAe,kBAAkB,QAAQ,MAAM;GACpE,SAAS,QAAQ;GACjB,mBAAmB,QAAQ;GAC3B,cAAc,QAAQ;GACtB,iBAAiB,QAAQ;GACzB,YAAY,QAAQ;GACpB,KAAK,QAAQ;EACf,CAAC;EACD,KAAK,OAAO;EACZ,KAAK,SAAS,QAAQ;EACtB,KAAK,OAAO,QAAQ;EACpB,KAAK,QAAQ,QAAQ;EACrB,KAAK,QAAQ,QAAQ;EACrB,KAAK,WAAW,QAAQ;CAC1B;;CAGA,OAAO,SAAS,OAAiD;EAC/D,OAAO,IAAI,kBAAkB;GAC3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EACA,YAAY;EACZ;EACA;EACA,gBAAgB;EAChB,SAA2B,OAAU,YACnC,OAAO,OAAO,SAAS,MAAM;EAC/B,sBAAsB;EACtB;EACA,aAAa;EACb,oBAAoB;EACpB;EACA,oBAAoB;CACtB,CAAC;AACH"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"browser-DccPw_wW.js","names":[],"sources":["../src/browser/providers/provider-adapter.ts","../src/browser/providers/browser-run.ts","../src/browser/browser.ts"],"sourcesContent":["/**\n * The internal seam between {@link Browser} and the service that runs its\n * browser. A provider is the public, plain-data config a host passes\n * (`browserRun(env.BROWSER)`); its adapter is the code that does the work.\n * `Browser` keeps everything that doesn't depend on the provider — the\n * durable record, locks, restart detection, scopes, and activity touches —\n * and calls the adapter for the rest.\n *\n * Not exported from `agents/browser`: the provider set is closed, and this\n * interface may change as providers are added.\n */\n\nimport type { CdpConnection } from \"../cdp-connection\";\nimport type { BrowserLiveView, LiveViewMode } from \"../live-view\";\nimport type { SearchableCdpSpec } from \"../spec\";\n\n/**\n * Thrown by {@link BrowserProviderAdapter.connect} when the session no longer\n * exists upstream (closed, expired, or reclaimed). `Browser` treats it as\n * \"this browser is lost\" and replaces it; any other error is passed on.\n */\nexport class BrowserSessionGoneError extends Error {\n constructor(\n readonly sessionId: string,\n options?: { cause?: unknown }\n ) {\n super(`Browser session gone: ${sessionId}`, options);\n this.name = \"BrowserSessionGoneError\";\n }\n}\n\nexport interface BrowserProviderAdapter {\n /** Start a new browser session. */\n create(): Promise<{ sessionId: string }>;\n /**\n * Whether the session still exists. `true` means alive and `false` means\n * definitely gone. Throw when the answer is unknown (a 5xx, a network\n * error): `Browser` discards the browser on `false`, so a flaky probe must\n * never report it.\n */\n isAlive(sessionId: string): Promise<boolean>;\n /**\n * Open a CDP connection to the session. Throws\n * {@link BrowserSessionGoneError} when the session is gone.\n */\n connect(\n sessionId: string,\n options: { timeoutMs?: number; onActivity?: () => void }\n ): Promise<CdpConnection>;\n /** End the session. A session that's already gone counts as closed. */\n close(sessionId: string): Promise<void>;\n /** The Chrome DevTools Protocol description the session's browser serves. */\n spec(sessionId: string): Promise<SearchableCdpSpec>;\n /**\n * Live View URLs for the session's open tabs, or `undefined` when the\n * session is gone.\n */\n liveView(\n sessionId: string,\n mode?: LiveViewMode\n ): Promise<BrowserLiveView | undefined>;\n /**\n * How long the provider keeps an idle session before reclaiming it.\n * `Browser` refreshes the record's `updatedAt` at most every half window.\n * `undefined` when idle sessions are never reclaimed.\n */\n readonly keepAliveMs?: number;\n}\n","/**\n * The Browser Run provider: `browserRun(env.BROWSER, options)` and the\n * adapter that runs a {@link Browser}'s browser on Cloudflare Browser Run.\n */\n\nimport {\n acquireBrowserSession,\n type BrowserBinding,\n type BrowserSessionGuardrails,\n closeBrowserSession,\n connectBrowserSession,\n isMissingBrowserSession,\n listBrowserTargets\n} from \"../browser-run\";\nimport { createLiveView } from \"../live-view\";\nimport { loadCdpSpec } from \"../spec\";\nimport {\n BrowserSessionGoneError,\n type BrowserProviderAdapter\n} from \"./provider-adapter\";\n\n/**\n * Default `keep_alive` for a `Browser` on Browser Run: 10 minutes. Long\n * enough to survive quiet spells between agent turns, while an abandoned\n * browser bills for at most 10 idle minutes (a whole day of Workers Free\n * browser time).\n */\nexport const BROWSER_SESSION_KEEP_ALIVE_DEFAULT_MS = 600_000;\n\n/**\n * Browser Run's `keep_alive` maximum: 20 minutes. Browser Run rejects\n * anything longer.\n */\nexport const BROWSER_SESSION_KEEP_ALIVE_MAX_MS = 1_200_000;\n\n/**\n * Browser Run settings applied every time a browser is created — including\n * when a lost browser is replaced — so options like guardrails survive a\n * restart.\n */\nexport interface BrowserRunOptions {\n /**\n * Platform `keep_alive` in milliseconds: how long an idle browser lives.\n * Defaults to {@link BROWSER_SESSION_KEEP_ALIVE_DEFAULT_MS} (10 minutes).\n * Browser Run accepts up to {@link BROWSER_SESSION_KEEP_ALIVE_MAX_MS}\n * (20 minutes).\n */\n keepAliveMs?: number;\n /** Opt into Browser Run session recording (rrweb capture). */\n recording?: boolean;\n /** Hostname guardrails, fixed at launch for every connection. */\n guardrails?: BrowserSessionGuardrails;\n}\n\n/** A {@link Browser} provider backed by Cloudflare Browser Run. */\nexport interface BrowserRunProvider {\n readonly kind: \"browser-run\";\n readonly binding: BrowserBinding;\n readonly options: BrowserRunOptions;\n}\n\n/**\n * Run the browser on Cloudflare Browser Run.\n *\n * @example\n * ```ts\n * new Browser({ provider: browserRun(env.BROWSER, { recording: true }) });\n * ```\n */\nexport function browserRun(\n binding: BrowserBinding,\n options: BrowserRunOptions = {}\n): BrowserRunProvider {\n return { kind: \"browser-run\", binding, options };\n}\n\n/** The code behind {@link browserRun}. */\nexport function browserRunAdapter(\n provider: BrowserRunProvider\n): BrowserProviderAdapter {\n const { binding, options } = provider;\n // Options are read on every use, like `recording` and `guardrails` below.\n const keepAliveMs = () =>\n options.keepAliveMs ?? BROWSER_SESSION_KEEP_ALIVE_DEFAULT_MS;\n\n return {\n get keepAliveMs() {\n return keepAliveMs();\n },\n\n async create() {\n return acquireBrowserSession(binding, {\n keepAliveMs: keepAliveMs(),\n recording: options.recording,\n guardrails: options.guardrails\n });\n },\n\n async isAlive(sessionId) {\n try {\n await listBrowserTargets(binding, sessionId);\n return true;\n } catch (error) {\n if (isMissingBrowserSession(error)) return false;\n throw error;\n }\n },\n\n async connect(sessionId, connectOptions) {\n try {\n return await connectBrowserSession(binding, sessionId, connectOptions);\n } catch (error) {\n if (isMissingBrowserSession(error)) {\n throw new BrowserSessionGoneError(sessionId, { cause: error });\n }\n throw error;\n }\n },\n\n async close(sessionId) {\n try {\n await closeBrowserSession(binding, sessionId);\n } catch (error) {\n if (!isMissingBrowserSession(error)) throw error;\n }\n },\n\n spec(sessionId) {\n return loadCdpSpec({ browser: binding, sessionId });\n },\n\n async liveView(sessionId, mode) {\n try {\n const targets = await listBrowserTargets(binding, sessionId);\n return createLiveView(sessionId, targets, mode);\n } catch (error) {\n if (isMissingBrowserSession(error)) return undefined;\n throw error;\n }\n }\n };\n}\n","/**\n * `Browser`: one named, persistent browser for an agent or Durable Object.\n *\n * Its tabs and logins survive between agent runs. When the browser is lost\n * (closed, idle past `keep_alive`, or crashed), the next use starts a fresh\n * one and reports `restarted: true` so the model knows its earlier state is\n * gone.\n *\n * Where the browser runs is its provider: Browser Run is the only one today\n * (`browserRun` in ./providers/browser-run.ts). `Browser` holds everything\n * that doesn't depend on the provider and calls the provider's adapter for\n * the rest (see ./providers/provider-adapter.ts).\n */\n\nimport { LifecycleCapability } from \"../lifecycle/capability\";\nimport type { CdpConnection } from \"./cdp-connection\";\nimport type { BrowserLiveView, LiveViewMode } from \"./live-view\";\nimport {\n browserRunAdapter,\n type BrowserRunProvider\n} from \"./providers/browser-run\";\nimport {\n BrowserSessionGoneError,\n type BrowserProviderAdapter\n} from \"./providers/provider-adapter\";\nimport {\n DurableBrowserSessionStore,\n type ListableBrowserSessionStore,\n type StoredBrowserSession\n} from \"./session-store\";\nimport type { SearchableCdpSpec } from \"./spec\";\n\n/**\n * Minimum interval between store `updatedAt` refreshes driven by CDP traffic\n * on connections returned by {@link Browser.connect}.\n */\nexport const SESSION_TOUCH_INTERVAL_MS = 60_000;\n\n/** The browser name used when a host doesn't pick one. */\nexport const DEFAULT_BROWSER_NAME = \"default\";\n\n/**\n * The scope used when a caller doesn't pick one: every caller that leaves\n * `scope` out shares this one active tab. See {@link BrowserConnectOptions}.\n */\nexport const DEFAULT_BROWSER_SCOPE = \"shared\";\n\n/**\n * Scope records kept per browser. Writing a new one past the cap deletes the\n * least recently used; a scope that comes back afterwards starts fresh.\n */\nexport const MAX_BROWSER_SCOPES = 100;\n\nconst NAMED_SESSION_KEY_PREFIX = \"browser:session:\";\n\n/** The store key holding the named browser's current record. */\nexport function namedBrowserSessionKey(name: string): string {\n return `${NAMED_SESSION_KEY_PREFIX}${name}`;\n}\n\n/**\n * Where a closed or lost browser's record moves: permanent evidence that the\n * name once owned a browser, so a later resolve reports `restarted: true`.\n * Kept outside {@link NAMED_SESSION_KEY_PREFIX} so listing that prefix\n * yields only names that currently own a browser. Grows with the number of\n * distinct names the host has ever used.\n */\nconst RETIRED_SESSION_KEY_PREFIX = \"browser:retired:\";\n\nfunction retiredBrowserSessionKey(name: string): string {\n return `${RETIRED_SESSION_KEY_PREFIX}${name}`;\n}\n\n/**\n * Where a browser's scope records live. The name's length is part of the\n * prefix, so one browser's prefix never matches another name's (`a` with\n * scope `b:c` vs. `a:b` with scope `c`).\n */\nfunction browserScopeKeyPrefix(name: string): string {\n return `browser:scope:${name.length}:${name}:`;\n}\n\n/** Where a {@link Browser} gets its browser from. */\nexport type BrowserProvider = BrowserRunProvider;\n\n/** The adapter behind a provider: one explicit case per provider kind. */\nfunction providerAdapterFor(provider: BrowserProvider): BrowserProviderAdapter {\n switch (provider.kind) {\n case \"browser-run\":\n return browserRunAdapter(provider);\n }\n}\n\nexport interface BrowserOptions {\n /** Where the browser runs. Create one with `browserRun()`. */\n provider: BrowserProvider;\n /**\n * Which browser this is. Two `Browser` objects on the same Durable Object\n * need different names. Defaults to {@link DEFAULT_BROWSER_NAME}.\n */\n name?: string;\n /**\n * Where the browser's record lives. Defaults to a\n * {@link DurableBrowserSessionStore} over the host object's storage, which\n * requires installing the `Browser` with `Lifecycle.use()`. Passing a store\n * lets the `Browser` work without Lifecycle. It must implement `list`.\n */\n store?: ListableBrowserSessionStore;\n /** Default CDP command timeout for {@link Browser.connect}. */\n timeoutMs?: number;\n /**\n * Minimum interval between activity-driven `updatedAt` refreshes.\n * Defaults to {@link SESSION_TOUCH_INTERVAL_MS}, capped at half the\n * keep-alive window.\n *\n * @internal For tests.\n */\n touchIntervalMs?: number;\n}\n\nexport interface ResolvedBrowser {\n name: string;\n /** The provider's session id — host-side only, never model-visible. */\n sessionId: string;\n /**\n * `true` when this resolution had to create a fresh browser to replace one\n * that previously existed (was closed, or expired or died upstream). Page\n * state from the prior browser is gone; surface this loudly to the model.\n * `false` only on first-ever use of the name — nothing was lost.\n */\n restarted: boolean;\n createdAt: number;\n updatedAt: number;\n}\n\nexport interface BrowserConnectOptions {\n /**\n * Who is driving. Connections with the same scope share an active tab, and\n * each scope keeps its own, so two conversations on one browser don't\n * drive each other's page. Cookies, logins, and the tabs themselves are\n * shared by every scope: a scope splits \"which tab is mine\", not the\n * browser. Defaults to {@link DEFAULT_BROWSER_SCOPE}.\n */\n scope?: string;\n}\n\nexport interface BrowserConnection {\n name: string;\n sessionId: string;\n /** The scope this connection works in; see {@link BrowserConnectOptions}. */\n scope: string;\n /**\n * `true` when this scope worked in an earlier browser that has since been\n * replaced, whichever scope's connection replaced it. Its tabs and page\n * state are gone; surface this loudly to the model. `false` on a scope's\n * first connection, even one that replaced a lost browser: the scope had\n * nothing to lose. This is per scope, not a browser-wide signal.\n */\n restarted: boolean;\n /**\n * The tab this scope last worked in, when it recorded one in this\n * browser.\n */\n activeTargetId?: string;\n /** Closing this connection does NOT close the browser. */\n cdp: CdpConnection;\n /**\n * Record the tab this scope is working in (or clear it with `undefined`).\n * Never resurrects: returns `false` when the browser was closed or\n * replaced since this connection resolved it.\n */\n setActiveTarget(targetId: string | undefined): Promise<boolean>;\n /** The tabs other scopes are working in, in this browser. */\n targetsInOtherScopes(): Promise<Set<string>>;\n /**\n * The Chrome DevTools Protocol description this browser serves, read from\n * the browser itself (cached).\n */\n spec(): Promise<SearchableCdpSpec>;\n}\n\n/**\n * One named, persistent browser.\n *\n * Install it with `Lifecycle.use()` — on an Agent subclass or any Durable\n * Object that composes `Lifecycle` — and it stores its record in the\n * object's own storage. It schedules nothing: the provider reclaims idle\n * browsers itself (Browser Run once `keep_alive` elapses), and the next use\n * replaces the lost browser with `restarted: true`.\n *\n * Everything here is host-side. Models never see browser names, provider\n * session ids, or Live View URLs through this surface.\n *\n * Store discipline: locks wrap storage operations only — liveness probes and\n * provider create/close calls always happen outside any lock, with a commit\n * re-check to detect concurrent swaps.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport class Browser extends LifecycleCapability {\n /** Which browser this is; see {@link BrowserOptions.name}. */\n readonly name: string;\n readonly #options: BrowserOptions;\n readonly #key: string;\n readonly #adapter: BrowserProviderAdapter;\n #store?: ListableBrowserSessionStore;\n\n constructor(options: BrowserOptions) {\n const name = options.name ?? DEFAULT_BROWSER_NAME;\n super(`browser:${name}`);\n if (name.trim() === \"\") {\n throw new Error(\"Browser names must be non-empty\");\n }\n this.name = name;\n this.#options = options;\n this.#key = namedBrowserSessionKey(name);\n this.#adapter = providerAdapterFor(options.provider);\n }\n\n /**\n * Reattach to the browser when it is still alive, otherwise create a fresh\n * one. See {@link ResolvedBrowser.restarted} for the mortality signal.\n */\n async resolve(): Promise<ResolvedBrowser> {\n const { name } = this;\n const key = this.#key;\n\n // Dead-browser recovery consumes two attempts (retire, then create).\n for (let attempt = 0; attempt < 4; attempt++) {\n const existing = await this.#readStored();\n\n if (existing === undefined) {\n // No browser on record: create one. The commit reports whether the\n // name was ever used before (see #createAndCommit).\n const { session, restarted } = await this.#createAndCommit();\n return { name, restarted, ...resolvedFields(session) };\n }\n\n // Live entry on record — probe it outside any lock.\n const alive = await this.#adapter.isAlive(existing.sessionId);\n const lock = await this.#sessionStore.acquireLock(key);\n try {\n const current = await this.#sessionStore.get(key);\n if (current?.sessionId !== existing.sessionId) {\n continue; // swapped or retired while we probed — revalidate\n }\n if (alive) {\n const refreshed = { ...current, updatedAt: Date.now() };\n await this.#sessionStore.set(key, refreshed);\n return { name, restarted: false, ...resolvedFields(refreshed) };\n }\n // The browser died upstream (expired or reclaimed). Retire the\n // record under this lock, so any resolver that reads it during the\n // replacement window sees the marker and reports restarted: true\n // too.\n await this.#retire(current);\n } finally {\n await lock.release();\n }\n // Re-enter the loop: the next attempt takes the create path.\n }\n\n throw new Error(`Browser \"${name}\" kept changing concurrently — retry`);\n }\n\n /**\n * Resolve the browser and open a CDP connection to it for one scope (see\n * {@link BrowserConnectOptions.scope}). Commands sent over the connection\n * refresh the record's `updatedAt` (throttled to\n * {@link SESSION_TOUCH_INTERVAL_MS}), so hosts can tell an actively used\n * browser from one the platform has likely reclaimed.\n *\n * If the browser expires between the liveness probe and the WebSocket\n * upgrade, the record is retired and the browser resolved once more, so\n * the caller gets a fresh browser instead of an error.\n */\n async connect(\n options: BrowserConnectOptions = {}\n ): Promise<BrowserConnection> {\n const scope = options.scope ?? DEFAULT_BROWSER_SCOPE;\n if (scope.trim() === \"\") {\n throw new Error(\"Browser scopes must be non-empty\");\n }\n let resolved = await this.resolve();\n let cdp: CdpConnection;\n try {\n cdp = await this.#open(resolved);\n } catch (error) {\n if (!(error instanceof BrowserSessionGoneError)) throw error;\n await this.#retireIfCurrent(resolved.sessionId);\n resolved = await this.resolve();\n cdp = await this.#open(resolved);\n }\n try {\n const entered = await this.#enterScope(scope, resolved.sessionId);\n return this.#connection(resolved, scope, cdp, entered);\n } catch (error) {\n cdp.disconnect();\n throw error;\n }\n }\n\n #connection(\n resolved: ResolvedBrowser,\n scope: string,\n cdp: CdpConnection,\n entered: { restarted: boolean; activeTargetId?: string }\n ): BrowserConnection {\n const { sessionId } = resolved;\n return {\n name: resolved.name,\n sessionId,\n scope,\n restarted: entered.restarted,\n activeTargetId: entered.activeTargetId,\n cdp,\n setActiveTarget: (targetId) =>\n this.#updateScope(scope, sessionId, targetId),\n targetsInOtherScopes: async () =>\n activeTargets(await this.#listScopes(), scope, sessionId),\n spec: () => this.#adapter.spec(sessionId)\n };\n }\n\n async #open(resolved: ResolvedBrowser): Promise<CdpConnection> {\n let lastTouchAt = Date.now();\n let touchInFlight = false;\n return this.#adapter.connect(resolved.sessionId, {\n timeoutMs: this.#options.timeoutMs,\n onActivity: () => {\n const now = Date.now();\n if (touchInFlight || now - lastTouchAt < this.#touchIntervalMs) {\n return;\n }\n touchInFlight = true;\n lastTouchAt = now;\n void this.#touch(resolved.sessionId)\n .catch((error: unknown) => {\n console.warn(\n `[agents/browser] Failed to refresh activity for browser \"${this.name}\"`,\n error\n );\n })\n .finally(() => {\n touchInFlight = false;\n });\n }\n });\n }\n\n /**\n * Close the browser: retire the record (so the next resolve reports\n * `restarted: true`) and close its provider session. Returns `false` when\n * there was nothing to close.\n *\n * The provider close is best-effort: the retired record is the durable\n * outcome, and a browser whose close failed is unreachable through this\n * store, so the provider reclaims it once idle (Browser Run: after\n * `keepAliveMs`, at most 20 minutes).\n */\n async close(): Promise<boolean> {\n let stored: StoredBrowserSession | undefined;\n const lock = await this.#sessionStore.acquireLock(this.#key);\n try {\n const current = await this.#sessionStore.get(this.#key);\n if (!current) return false;\n stored = current;\n await this.#retire(current);\n } finally {\n await lock.release();\n }\n try {\n await this.#adapter.close(stored.sessionId);\n } catch (error) {\n console.warn(\n `[agents/browser] Failed to close browser session ${stored.sessionId}`,\n error\n );\n }\n return true;\n }\n\n /**\n * Mint Live View URLs for the browser's open tabs, fresh from a target\n * listing. `undefined` when the browser was never created, is closed, or\n * is gone. The URLs are bearer credentials with a short connect window\n * (~5 min) — hand them to a trusted human, never to the model, and never\n * store them: re-mint instead.\n */\n async liveView(options?: {\n mode?: LiveViewMode;\n }): Promise<BrowserLiveView | undefined> {\n const entry = await this.#sessionStore.get(this.#key);\n if (!entry) return undefined;\n const view = await this.#adapter.liveView(entry.sessionId, options?.mode);\n if (!view) return undefined;\n // A human is about to look: minting counts as activity. Target listing\n // yields to the network, so a concurrent close or replacement can retire\n // the browser mid-mint — the touch and the retire serialize on the key\n // lock, and a lost touch means the listed targets are already dead:\n // report the browser gone rather than handing out doomed links. Touch\n // *errors* stay best effort — a store blip must not break minting.\n try {\n if (!(await this.#touch(entry.sessionId))) return undefined;\n } catch (error) {\n console.warn(\n `[agents/browser] Failed to refresh activity for browser \"${this.name}\"`,\n error\n );\n }\n return view;\n }\n\n // ── Internals ────────────────────────────────────────────────────────────\n\n /**\n * Capped at half the provider's keep-alive window: a browser with\n * continuous CDP traffic must never look older than the window the\n * provider uses to reclaim it.\n */\n get #touchIntervalMs(): number {\n const interval = this.#options.touchIntervalMs ?? SESSION_TOUCH_INTERVAL_MS;\n const { keepAliveMs } = this.#adapter;\n return keepAliveMs === undefined\n ? interval\n : Math.min(interval, Math.floor(keepAliveMs / 2));\n }\n\n /** Lazy: `lifecycle.storage` exists only once `Lifecycle.use()` ran. */\n get #sessionStore(): ListableBrowserSessionStore {\n this.#store ??=\n this.#options.store ??\n new DurableBrowserSessionStore(this.lifecycle.storage);\n return this.#store;\n }\n\n /**\n * Refresh `updatedAt` while the record still holds `sessionId`. Returns\n * false when a concurrent close or replacement already retired it.\n */\n #touch(sessionId: string): Promise<boolean> {\n return this.#update(sessionId, (current) => ({\n ...current,\n updatedAt: Date.now()\n }));\n }\n\n /**\n * Rewrite the record only while it still holds `sessionId`: a replaced or\n * retired record is never resurrected.\n */\n async #update(\n sessionId: string,\n change: (current: StoredBrowserSession) => StoredBrowserSession\n ): Promise<boolean> {\n const lock = await this.#sessionStore.acquireLock(this.#key);\n try {\n const current = await this.#sessionStore.get(this.#key);\n if (current?.sessionId !== sessionId) {\n return false; // replaced or gone — the caller's view is stale\n }\n await this.#sessionStore.set(this.#key, change(current));\n return true;\n } finally {\n await lock.release();\n }\n }\n\n // ── Scopes ───────────────────────────────────────────────────────────────\n //\n // Each scope has a small record next to the browser's: the browser it last\n // worked in (`sessionId`) and its tab there. All of a browser's scope\n // records share one lock, so claiming a tab can check the others.\n\n #scopeKey(scope: string): string {\n return `${browserScopeKeyPrefix(this.name)}${scope}`;\n }\n\n /** The lock every scope record of this browser is written under. */\n get #scopesLockKey(): string {\n return browserScopeKeyPrefix(this.name);\n }\n\n /** Every scope record of this browser, by scope. */\n async #listScopes(): Promise<Map<string, StoredBrowserSession>> {\n const prefix = browserScopeKeyPrefix(this.name);\n const entries = await this.#sessionStore.list(prefix);\n const scopes = new Map<string, StoredBrowserSession>();\n for (const [key, entry] of entries) {\n scopes.set(key.slice(prefix.length), entry);\n }\n return scopes;\n }\n\n /**\n * Start a connection's scope: a scope whose record names an earlier\n * browser was restarted, and its record moves to this one. A new record\n * past {@link MAX_BROWSER_SCOPES} evicts the least recently used.\n */\n async #enterScope(\n scope: string,\n sessionId: string\n ): Promise<{ restarted: boolean; activeTargetId?: string }> {\n const key = this.#scopeKey(scope);\n const lock = await this.#sessionStore.acquireLock(this.#scopesLockKey);\n try {\n const entry = await this.#sessionStore.get(key);\n const now = Date.now();\n if (entry?.sessionId === sessionId) {\n await this.#sessionStore.set(key, { ...entry, updatedAt: now });\n return { restarted: false, activeTargetId: entry.activeTargetId };\n }\n await this.#sessionStore.set(key, {\n sessionId,\n createdAt: now,\n updatedAt: now\n });\n if (!entry) await this.#evictScopes();\n return { restarted: entry !== undefined };\n } finally {\n await lock.release();\n }\n }\n\n /** Delete the least recently used scope records past the cap. */\n async #evictScopes(): Promise<void> {\n const scopes = await this.#listScopes();\n if (scopes.size <= MAX_BROWSER_SCOPES) return;\n const oldest = [...scopes]\n .sort(([, a], [, b]) => a.updatedAt - b.updatedAt)\n .slice(0, scopes.size - MAX_BROWSER_SCOPES);\n for (const [scope] of oldest) {\n await this.#sessionStore.delete(this.#scopeKey(scope));\n }\n }\n\n /**\n * Set a scope's tab (or clear it with `undefined`). Never resurrects:\n * does nothing (and returns `false`) once the browser this connection\n * resolved was closed or replaced.\n */\n async #updateScope(\n scope: string,\n sessionId: string,\n targetId: string | undefined\n ): Promise<boolean> {\n const key = this.#scopeKey(scope);\n const lock = await this.#sessionStore.acquireLock(this.#scopesLockKey);\n try {\n const current = await this.#sessionStore.get(this.#key);\n const entry = await this.#sessionStore.get(key);\n if (current?.sessionId !== sessionId || entry?.sessionId !== sessionId) {\n return false;\n }\n await this.#sessionStore.set(key, {\n ...entry,\n activeTargetId: targetId,\n updatedAt: Date.now()\n });\n return true;\n } finally {\n await lock.release();\n }\n }\n\n /** Retire the record if it still holds `sessionId`. */\n async #retireIfCurrent(sessionId: string): Promise<void> {\n const lock = await this.#sessionStore.acquireLock(this.#key);\n try {\n const current = await this.#sessionStore.get(this.#key);\n if (current?.sessionId === sessionId) await this.#retire(current);\n } finally {\n await lock.release();\n }\n }\n\n /**\n * Move the record to its retired marker. Callers hold the key lock, so a\n * resolver always sees either the record or the marker.\n */\n async #retire(current: StoredBrowserSession): Promise<void> {\n await this.#sessionStore.set(retiredBrowserSessionKey(this.name), {\n ...current,\n closedAt: Date.now()\n });\n await this.#sessionStore.delete(this.#key);\n }\n\n /**\n * Create a provider session (outside any lock) and commit it. The adapter\n * applies the provider's creation options. If a concurrent caller\n * committed an entry first, theirs wins and the redundant session is\n * closed best-effort.\n *\n * `restarted` is read under the commit lock: a retired marker — left by\n * close() or a dead-browser recovery — is evidence a prior browser\n * existed, and only first-ever use of the name is not a restart. Markers\n * are permanent, so reading at commit time also catches a browser that\n * was created and closed while this create was in flight.\n */\n async #createAndCommit(): Promise<{\n session: StoredBrowserSession;\n restarted: boolean;\n }> {\n const info = await this.#adapter.create();\n const now = Date.now();\n const stored: StoredBrowserSession = {\n sessionId: info.sessionId,\n createdAt: now,\n updatedAt: now\n };\n\n let winner: StoredBrowserSession | undefined;\n let restarted: boolean;\n const lock = await this.#sessionStore.acquireLock(this.#key);\n try {\n restarted =\n (await this.#sessionStore.get(retiredBrowserSessionKey(this.name))) !==\n undefined;\n const current = await this.#sessionStore.get(this.#key);\n if (current === undefined) {\n await this.#sessionStore.set(this.#key, stored);\n } else {\n winner = current;\n }\n } finally {\n await lock.release();\n }\n\n if (winner) {\n try {\n await this.#adapter.close(stored.sessionId);\n } catch (error) {\n console.warn(\n `[agents/browser] Failed to close redundant browser session ${stored.sessionId}`,\n error\n );\n }\n return { session: winner, restarted };\n }\n return { session: stored, restarted };\n }\n\n async #readStored(): Promise<StoredBrowserSession | undefined> {\n const lock = await this.#sessionStore.acquireLock(this.#key);\n try {\n return await this.#sessionStore.get(this.#key);\n } finally {\n await lock.release();\n }\n }\n}\n\n/** A store record without fields that belong to scope records. */\nfunction resolvedFields(session: StoredBrowserSession) {\n const { sessionId, createdAt, updatedAt } = session;\n return { sessionId, createdAt, updatedAt };\n}\n\n/** The tabs scopes other than `scope` are working in, in `sessionId`. */\nfunction activeTargets(\n scopes: Map<string, StoredBrowserSession>,\n scope: string,\n sessionId: string\n): Set<string> {\n const targets = new Set<string>();\n for (const [other, entry] of scopes) {\n if (other === scope || entry.sessionId !== sessionId) continue;\n if (entry.activeTargetId) targets.add(entry.activeTargetId);\n }\n return targets;\n}\n"],"mappings":";;;;;;;;;;AAqBA,IAAa,0BAAb,cAA6C,MAAM;CACjD,YACE,WACA,SACA;EACA,MAAM,yBAAyB,aAAa,OAAO;EAH1C,KAAA,YAAA;EAIT,KAAK,OAAO;CACd;AACF;;;;;;;;;ACwCA,SAAgB,WACd,SACA,UAA6B,CAAC,GACV;CACpB,OAAO;EAAE,MAAM;EAAe;EAAS;CAAQ;AACjD;;AAGA,SAAgB,kBACd,UACwB;CACxB,MAAM,EAAE,SAAS,YAAY;CAE7B,MAAM,oBACJ,QAAQ,eAAA;CAEV,OAAO;EACL,IAAI,cAAc;GAChB,OAAO,YAAY;EACrB;EAEA,MAAM,SAAS;GACb,OAAO,sBAAsB,SAAS;IACpC,aAAa,YAAY;IACzB,WAAW,QAAQ;IACnB,YAAY,QAAQ;GACtB,CAAC;EACH;EAEA,MAAM,QAAQ,WAAW;GACvB,IAAI;IACF,MAAM,mBAAmB,SAAS,SAAS;IAC3C,OAAO;GACT,SAAS,OAAO;IACd,IAAI,wBAAwB,KAAK,GAAG,OAAO;IAC3C,MAAM;GACR;EACF;EAEA,MAAM,QAAQ,WAAW,gBAAgB;GACvC,IAAI;IACF,OAAO,MAAM,sBAAsB,SAAS,WAAW,cAAc;GACvE,SAAS,OAAO;IACd,IAAI,wBAAwB,KAAK,GAC/B,MAAM,IAAI,wBAAwB,WAAW,EAAE,OAAO,MAAM,CAAC;IAE/D,MAAM;GACR;EACF;EAEA,MAAM,MAAM,WAAW;GACrB,IAAI;IACF,MAAM,oBAAoB,SAAS,SAAS;GAC9C,SAAS,OAAO;IACd,IAAI,CAAC,wBAAwB,KAAK,GAAG,MAAM;GAC7C;EACF;EAEA,KAAK,WAAW;GACd,OAAO,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