@shop-os/modelkit 0.33.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -152,6 +152,7 @@ __export(index_exports, {
152
152
  videoLengthViolation: () => videoLengthViolation,
153
153
  videoSizeViolation: () => videoSizeViolation,
154
154
  videoToolConstraints: () => videoToolConstraints,
155
+ wavespeedAdapter: () => wavespeedAdapter,
155
156
  withRetry: () => withRetry,
156
157
  xaiVideoAdapter: () => xaiVideoAdapter
157
158
  });
@@ -177,32 +178,32 @@ var ModelKitError = class _ModelKitError extends Error {
177
178
  finishReason;
178
179
  /** Set when the provider billed a call that still failed; never sent to `onUsage`. */
179
180
  usage;
180
- constructor(init) {
181
- super(init.message, { cause: init.cause });
181
+ constructor(init2) {
182
+ super(init2.message, { cause: init2.cause });
182
183
  this.name = "ModelKitError";
183
- this.code = init.code;
184
- this.provider = init.provider;
185
- this.model = init.model;
186
- this.status = init.status;
187
- this.body = init.body;
188
- this.retryable = init.retryable ?? defaultRetryable(init.code);
189
- this.finishReason = init.finishReason;
190
- this.usage = init.usage;
191
- }
192
- withUsage(usage6) {
193
- const init = {
184
+ this.code = init2.code;
185
+ this.provider = init2.provider;
186
+ this.model = init2.model;
187
+ this.status = init2.status;
188
+ this.body = init2.body;
189
+ this.retryable = init2.retryable ?? defaultRetryable(init2.code);
190
+ this.finishReason = init2.finishReason;
191
+ this.usage = init2.usage;
192
+ }
193
+ withUsage(usage7) {
194
+ const init2 = {
194
195
  code: this.code,
195
196
  message: this.message,
196
197
  cause: this.cause,
197
198
  retryable: this.retryable,
198
- usage: usage6
199
+ usage: usage7
199
200
  };
200
- if (this.provider !== void 0) init.provider = this.provider;
201
- if (this.model !== void 0) init.model = this.model;
202
- if (this.status !== void 0) init.status = this.status;
203
- if (this.body !== void 0) init.body = this.body;
204
- if (this.finishReason !== void 0) init.finishReason = this.finishReason;
205
- const copy = new _ModelKitError(init);
201
+ if (this.provider !== void 0) init2.provider = this.provider;
202
+ if (this.model !== void 0) init2.model = this.model;
203
+ if (this.status !== void 0) init2.status = this.status;
204
+ if (this.body !== void 0) init2.body = this.body;
205
+ if (this.finishReason !== void 0) init2.finishReason = this.finishReason;
206
+ const copy = new _ModelKitError(init2);
206
207
  if (this.stack !== void 0) copy.stack = this.stack;
207
208
  return copy;
208
209
  }
@@ -6638,6 +6639,7 @@ var GROK_RATIOS = ["1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3"];
6638
6639
  var H3_RATIOS2 = ["21:9", "16:9", "4:3", "1:1", "3:4", "9:16"];
6639
6640
  var H3_REFERENCE_RATIOS = ["adaptive", ...H3_RATIOS2];
6640
6641
  var WAN_RATIOS = ["adaptive", "16:9", "4:3", "1:1", "3:4", "9:16"];
6642
+ var MAGI_RATIOS = ["21:9", "16:9", "4:3", "1:1", "3:4", "9:16"];
6641
6643
  var NEGATIVE_PROMPT = "blur, distort, and low quality";
6642
6644
  var FRAMES_EXCLUDE_REFERENCES = { framesExcludeReferences: true };
6643
6645
  var KLING_PROMPT2 = { referenceSyntax: "numbered", maxChars: 2500 };
@@ -7567,6 +7569,48 @@ var VIDEO_MODELS = [
7567
7569
  },
7568
7570
  capabilities: {}
7569
7571
  },
7572
+ {
7573
+ // Sand AI MAGI-2 on WaveSpeed. One row for text-, image- (start/end frame) and
7574
+ // reference-to-video; the adapter picks the endpoint from the inputs. WaveSpeed bills
7575
+ // USD 0.08 per requested second, sound and references included.
7576
+ // https://wavespeed.ai/docs/docs-api/sand-ai/magi-2/reference-to-video
7577
+ id: "magi-2",
7578
+ aliases: ["magi2", "sand-magi-2"],
7579
+ label: "MAGI-2",
7580
+ type: "video",
7581
+ adapter: "wavespeed",
7582
+ providerModelId: "sand-ai/magi-2",
7583
+ lifecycle: "active",
7584
+ exposure: ["cowork", "space_builder"],
7585
+ constraints: {
7586
+ aspectRatios: [...MAGI_RATIOS],
7587
+ resolutions: ["1080p"],
7588
+ durations: { min: 4, max: 30 },
7589
+ preferDefaultDuration: true,
7590
+ references: {
7591
+ images: 10,
7592
+ videos: 5,
7593
+ audios: 5,
7594
+ videoSeconds: { min: 2, max: 30, total: 30 },
7595
+ audioSeconds: { min: 2, max: 30, total: 30 }
7596
+ },
7597
+ supports: ["seed", "lastFrame", "generateAudio"],
7598
+ prompt: { referenceSyntax: "descriptive", maxChars: 15e3 },
7599
+ audio: "optional"
7600
+ },
7601
+ defaults: {
7602
+ durationSeconds: 5,
7603
+ resolution: "1080p",
7604
+ generateAudio: true
7605
+ },
7606
+ usage: { ...VIDEO_USAGE3 },
7607
+ pricingKind: "video_per_second",
7608
+ display: {
7609
+ provider: "sand-ai",
7610
+ description: "Sand AI MAGI-2 video model for text-to-video, image-to-video (start/end frame), and reference-to-video from up to 10 images, 5 videos and 5 audio clips, with native audio; 4 to 30 seconds at 1080p."
7611
+ },
7612
+ capabilities: { ...FRAMES_EXCLUDE_REFERENCES, lastFrameRequiresFirstFrame: true }
7613
+ },
7570
7614
  ...VIDEO_FAMILY_MODELS,
7571
7615
  ...VIDEO_AVATAR_MODELS,
7572
7616
  ...LUMA_VIDEO_MODELS
@@ -8799,7 +8843,8 @@ var ADAPTER_IDS = [
8799
8843
  "luma",
8800
8844
  "alibaba",
8801
8845
  "fish",
8802
- "elevenlabs"
8846
+ "elevenlabs",
8847
+ "wavespeed"
8803
8848
  ];
8804
8849
  var ModelTypeSchema = import_zod3.z.enum([
8805
8850
  "text",
@@ -9598,9 +9643,9 @@ var aiSdkTextAdapter = {
9598
9643
  if (route2.client === "bedrock-anthropic") return bedrockLanguageModel(ctx, route2);
9599
9644
  const { keyName } = route2;
9600
9645
  if (keyName === "aws") throw missingKey(ctx, keyName);
9601
- const apiKey = ctx.keys[keyName];
9602
- if (!apiKey) throw missingKey(ctx, keyName);
9603
- const settings = { apiKey, fetch: ctx.fetch };
9646
+ const apiKey2 = ctx.keys[keyName];
9647
+ if (!apiKey2) throw missingKey(ctx, keyName);
9648
+ const settings = { apiKey: apiKey2, fetch: ctx.fetch };
9604
9649
  if (route2.baseURL !== void 0) settings.baseURL = route2.baseURL;
9605
9650
  if (route2.headers !== void 0) settings.headers = route2.headers;
9606
9651
  switch (route2.client) {
@@ -9619,7 +9664,7 @@ var aiSdkTextAdapter = {
9619
9664
  case "openai-compatible": {
9620
9665
  const model = (0, import_openai_compatible.createOpenAICompatible)({
9621
9666
  name: route2.provider,
9622
- apiKey,
9667
+ apiKey: apiKey2,
9623
9668
  baseURL: route2.baseURL,
9624
9669
  fetch: ctx.fetch,
9625
9670
  ...route2.headers ? { headers: route2.headers } : {}
@@ -10075,16 +10120,16 @@ function classifyHttpError(status, body, provider, model) {
10075
10120
  else if (status === 408 || status === 504) code = "timeout";
10076
10121
  else if (status !== void 0 && status >= 500) code = "network";
10077
10122
  const retryable = code === "rate_limited" || code === "timeout" || code === "network";
10078
- const init = {
10123
+ const init2 = {
10079
10124
  code,
10080
10125
  message: `${provider} responded ${status ?? "?"}: ${text2.slice(0, 500)}`,
10081
10126
  provider,
10082
10127
  body,
10083
10128
  retryable
10084
10129
  };
10085
- if (status !== void 0) init.status = status;
10086
- if (model !== void 0) init.model = model;
10087
- return new ModelKitError(init);
10130
+ if (status !== void 0) init2.status = status;
10131
+ if (model !== void 0) init2.model = model;
10132
+ return new ModelKitError(init2);
10088
10133
  }
10089
10134
  function shouldRetry(err) {
10090
10135
  if (err instanceof ModelKitError) return err.retryable;
@@ -10175,15 +10220,15 @@ function throwAborted() {
10175
10220
  function transportError(provider, cause, model) {
10176
10221
  const message = cause instanceof Error ? cause.message : String(cause);
10177
10222
  const aborted = cause instanceof Error && cause.name === "AbortError";
10178
- const init = {
10223
+ const init2 = {
10179
10224
  code: aborted ? "timeout" : "network",
10180
10225
  message: `${provider} request failed before a response: ${message}`,
10181
10226
  provider,
10182
10227
  retryable: !aborted,
10183
10228
  cause
10184
10229
  };
10185
- if (model !== void 0) init.model = model;
10186
- return new ModelKitError(init);
10230
+ if (model !== void 0) init2.model = model;
10231
+ return new ModelKitError(init2);
10187
10232
  }
10188
10233
  function classifyThrown(provider, cause, model, override = {}) {
10189
10234
  if (cause instanceof ModelKitError) return cause;
@@ -10277,7 +10322,7 @@ function alibabaError(status, body, model, code = alibabaErrorCode(body)) {
10277
10322
  }
10278
10323
  const parsed = import_zod7.z.string().safeParse(body);
10279
10324
  const text2 = parsed.success ? parsed.data : JSON.stringify(body ?? "");
10280
- const init = {
10325
+ const init2 = {
10281
10326
  // A verdict with no HTTP status (a failed task) is not a transport failure.
10282
10327
  code: rule ?? "provider_rejected",
10283
10328
  message: `alibaba rejected the request${code ? ` (${code})` : ""}: ${text2.slice(0, 500)}`,
@@ -10286,11 +10331,11 @@ function alibabaError(status, body, model, code = alibabaErrorCode(body)) {
10286
10331
  body,
10287
10332
  retryable: false
10288
10333
  };
10289
- if (status !== void 0) init.status = status;
10290
- return new ModelKitError(init);
10334
+ if (status !== void 0) init2.status = status;
10335
+ return new ModelKitError(init2);
10291
10336
  }
10292
- function alibabaFetch(ctx, url, init) {
10293
- const withSignal = ctx.signal === void 0 ? init : { ...init, signal: ctx.signal };
10337
+ function alibabaFetch(ctx, url, init2) {
10338
+ const withSignal = ctx.signal === void 0 ? init2 : { ...init2, signal: ctx.signal };
10294
10339
  return ctx.fetch(url, withSignal).catch((cause) => {
10295
10340
  throw classifyThrown("alibaba", cause, ctx.model.id);
10296
10341
  });
@@ -10347,9 +10392,9 @@ async function readBody(res) {
10347
10392
  }
10348
10393
  async function mediaRefToBytes(ref, fetch2, options = {}) {
10349
10394
  if (!isUrlRef(ref)) return { bytes: ref.bytes, mime: ref.mime };
10350
- const init = {};
10351
- if (options.signal !== void 0) init.signal = options.signal;
10352
- const res = await fetch2(ref.url, init);
10395
+ const init2 = {};
10396
+ if (options.signal !== void 0) init2.signal = options.signal;
10397
+ const res = await fetch2(ref.url, init2);
10353
10398
  if (!res.ok) {
10354
10399
  const text2 = await res.text().catch(() => "");
10355
10400
  throw classifyHttpError(
@@ -10391,15 +10436,15 @@ function applyInputSpec(spec, req, refToUrl2, opts) {
10391
10436
  out[providerField] = mapped ?? serialised;
10392
10437
  }
10393
10438
  for (const [providerField, keys] of Object.entries(spec.arrays ?? {})) {
10394
- const urls2 = [];
10439
+ const urls3 = [];
10395
10440
  for (const key of keys) {
10396
10441
  if (!isArrayInputSpecKey(key)) continue;
10397
10442
  const value = canonicalValue(req, key);
10398
10443
  if (value === void 0) continue;
10399
- if (Array.isArray(value)) urls2.push(...value.map(refToUrl2));
10400
- else if (isMediaRef(value)) urls2.push(refToUrl2(value));
10444
+ if (Array.isArray(value)) urls3.push(...value.map(refToUrl2));
10445
+ else if (isMediaRef(value)) urls3.push(refToUrl2(value));
10401
10446
  }
10402
- if (urls2.length > 0) out[providerField] = urls2;
10447
+ if (urls3.length > 0) out[providerField] = urls3;
10403
10448
  }
10404
10449
  if (spec.dimensions !== void 0) {
10405
10450
  const dims = dimensionsFor(spec.dimensions, req);
@@ -10567,19 +10612,19 @@ async function generateAlibabaImage(req, ctx) {
10567
10612
  },
10568
10613
  mediaRetryOptions(ctx.call, ctx.signal)
10569
10614
  );
10570
- const urls2 = (data.output?.choices ?? []).flatMap(
10615
+ const urls3 = (data.output?.choices ?? []).flatMap(
10571
10616
  (choice) => (choice.message?.content ?? []).flatMap((part) => part.image ? [part.image] : [])
10572
10617
  );
10573
- if (urls2.length === 0) throw alibabaError(void 0, "Qwen Image returned no image", modelId);
10618
+ if (urls3.length === 0) throw alibabaError(void 0, "Qwen Image returned no image", modelId);
10574
10619
  const images = await Promise.all(
10575
- urls2.map(async (url) => {
10620
+ urls3.map(async (url) => {
10576
10621
  const res = await alibabaFetch(ctx, url, {});
10577
10622
  if (!res.ok) throw alibabaError(res.status, await res.text().catch(() => ""), modelId);
10578
10623
  const mime = res.headers.get("content-type") ?? "image/png";
10579
10624
  return { bytes: new Uint8Array(await res.arrayBuffer()), mime };
10580
10625
  })
10581
10626
  );
10582
- const usage6 = {
10627
+ const usage7 = {
10583
10628
  model: modelId,
10584
10629
  provider: "alibaba",
10585
10630
  modality: "IMAGE",
@@ -10587,9 +10632,9 @@ async function generateAlibabaImage(req, ctx) {
10587
10632
  quantity: data.usage?.output_image_count ?? images.length
10588
10633
  };
10589
10634
  const tier = billedTier(data.usage?.output_image_type, req.size);
10590
- if (tier !== void 0) usage6.imageSize = tier;
10591
- if (req.quality !== void 0) usage6.imageQuality = req.quality;
10592
- return { images, usage: usage6, raw: data };
10635
+ if (tier !== void 0) usage7.imageSize = tier;
10636
+ if (req.quality !== void 0) usage7.imageQuality = req.quality;
10637
+ return { images, usage: usage7, raw: data };
10593
10638
  }
10594
10639
 
10595
10640
  // src/adapters/alibaba-video.ts
@@ -11051,17 +11096,17 @@ var RENDERED = /* @__PURE__ */ new Map([
11051
11096
  [720, "720p"],
11052
11097
  [1080, "1080p"]
11053
11098
  ]);
11054
- function settleUsage(usage6, task) {
11099
+ function settleUsage(usage7, task) {
11055
11100
  const reported = task.usage;
11056
11101
  if (reported?.duration !== void 0 && reported.duration > 0) {
11057
- usage6.quantity = reported.duration;
11102
+ usage7.quantity = reported.duration;
11058
11103
  }
11059
11104
  const output = reported?.output_video_duration;
11060
- if (output !== void 0 && output > 0) usage6.durationSeconds = output;
11105
+ if (output !== void 0 && output > 0) usage7.durationSeconds = output;
11061
11106
  const rendered = reported?.SR === void 0 ? void 0 : RENDERED.get(reported.SR);
11062
- if (rendered !== void 0) usage6.resolution = rendered;
11107
+ if (rendered !== void 0) usage7.resolution = rendered;
11063
11108
  }
11064
- function alibabaVideoJob(ctx, jobId, usage6) {
11109
+ function alibabaVideoJob(ctx, jobId, usage7) {
11065
11110
  const { key } = alibabaCredentials(ctx);
11066
11111
  const modelId = ctx.model.id;
11067
11112
  const fetchTask = async () => {
@@ -11105,10 +11150,10 @@ function alibabaVideoJob(ctx, jobId, usage6) {
11105
11150
  if (!url) {
11106
11151
  throw alibabaError(void 0, "task succeeded with no video_url", modelId);
11107
11152
  }
11108
- settleUsage(usage6, task);
11153
+ settleUsage(usage7, task);
11109
11154
  return {
11110
11155
  video: { url, expiresAt: new Date(Date.now() + VIDEO_URL_TTL_MS) },
11111
- usage: usage6,
11156
+ usage: usage7,
11112
11157
  raw: task
11113
11158
  };
11114
11159
  }
@@ -11282,7 +11327,7 @@ function throwArkError(status, body, model, code = arkErrorCode(body)) {
11282
11327
  const parsed = import_zod10.z.string().safeParse(body);
11283
11328
  const text2 = parsed.success ? parsed.data : JSON.stringify(body ?? "");
11284
11329
  if (/sensitive.?content|human.?face/i.test(`${code ?? ""} ${text2}`)) {
11285
- const init = {
11330
+ const init2 = {
11286
11331
  code: "content_blocked",
11287
11332
  message: `ark rejected the request: ${text2.slice(0, 500)}`,
11288
11333
  provider: "ark",
@@ -11290,12 +11335,12 @@ function throwArkError(status, body, model, code = arkErrorCode(body)) {
11290
11335
  body,
11291
11336
  retryable: false
11292
11337
  };
11293
- if (status !== void 0) init.status = status;
11294
- throw new ModelKitError(init);
11338
+ if (status !== void 0) init2.status = status;
11339
+ throw new ModelKitError(init2);
11295
11340
  }
11296
11341
  const rule = arkCodeRule(status, code);
11297
11342
  if (rule || status === void 0) {
11298
- const init = {
11343
+ const init2 = {
11299
11344
  code: rule?.code ?? "provider_rejected",
11300
11345
  message: `ark rejected the request${code ? ` (${code})` : ""}: ${text2.slice(0, 500)}`,
11301
11346
  provider: "ark",
@@ -11303,8 +11348,8 @@ function throwArkError(status, body, model, code = arkErrorCode(body)) {
11303
11348
  body,
11304
11349
  retryable: false
11305
11350
  };
11306
- if (status !== void 0) init.status = status;
11307
- throw new ModelKitError(init);
11351
+ if (status !== void 0) init2.status = status;
11352
+ throw new ModelKitError(init2);
11308
11353
  }
11309
11354
  throw classifyHttpError(status, body, "ark", model);
11310
11355
  }
@@ -11328,12 +11373,12 @@ var SeedreamResponseSchema = import_zod10.z.object({
11328
11373
  data: import_zod10.z.array(SeedreamImageSchema).optional(),
11329
11374
  error: import_zod10.z.object({ message: import_zod10.z.string().optional(), code: import_zod10.z.string().optional() }).optional()
11330
11375
  });
11331
- function fetchInitFor(ctx, init) {
11332
- if (ctx.signal !== void 0) init.signal = ctx.signal;
11333
- return init;
11376
+ function fetchInitFor(ctx, init2) {
11377
+ if (ctx.signal !== void 0) init2.signal = ctx.signal;
11378
+ return init2;
11334
11379
  }
11335
- function arkFetch(ctx, url, init) {
11336
- return ctx.fetch(url, fetchInitFor(ctx, init)).catch((cause) => {
11380
+ function arkFetch(ctx, url, init2) {
11381
+ return ctx.fetch(url, fetchInitFor(ctx, init2)).catch((cause) => {
11337
11382
  throw classifyThrown("ark", cause, ctx.model.id);
11338
11383
  });
11339
11384
  }
@@ -11410,16 +11455,16 @@ async function generateSeedreamImage(req, ctx) {
11410
11455
  } else {
11411
11456
  throwArkError(void 0, "Seedream returned no image URL or base64 data", modelId);
11412
11457
  }
11413
- const usage6 = {
11458
+ const usage7 = {
11414
11459
  model: modelId,
11415
11460
  provider: "ark",
11416
11461
  modality: "IMAGE",
11417
11462
  unit: "images",
11418
11463
  quantity: 1
11419
11464
  };
11420
- if (req.size !== void 0) usage6.imageSize = req.size;
11421
- if (req.quality !== void 0) usage6.imageQuality = req.quality;
11422
- return { images: [{ bytes, mime: sniffedImageMime(bytes) }], usage: usage6, raw: data };
11465
+ if (req.size !== void 0) usage7.imageSize = req.size;
11466
+ if (req.quality !== void 0) usage7.imageQuality = req.quality;
11467
+ return { images: [{ bytes, mime: sniffedImageMime(bytes) }], usage: usage7, raw: data };
11423
11468
  }
11424
11469
  var SeedanceUsageSchema = import_zod10.z.object({
11425
11470
  total_tokens: import_zod10.z.number().optional(),
@@ -11474,7 +11519,7 @@ function seedanceErrorCode(error) {
11474
11519
  const parsed = SeedanceErrorSchema.safeParse(error);
11475
11520
  return parsed.success ? parsed.data.code : void 0;
11476
11521
  }
11477
- function seedanceJob(ctx, key, jobId, usage6) {
11522
+ function seedanceJob(ctx, key, jobId, usage7) {
11478
11523
  const modelId = ctx.model.id;
11479
11524
  const fetchStatus = async () => {
11480
11525
  const res = await arkFetch(ctx, `${arkBaseUrl(ctx)}${SUBMIT_PATH2}/${jobId}`, {
@@ -11524,21 +11569,21 @@ function seedanceJob(ctx, key, jobId, usage6) {
11524
11569
  modelId
11525
11570
  );
11526
11571
  if (polled.duration !== void 0 && polled.duration > 0) {
11527
- usage6.quantity = polled.duration;
11528
- usage6.durationSeconds = polled.duration;
11572
+ usage7.quantity = polled.duration;
11573
+ usage7.durationSeconds = polled.duration;
11529
11574
  }
11530
11575
  const rendered = VideoResolutionSchema.safeParse(
11531
11576
  polled.resolution?.toLowerCase()
11532
11577
  );
11533
- if (rendered.success) usage6.resolution = rendered.data;
11578
+ if (rendered.success) usage7.resolution = rendered.data;
11534
11579
  const tokens = polled.usage;
11535
11580
  if (tokens?.total_tokens !== void 0 && tokens.completion_tokens !== void 0) {
11536
- usage6.inputTokens = tokens.total_tokens - tokens.completion_tokens;
11537
- usage6.outputTokens = tokens.completion_tokens;
11581
+ usage7.inputTokens = tokens.total_tokens - tokens.completion_tokens;
11582
+ usage7.outputTokens = tokens.completion_tokens;
11538
11583
  }
11539
11584
  return {
11540
11585
  video: { url, expiresAt: new Date(Date.now() + VIDEO_URL_TTL_MS2) },
11541
- usage: usage6,
11586
+ usage: usage7,
11542
11587
  raw: polled
11543
11588
  };
11544
11589
  }
@@ -11691,8 +11736,8 @@ async function generateSeedanceVideo(req, ctx) {
11691
11736
  if (req.watermark !== void 0) body.watermark = req.watermark;
11692
11737
  if (ctx.model.constraints.draft) body.draft = true;
11693
11738
  const jobId = await submitSeedanceTask(ctx, key, body);
11694
- const usage6 = seedanceUsage(ctx, req, taskType === "edit" ? requestedDuration : duration);
11695
- return seedanceJob(ctx, key, jobId, usage6);
11739
+ const usage7 = seedanceUsage(ctx, req, taskType === "edit" ? requestedDuration : duration);
11740
+ return seedanceJob(ctx, key, jobId, usage7);
11696
11741
  }
11697
11742
 
11698
11743
  // src/adapters/fal.ts
@@ -11836,15 +11881,15 @@ function gatewayConfig(ctx) {
11836
11881
  if (ctx.signal !== void 0) config.signal = ctx.signal;
11837
11882
  return config;
11838
11883
  }
11839
- async function gatewayFetch(cfg, fetchImpl, targetUrl, init) {
11884
+ async function gatewayFetch(cfg, fetchImpl, targetUrl, init2) {
11840
11885
  const headers2 = { "x-fal-target-url": targetUrl };
11841
11886
  if (cfg.falKey) headers2.Authorization = `Bearer ${cfg.falKey}`;
11842
- if (init.body) headers2["Content-Type"] = "application/json";
11887
+ if (init2.body) headers2["Content-Type"] = "application/json";
11843
11888
  if (cfg.cfToken) headers2["cf-aig-authorization"] = `Bearer ${cfg.cfToken}`;
11844
11889
  if (cfg.singleAttempt) headers2["cf-aig-max-attempts"] = "1";
11845
- const request = { method: init.method, headers: headers2 };
11890
+ const request = { method: init2.method, headers: headers2 };
11846
11891
  if (cfg.signal !== void 0) request.signal = cfg.signal;
11847
- if (init.body !== void 0) request.body = init.body;
11892
+ if (init2.body !== void 0) request.body = init2.body;
11848
11893
  return fetchImpl(cfg.baseUrl, request);
11849
11894
  }
11850
11895
 
@@ -12835,7 +12880,7 @@ async function collectFalPlanImages(payload, plan5, ctx, req) {
12835
12880
  return { bytes, mime: mime || "image/png" };
12836
12881
  })
12837
12882
  );
12838
- const usage6 = {
12883
+ const usage7 = {
12839
12884
  model: ctx.model.id,
12840
12885
  provider: "fal",
12841
12886
  modality: "IMAGE",
@@ -12843,9 +12888,9 @@ async function collectFalPlanImages(payload, plan5, ctx, req) {
12843
12888
  quantity: images.length
12844
12889
  };
12845
12890
  const billedSize = plan5.imageSize ?? req.size;
12846
- if (billedSize !== void 0 && ctx.model.type === "image") usage6.imageSize = billedSize;
12847
- if (plan5.imageQuality !== void 0) usage6.imageQuality = plan5.imageQuality;
12848
- const result = { images, usage: usage6, raw: payload };
12891
+ if (billedSize !== void 0 && ctx.model.type === "image") usage7.imageSize = billedSize;
12892
+ if (plan5.imageQuality !== void 0) usage7.imageQuality = plan5.imageQuality;
12893
+ const result = { images, usage: usage7, raw: payload };
12849
12894
  const remote = files.find((f) => !f.url.startsWith("data:"));
12850
12895
  if (remote !== void 0) result.outputUrl = remote.url;
12851
12896
  return result;
@@ -14586,14 +14631,14 @@ async function collectFalImages(payload, ctx, req, label) {
14586
14631
  retryable: false
14587
14632
  });
14588
14633
  }
14589
- const usage6 = imageUsage(ctx, req, delivered.length);
14634
+ const usage7 = imageUsage(ctx, req, delivered.length);
14590
14635
  if (isIdeogram46(ctx.model.providerModelId)) {
14591
14636
  const billed = ideogramBilledSize(delivered, req.size);
14592
- if (billed !== void 0) usage6.imageSize = billed;
14637
+ if (billed !== void 0) usage7.imageSize = billed;
14593
14638
  }
14594
14639
  return {
14595
14640
  images: delivered.map(({ bytes, mime }) => ({ bytes, mime })),
14596
- usage: usage6,
14641
+ usage: usage7,
14597
14642
  raw: payload
14598
14643
  };
14599
14644
  }
@@ -14928,13 +14973,13 @@ function classifyResponse(ctx, status, body) {
14928
14973
  }
14929
14974
  return error;
14930
14975
  }
14931
- async function elevenLabsFetch(ctx, path, init) {
14976
+ async function elevenLabsFetch(ctx, path, init2) {
14932
14977
  throwIfAborted(ctx.signal);
14933
14978
  const request = {
14934
- method: init.method,
14935
- headers: { "xi-api-key": elevenLabsKey(ctx), ...init.headers }
14979
+ method: init2.method,
14980
+ headers: { "xi-api-key": elevenLabsKey(ctx), ...init2.headers }
14936
14981
  };
14937
- if (init.body !== void 0) request.body = init.body;
14982
+ if (init2.body !== void 0) request.body = init2.body;
14938
14983
  if (ctx.signal !== void 0) request.signal = ctx.signal;
14939
14984
  let res;
14940
14985
  try {
@@ -15224,13 +15269,13 @@ function fishKey(ctx) {
15224
15269
  function fishUrl(ctx, path) {
15225
15270
  return `${ctx.endpoints?.fish ?? DEFAULT_BASE_URL2}${path}`;
15226
15271
  }
15227
- async function fishFetch(ctx, path, init) {
15272
+ async function fishFetch(ctx, path, init2) {
15228
15273
  throwIfAborted(ctx.signal);
15229
15274
  const request = {
15230
- method: init.method,
15231
- headers: { Authorization: `Bearer ${fishKey(ctx)}`, ...init.headers }
15275
+ method: init2.method,
15276
+ headers: { Authorization: `Bearer ${fishKey(ctx)}`, ...init2.headers }
15232
15277
  };
15233
- if (init.body !== void 0) request.body = init.body;
15278
+ if (init2.body !== void 0) request.body = init2.body;
15234
15279
  if (ctx.signal !== void 0) request.signal = ctx.signal;
15235
15280
  let res;
15236
15281
  try {
@@ -15481,13 +15526,13 @@ function googleKey(ctx) {
15481
15526
  if (!key) throw refuse(ctx, "auth", "Missing Google API key");
15482
15527
  return key;
15483
15528
  }
15484
- async function googleFetch(ctx, path, init) {
15529
+ async function googleFetch(ctx, path, init2) {
15485
15530
  throwIfAborted(ctx.signal);
15486
15531
  const request = {
15487
- method: init.method,
15532
+ method: init2.method,
15488
15533
  headers: { "x-goog-api-key": googleKey(ctx), "Content-Type": "application/json" }
15489
15534
  };
15490
- if (init.body !== void 0) request.body = JSON.stringify(init.body);
15535
+ if (init2.body !== void 0) request.body = JSON.stringify(init2.body);
15491
15536
  if (ctx.signal !== void 0) request.signal = ctx.signal;
15492
15537
  let res;
15493
15538
  try {
@@ -15707,20 +15752,20 @@ function fileNameFromUri(fileUri, model) {
15707
15752
  return name;
15708
15753
  }
15709
15754
  function oversizeError(bytes, label, model) {
15710
- const init = {
15755
+ const init2 = {
15711
15756
  code: "unsupported_option",
15712
15757
  message: `${label}: source is ${bytes} bytes, over the Files API limit of ${GOOGLE_FILES_MAX_BYTES}`,
15713
15758
  provider: "google-genai",
15714
15759
  retryable: false
15715
15760
  };
15716
- if (model !== void 0) init.model = model;
15717
- return new ModelKitError(init);
15761
+ if (model !== void 0) init2.model = model;
15762
+ return new ModelKitError(init2);
15718
15763
  }
15719
15764
  async function resolveSource(source2, fetchImpl, signal, label, model) {
15720
15765
  if ("bytes" in source2) return { bytes: source2.bytes, mimeType: source2.mime };
15721
- const init = {};
15722
- if (signal !== void 0) init.signal = signal;
15723
- const res = await fetchImpl(source2.url, init);
15766
+ const init2 = {};
15767
+ if (signal !== void 0) init2.signal = signal;
15768
+ const res = await fetchImpl(source2.url, init2);
15724
15769
  if (!res.ok) {
15725
15770
  const text2 = await res.text().catch(() => "");
15726
15771
  throw classifyHttpError(res.status, text2, "google-genai", model);
@@ -15826,11 +15871,11 @@ async function waitForActive(fileName3, opts) {
15826
15871
  throw classifyHttpError(res.status, text2, "google-genai", opts.model);
15827
15872
  }, pollOptions2);
15828
15873
  }
15829
- async function deleteGoogleFile(fileName3, apiKey, fetchImpl) {
15874
+ async function deleteGoogleFile(fileName3, apiKey2, fetchImpl) {
15830
15875
  try {
15831
15876
  await fetchImpl(`${GOOGLE_FILES_BASE}/v1beta/${fileName3}`, {
15832
15877
  method: "DELETE",
15833
- headers: { "x-goog-api-key": apiKey }
15878
+ headers: { "x-goog-api-key": apiKey2 }
15834
15879
  });
15835
15880
  } catch {
15836
15881
  }
@@ -15979,9 +16024,9 @@ function toBase64(bytes) {
15979
16024
  }
15980
16025
  async function resolveMedia(ref, fetchImpl, signal, defaultMime, model) {
15981
16026
  if ("bytes" in ref) return { bytes: ref.bytes, mime: ref.mime };
15982
- const init = {};
15983
- if (signal !== void 0) init.signal = signal;
15984
- const res = await fetchImpl(ref.url, init);
16027
+ const init2 = {};
16028
+ if (signal !== void 0) init2.signal = signal;
16029
+ const res = await fetchImpl(ref.url, init2);
15985
16030
  if (!res.ok) {
15986
16031
  const text2 = await res.text().catch(() => "");
15987
16032
  throw classifyHttpError(res.status, text2, "google-genai", model);
@@ -15991,10 +16036,10 @@ async function resolveMedia(ref, fetchImpl, signal, defaultMime, model) {
15991
16036
  mime: res.headers.get("content-type")?.split(";")[0]?.trim() || defaultMime
15992
16037
  };
15993
16038
  }
15994
- async function downloadVideo(ctx, url, apiKey, signal) {
15995
- const init = { headers: { "x-goog-api-key": apiKey } };
15996
- if (signal !== void 0) init.signal = signal;
15997
- const res = await ctx.fetch(url, init);
16039
+ async function downloadVideo(ctx, url, apiKey2, signal) {
16040
+ const init2 = { headers: { "x-goog-api-key": apiKey2 } };
16041
+ if (signal !== void 0) init2.signal = signal;
16042
+ const res = await ctx.fetch(url, init2);
15998
16043
  if (!res.ok) {
15999
16044
  const text2 = await res.text().catch(() => "");
16000
16045
  throw classifyHttpError(res.status, text2, "google-genai", ctx.model.id);
@@ -16017,7 +16062,7 @@ function videoUsage2(ctx, duration, resolution) {
16017
16062
  return event;
16018
16063
  }
16019
16064
  async function generateVeoVideo(req, ctx, createGenAIClient) {
16020
- const apiKey = googleKey2(ctx);
16065
+ const apiKey2 = googleKey2(ctx);
16021
16066
  const modelId = ctx.model.id;
16022
16067
  const refs = req.referenceImages ?? [];
16023
16068
  if (req.firstFrame && refs.length > 0) {
@@ -16070,7 +16115,7 @@ async function generateVeoVideo(req, ctx, createGenAIClient) {
16070
16115
  }));
16071
16116
  }
16072
16117
  const client2 = createGenAIClient({
16073
- apiKey,
16118
+ apiKey: apiKey2,
16074
16119
  ...ctx.call.maxRetries !== void 0 ? { maxRetries: ctx.call.maxRetries } : {},
16075
16120
  ...ctx.signal !== void 0 ? { signal: ctx.signal } : {}
16076
16121
  });
@@ -16107,7 +16152,7 @@ async function generateVeoVideo(req, ctx, createGenAIClient) {
16107
16152
  }
16108
16153
  };
16109
16154
  const jobId = operation.name ?? crypto.randomUUID();
16110
- const usage6 = videoUsage2(ctx, duration, req.resolution ?? "720p");
16155
+ const usage7 = videoUsage2(ctx, duration, req.resolution ?? "720p");
16111
16156
  return {
16112
16157
  jobId,
16113
16158
  async poll() {
@@ -16145,7 +16190,7 @@ async function generateVeoVideo(req, ctx, createGenAIClient) {
16145
16190
  modelId
16146
16191
  );
16147
16192
  }
16148
- return { video: await downloadVideo(ctx, uri, apiKey, signal), usage: usage6, raw: finished };
16193
+ return { video: await downloadVideo(ctx, uri, apiKey2, signal), usage: usage7, raw: finished };
16149
16194
  }
16150
16195
  };
16151
16196
  }
@@ -16182,7 +16227,7 @@ function extractOmniVideo(interaction, model) {
16182
16227
  );
16183
16228
  }
16184
16229
  async function generateOmniVideo(req, ctx, createGenAIClient) {
16185
- const apiKey = googleKey2(ctx);
16230
+ const apiKey2 = googleKey2(ctx);
16186
16231
  const modelId = ctx.model.id;
16187
16232
  const providerModelId = ctx.model.providerModelId;
16188
16233
  const extend = req.taskType === "extend";
@@ -16242,7 +16287,7 @@ async function generateOmniVideo(req, ctx, createGenAIClient) {
16242
16287
  if (omniResolution !== void 0) responseFormat.resolution = omniResolution;
16243
16288
  if (req.durationSeconds !== void 0) responseFormat.duration = `${req.durationSeconds}s`;
16244
16289
  const client2 = createGenAIClient({
16245
- apiKey,
16290
+ apiKey: apiKey2,
16246
16291
  ...ctx.call.maxRetries !== void 0 ? { maxRetries: ctx.call.maxRetries } : {},
16247
16292
  ...ctx.signal !== void 0 ? { signal: ctx.signal } : {}
16248
16293
  });
@@ -16250,7 +16295,7 @@ async function generateOmniVideo(req, ctx, createGenAIClient) {
16250
16295
  const uploadedNames = [];
16251
16296
  const uploadOne = async (kind, bytes, mime) => {
16252
16297
  const uploadOptions = {
16253
- apiKey,
16298
+ apiKey: apiKey2,
16254
16299
  fetchImpl: ctx.fetch,
16255
16300
  model: modelId,
16256
16301
  label: "gemini-omni"
@@ -16263,7 +16308,7 @@ async function generateOmniVideo(req, ctx, createGenAIClient) {
16263
16308
  return file.fileUri;
16264
16309
  };
16265
16310
  const cleanupUploads = async () => {
16266
- for (const fileName3 of uploadedNames) await deleteGoogleFile(fileName3, apiKey, ctx.fetch);
16311
+ for (const fileName3 of uploadedNames) await deleteGoogleFile(fileName3, apiKey2, ctx.fetch);
16267
16312
  };
16268
16313
  const callCreate = (input) => client2.interactions.create(
16269
16314
  previousId !== void 0 ? {
@@ -16357,7 +16402,7 @@ async function generateOmniVideo(req, ctx, createGenAIClient) {
16357
16402
  if (!(extend && !chained)) await cleanupUploads();
16358
16403
  }
16359
16404
  const jobId = interaction.id ?? crypto.randomUUID();
16360
- const usage6 = videoUsage2(ctx, duration, omniResolution ?? "720p");
16405
+ const usage7 = videoUsage2(ctx, duration, omniResolution ?? "720p");
16361
16406
  const getInteraction = async () => {
16362
16407
  try {
16363
16408
  const getParams = { stream: false };
@@ -16405,15 +16450,15 @@ async function generateOmniVideo(req, ctx, createGenAIClient) {
16405
16450
  bytes: Buffer.from(video.data, "base64"),
16406
16451
  mime: video.mime_type ?? "video/mp4"
16407
16452
  },
16408
- usage: usage6,
16453
+ usage: usage7,
16409
16454
  raw: done,
16410
16455
  providerRef
16411
16456
  };
16412
16457
  }
16413
16458
  if (video.uri)
16414
16459
  return {
16415
- video: await downloadVideo(ctx, video.uri, apiKey, signal),
16416
- usage: usage6,
16460
+ video: await downloadVideo(ctx, video.uri, apiKey2, signal),
16461
+ usage: usage7,
16417
16462
  raw: done,
16418
16463
  providerRef
16419
16464
  };
@@ -16440,7 +16485,7 @@ function lyriaUsage(ctx, req, meta) {
16440
16485
  return event;
16441
16486
  }
16442
16487
  async function generateLyriaAudio(req, ctx, createGenAIClient) {
16443
- const apiKey = googleKey2(ctx);
16488
+ const apiKey2 = googleKey2(ctx);
16444
16489
  const modelId = ctx.model.id;
16445
16490
  const parts = [{ text: req.prompt }];
16446
16491
  for (const ref of req.references ?? []) {
@@ -16448,7 +16493,7 @@ async function generateLyriaAudio(req, ctx, createGenAIClient) {
16448
16493
  parts.push({ inlineData: { mimeType: image.mime, data: toBase64(image.bytes) } });
16449
16494
  }
16450
16495
  const client2 = createGenAIClient({
16451
- apiKey,
16496
+ apiKey: apiKey2,
16452
16497
  ...ctx.call.maxRetries !== void 0 ? { maxRetries: ctx.call.maxRetries } : {},
16453
16498
  ...ctx.signal !== void 0 ? { signal: ctx.signal } : {}
16454
16499
  });
@@ -16502,14 +16547,14 @@ async function generateLyriaAudio(req, ctx, createGenAIClient) {
16502
16547
  return result;
16503
16548
  }
16504
16549
  async function generateLyriaInteraction(req, ctx, createGenAIClient) {
16505
- const apiKey = googleKey2(ctx);
16550
+ const apiKey2 = googleKey2(ctx);
16506
16551
  const modelId = ctx.model.id;
16507
16552
  const input = [{ type: "text", text: req.prompt }];
16508
16553
  for (const ref of req.references ?? []) {
16509
16554
  const image = await resolveMedia(ref, ctx.fetch, ctx.signal, "image/jpeg", modelId);
16510
16555
  input.push({ type: "image", mime_type: image.mime, data: toBase64(image.bytes) });
16511
16556
  }
16512
- const clientOptions = { apiKey };
16557
+ const clientOptions = { apiKey: apiKey2 };
16513
16558
  if (ctx.call.maxRetries !== void 0) clientOptions.maxRetries = ctx.call.maxRetries;
16514
16559
  if (ctx.signal !== void 0) clientOptions.signal = ctx.signal;
16515
16560
  const client2 = createGenAIClient(clientOptions);
@@ -16562,9 +16607,9 @@ async function prepareGoogleMediaPart(ref, mediaType, ctx) {
16562
16607
  if (ref.bytes.length <= MEDIA_PART_INLINE_LIMIT_BYTES) {
16563
16608
  return { type: "file", data: ref.bytes, mediaType };
16564
16609
  }
16565
- const apiKey = googleKey2(ctx);
16610
+ const apiKey2 = googleKey2(ctx);
16566
16611
  const uploadOptions = {
16567
- apiKey,
16612
+ apiKey: apiKey2,
16568
16613
  fetchImpl: ctx.fetch,
16569
16614
  model: ctx.model.id,
16570
16615
  label: "media-part"
@@ -16576,7 +16621,7 @@ async function prepareGoogleMediaPart(ref, mediaType, ctx) {
16576
16621
  type: "file",
16577
16622
  data: file.fileUri,
16578
16623
  mediaType: file.mimeType,
16579
- cleanup: () => deleteGoogleFile(file.fileName, apiKey, ctx.fetch)
16624
+ cleanup: () => deleteGoogleFile(file.fileName, apiKey2, ctx.fetch)
16580
16625
  };
16581
16626
  }
16582
16627
 
@@ -16611,9 +16656,9 @@ function extractBlockReason(cause) {
16611
16656
  current = parsed.data.cause ?? null;
16612
16657
  }
16613
16658
  }
16614
- function billedTokens(model, usage6) {
16615
- const inputTokens = usage6?.inputTokens;
16616
- const outputTokens = usage6?.outputTokens;
16659
+ function billedTokens(model, usage7) {
16660
+ const inputTokens = usage7?.inputTokens;
16661
+ const outputTokens = usage7?.outputTokens;
16617
16662
  if (inputTokens === void 0 && outputTokens === void 0) return void 0;
16618
16663
  const event = {
16619
16664
  model,
@@ -16647,8 +16692,8 @@ function createGoogleImageAdapter(deps = defaultGoogleImageDeps) {
16647
16692
  return {
16648
16693
  id: "google-image",
16649
16694
  async generateImage(req, ctx) {
16650
- const apiKey = ctx.keys.google;
16651
- if (!apiKey)
16695
+ const apiKey2 = ctx.keys.google;
16696
+ if (!apiKey2)
16652
16697
  throw new ModelKitError({
16653
16698
  code: "auth",
16654
16699
  message: "Missing API key for google",
@@ -16656,7 +16701,7 @@ function createGoogleImageAdapter(deps = defaultGoogleImageDeps) {
16656
16701
  model: ctx.model.id,
16657
16702
  retryable: false
16658
16703
  });
16659
- const google = deps.createGoogleClient({ apiKey, fetch: ctx.fetch });
16704
+ const google = deps.createGoogleClient({ apiKey: apiKey2, fetch: ctx.fetch });
16660
16705
  const model = google(ctx.model.providerModelId);
16661
16706
  const content = [];
16662
16707
  for (const ref of req.references ?? []) {
@@ -16697,7 +16742,7 @@ function createGoogleImageAdapter(deps = defaultGoogleImageDeps) {
16697
16742
  const images = (result.files ?? []).filter((file) => file.mediaType.startsWith("image/")).map((file) => ({ bytes: file.uint8Array, mime: file.mediaType }));
16698
16743
  if (images.length === 0) {
16699
16744
  const filtered = result.finishReason === "content-filter" || result.finishReason === "other";
16700
- const init = {
16745
+ const init2 = {
16701
16746
  code: filtered ? "content_blocked" : "provider_rejected",
16702
16747
  message: `google-image returned no image (finishReason: ${result.finishReason}). ${result.text}`.trim(),
16703
16748
  provider: "google-image",
@@ -16709,12 +16754,12 @@ function createGoogleImageAdapter(deps = defaultGoogleImageDeps) {
16709
16754
  },
16710
16755
  retryable: false
16711
16756
  };
16712
- if (result.finishReason !== void 0) init.finishReason = result.finishReason;
16757
+ if (result.finishReason !== void 0) init2.finishReason = result.finishReason;
16713
16758
  const billed = billedTokens(ctx.model.id, result.usage);
16714
- if (billed !== void 0) init.usage = billed;
16715
- throw new ModelKitError(init);
16759
+ if (billed !== void 0) init2.usage = billed;
16760
+ throw new ModelKitError(init2);
16716
16761
  }
16717
- const usage6 = {
16762
+ const usage7 = {
16718
16763
  model: ctx.model.id,
16719
16764
  provider: "google-image",
16720
16765
  modality: "IMAGE",
@@ -16722,12 +16767,12 @@ function createGoogleImageAdapter(deps = defaultGoogleImageDeps) {
16722
16767
  quantity: images.length,
16723
16768
  imageQuality: "auto"
16724
16769
  };
16725
- if (req.size !== void 0) usage6.imageSize = req.size;
16770
+ if (req.size !== void 0) usage7.imageSize = req.size;
16726
16771
  if (result.usage?.inputTokens !== void 0)
16727
- usage6.inputTokens = result.usage.inputTokens;
16772
+ usage7.inputTokens = result.usage.inputTokens;
16728
16773
  if (result.usage?.outputTokens !== void 0)
16729
- usage6.outputTokens = result.usage.outputTokens;
16730
- return { images, usage: usage6, raw: result };
16774
+ usage7.outputTokens = result.usage.outputTokens;
16775
+ return { images, usage: usage7, raw: result };
16731
16776
  }
16732
16777
  };
16733
16778
  }
@@ -16969,16 +17014,16 @@ function klingErrorDetail(error) {
16969
17014
  if (asObject.success) return asObject.data.message ?? "unknown_error";
16970
17015
  return "unknown_error";
16971
17016
  }
16972
- function requestInit(ctx, init) {
16973
- const request = { method: init.method, headers: headers(ctx) };
16974
- if (init.body !== void 0) request.body = init.body;
17017
+ function requestInit(ctx, init2) {
17018
+ const request = { method: init2.method, headers: headers(ctx) };
17019
+ if (init2.body !== void 0) request.body = init2.body;
16975
17020
  if (ctx.signal !== void 0) request.signal = ctx.signal;
16976
17021
  return request;
16977
17022
  }
16978
- async function createRequest(ctx, url, init) {
17023
+ async function createRequest(ctx, url, init2) {
16979
17024
  let res;
16980
17025
  try {
16981
- res = await ctx.fetch(url, requestInit(ctx, init));
17026
+ res = await ctx.fetch(url, requestInit(ctx, init2));
16982
17027
  } catch (cause) {
16983
17028
  throw classifyThrown("higgsfield", cause, ctx.model.id);
16984
17029
  }
@@ -17574,13 +17619,13 @@ function lumaFailure(ctx, code, reason) {
17574
17619
  }
17575
17620
  }
17576
17621
  function requestInit2(ctx, key, body) {
17577
- const init = {
17622
+ const init2 = {
17578
17623
  method: body !== void 0 ? "POST" : "GET",
17579
17624
  headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" }
17580
17625
  };
17581
- if (body !== void 0) init.body = body;
17582
- if (ctx.signal !== void 0) init.signal = ctx.signal;
17583
- return init;
17626
+ if (body !== void 0) init2.body = body;
17627
+ if (ctx.signal !== void 0) init2.signal = ctx.signal;
17628
+ return init2;
17584
17629
  }
17585
17630
  async function lumaRequest(ctx, url, body) {
17586
17631
  const key = lumaKey(ctx);
@@ -18069,8 +18114,8 @@ var openaiImageAdapter = {
18069
18114
  id: "openai-image",
18070
18115
  async generateImage(req, ctx) {
18071
18116
  throwIfAborted(ctx.signal);
18072
- const apiKey = ctx.keys.openai;
18073
- if (!apiKey)
18117
+ const apiKey2 = ctx.keys.openai;
18118
+ if (!apiKey2)
18074
18119
  throw new ModelKitError({
18075
18120
  code: "auth",
18076
18121
  message: "Missing API key for openai",
@@ -18085,7 +18130,7 @@ var openaiImageAdapter = {
18085
18130
  message: "openai-image cannot express reference labels; ignoring them"
18086
18131
  });
18087
18132
  }
18088
- const client2 = new import_openai2.default({ apiKey, fetch: ctx.fetch, maxRetries: 0 });
18133
+ const client2 = new import_openai2.default({ apiKey: apiKey2, fetch: ctx.fetch, maxRetries: 0 });
18089
18134
  const size = req.exactSize !== void 0 ? req.exactSize : req.aspectRatio === void 0 || req.aspectRatio === "adaptive" ? void 0 : aspectRatioToSize(req.aspectRatio, req.size ?? "1K");
18090
18135
  const refs = req.references ?? [];
18091
18136
  const isEdit = refs.length > 0;
@@ -18175,7 +18220,7 @@ var openaiImageAdapter = {
18175
18220
  const usageParsed = openaiUsageSchema.safeParse(response.usage);
18176
18221
  const inputTokens = usageParsed.success ? usageParsed.data.input_tokens : void 0;
18177
18222
  const outputTokens = usageParsed.success ? usageParsed.data.output_tokens : void 0;
18178
- const usage6 = {
18223
+ const usage7 = {
18179
18224
  model: ctx.model.id,
18180
18225
  provider: "openai-image",
18181
18226
  modality: "IMAGE",
@@ -18183,10 +18228,10 @@ var openaiImageAdapter = {
18183
18228
  quantity: images.length,
18184
18229
  imageQuality: quality
18185
18230
  };
18186
- if (inputTokens !== void 0) usage6.inputTokens = inputTokens;
18187
- if (outputTokens !== void 0) usage6.outputTokens = outputTokens;
18188
- if (req.size !== void 0) usage6.imageSize = req.size;
18189
- return { images, usage: usage6, raw: response };
18231
+ if (inputTokens !== void 0) usage7.inputTokens = inputTokens;
18232
+ if (outputTokens !== void 0) usage7.outputTokens = outputTokens;
18233
+ if (req.size !== void 0) usage7.imageSize = req.size;
18234
+ return { images, usage: usage7, raw: response };
18190
18235
  }
18191
18236
  };
18192
18237
 
@@ -18419,13 +18464,13 @@ async function generateProdiaImage(req, ctx) {
18419
18464
  res = await withRetry(async () => {
18420
18465
  let attemptRes;
18421
18466
  try {
18422
- const init = {
18467
+ const init2 = {
18423
18468
  method: "POST",
18424
18469
  headers: { Authorization: `Bearer ${key}`, Accept: accept },
18425
18470
  body: form
18426
18471
  };
18427
- if (ctx.signal !== void 0) init.signal = ctx.signal;
18428
- attemptRes = await ctx.fetch(PRODIA_JOB_URL, init);
18472
+ if (ctx.signal !== void 0) init2.signal = ctx.signal;
18473
+ attemptRes = await ctx.fetch(PRODIA_JOB_URL, init2);
18429
18474
  } catch (err) {
18430
18475
  throw classifyThrown("prodia", err, ctx.model.id);
18431
18476
  }
@@ -18442,16 +18487,16 @@ async function generateProdiaImage(req, ctx) {
18442
18487
  new Uint8Array(await res.arrayBuffer()),
18443
18488
  res.headers.get("content-type")
18444
18489
  );
18445
- const usage6 = {
18490
+ const usage7 = {
18446
18491
  model: ctx.model.id,
18447
18492
  provider: "prodia",
18448
18493
  modality: "IMAGE",
18449
18494
  unit: "images",
18450
18495
  quantity: 1
18451
18496
  };
18452
- if (req.size !== void 0) usage6.imageSize = req.size;
18453
- if (req.quality !== void 0) usage6.imageQuality = req.quality;
18454
- return { images: [{ bytes, mime }], usage: usage6, raw: void 0 };
18497
+ if (req.size !== void 0) usage7.imageSize = req.size;
18498
+ if (req.quality !== void 0) usage7.imageQuality = req.quality;
18499
+ return { images: [{ bytes, mime }], usage: usage7, raw: void 0 };
18455
18500
  }
18456
18501
  var prodiaAdapter = {
18457
18502
  id: "prodia",
@@ -18907,9 +18952,9 @@ async function generateReplicateImage(req, ctx, deps) {
18907
18952
  }
18908
18953
  const { url, predictTime, raw } = await runPrediction(ctx, input, deps);
18909
18954
  const file = await download(ctx, url);
18910
- const usage6 = imageUsage3(ctx, req);
18911
- usage6.quantity = predictTime;
18912
- return { images: [{ bytes: file.bytes, mime: file.mime }], usage: usage6, raw, outputUrl: url };
18955
+ const usage7 = imageUsage3(ctx, req);
18956
+ usage7.quantity = predictTime;
18957
+ return { images: [{ bytes: file.bytes, mime: file.mime }], usage: usage7, raw, outputUrl: url };
18913
18958
  }
18914
18959
  function klingInput(req) {
18915
18960
  const images = (req.firstFrame ? [req.firstFrame] : []).map(refToUrl);
@@ -19033,9 +19078,9 @@ async function generateReplicateVideo(req, ctx, deps) {
19033
19078
  return void 0;
19034
19079
  };
19035
19080
  const toResult = (done) => {
19036
- const usage6 = videoUsage5(ctx, req);
19037
- usage6.quantity = done.predictTime;
19038
- return { video: { url: done.url }, usage: usage6, raw: done.raw };
19081
+ const usage7 = videoUsage5(ctx, req);
19082
+ usage7.quantity = done.predictTime;
19083
+ return { video: { url: done.url }, usage: usage7, raw: done.raw };
19039
19084
  };
19040
19085
  return {
19041
19086
  jobId,
@@ -19142,23 +19187,277 @@ async function generateReplicateAudio(req, ctx, deps) {
19142
19187
  input = specResult.input;
19143
19188
  }
19144
19189
  const { url, predictTime, raw } = await runPrediction(ctx, input, deps);
19145
- const usage6 = audioUsage(ctx, req);
19190
+ const usage7 = audioUsage(ctx, req);
19146
19191
  if (ctx.model.usage.unit === "seconds") {
19147
19192
  const seconds3 = elevenLabsMusicDuration(req.durationSeconds);
19148
- usage6.quantity = seconds3;
19149
- usage6.durationSeconds = seconds3;
19193
+ usage7.quantity = seconds3;
19194
+ usage7.durationSeconds = seconds3;
19150
19195
  } else {
19151
- usage6.quantity = predictTime;
19196
+ usage7.quantity = predictTime;
19197
+ }
19198
+ return { audio: { url }, usage: usage7, raw: predictionRaw(raw) };
19199
+ }
19200
+
19201
+ // src/adapters/wavespeed.ts
19202
+ var import_zod35 = require("zod");
19203
+ var BASE = "https://api.wavespeed.ai/api/v3";
19204
+ var POLL_INTERVAL_MS3 = 3e3;
19205
+ var POLL_BACKOFF = 1.2;
19206
+ var POLL_MAX_INTERVAL_MS = 15e3;
19207
+ var POLL_TIMEOUT_MS2 = 30 * 6e4;
19208
+ var FAILED_STATUSES = /* @__PURE__ */ new Set(["failed", "cancelled", "timeout", "deleted"]);
19209
+ var VIDEO_MODEL_IDS = /* @__PURE__ */ new Set(["sand-ai/magi-2"]);
19210
+ function wavespeedRowRefusal(row2) {
19211
+ if (row2.type !== "video") return `wavespeed has no ${row2.type} rows`;
19212
+ return VIDEO_MODEL_IDS.has(row2.providerModelId.toLowerCase()) ? void 0 : `wavespeed video rows need providerModelId ${[...VIDEO_MODEL_IDS].join(", ")}`;
19213
+ }
19214
+ function fail4(ctx, code, message) {
19215
+ return new ModelKitError({
19216
+ code,
19217
+ message,
19218
+ provider: "wavespeed",
19219
+ model: ctx.model.id,
19220
+ retryable: false
19221
+ });
19222
+ }
19223
+ function ignore(ctx, field, why) {
19224
+ ctx.warnings.push({
19225
+ code: "option_ignored",
19226
+ field,
19227
+ message: `${ctx.model.id}: ${why}; ${field} ignored`
19228
+ });
19229
+ }
19230
+ function urls2(refs) {
19231
+ return (refs ?? []).map(refToUrl);
19232
+ }
19233
+ function magiRequest(req, ctx) {
19234
+ const images = urls2(req.referenceImages);
19235
+ const videos = urls2(req.referenceVideos);
19236
+ const audios = urls2(req.referenceAudios);
19237
+ const hasReferences2 = images.length + videos.length + audios.length > 0;
19238
+ let mode = "text-to-video";
19239
+ const body = {};
19240
+ if (req.firstFrame) {
19241
+ mode = "image-to-video";
19242
+ body.image = refToUrl(req.firstFrame);
19243
+ if (req.lastFrame) body.last_image = refToUrl(req.lastFrame);
19244
+ if (hasReferences2) ignore(ctx, "references", "image-to-video takes no references");
19245
+ } else {
19246
+ if (req.lastFrame) ignore(ctx, "lastFrame", "an end frame needs a start frame");
19247
+ if (hasReferences2) {
19248
+ mode = "reference-to-video";
19249
+ if (images.length > 0) body.images = images;
19250
+ if (videos.length > 0) body.videos = videos;
19251
+ if (audios.length > 0) body.audios = audios;
19252
+ }
19253
+ }
19254
+ const prompt = req.prompt.trim();
19255
+ if (prompt !== "") body.prompt = prompt;
19256
+ else if (mode !== "image-to-video") {
19257
+ throw fail4(ctx, "missing_input", `${ctx.model.id} ${mode} requires a prompt`);
19258
+ }
19259
+ if (req.durationSeconds !== void 0) body.duration = req.durationSeconds;
19260
+ if (req.aspectRatio !== void 0 && req.aspectRatio !== "adaptive") {
19261
+ body.aspect_ratio = req.aspectRatio;
19262
+ }
19263
+ if (req.generateAudio !== void 0) body.generate_audio = req.generateAudio;
19264
+ if (req.seed !== void 0) body.seed = req.seed;
19265
+ return { path: `${ctx.model.providerModelId.toLowerCase()}/${mode}`, body };
19266
+ }
19267
+ function apiKey(ctx) {
19268
+ const key = ctx.keys.wavespeed;
19269
+ if (!key) throw fail4(ctx, "auth", "Missing API key for wavespeed");
19270
+ return key;
19271
+ }
19272
+ function init(ctx, method, body) {
19273
+ const request = {
19274
+ method,
19275
+ headers: { Authorization: `Bearer ${apiKey(ctx)}`, "Content-Type": "application/json" }
19276
+ };
19277
+ if (body !== void 0) request.body = body;
19278
+ if (ctx.signal !== void 0) request.signal = ctx.signal;
19279
+ return request;
19280
+ }
19281
+ var taskFields = import_zod35.z.object({
19282
+ id: import_zod35.z.string().optional(),
19283
+ status: import_zod35.z.string().optional(),
19284
+ outputs: import_zod35.z.array(import_zod35.z.unknown()).optional(),
19285
+ error: JsonValueSchema.optional()
19286
+ }).refine((task) => task.id !== void 0 || task.status !== void 0);
19287
+ var taskSchema = import_zod35.z.union([
19288
+ import_zod35.z.object({ data: taskFields }).transform((wrapped) => wrapped.data),
19289
+ taskFields
19290
+ ]);
19291
+ async function parseTask(res) {
19292
+ let raw;
19293
+ try {
19294
+ raw = await res.json();
19295
+ } catch {
19296
+ return "not_json";
19297
+ }
19298
+ const parsed = taskSchema.safeParse(raw);
19299
+ return parsed.success ? parsed.data : void 0;
19300
+ }
19301
+ function finalSubmitError(err) {
19302
+ if (err.code === "rate_limited" || !err.retryable) return err;
19303
+ const init2 = {
19304
+ code: err.code,
19305
+ message: `${err.message} (the task may exist; not retried)`,
19306
+ cause: err,
19307
+ retryable: false
19308
+ };
19309
+ if (err.provider !== void 0) init2.provider = err.provider;
19310
+ if (err.model !== void 0) init2.model = err.model;
19311
+ if (err.status !== void 0) init2.status = err.status;
19312
+ if (err.body !== void 0) init2.body = err.body;
19313
+ return new ModelKitError(init2);
19314
+ }
19315
+ function failedTask(ctx, status, error) {
19316
+ const text2 = import_zod35.z.string().safeParse(error);
19317
+ const detail = text2.success ? text2.data || "unknown_error" : error == null ? "unknown_error" : JSON.stringify(error);
19318
+ const classified = classifyHttpError(void 0, detail, "wavespeed", ctx.model.id);
19319
+ return new ModelKitError({
19320
+ code: classified.code === "content_blocked" ? "content_blocked" : "provider_rejected",
19321
+ message: `WaveSpeed generation ${status}: ${detail}`,
19322
+ provider: "wavespeed",
19323
+ model: ctx.model.id,
19324
+ retryable: false
19325
+ });
19326
+ }
19327
+ var TaskFailed = class extends Error {
19328
+ constructor(error) {
19329
+ super(error.message);
19330
+ this.error = error;
19152
19331
  }
19153
- return { audio: { url }, usage: usage6, raw: predictionRaw(raw) };
19332
+ error;
19333
+ };
19334
+ function usage5(ctx, req) {
19335
+ const event = {
19336
+ model: ctx.model.id,
19337
+ provider: "wavespeed",
19338
+ modality: "VIDEO",
19339
+ unit: "seconds",
19340
+ quantity: req.durationSeconds ?? 0
19341
+ };
19342
+ if (req.resolution !== void 0) event.resolution = req.resolution;
19343
+ if (req.durationSeconds !== void 0) event.durationSeconds = req.durationSeconds;
19344
+ return event;
19154
19345
  }
19346
+ function jobFor(req, ctx, taskId) {
19347
+ const resultUrl = `${BASE}/predictions/${encodeURIComponent(taskId)}/result`;
19348
+ const transient = ctx.call.maxRetries !== 0;
19349
+ const check = async (signal) => {
19350
+ const request = init(ctx, "GET");
19351
+ if (signal !== void 0) request.signal = signal;
19352
+ let res;
19353
+ try {
19354
+ res = await ctx.fetch(resultUrl, request);
19355
+ } catch (cause) {
19356
+ if (signal?.aborted || !transient) {
19357
+ throw classifyThrown("wavespeed", cause, ctx.model.id);
19358
+ }
19359
+ return void 0;
19360
+ }
19361
+ if (transient && (res.status === 429 || res.status >= 500)) {
19362
+ await res.body?.cancel().catch(() => void 0);
19363
+ return void 0;
19364
+ }
19365
+ if (!res.ok)
19366
+ throw classifyHttpError(res.status, await readBody(res), "wavespeed", ctx.model.id);
19367
+ const task = await parseTask(res);
19368
+ if (task === "not_json") {
19369
+ if (transient) return void 0;
19370
+ throw new ModelKitError({
19371
+ code: "network",
19372
+ message: "WaveSpeed returned a result response that is not JSON",
19373
+ provider: "wavespeed",
19374
+ model: ctx.model.id
19375
+ });
19376
+ }
19377
+ if (task === void 0) {
19378
+ throw fail4(ctx, "provider_rejected", "WaveSpeed returned an unreadable task");
19379
+ }
19380
+ if (task.status === "completed") {
19381
+ const url = import_zod35.z.string().safeParse(task.outputs?.[0]);
19382
+ if (!url.success)
19383
+ throw fail4(ctx, "provider_rejected", "WaveSpeed completed without a video URL");
19384
+ return url.data;
19385
+ }
19386
+ if (task.status !== void 0 && FAILED_STATUSES.has(task.status)) {
19387
+ throw new TaskFailed(failedTask(ctx, task.status, task.error));
19388
+ }
19389
+ return void 0;
19390
+ };
19391
+ const unwrap = async (signal) => {
19392
+ try {
19393
+ return await check(signal);
19394
+ } catch (cause) {
19395
+ throw cause instanceof TaskFailed ? cause.error : cause;
19396
+ }
19397
+ };
19398
+ return {
19399
+ jobId: taskId,
19400
+ async poll() {
19401
+ try {
19402
+ return await check(ctx.signal) ? { status: "succeeded" } : { status: "pending" };
19403
+ } catch (cause) {
19404
+ if (cause instanceof TaskFailed) return { status: "failed" };
19405
+ if (ctx.signal?.aborted || ctx.call.maxRetries === 0) throw cause;
19406
+ if (cause instanceof ModelKitError && !cause.retryable) return { status: "failed" };
19407
+ throw cause;
19408
+ }
19409
+ },
19410
+ async result(opts) {
19411
+ const signal = combineSignals(ctx.signal, opts?.signal);
19412
+ const settings = {
19413
+ intervalMs: opts?.pollIntervalMs ?? POLL_INTERVAL_MS3,
19414
+ backoff: POLL_BACKOFF,
19415
+ maxIntervalMs: POLL_MAX_INTERVAL_MS,
19416
+ timeoutMs: opts?.timeoutMs ?? POLL_TIMEOUT_MS2
19417
+ };
19418
+ if (signal !== void 0) settings.signal = signal;
19419
+ const url = await pollUntil(() => unwrap(signal), settings);
19420
+ const result = { video: { url }, usage: usage5(ctx, req) };
19421
+ return result;
19422
+ }
19423
+ };
19424
+ }
19425
+ var PROVIDER_DEFAULT_SECONDS = 5;
19426
+ function wholeSeconds2(req, ctx) {
19427
+ const seconds3 = req.durationSeconds ?? ctx.model.defaults.durationSeconds ?? PROVIDER_DEFAULT_SECONDS;
19428
+ return { ...req, durationSeconds: Math.round(seconds3) };
19429
+ }
19430
+ async function generateWavespeedVideo(req, ctx) {
19431
+ throwIfAborted(ctx.signal);
19432
+ const sent = wholeSeconds2(req, ctx);
19433
+ const { path, body } = magiRequest(sent, ctx);
19434
+ let res;
19435
+ try {
19436
+ res = await ctx.fetch(`${BASE}/${path}`, init(ctx, "POST", JSON.stringify(body)));
19437
+ } catch (cause) {
19438
+ throw finalSubmitError(classifyThrown("wavespeed", cause, ctx.model.id));
19439
+ }
19440
+ if (!res.ok) {
19441
+ const err = classifyHttpError(res.status, await readBody(res), "wavespeed", ctx.model.id);
19442
+ throw finalSubmitError(err);
19443
+ }
19444
+ const task = await parseTask(res);
19445
+ const taskId = task === "not_json" ? void 0 : task?.id;
19446
+ if (!taskId) throw fail4(ctx, "provider_rejected", "WaveSpeed submit returned no task id");
19447
+ return jobFor(sent, ctx, taskId);
19448
+ }
19449
+ var wavespeedAdapter = {
19450
+ id: "wavespeed",
19451
+ generateVideo: generateWavespeedVideo,
19452
+ resumeVideo: (req, jobId, ctx) => jobFor(wholeSeconds2(req, ctx), ctx, jobId)
19453
+ };
19155
19454
 
19156
19455
  // src/adapters/xai-video.ts
19157
19456
  var import_ai3 = require("ai");
19158
19457
  var import_xai2 = require("@ai-sdk/xai");
19159
- var import_zod35 = require("zod");
19160
- var POLL_INTERVAL_MS3 = 1e4;
19161
- var POLL_TIMEOUT_MS2 = 15 * 6e4;
19458
+ var import_zod36 = require("zod");
19459
+ var POLL_INTERVAL_MS4 = 1e4;
19460
+ var POLL_TIMEOUT_MS3 = 15 * 6e4;
19162
19461
  var defaultXaiDeps = {
19163
19462
  createXaiClient: () => ({ generateVideo: import_ai3.experimental_generateVideo })
19164
19463
  };
@@ -19169,8 +19468,8 @@ function createXaiVideoAdapter(deps = defaultXaiDeps) {
19169
19468
  };
19170
19469
  }
19171
19470
  var xaiVideoAdapter = createXaiVideoAdapter();
19172
- var xaiResponseStatusSchema = import_zod35.z.object({
19173
- response: import_zod35.z.object({ status: import_zod35.z.number() }).partial()
19471
+ var xaiResponseStatusSchema = import_zod36.z.object({
19472
+ response: import_zod36.z.object({ status: import_zod36.z.number() }).partial()
19174
19473
  });
19175
19474
  function xaiError(cause, ctx) {
19176
19475
  const info = describeThrown(cause);
@@ -19178,12 +19477,12 @@ function xaiError(cause, ctx) {
19178
19477
  const status = info.status ?? (nested.success ? nested.data.response?.status : void 0);
19179
19478
  return classifyThrown("xai-video", cause, ctx.model.id, { status, body: info.body });
19180
19479
  }
19181
- var xaiMetaSchema = import_zod35.z.object({
19480
+ var xaiMetaSchema = import_zod36.z.object({
19182
19481
  videoUrl: JsonValueSchema.optional(),
19183
19482
  costInUsdTicks: JsonValueSchema.optional(),
19184
19483
  duration: JsonValueSchema.optional()
19185
19484
  });
19186
- var xaiProviderMetadataSchema = import_zod35.z.object({ xai: xaiMetaSchema });
19485
+ var xaiProviderMetadataSchema = import_zod36.z.object({ xai: xaiMetaSchema });
19187
19486
  function metaOf(result) {
19188
19487
  const parsed = xaiProviderMetadataSchema.partial().safeParse(result.providerMetadata);
19189
19488
  if (!parsed.success) return {};
@@ -19191,8 +19490,8 @@ function metaOf(result) {
19191
19490
  }
19192
19491
  var SDK_REFERENCE_CAP = 7;
19193
19492
  async function generateXaiVideo(req, ctx, deps) {
19194
- const apiKey = ctx.keys.xai;
19195
- if (!apiKey) {
19493
+ const apiKey2 = ctx.keys.xai;
19494
+ if (!apiKey2) {
19196
19495
  throw new ModelKitError({
19197
19496
  code: "auth",
19198
19497
  message: "Missing API key for xai",
@@ -19207,8 +19506,8 @@ async function generateXaiVideo(req, ctx, deps) {
19207
19506
  const takesLastFrame = (ctx.model.constraints.supports ?? []).includes("lastFrame");
19208
19507
  const lastFrame = takesLastFrame && req.lastFrame ? refToUrl(req.lastFrame) : void 0;
19209
19508
  const xaiOptions = {
19210
- pollIntervalMs: POLL_INTERVAL_MS3,
19211
- pollTimeoutMs: POLL_TIMEOUT_MS2
19509
+ pollIntervalMs: POLL_INTERVAL_MS4,
19510
+ pollTimeoutMs: POLL_TIMEOUT_MS3
19212
19511
  };
19213
19512
  const resolution = xaiResolution(req, ctx, refs);
19214
19513
  if (resolution !== void 0) xaiOptions.resolution = resolution;
@@ -19228,8 +19527,8 @@ async function generateXaiVideo(req, ctx, deps) {
19228
19527
  message: "xai-video does not support lastFrame; ignored"
19229
19528
  });
19230
19529
  }
19231
- const client2 = deps.createXaiClient({ apiKey });
19232
- const model = (0, import_xai2.createXai)({ apiKey, fetch: ctx.fetch }).video(ctx.model.providerModelId);
19530
+ const client2 = deps.createXaiClient({ apiKey: apiKey2 });
19531
+ const model = (0, import_xai2.createXai)({ apiKey: apiKey2, fetch: ctx.fetch }).video(ctx.model.providerModelId);
19233
19532
  const callBody = {
19234
19533
  model,
19235
19534
  prompt: req.prompt,
@@ -19282,8 +19581,8 @@ async function generateXaiVideo(req, ctx, deps) {
19282
19581
  async result(opts) {
19283
19582
  const resultSignal = opts?.signal ?? ctx.signal;
19284
19583
  const resultOpts = {
19285
- intervalMs: opts?.pollIntervalMs ?? POLL_INTERVAL_MS3,
19286
- timeoutMs: opts?.timeoutMs ?? POLL_TIMEOUT_MS2
19584
+ intervalMs: opts?.pollIntervalMs ?? POLL_INTERVAL_MS4,
19585
+ timeoutMs: opts?.timeoutMs ?? POLL_TIMEOUT_MS3
19287
19586
  };
19288
19587
  if (resultSignal) resultOpts.signal = resultSignal;
19289
19588
  return pollUntil(check, resultOpts);
@@ -19295,12 +19594,12 @@ async function mapResult(ctx, req, result) {
19295
19594
  if (first) {
19296
19595
  return {
19297
19596
  video: { bytes: Uint8Array.from(first.uint8Array), mime: first.mediaType },
19298
- usage: usage5(ctx, req, metaOf(result)),
19597
+ usage: usage6(ctx, req, metaOf(result)),
19299
19598
  raw: result.providerMetadata
19300
19599
  };
19301
19600
  }
19302
19601
  const meta = metaOf(result);
19303
- const videoUrl = import_zod35.z.string().safeParse(meta.videoUrl);
19602
+ const videoUrl = import_zod36.z.string().safeParse(meta.videoUrl);
19304
19603
  if (videoUrl.success && videoUrl.data) {
19305
19604
  const res = await ctx.fetch(videoUrl.data);
19306
19605
  if (!res.ok) {
@@ -19310,7 +19609,7 @@ async function mapResult(ctx, req, result) {
19310
19609
  const mime = res.headers.get("content-type") ?? "video/mp4";
19311
19610
  return {
19312
19611
  video: { bytes: new Uint8Array(await res.arrayBuffer()), mime },
19313
- usage: usage5(ctx, req, meta),
19612
+ usage: usage6(ctx, req, meta),
19314
19613
  raw: result.providerMetadata
19315
19614
  };
19316
19615
  }
@@ -19322,8 +19621,8 @@ async function mapResult(ctx, req, result) {
19322
19621
  retryable: false
19323
19622
  });
19324
19623
  }
19325
- function usage5(ctx, req, meta) {
19326
- const costTicks = import_zod35.z.number().safeParse(meta.costInUsdTicks);
19624
+ function usage6(ctx, req, meta) {
19625
+ const costTicks = import_zod36.z.number().safeParse(meta.costInUsdTicks);
19327
19626
  const cost = costTicks.success ? costTicks.data / 1e10 : void 0;
19328
19627
  const event = {
19329
19628
  model: ctx.model.id,
@@ -19365,7 +19664,8 @@ var DEFAULT_ADAPTERS = {
19365
19664
  luma: lumaAdapter,
19366
19665
  alibaba: alibabaAdapter,
19367
19666
  fish: fishAdapter,
19368
- elevenlabs: elevenLabsAdapter
19667
+ elevenlabs: elevenLabsAdapter,
19668
+ wavespeed: wavespeedAdapter
19369
19669
  };
19370
19670
 
19371
19671
  // src/catalog/data-only.ts
@@ -19508,6 +19808,10 @@ function dataOnlyCapable(row2) {
19508
19808
  const reason = elevenLabsRowRefusal(row2);
19509
19809
  return reason === void 0 ? { ok: true } : { ok: false, reason };
19510
19810
  }
19811
+ case "wavespeed": {
19812
+ const reason = wavespeedRowRefusal(row2);
19813
+ return reason === void 0 ? { ok: true } : { ok: false, reason };
19814
+ }
19511
19815
  default: {
19512
19816
  return assertNever(row2.adapter);
19513
19817
  }
@@ -19527,22 +19831,22 @@ var liveState = store[KEY] ??= {
19527
19831
  var liveCatalog = liveState.catalog;
19528
19832
 
19529
19833
  // src/catalog/load.ts
19530
- var import_zod36 = require("zod");
19834
+ var import_zod37 = require("zod");
19531
19835
  function rowCount() {
19532
19836
  return liveCatalog.list({ lifecycle: ["active", "deprecated", "retired"] }).length;
19533
19837
  }
19534
19838
  function authHeaders2(auth) {
19535
19839
  return "bearer" in auth ? { Authorization: `Bearer ${auth.bearer}` } : { "x-api-key": auth.apiKey };
19536
19840
  }
19537
- var EnvelopeSchema = import_zod36.z.object({
19538
- rows: import_zod36.z.array(JsonValueSchema),
19539
- revision: import_zod36.z.string().optional()
19841
+ var EnvelopeSchema = import_zod37.z.object({
19842
+ rows: import_zod37.z.array(JsonValueSchema),
19843
+ revision: import_zod37.z.string().optional()
19540
19844
  });
19541
19845
  function dropReason(path, message) {
19542
19846
  return path.length === 0 ? message : `${path.map((part) => String(part)).join(".")} ${message}`;
19543
19847
  }
19544
19848
  function rowId(raw) {
19545
- const parsed = import_zod36.z.object({ id: import_zod36.z.string().min(1) }).loose().safeParse(raw);
19849
+ const parsed = import_zod37.z.object({ id: import_zod37.z.string().min(1) }).loose().safeParse(raw);
19546
19850
  if (!parsed.success) return "?";
19547
19851
  return parsed.data.id;
19548
19852
  }
@@ -19759,7 +20063,7 @@ function fileCatalogCache(path) {
19759
20063
  }
19760
20064
 
19761
20065
  // src/catalog/input-billing.ts
19762
- var import_zod37 = require("zod");
20066
+ var import_zod38 = require("zod");
19763
20067
  var DATA_ONLY_INPUT_BILLING = /* @__PURE__ */ new Map([
19764
20068
  ["flux-3", "source-video-rate"]
19765
20069
  ]);
@@ -19768,7 +20072,7 @@ var KIT_INPUT_BILLING = new Map(
19768
20072
  (row2) => row2.constraints.inputBilling ? [[row2.id, row2.constraints.inputBilling]] : []
19769
20073
  )
19770
20074
  );
19771
- var ConstraintsReadView2 = import_zod37.z.looseObject({
20075
+ var ConstraintsReadView2 = import_zod38.z.looseObject({
19772
20076
  inputBilling: InputBillingSchema.optional().catch(void 0)
19773
20077
  });
19774
20078
  function inputBillingOf(row2) {
@@ -21073,7 +21377,8 @@ var ADAPTER_KEYS = {
21073
21377
  luma: ["luma"],
21074
21378
  alibaba: ["alibaba"],
21075
21379
  fish: ["fish"],
21076
- elevenlabs: ["elevenlabs"]
21380
+ elevenlabs: ["elevenlabs"],
21381
+ wavespeed: ["wavespeed"]
21077
21382
  };
21078
21383
  var PAIRED = {
21079
21384
  higgsfield: "higgsfieldSecret",
@@ -21177,6 +21482,7 @@ function keysFromEnv(env, prefix = "") {
21177
21482
  set("alibabaWorkspace", pick2("DASHSCOPE_WORKSPACE_ID"));
21178
21483
  set("fish", pick2("FISH_AUDIO_API_KEY"));
21179
21484
  set("elevenlabs", pick2("ELEVENLABS_API_KEY"));
21485
+ set("wavespeed", pick2("WAVESPEED_API_KEY"));
21180
21486
  set("cloudflare", pick2("CF_AIG_TOKEN"));
21181
21487
  const bearer2 = pick2("AWS_BEARER_TOKEN_BEDROCK");
21182
21488
  const accessKeyId = pick2("AWS_ACCESS_KEY_ID");
@@ -21231,12 +21537,12 @@ function modelsPoweredBy(provider, catalog) {
21231
21537
  function keyOverrideFor(secrets) {
21232
21538
  const override = {};
21233
21539
  for (const provider of Object.values(BYOK_PROVIDERS)) {
21234
- const apiKey = secrets[provider.id]?.apiKey?.trim();
21235
- if (apiKey) override[provider.keyName] = apiKey;
21540
+ const apiKey2 = secrets[provider.id]?.apiKey?.trim();
21541
+ if (apiKey2) override[provider.keyName] = apiKey2;
21236
21542
  }
21237
21543
  return override;
21238
21544
  }
21239
- var bearer = (apiKey) => ({ Authorization: `Bearer ${apiKey}` });
21545
+ var bearer = (apiKey2) => ({ Authorization: `Bearer ${apiKey2}` });
21240
21546
  var PROBES = {
21241
21547
  ark: {
21242
21548
  url: (endpoints) => `${endpoints.ark ?? ARK_BASE_URL}/contents/generations/tasks?page_num=1&page_size=1`,
@@ -21244,7 +21550,7 @@ var PROBES = {
21244
21550
  },
21245
21551
  fal: {
21246
21552
  url: () => "https://api.fal.ai/v1/assets/collections?limit=1",
21247
- headers: (apiKey) => ({ Authorization: `Key ${apiKey}` }),
21553
+ headers: (apiKey2) => ({ Authorization: `Key ${apiKey2}` }),
21248
21554
  unverifiableStatus: 403
21249
21555
  },
21250
21556
  replicate: {
@@ -21258,20 +21564,20 @@ var PROBES = {
21258
21564
  },
21259
21565
  google: {
21260
21566
  url: () => "https://generativelanguage.googleapis.com/v1beta/models?pageSize=1",
21261
- headers: (apiKey) => ({ "x-goog-api-key": apiKey }),
21567
+ headers: (apiKey2) => ({ "x-goog-api-key": apiKey2 }),
21262
21568
  unverifiableStatus: 403
21263
21569
  }
21264
21570
  };
21265
21571
  async function testProviderKey(provider, secret, opts = {}) {
21266
- const apiKey = secret.apiKey?.trim();
21267
- if (!apiKey) return { ok: false, reason: "invalid" };
21572
+ const apiKey2 = secret.apiKey?.trim();
21573
+ if (!apiKey2) return { ok: false, reason: "invalid" };
21268
21574
  const probe = PROBES[provider];
21269
21575
  const fetchImpl = opts.fetch ?? globalThis.fetch;
21270
21576
  let res;
21271
21577
  try {
21272
21578
  res = await fetchImpl(probe.url(opts.endpoints ?? {}), {
21273
21579
  method: "GET",
21274
- headers: probe.headers(apiKey),
21580
+ headers: probe.headers(apiKey2),
21275
21581
  ...opts.signal !== void 0 && { signal: opts.signal }
21276
21582
  });
21277
21583
  } catch (cause) {
@@ -21288,7 +21594,7 @@ async function testProviderKey(provider, secret, opts = {}) {
21288
21594
 
21289
21595
  // src/text.ts
21290
21596
  var import_ai4 = require("ai");
21291
- var import_zod38 = require("zod");
21597
+ var import_zod39 = require("zod");
21292
21598
  function mergeTextProviderOptions(catalog, caller) {
21293
21599
  const merged = {};
21294
21600
  const catalogOptions = catalog.providerOptions ?? {};
@@ -21327,17 +21633,17 @@ function passthroughTextModel(model) {
21327
21633
  pricingKind: "token"
21328
21634
  };
21329
21635
  }
21330
- var perplexityCostSchema = import_zod38.z.object({
21331
- perplexity: import_zod38.z.object({ cost: import_zod38.z.object({ totalCost: import_zod38.z.number().finite().nonnegative() }) })
21636
+ var perplexityCostSchema = import_zod39.z.object({
21637
+ perplexity: import_zod39.z.object({ cost: import_zod39.z.object({ totalCost: import_zod39.z.number().finite().nonnegative() }) })
21332
21638
  });
21333
21639
  function reportedCostUsd(metadata) {
21334
21640
  const parsed = perplexityCostSchema.safeParse(metadata);
21335
21641
  return parsed.success ? parsed.data.perplexity.cost.totalCost : void 0;
21336
21642
  }
21337
- function textUsageEvent(model, provider, usage6, providerMetadata) {
21338
- const inputTokens = usage6.inputTokens ?? 0;
21339
- const outputTokens = usage6.outputTokens ?? 0;
21340
- const total = usage6.totalTokens ?? inputTokens + outputTokens;
21643
+ function textUsageEvent(model, provider, usage7, providerMetadata) {
21644
+ const inputTokens = usage7.inputTokens ?? 0;
21645
+ const outputTokens = usage7.outputTokens ?? 0;
21646
+ const total = usage7.totalTokens ?? inputTokens + outputTokens;
21341
21647
  const event = {
21342
21648
  model: model.id,
21343
21649
  provider,
@@ -21372,7 +21678,7 @@ function createTextSteps(initial, resolve, callerProviderOptions) {
21372
21678
  return { ...prepared, providerOptions };
21373
21679
  };
21374
21680
  }
21375
- function usage6(results) {
21681
+ function usage7(results) {
21376
21682
  const grouped = /* @__PURE__ */ new Map();
21377
21683
  for (const [index, step] of results.entries()) {
21378
21684
  const target = steps.get(index) ?? initial;
@@ -21394,12 +21700,12 @@ function createTextSteps(initial, resolve, callerProviderOptions) {
21394
21700
  }
21395
21701
  return [...grouped.values()];
21396
21702
  }
21397
- return { wrap, usage: usage6 };
21703
+ return { wrap, usage: usage7 };
21398
21704
  }
21399
21705
 
21400
21706
  // src/client.ts
21401
21707
  var import_ai5 = require("ai");
21402
- var import_zod39 = require("zod");
21708
+ var import_zod40 = require("zod");
21403
21709
 
21404
21710
  // src/generated-image.ts
21405
21711
  function toGeneratedImage(image) {
@@ -21521,9 +21827,9 @@ function providerJobMethods(kind, deps) {
21521
21827
  const { methods, adapter, ctx } = target(sub.model, rest);
21522
21828
  if (!methods.result) throw missing3(adapter, ctx.model);
21523
21829
  const result = await methods.result(sub, ctx, webhook);
21524
- const usage6 = deps.rowUsage(ctx, result.usage, sub.submittedAt);
21525
- await deps.emit(usage6);
21526
- return { ...result, usage: usage6 };
21830
+ const usage7 = deps.rowUsage(ctx, result.usage, sub.submittedAt);
21831
+ await deps.emit(usage7);
21832
+ return { ...result, usage: usage7 };
21527
21833
  },
21528
21834
  async cancel(sub, call = {}) {
21529
21835
  const { methods, adapter, ctx } = target(sub.model, call);
@@ -21763,10 +22069,10 @@ function audioNodeMethods(deps) {
21763
22069
  const startedAt = Date.now();
21764
22070
  const outcome = await adapter.dub(resolved, ctx);
21765
22071
  if (outcome.kind === "audio") {
21766
- const { audio, usage: usage6, raw } = outcome.result;
22072
+ const { audio, usage: usage7, raw } = outcome.result;
21767
22073
  return {
21768
22074
  audio,
21769
- usage: await deps.settle(ctx, usage6, startedAt),
22075
+ usage: await deps.settle(ctx, usage7, startedAt),
21770
22076
  ...raw !== void 0 && { raw }
21771
22077
  };
21772
22078
  }
@@ -21818,10 +22124,10 @@ function textAbortOptions(sdk, context) {
21818
22124
  if (abortSignal) return { abortSignal };
21819
22125
  return {};
21820
22126
  }
21821
- var catalogId = import_zod39.z.string();
21822
- var exactSize = import_zod39.z.templateLiteral([import_zod39.z.number(), "x", import_zod39.z.number()]);
21823
- var sdkRatio = import_zod39.z.templateLiteral([import_zod39.z.number(), ":", import_zod39.z.number()]);
21824
- var sizeTier = import_zod39.z.enum(["512", "1K", "2K", "4K", "8K"]);
22127
+ var catalogId = import_zod40.z.string();
22128
+ var exactSize = import_zod40.z.templateLiteral([import_zod40.z.number(), "x", import_zod40.z.number()]);
22129
+ var sdkRatio = import_zod40.z.templateLiteral([import_zod40.z.number(), ":", import_zod40.z.number()]);
22130
+ var sizeTier = import_zod40.z.enum(["512", "1K", "2K", "4K", "8K"]);
21825
22131
  function isCatalogId(model) {
21826
22132
  return catalogId.safeParse(model).success;
21827
22133
  }
@@ -22064,7 +22370,7 @@ function createModelKit(config, adapters) {
22064
22370
  const images = result.images.map(
22065
22371
  (file) => toGeneratedImage({ bytes: file.uint8Array, mime: file.mediaType })
22066
22372
  );
22067
- const usage6 = timed(
22373
+ const usage7 = timed(
22068
22374
  {
22069
22375
  model: model.modelId,
22070
22376
  provider: model.provider,
@@ -22074,8 +22380,8 @@ function createModelKit(config, adapters) {
22074
22380
  },
22075
22381
  startedAt
22076
22382
  );
22077
- await emit(usage6);
22078
- return { image: images[0], images, usage: usage6, raw: result, warnings };
22383
+ await emit(usage7);
22384
+ return { image: images[0], images, usage: usage7, raw: result, warnings };
22079
22385
  }
22080
22386
  function passthroughVideo(req, call) {
22081
22387
  const {
@@ -22151,7 +22457,7 @@ function createModelKit(config, adapters) {
22151
22457
  let settled;
22152
22458
  let failed = false;
22153
22459
  const done = pending.then(async (result) => {
22154
- const usage6 = timed(
22460
+ const usage7 = timed(
22155
22461
  {
22156
22462
  model: model.modelId,
22157
22463
  provider: model.provider,
@@ -22164,10 +22470,10 @@ function createModelKit(config, adapters) {
22164
22470
  );
22165
22471
  settled = {
22166
22472
  video: { bytes: result.video.uint8Array, mime: result.video.mediaType },
22167
- usage: usage6,
22473
+ usage: usage7,
22168
22474
  raw: result
22169
22475
  };
22170
- await emit(usage6);
22476
+ await emit(usage7);
22171
22477
  return settled;
22172
22478
  });
22173
22479
  done.catch(() => {
@@ -22194,9 +22500,9 @@ function createModelKit(config, adapters) {
22194
22500
  if (settled) return settled;
22195
22501
  const pending = result(opts).then(
22196
22502
  async (out) => {
22197
- const usage6 = rowUsage(ctx, out.usage, startedAt);
22198
- await emit(usage6);
22199
- return { ...out, usage: usage6 };
22503
+ const usage7 = rowUsage(ctx, out.usage, startedAt);
22504
+ await emit(usage7);
22505
+ return { ...out, usage: usage7 };
22200
22506
  },
22201
22507
  (cause) => {
22202
22508
  settled = void 0;
@@ -22216,9 +22522,9 @@ function createModelKit(config, adapters) {
22216
22522
  return context(model, signal ? { ...call, signal } : call, warnings);
22217
22523
  },
22218
22524
  async settle(ctx, event, startedAt) {
22219
- const usage6 = rowUsage(ctx, event, startedAt);
22220
- await emit(usage6);
22221
- return usage6;
22525
+ const usage7 = rowUsage(ctx, event, startedAt);
22526
+ await emit(usage7);
22527
+ return usage7;
22222
22528
  },
22223
22529
  wrapVideoJob
22224
22530
  });
@@ -22263,8 +22569,8 @@ function createModelKit(config, adapters) {
22263
22569
  throw billedFailure(ctx, err, err.usage, startedAt);
22264
22570
  throw err;
22265
22571
  }
22266
- const usage6 = rowUsage(ctx, result.usage, startedAt);
22267
- await emit(usage6);
22572
+ const usage7 = rowUsage(ctx, result.usage, startedAt);
22573
+ await emit(usage7);
22268
22574
  const images = result.images.map(toGeneratedImage);
22269
22575
  const first = images[0];
22270
22576
  if (!first)
@@ -22273,7 +22579,7 @@ function createModelKit(config, adapters) {
22273
22579
  message: `${model.id} returned no image`,
22274
22580
  model: model.id
22275
22581
  });
22276
- return { ...result, usage: usage6, image: first, images, warnings };
22582
+ return { ...result, usage: usage7, image: first, images, warnings };
22277
22583
  },
22278
22584
  async generateVideo(req, call = {}) {
22279
22585
  mediaRetryOptions(call);
@@ -22374,9 +22680,9 @@ function createModelKit(config, adapters) {
22374
22680
  }
22375
22681
  const startedAt = Date.now();
22376
22682
  const result = await adapter.generateAudio(resolved, ctx);
22377
- const usage6 = rowUsage(ctx, result.usage, startedAt);
22378
- await emit(usage6);
22379
- return { ...result, usage: usage6 };
22683
+ const usage7 = rowUsage(ctx, result.usage, startedAt);
22684
+ await emit(usage7);
22685
+ return { ...result, usage: usage7 };
22380
22686
  },
22381
22687
  async prepareMediaPart(modelId, ref, mediaType, call = {}) {
22382
22688
  mediaRetryOptions(call);
@@ -22457,8 +22763,8 @@ function createModelKit(config, adapters) {
22457
22763
  options.prepareStep ?? options.experimental_prepareStep
22458
22764
  ),
22459
22765
  onFinish: async (event) => {
22460
- for (const usage6 of steps.usage(event.steps))
22461
- await emit(textTimed(withRowUnit(usage6), event.steps.length, startedAt));
22766
+ for (const usage7 of steps.usage(event.steps))
22767
+ await emit(textTimed(withRowUnit(usage7), event.steps.length, startedAt));
22462
22768
  await callerOnFinish?.(event);
22463
22769
  }
22464
22770
  });
@@ -22665,6 +22971,7 @@ var describe = (modelId) => createDefaultModelKit().describe(modelId);
22665
22971
  videoLengthViolation,
22666
22972
  videoSizeViolation,
22667
22973
  videoToolConstraints,
22974
+ wavespeedAdapter,
22668
22975
  withRetry,
22669
22976
  xaiVideoAdapter,
22670
22977
  ...require("ai")