agents 0.23.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/dist/{agent-routing-DE5zmCQ8.d.ts → agent-routing-0DR0Tk2v.d.ts} +270 -190
  2. package/dist/agent-routing.d.ts +1 -1
  3. package/dist/agent-routing.js.map +1 -1
  4. package/dist/agent-tool-types.d.ts +13 -7
  5. package/dist/agent-tool-types.js +23 -1
  6. package/dist/agent-tool-types.js.map +1 -1
  7. package/dist/{agent-tools-y7zLfw4Q.js → agent-tools-CdJC-8Dc.js} +72 -9
  8. package/dist/agent-tools-CdJC-8Dc.js.map +1 -0
  9. package/dist/{agent-tools-DtXMTDGM.d.ts → agent-tools-YrATZJu2.d.ts} +29 -15
  10. package/dist/agent-tools.d.ts +6 -4
  11. package/dist/agent-tools.js.map +1 -1
  12. package/dist/ai-fm7xx1BK.js +312 -0
  13. package/dist/ai-fm7xx1BK.js.map +1 -0
  14. package/dist/base64-redaction-C1Uu29t5.js +59 -0
  15. package/dist/base64-redaction-C1Uu29t5.js.map +1 -0
  16. package/dist/browser/ai-sdk.d.ts +90 -0
  17. package/dist/browser/ai-sdk.js +51 -0
  18. package/dist/browser/ai-sdk.js.map +1 -0
  19. package/dist/browser/ai.d.ts +4 -4
  20. package/dist/browser/ai.js +1 -347
  21. package/dist/browser/index.d.ts +81 -79
  22. package/dist/browser/index.js +361 -2
  23. package/dist/browser/index.js.map +1 -0
  24. package/dist/browser/tanstack-ai.d.ts +96 -1
  25. package/dist/browser/tanstack-ai.js +62 -2
  26. package/dist/browser/tanstack-ai.js.map +1 -1
  27. package/dist/browser-DE3d-RLk.d.ts +275 -0
  28. package/dist/browser-tool-CQ10e6Kj.js +480 -0
  29. package/dist/browser-tool-CQ10e6Kj.js.map +1 -0
  30. package/dist/browser-tool-DuNdlwZ9.d.ts +73 -0
  31. package/dist/{capability-BjSKYpzg.js → capability-B4WbF81e.js} +2 -1
  32. package/dist/capability-B4WbF81e.js.map +1 -0
  33. package/dist/{capability-runner-Be_-PLR1.d.ts → capability-runner-DBAnGr6L.d.ts} +45 -15
  34. package/dist/chat/index.d.ts +341 -232
  35. package/dist/chat/index.js +602 -72
  36. package/dist/chat/index.js.map +1 -1
  37. package/dist/chat/react.d.ts +42 -2
  38. package/dist/chat/react.js +191 -35
  39. package/dist/chat/react.js.map +1 -1
  40. package/dist/chat/transport.d.ts +1 -1
  41. package/dist/chat/transport.js +1 -1
  42. package/dist/chat-sdk/index.d.ts +17 -3
  43. package/dist/chat-sdk/index.js +28 -2
  44. package/dist/chat-sdk/index.js.map +1 -1
  45. package/dist/client-4OlMIJx-.js +591 -0
  46. package/dist/client-4OlMIJx-.js.map +1 -0
  47. package/dist/{client-jagG8a9_.js → client-fyQrLGkD.js} +2 -2
  48. package/dist/{client-jagG8a9_.js.map → client-fyQrLGkD.js.map} +1 -1
  49. package/dist/client-je3koD9Z.d.ts +446 -0
  50. package/dist/client.d.ts +29 -283
  51. package/dist/client.js +2 -274
  52. package/dist/{connector-CptFKzRh.js → connector-58XDGvc3.js} +251 -120
  53. package/dist/connector-58XDGvc3.js.map +1 -0
  54. package/dist/{connector-CkQD4MK3.d.ts → connector-Cl-VqPmA.d.ts} +244 -146
  55. package/dist/context/index.d.ts +29 -0
  56. package/dist/context/index.js +64 -17
  57. package/dist/context/index.js.map +1 -1
  58. package/dist/current-agent-DhoDkSnH.js.map +1 -1
  59. package/dist/current-agent-vAk_5JMt.d.ts +93 -0
  60. package/dist/{current-agent-Da_C9a3b.d.ts → durable-object-lifecycle-HhgOMWq9.d.ts} +26 -127
  61. package/dist/harnesses/pi/index.d.ts +348 -0
  62. package/dist/harnesses/pi/index.js +754 -0
  63. package/dist/harnesses/pi/index.js.map +1 -0
  64. package/dist/images-iiTDSyRu.js +1631 -0
  65. package/dist/images-iiTDSyRu.js.map +1 -0
  66. package/dist/index-BreL0YrQ.d.ts +78 -0
  67. package/dist/index-kbSUIer3.d.ts +343 -0
  68. package/dist/index.d.ts +43 -41
  69. package/dist/index.js +2 -2
  70. package/dist/internal_context.d.ts +1 -1
  71. package/dist/lifecycle/index.d.ts +19 -17
  72. package/dist/lifecycle/index.js +2 -2
  73. package/dist/{lifecycle-CMRGjZdw.js → lifecycle-CFu6OV03.js} +73 -29
  74. package/dist/lifecycle-CFu6OV03.js.map +1 -0
  75. package/dist/mcp/client/index.d.ts +20 -20
  76. package/dist/mcp/client/index.js +1 -1
  77. package/dist/mcp/client/x402.js +21 -19
  78. package/dist/mcp/client/x402.js.map +1 -1
  79. package/dist/mcp/index.d.ts +35 -35
  80. package/dist/mcp/index.js +2 -2
  81. package/dist/{message-builder-BymO4N_D.js → message-builder-DAl9AhHH.js} +89 -4
  82. package/dist/message-builder-DAl9AhHH.js.map +1 -0
  83. package/dist/models/ai-sdk/index.d.ts +353 -0
  84. package/dist/models/ai-sdk/index.js +2443 -0
  85. package/dist/models/ai-sdk/index.js.map +1 -0
  86. package/dist/models/pi-ai/index.d.ts +313 -0
  87. package/dist/models/pi-ai/index.js +1795 -0
  88. package/dist/models/pi-ai/index.js.map +1 -0
  89. package/dist/observability/ai/index.js +20 -4
  90. package/dist/observability/ai/index.js.map +1 -1
  91. package/dist/{protocol-B0nh6KNf.js → protocol-kHsr-f0X.js} +26 -12
  92. package/dist/{protocol-B0nh6KNf.js.map → protocol-kHsr-f0X.js.map} +1 -1
  93. package/dist/queue/index.d.ts +123 -0
  94. package/dist/queue/index.js +2 -0
  95. package/dist/queue-BB-zfIYF.js +406 -0
  96. package/dist/queue-BB-zfIYF.js.map +1 -0
  97. package/dist/react.d.ts +31 -13
  98. package/dist/react.js +190 -71
  99. package/dist/react.js.map +1 -1
  100. package/dist/{retries-D9Ds-1lz.d.ts → retries-CV6AkXmQ.d.ts} +23 -8
  101. package/dist/retries.d.ts +12 -8
  102. package/dist/retries.js +19 -1
  103. package/dist/retries.js.map +1 -1
  104. package/dist/routing/index.d.ts +2 -2
  105. package/dist/routing/index.js +1 -1
  106. package/dist/{scheduler-DD9NdYbF.js → scheduler-DZ3xQfeK.js} +4 -11
  107. package/dist/scheduler-DZ3xQfeK.js.map +1 -0
  108. package/dist/{scheduler-Dwh85ZGl.d.ts → scheduler-RdACNXDP.d.ts} +6 -6
  109. package/dist/schedules/index.d.ts +1 -1
  110. package/dist/schedules/index.js +1 -1
  111. package/dist/serializable.d.ts +1 -1
  112. package/dist/sessions/index.d.ts +70 -3
  113. package/dist/sessions/index.js +276 -67
  114. package/dist/sessions/index.js.map +1 -1
  115. package/dist/skills/index.d.ts +29 -314
  116. package/dist/socket-address.d.ts +16 -0
  117. package/dist/socket-address.js +19 -0
  118. package/dist/socket-address.js.map +1 -0
  119. package/dist/{src-DlSHshb2.js → src-BZeu-SCD.js} +541 -500
  120. package/dist/src-BZeu-SCD.js.map +1 -0
  121. package/dist/state/index.d.ts +6 -0
  122. package/dist/state/index.js +137 -0
  123. package/dist/state/index.js.map +1 -0
  124. package/dist/streams/index.d.ts +1 -1
  125. package/dist/streams/index.js +1 -1
  126. package/dist/{streams-D6tJ0NN9.d.ts → streams-Cmkj9QfW.d.ts} +4 -2
  127. package/dist/{streams-DZKgAj9b.js → streams-DW-UCOUc.js} +9 -2
  128. package/dist/streams-DW-UCOUc.js.map +1 -0
  129. package/dist/sub-routing.d.ts +12 -12
  130. package/dist/tasks/index.d.ts +1 -1
  131. package/dist/tasks/index.js +1 -1
  132. package/dist/{tasks-ylZgBjhj.js → tasks-68DESxf0.js} +3 -3
  133. package/dist/{tasks-ylZgBjhj.js.map → tasks-68DESxf0.js.map} +1 -1
  134. package/dist/{tasks-BRJ5zgya.d.ts → tasks-9YxYtByh.d.ts} +5 -5
  135. package/dist/transport-PfFnt-Ld.d.ts +525 -0
  136. package/dist/transport-protocol-BxyngQ_R.js +25 -0
  137. package/dist/transport-protocol-BxyngQ_R.js.map +1 -0
  138. package/dist/transport-protocol-ZTew5Wso.d.ts +27 -0
  139. package/dist/types-BA4anrjI.d.ts +70 -0
  140. package/dist/voice/index.d.ts +2 -2
  141. package/dist/websockets/index.d.ts +195 -69
  142. package/dist/websockets/index.js +3 -2
  143. package/dist/websockets-Ci-LZFHH.js +1030 -0
  144. package/dist/websockets-Ci-LZFHH.js.map +1 -0
  145. package/dist/wire-types-CnMt6_HR.js.map +1 -1
  146. package/dist/wire-types-CrjKvDyi.d.ts +300 -0
  147. package/dist/workflow-types.d.ts +25 -25
  148. package/dist/workflows.d.ts +21 -21
  149. package/dist/workflows.js +1 -1
  150. package/dist/{ws-chat-transport-UNRIS2xl.d.ts → ws-chat-transport-BbT1A5Lc.d.ts} +51 -2
  151. package/dist/{ws-chat-transport-rWwta645.js → ws-chat-transport-cqMKq3IY.js} +143 -16
  152. package/dist/ws-chat-transport-cqMKq3IY.js.map +1 -0
  153. package/docs/agent-class.md +2 -2
  154. package/docs/agent-tools.md +29 -4
  155. package/docs/browse-the-web.md +87 -5
  156. package/docs/chat-agents.md +124 -16
  157. package/docs/client-sdk.md +30 -0
  158. package/docs/context.md +27 -0
  159. package/docs/durable-execution.md +2 -0
  160. package/docs/harnesses/pi.md +91 -0
  161. package/docs/human-in-the-loop.md +4 -0
  162. package/docs/index.md +4 -1
  163. package/docs/lifecycle.md +114 -23
  164. package/docs/models-pi-ai.md +325 -0
  165. package/docs/models.md +504 -0
  166. package/docs/queue.md +135 -241
  167. package/docs/resumable-streaming.md +2 -0
  168. package/docs/retries.md +1 -1
  169. package/docs/routing.md +13 -13
  170. package/docs/sessions.md +36 -1
  171. package/docs/state.md +1 -0
  172. package/docs/sub-agents.md +12 -3
  173. package/package.json +51 -3
  174. package/dist/agent-tools-y7zLfw4Q.js.map +0 -1
  175. package/dist/browser/ai.js.map +0 -1
  176. package/dist/capability-BjSKYpzg.js.map +0 -1
  177. package/dist/client-tools-aIBO0Fk7.d.ts +0 -53
  178. package/dist/client.js.map +0 -1
  179. package/dist/connector-CptFKzRh.js.map +0 -1
  180. package/dist/lifecycle-CMRGjZdw.js.map +0 -1
  181. package/dist/message-builder-BymO4N_D.js.map +0 -1
  182. package/dist/scheduler-DD9NdYbF.js.map +0 -1
  183. package/dist/src-DlSHshb2.js.map +0 -1
  184. package/dist/streams-DZKgAj9b.js.map +0 -1
  185. package/dist/websockets-DUfRHPRq.js +0 -502
  186. package/dist/websockets-DUfRHPRq.js.map +0 -1
  187. package/dist/ws-chat-transport-rWwta645.js.map +0 -1
@@ -0,0 +1,2443 @@
1
+ import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, r as _assertClassBrand, t as _classPrivateFieldGet2 } from "../../classPrivateFieldGet2-DZBYAB34.js";
2
+ import { t as _classPrivateMethodInitSpec } from "../../classPrivateMethodInitSpec-qMjJ6sHQ.js";
3
+ import { C as resolveOptions, D as isRetryableStatus, E as isAbortError, S as parseModelOptions, T as classifyStatus, _ as isGatewayErrorEnvelope, a as normalizeChatCompletion, b as gatewayLayerOf, f as createTransport$1, g as headersToObject, h as errorFromResponse$1, i as normalizeChatCompletionsStream, m as errorFromGatewayEnvelope$1, n as imageMediaTypeOf, o as prepareChatCompletionsRequest, p as definedHeaders, r as sseDataStream, t as buildImageInput, u as requireGatewayProvider, v as unwrapEnvelope$1, w as CloudflareAIError$1, x as mergeModelOptions, y as PROVIDER_OPTIONS_KEY } from "../../images-iiTDSyRu.js";
4
+ import { APICallError, TooManyEmbeddingValuesForCallError } from "@ai-sdk/provider";
5
+ //#region src/models/ai-sdk/errors.ts
6
+ /** The provider packages worth naming when someone passes a vendor id. */
7
+ const VENDOR_PACKAGES = {
8
+ anthropic: {
9
+ call: "anthropic(\"claude-opus-4-8\")",
10
+ package: "@ai-sdk/anthropic"
11
+ },
12
+ google: {
13
+ call: "google(\"gemini-3-flash\")",
14
+ package: "@ai-sdk/google"
15
+ },
16
+ openai: {
17
+ call: "openai(\"gpt-5-mini\")",
18
+ package: "@ai-sdk/openai"
19
+ }
20
+ };
21
+ /**
22
+ * The one error a bad model id produces. Workers AI ids are the only strings
23
+ * this provider knows; a third-party model is a model object built by that
24
+ * vendor's own provider package.
25
+ */
26
+ function notAWorkersAIId(modelId) {
27
+ const vendor = VENDOR_PACKAGES[modelId.split("/")[0] ?? ""];
28
+ const advice = vendor === void 0 ? "install its AI SDK provider package and pass the model object, e.g. ai(anthropic(\"claude-opus-4-8\"))" : `install ${vendor.package} and pass the model object: ai(${vendor.call})`;
29
+ return /* @__PURE__ */ new TypeError(`"${modelId}" is not a Workers AI model id. Workers AI ids start with "@cf/", and they are the only ids this provider takes: a third-party model goes through its own provider and is only routed by AI Gateway — ${advice}.`);
30
+ }
31
+ /**
32
+ * The gate every string that names a model passes through, wherever it enters
33
+ * the module: `ai("…")`, a per-model fallback leg, or a leg read out of the
34
+ * per-call `providerOptions.cloudflare` bag. One rule, one message, thrown at
35
+ * the line that supplied the id rather than at the request it would have made.
36
+ */
37
+ function requireWorkersAIId(modelId) {
38
+ if (!modelId.startsWith("@cf/")) throw notAWorkersAIId(modelId);
39
+ return modelId;
40
+ }
41
+ /**
42
+ * Error thrown for every failed Cloudflare AI call, whether it came back as a
43
+ * non-2xx `Response` or as a thrown Workers AI binding error.
44
+ *
45
+ * Extends the AI SDK's `APICallError` so `ai`'s built-in retry loop honours
46
+ * {@link CloudflareAIError.isRetryable} without any extra wiring.
47
+ *
48
+ * @experimental This surface is experimental and may change.
49
+ */
50
+ var CloudflareAIError = class CloudflareAIError extends APICallError {
51
+ constructor(options) {
52
+ super({
53
+ cause: options.cause,
54
+ data: options.data,
55
+ isRetryable: options.isRetryable ?? isRetryableStatus(options.status),
56
+ message: options.message,
57
+ requestBodyValues: options.requestBodyValues,
58
+ responseBody: options.responseBody,
59
+ responseHeaders: options.responseHeaders,
60
+ statusCode: options.status,
61
+ url: options.url
62
+ });
63
+ this.name = "CloudflareAIError";
64
+ this.status = options.status;
65
+ this.code = options.code;
66
+ this.logId = options.logId;
67
+ this.model = options.model;
68
+ this.attempts = options.attempts;
69
+ }
70
+ /** Lifts the framework-neutral core error into the AI SDK error type. */
71
+ static fromCore(error) {
72
+ return new CloudflareAIError({
73
+ attempts: error.attempts,
74
+ cause: error.cause,
75
+ code: error.code,
76
+ data: error.data,
77
+ isRetryable: error.isRetryable,
78
+ logId: error.logId,
79
+ message: error.message,
80
+ model: error.model,
81
+ requestBodyValues: error.requestBodyValues,
82
+ responseBody: error.responseBody,
83
+ responseHeaders: error.responseHeaders,
84
+ status: error.status,
85
+ url: error.url
86
+ });
87
+ }
88
+ };
89
+ /**
90
+ * Converts whatever the core transport threw into what AI SDK callers expect:
91
+ * core errors become {@link CloudflareAIError}s; everything else passes
92
+ * through untouched.
93
+ */
94
+ function toAISDKError(error) {
95
+ return error instanceof CloudflareAIError$1 ? CloudflareAIError.fromCore(error) : error;
96
+ }
97
+ //#endregion
98
+ //#region src/models/ai-sdk/settings.ts
99
+ /**
100
+ * The fallback legs for one call, in the caller's order. Precedence matches
101
+ * the rest of the option merge: a per-call list replaces the per-model one
102
+ * rather than extending it.
103
+ */
104
+ function fallbackLegs(model, call) {
105
+ return call?.fallback ?? model?.fallback ?? [];
106
+ }
107
+ /**
108
+ * Reads per-call options out of AI SDK `providerOptions.cloudflare`.
109
+ *
110
+ * This is the one place the untyped per-call bag enters the module, so it is
111
+ * where the "`@cf/` ids only" rule is enforced for the fallback legs a caller
112
+ * wrote there: `parseModelOptions` is framework-neutral and drops rather than
113
+ * throws, and no type ever sees that JSON. A vendor id in a leg would
114
+ * otherwise reach `env.AI.run` — the path a vendor model must never take.
115
+ *
116
+ * @experimental This surface is experimental and may change.
117
+ */
118
+ function parseCallOptions(providerOptions) {
119
+ const options = parseModelOptions(providerOptions?.[PROVIDER_OPTIONS_KEY]);
120
+ for (const leg of options?.fallback ?? []) requireWorkersAIId(leg);
121
+ return options;
122
+ }
123
+ /**
124
+ * The options each model this provider built was built with.
125
+ *
126
+ * A `WeakMap` rather than a field: `createAI` needs to read a leg's own bag
127
+ * back when it layers a fallback chain's gateway options over it, and that is
128
+ * this module's business rather than part of any model's public shape.
129
+ */
130
+ const MODEL_OPTIONS = /* @__PURE__ */ new WeakMap();
131
+ /** Records the options a model of this provider was built with. */
132
+ function rememberOptions(model, options) {
133
+ if (options !== void 0) MODEL_OPTIONS.set(model, options);
134
+ }
135
+ /** The options a model of this provider was built with, if it is one. */
136
+ function optionsOf(model) {
137
+ return model !== null && typeof model === "object" ? MODEL_OPTIONS.get(model) : void 0;
138
+ }
139
+ /**
140
+ * The per-call options a fallback leg is asked with: everything the caller
141
+ * sent, minus the fallback list itself.
142
+ *
143
+ * Every leg here is a model object, so a leg that read the same
144
+ * `providerOptions.cloudflare.fallback` would build the whole chain again —
145
+ * once per leg, each of those re-expanding in turn. The rest of the per-call
146
+ * bag stays, so a leg still honours a per-call `cacheTtl` or gateway id.
147
+ */
148
+ function withoutCallFallback(options) {
149
+ const providerOptions = options.providerOptions;
150
+ const ours = providerOptions?.[PROVIDER_OPTIONS_KEY];
151
+ if (ours === void 0 || !("fallback" in ours)) return options;
152
+ const bag = { ...ours };
153
+ delete bag.fallback;
154
+ return {
155
+ ...options,
156
+ providerOptions: {
157
+ ...providerOptions,
158
+ [PROVIDER_OPTIONS_KEY]: bag
159
+ }
160
+ };
161
+ }
162
+ //#endregion
163
+ //#region src/models/ai-sdk/transport.ts
164
+ /**
165
+ * The typed AI SDK error for the gateway's own error envelope — a missing
166
+ * gateway, an unpaid account — on the universal path.
167
+ */
168
+ function errorFromGatewayEnvelope(body, context) {
169
+ return CloudflareAIError.fromCore(errorFromGatewayEnvelope$1(body, context));
170
+ }
171
+ /**
172
+ * Unwraps the Cloudflare `{ success, result }` envelope, throwing an AI SDK
173
+ * {@link CloudflareAIError} for a failed envelope.
174
+ */
175
+ function unwrapEnvelope(value, context) {
176
+ try {
177
+ return unwrapEnvelope$1(value, context);
178
+ } catch (error) {
179
+ throw toAISDKError(error);
180
+ }
181
+ }
182
+ /** The typed AI SDK error for a non-2xx response. */
183
+ async function errorFromResponse(response, context) {
184
+ return CloudflareAIError.fromCore(await errorFromResponse$1(response, context));
185
+ }
186
+ /**
187
+ * Builds the transport for a set of provider settings, with every failure
188
+ * lifted into the AI SDK error type.
189
+ *
190
+ * @experimental This surface is experimental and may change.
191
+ */
192
+ function createTransport(settings) {
193
+ const inner = createTransport$1(settings);
194
+ return {
195
+ logIdFallback: (response) => inner.logIdFallback(response),
196
+ async run(request) {
197
+ try {
198
+ return await inner.run(request);
199
+ } catch (error) {
200
+ throw toAISDKError(error);
201
+ }
202
+ },
203
+ async universal(request) {
204
+ try {
205
+ return await inner.universal(request);
206
+ } catch (error) {
207
+ throw toAISDKError(error);
208
+ }
209
+ },
210
+ url: inner.url
211
+ };
212
+ }
213
+ //#endregion
214
+ //#region src/models/ai-sdk/models/fallback.ts
215
+ /**
216
+ * Client-side fallback across models: the primary is tried first, then each
217
+ * fallback in order, when a call fails before producing output. Shared by the
218
+ * language and embedding models.
219
+ */
220
+ /**
221
+ * Runs each leg in order until one answers. Legs may be anything — a model id
222
+ * this provider owns, or a whole other `LanguageModelV4` — because a leg is
223
+ * only ever a name and a thunk here.
224
+ */
225
+ async function withFallbackLegs(legs, url) {
226
+ const attempts = [];
227
+ let lastError;
228
+ for (const leg of legs) try {
229
+ return await leg.run();
230
+ } catch (error) {
231
+ if (isAbortError(error)) throw error;
232
+ attempts.push({
233
+ error,
234
+ model: leg.model
235
+ });
236
+ lastError = error;
237
+ }
238
+ if (attempts.length <= 1) throw lastError;
239
+ throw fallbackError(lastError, attempts, url);
240
+ }
241
+ /**
242
+ * The parts a stream emits before it has said anything: protocol preamble
243
+ * that every leg would repeat. Anything else is output the caller has seen,
244
+ * after which the leg is committed and a later failure is its own.
245
+ */
246
+ const PREAMBLE_PARTS = /* @__PURE__ */ new Set([
247
+ "stream-start",
248
+ "response-metadata",
249
+ "text-start",
250
+ "reasoning-start",
251
+ "tool-input-start",
252
+ "raw"
253
+ ]);
254
+ /**
255
+ * {@link withFallbackLegs} for streams. A 2xx that then fails before any
256
+ * output — an `error` part, an error finish, or a broken body — is still a
257
+ * failed leg, so the next one is tried; the preamble the failed leg sent is
258
+ * dropped and the answering leg's own is delivered instead. Once a leg has
259
+ * produced output it is the answer, failures and all.
260
+ */
261
+ async function withStreamFallbackLegs(legs, url) {
262
+ if (legs.length <= 1) return withFallbackLegs(legs, url);
263
+ const attempts = [];
264
+ let lastError;
265
+ for (const leg of legs) {
266
+ let result;
267
+ try {
268
+ result = await leg.run();
269
+ } catch (error) {
270
+ if (isAbortError(error)) throw error;
271
+ attempts.push({
272
+ error,
273
+ model: leg.model
274
+ });
275
+ lastError = error;
276
+ continue;
277
+ }
278
+ const reader = result.stream.getReader();
279
+ const preamble = [];
280
+ let failure;
281
+ let committed = false;
282
+ try {
283
+ for (;;) {
284
+ const { done, value } = await reader.read();
285
+ if (done) {
286
+ committed = true;
287
+ break;
288
+ }
289
+ if (value.type === "error") {
290
+ failure = value.error;
291
+ break;
292
+ }
293
+ if (value.type === "finish" && value.finishReason.unified === "error") {
294
+ failure = streamFailure(leg.model, url, value.finishReason.raw);
295
+ break;
296
+ }
297
+ preamble.push(value);
298
+ if (!PREAMBLE_PARTS.has(value.type)) {
299
+ committed = true;
300
+ break;
301
+ }
302
+ }
303
+ } catch (error) {
304
+ if (isAbortError(error)) throw error;
305
+ failure = error;
306
+ }
307
+ if (!committed) {
308
+ await reader.cancel().catch(() => void 0);
309
+ attempts.push({
310
+ error: failure,
311
+ model: leg.model
312
+ });
313
+ lastError = failure;
314
+ continue;
315
+ }
316
+ return {
317
+ ...result,
318
+ stream: resumed(preamble, reader)
319
+ };
320
+ }
321
+ if (attempts.length <= 1) throw lastError;
322
+ throw fallbackError(lastError, attempts, url);
323
+ }
324
+ /** The parts already read, then the rest of the stream, as one stream. */
325
+ function resumed(head, reader) {
326
+ return new ReadableStream({
327
+ cancel(reason) {
328
+ return reader.cancel(reason);
329
+ },
330
+ async pull(controller) {
331
+ const { done, value } = await reader.read();
332
+ if (done) controller.close();
333
+ else controller.enqueue(value);
334
+ },
335
+ start(controller) {
336
+ for (const part of head) controller.enqueue(part);
337
+ }
338
+ });
339
+ }
340
+ /** A stream that ended in an error finish before it produced anything. */
341
+ function streamFailure(model, url, raw) {
342
+ return new CloudflareAIError({
343
+ code: "provider-error",
344
+ isRetryable: false,
345
+ message: `The stream from ${model} ended in an error before producing any output${raw === void 0 ? "" : ` (${raw})`}.`,
346
+ model,
347
+ requestBodyValues: void 0,
348
+ url
349
+ });
350
+ }
351
+ async function withFallback(primary, fallback, url, run) {
352
+ return withFallbackLegs([primary, ...fallback].map((modelId) => ({
353
+ model: modelId,
354
+ run: () => run(modelId)
355
+ })), url);
356
+ }
357
+ /** Rebuilds the last error with the whole attempt chain attached. */
358
+ function fallbackError(lastError, attempts, url) {
359
+ const models = attempts.map((attempt) => attempt.model).join(", ");
360
+ if (lastError instanceof CloudflareAIError) return new CloudflareAIError({
361
+ attempts,
362
+ cause: lastError,
363
+ code: lastError.code,
364
+ data: lastError.data,
365
+ isRetryable: lastError.isRetryable,
366
+ logId: lastError.logId,
367
+ message: `All models failed (${models}). Last error: ${lastError.message}`,
368
+ model: lastError.model,
369
+ requestBodyValues: lastError.requestBodyValues,
370
+ responseBody: lastError.responseBody,
371
+ responseHeaders: lastError.responseHeaders,
372
+ status: lastError.status,
373
+ url: lastError.url
374
+ });
375
+ if (APICallError.isInstance(lastError)) return new CloudflareAIError({
376
+ attempts,
377
+ cause: lastError,
378
+ code: classifyStatus(lastError.statusCode),
379
+ isRetryable: lastError.isRetryable,
380
+ message: `All models failed (${models}). Last error: ${lastError.message}`,
381
+ model: attempts.at(-1)?.model ?? "",
382
+ requestBodyValues: lastError.requestBodyValues,
383
+ responseBody: lastError.responseBody,
384
+ responseHeaders: lastError.responseHeaders,
385
+ status: lastError.statusCode,
386
+ url: lastError.url
387
+ });
388
+ return new CloudflareAIError({
389
+ attempts,
390
+ cause: lastError,
391
+ code: "unknown",
392
+ isRetryable: false,
393
+ message: `All models failed (${models}). Last error: ${String(lastError)}`,
394
+ model: attempts.at(-1)?.model ?? "",
395
+ requestBodyValues: void 0,
396
+ url
397
+ });
398
+ }
399
+ //#endregion
400
+ //#region src/models/ai-sdk/wires/shared.ts
401
+ /** Usage with every field unknown — the shape callers can always fall back to. */
402
+ function emptyUsage() {
403
+ return {
404
+ inputTokens: {
405
+ cacheRead: void 0,
406
+ cacheWrite: void 0,
407
+ noCache: void 0,
408
+ total: void 0
409
+ },
410
+ outputTokens: {
411
+ reasoning: void 0,
412
+ text: void 0,
413
+ total: void 0
414
+ }
415
+ };
416
+ }
417
+ /** A fresh id for a stream part or a tool call the provider did not name. */
418
+ function newId() {
419
+ return crypto.randomUUID();
420
+ }
421
+ const BASE64_CHUNK = 32768;
422
+ /** Base64-encodes bytes without blowing the argument limit on large files. */
423
+ function toBase64(data) {
424
+ if (typeof data === "string") return data;
425
+ let binary = "";
426
+ for (let offset = 0; offset < data.length; offset += BASE64_CHUNK) binary += String.fromCharCode(...data.subarray(offset, offset + BASE64_CHUNK));
427
+ return btoa(binary);
428
+ }
429
+ /** Reads a record field without widening everything to `any`. */
430
+ function record(value) {
431
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
432
+ }
433
+ /** Reads an array field, or `undefined` when it is not one. */
434
+ function array(value) {
435
+ return Array.isArray(value) ? value : void 0;
436
+ }
437
+ /** Reads a string field, or `undefined` when it is not one. */
438
+ function text(value) {
439
+ return typeof value === "string" ? value : void 0;
440
+ }
441
+ /** Reads a number field, or `undefined` when it is not one. */
442
+ function count(value) {
443
+ return typeof value === "number" ? value : void 0;
444
+ }
445
+ /** The finish reason used when a provider ends a stream without saying why. */
446
+ function defaultFinishReason() {
447
+ return {
448
+ raw: void 0,
449
+ unified: "stop"
450
+ };
451
+ }
452
+ //#endregion
453
+ //#region src/models/ai-sdk/models/embedding.ts
454
+ /**
455
+ * Workers AI batches up to this many strings per embedding call.
456
+ *
457
+ * @see https://developers.cloudflare.com/workers-ai/platform/limits/
458
+ */
459
+ const MAX_EMBEDDINGS_PER_CALL = 3e3;
460
+ var _config$3 = /* @__PURE__ */ new WeakMap();
461
+ var _options$3 = /* @__PURE__ */ new WeakMap();
462
+ /**
463
+ * An `EmbeddingModelV4` over the Workers AI text-embedding catalog. The run
464
+ * path takes `{ text: string[] }` and answers `{ data, shape, usage }`,
465
+ * sometimes inside the Cloudflare envelope.
466
+ *
467
+ * @experimental This surface is experimental and may change.
468
+ */
469
+ var CloudflareEmbeddingModel = class {
470
+ constructor(modelId, options, config) {
471
+ this.specificationVersion = "v4";
472
+ this.provider = "cloudflare";
473
+ this.maxEmbeddingsPerCall = MAX_EMBEDDINGS_PER_CALL;
474
+ this.supportsParallelCalls = true;
475
+ _classPrivateFieldInitSpec(this, _config$3, void 0);
476
+ _classPrivateFieldInitSpec(this, _options$3, void 0);
477
+ options?.fallback?.forEach((leg) => {
478
+ if (typeof leg === "string") requireWorkersAIId(leg);
479
+ });
480
+ this.modelId = modelId;
481
+ _classPrivateFieldSet2(_options$3, this, options);
482
+ _classPrivateFieldSet2(_config$3, this, config);
483
+ }
484
+ async doEmbed(options) {
485
+ if (options.values.length > MAX_EMBEDDINGS_PER_CALL) throw new TooManyEmbeddingValuesForCallError({
486
+ maxEmbeddingsPerCall: MAX_EMBEDDINGS_PER_CALL,
487
+ modelId: this.modelId,
488
+ provider: this.provider,
489
+ values: options.values
490
+ });
491
+ const resolved = resolveOptions(_classPrivateFieldGet2(_config$3, this).providerGateway, _classPrivateFieldGet2(_options$3, this), parseCallOptions(options.providerOptions));
492
+ const input = { text: options.values };
493
+ const transport = _classPrivateFieldGet2(_config$3, this).transport;
494
+ return withFallback(this.modelId, resolved.fallback, transport.url, async (modelId) => {
495
+ const response = await transport.run({
496
+ gateway: resolved.gateway,
497
+ headers: {
498
+ ...definedHeaders(options.headers),
499
+ ...resolved.headers,
500
+ ...resolved.sessionAffinity === void 0 ? {} : { "x-session-affinity": resolved.sessionAffinity }
501
+ },
502
+ input,
503
+ model: modelId,
504
+ signal: options.abortSignal
505
+ });
506
+ if (!response.ok) throw await errorFromResponse(response, {
507
+ model: modelId,
508
+ requestBodyValues: input,
509
+ url: transport.url
510
+ });
511
+ const body = record(unwrapEnvelope(await response.json(), {
512
+ model: modelId,
513
+ status: response.status,
514
+ url: transport.url
515
+ })) ?? {};
516
+ const embeddings = (array(body.data) ?? []).map((row) => (array(row) ?? []).filter((value) => typeof value === "number"));
517
+ const tokens = count(record(body.usage)?.prompt_tokens);
518
+ return {
519
+ embeddings,
520
+ response: { headers: headersToObject(response.headers) },
521
+ ...tokens === void 0 ? {} : { usage: { tokens } },
522
+ warnings: []
523
+ };
524
+ });
525
+ }
526
+ };
527
+ //#endregion
528
+ //#region src/models/ai-sdk/wires/chat-completions.ts
529
+ function fullMediaType(mediaType) {
530
+ return mediaType.includes("/") ? mediaType : `${mediaType}/jpeg`;
531
+ }
532
+ function unsupported$1(feature, details) {
533
+ return {
534
+ details,
535
+ feature,
536
+ type: "unsupported"
537
+ };
538
+ }
539
+ /** A compat-layer warning in the AI SDK's warning shape. */
540
+ function fromCompat(warning) {
541
+ return unsupported$1(warning.feature, warning.message);
542
+ }
543
+ /**
544
+ * Gemini 3 signs each assistant turn and each function call with an opaque
545
+ * `extra_content.google.thought_signature`, and rejects a function call
546
+ * replayed in the same turn without it. Nothing here reads the payload: it is
547
+ * carried out as provider metadata and put back verbatim on the next turn.
548
+ *
549
+ * `extraContent` is the signature of the assistant message; `toolExtraContent`
550
+ * is the one that belongs to an individual `tool_calls[i]` entry.
551
+ */
552
+ function extraContentMetadata(fields) {
553
+ const metadata = {};
554
+ const message = record(fields.extraContent);
555
+ const tool = record(fields.toolExtraContent);
556
+ if (message !== void 0) metadata.extraContent = message;
557
+ if (tool !== void 0) metadata.toolExtraContent = tool;
558
+ if (Object.keys(metadata).length === 0) return {};
559
+ return { providerMetadata: { [PROVIDER_OPTIONS_KEY]: metadata } };
560
+ }
561
+ /** Reads back what {@link extraContentMetadata} stored on a replayed part. */
562
+ function storedExtraContent(options, key) {
563
+ return record(options?.[PROVIDER_OPTIONS_KEY]?.[key]);
564
+ }
565
+ function toolResultText(output, warnings) {
566
+ switch (output.type) {
567
+ case "text":
568
+ case "error-text": return output.value;
569
+ case "json":
570
+ case "error-json": return JSON.stringify(output.value);
571
+ case "execution-denied": return output.reason ?? "The user denied this tool call.";
572
+ case "content": {
573
+ const dropped = output.value.filter((part) => part.type !== "text");
574
+ if (dropped.length > 0) warnings.push(unsupported$1("tool-result-part", `Tool result parts of type ${[...new Set(dropped.map((part) => part.type))].join(", ")} cannot be sent on the chat-completions wire and were dropped.`));
575
+ return output.value.map((part) => part.type === "text" ? part.text : "").filter((part) => part !== "").join("\n");
576
+ }
577
+ default: return String(output);
578
+ }
579
+ }
580
+ function userContent(message, warnings) {
581
+ const parts = [];
582
+ let onlyText = true;
583
+ for (const part of message.content) {
584
+ if (part.type === "text") {
585
+ parts.push({
586
+ text: part.text,
587
+ type: "text"
588
+ });
589
+ continue;
590
+ }
591
+ if (!(part.mediaType === "image" || part.mediaType.startsWith("image/"))) {
592
+ warnings.push(unsupported$1("file-part", `Files of type ${part.mediaType} are not supported on this wire and were dropped.`));
593
+ continue;
594
+ }
595
+ if (part.data.type === "data") {
596
+ onlyText = false;
597
+ parts.push({
598
+ image_url: { url: `data:${fullMediaType(part.mediaType)};base64,${toBase64(part.data.data)}` },
599
+ type: "image_url"
600
+ });
601
+ continue;
602
+ }
603
+ if (part.data.type === "url") {
604
+ onlyText = false;
605
+ parts.push({
606
+ image_url: { url: part.data.url.toString() },
607
+ type: "image_url"
608
+ });
609
+ continue;
610
+ }
611
+ warnings.push(unsupported$1("file-part", "Only inline data and URL images are supported; the file was dropped."));
612
+ }
613
+ if (onlyText) return parts.map((part) => part.type === "text" ? part.text : "").join("");
614
+ return parts;
615
+ }
616
+ function convertPrompt(prompt, warnings) {
617
+ const messages = [];
618
+ for (const message of prompt) switch (message.role) {
619
+ case "system":
620
+ messages.push({
621
+ content: message.content,
622
+ role: "system"
623
+ });
624
+ break;
625
+ case "user":
626
+ messages.push({
627
+ content: userContent(message, warnings),
628
+ role: "user"
629
+ });
630
+ break;
631
+ case "assistant": {
632
+ let content = "";
633
+ let reasoning = "";
634
+ let extraContent;
635
+ const toolCalls = [];
636
+ for (const part of message.content) {
637
+ extraContent ??= storedExtraContent(part.providerOptions, "extraContent");
638
+ if (part.type === "text") content += part.text;
639
+ else if (part.type === "reasoning") reasoning += part.text;
640
+ else if (part.type === "tool-call") {
641
+ const toolExtra = storedExtraContent(part.providerOptions, "toolExtraContent");
642
+ toolCalls.push({
643
+ function: {
644
+ arguments: typeof part.input === "string" ? part.input : JSON.stringify(part.input ?? {}),
645
+ name: part.toolName
646
+ },
647
+ id: part.toolCallId,
648
+ type: "function",
649
+ ...toolExtra === void 0 ? {} : { extra_content: toolExtra }
650
+ });
651
+ } else warnings.push(unsupported$1("assistant-part", `Assistant "${part.type}" parts cannot be replayed on the chat-completions wire and were dropped.`));
652
+ }
653
+ messages.push({
654
+ content,
655
+ ...reasoning !== "" ? { reasoning_content: reasoning } : {},
656
+ ...extraContent === void 0 ? {} : { extra_content: extraContent },
657
+ ...toolCalls.length > 0 ? { tool_calls: toolCalls } : {},
658
+ role: "assistant"
659
+ });
660
+ break;
661
+ }
662
+ case "tool":
663
+ for (const part of message.content) {
664
+ if (part.type !== "tool-result") {
665
+ warnings.push(unsupported$1("tool-part", `Tool "${part.type}" parts are not carried on the chat-completions wire and were dropped.`));
666
+ continue;
667
+ }
668
+ messages.push({
669
+ content: toolResultText(part.output, warnings),
670
+ name: part.toolName,
671
+ role: "tool",
672
+ tool_call_id: part.toolCallId
673
+ });
674
+ }
675
+ break;
676
+ default: throw new Error(`Unsupported message role: ${String(message)}`);
677
+ }
678
+ return messages;
679
+ }
680
+ /** Folds the AI SDK's schema description into the schema itself. */
681
+ function foldSchema(schema, description) {
682
+ if (description === void 0 || schema.description !== void 0) return schema;
683
+ return {
684
+ ...schema,
685
+ description
686
+ };
687
+ }
688
+ function responseFormat(options) {
689
+ const format = options.responseFormat;
690
+ if (format === void 0 || format.type !== "json") return void 0;
691
+ if (format.schema === void 0) return { type: "json_object" };
692
+ return {
693
+ json_schema: {
694
+ name: format.name ?? "response",
695
+ schema: foldSchema(format.schema, format.description),
696
+ strict: true
697
+ },
698
+ type: "json_schema"
699
+ };
700
+ }
701
+ function toolFields(options, warnings) {
702
+ const tools = [];
703
+ for (const tool of options.tools ?? []) {
704
+ if (tool.type !== "function") {
705
+ warnings.push(unsupported$1("provider-tool", `Provider tool "${tool.name}" is not available through the Cloudflare run path.`));
706
+ continue;
707
+ }
708
+ tools.push({
709
+ function: {
710
+ description: tool.description,
711
+ name: tool.name,
712
+ parameters: tool.inputSchema
713
+ },
714
+ type: "function"
715
+ });
716
+ }
717
+ if (tools.length === 0) return {};
718
+ const choice = options.toolChoice;
719
+ let toolChoice;
720
+ switch (choice?.type) {
721
+ case void 0: break;
722
+ case "auto":
723
+ toolChoice = "auto";
724
+ break;
725
+ case "none":
726
+ toolChoice = "none";
727
+ break;
728
+ case "required":
729
+ toolChoice = "required";
730
+ break;
731
+ case "tool":
732
+ toolChoice = {
733
+ function: { name: choice.toolName },
734
+ type: "function"
735
+ };
736
+ break;
737
+ default: throw new Error(`Unsupported tool choice: ${String(choice)}`);
738
+ }
739
+ return {
740
+ tools,
741
+ ...toolChoice === void 0 ? {} : { tool_choice: toolChoice }
742
+ };
743
+ }
744
+ /**
745
+ * The strict-body spelling of the reasoning request: an effort level, or
746
+ * `null` for "off". The compat layer turns `null` into whatever the model
747
+ * understands, or warns when nothing does.
748
+ */
749
+ function reasoningEffortField(options, context) {
750
+ if (context.reasoningEffort !== void 0) return { reasoning_effort: context.reasoningEffort };
751
+ const reasoning = options.reasoning;
752
+ if (reasoning === void 0 || reasoning === "provider-default") return {};
753
+ if (reasoning === "none") return { reasoning_effort: null };
754
+ return { reasoning_effort: reasoning };
755
+ }
756
+ /**
757
+ * Builds a strict OpenAI chat-completions body from AI SDK call options and
758
+ * runs it through the compat layer for the target model.
759
+ *
760
+ * @experimental This surface is experimental and may change.
761
+ */
762
+ function buildOpenAIRequest(options, context) {
763
+ const warnings = [];
764
+ if (options.topK !== void 0) warnings.push(unsupported$1("topK", "topK is not part of the chat-completions API."));
765
+ const format = responseFormat(options);
766
+ const prepared = prepareChatCompletionsRequest({
767
+ messages: convertPrompt(options.prompt, warnings),
768
+ ...options.maxOutputTokens === void 0 ? {} : { max_tokens: options.maxOutputTokens },
769
+ ...options.temperature === void 0 ? {} : { temperature: options.temperature },
770
+ ...options.topP === void 0 ? {} : { top_p: options.topP },
771
+ ...options.stopSequences === void 0 || options.stopSequences.length === 0 ? {} : { stop: options.stopSequences },
772
+ ...options.seed === void 0 ? {} : { seed: options.seed },
773
+ ...options.frequencyPenalty === void 0 ? {} : { frequency_penalty: options.frequencyPenalty },
774
+ ...options.presencePenalty === void 0 ? {} : { presence_penalty: options.presencePenalty },
775
+ ...format === void 0 ? {} : { response_format: format },
776
+ ...toolFields(options, warnings),
777
+ ...reasoningEffortField(options, context),
778
+ ...context.chatTemplateKwargs === void 0 ? {} : { chat_template_kwargs: context.chatTemplateKwargs },
779
+ ...context.stream ? {
780
+ stream: true,
781
+ stream_options: { include_usage: true }
782
+ } : {}
783
+ }, context.modelId);
784
+ return {
785
+ body: prepared.body,
786
+ reasoningOff: prepared.reasoningOff,
787
+ warnings: [...warnings, ...prepared.warnings.map(fromCompat)]
788
+ };
789
+ }
790
+ function mapFinishReason(raw) {
791
+ const value = text(raw);
792
+ switch (value) {
793
+ case "stop": return {
794
+ raw: value,
795
+ unified: "stop"
796
+ };
797
+ case "length": return {
798
+ raw: value,
799
+ unified: "length"
800
+ };
801
+ case "tool_calls":
802
+ case "function_call": return {
803
+ raw: value,
804
+ unified: "tool-calls"
805
+ };
806
+ case "content_filter": return {
807
+ raw: value,
808
+ unified: "content-filter"
809
+ };
810
+ case "error": return {
811
+ raw: value,
812
+ unified: "error"
813
+ };
814
+ default: return value === void 0 ? defaultFinishReason() : {
815
+ raw: value,
816
+ unified: "other"
817
+ };
818
+ }
819
+ }
820
+ function mapUsage(raw) {
821
+ const usage = record(raw);
822
+ if (usage === void 0) return emptyUsage();
823
+ const promptTokens = count(usage.prompt_tokens);
824
+ const cacheRead = count(record(usage.prompt_tokens_details)?.cached_tokens);
825
+ const reasoningTokens = count(record(usage.completion_tokens_details)?.reasoning_tokens);
826
+ const completionTokens = count(usage.completion_tokens);
827
+ const totalTokens = count(usage.total_tokens);
828
+ const outputTotal = totalTokens !== void 0 && promptTokens !== void 0 ? Math.max(completionTokens ?? 0, totalTokens - promptTokens) : completionTokens;
829
+ return {
830
+ inputTokens: {
831
+ cacheRead,
832
+ cacheWrite: void 0,
833
+ noCache: promptTokens === void 0 ? void 0 : Math.max(0, promptTokens - (cacheRead ?? 0)),
834
+ total: promptTokens
835
+ },
836
+ outputTokens: {
837
+ reasoning: reasoningTokens,
838
+ text: void 0,
839
+ total: outputTotal
840
+ },
841
+ raw: usage
842
+ };
843
+ }
844
+ function toolCallsFrom(raw, messageExtra) {
845
+ const calls = array(raw) ?? [];
846
+ const content = [];
847
+ for (const entry of calls) {
848
+ const call = record(entry);
849
+ if (call === void 0) continue;
850
+ const fn = record(call.function);
851
+ const name = text(fn?.name);
852
+ if (name === void 0) continue;
853
+ content.push({
854
+ input: text(fn?.arguments) ?? "{}",
855
+ toolCallId: text(call.id) ?? newId(),
856
+ toolName: name,
857
+ type: "tool-call",
858
+ ...extraContentMetadata({
859
+ extraContent: content.length === 0 ? messageExtra : void 0,
860
+ toolExtraContent: call.extra_content
861
+ })
862
+ });
863
+ }
864
+ return content;
865
+ }
866
+ /**
867
+ * Parses a non-streaming response. The body is normalized to the strict
868
+ * `chat.completion` shape first, so only `choices[0].message` is read.
869
+ *
870
+ * @experimental This surface is experimental and may change.
871
+ */
872
+ function parseOpenAIGeneration(json, modelId) {
873
+ const body = normalizeChatCompletion(json, modelId);
874
+ const choice = record(array(body.choices)?.[0]);
875
+ const message = record(choice?.message);
876
+ const content = [];
877
+ const reasoning = text(message?.reasoning_content);
878
+ if (reasoning !== void 0 && reasoning !== "") content.push({
879
+ text: reasoning,
880
+ type: "reasoning"
881
+ });
882
+ const answer = text(message?.content);
883
+ const messageExtra = message?.extra_content;
884
+ if (answer !== void 0 && answer !== "") content.push({
885
+ text: answer,
886
+ type: "text",
887
+ ...extraContentMetadata({ extraContent: messageExtra })
888
+ });
889
+ content.push(...toolCallsFrom(message?.tool_calls, answer === void 0 || answer === "" ? messageExtra : void 0));
890
+ const created = count(body.created);
891
+ return {
892
+ content,
893
+ finishReason: mapFinishReason(choice?.finish_reason),
894
+ responseId: text(body.id),
895
+ responseModelId: text(body.model),
896
+ timestamp: created === void 0 ? void 0 : /* @__PURE__ */ new Date(created * 1e3),
897
+ usage: mapUsage(body.usage)
898
+ };
899
+ }
900
+ /**
901
+ * Streams strict OpenAI `chat.completion.chunk` events into AI SDK stream
902
+ * parts. Tool calls arrive either as incremental `arguments` fragments closed
903
+ * by a null-finalization chunk, or as one delta with the complete arguments
904
+ * string; both are handled. Usage is read from whichever chunk carries it.
905
+ *
906
+ * @experimental This surface is experimental and may change.
907
+ */
908
+ function openAIStreamParser() {
909
+ const toolCalls = /* @__PURE__ */ new Map();
910
+ let lastToolIndex;
911
+ let textId;
912
+ let reasoningId;
913
+ let usage = emptyUsage();
914
+ let finishReason;
915
+ let sentMetadata = false;
916
+ let receivedDone = false;
917
+ let receivedEvent = false;
918
+ /** Message-level `extra_content` (Gemini's thought signature). */
919
+ let messageExtra;
920
+ let messageExtraClaimed = false;
921
+ let textEverOpened = false;
922
+ /**
923
+ * The message signature belongs on whichever part replays the message: the
924
+ * text block when there is one, otherwise the first tool call.
925
+ */
926
+ const claimMessageExtra = () => {
927
+ if (messageExtraClaimed) return void 0;
928
+ messageExtraClaimed = true;
929
+ return messageExtra;
930
+ };
931
+ const closeReasoning = (controller) => {
932
+ if (reasoningId === void 0) return;
933
+ controller.enqueue({
934
+ id: reasoningId,
935
+ type: "reasoning-end"
936
+ });
937
+ reasoningId = void 0;
938
+ };
939
+ const closeText = (controller) => {
940
+ if (textId === void 0) return;
941
+ controller.enqueue({
942
+ id: textId,
943
+ type: "text-end",
944
+ ...extraContentMetadata({ extraContent: claimMessageExtra() })
945
+ });
946
+ textId = void 0;
947
+ };
948
+ const closeToolCall = (index, controller) => {
949
+ const state = toolCalls.get(index);
950
+ if (state === void 0 || state.closed) return;
951
+ state.closed = true;
952
+ controller.enqueue({
953
+ id: state.id,
954
+ type: "tool-input-end"
955
+ });
956
+ controller.enqueue({
957
+ input: state.input,
958
+ toolCallId: state.id,
959
+ toolName: state.name,
960
+ type: "tool-call",
961
+ ...extraContentMetadata({
962
+ extraContent: textEverOpened ? void 0 : claimMessageExtra(),
963
+ toolExtraContent: state.extraContent
964
+ })
965
+ });
966
+ };
967
+ const emitToolDeltas = (raw, controller) => {
968
+ const deltas = array(raw);
969
+ if (deltas === void 0) return;
970
+ for (const entry of deltas) {
971
+ const call = record(entry);
972
+ if (call === void 0) continue;
973
+ const fn = record(call.function);
974
+ const name = text(fn?.name);
975
+ const input = text(fn?.arguments);
976
+ const id = text(call.id);
977
+ const rawIndex = count(call.index);
978
+ if (rawIndex === void 0 && id === void 0 && (name === void 0 || name === "") && (input === void 0 || input === "")) {
979
+ if (lastToolIndex !== void 0) closeToolCall(lastToolIndex, controller);
980
+ continue;
981
+ }
982
+ closeReasoning(controller);
983
+ closeText(controller);
984
+ const index = rawIndex ?? lastToolIndex ?? 0;
985
+ let state = toolCalls.get(index);
986
+ if (state?.closed === true) continue;
987
+ if (state === void 0) {
988
+ if (lastToolIndex !== void 0 && lastToolIndex !== index) closeToolCall(lastToolIndex, controller);
989
+ state = {
990
+ closed: false,
991
+ extraContent: call.extra_content,
992
+ id: id ?? newId(),
993
+ input: "",
994
+ name: name ?? ""
995
+ };
996
+ toolCalls.set(index, state);
997
+ lastToolIndex = index;
998
+ controller.enqueue({
999
+ id: state.id,
1000
+ toolName: state.name,
1001
+ type: "tool-input-start"
1002
+ });
1003
+ } else {
1004
+ if (name !== void 0 && state.name === "") state.name = name;
1005
+ state.extraContent ??= call.extra_content;
1006
+ }
1007
+ if (input !== void 0 && input !== "") {
1008
+ state.input += input;
1009
+ controller.enqueue({
1010
+ delta: input,
1011
+ id: state.id,
1012
+ type: "tool-input-delta"
1013
+ });
1014
+ }
1015
+ }
1016
+ };
1017
+ return new TransformStream({
1018
+ flush(controller) {
1019
+ for (const index of toolCalls.keys()) closeToolCall(index, controller);
1020
+ closeReasoning(controller);
1021
+ closeText(controller);
1022
+ if (finishReason === void 0) finishReason = receivedEvent && !receivedDone ? {
1023
+ raw: "stream-truncated",
1024
+ unified: "error"
1025
+ } : defaultFinishReason();
1026
+ controller.enqueue({
1027
+ finishReason,
1028
+ type: "finish",
1029
+ usage
1030
+ });
1031
+ },
1032
+ transform(data, controller) {
1033
+ if (data === "") return;
1034
+ if (data === "[DONE]") {
1035
+ receivedDone = true;
1036
+ return;
1037
+ }
1038
+ let parsed;
1039
+ try {
1040
+ parsed = JSON.parse(data);
1041
+ } catch {
1042
+ return;
1043
+ }
1044
+ const chunk = record(parsed);
1045
+ if (chunk === void 0) return;
1046
+ receivedEvent = true;
1047
+ const failure = record(chunk.error);
1048
+ if (failure !== void 0) {
1049
+ closeReasoning(controller);
1050
+ closeText(controller);
1051
+ controller.enqueue({
1052
+ error: failure,
1053
+ type: "error"
1054
+ });
1055
+ finishReason = {
1056
+ raw: text(failure.type) ?? "error",
1057
+ unified: "error"
1058
+ };
1059
+ return;
1060
+ }
1061
+ if (!sentMetadata) {
1062
+ const created = count(chunk.created);
1063
+ const id = text(chunk.id);
1064
+ const modelId = text(chunk.model);
1065
+ if (id !== void 0 || modelId !== void 0) {
1066
+ sentMetadata = true;
1067
+ controller.enqueue({
1068
+ id,
1069
+ modelId,
1070
+ timestamp: created === void 0 ? void 0 : /* @__PURE__ */ new Date(created * 1e3),
1071
+ type: "response-metadata"
1072
+ });
1073
+ }
1074
+ }
1075
+ if (record(chunk.usage) !== void 0) usage = mapUsage(chunk.usage);
1076
+ const choice = record(array(chunk.choices)?.[0]);
1077
+ const delta = record(choice?.delta);
1078
+ if (delta !== void 0) {
1079
+ messageExtra ??= record(delta.extra_content);
1080
+ const reasoning = text(delta.reasoning_content);
1081
+ if (reasoning !== void 0 && reasoning !== "") {
1082
+ if (reasoningId === void 0) {
1083
+ reasoningId = newId();
1084
+ controller.enqueue({
1085
+ id: reasoningId,
1086
+ type: "reasoning-start"
1087
+ });
1088
+ }
1089
+ controller.enqueue({
1090
+ delta: reasoning,
1091
+ id: reasoningId,
1092
+ type: "reasoning-delta"
1093
+ });
1094
+ }
1095
+ const content = text(delta.content);
1096
+ if (content !== void 0 && content !== "") {
1097
+ closeReasoning(controller);
1098
+ if (textId === void 0) {
1099
+ textId = newId();
1100
+ textEverOpened = true;
1101
+ controller.enqueue({
1102
+ id: textId,
1103
+ type: "text-start"
1104
+ });
1105
+ }
1106
+ controller.enqueue({
1107
+ delta: content,
1108
+ id: textId,
1109
+ type: "text-delta"
1110
+ });
1111
+ }
1112
+ emitToolDeltas(delta.tool_calls, controller);
1113
+ }
1114
+ if (text(choice?.finish_reason) !== void 0) finishReason = mapFinishReason(choice?.finish_reason);
1115
+ }
1116
+ });
1117
+ }
1118
+ //#endregion
1119
+ //#region src/models/ai-sdk/models/language.ts
1120
+ function callHeaders(options, resolved) {
1121
+ const headers = definedHeaders(options.headers);
1122
+ Object.assign(headers, resolved.headers);
1123
+ if (resolved.sessionAffinity !== void 0) headers["x-session-affinity"] = resolved.sessionAffinity;
1124
+ return headers;
1125
+ }
1126
+ /**
1127
+ * Builds the `providerMetadata.cloudflare` block every model in this module
1128
+ * attaches to its result. Shared with the non-language models in
1129
+ * `models/modality.ts`.
1130
+ */
1131
+ function cloudflareMetadata(model, resolved, response, transport, provider) {
1132
+ const headers = response.headers;
1133
+ const rawStep = headers.get("cf-aig-step");
1134
+ const step = rawStep === null ? NaN : Number(rawStep);
1135
+ const metadata = {
1136
+ gateway: resolved.gateway.id,
1137
+ model,
1138
+ ...provider === void 0 ? {} : { provider },
1139
+ ...Number.isNaN(step) ? {} : { step }
1140
+ };
1141
+ for (const [field, header] of [
1142
+ ["cacheStatus", "cf-aig-cache-status"],
1143
+ ["eventId", "cf-aig-event-id"],
1144
+ ["requestId", "cf-aig-request-id"],
1145
+ ["runId", "cf-aig-run-id"],
1146
+ ["traceId", "cf-aig-trace-id"]
1147
+ ]) {
1148
+ const value = headers.get(header);
1149
+ if (value !== null) metadata[field] = value;
1150
+ }
1151
+ const logId = headers.get("cf-aig-log-id") ?? transport.logIdFallback(response);
1152
+ if (logId !== void 0 && logId !== null) metadata.logId = logId;
1153
+ return { [PROVIDER_OPTIONS_KEY]: metadata };
1154
+ }
1155
+ function buildRequest(modelId, options, resolved, stream) {
1156
+ return buildOpenAIRequest(options, {
1157
+ chatTemplateKwargs: resolved.chatTemplateKwargs,
1158
+ modelId,
1159
+ reasoningEffort: resolved.reasoningEffort,
1160
+ stream
1161
+ });
1162
+ }
1163
+ /**
1164
+ * Prepends the single `stream-start` part and stamps `providerMetadata` onto
1165
+ * the `finish` part. A `TransformStream` rather than a manual enqueue so the
1166
+ * pipeline keeps its backpressure and error propagation.
1167
+ */
1168
+ function decorateStream(warnings, providerMetadata) {
1169
+ let started = false;
1170
+ const start = (controller) => {
1171
+ if (started) return;
1172
+ started = true;
1173
+ controller.enqueue({
1174
+ type: "stream-start",
1175
+ warnings
1176
+ });
1177
+ };
1178
+ return new TransformStream({
1179
+ flush(controller) {
1180
+ start(controller);
1181
+ },
1182
+ transform(part, controller) {
1183
+ start(controller);
1184
+ controller.enqueue(part.type === "finish" ? {
1185
+ ...part,
1186
+ providerMetadata
1187
+ } : part);
1188
+ }
1189
+ });
1190
+ }
1191
+ /**
1192
+ * Replays an already-complete generation as a stream. Workers AI sometimes
1193
+ * answers a `stream: true` request with a plain JSON body; degrading
1194
+ * gracefully beats failing the call.
1195
+ */
1196
+ function oneShotStream(generation) {
1197
+ return new ReadableStream({ start(controller) {
1198
+ if (generation.responseId !== void 0 || generation.responseModelId !== void 0) controller.enqueue({
1199
+ id: generation.responseId,
1200
+ modelId: generation.responseModelId,
1201
+ timestamp: generation.timestamp,
1202
+ type: "response-metadata"
1203
+ });
1204
+ for (const part of generation.content) emitContent(part, controller);
1205
+ controller.enqueue({
1206
+ finishReason: generation.finishReason,
1207
+ type: "finish",
1208
+ usage: generation.usage
1209
+ });
1210
+ controller.close();
1211
+ } });
1212
+ }
1213
+ function emitContent(part, controller) {
1214
+ switch (part.type) {
1215
+ case "text": {
1216
+ const id = newId();
1217
+ controller.enqueue({
1218
+ id,
1219
+ type: "text-start"
1220
+ });
1221
+ controller.enqueue({
1222
+ delta: part.text,
1223
+ id,
1224
+ type: "text-delta"
1225
+ });
1226
+ controller.enqueue({
1227
+ id,
1228
+ type: "text-end",
1229
+ ...part.providerMetadata === void 0 ? {} : { providerMetadata: part.providerMetadata }
1230
+ });
1231
+ break;
1232
+ }
1233
+ case "reasoning": {
1234
+ const id = newId();
1235
+ controller.enqueue({
1236
+ id,
1237
+ type: "reasoning-start"
1238
+ });
1239
+ controller.enqueue({
1240
+ delta: part.text,
1241
+ id,
1242
+ type: "reasoning-delta"
1243
+ });
1244
+ controller.enqueue({
1245
+ id,
1246
+ type: "reasoning-end",
1247
+ ...part.providerMetadata === void 0 ? {} : { providerMetadata: part.providerMetadata }
1248
+ });
1249
+ break;
1250
+ }
1251
+ case "tool-call":
1252
+ controller.enqueue({
1253
+ id: part.toolCallId,
1254
+ toolName: part.toolName,
1255
+ type: "tool-input-start"
1256
+ });
1257
+ controller.enqueue({
1258
+ delta: part.input,
1259
+ id: part.toolCallId,
1260
+ type: "tool-input-delta"
1261
+ });
1262
+ controller.enqueue({
1263
+ id: part.toolCallId,
1264
+ type: "tool-input-end"
1265
+ });
1266
+ controller.enqueue(part);
1267
+ break;
1268
+ default: controller.enqueue(part);
1269
+ }
1270
+ }
1271
+ var _config$2 = /* @__PURE__ */ new WeakMap();
1272
+ var _options$2 = /* @__PURE__ */ new WeakMap();
1273
+ var _CloudflareLanguageModel_brand = /* @__PURE__ */ new WeakSet();
1274
+ /**
1275
+ * A `LanguageModelV4` backed by the Cloudflare run path. The model id decides
1276
+ * the wire format; nothing about transport or wire format reaches user land.
1277
+ *
1278
+ * @experimental This surface is experimental and may change.
1279
+ */
1280
+ var CloudflareLanguageModel = class {
1281
+ constructor(modelId, options, config) {
1282
+ _classPrivateMethodInitSpec(this, _CloudflareLanguageModel_brand);
1283
+ this.specificationVersion = "v4";
1284
+ this.provider = "cloudflare";
1285
+ _classPrivateFieldInitSpec(this, _config$2, void 0);
1286
+ _classPrivateFieldInitSpec(this, _options$2, void 0);
1287
+ this.modelId = modelId;
1288
+ _classPrivateFieldSet2(_options$2, this, options);
1289
+ _classPrivateFieldSet2(_config$2, this, config);
1290
+ rememberOptions(this, options);
1291
+ this.supportedUrls = {};
1292
+ }
1293
+ async doGenerate(options) {
1294
+ const call = parseCallOptions(options.providerOptions);
1295
+ const resolved = _assertClassBrand(_CloudflareLanguageModel_brand, this, _resolve$1).call(this, call);
1296
+ const legOptions = withoutCallFallback(options);
1297
+ return _assertClassBrand(_CloudflareLanguageModel_brand, this, _withFallback$1).call(this, call, (model) => model.doGenerate(legOptions), async (modelId) => {
1298
+ const request = buildRequest(modelId, options, resolved, false);
1299
+ const response = await _assertClassBrand(_CloudflareLanguageModel_brand, this, _send).call(this, modelId, request, options, resolved);
1300
+ const generation = parseOpenAIGeneration(await _assertClassBrand(_CloudflareLanguageModel_brand, this, _readBody).call(this, modelId, request, response), modelId);
1301
+ return {
1302
+ content: generation.content,
1303
+ finishReason: generation.finishReason,
1304
+ providerMetadata: cloudflareMetadata(modelId, resolved, response, _classPrivateFieldGet2(_config$2, this).transport),
1305
+ request: { body: request.body },
1306
+ response: {
1307
+ headers: headersToObject(response.headers),
1308
+ id: generation.responseId,
1309
+ modelId: generation.responseModelId ?? modelId,
1310
+ timestamp: generation.timestamp
1311
+ },
1312
+ usage: generation.usage,
1313
+ warnings: request.warnings
1314
+ };
1315
+ });
1316
+ }
1317
+ async doStream(options) {
1318
+ const call = parseCallOptions(options.providerOptions);
1319
+ const resolved = _assertClassBrand(_CloudflareLanguageModel_brand, this, _resolve$1).call(this, call);
1320
+ const legOptions = withoutCallFallback(options);
1321
+ return _assertClassBrand(_CloudflareLanguageModel_brand, this, _withFallback$1).call(this, call, (model) => model.doStream(legOptions), async (modelId) => {
1322
+ const request = buildRequest(modelId, options, resolved, true);
1323
+ const response = await _assertClassBrand(_CloudflareLanguageModel_brand, this, _send).call(this, modelId, request, options, resolved);
1324
+ const providerMetadata = cloudflareMetadata(modelId, resolved, response, _classPrivateFieldGet2(_config$2, this).transport);
1325
+ const contentType = response.headers.get("content-type") ?? "";
1326
+ const decorate = decorateStream(request.warnings, providerMetadata);
1327
+ let parts;
1328
+ if (!contentType.includes("event-stream") || response.body === null) parts = oneShotStream(parseOpenAIGeneration(await _assertClassBrand(_CloudflareLanguageModel_brand, this, _readBody).call(this, modelId, request, response), modelId));
1329
+ else parts = response.body.pipeThrough(sseDataStream()).pipeThrough(normalizeChatCompletionsStream(modelId, { reasoningOff: request.reasoningOff })).pipeThrough(openAIStreamParser());
1330
+ return {
1331
+ request: { body: request.body },
1332
+ response: { headers: headersToObject(response.headers) },
1333
+ stream: parts.pipeThrough(decorate)
1334
+ };
1335
+ }, "stream");
1336
+ }
1337
+ };
1338
+ /**
1339
+ * Reads a 2xx body as JSON and unwraps the Cloudflare envelope. A 2xx that
1340
+ * is not JSON at all is a provider failure, not a caller bug, so it comes
1341
+ * back as a {@link CloudflareAIError} rather than a bare `SyntaxError`.
1342
+ */
1343
+ async function _readBody(modelId, request, response) {
1344
+ let json;
1345
+ try {
1346
+ json = await response.json();
1347
+ } catch (error) {
1348
+ throw new CloudflareAIError({
1349
+ cause: error,
1350
+ code: "provider-error",
1351
+ isRetryable: false,
1352
+ message: `The model answered ${response.status} with a body that is not JSON.`,
1353
+ model: modelId,
1354
+ requestBodyValues: request.body,
1355
+ status: response.status,
1356
+ url: _classPrivateFieldGet2(_config$2, this).transport.url
1357
+ });
1358
+ }
1359
+ return unwrapEnvelope(json, {
1360
+ model: modelId,
1361
+ status: response.status,
1362
+ url: _classPrivateFieldGet2(_config$2, this).transport.url
1363
+ });
1364
+ }
1365
+ function _resolve$1(call) {
1366
+ return resolveOptions(_classPrivateFieldGet2(_config$2, this).providerGateway, _classPrivateFieldGet2(_options$2, this), call);
1367
+ }
1368
+ async function _send(modelId, request, options, resolved) {
1369
+ const response = await _classPrivateFieldGet2(_config$2, this).transport.run({
1370
+ gateway: resolved.gateway,
1371
+ headers: callHeaders(options, resolved),
1372
+ input: request.body,
1373
+ model: modelId,
1374
+ signal: options.abortSignal
1375
+ });
1376
+ if (!response.ok) throw await errorFromResponse(response, {
1377
+ model: modelId,
1378
+ requestBodyValues: request.body,
1379
+ url: _classPrivateFieldGet2(_config$2, this).transport.url
1380
+ });
1381
+ return response;
1382
+ }
1383
+ /**
1384
+ * Runs this model, then each fallback leg in order. A leg named by id runs
1385
+ * through this same pipeline; a leg that is a model object — a vendor model
1386
+ * `ai()` already wrapped, or another provider's — is asked directly, so a
1387
+ * chain can mix Workers AI with anything the AI SDK can reach.
1388
+ */
1389
+ function _withFallback$1(call, runLeg, runSelf, mode = "generate") {
1390
+ const legs = fallbackLegs(_classPrivateFieldGet2(_options$2, this), call);
1391
+ const chain = (attempts) => mode === "stream" ? withStreamFallbackLegs(attempts, _classPrivateFieldGet2(_config$2, this).transport.url) : withFallbackLegs(attempts, _classPrivateFieldGet2(_config$2, this).transport.url);
1392
+ return chain([{
1393
+ model: this.modelId,
1394
+ run: () => runSelf(this.modelId)
1395
+ }, ...legs.map((leg) => typeof leg === "string" ? {
1396
+ model: requireWorkersAIId(leg),
1397
+ run: () => runSelf(leg)
1398
+ } : {
1399
+ model: leg.modelId,
1400
+ run: () => runLeg(leg)
1401
+ })]);
1402
+ }
1403
+ //#endregion
1404
+ //#region src/models/ai-sdk/models/gateway.ts
1405
+ /**
1406
+ * Throws unless a model's provider keeps its settings where every `@ai-sdk/*`
1407
+ * provider keeps them. Checked when the model is wrapped rather than when it
1408
+ * is called, so the mistake is reported at the line that made it.
1409
+ */
1410
+ function requireConfig(model) {
1411
+ const config = model.config;
1412
+ if (config === null || typeof config !== "object") throw new TypeError(`The model "${String(model.modelId ?? "unknown")}" from provider "${String(model.provider ?? "unknown")}" 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 }).`);
1413
+ return config;
1414
+ }
1415
+ /**
1416
+ * A per-call copy of the upstream model whose `config.fetch` is ours. The
1417
+ * user's model object is never touched: it may be shared across requests, and
1418
+ * two concurrent calls must not see each other's transport.
1419
+ */
1420
+ function cloneWithFetch(model, fetchImpl) {
1421
+ const config = requireConfig(model);
1422
+ const clone = Object.create(Object.getPrototypeOf(model));
1423
+ Object.defineProperties(clone, Object.getOwnPropertyDescriptors(model));
1424
+ Object.defineProperty(clone, "config", {
1425
+ configurable: true,
1426
+ enumerable: true,
1427
+ value: {
1428
+ ...config,
1429
+ fetch: fetchImpl
1430
+ },
1431
+ writable: true
1432
+ });
1433
+ return clone;
1434
+ }
1435
+ /** The request URL, whichever of `fetch`'s two call shapes was used. */
1436
+ function requestUrl(input) {
1437
+ if (typeof input === "string") return input;
1438
+ if (input instanceof URL) return input.href;
1439
+ return input.url;
1440
+ }
1441
+ /**
1442
+ * The body of either `fetch` call form: the `RequestInit`'s when one was
1443
+ * given, else the `Request`'s own, read from a clone so the caller's object
1444
+ * is neither consumed nor mutated.
1445
+ */
1446
+ async function requestBody(input, init) {
1447
+ if (init?.body !== void 0) return init.body;
1448
+ if (input instanceof Request && input.body !== null) return await input.clone().text();
1449
+ }
1450
+ /**
1451
+ * The vendor's body as the universal request's `query`. Only JSON travels:
1452
+ * the gateway's universal request has one JSON field for the whole upstream
1453
+ * body, so a multipart upload or a streamed body cannot be expressed.
1454
+ */
1455
+ function universalQuery(body) {
1456
+ if (typeof body !== "string") {
1457
+ const kind = body === null || body === void 0 ? "an empty" : body instanceof FormData ? "a FormData" : `a ${body.constructor?.name ?? typeof body}`;
1458
+ throw new TypeError(`AI Gateway's universal request carries a JSON body only, and this model sent ${kind} body. File uploads and other multipart requests cannot be routed through the gateway; call the vendor directly for those.`);
1459
+ }
1460
+ try {
1461
+ return JSON.parse(body);
1462
+ } catch (error) {
1463
+ throw new TypeError(`AI Gateway's universal request carries a JSON body only, and this model sent a body that is not JSON: ${String(error)}`);
1464
+ }
1465
+ }
1466
+ /**
1467
+ * The vendor's own request headers, minus the credential the gateway supplies
1468
+ * itself and the length of a body we are about to re-serialize.
1469
+ */
1470
+ function forwardedHeaders(init, input, route) {
1471
+ const source = init?.headers ?? (input instanceof Request ? input.headers : void 0);
1472
+ const dropped = /* @__PURE__ */ new Set([...route.authHeaders, "content-length"]);
1473
+ const headers = {};
1474
+ new Headers(source).forEach((value, key) => {
1475
+ if (!dropped.has(key.toLowerCase())) headers[key] = value;
1476
+ });
1477
+ return headers;
1478
+ }
1479
+ /** A response whose body can be read again, for the vendor's error handler. */
1480
+ function replayed(response, text) {
1481
+ const bodyless = response.status === 204 || response.status === 205 || response.status === 304;
1482
+ return new Response(bodyless ? null : text, {
1483
+ headers: response.headers,
1484
+ status: response.status,
1485
+ statusText: response.statusText
1486
+ });
1487
+ }
1488
+ /**
1489
+ * The `fetch` a routed model is given. It never reaches the vendor: it maps
1490
+ * the vendor's URL onto a gateway provider slug and endpoint, hands the body
1491
+ * over untouched, and returns the gateway's answer as the vendor's own.
1492
+ */
1493
+ function routedFetch(context) {
1494
+ const routed = async (input, init) => {
1495
+ const route = requireGatewayProvider(requestUrl(input));
1496
+ const query = universalQuery(await requestBody(input, init));
1497
+ const { resolved } = context;
1498
+ const extraHeaders = {
1499
+ ...resolved.headers,
1500
+ ...resolved.sessionAffinity === void 0 ? {} : { "x-session-affinity": resolved.sessionAffinity }
1501
+ };
1502
+ const response = await context.config.transport.universal({
1503
+ endpoint: route.endpoint,
1504
+ ...Object.keys(extraHeaders).length > 0 ? { extraHeaders } : {},
1505
+ gateway: resolved.gateway,
1506
+ headers: forwardedHeaders(init, input, route),
1507
+ provider: route.provider,
1508
+ query,
1509
+ signal: init?.signal ?? (input instanceof Request ? input.signal : void 0) ?? context.signal
1510
+ });
1511
+ context.capture.provider = route.provider;
1512
+ context.capture.response = response;
1513
+ if (response.ok) return response;
1514
+ const text = await response.text();
1515
+ let body;
1516
+ try {
1517
+ body = JSON.parse(text);
1518
+ } catch {
1519
+ return replayed(response, text);
1520
+ }
1521
+ if (!isGatewayErrorEnvelope(body)) return replayed(response, text);
1522
+ throw errorFromGatewayEnvelope(body, {
1523
+ model: modelOf(query) ?? route.provider,
1524
+ requestBodyValues: query,
1525
+ responseBody: text,
1526
+ responseHeaders: headersToObject(response.headers),
1527
+ status: response.status,
1528
+ url: context.config.transport.url
1529
+ });
1530
+ };
1531
+ return routed;
1532
+ }
1533
+ /** The model id out of a vendor body, for error reporting. */
1534
+ function modelOf(query) {
1535
+ if (query === null || typeof query !== "object") return void 0;
1536
+ const model = query.model;
1537
+ return typeof model === "string" ? model : void 0;
1538
+ }
1539
+ /** The call options a routed model sees: ours are read out and removed. */
1540
+ function withoutOurOptions(options) {
1541
+ const providerOptions = options.providerOptions;
1542
+ if (providerOptions === void 0 || !("cloudflare" in providerOptions)) return options;
1543
+ const rest = { ...providerOptions };
1544
+ delete rest[PROVIDER_OPTIONS_KEY];
1545
+ return {
1546
+ ...options,
1547
+ providerOptions: rest
1548
+ };
1549
+ }
1550
+ /** Adds our metadata block without dropping the vendor's own keys. */
1551
+ function mergeMetadata(existing, ours) {
1552
+ return {
1553
+ ...existing,
1554
+ ...ours
1555
+ };
1556
+ }
1557
+ /**
1558
+ * The same metadata, in the shape an image result's provider metadata takes.
1559
+ *
1560
+ * `ImageModelV4ProviderMetadata` is not the shared shape: every provider block
1561
+ * must carry an `images` array, one entry per generated image, and the AI SDK
1562
+ * spreads that array when it merges the calls a multi-image request fanned out
1563
+ * into. A block without one makes `generateImage` throw, and only the array's
1564
+ * entries survive that merge, so ours goes inside it.
1565
+ */
1566
+ function metadataFor(result, ours) {
1567
+ const images = result.images;
1568
+ if (!Array.isArray(images)) return ours;
1569
+ const block = ours[PROVIDER_OPTIONS_KEY];
1570
+ return {
1571
+ ...ours,
1572
+ [PROVIDER_OPTIONS_KEY]: {
1573
+ ...block,
1574
+ images: images.map(() => ({ ...block }))
1575
+ }
1576
+ };
1577
+ }
1578
+ /**
1579
+ * The Workers AI knobs a routed vendor model cannot honour. They are not
1580
+ * dropped silently: the vendor decides its own reasoning, so a caller who set
1581
+ * `reasoningEffort` here is asking for something that never leaves.
1582
+ */
1583
+ function ignoredWarnings(resolved) {
1584
+ const warnings = [];
1585
+ for (const [option, value] of [["reasoningEffort", resolved.reasoningEffort], ["chatTemplateKwargs", resolved.chatTemplateKwargs]]) {
1586
+ if (value === void 0) continue;
1587
+ warnings.push({
1588
+ 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.`,
1589
+ feature: option,
1590
+ type: "unsupported"
1591
+ });
1592
+ }
1593
+ return warnings;
1594
+ }
1595
+ /**
1596
+ * The Workers AI knobs a routed non-language model was asked with, added to
1597
+ * the result's own `warnings` when it has one.
1598
+ *
1599
+ * Only the per-call `providerOptions.cloudflare` bag can carry them here —
1600
+ * {@link RoutedModelOptions} leaves them off the per-model type — and only
1601
+ * some v4 result shapes have somewhere to put a warning: image, speech,
1602
+ * transcription and reranking results do, an embedding result does not.
1603
+ */
1604
+ function routedWarnings(result, resolved) {
1605
+ const existing = result.warnings;
1606
+ if (!Array.isArray(existing)) return {};
1607
+ const warnings = ignoredWarnings(resolved);
1608
+ if (warnings.length === 0) return {};
1609
+ return { warnings: [...existing, ...warnings] };
1610
+ }
1611
+ /**
1612
+ * Stamps the finish part with `providerMetadata.cloudflare`, and adds our own
1613
+ * warnings to the `stream-start` the vendor emitted.
1614
+ */
1615
+ function stampStream(metadata, warnings) {
1616
+ return new TransformStream({ transform(part, controller) {
1617
+ if (part.type === "finish") {
1618
+ controller.enqueue({
1619
+ ...part,
1620
+ providerMetadata: mergeMetadata(part.providerMetadata, metadata())
1621
+ });
1622
+ return;
1623
+ }
1624
+ if (part.type === "stream-start" && warnings.length > 0) {
1625
+ controller.enqueue({
1626
+ ...part,
1627
+ warnings: [...part.warnings, ...warnings]
1628
+ });
1629
+ return;
1630
+ }
1631
+ controller.enqueue(part);
1632
+ } });
1633
+ }
1634
+ var _model = /* @__PURE__ */ new WeakMap();
1635
+ var _options$1 = /* @__PURE__ */ new WeakMap();
1636
+ var _config$1 = /* @__PURE__ */ new WeakMap();
1637
+ var _GatewayLanguageModel_brand = /* @__PURE__ */ new WeakSet();
1638
+ /**
1639
+ * A `LanguageModelV4` that is the user's own vendor model, routed through AI
1640
+ * Gateway. Generation, parsing, tool handling and error shapes stay the
1641
+ * vendor's; only the transport is Cloudflare's.
1642
+ *
1643
+ * @experimental This surface is experimental and may change.
1644
+ */
1645
+ var GatewayLanguageModel = class {
1646
+ constructor(model, options, config) {
1647
+ _classPrivateMethodInitSpec(this, _GatewayLanguageModel_brand);
1648
+ this.specificationVersion = "v4";
1649
+ _classPrivateFieldInitSpec(this, _model, void 0);
1650
+ _classPrivateFieldInitSpec(this, _options$1, void 0);
1651
+ _classPrivateFieldInitSpec(this, _config$1, void 0);
1652
+ requireConfig(model);
1653
+ _classPrivateFieldSet2(_model, this, model);
1654
+ _classPrivateFieldSet2(_options$1, this, options);
1655
+ _classPrivateFieldSet2(_config$1, this, config);
1656
+ rememberOptions(this, options);
1657
+ }
1658
+ /** The vendor's own provider name — `anthropic.messages`, `openai.responses`. */
1659
+ get provider() {
1660
+ return _classPrivateFieldGet2(_model, this).provider;
1661
+ }
1662
+ /** The vendor's own id spelling, which the gateway requires verbatim. */
1663
+ get modelId() {
1664
+ return _classPrivateFieldGet2(_model, this).modelId;
1665
+ }
1666
+ get supportedUrls() {
1667
+ return _classPrivateFieldGet2(_model, this).supportedUrls;
1668
+ }
1669
+ /** The model this wraps, for callers that need the vendor object back. */
1670
+ get model() {
1671
+ return _classPrivateFieldGet2(_model, this);
1672
+ }
1673
+ async doGenerate(options) {
1674
+ const call = parseCallOptions(options.providerOptions);
1675
+ const resolved = _assertClassBrand(_GatewayLanguageModel_brand, this, _resolve).call(this, call);
1676
+ const upstream = withoutOurOptions(options);
1677
+ const legOptions = withoutCallFallback(options);
1678
+ return _assertClassBrand(_GatewayLanguageModel_brand, this, _withFallback).call(this, call, (leg) => leg.doGenerate(legOptions), async () => {
1679
+ const capture = {};
1680
+ const result = await _assertClassBrand(_GatewayLanguageModel_brand, this, _route).call(this, resolved, capture, options.abortSignal).doGenerate(upstream);
1681
+ const warnings = ignoredWarnings(resolved);
1682
+ return {
1683
+ ...result,
1684
+ providerMetadata: mergeMetadata(result.providerMetadata, _assertClassBrand(_GatewayLanguageModel_brand, this, _metadata).call(this, resolved, capture)),
1685
+ response: _assertClassBrand(_GatewayLanguageModel_brand, this, _response).call(this, result.response, capture),
1686
+ warnings: warnings.length > 0 ? [...result.warnings, ...warnings] : result.warnings
1687
+ };
1688
+ });
1689
+ }
1690
+ async doStream(options) {
1691
+ const call = parseCallOptions(options.providerOptions);
1692
+ const resolved = _assertClassBrand(_GatewayLanguageModel_brand, this, _resolve).call(this, call);
1693
+ const upstream = withoutOurOptions(options);
1694
+ const legOptions = withoutCallFallback(options);
1695
+ return _assertClassBrand(_GatewayLanguageModel_brand, this, _withFallback).call(this, call, (leg) => leg.doStream(legOptions), async () => {
1696
+ const capture = {};
1697
+ const result = await _assertClassBrand(_GatewayLanguageModel_brand, this, _route).call(this, resolved, capture, options.abortSignal).doStream(upstream);
1698
+ return {
1699
+ ...result,
1700
+ response: _assertClassBrand(_GatewayLanguageModel_brand, this, _response).call(this, result.response, capture),
1701
+ stream: result.stream.pipeThrough(stampStream(() => _assertClassBrand(_GatewayLanguageModel_brand, this, _metadata).call(this, resolved, capture), ignoredWarnings(resolved)))
1702
+ };
1703
+ }, "stream");
1704
+ }
1705
+ };
1706
+ function _route(resolved, capture, signal) {
1707
+ return cloneWithFetch(_classPrivateFieldGet2(_model, this), routedFetch({
1708
+ capture,
1709
+ config: _classPrivateFieldGet2(_config$1, this),
1710
+ resolved,
1711
+ signal
1712
+ }));
1713
+ }
1714
+ function _resolve(call) {
1715
+ return resolveOptions(_classPrivateFieldGet2(_config$1, this).providerGateway, _classPrivateFieldGet2(_options$1, this), call);
1716
+ }
1717
+ function _metadata(resolved, capture) {
1718
+ const response = capture.response ?? new Response(null);
1719
+ return cloudflareMetadata(this.modelId, resolved, response, _classPrivateFieldGet2(_config$1, this).transport, capture.provider);
1720
+ }
1721
+ function _response(response, capture) {
1722
+ if (capture.response === void 0) return response;
1723
+ const headers = headersToObject(capture.response.headers);
1724
+ return {
1725
+ ...response,
1726
+ headers: {
1727
+ ...response?.headers,
1728
+ ...headers
1729
+ }
1730
+ };
1731
+ }
1732
+ /**
1733
+ * The vendor model first, then each fallback leg. A leg named by id is a
1734
+ * Workers AI model; a leg that is a model object is asked as it stands, so
1735
+ * `ai()` has already wrapped it if it needed wrapping.
1736
+ */
1737
+ function _withFallback(call, runLeg, run, mode = "generate") {
1738
+ const legs = fallbackLegs(_classPrivateFieldGet2(_options$1, this), call);
1739
+ if (legs.length === 0) return run();
1740
+ const chain = (attempts) => mode === "stream" ? withStreamFallbackLegs(attempts, _classPrivateFieldGet2(_config$1, this).transport.url) : withFallbackLegs(attempts, _classPrivateFieldGet2(_config$1, this).transport.url);
1741
+ return chain([{
1742
+ model: this.modelId,
1743
+ run
1744
+ }, ...legs.map((leg) => {
1745
+ const model = typeof leg === "string" ? _assertClassBrand(_GatewayLanguageModel_brand, this, _workersAI).call(this, leg) : leg;
1746
+ return {
1747
+ model: model.modelId,
1748
+ run: () => runLeg(model)
1749
+ };
1750
+ })]);
1751
+ }
1752
+ /** A Workers AI leg, carrying this model's gateway options but no chain. */
1753
+ function _workersAI(modelId) {
1754
+ return new CloudflareLanguageModel(requireWorkersAIId(modelId), {
1755
+ ..._classPrivateFieldGet2(_options$1, this),
1756
+ fallback: void 0
1757
+ }, _classPrivateFieldGet2(_config$1, this));
1758
+ }
1759
+ /**
1760
+ * Routes any other AI SDK v4 model the vendor built — embedding, image,
1761
+ * speech, transcription — through the same universal gateway request. Only
1762
+ * `fetch` is swapped; every `do…` method stays the vendor's, and its result
1763
+ * gains `providerMetadata.cloudflare` when the result is an object that can
1764
+ * carry one.
1765
+ *
1766
+ * @experimental This surface is experimental and may change.
1767
+ */
1768
+ function routed(model, options, config) {
1769
+ requireConfig(model);
1770
+ return new Proxy(model, { get(target, property, receiver) {
1771
+ const value = Reflect.get(target, property, receiver);
1772
+ if (typeof value !== "function" || typeof property !== "string" || !property.startsWith("do")) return value;
1773
+ return async (call) => {
1774
+ const resolved = resolveOptions(config.providerGateway, options, parseCallOptions(call?.providerOptions));
1775
+ const upstream = call?.providerOptions === void 0 ? call : withoutOurOptions(call);
1776
+ const capture = {};
1777
+ const clone = cloneWithFetch(target, routedFetch({
1778
+ capture,
1779
+ config,
1780
+ resolved,
1781
+ signal: call?.abortSignal
1782
+ }));
1783
+ const result = await Reflect.get(clone, property).call(clone, upstream);
1784
+ if (result === null || typeof result !== "object") return result;
1785
+ const existing = result.providerMetadata;
1786
+ return {
1787
+ ...result,
1788
+ ...routedWarnings(result, resolved),
1789
+ providerMetadata: mergeMetadata(existing, metadataFor(result, cloudflareMetadata(String(target.modelId ?? ""), resolved, capture.response ?? new Response(null), config.transport, capture.provider)))
1790
+ };
1791
+ };
1792
+ } });
1793
+ }
1794
+ //#endregion
1795
+ //#region src/models/ai-sdk/models/modality.ts
1796
+ /** The `unsupported` warning shape, which every modality needs. */
1797
+ function unsupported(feature, details) {
1798
+ return {
1799
+ feature,
1800
+ type: "unsupported",
1801
+ ...details === void 0 ? {} : { details }
1802
+ };
1803
+ }
1804
+ /** Decodes base64 into bytes; passes `Uint8Array` input straight through. */
1805
+ function toBytes(data) {
1806
+ if (typeof data !== "string") return data;
1807
+ const binary = atob(data);
1808
+ const bytes = new Uint8Array(binary.length);
1809
+ for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
1810
+ return bytes;
1811
+ }
1812
+ var _config = /* @__PURE__ */ new WeakMap();
1813
+ var _options = /* @__PURE__ */ new WeakMap();
1814
+ var _CloudflareModalityModel_brand = /* @__PURE__ */ new WeakSet();
1815
+ /**
1816
+ * A model over the Cloudflare run path that is not a language model. Holds
1817
+ * the one call path all four modalities share; each subclass only builds a
1818
+ * body and reads an answer.
1819
+ *
1820
+ * @experimental This surface is experimental and may change.
1821
+ */
1822
+ var CloudflareModalityModel = class {
1823
+ constructor(modelId, options, config) {
1824
+ _classPrivateMethodInitSpec(this, _CloudflareModalityModel_brand);
1825
+ this.specificationVersion = "v4";
1826
+ this.provider = "cloudflare";
1827
+ _classPrivateFieldInitSpec(this, _config, void 0);
1828
+ _classPrivateFieldInitSpec(this, _options, void 0);
1829
+ options?.fallback?.forEach((leg) => {
1830
+ if (typeof leg === "string") requireWorkersAIId(leg);
1831
+ });
1832
+ this.modelId = modelId;
1833
+ _classPrivateFieldSet2(_options, this, options);
1834
+ _classPrivateFieldSet2(_config, this, config);
1835
+ }
1836
+ /** The endpoint this model calls, for error reporting. */
1837
+ get endpoint() {
1838
+ return _classPrivateFieldGet2(_config, this).transport.url;
1839
+ }
1840
+ /**
1841
+ * Sends one call, trying each fallback leg in turn, and decodes the answer
1842
+ * as JSON or as raw bytes depending on what the model sent back.
1843
+ */
1844
+ async send(call) {
1845
+ const resolved = resolveOptions(_classPrivateFieldGet2(_config, this).providerGateway, _classPrivateFieldGet2(_options, this), parseCallOptions(call.providerOptions));
1846
+ const transport = _classPrivateFieldGet2(_config, this).transport;
1847
+ return withFallback(this.modelId, resolved.fallback, transport.url, async (modelId) => {
1848
+ const request = call.build(modelId);
1849
+ const response = await transport.run({
1850
+ gateway: resolved.gateway,
1851
+ headers: {
1852
+ ...definedHeaders(call.headers),
1853
+ ...resolved.headers,
1854
+ ...resolved.sessionAffinity === void 0 ? {} : { "x-session-affinity": resolved.sessionAffinity }
1855
+ },
1856
+ input: request.input,
1857
+ model: modelId,
1858
+ signal: call.abortSignal
1859
+ });
1860
+ if (!response.ok) throw await errorFromResponse(response, {
1861
+ model: modelId,
1862
+ requestBodyValues: request.input,
1863
+ url: transport.url
1864
+ });
1865
+ const mediaType = (response.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
1866
+ const body = await _assertClassBrand(_CloudflareModalityModel_brand, this, _decode).call(this, response, modelId, request.input, mediaType);
1867
+ const answer = {
1868
+ headers: headersToObject(response.headers),
1869
+ input: request.input,
1870
+ mediaType,
1871
+ modelId,
1872
+ providerMetadata: cloudflareMetadata(modelId, resolved, response, transport),
1873
+ timestamp: /* @__PURE__ */ new Date(),
1874
+ url: transport.url,
1875
+ warnings: request.warnings,
1876
+ ...body
1877
+ };
1878
+ call.check?.(answer);
1879
+ return answer;
1880
+ });
1881
+ }
1882
+ };
1883
+ /**
1884
+ * Reads a 2xx body. A JSON content type is parsed and unwrapped; anything
1885
+ * else is the model's own bytes (PNG, JPEG, MP3). A JSON content type with a
1886
+ * body that will not parse is a provider failure, not a caller bug, so it
1887
+ * comes back as a {@link CloudflareAIError} rather than a bare `SyntaxError`.
1888
+ */
1889
+ async function _decode(response, modelId, input, mediaType) {
1890
+ if (!mediaType.includes("json")) return {
1891
+ bytes: new Uint8Array(await response.arrayBuffer()),
1892
+ json: void 0
1893
+ };
1894
+ let json;
1895
+ try {
1896
+ json = await response.json();
1897
+ } catch (error) {
1898
+ throw new CloudflareAIError({
1899
+ cause: error,
1900
+ code: "provider-error",
1901
+ isRetryable: false,
1902
+ message: `The model answered ${response.status} with a body that is not JSON.`,
1903
+ model: modelId,
1904
+ requestBodyValues: input,
1905
+ status: response.status,
1906
+ url: _classPrivateFieldGet2(_config, this).transport.url
1907
+ });
1908
+ }
1909
+ return {
1910
+ bytes: void 0,
1911
+ json: unwrapEnvelope(json, {
1912
+ model: modelId,
1913
+ status: response.status,
1914
+ url: _classPrivateFieldGet2(_config, this).transport.url
1915
+ })
1916
+ };
1917
+ }
1918
+ //#endregion
1919
+ //#region src/models/ai-sdk/models/image.ts
1920
+ function imageOptions(providerOptions) {
1921
+ const raw = record(providerOptions?.["cloudflare"]) ?? {};
1922
+ const negativePrompt = text(raw.negativePrompt);
1923
+ return {
1924
+ ...count(raw.steps) === void 0 ? {} : { steps: count(raw.steps) },
1925
+ ...count(raw.guidance) === void 0 ? {} : { guidance: count(raw.guidance) },
1926
+ ...count(raw.strength) === void 0 ? {} : { strength: count(raw.strength) },
1927
+ ...negativePrompt === void 0 ? {} : { negativePrompt }
1928
+ };
1929
+ }
1930
+ /** `1024x768` → `{ width: 1024, height: 768 }`. */
1931
+ function parseSize(size) {
1932
+ const [width, height] = size.split("x").map(Number);
1933
+ return Number.isFinite(width) && Number.isFinite(height) ? {
1934
+ height,
1935
+ width
1936
+ } : void 0;
1937
+ }
1938
+ /** The base64 bytes of a file the caller passed for img2img or masking. */
1939
+ function fileData(file) {
1940
+ if (file.type === "file") return toBase64(file.data);
1941
+ }
1942
+ /**
1943
+ * Builds the run-path body. The knobs and the flux-1 subset rule live in
1944
+ * `core/images.ts`, shared with the pi-ai module so the two cannot drift; the
1945
+ * AI SDK call options and the `files`/`mask` byte handling are mapped here.
1946
+ */
1947
+ function buildImageRequest(modelId, options) {
1948
+ const warnings = [];
1949
+ const extra = imageOptions(options.providerOptions);
1950
+ if (options.prompt === void 0) warnings.push({
1951
+ message: "Cloudflare image models require a prompt; sent an empty one.",
1952
+ type: "other"
1953
+ });
1954
+ if (options.aspectRatio !== void 0) warnings.push(unsupported("aspectRatio", "Use `size` instead: Workers AI takes pixels."));
1955
+ let size;
1956
+ if (options.size !== void 0) {
1957
+ size = parseSize(options.size);
1958
+ if (size === void 0) warnings.push(unsupported("size", `Could not read "${options.size}".`));
1959
+ }
1960
+ const built = buildImageInput(modelId, options.prompt ?? "", {
1961
+ ...size === void 0 ? {} : {
1962
+ height: size.height,
1963
+ width: size.width
1964
+ },
1965
+ ...options.seed === void 0 ? {} : { seed: options.seed },
1966
+ ...extra.steps === void 0 ? {} : { steps: extra.steps },
1967
+ ...extra.guidance === void 0 ? {} : { guidance: extra.guidance },
1968
+ ...extra.strength === void 0 ? {} : { strength: extra.strength },
1969
+ ...extra.negativePrompt === void 0 ? {} : { negativePrompt: extra.negativePrompt },
1970
+ ...options.mask === void 0 ? {} : { mask: true },
1971
+ ...options.files?.[0] === void 0 ? {} : { sourceImage: true }
1972
+ });
1973
+ const input = built.input;
1974
+ for (const warning of built.warnings) warnings.push(unsupported(warning.feature, warning.message));
1975
+ if (built.minimal) return {
1976
+ input,
1977
+ warnings
1978
+ };
1979
+ const source = options.files?.[0];
1980
+ if (source !== void 0) {
1981
+ const data = fileData(source);
1982
+ if (data === void 0) warnings.push(unsupported("files", "Image URLs are not supported; send the bytes."));
1983
+ else input.image_b64 = data;
1984
+ if ((options.files?.length ?? 0) > 1) warnings.push(unsupported("files", "Only the first image is used for img2img."));
1985
+ }
1986
+ if (options.mask !== void 0) {
1987
+ const data = fileData(options.mask);
1988
+ if (data === void 0) warnings.push(unsupported("mask", "Mask URLs are not supported; send the bytes."));
1989
+ else input.mask = Array.from(toBytes(data));
1990
+ }
1991
+ return {
1992
+ input,
1993
+ warnings
1994
+ };
1995
+ }
1996
+ function readImage(answer) {
1997
+ if (answer.bytes !== void 0) return {
1998
+ base64: void 0,
1999
+ bytes: answer.bytes,
2000
+ mediaType: answer.mediaType === "" ? "image/png" : answer.mediaType
2001
+ };
2002
+ const base64 = text((record(answer.json) ?? {}).image);
2003
+ if (base64 === void 0) throw new CloudflareAIError({
2004
+ code: "provider-error",
2005
+ data: answer.json,
2006
+ isRetryable: false,
2007
+ message: "The image model answered JSON without an `image` field.",
2008
+ model: answer.modelId,
2009
+ requestBodyValues: answer.input,
2010
+ url: answer.url
2011
+ });
2012
+ return {
2013
+ base64,
2014
+ bytes: void 0,
2015
+ mediaType: imageMediaTypeOf(base64)
2016
+ };
2017
+ }
2018
+ function imageUsage(json) {
2019
+ const usage = record(record(json)?.usage);
2020
+ if (usage === void 0) return void 0;
2021
+ return {
2022
+ inputTokens: count(usage.prompt_tokens),
2023
+ outputTokens: count(usage.completion_tokens),
2024
+ totalTokens: count(usage.total_tokens)
2025
+ };
2026
+ }
2027
+ /**
2028
+ * An `ImageModelV4` over the Cloudflare text-to-image catalog.
2029
+ *
2030
+ * The run path generates one image per call, so `maxImagesPerCall` is 1 and
2031
+ * `generateImage` fans a larger `n` out itself; a direct `doGenerate` with
2032
+ * `n > 1` is fanned out here instead.
2033
+ *
2034
+ * @experimental This surface is experimental and may change.
2035
+ */
2036
+ var CloudflareImageModel = class extends CloudflareModalityModel {
2037
+ constructor(modelId, options, config) {
2038
+ super(modelId, options, config);
2039
+ this.maxImagesPerCall = 1;
2040
+ }
2041
+ async doGenerate(options) {
2042
+ const wanted = Math.max(1, options.n);
2043
+ const answers = await Promise.all(Array.from({ length: wanted }, () => this.send({
2044
+ abortSignal: options.abortSignal,
2045
+ build: (modelId) => buildImageRequest(modelId, options),
2046
+ check: (answer) => {
2047
+ readImage(answer);
2048
+ },
2049
+ headers: options.headers,
2050
+ providerOptions: options.providerOptions
2051
+ })));
2052
+ const first = answers[0];
2053
+ const generated = answers.map(readImage);
2054
+ const images = generated.some((image) => image.base64 !== void 0) ? generated.map((image) => image.base64 ?? toBase64(image.bytes)) : generated.map((image) => image.bytes);
2055
+ const usage = imageUsage(first.json);
2056
+ return {
2057
+ images,
2058
+ providerMetadata: { [PROVIDER_OPTIONS_KEY]: {
2059
+ ...first.providerMetadata[PROVIDER_OPTIONS_KEY],
2060
+ images: generated.map((image, index) => ({
2061
+ ...answers[index]?.providerMetadata[PROVIDER_OPTIONS_KEY],
2062
+ mediaType: image.mediaType
2063
+ }))
2064
+ } },
2065
+ response: {
2066
+ headers: first.headers,
2067
+ modelId: first.modelId,
2068
+ timestamp: first.timestamp
2069
+ },
2070
+ ...usage === void 0 ? {} : { usage },
2071
+ warnings: first.warnings
2072
+ };
2073
+ }
2074
+ };
2075
+ //#endregion
2076
+ //#region src/models/ai-sdk/models/reranking.ts
2077
+ /** Builds the run-path body for one reranking leg. */
2078
+ function buildRerankingRequest(options) {
2079
+ const warnings = [];
2080
+ const documents = options.documents.type === "text" ? options.documents.values : options.documents.values.map((value) => JSON.stringify(value));
2081
+ if (options.documents.type === "object") warnings.push({
2082
+ details: "Object documents are sent as JSON text.",
2083
+ feature: "documents",
2084
+ type: "compatibility"
2085
+ });
2086
+ const input = {
2087
+ contexts: documents.map((value) => ({ text: value })),
2088
+ query: options.query
2089
+ };
2090
+ if (options.topN !== void 0) input.top_k = options.topN;
2091
+ return {
2092
+ input,
2093
+ warnings
2094
+ };
2095
+ }
2096
+ /**
2097
+ * A `RerankingModelV4` over the Workers AI reranker catalog.
2098
+ *
2099
+ * @experimental This surface is experimental and may change.
2100
+ */
2101
+ var CloudflareRerankingModel = class extends CloudflareModalityModel {
2102
+ constructor(modelId, options, config) {
2103
+ super(modelId, options, config);
2104
+ }
2105
+ async doRerank(options) {
2106
+ const answer = await this.send({
2107
+ abortSignal: options.abortSignal,
2108
+ build: () => buildRerankingRequest(options),
2109
+ headers: options.headers,
2110
+ providerOptions: options.providerOptions
2111
+ });
2112
+ const ranking = (array((record(answer.json) ?? {}).response) ?? []).flatMap((entry) => {
2113
+ const row = record(entry);
2114
+ const index = count(row?.id);
2115
+ const relevanceScore = count(row?.score);
2116
+ if (index === void 0 || relevanceScore === void 0) return [];
2117
+ return [{
2118
+ index,
2119
+ relevanceScore
2120
+ }];
2121
+ });
2122
+ ranking.sort((left, right) => right.relevanceScore - left.relevanceScore);
2123
+ return {
2124
+ providerMetadata: answer.providerMetadata,
2125
+ ranking,
2126
+ response: {
2127
+ body: answer.json,
2128
+ headers: answer.headers,
2129
+ modelId: answer.modelId,
2130
+ timestamp: answer.timestamp
2131
+ },
2132
+ warnings: answer.warnings
2133
+ };
2134
+ }
2135
+ };
2136
+ //#endregion
2137
+ //#region src/models/ai-sdk/models/speech.ts
2138
+ /**
2139
+ * MeloTTS is the odd one out: the prompt key is `prompt`, the language key is
2140
+ * `lang`, and there is no voice.
2141
+ *
2142
+ * @see https://developers.cloudflare.com/workers-ai/models/melotts/
2143
+ */
2144
+ const MELOTTS = "@cf/myshell-ai/melotts";
2145
+ /**
2146
+ * Output encodings Aura accepts. `outputFormat` maps onto this; anything else
2147
+ * is warned about rather than sent, because the run path validates the enum.
2148
+ *
2149
+ * @see https://developers.cloudflare.com/workers-ai/models/aura-1/
2150
+ */
2151
+ const AURA_ENCODINGS = /* @__PURE__ */ new Set([
2152
+ "linear16",
2153
+ "flac",
2154
+ "mulaw",
2155
+ "alaw",
2156
+ "mp3",
2157
+ "opus",
2158
+ "aac"
2159
+ ]);
2160
+ /** Builds the run-path body for one speech leg. */
2161
+ function buildSpeechRequest(modelId, options) {
2162
+ const warnings = [];
2163
+ if (options.speed !== void 0) warnings.push(unsupported("speed", "Workers AI speech models do not take a speed."));
2164
+ if (options.instructions !== void 0) warnings.push(unsupported("instructions", "Workers AI speech models take text, not instructions."));
2165
+ if (modelId === MELOTTS) {
2166
+ const input = { prompt: options.text };
2167
+ if (options.language !== void 0) input.lang = options.language;
2168
+ if (options.voice !== void 0) warnings.push(unsupported("voice", `${MELOTTS} has a single voice.`));
2169
+ if (options.outputFormat !== void 0) warnings.push(unsupported("outputFormat", `${MELOTTS} picks its own audio format.`));
2170
+ return {
2171
+ input,
2172
+ warnings
2173
+ };
2174
+ }
2175
+ const input = { text: options.text };
2176
+ if (options.voice !== void 0) input.speaker = options.voice;
2177
+ if (options.outputFormat !== void 0) if (AURA_ENCODINGS.has(options.outputFormat)) input.encoding = options.outputFormat;
2178
+ else warnings.push(unsupported("outputFormat", `Expected one of ${[...AURA_ENCODINGS].join(", ")}.`));
2179
+ if (options.language !== void 0) warnings.push(unsupported("language", "Aura picks its language from the model id, e.g. @cf/deepgram/aura-2-es."));
2180
+ return {
2181
+ input,
2182
+ warnings
2183
+ };
2184
+ }
2185
+ /**
2186
+ * The audio in one answer. Bytes stay bytes and base64 stays base64: the AI
2187
+ * SDK converts either way on demand, and converting here would only lose
2188
+ * fidelity.
2189
+ */
2190
+ function readAudio(answer) {
2191
+ if (answer.bytes !== void 0) return answer.bytes;
2192
+ const encoded = text((record(answer.json) ?? {}).audio);
2193
+ if (encoded === void 0) throw new CloudflareAIError({
2194
+ code: "provider-error",
2195
+ data: answer.json,
2196
+ isRetryable: false,
2197
+ message: "The speech model answered JSON without an `audio` field.",
2198
+ model: answer.modelId,
2199
+ requestBodyValues: answer.input,
2200
+ url: answer.url
2201
+ });
2202
+ return encoded;
2203
+ }
2204
+ /**
2205
+ * A `SpeechModelV4` over the Workers AI text-to-speech catalog.
2206
+ *
2207
+ * @experimental This surface is experimental and may change.
2208
+ */
2209
+ var CloudflareSpeechModel = class extends CloudflareModalityModel {
2210
+ constructor(modelId, options, config) {
2211
+ super(modelId, options, config);
2212
+ }
2213
+ async doGenerate(options) {
2214
+ const answer = await this.send({
2215
+ abortSignal: options.abortSignal,
2216
+ build: (modelId) => buildSpeechRequest(modelId, options),
2217
+ check: (answer) => {
2218
+ readAudio(answer);
2219
+ },
2220
+ headers: options.headers,
2221
+ providerOptions: options.providerOptions
2222
+ });
2223
+ return {
2224
+ audio: readAudio(answer),
2225
+ providerMetadata: answer.providerMetadata,
2226
+ request: { body: answer.input },
2227
+ response: {
2228
+ headers: answer.headers,
2229
+ modelId: answer.modelId,
2230
+ timestamp: answer.timestamp
2231
+ },
2232
+ warnings: answer.warnings
2233
+ };
2234
+ }
2235
+ };
2236
+ //#endregion
2237
+ //#region src/models/ai-sdk/models/transcription.ts
2238
+ /**
2239
+ * Whisper ids that take the audio as an unsigned-byte array rather than as
2240
+ * base64.
2241
+ *
2242
+ * @see https://developers.cloudflare.com/workers-ai/models/whisper/
2243
+ */
2244
+ const BYTE_ARRAY_AUDIO = /* @__PURE__ */ new Set(["@cf/openai/whisper", "@cf/openai/whisper-tiny-en"]);
2245
+ /**
2246
+ * Deepgram's recognition models declare `audio: { body: object, contentType }`.
2247
+ * Every documented encoding of that shape answered `400 required properties at
2248
+ * '/audio' are 'body,contentType'` on the live run path, because `body` has to
2249
+ * be the audio object itself and JSON cannot carry it. Refuse early rather
2250
+ * than send a body known to fail.
2251
+ */
2252
+ const UNSUPPORTED = /* @__PURE__ */ new Set(["@cf/deepgram/nova-3", "@cf/deepgram/flux"]);
2253
+ function transcriptionOptions(providerOptions) {
2254
+ const raw = record(providerOptions?.["cloudflare"]) ?? {};
2255
+ const vadFilter = raw.vadFilter;
2256
+ return {
2257
+ ...text(raw.language) === void 0 ? {} : { language: text(raw.language) },
2258
+ ...text(raw.task) === void 0 ? {} : { task: text(raw.task) },
2259
+ ...text(raw.initialPrompt) === void 0 ? {} : { initialPrompt: text(raw.initialPrompt) },
2260
+ ...text(raw.prefix) === void 0 ? {} : { prefix: text(raw.prefix) },
2261
+ ...typeof vadFilter === "boolean" ? { vadFilter } : {}
2262
+ };
2263
+ }
2264
+ /** Builds the run-path body for one whisper leg. */
2265
+ function buildTranscriptionRequest(modelId, options) {
2266
+ const warnings = [];
2267
+ const extra = transcriptionOptions(options.providerOptions);
2268
+ const input = BYTE_ARRAY_AUDIO.has(modelId) ? { audio: Array.from(toBytes(options.audio)) } : { audio: toBase64(options.audio) };
2269
+ if (extra.language !== void 0) input.language = extra.language;
2270
+ if (extra.task !== void 0) input.task = extra.task;
2271
+ if (extra.initialPrompt !== void 0) input.initial_prompt = extra.initialPrompt;
2272
+ if (extra.prefix !== void 0) input.prefix = extra.prefix;
2273
+ if (extra.vadFilter !== void 0) input.vad_filter = extra.vadFilter;
2274
+ return {
2275
+ input,
2276
+ warnings
2277
+ };
2278
+ }
2279
+ /**
2280
+ * Reads segments out of a whisper answer. `segments` is what the large models
2281
+ * send; the smaller ones send only `words`, whose timings are the best segment
2282
+ * boundaries available.
2283
+ */
2284
+ function readSegments(body) {
2285
+ const segments = array(body.segments);
2286
+ if (segments !== void 0) return segments.flatMap((entry) => {
2287
+ const segment = record(entry);
2288
+ const value = text(segment?.text);
2289
+ if (segment === void 0 || value === void 0) return [];
2290
+ return [{
2291
+ endSecond: count(segment.end) ?? 0,
2292
+ startSecond: count(segment.start) ?? 0,
2293
+ text: value
2294
+ }];
2295
+ });
2296
+ return (array(body.words) ?? []).flatMap((entry) => {
2297
+ const word = record(entry);
2298
+ const value = text(word?.word);
2299
+ if (word === void 0 || value === void 0) return [];
2300
+ return [{
2301
+ endSecond: count(word.end) ?? 0,
2302
+ startSecond: count(word.start) ?? 0,
2303
+ text: value
2304
+ }];
2305
+ });
2306
+ }
2307
+ /**
2308
+ * A `TranscriptionModelV4` over the Workers AI speech-recognition catalog.
2309
+ *
2310
+ * @experimental This surface is experimental and may change.
2311
+ */
2312
+ var CloudflareTranscriptionModel = class extends CloudflareModalityModel {
2313
+ constructor(modelId, options, config) {
2314
+ super(modelId, options, config);
2315
+ }
2316
+ async doGenerate(options) {
2317
+ const answer = await this.send({
2318
+ abortSignal: options.abortSignal,
2319
+ build: (modelId) => {
2320
+ if (UNSUPPORTED.has(modelId)) throw new CloudflareAIError({
2321
+ code: "bad-request",
2322
+ isRetryable: false,
2323
+ message: `${modelId} takes the audio as an object body, which the JSON run path cannot carry. Use @cf/openai/whisper-large-v3-turbo.`,
2324
+ model: modelId,
2325
+ requestBodyValues: void 0,
2326
+ url: this.endpoint
2327
+ });
2328
+ return buildTranscriptionRequest(modelId, options);
2329
+ },
2330
+ headers: options.headers,
2331
+ providerOptions: options.providerOptions
2332
+ });
2333
+ const body = record(answer.json) ?? {};
2334
+ const info = record(body.transcription_info);
2335
+ const language = text(info?.language);
2336
+ return {
2337
+ durationInSeconds: count(info?.duration),
2338
+ language,
2339
+ providerMetadata: answer.providerMetadata,
2340
+ request: { body: JSON.stringify(answer.input) },
2341
+ response: {
2342
+ body: answer.json,
2343
+ headers: answer.headers,
2344
+ modelId: answer.modelId,
2345
+ timestamp: answer.timestamp
2346
+ },
2347
+ segments: readSegments(body),
2348
+ text: text(body.text) ?? "",
2349
+ warnings: answer.warnings
2350
+ };
2351
+ }
2352
+ };
2353
+ //#endregion
2354
+ //#region src/models/ai-sdk/index.ts
2355
+ /** Whether a value is a model object rather than a model id. */
2356
+ function isModel(value) {
2357
+ return typeof value === "object" && value !== null;
2358
+ }
2359
+ /**
2360
+ * Creates a provider over Workers AI, and over every vendor AI Gateway can
2361
+ * reach.
2362
+ *
2363
+ * The Workers AI binding is the only way in — Workers AI models go through
2364
+ * `env.AI.run`, vendor models through `env.AI.gateway(id).run`, and there is
2365
+ * no HTTP transport and no API token. Gateway options are flat (`id`,
2366
+ * `cacheTtl`, …) or nested under `gateway`; per-model options and per-call
2367
+ * `providerOptions.cloudflare` override them in that order.
2368
+ *
2369
+ * ```ts
2370
+ * const ai = createAI({ binding: env.AI, id: "prod", cacheTtl: 60 });
2371
+ * const anthropic = createAnthropic({ apiKey: "cloudflare" });
2372
+ *
2373
+ * ai("@cf/zai-org/glm-4.7-flash");
2374
+ * ai(anthropic("claude-opus-4-8"), { fallback: [ai("@cf/zai-org/glm-4.7-flash")] });
2375
+ * ai.embedding("@cf/baai/bge-base-en-v1.5");
2376
+ * ```
2377
+ *
2378
+ * @experimental This surface is experimental and may change.
2379
+ */
2380
+ function createAI(settings) {
2381
+ const config = {
2382
+ providerGateway: settings,
2383
+ transport: createTransport(settings)
2384
+ };
2385
+ /**
2386
+ * Fallback legs are normalized once, here: a model object becomes a routed
2387
+ * model, so every leg a model runs is already this provider's.
2388
+ *
2389
+ * A leg inherits the chain's *gateway* options and nothing else. The rest of
2390
+ * the bag — `reasoningEffort`, `chatTemplateKwargs`, `headers`,
2391
+ * `sessionAffinity` — was written for the model it was written on, and a leg
2392
+ * that was configured with its own keeps every one of them.
2393
+ */
2394
+ const normalize = (options) => {
2395
+ if (options?.fallback === void 0) return options;
2396
+ const inherited = gatewayLayerOf(options);
2397
+ return {
2398
+ ...options,
2399
+ fallback: options.fallback.map((leg) => typeof leg === "string" ? requireWorkersAIId(leg) : languageModel(leg, inherited))
2400
+ };
2401
+ };
2402
+ function languageModel(model, options) {
2403
+ const resolved = normalize(options);
2404
+ if (isModel(model)) {
2405
+ if (model instanceof CloudflareLanguageModel) {
2406
+ const merged = normalize(mergeModelOptions(optionsOf(model), resolved));
2407
+ return new CloudflareLanguageModel(model.modelId, merged, config);
2408
+ }
2409
+ if (model instanceof GatewayLanguageModel) {
2410
+ const merged = normalize(mergeModelOptions(optionsOf(model), resolved));
2411
+ return new GatewayLanguageModel(model.model, merged, config);
2412
+ }
2413
+ return new GatewayLanguageModel(model, resolved, config);
2414
+ }
2415
+ return new CloudflareLanguageModel(requireWorkersAIId(model), resolved, config);
2416
+ }
2417
+ const embedding = (modelId, options) => new CloudflareEmbeddingModel(modelId, options, config);
2418
+ const image = (modelId, options) => new CloudflareImageModel(modelId, options, config);
2419
+ const transcription = (modelId, options) => new CloudflareTranscriptionModel(modelId, options, config);
2420
+ const speech = (modelId, options) => new CloudflareSpeechModel(modelId, options, config);
2421
+ const reranking = (modelId, options) => new CloudflareRerankingModel(modelId, options, config);
2422
+ const provider = (model, options) => languageModel(model, options);
2423
+ return Object.assign(provider, {
2424
+ embedding,
2425
+ embeddingModel: embedding,
2426
+ image,
2427
+ imageModel: image,
2428
+ languageModel,
2429
+ reranking,
2430
+ rerankingModel: reranking,
2431
+ routed: (model, options) => routed(model, options, config),
2432
+ specificationVersion: "v4",
2433
+ speech,
2434
+ speechModel: speech,
2435
+ textEmbeddingModel: embedding,
2436
+ transcription,
2437
+ transcriptionModel: transcription
2438
+ });
2439
+ }
2440
+ //#endregion
2441
+ export { CloudflareAIError, GatewayLanguageModel, createAI };
2442
+
2443
+ //# sourceMappingURL=index.js.map