@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.js CHANGED
@@ -20,32 +20,32 @@ var ModelKitError = class _ModelKitError extends Error {
20
20
  finishReason;
21
21
  /** Set when the provider billed a call that still failed; never sent to `onUsage`. */
22
22
  usage;
23
- constructor(init) {
24
- super(init.message, { cause: init.cause });
23
+ constructor(init2) {
24
+ super(init2.message, { cause: init2.cause });
25
25
  this.name = "ModelKitError";
26
- this.code = init.code;
27
- this.provider = init.provider;
28
- this.model = init.model;
29
- this.status = init.status;
30
- this.body = init.body;
31
- this.retryable = init.retryable ?? defaultRetryable(init.code);
32
- this.finishReason = init.finishReason;
33
- this.usage = init.usage;
34
- }
35
- withUsage(usage6) {
36
- const init = {
26
+ this.code = init2.code;
27
+ this.provider = init2.provider;
28
+ this.model = init2.model;
29
+ this.status = init2.status;
30
+ this.body = init2.body;
31
+ this.retryable = init2.retryable ?? defaultRetryable(init2.code);
32
+ this.finishReason = init2.finishReason;
33
+ this.usage = init2.usage;
34
+ }
35
+ withUsage(usage7) {
36
+ const init2 = {
37
37
  code: this.code,
38
38
  message: this.message,
39
39
  cause: this.cause,
40
40
  retryable: this.retryable,
41
- usage: usage6
41
+ usage: usage7
42
42
  };
43
- if (this.provider !== void 0) init.provider = this.provider;
44
- if (this.model !== void 0) init.model = this.model;
45
- if (this.status !== void 0) init.status = this.status;
46
- if (this.body !== void 0) init.body = this.body;
47
- if (this.finishReason !== void 0) init.finishReason = this.finishReason;
48
- const copy = new _ModelKitError(init);
43
+ if (this.provider !== void 0) init2.provider = this.provider;
44
+ if (this.model !== void 0) init2.model = this.model;
45
+ if (this.status !== void 0) init2.status = this.status;
46
+ if (this.body !== void 0) init2.body = this.body;
47
+ if (this.finishReason !== void 0) init2.finishReason = this.finishReason;
48
+ const copy = new _ModelKitError(init2);
49
49
  if (this.stack !== void 0) copy.stack = this.stack;
50
50
  return copy;
51
51
  }
@@ -6481,6 +6481,7 @@ var GROK_RATIOS = ["1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3"];
6481
6481
  var H3_RATIOS2 = ["21:9", "16:9", "4:3", "1:1", "3:4", "9:16"];
6482
6482
  var H3_REFERENCE_RATIOS = ["adaptive", ...H3_RATIOS2];
6483
6483
  var WAN_RATIOS = ["adaptive", "16:9", "4:3", "1:1", "3:4", "9:16"];
6484
+ var MAGI_RATIOS = ["21:9", "16:9", "4:3", "1:1", "3:4", "9:16"];
6484
6485
  var NEGATIVE_PROMPT = "blur, distort, and low quality";
6485
6486
  var FRAMES_EXCLUDE_REFERENCES = { framesExcludeReferences: true };
6486
6487
  var KLING_PROMPT2 = { referenceSyntax: "numbered", maxChars: 2500 };
@@ -7410,6 +7411,48 @@ var VIDEO_MODELS = [
7410
7411
  },
7411
7412
  capabilities: {}
7412
7413
  },
7414
+ {
7415
+ // Sand AI MAGI-2 on WaveSpeed. One row for text-, image- (start/end frame) and
7416
+ // reference-to-video; the adapter picks the endpoint from the inputs. WaveSpeed bills
7417
+ // USD 0.08 per requested second, sound and references included.
7418
+ // https://wavespeed.ai/docs/docs-api/sand-ai/magi-2/reference-to-video
7419
+ id: "magi-2",
7420
+ aliases: ["magi2", "sand-magi-2"],
7421
+ label: "MAGI-2",
7422
+ type: "video",
7423
+ adapter: "wavespeed",
7424
+ providerModelId: "sand-ai/magi-2",
7425
+ lifecycle: "active",
7426
+ exposure: ["cowork", "space_builder"],
7427
+ constraints: {
7428
+ aspectRatios: [...MAGI_RATIOS],
7429
+ resolutions: ["1080p"],
7430
+ durations: { min: 4, max: 30 },
7431
+ preferDefaultDuration: true,
7432
+ references: {
7433
+ images: 10,
7434
+ videos: 5,
7435
+ audios: 5,
7436
+ videoSeconds: { min: 2, max: 30, total: 30 },
7437
+ audioSeconds: { min: 2, max: 30, total: 30 }
7438
+ },
7439
+ supports: ["seed", "lastFrame", "generateAudio"],
7440
+ prompt: { referenceSyntax: "descriptive", maxChars: 15e3 },
7441
+ audio: "optional"
7442
+ },
7443
+ defaults: {
7444
+ durationSeconds: 5,
7445
+ resolution: "1080p",
7446
+ generateAudio: true
7447
+ },
7448
+ usage: { ...VIDEO_USAGE3 },
7449
+ pricingKind: "video_per_second",
7450
+ display: {
7451
+ provider: "sand-ai",
7452
+ 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."
7453
+ },
7454
+ capabilities: { ...FRAMES_EXCLUDE_REFERENCES, lastFrameRequiresFirstFrame: true }
7455
+ },
7413
7456
  ...VIDEO_FAMILY_MODELS,
7414
7457
  ...VIDEO_AVATAR_MODELS,
7415
7458
  ...LUMA_VIDEO_MODELS
@@ -8642,7 +8685,8 @@ var ADAPTER_IDS = [
8642
8685
  "luma",
8643
8686
  "alibaba",
8644
8687
  "fish",
8645
- "elevenlabs"
8688
+ "elevenlabs",
8689
+ "wavespeed"
8646
8690
  ];
8647
8691
  var ModelTypeSchema = z3.enum([
8648
8692
  "text",
@@ -9441,9 +9485,9 @@ var aiSdkTextAdapter = {
9441
9485
  if (route2.client === "bedrock-anthropic") return bedrockLanguageModel(ctx, route2);
9442
9486
  const { keyName } = route2;
9443
9487
  if (keyName === "aws") throw missingKey(ctx, keyName);
9444
- const apiKey = ctx.keys[keyName];
9445
- if (!apiKey) throw missingKey(ctx, keyName);
9446
- const settings = { apiKey, fetch: ctx.fetch };
9488
+ const apiKey2 = ctx.keys[keyName];
9489
+ if (!apiKey2) throw missingKey(ctx, keyName);
9490
+ const settings = { apiKey: apiKey2, fetch: ctx.fetch };
9447
9491
  if (route2.baseURL !== void 0) settings.baseURL = route2.baseURL;
9448
9492
  if (route2.headers !== void 0) settings.headers = route2.headers;
9449
9493
  switch (route2.client) {
@@ -9462,7 +9506,7 @@ var aiSdkTextAdapter = {
9462
9506
  case "openai-compatible": {
9463
9507
  const model = createOpenAICompatible({
9464
9508
  name: route2.provider,
9465
- apiKey,
9509
+ apiKey: apiKey2,
9466
9510
  baseURL: route2.baseURL,
9467
9511
  fetch: ctx.fetch,
9468
9512
  ...route2.headers ? { headers: route2.headers } : {}
@@ -9918,16 +9962,16 @@ function classifyHttpError(status, body, provider, model) {
9918
9962
  else if (status === 408 || status === 504) code = "timeout";
9919
9963
  else if (status !== void 0 && status >= 500) code = "network";
9920
9964
  const retryable = code === "rate_limited" || code === "timeout" || code === "network";
9921
- const init = {
9965
+ const init2 = {
9922
9966
  code,
9923
9967
  message: `${provider} responded ${status ?? "?"}: ${text2.slice(0, 500)}`,
9924
9968
  provider,
9925
9969
  body,
9926
9970
  retryable
9927
9971
  };
9928
- if (status !== void 0) init.status = status;
9929
- if (model !== void 0) init.model = model;
9930
- return new ModelKitError(init);
9972
+ if (status !== void 0) init2.status = status;
9973
+ if (model !== void 0) init2.model = model;
9974
+ return new ModelKitError(init2);
9931
9975
  }
9932
9976
  function shouldRetry(err) {
9933
9977
  if (err instanceof ModelKitError) return err.retryable;
@@ -10018,15 +10062,15 @@ function throwAborted() {
10018
10062
  function transportError(provider, cause, model) {
10019
10063
  const message = cause instanceof Error ? cause.message : String(cause);
10020
10064
  const aborted = cause instanceof Error && cause.name === "AbortError";
10021
- const init = {
10065
+ const init2 = {
10022
10066
  code: aborted ? "timeout" : "network",
10023
10067
  message: `${provider} request failed before a response: ${message}`,
10024
10068
  provider,
10025
10069
  retryable: !aborted,
10026
10070
  cause
10027
10071
  };
10028
- if (model !== void 0) init.model = model;
10029
- return new ModelKitError(init);
10072
+ if (model !== void 0) init2.model = model;
10073
+ return new ModelKitError(init2);
10030
10074
  }
10031
10075
  function classifyThrown(provider, cause, model, override = {}) {
10032
10076
  if (cause instanceof ModelKitError) return cause;
@@ -10120,7 +10164,7 @@ function alibabaError(status, body, model, code = alibabaErrorCode(body)) {
10120
10164
  }
10121
10165
  const parsed = z7.string().safeParse(body);
10122
10166
  const text2 = parsed.success ? parsed.data : JSON.stringify(body ?? "");
10123
- const init = {
10167
+ const init2 = {
10124
10168
  // A verdict with no HTTP status (a failed task) is not a transport failure.
10125
10169
  code: rule ?? "provider_rejected",
10126
10170
  message: `alibaba rejected the request${code ? ` (${code})` : ""}: ${text2.slice(0, 500)}`,
@@ -10129,11 +10173,11 @@ function alibabaError(status, body, model, code = alibabaErrorCode(body)) {
10129
10173
  body,
10130
10174
  retryable: false
10131
10175
  };
10132
- if (status !== void 0) init.status = status;
10133
- return new ModelKitError(init);
10176
+ if (status !== void 0) init2.status = status;
10177
+ return new ModelKitError(init2);
10134
10178
  }
10135
- function alibabaFetch(ctx, url, init) {
10136
- const withSignal = ctx.signal === void 0 ? init : { ...init, signal: ctx.signal };
10179
+ function alibabaFetch(ctx, url, init2) {
10180
+ const withSignal = ctx.signal === void 0 ? init2 : { ...init2, signal: ctx.signal };
10137
10181
  return ctx.fetch(url, withSignal).catch((cause) => {
10138
10182
  throw classifyThrown("alibaba", cause, ctx.model.id);
10139
10183
  });
@@ -10190,9 +10234,9 @@ async function readBody(res) {
10190
10234
  }
10191
10235
  async function mediaRefToBytes(ref, fetch2, options = {}) {
10192
10236
  if (!isUrlRef(ref)) return { bytes: ref.bytes, mime: ref.mime };
10193
- const init = {};
10194
- if (options.signal !== void 0) init.signal = options.signal;
10195
- const res = await fetch2(ref.url, init);
10237
+ const init2 = {};
10238
+ if (options.signal !== void 0) init2.signal = options.signal;
10239
+ const res = await fetch2(ref.url, init2);
10196
10240
  if (!res.ok) {
10197
10241
  const text2 = await res.text().catch(() => "");
10198
10242
  throw classifyHttpError(
@@ -10234,15 +10278,15 @@ function applyInputSpec(spec, req, refToUrl2, opts) {
10234
10278
  out[providerField] = mapped ?? serialised;
10235
10279
  }
10236
10280
  for (const [providerField, keys] of Object.entries(spec.arrays ?? {})) {
10237
- const urls2 = [];
10281
+ const urls3 = [];
10238
10282
  for (const key of keys) {
10239
10283
  if (!isArrayInputSpecKey(key)) continue;
10240
10284
  const value = canonicalValue(req, key);
10241
10285
  if (value === void 0) continue;
10242
- if (Array.isArray(value)) urls2.push(...value.map(refToUrl2));
10243
- else if (isMediaRef(value)) urls2.push(refToUrl2(value));
10286
+ if (Array.isArray(value)) urls3.push(...value.map(refToUrl2));
10287
+ else if (isMediaRef(value)) urls3.push(refToUrl2(value));
10244
10288
  }
10245
- if (urls2.length > 0) out[providerField] = urls2;
10289
+ if (urls3.length > 0) out[providerField] = urls3;
10246
10290
  }
10247
10291
  if (spec.dimensions !== void 0) {
10248
10292
  const dims = dimensionsFor(spec.dimensions, req);
@@ -10410,19 +10454,19 @@ async function generateAlibabaImage(req, ctx) {
10410
10454
  },
10411
10455
  mediaRetryOptions(ctx.call, ctx.signal)
10412
10456
  );
10413
- const urls2 = (data.output?.choices ?? []).flatMap(
10457
+ const urls3 = (data.output?.choices ?? []).flatMap(
10414
10458
  (choice) => (choice.message?.content ?? []).flatMap((part) => part.image ? [part.image] : [])
10415
10459
  );
10416
- if (urls2.length === 0) throw alibabaError(void 0, "Qwen Image returned no image", modelId);
10460
+ if (urls3.length === 0) throw alibabaError(void 0, "Qwen Image returned no image", modelId);
10417
10461
  const images = await Promise.all(
10418
- urls2.map(async (url) => {
10462
+ urls3.map(async (url) => {
10419
10463
  const res = await alibabaFetch(ctx, url, {});
10420
10464
  if (!res.ok) throw alibabaError(res.status, await res.text().catch(() => ""), modelId);
10421
10465
  const mime = res.headers.get("content-type") ?? "image/png";
10422
10466
  return { bytes: new Uint8Array(await res.arrayBuffer()), mime };
10423
10467
  })
10424
10468
  );
10425
- const usage6 = {
10469
+ const usage7 = {
10426
10470
  model: modelId,
10427
10471
  provider: "alibaba",
10428
10472
  modality: "IMAGE",
@@ -10430,9 +10474,9 @@ async function generateAlibabaImage(req, ctx) {
10430
10474
  quantity: data.usage?.output_image_count ?? images.length
10431
10475
  };
10432
10476
  const tier = billedTier(data.usage?.output_image_type, req.size);
10433
- if (tier !== void 0) usage6.imageSize = tier;
10434
- if (req.quality !== void 0) usage6.imageQuality = req.quality;
10435
- return { images, usage: usage6, raw: data };
10477
+ if (tier !== void 0) usage7.imageSize = tier;
10478
+ if (req.quality !== void 0) usage7.imageQuality = req.quality;
10479
+ return { images, usage: usage7, raw: data };
10436
10480
  }
10437
10481
 
10438
10482
  // src/adapters/alibaba-video.ts
@@ -10894,17 +10938,17 @@ var RENDERED = /* @__PURE__ */ new Map([
10894
10938
  [720, "720p"],
10895
10939
  [1080, "1080p"]
10896
10940
  ]);
10897
- function settleUsage(usage6, task) {
10941
+ function settleUsage(usage7, task) {
10898
10942
  const reported = task.usage;
10899
10943
  if (reported?.duration !== void 0 && reported.duration > 0) {
10900
- usage6.quantity = reported.duration;
10944
+ usage7.quantity = reported.duration;
10901
10945
  }
10902
10946
  const output = reported?.output_video_duration;
10903
- if (output !== void 0 && output > 0) usage6.durationSeconds = output;
10947
+ if (output !== void 0 && output > 0) usage7.durationSeconds = output;
10904
10948
  const rendered = reported?.SR === void 0 ? void 0 : RENDERED.get(reported.SR);
10905
- if (rendered !== void 0) usage6.resolution = rendered;
10949
+ if (rendered !== void 0) usage7.resolution = rendered;
10906
10950
  }
10907
- function alibabaVideoJob(ctx, jobId, usage6) {
10951
+ function alibabaVideoJob(ctx, jobId, usage7) {
10908
10952
  const { key } = alibabaCredentials(ctx);
10909
10953
  const modelId = ctx.model.id;
10910
10954
  const fetchTask = async () => {
@@ -10948,10 +10992,10 @@ function alibabaVideoJob(ctx, jobId, usage6) {
10948
10992
  if (!url) {
10949
10993
  throw alibabaError(void 0, "task succeeded with no video_url", modelId);
10950
10994
  }
10951
- settleUsage(usage6, task);
10995
+ settleUsage(usage7, task);
10952
10996
  return {
10953
10997
  video: { url, expiresAt: new Date(Date.now() + VIDEO_URL_TTL_MS) },
10954
- usage: usage6,
10998
+ usage: usage7,
10955
10999
  raw: task
10956
11000
  };
10957
11001
  }
@@ -11125,7 +11169,7 @@ function throwArkError(status, body, model, code = arkErrorCode(body)) {
11125
11169
  const parsed = z10.string().safeParse(body);
11126
11170
  const text2 = parsed.success ? parsed.data : JSON.stringify(body ?? "");
11127
11171
  if (/sensitive.?content|human.?face/i.test(`${code ?? ""} ${text2}`)) {
11128
- const init = {
11172
+ const init2 = {
11129
11173
  code: "content_blocked",
11130
11174
  message: `ark rejected the request: ${text2.slice(0, 500)}`,
11131
11175
  provider: "ark",
@@ -11133,12 +11177,12 @@ function throwArkError(status, body, model, code = arkErrorCode(body)) {
11133
11177
  body,
11134
11178
  retryable: false
11135
11179
  };
11136
- if (status !== void 0) init.status = status;
11137
- throw new ModelKitError(init);
11180
+ if (status !== void 0) init2.status = status;
11181
+ throw new ModelKitError(init2);
11138
11182
  }
11139
11183
  const rule = arkCodeRule(status, code);
11140
11184
  if (rule || status === void 0) {
11141
- const init = {
11185
+ const init2 = {
11142
11186
  code: rule?.code ?? "provider_rejected",
11143
11187
  message: `ark rejected the request${code ? ` (${code})` : ""}: ${text2.slice(0, 500)}`,
11144
11188
  provider: "ark",
@@ -11146,8 +11190,8 @@ function throwArkError(status, body, model, code = arkErrorCode(body)) {
11146
11190
  body,
11147
11191
  retryable: false
11148
11192
  };
11149
- if (status !== void 0) init.status = status;
11150
- throw new ModelKitError(init);
11193
+ if (status !== void 0) init2.status = status;
11194
+ throw new ModelKitError(init2);
11151
11195
  }
11152
11196
  throw classifyHttpError(status, body, "ark", model);
11153
11197
  }
@@ -11171,12 +11215,12 @@ var SeedreamResponseSchema = z10.object({
11171
11215
  data: z10.array(SeedreamImageSchema).optional(),
11172
11216
  error: z10.object({ message: z10.string().optional(), code: z10.string().optional() }).optional()
11173
11217
  });
11174
- function fetchInitFor(ctx, init) {
11175
- if (ctx.signal !== void 0) init.signal = ctx.signal;
11176
- return init;
11218
+ function fetchInitFor(ctx, init2) {
11219
+ if (ctx.signal !== void 0) init2.signal = ctx.signal;
11220
+ return init2;
11177
11221
  }
11178
- function arkFetch(ctx, url, init) {
11179
- return ctx.fetch(url, fetchInitFor(ctx, init)).catch((cause) => {
11222
+ function arkFetch(ctx, url, init2) {
11223
+ return ctx.fetch(url, fetchInitFor(ctx, init2)).catch((cause) => {
11180
11224
  throw classifyThrown("ark", cause, ctx.model.id);
11181
11225
  });
11182
11226
  }
@@ -11253,16 +11297,16 @@ async function generateSeedreamImage(req, ctx) {
11253
11297
  } else {
11254
11298
  throwArkError(void 0, "Seedream returned no image URL or base64 data", modelId);
11255
11299
  }
11256
- const usage6 = {
11300
+ const usage7 = {
11257
11301
  model: modelId,
11258
11302
  provider: "ark",
11259
11303
  modality: "IMAGE",
11260
11304
  unit: "images",
11261
11305
  quantity: 1
11262
11306
  };
11263
- if (req.size !== void 0) usage6.imageSize = req.size;
11264
- if (req.quality !== void 0) usage6.imageQuality = req.quality;
11265
- return { images: [{ bytes, mime: sniffedImageMime(bytes) }], usage: usage6, raw: data };
11307
+ if (req.size !== void 0) usage7.imageSize = req.size;
11308
+ if (req.quality !== void 0) usage7.imageQuality = req.quality;
11309
+ return { images: [{ bytes, mime: sniffedImageMime(bytes) }], usage: usage7, raw: data };
11266
11310
  }
11267
11311
  var SeedanceUsageSchema = z10.object({
11268
11312
  total_tokens: z10.number().optional(),
@@ -11317,7 +11361,7 @@ function seedanceErrorCode(error) {
11317
11361
  const parsed = SeedanceErrorSchema.safeParse(error);
11318
11362
  return parsed.success ? parsed.data.code : void 0;
11319
11363
  }
11320
- function seedanceJob(ctx, key, jobId, usage6) {
11364
+ function seedanceJob(ctx, key, jobId, usage7) {
11321
11365
  const modelId = ctx.model.id;
11322
11366
  const fetchStatus = async () => {
11323
11367
  const res = await arkFetch(ctx, `${arkBaseUrl(ctx)}${SUBMIT_PATH2}/${jobId}`, {
@@ -11367,21 +11411,21 @@ function seedanceJob(ctx, key, jobId, usage6) {
11367
11411
  modelId
11368
11412
  );
11369
11413
  if (polled.duration !== void 0 && polled.duration > 0) {
11370
- usage6.quantity = polled.duration;
11371
- usage6.durationSeconds = polled.duration;
11414
+ usage7.quantity = polled.duration;
11415
+ usage7.durationSeconds = polled.duration;
11372
11416
  }
11373
11417
  const rendered = VideoResolutionSchema.safeParse(
11374
11418
  polled.resolution?.toLowerCase()
11375
11419
  );
11376
- if (rendered.success) usage6.resolution = rendered.data;
11420
+ if (rendered.success) usage7.resolution = rendered.data;
11377
11421
  const tokens = polled.usage;
11378
11422
  if (tokens?.total_tokens !== void 0 && tokens.completion_tokens !== void 0) {
11379
- usage6.inputTokens = tokens.total_tokens - tokens.completion_tokens;
11380
- usage6.outputTokens = tokens.completion_tokens;
11423
+ usage7.inputTokens = tokens.total_tokens - tokens.completion_tokens;
11424
+ usage7.outputTokens = tokens.completion_tokens;
11381
11425
  }
11382
11426
  return {
11383
11427
  video: { url, expiresAt: new Date(Date.now() + VIDEO_URL_TTL_MS2) },
11384
- usage: usage6,
11428
+ usage: usage7,
11385
11429
  raw: polled
11386
11430
  };
11387
11431
  }
@@ -11534,8 +11578,8 @@ async function generateSeedanceVideo(req, ctx) {
11534
11578
  if (req.watermark !== void 0) body.watermark = req.watermark;
11535
11579
  if (ctx.model.constraints.draft) body.draft = true;
11536
11580
  const jobId = await submitSeedanceTask(ctx, key, body);
11537
- const usage6 = seedanceUsage(ctx, req, taskType === "edit" ? requestedDuration : duration);
11538
- return seedanceJob(ctx, key, jobId, usage6);
11581
+ const usage7 = seedanceUsage(ctx, req, taskType === "edit" ? requestedDuration : duration);
11582
+ return seedanceJob(ctx, key, jobId, usage7);
11539
11583
  }
11540
11584
 
11541
11585
  // src/adapters/fal.ts
@@ -11679,15 +11723,15 @@ function gatewayConfig(ctx) {
11679
11723
  if (ctx.signal !== void 0) config.signal = ctx.signal;
11680
11724
  return config;
11681
11725
  }
11682
- async function gatewayFetch(cfg, fetchImpl, targetUrl, init) {
11726
+ async function gatewayFetch(cfg, fetchImpl, targetUrl, init2) {
11683
11727
  const headers2 = { "x-fal-target-url": targetUrl };
11684
11728
  if (cfg.falKey) headers2.Authorization = `Bearer ${cfg.falKey}`;
11685
- if (init.body) headers2["Content-Type"] = "application/json";
11729
+ if (init2.body) headers2["Content-Type"] = "application/json";
11686
11730
  if (cfg.cfToken) headers2["cf-aig-authorization"] = `Bearer ${cfg.cfToken}`;
11687
11731
  if (cfg.singleAttempt) headers2["cf-aig-max-attempts"] = "1";
11688
- const request = { method: init.method, headers: headers2 };
11732
+ const request = { method: init2.method, headers: headers2 };
11689
11733
  if (cfg.signal !== void 0) request.signal = cfg.signal;
11690
- if (init.body !== void 0) request.body = init.body;
11734
+ if (init2.body !== void 0) request.body = init2.body;
11691
11735
  return fetchImpl(cfg.baseUrl, request);
11692
11736
  }
11693
11737
 
@@ -12678,7 +12722,7 @@ async function collectFalPlanImages(payload, plan5, ctx, req) {
12678
12722
  return { bytes, mime: mime || "image/png" };
12679
12723
  })
12680
12724
  );
12681
- const usage6 = {
12725
+ const usage7 = {
12682
12726
  model: ctx.model.id,
12683
12727
  provider: "fal",
12684
12728
  modality: "IMAGE",
@@ -12686,9 +12730,9 @@ async function collectFalPlanImages(payload, plan5, ctx, req) {
12686
12730
  quantity: images.length
12687
12731
  };
12688
12732
  const billedSize = plan5.imageSize ?? req.size;
12689
- if (billedSize !== void 0 && ctx.model.type === "image") usage6.imageSize = billedSize;
12690
- if (plan5.imageQuality !== void 0) usage6.imageQuality = plan5.imageQuality;
12691
- const result = { images, usage: usage6, raw: payload };
12733
+ if (billedSize !== void 0 && ctx.model.type === "image") usage7.imageSize = billedSize;
12734
+ if (plan5.imageQuality !== void 0) usage7.imageQuality = plan5.imageQuality;
12735
+ const result = { images, usage: usage7, raw: payload };
12692
12736
  const remote = files.find((f) => !f.url.startsWith("data:"));
12693
12737
  if (remote !== void 0) result.outputUrl = remote.url;
12694
12738
  return result;
@@ -14429,14 +14473,14 @@ async function collectFalImages(payload, ctx, req, label) {
14429
14473
  retryable: false
14430
14474
  });
14431
14475
  }
14432
- const usage6 = imageUsage(ctx, req, delivered.length);
14476
+ const usage7 = imageUsage(ctx, req, delivered.length);
14433
14477
  if (isIdeogram46(ctx.model.providerModelId)) {
14434
14478
  const billed = ideogramBilledSize(delivered, req.size);
14435
- if (billed !== void 0) usage6.imageSize = billed;
14479
+ if (billed !== void 0) usage7.imageSize = billed;
14436
14480
  }
14437
14481
  return {
14438
14482
  images: delivered.map(({ bytes, mime }) => ({ bytes, mime })),
14439
- usage: usage6,
14483
+ usage: usage7,
14440
14484
  raw: payload
14441
14485
  };
14442
14486
  }
@@ -14771,13 +14815,13 @@ function classifyResponse(ctx, status, body) {
14771
14815
  }
14772
14816
  return error;
14773
14817
  }
14774
- async function elevenLabsFetch(ctx, path, init) {
14818
+ async function elevenLabsFetch(ctx, path, init2) {
14775
14819
  throwIfAborted(ctx.signal);
14776
14820
  const request = {
14777
- method: init.method,
14778
- headers: { "xi-api-key": elevenLabsKey(ctx), ...init.headers }
14821
+ method: init2.method,
14822
+ headers: { "xi-api-key": elevenLabsKey(ctx), ...init2.headers }
14779
14823
  };
14780
- if (init.body !== void 0) request.body = init.body;
14824
+ if (init2.body !== void 0) request.body = init2.body;
14781
14825
  if (ctx.signal !== void 0) request.signal = ctx.signal;
14782
14826
  let res;
14783
14827
  try {
@@ -15067,13 +15111,13 @@ function fishKey(ctx) {
15067
15111
  function fishUrl(ctx, path) {
15068
15112
  return `${ctx.endpoints?.fish ?? DEFAULT_BASE_URL2}${path}`;
15069
15113
  }
15070
- async function fishFetch(ctx, path, init) {
15114
+ async function fishFetch(ctx, path, init2) {
15071
15115
  throwIfAborted(ctx.signal);
15072
15116
  const request = {
15073
- method: init.method,
15074
- headers: { Authorization: `Bearer ${fishKey(ctx)}`, ...init.headers }
15117
+ method: init2.method,
15118
+ headers: { Authorization: `Bearer ${fishKey(ctx)}`, ...init2.headers }
15075
15119
  };
15076
- if (init.body !== void 0) request.body = init.body;
15120
+ if (init2.body !== void 0) request.body = init2.body;
15077
15121
  if (ctx.signal !== void 0) request.signal = ctx.signal;
15078
15122
  let res;
15079
15123
  try {
@@ -15324,13 +15368,13 @@ function googleKey(ctx) {
15324
15368
  if (!key) throw refuse(ctx, "auth", "Missing Google API key");
15325
15369
  return key;
15326
15370
  }
15327
- async function googleFetch(ctx, path, init) {
15371
+ async function googleFetch(ctx, path, init2) {
15328
15372
  throwIfAborted(ctx.signal);
15329
15373
  const request = {
15330
- method: init.method,
15374
+ method: init2.method,
15331
15375
  headers: { "x-goog-api-key": googleKey(ctx), "Content-Type": "application/json" }
15332
15376
  };
15333
- if (init.body !== void 0) request.body = JSON.stringify(init.body);
15377
+ if (init2.body !== void 0) request.body = JSON.stringify(init2.body);
15334
15378
  if (ctx.signal !== void 0) request.signal = ctx.signal;
15335
15379
  let res;
15336
15380
  try {
@@ -15552,20 +15596,20 @@ function fileNameFromUri(fileUri, model) {
15552
15596
  return name;
15553
15597
  }
15554
15598
  function oversizeError(bytes, label, model) {
15555
- const init = {
15599
+ const init2 = {
15556
15600
  code: "unsupported_option",
15557
15601
  message: `${label}: source is ${bytes} bytes, over the Files API limit of ${GOOGLE_FILES_MAX_BYTES}`,
15558
15602
  provider: "google-genai",
15559
15603
  retryable: false
15560
15604
  };
15561
- if (model !== void 0) init.model = model;
15562
- return new ModelKitError(init);
15605
+ if (model !== void 0) init2.model = model;
15606
+ return new ModelKitError(init2);
15563
15607
  }
15564
15608
  async function resolveSource(source2, fetchImpl, signal, label, model) {
15565
15609
  if ("bytes" in source2) return { bytes: source2.bytes, mimeType: source2.mime };
15566
- const init = {};
15567
- if (signal !== void 0) init.signal = signal;
15568
- const res = await fetchImpl(source2.url, init);
15610
+ const init2 = {};
15611
+ if (signal !== void 0) init2.signal = signal;
15612
+ const res = await fetchImpl(source2.url, init2);
15569
15613
  if (!res.ok) {
15570
15614
  const text2 = await res.text().catch(() => "");
15571
15615
  throw classifyHttpError(res.status, text2, "google-genai", model);
@@ -15671,11 +15715,11 @@ async function waitForActive(fileName3, opts) {
15671
15715
  throw classifyHttpError(res.status, text2, "google-genai", opts.model);
15672
15716
  }, pollOptions2);
15673
15717
  }
15674
- async function deleteGoogleFile(fileName3, apiKey, fetchImpl) {
15718
+ async function deleteGoogleFile(fileName3, apiKey2, fetchImpl) {
15675
15719
  try {
15676
15720
  await fetchImpl(`${GOOGLE_FILES_BASE}/v1beta/${fileName3}`, {
15677
15721
  method: "DELETE",
15678
- headers: { "x-goog-api-key": apiKey }
15722
+ headers: { "x-goog-api-key": apiKey2 }
15679
15723
  });
15680
15724
  } catch {
15681
15725
  }
@@ -15824,9 +15868,9 @@ function toBase64(bytes) {
15824
15868
  }
15825
15869
  async function resolveMedia(ref, fetchImpl, signal, defaultMime, model) {
15826
15870
  if ("bytes" in ref) return { bytes: ref.bytes, mime: ref.mime };
15827
- const init = {};
15828
- if (signal !== void 0) init.signal = signal;
15829
- const res = await fetchImpl(ref.url, init);
15871
+ const init2 = {};
15872
+ if (signal !== void 0) init2.signal = signal;
15873
+ const res = await fetchImpl(ref.url, init2);
15830
15874
  if (!res.ok) {
15831
15875
  const text2 = await res.text().catch(() => "");
15832
15876
  throw classifyHttpError(res.status, text2, "google-genai", model);
@@ -15836,10 +15880,10 @@ async function resolveMedia(ref, fetchImpl, signal, defaultMime, model) {
15836
15880
  mime: res.headers.get("content-type")?.split(";")[0]?.trim() || defaultMime
15837
15881
  };
15838
15882
  }
15839
- async function downloadVideo(ctx, url, apiKey, signal) {
15840
- const init = { headers: { "x-goog-api-key": apiKey } };
15841
- if (signal !== void 0) init.signal = signal;
15842
- const res = await ctx.fetch(url, init);
15883
+ async function downloadVideo(ctx, url, apiKey2, signal) {
15884
+ const init2 = { headers: { "x-goog-api-key": apiKey2 } };
15885
+ if (signal !== void 0) init2.signal = signal;
15886
+ const res = await ctx.fetch(url, init2);
15843
15887
  if (!res.ok) {
15844
15888
  const text2 = await res.text().catch(() => "");
15845
15889
  throw classifyHttpError(res.status, text2, "google-genai", ctx.model.id);
@@ -15862,7 +15906,7 @@ function videoUsage2(ctx, duration, resolution) {
15862
15906
  return event;
15863
15907
  }
15864
15908
  async function generateVeoVideo(req, ctx, createGenAIClient) {
15865
- const apiKey = googleKey2(ctx);
15909
+ const apiKey2 = googleKey2(ctx);
15866
15910
  const modelId = ctx.model.id;
15867
15911
  const refs = req.referenceImages ?? [];
15868
15912
  if (req.firstFrame && refs.length > 0) {
@@ -15915,7 +15959,7 @@ async function generateVeoVideo(req, ctx, createGenAIClient) {
15915
15959
  }));
15916
15960
  }
15917
15961
  const client2 = createGenAIClient({
15918
- apiKey,
15962
+ apiKey: apiKey2,
15919
15963
  ...ctx.call.maxRetries !== void 0 ? { maxRetries: ctx.call.maxRetries } : {},
15920
15964
  ...ctx.signal !== void 0 ? { signal: ctx.signal } : {}
15921
15965
  });
@@ -15952,7 +15996,7 @@ async function generateVeoVideo(req, ctx, createGenAIClient) {
15952
15996
  }
15953
15997
  };
15954
15998
  const jobId = operation.name ?? crypto.randomUUID();
15955
- const usage6 = videoUsage2(ctx, duration, req.resolution ?? "720p");
15999
+ const usage7 = videoUsage2(ctx, duration, req.resolution ?? "720p");
15956
16000
  return {
15957
16001
  jobId,
15958
16002
  async poll() {
@@ -15990,7 +16034,7 @@ async function generateVeoVideo(req, ctx, createGenAIClient) {
15990
16034
  modelId
15991
16035
  );
15992
16036
  }
15993
- return { video: await downloadVideo(ctx, uri, apiKey, signal), usage: usage6, raw: finished };
16037
+ return { video: await downloadVideo(ctx, uri, apiKey2, signal), usage: usage7, raw: finished };
15994
16038
  }
15995
16039
  };
15996
16040
  }
@@ -16027,7 +16071,7 @@ function extractOmniVideo(interaction, model) {
16027
16071
  );
16028
16072
  }
16029
16073
  async function generateOmniVideo(req, ctx, createGenAIClient) {
16030
- const apiKey = googleKey2(ctx);
16074
+ const apiKey2 = googleKey2(ctx);
16031
16075
  const modelId = ctx.model.id;
16032
16076
  const providerModelId = ctx.model.providerModelId;
16033
16077
  const extend = req.taskType === "extend";
@@ -16087,7 +16131,7 @@ async function generateOmniVideo(req, ctx, createGenAIClient) {
16087
16131
  if (omniResolution !== void 0) responseFormat.resolution = omniResolution;
16088
16132
  if (req.durationSeconds !== void 0) responseFormat.duration = `${req.durationSeconds}s`;
16089
16133
  const client2 = createGenAIClient({
16090
- apiKey,
16134
+ apiKey: apiKey2,
16091
16135
  ...ctx.call.maxRetries !== void 0 ? { maxRetries: ctx.call.maxRetries } : {},
16092
16136
  ...ctx.signal !== void 0 ? { signal: ctx.signal } : {}
16093
16137
  });
@@ -16095,7 +16139,7 @@ async function generateOmniVideo(req, ctx, createGenAIClient) {
16095
16139
  const uploadedNames = [];
16096
16140
  const uploadOne = async (kind, bytes, mime) => {
16097
16141
  const uploadOptions = {
16098
- apiKey,
16142
+ apiKey: apiKey2,
16099
16143
  fetchImpl: ctx.fetch,
16100
16144
  model: modelId,
16101
16145
  label: "gemini-omni"
@@ -16108,7 +16152,7 @@ async function generateOmniVideo(req, ctx, createGenAIClient) {
16108
16152
  return file.fileUri;
16109
16153
  };
16110
16154
  const cleanupUploads = async () => {
16111
- for (const fileName3 of uploadedNames) await deleteGoogleFile(fileName3, apiKey, ctx.fetch);
16155
+ for (const fileName3 of uploadedNames) await deleteGoogleFile(fileName3, apiKey2, ctx.fetch);
16112
16156
  };
16113
16157
  const callCreate = (input) => client2.interactions.create(
16114
16158
  previousId !== void 0 ? {
@@ -16202,7 +16246,7 @@ async function generateOmniVideo(req, ctx, createGenAIClient) {
16202
16246
  if (!(extend && !chained)) await cleanupUploads();
16203
16247
  }
16204
16248
  const jobId = interaction.id ?? crypto.randomUUID();
16205
- const usage6 = videoUsage2(ctx, duration, omniResolution ?? "720p");
16249
+ const usage7 = videoUsage2(ctx, duration, omniResolution ?? "720p");
16206
16250
  const getInteraction = async () => {
16207
16251
  try {
16208
16252
  const getParams = { stream: false };
@@ -16250,15 +16294,15 @@ async function generateOmniVideo(req, ctx, createGenAIClient) {
16250
16294
  bytes: Buffer.from(video.data, "base64"),
16251
16295
  mime: video.mime_type ?? "video/mp4"
16252
16296
  },
16253
- usage: usage6,
16297
+ usage: usage7,
16254
16298
  raw: done,
16255
16299
  providerRef
16256
16300
  };
16257
16301
  }
16258
16302
  if (video.uri)
16259
16303
  return {
16260
- video: await downloadVideo(ctx, video.uri, apiKey, signal),
16261
- usage: usage6,
16304
+ video: await downloadVideo(ctx, video.uri, apiKey2, signal),
16305
+ usage: usage7,
16262
16306
  raw: done,
16263
16307
  providerRef
16264
16308
  };
@@ -16285,7 +16329,7 @@ function lyriaUsage(ctx, req, meta) {
16285
16329
  return event;
16286
16330
  }
16287
16331
  async function generateLyriaAudio(req, ctx, createGenAIClient) {
16288
- const apiKey = googleKey2(ctx);
16332
+ const apiKey2 = googleKey2(ctx);
16289
16333
  const modelId = ctx.model.id;
16290
16334
  const parts = [{ text: req.prompt }];
16291
16335
  for (const ref of req.references ?? []) {
@@ -16293,7 +16337,7 @@ async function generateLyriaAudio(req, ctx, createGenAIClient) {
16293
16337
  parts.push({ inlineData: { mimeType: image.mime, data: toBase64(image.bytes) } });
16294
16338
  }
16295
16339
  const client2 = createGenAIClient({
16296
- apiKey,
16340
+ apiKey: apiKey2,
16297
16341
  ...ctx.call.maxRetries !== void 0 ? { maxRetries: ctx.call.maxRetries } : {},
16298
16342
  ...ctx.signal !== void 0 ? { signal: ctx.signal } : {}
16299
16343
  });
@@ -16347,14 +16391,14 @@ async function generateLyriaAudio(req, ctx, createGenAIClient) {
16347
16391
  return result;
16348
16392
  }
16349
16393
  async function generateLyriaInteraction(req, ctx, createGenAIClient) {
16350
- const apiKey = googleKey2(ctx);
16394
+ const apiKey2 = googleKey2(ctx);
16351
16395
  const modelId = ctx.model.id;
16352
16396
  const input = [{ type: "text", text: req.prompt }];
16353
16397
  for (const ref of req.references ?? []) {
16354
16398
  const image = await resolveMedia(ref, ctx.fetch, ctx.signal, "image/jpeg", modelId);
16355
16399
  input.push({ type: "image", mime_type: image.mime, data: toBase64(image.bytes) });
16356
16400
  }
16357
- const clientOptions = { apiKey };
16401
+ const clientOptions = { apiKey: apiKey2 };
16358
16402
  if (ctx.call.maxRetries !== void 0) clientOptions.maxRetries = ctx.call.maxRetries;
16359
16403
  if (ctx.signal !== void 0) clientOptions.signal = ctx.signal;
16360
16404
  const client2 = createGenAIClient(clientOptions);
@@ -16407,9 +16451,9 @@ async function prepareGoogleMediaPart(ref, mediaType, ctx) {
16407
16451
  if (ref.bytes.length <= MEDIA_PART_INLINE_LIMIT_BYTES) {
16408
16452
  return { type: "file", data: ref.bytes, mediaType };
16409
16453
  }
16410
- const apiKey = googleKey2(ctx);
16454
+ const apiKey2 = googleKey2(ctx);
16411
16455
  const uploadOptions = {
16412
- apiKey,
16456
+ apiKey: apiKey2,
16413
16457
  fetchImpl: ctx.fetch,
16414
16458
  model: ctx.model.id,
16415
16459
  label: "media-part"
@@ -16421,7 +16465,7 @@ async function prepareGoogleMediaPart(ref, mediaType, ctx) {
16421
16465
  type: "file",
16422
16466
  data: file.fileUri,
16423
16467
  mediaType: file.mimeType,
16424
- cleanup: () => deleteGoogleFile(file.fileName, apiKey, ctx.fetch)
16468
+ cleanup: () => deleteGoogleFile(file.fileName, apiKey2, ctx.fetch)
16425
16469
  };
16426
16470
  }
16427
16471
 
@@ -16456,9 +16500,9 @@ function extractBlockReason(cause) {
16456
16500
  current = parsed.data.cause ?? null;
16457
16501
  }
16458
16502
  }
16459
- function billedTokens(model, usage6) {
16460
- const inputTokens = usage6?.inputTokens;
16461
- const outputTokens = usage6?.outputTokens;
16503
+ function billedTokens(model, usage7) {
16504
+ const inputTokens = usage7?.inputTokens;
16505
+ const outputTokens = usage7?.outputTokens;
16462
16506
  if (inputTokens === void 0 && outputTokens === void 0) return void 0;
16463
16507
  const event = {
16464
16508
  model,
@@ -16492,8 +16536,8 @@ function createGoogleImageAdapter(deps = defaultGoogleImageDeps) {
16492
16536
  return {
16493
16537
  id: "google-image",
16494
16538
  async generateImage(req, ctx) {
16495
- const apiKey = ctx.keys.google;
16496
- if (!apiKey)
16539
+ const apiKey2 = ctx.keys.google;
16540
+ if (!apiKey2)
16497
16541
  throw new ModelKitError({
16498
16542
  code: "auth",
16499
16543
  message: "Missing API key for google",
@@ -16501,7 +16545,7 @@ function createGoogleImageAdapter(deps = defaultGoogleImageDeps) {
16501
16545
  model: ctx.model.id,
16502
16546
  retryable: false
16503
16547
  });
16504
- const google = deps.createGoogleClient({ apiKey, fetch: ctx.fetch });
16548
+ const google = deps.createGoogleClient({ apiKey: apiKey2, fetch: ctx.fetch });
16505
16549
  const model = google(ctx.model.providerModelId);
16506
16550
  const content = [];
16507
16551
  for (const ref of req.references ?? []) {
@@ -16542,7 +16586,7 @@ function createGoogleImageAdapter(deps = defaultGoogleImageDeps) {
16542
16586
  const images = (result.files ?? []).filter((file) => file.mediaType.startsWith("image/")).map((file) => ({ bytes: file.uint8Array, mime: file.mediaType }));
16543
16587
  if (images.length === 0) {
16544
16588
  const filtered = result.finishReason === "content-filter" || result.finishReason === "other";
16545
- const init = {
16589
+ const init2 = {
16546
16590
  code: filtered ? "content_blocked" : "provider_rejected",
16547
16591
  message: `google-image returned no image (finishReason: ${result.finishReason}). ${result.text}`.trim(),
16548
16592
  provider: "google-image",
@@ -16554,12 +16598,12 @@ function createGoogleImageAdapter(deps = defaultGoogleImageDeps) {
16554
16598
  },
16555
16599
  retryable: false
16556
16600
  };
16557
- if (result.finishReason !== void 0) init.finishReason = result.finishReason;
16601
+ if (result.finishReason !== void 0) init2.finishReason = result.finishReason;
16558
16602
  const billed = billedTokens(ctx.model.id, result.usage);
16559
- if (billed !== void 0) init.usage = billed;
16560
- throw new ModelKitError(init);
16603
+ if (billed !== void 0) init2.usage = billed;
16604
+ throw new ModelKitError(init2);
16561
16605
  }
16562
- const usage6 = {
16606
+ const usage7 = {
16563
16607
  model: ctx.model.id,
16564
16608
  provider: "google-image",
16565
16609
  modality: "IMAGE",
@@ -16567,12 +16611,12 @@ function createGoogleImageAdapter(deps = defaultGoogleImageDeps) {
16567
16611
  quantity: images.length,
16568
16612
  imageQuality: "auto"
16569
16613
  };
16570
- if (req.size !== void 0) usage6.imageSize = req.size;
16614
+ if (req.size !== void 0) usage7.imageSize = req.size;
16571
16615
  if (result.usage?.inputTokens !== void 0)
16572
- usage6.inputTokens = result.usage.inputTokens;
16616
+ usage7.inputTokens = result.usage.inputTokens;
16573
16617
  if (result.usage?.outputTokens !== void 0)
16574
- usage6.outputTokens = result.usage.outputTokens;
16575
- return { images, usage: usage6, raw: result };
16618
+ usage7.outputTokens = result.usage.outputTokens;
16619
+ return { images, usage: usage7, raw: result };
16576
16620
  }
16577
16621
  };
16578
16622
  }
@@ -16814,16 +16858,16 @@ function klingErrorDetail(error) {
16814
16858
  if (asObject.success) return asObject.data.message ?? "unknown_error";
16815
16859
  return "unknown_error";
16816
16860
  }
16817
- function requestInit(ctx, init) {
16818
- const request = { method: init.method, headers: headers(ctx) };
16819
- if (init.body !== void 0) request.body = init.body;
16861
+ function requestInit(ctx, init2) {
16862
+ const request = { method: init2.method, headers: headers(ctx) };
16863
+ if (init2.body !== void 0) request.body = init2.body;
16820
16864
  if (ctx.signal !== void 0) request.signal = ctx.signal;
16821
16865
  return request;
16822
16866
  }
16823
- async function createRequest(ctx, url, init) {
16867
+ async function createRequest(ctx, url, init2) {
16824
16868
  let res;
16825
16869
  try {
16826
- res = await ctx.fetch(url, requestInit(ctx, init));
16870
+ res = await ctx.fetch(url, requestInit(ctx, init2));
16827
16871
  } catch (cause) {
16828
16872
  throw classifyThrown("higgsfield", cause, ctx.model.id);
16829
16873
  }
@@ -17419,13 +17463,13 @@ function lumaFailure(ctx, code, reason) {
17419
17463
  }
17420
17464
  }
17421
17465
  function requestInit2(ctx, key, body) {
17422
- const init = {
17466
+ const init2 = {
17423
17467
  method: body !== void 0 ? "POST" : "GET",
17424
17468
  headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" }
17425
17469
  };
17426
- if (body !== void 0) init.body = body;
17427
- if (ctx.signal !== void 0) init.signal = ctx.signal;
17428
- return init;
17470
+ if (body !== void 0) init2.body = body;
17471
+ if (ctx.signal !== void 0) init2.signal = ctx.signal;
17472
+ return init2;
17429
17473
  }
17430
17474
  async function lumaRequest(ctx, url, body) {
17431
17475
  const key = lumaKey(ctx);
@@ -17914,8 +17958,8 @@ var openaiImageAdapter = {
17914
17958
  id: "openai-image",
17915
17959
  async generateImage(req, ctx) {
17916
17960
  throwIfAborted(ctx.signal);
17917
- const apiKey = ctx.keys.openai;
17918
- if (!apiKey)
17961
+ const apiKey2 = ctx.keys.openai;
17962
+ if (!apiKey2)
17919
17963
  throw new ModelKitError({
17920
17964
  code: "auth",
17921
17965
  message: "Missing API key for openai",
@@ -17930,7 +17974,7 @@ var openaiImageAdapter = {
17930
17974
  message: "openai-image cannot express reference labels; ignoring them"
17931
17975
  });
17932
17976
  }
17933
- const client2 = new OpenAI({ apiKey, fetch: ctx.fetch, maxRetries: 0 });
17977
+ const client2 = new OpenAI({ apiKey: apiKey2, fetch: ctx.fetch, maxRetries: 0 });
17934
17978
  const size = req.exactSize !== void 0 ? req.exactSize : req.aspectRatio === void 0 || req.aspectRatio === "adaptive" ? void 0 : aspectRatioToSize(req.aspectRatio, req.size ?? "1K");
17935
17979
  const refs = req.references ?? [];
17936
17980
  const isEdit = refs.length > 0;
@@ -18020,7 +18064,7 @@ var openaiImageAdapter = {
18020
18064
  const usageParsed = openaiUsageSchema.safeParse(response.usage);
18021
18065
  const inputTokens = usageParsed.success ? usageParsed.data.input_tokens : void 0;
18022
18066
  const outputTokens = usageParsed.success ? usageParsed.data.output_tokens : void 0;
18023
- const usage6 = {
18067
+ const usage7 = {
18024
18068
  model: ctx.model.id,
18025
18069
  provider: "openai-image",
18026
18070
  modality: "IMAGE",
@@ -18028,10 +18072,10 @@ var openaiImageAdapter = {
18028
18072
  quantity: images.length,
18029
18073
  imageQuality: quality
18030
18074
  };
18031
- if (inputTokens !== void 0) usage6.inputTokens = inputTokens;
18032
- if (outputTokens !== void 0) usage6.outputTokens = outputTokens;
18033
- if (req.size !== void 0) usage6.imageSize = req.size;
18034
- return { images, usage: usage6, raw: response };
18075
+ if (inputTokens !== void 0) usage7.inputTokens = inputTokens;
18076
+ if (outputTokens !== void 0) usage7.outputTokens = outputTokens;
18077
+ if (req.size !== void 0) usage7.imageSize = req.size;
18078
+ return { images, usage: usage7, raw: response };
18035
18079
  }
18036
18080
  };
18037
18081
 
@@ -18264,13 +18308,13 @@ async function generateProdiaImage(req, ctx) {
18264
18308
  res = await withRetry(async () => {
18265
18309
  let attemptRes;
18266
18310
  try {
18267
- const init = {
18311
+ const init2 = {
18268
18312
  method: "POST",
18269
18313
  headers: { Authorization: `Bearer ${key}`, Accept: accept },
18270
18314
  body: form
18271
18315
  };
18272
- if (ctx.signal !== void 0) init.signal = ctx.signal;
18273
- attemptRes = await ctx.fetch(PRODIA_JOB_URL, init);
18316
+ if (ctx.signal !== void 0) init2.signal = ctx.signal;
18317
+ attemptRes = await ctx.fetch(PRODIA_JOB_URL, init2);
18274
18318
  } catch (err) {
18275
18319
  throw classifyThrown("prodia", err, ctx.model.id);
18276
18320
  }
@@ -18287,16 +18331,16 @@ async function generateProdiaImage(req, ctx) {
18287
18331
  new Uint8Array(await res.arrayBuffer()),
18288
18332
  res.headers.get("content-type")
18289
18333
  );
18290
- const usage6 = {
18334
+ const usage7 = {
18291
18335
  model: ctx.model.id,
18292
18336
  provider: "prodia",
18293
18337
  modality: "IMAGE",
18294
18338
  unit: "images",
18295
18339
  quantity: 1
18296
18340
  };
18297
- if (req.size !== void 0) usage6.imageSize = req.size;
18298
- if (req.quality !== void 0) usage6.imageQuality = req.quality;
18299
- return { images: [{ bytes, mime }], usage: usage6, raw: void 0 };
18341
+ if (req.size !== void 0) usage7.imageSize = req.size;
18342
+ if (req.quality !== void 0) usage7.imageQuality = req.quality;
18343
+ return { images: [{ bytes, mime }], usage: usage7, raw: void 0 };
18300
18344
  }
18301
18345
  var prodiaAdapter = {
18302
18346
  id: "prodia",
@@ -18752,9 +18796,9 @@ async function generateReplicateImage(req, ctx, deps) {
18752
18796
  }
18753
18797
  const { url, predictTime, raw } = await runPrediction(ctx, input, deps);
18754
18798
  const file = await download(ctx, url);
18755
- const usage6 = imageUsage3(ctx, req);
18756
- usage6.quantity = predictTime;
18757
- return { images: [{ bytes: file.bytes, mime: file.mime }], usage: usage6, raw, outputUrl: url };
18799
+ const usage7 = imageUsage3(ctx, req);
18800
+ usage7.quantity = predictTime;
18801
+ return { images: [{ bytes: file.bytes, mime: file.mime }], usage: usage7, raw, outputUrl: url };
18758
18802
  }
18759
18803
  function klingInput(req) {
18760
18804
  const images = (req.firstFrame ? [req.firstFrame] : []).map(refToUrl);
@@ -18878,9 +18922,9 @@ async function generateReplicateVideo(req, ctx, deps) {
18878
18922
  return void 0;
18879
18923
  };
18880
18924
  const toResult = (done) => {
18881
- const usage6 = videoUsage5(ctx, req);
18882
- usage6.quantity = done.predictTime;
18883
- return { video: { url: done.url }, usage: usage6, raw: done.raw };
18925
+ const usage7 = videoUsage5(ctx, req);
18926
+ usage7.quantity = done.predictTime;
18927
+ return { video: { url: done.url }, usage: usage7, raw: done.raw };
18884
18928
  };
18885
18929
  return {
18886
18930
  jobId,
@@ -18987,23 +19031,277 @@ async function generateReplicateAudio(req, ctx, deps) {
18987
19031
  input = specResult.input;
18988
19032
  }
18989
19033
  const { url, predictTime, raw } = await runPrediction(ctx, input, deps);
18990
- const usage6 = audioUsage(ctx, req);
19034
+ const usage7 = audioUsage(ctx, req);
18991
19035
  if (ctx.model.usage.unit === "seconds") {
18992
19036
  const seconds3 = elevenLabsMusicDuration(req.durationSeconds);
18993
- usage6.quantity = seconds3;
18994
- usage6.durationSeconds = seconds3;
19037
+ usage7.quantity = seconds3;
19038
+ usage7.durationSeconds = seconds3;
18995
19039
  } else {
18996
- usage6.quantity = predictTime;
19040
+ usage7.quantity = predictTime;
19041
+ }
19042
+ return { audio: { url }, usage: usage7, raw: predictionRaw(raw) };
19043
+ }
19044
+
19045
+ // src/adapters/wavespeed.ts
19046
+ import { z as z35 } from "zod";
19047
+ var BASE = "https://api.wavespeed.ai/api/v3";
19048
+ var POLL_INTERVAL_MS3 = 3e3;
19049
+ var POLL_BACKOFF = 1.2;
19050
+ var POLL_MAX_INTERVAL_MS = 15e3;
19051
+ var POLL_TIMEOUT_MS2 = 30 * 6e4;
19052
+ var FAILED_STATUSES = /* @__PURE__ */ new Set(["failed", "cancelled", "timeout", "deleted"]);
19053
+ var VIDEO_MODEL_IDS = /* @__PURE__ */ new Set(["sand-ai/magi-2"]);
19054
+ function wavespeedRowRefusal(row2) {
19055
+ if (row2.type !== "video") return `wavespeed has no ${row2.type} rows`;
19056
+ return VIDEO_MODEL_IDS.has(row2.providerModelId.toLowerCase()) ? void 0 : `wavespeed video rows need providerModelId ${[...VIDEO_MODEL_IDS].join(", ")}`;
19057
+ }
19058
+ function fail4(ctx, code, message) {
19059
+ return new ModelKitError({
19060
+ code,
19061
+ message,
19062
+ provider: "wavespeed",
19063
+ model: ctx.model.id,
19064
+ retryable: false
19065
+ });
19066
+ }
19067
+ function ignore(ctx, field, why) {
19068
+ ctx.warnings.push({
19069
+ code: "option_ignored",
19070
+ field,
19071
+ message: `${ctx.model.id}: ${why}; ${field} ignored`
19072
+ });
19073
+ }
19074
+ function urls2(refs) {
19075
+ return (refs ?? []).map(refToUrl);
19076
+ }
19077
+ function magiRequest(req, ctx) {
19078
+ const images = urls2(req.referenceImages);
19079
+ const videos = urls2(req.referenceVideos);
19080
+ const audios = urls2(req.referenceAudios);
19081
+ const hasReferences2 = images.length + videos.length + audios.length > 0;
19082
+ let mode = "text-to-video";
19083
+ const body = {};
19084
+ if (req.firstFrame) {
19085
+ mode = "image-to-video";
19086
+ body.image = refToUrl(req.firstFrame);
19087
+ if (req.lastFrame) body.last_image = refToUrl(req.lastFrame);
19088
+ if (hasReferences2) ignore(ctx, "references", "image-to-video takes no references");
19089
+ } else {
19090
+ if (req.lastFrame) ignore(ctx, "lastFrame", "an end frame needs a start frame");
19091
+ if (hasReferences2) {
19092
+ mode = "reference-to-video";
19093
+ if (images.length > 0) body.images = images;
19094
+ if (videos.length > 0) body.videos = videos;
19095
+ if (audios.length > 0) body.audios = audios;
19096
+ }
19097
+ }
19098
+ const prompt = req.prompt.trim();
19099
+ if (prompt !== "") body.prompt = prompt;
19100
+ else if (mode !== "image-to-video") {
19101
+ throw fail4(ctx, "missing_input", `${ctx.model.id} ${mode} requires a prompt`);
19102
+ }
19103
+ if (req.durationSeconds !== void 0) body.duration = req.durationSeconds;
19104
+ if (req.aspectRatio !== void 0 && req.aspectRatio !== "adaptive") {
19105
+ body.aspect_ratio = req.aspectRatio;
19106
+ }
19107
+ if (req.generateAudio !== void 0) body.generate_audio = req.generateAudio;
19108
+ if (req.seed !== void 0) body.seed = req.seed;
19109
+ return { path: `${ctx.model.providerModelId.toLowerCase()}/${mode}`, body };
19110
+ }
19111
+ function apiKey(ctx) {
19112
+ const key = ctx.keys.wavespeed;
19113
+ if (!key) throw fail4(ctx, "auth", "Missing API key for wavespeed");
19114
+ return key;
19115
+ }
19116
+ function init(ctx, method, body) {
19117
+ const request = {
19118
+ method,
19119
+ headers: { Authorization: `Bearer ${apiKey(ctx)}`, "Content-Type": "application/json" }
19120
+ };
19121
+ if (body !== void 0) request.body = body;
19122
+ if (ctx.signal !== void 0) request.signal = ctx.signal;
19123
+ return request;
19124
+ }
19125
+ var taskFields = z35.object({
19126
+ id: z35.string().optional(),
19127
+ status: z35.string().optional(),
19128
+ outputs: z35.array(z35.unknown()).optional(),
19129
+ error: JsonValueSchema.optional()
19130
+ }).refine((task) => task.id !== void 0 || task.status !== void 0);
19131
+ var taskSchema = z35.union([
19132
+ z35.object({ data: taskFields }).transform((wrapped) => wrapped.data),
19133
+ taskFields
19134
+ ]);
19135
+ async function parseTask(res) {
19136
+ let raw;
19137
+ try {
19138
+ raw = await res.json();
19139
+ } catch {
19140
+ return "not_json";
19141
+ }
19142
+ const parsed = taskSchema.safeParse(raw);
19143
+ return parsed.success ? parsed.data : void 0;
19144
+ }
19145
+ function finalSubmitError(err) {
19146
+ if (err.code === "rate_limited" || !err.retryable) return err;
19147
+ const init2 = {
19148
+ code: err.code,
19149
+ message: `${err.message} (the task may exist; not retried)`,
19150
+ cause: err,
19151
+ retryable: false
19152
+ };
19153
+ if (err.provider !== void 0) init2.provider = err.provider;
19154
+ if (err.model !== void 0) init2.model = err.model;
19155
+ if (err.status !== void 0) init2.status = err.status;
19156
+ if (err.body !== void 0) init2.body = err.body;
19157
+ return new ModelKitError(init2);
19158
+ }
19159
+ function failedTask(ctx, status, error) {
19160
+ const text2 = z35.string().safeParse(error);
19161
+ const detail = text2.success ? text2.data || "unknown_error" : error == null ? "unknown_error" : JSON.stringify(error);
19162
+ const classified = classifyHttpError(void 0, detail, "wavespeed", ctx.model.id);
19163
+ return new ModelKitError({
19164
+ code: classified.code === "content_blocked" ? "content_blocked" : "provider_rejected",
19165
+ message: `WaveSpeed generation ${status}: ${detail}`,
19166
+ provider: "wavespeed",
19167
+ model: ctx.model.id,
19168
+ retryable: false
19169
+ });
19170
+ }
19171
+ var TaskFailed = class extends Error {
19172
+ constructor(error) {
19173
+ super(error.message);
19174
+ this.error = error;
18997
19175
  }
18998
- return { audio: { url }, usage: usage6, raw: predictionRaw(raw) };
19176
+ error;
19177
+ };
19178
+ function usage5(ctx, req) {
19179
+ const event = {
19180
+ model: ctx.model.id,
19181
+ provider: "wavespeed",
19182
+ modality: "VIDEO",
19183
+ unit: "seconds",
19184
+ quantity: req.durationSeconds ?? 0
19185
+ };
19186
+ if (req.resolution !== void 0) event.resolution = req.resolution;
19187
+ if (req.durationSeconds !== void 0) event.durationSeconds = req.durationSeconds;
19188
+ return event;
18999
19189
  }
19190
+ function jobFor(req, ctx, taskId) {
19191
+ const resultUrl = `${BASE}/predictions/${encodeURIComponent(taskId)}/result`;
19192
+ const transient = ctx.call.maxRetries !== 0;
19193
+ const check = async (signal) => {
19194
+ const request = init(ctx, "GET");
19195
+ if (signal !== void 0) request.signal = signal;
19196
+ let res;
19197
+ try {
19198
+ res = await ctx.fetch(resultUrl, request);
19199
+ } catch (cause) {
19200
+ if (signal?.aborted || !transient) {
19201
+ throw classifyThrown("wavespeed", cause, ctx.model.id);
19202
+ }
19203
+ return void 0;
19204
+ }
19205
+ if (transient && (res.status === 429 || res.status >= 500)) {
19206
+ await res.body?.cancel().catch(() => void 0);
19207
+ return void 0;
19208
+ }
19209
+ if (!res.ok)
19210
+ throw classifyHttpError(res.status, await readBody(res), "wavespeed", ctx.model.id);
19211
+ const task = await parseTask(res);
19212
+ if (task === "not_json") {
19213
+ if (transient) return void 0;
19214
+ throw new ModelKitError({
19215
+ code: "network",
19216
+ message: "WaveSpeed returned a result response that is not JSON",
19217
+ provider: "wavespeed",
19218
+ model: ctx.model.id
19219
+ });
19220
+ }
19221
+ if (task === void 0) {
19222
+ throw fail4(ctx, "provider_rejected", "WaveSpeed returned an unreadable task");
19223
+ }
19224
+ if (task.status === "completed") {
19225
+ const url = z35.string().safeParse(task.outputs?.[0]);
19226
+ if (!url.success)
19227
+ throw fail4(ctx, "provider_rejected", "WaveSpeed completed without a video URL");
19228
+ return url.data;
19229
+ }
19230
+ if (task.status !== void 0 && FAILED_STATUSES.has(task.status)) {
19231
+ throw new TaskFailed(failedTask(ctx, task.status, task.error));
19232
+ }
19233
+ return void 0;
19234
+ };
19235
+ const unwrap = async (signal) => {
19236
+ try {
19237
+ return await check(signal);
19238
+ } catch (cause) {
19239
+ throw cause instanceof TaskFailed ? cause.error : cause;
19240
+ }
19241
+ };
19242
+ return {
19243
+ jobId: taskId,
19244
+ async poll() {
19245
+ try {
19246
+ return await check(ctx.signal) ? { status: "succeeded" } : { status: "pending" };
19247
+ } catch (cause) {
19248
+ if (cause instanceof TaskFailed) return { status: "failed" };
19249
+ if (ctx.signal?.aborted || ctx.call.maxRetries === 0) throw cause;
19250
+ if (cause instanceof ModelKitError && !cause.retryable) return { status: "failed" };
19251
+ throw cause;
19252
+ }
19253
+ },
19254
+ async result(opts) {
19255
+ const signal = combineSignals(ctx.signal, opts?.signal);
19256
+ const settings = {
19257
+ intervalMs: opts?.pollIntervalMs ?? POLL_INTERVAL_MS3,
19258
+ backoff: POLL_BACKOFF,
19259
+ maxIntervalMs: POLL_MAX_INTERVAL_MS,
19260
+ timeoutMs: opts?.timeoutMs ?? POLL_TIMEOUT_MS2
19261
+ };
19262
+ if (signal !== void 0) settings.signal = signal;
19263
+ const url = await pollUntil(() => unwrap(signal), settings);
19264
+ const result = { video: { url }, usage: usage5(ctx, req) };
19265
+ return result;
19266
+ }
19267
+ };
19268
+ }
19269
+ var PROVIDER_DEFAULT_SECONDS = 5;
19270
+ function wholeSeconds2(req, ctx) {
19271
+ const seconds3 = req.durationSeconds ?? ctx.model.defaults.durationSeconds ?? PROVIDER_DEFAULT_SECONDS;
19272
+ return { ...req, durationSeconds: Math.round(seconds3) };
19273
+ }
19274
+ async function generateWavespeedVideo(req, ctx) {
19275
+ throwIfAborted(ctx.signal);
19276
+ const sent = wholeSeconds2(req, ctx);
19277
+ const { path, body } = magiRequest(sent, ctx);
19278
+ let res;
19279
+ try {
19280
+ res = await ctx.fetch(`${BASE}/${path}`, init(ctx, "POST", JSON.stringify(body)));
19281
+ } catch (cause) {
19282
+ throw finalSubmitError(classifyThrown("wavespeed", cause, ctx.model.id));
19283
+ }
19284
+ if (!res.ok) {
19285
+ const err = classifyHttpError(res.status, await readBody(res), "wavespeed", ctx.model.id);
19286
+ throw finalSubmitError(err);
19287
+ }
19288
+ const task = await parseTask(res);
19289
+ const taskId = task === "not_json" ? void 0 : task?.id;
19290
+ if (!taskId) throw fail4(ctx, "provider_rejected", "WaveSpeed submit returned no task id");
19291
+ return jobFor(sent, ctx, taskId);
19292
+ }
19293
+ var wavespeedAdapter = {
19294
+ id: "wavespeed",
19295
+ generateVideo: generateWavespeedVideo,
19296
+ resumeVideo: (req, jobId, ctx) => jobFor(wholeSeconds2(req, ctx), ctx, jobId)
19297
+ };
19000
19298
 
19001
19299
  // src/adapters/xai-video.ts
19002
19300
  import { experimental_generateVideo } from "ai";
19003
19301
  import { createXai as createXai2 } from "@ai-sdk/xai";
19004
- import { z as z35 } from "zod";
19005
- var POLL_INTERVAL_MS3 = 1e4;
19006
- var POLL_TIMEOUT_MS2 = 15 * 6e4;
19302
+ import { z as z36 } from "zod";
19303
+ var POLL_INTERVAL_MS4 = 1e4;
19304
+ var POLL_TIMEOUT_MS3 = 15 * 6e4;
19007
19305
  var defaultXaiDeps = {
19008
19306
  createXaiClient: () => ({ generateVideo: experimental_generateVideo })
19009
19307
  };
@@ -19014,8 +19312,8 @@ function createXaiVideoAdapter(deps = defaultXaiDeps) {
19014
19312
  };
19015
19313
  }
19016
19314
  var xaiVideoAdapter = createXaiVideoAdapter();
19017
- var xaiResponseStatusSchema = z35.object({
19018
- response: z35.object({ status: z35.number() }).partial()
19315
+ var xaiResponseStatusSchema = z36.object({
19316
+ response: z36.object({ status: z36.number() }).partial()
19019
19317
  });
19020
19318
  function xaiError(cause, ctx) {
19021
19319
  const info = describeThrown(cause);
@@ -19023,12 +19321,12 @@ function xaiError(cause, ctx) {
19023
19321
  const status = info.status ?? (nested.success ? nested.data.response?.status : void 0);
19024
19322
  return classifyThrown("xai-video", cause, ctx.model.id, { status, body: info.body });
19025
19323
  }
19026
- var xaiMetaSchema = z35.object({
19324
+ var xaiMetaSchema = z36.object({
19027
19325
  videoUrl: JsonValueSchema.optional(),
19028
19326
  costInUsdTicks: JsonValueSchema.optional(),
19029
19327
  duration: JsonValueSchema.optional()
19030
19328
  });
19031
- var xaiProviderMetadataSchema = z35.object({ xai: xaiMetaSchema });
19329
+ var xaiProviderMetadataSchema = z36.object({ xai: xaiMetaSchema });
19032
19330
  function metaOf(result) {
19033
19331
  const parsed = xaiProviderMetadataSchema.partial().safeParse(result.providerMetadata);
19034
19332
  if (!parsed.success) return {};
@@ -19036,8 +19334,8 @@ function metaOf(result) {
19036
19334
  }
19037
19335
  var SDK_REFERENCE_CAP = 7;
19038
19336
  async function generateXaiVideo(req, ctx, deps) {
19039
- const apiKey = ctx.keys.xai;
19040
- if (!apiKey) {
19337
+ const apiKey2 = ctx.keys.xai;
19338
+ if (!apiKey2) {
19041
19339
  throw new ModelKitError({
19042
19340
  code: "auth",
19043
19341
  message: "Missing API key for xai",
@@ -19052,8 +19350,8 @@ async function generateXaiVideo(req, ctx, deps) {
19052
19350
  const takesLastFrame = (ctx.model.constraints.supports ?? []).includes("lastFrame");
19053
19351
  const lastFrame = takesLastFrame && req.lastFrame ? refToUrl(req.lastFrame) : void 0;
19054
19352
  const xaiOptions = {
19055
- pollIntervalMs: POLL_INTERVAL_MS3,
19056
- pollTimeoutMs: POLL_TIMEOUT_MS2
19353
+ pollIntervalMs: POLL_INTERVAL_MS4,
19354
+ pollTimeoutMs: POLL_TIMEOUT_MS3
19057
19355
  };
19058
19356
  const resolution = xaiResolution(req, ctx, refs);
19059
19357
  if (resolution !== void 0) xaiOptions.resolution = resolution;
@@ -19073,8 +19371,8 @@ async function generateXaiVideo(req, ctx, deps) {
19073
19371
  message: "xai-video does not support lastFrame; ignored"
19074
19372
  });
19075
19373
  }
19076
- const client2 = deps.createXaiClient({ apiKey });
19077
- const model = createXai2({ apiKey, fetch: ctx.fetch }).video(ctx.model.providerModelId);
19374
+ const client2 = deps.createXaiClient({ apiKey: apiKey2 });
19375
+ const model = createXai2({ apiKey: apiKey2, fetch: ctx.fetch }).video(ctx.model.providerModelId);
19078
19376
  const callBody = {
19079
19377
  model,
19080
19378
  prompt: req.prompt,
@@ -19127,8 +19425,8 @@ async function generateXaiVideo(req, ctx, deps) {
19127
19425
  async result(opts) {
19128
19426
  const resultSignal = opts?.signal ?? ctx.signal;
19129
19427
  const resultOpts = {
19130
- intervalMs: opts?.pollIntervalMs ?? POLL_INTERVAL_MS3,
19131
- timeoutMs: opts?.timeoutMs ?? POLL_TIMEOUT_MS2
19428
+ intervalMs: opts?.pollIntervalMs ?? POLL_INTERVAL_MS4,
19429
+ timeoutMs: opts?.timeoutMs ?? POLL_TIMEOUT_MS3
19132
19430
  };
19133
19431
  if (resultSignal) resultOpts.signal = resultSignal;
19134
19432
  return pollUntil(check, resultOpts);
@@ -19140,12 +19438,12 @@ async function mapResult(ctx, req, result) {
19140
19438
  if (first) {
19141
19439
  return {
19142
19440
  video: { bytes: Uint8Array.from(first.uint8Array), mime: first.mediaType },
19143
- usage: usage5(ctx, req, metaOf(result)),
19441
+ usage: usage6(ctx, req, metaOf(result)),
19144
19442
  raw: result.providerMetadata
19145
19443
  };
19146
19444
  }
19147
19445
  const meta = metaOf(result);
19148
- const videoUrl = z35.string().safeParse(meta.videoUrl);
19446
+ const videoUrl = z36.string().safeParse(meta.videoUrl);
19149
19447
  if (videoUrl.success && videoUrl.data) {
19150
19448
  const res = await ctx.fetch(videoUrl.data);
19151
19449
  if (!res.ok) {
@@ -19155,7 +19453,7 @@ async function mapResult(ctx, req, result) {
19155
19453
  const mime = res.headers.get("content-type") ?? "video/mp4";
19156
19454
  return {
19157
19455
  video: { bytes: new Uint8Array(await res.arrayBuffer()), mime },
19158
- usage: usage5(ctx, req, meta),
19456
+ usage: usage6(ctx, req, meta),
19159
19457
  raw: result.providerMetadata
19160
19458
  };
19161
19459
  }
@@ -19167,8 +19465,8 @@ async function mapResult(ctx, req, result) {
19167
19465
  retryable: false
19168
19466
  });
19169
19467
  }
19170
- function usage5(ctx, req, meta) {
19171
- const costTicks = z35.number().safeParse(meta.costInUsdTicks);
19468
+ function usage6(ctx, req, meta) {
19469
+ const costTicks = z36.number().safeParse(meta.costInUsdTicks);
19172
19470
  const cost = costTicks.success ? costTicks.data / 1e10 : void 0;
19173
19471
  const event = {
19174
19472
  model: ctx.model.id,
@@ -19210,7 +19508,8 @@ var DEFAULT_ADAPTERS = {
19210
19508
  luma: lumaAdapter,
19211
19509
  alibaba: alibabaAdapter,
19212
19510
  fish: fishAdapter,
19213
- elevenlabs: elevenLabsAdapter
19511
+ elevenlabs: elevenLabsAdapter,
19512
+ wavespeed: wavespeedAdapter
19214
19513
  };
19215
19514
 
19216
19515
  // src/catalog/data-only.ts
@@ -19353,6 +19652,10 @@ function dataOnlyCapable(row2) {
19353
19652
  const reason = elevenLabsRowRefusal(row2);
19354
19653
  return reason === void 0 ? { ok: true } : { ok: false, reason };
19355
19654
  }
19655
+ case "wavespeed": {
19656
+ const reason = wavespeedRowRefusal(row2);
19657
+ return reason === void 0 ? { ok: true } : { ok: false, reason };
19658
+ }
19356
19659
  default: {
19357
19660
  return assertNever(row2.adapter);
19358
19661
  }
@@ -19372,22 +19675,22 @@ var liveState = store[KEY] ??= {
19372
19675
  var liveCatalog = liveState.catalog;
19373
19676
 
19374
19677
  // src/catalog/load.ts
19375
- import { z as z36 } from "zod";
19678
+ import { z as z37 } from "zod";
19376
19679
  function rowCount() {
19377
19680
  return liveCatalog.list({ lifecycle: ["active", "deprecated", "retired"] }).length;
19378
19681
  }
19379
19682
  function authHeaders2(auth) {
19380
19683
  return "bearer" in auth ? { Authorization: `Bearer ${auth.bearer}` } : { "x-api-key": auth.apiKey };
19381
19684
  }
19382
- var EnvelopeSchema = z36.object({
19383
- rows: z36.array(JsonValueSchema),
19384
- revision: z36.string().optional()
19685
+ var EnvelopeSchema = z37.object({
19686
+ rows: z37.array(JsonValueSchema),
19687
+ revision: z37.string().optional()
19385
19688
  });
19386
19689
  function dropReason(path, message) {
19387
19690
  return path.length === 0 ? message : `${path.map((part) => String(part)).join(".")} ${message}`;
19388
19691
  }
19389
19692
  function rowId(raw) {
19390
- const parsed = z36.object({ id: z36.string().min(1) }).loose().safeParse(raw);
19693
+ const parsed = z37.object({ id: z37.string().min(1) }).loose().safeParse(raw);
19391
19694
  if (!parsed.success) return "?";
19392
19695
  return parsed.data.id;
19393
19696
  }
@@ -19604,7 +19907,7 @@ function fileCatalogCache(path) {
19604
19907
  }
19605
19908
 
19606
19909
  // src/catalog/input-billing.ts
19607
- import { z as z37 } from "zod";
19910
+ import { z as z38 } from "zod";
19608
19911
  var DATA_ONLY_INPUT_BILLING = /* @__PURE__ */ new Map([
19609
19912
  ["flux-3", "source-video-rate"]
19610
19913
  ]);
@@ -19613,7 +19916,7 @@ var KIT_INPUT_BILLING = new Map(
19613
19916
  (row2) => row2.constraints.inputBilling ? [[row2.id, row2.constraints.inputBilling]] : []
19614
19917
  )
19615
19918
  );
19616
- var ConstraintsReadView2 = z37.looseObject({
19919
+ var ConstraintsReadView2 = z38.looseObject({
19617
19920
  inputBilling: InputBillingSchema.optional().catch(void 0)
19618
19921
  });
19619
19922
  function inputBillingOf(row2) {
@@ -20918,7 +21221,8 @@ var ADAPTER_KEYS = {
20918
21221
  luma: ["luma"],
20919
21222
  alibaba: ["alibaba"],
20920
21223
  fish: ["fish"],
20921
- elevenlabs: ["elevenlabs"]
21224
+ elevenlabs: ["elevenlabs"],
21225
+ wavespeed: ["wavespeed"]
20922
21226
  };
20923
21227
  var PAIRED = {
20924
21228
  higgsfield: "higgsfieldSecret",
@@ -21022,6 +21326,7 @@ function keysFromEnv(env, prefix = "") {
21022
21326
  set("alibabaWorkspace", pick2("DASHSCOPE_WORKSPACE_ID"));
21023
21327
  set("fish", pick2("FISH_AUDIO_API_KEY"));
21024
21328
  set("elevenlabs", pick2("ELEVENLABS_API_KEY"));
21329
+ set("wavespeed", pick2("WAVESPEED_API_KEY"));
21025
21330
  set("cloudflare", pick2("CF_AIG_TOKEN"));
21026
21331
  const bearer2 = pick2("AWS_BEARER_TOKEN_BEDROCK");
21027
21332
  const accessKeyId = pick2("AWS_ACCESS_KEY_ID");
@@ -21076,12 +21381,12 @@ function modelsPoweredBy(provider, catalog) {
21076
21381
  function keyOverrideFor(secrets) {
21077
21382
  const override = {};
21078
21383
  for (const provider of Object.values(BYOK_PROVIDERS)) {
21079
- const apiKey = secrets[provider.id]?.apiKey?.trim();
21080
- if (apiKey) override[provider.keyName] = apiKey;
21384
+ const apiKey2 = secrets[provider.id]?.apiKey?.trim();
21385
+ if (apiKey2) override[provider.keyName] = apiKey2;
21081
21386
  }
21082
21387
  return override;
21083
21388
  }
21084
- var bearer = (apiKey) => ({ Authorization: `Bearer ${apiKey}` });
21389
+ var bearer = (apiKey2) => ({ Authorization: `Bearer ${apiKey2}` });
21085
21390
  var PROBES = {
21086
21391
  ark: {
21087
21392
  url: (endpoints) => `${endpoints.ark ?? ARK_BASE_URL}/contents/generations/tasks?page_num=1&page_size=1`,
@@ -21089,7 +21394,7 @@ var PROBES = {
21089
21394
  },
21090
21395
  fal: {
21091
21396
  url: () => "https://api.fal.ai/v1/assets/collections?limit=1",
21092
- headers: (apiKey) => ({ Authorization: `Key ${apiKey}` }),
21397
+ headers: (apiKey2) => ({ Authorization: `Key ${apiKey2}` }),
21093
21398
  unverifiableStatus: 403
21094
21399
  },
21095
21400
  replicate: {
@@ -21103,20 +21408,20 @@ var PROBES = {
21103
21408
  },
21104
21409
  google: {
21105
21410
  url: () => "https://generativelanguage.googleapis.com/v1beta/models?pageSize=1",
21106
- headers: (apiKey) => ({ "x-goog-api-key": apiKey }),
21411
+ headers: (apiKey2) => ({ "x-goog-api-key": apiKey2 }),
21107
21412
  unverifiableStatus: 403
21108
21413
  }
21109
21414
  };
21110
21415
  async function testProviderKey(provider, secret, opts = {}) {
21111
- const apiKey = secret.apiKey?.trim();
21112
- if (!apiKey) return { ok: false, reason: "invalid" };
21416
+ const apiKey2 = secret.apiKey?.trim();
21417
+ if (!apiKey2) return { ok: false, reason: "invalid" };
21113
21418
  const probe = PROBES[provider];
21114
21419
  const fetchImpl = opts.fetch ?? globalThis.fetch;
21115
21420
  let res;
21116
21421
  try {
21117
21422
  res = await fetchImpl(probe.url(opts.endpoints ?? {}), {
21118
21423
  method: "GET",
21119
- headers: probe.headers(apiKey),
21424
+ headers: probe.headers(apiKey2),
21120
21425
  ...opts.signal !== void 0 && { signal: opts.signal }
21121
21426
  });
21122
21427
  } catch (cause) {
@@ -21133,7 +21438,7 @@ async function testProviderKey(provider, secret, opts = {}) {
21133
21438
 
21134
21439
  // src/text.ts
21135
21440
  import "ai";
21136
- import { z as z38 } from "zod";
21441
+ import { z as z39 } from "zod";
21137
21442
  function mergeTextProviderOptions(catalog, caller) {
21138
21443
  const merged = {};
21139
21444
  const catalogOptions = catalog.providerOptions ?? {};
@@ -21172,17 +21477,17 @@ function passthroughTextModel(model) {
21172
21477
  pricingKind: "token"
21173
21478
  };
21174
21479
  }
21175
- var perplexityCostSchema = z38.object({
21176
- perplexity: z38.object({ cost: z38.object({ totalCost: z38.number().finite().nonnegative() }) })
21480
+ var perplexityCostSchema = z39.object({
21481
+ perplexity: z39.object({ cost: z39.object({ totalCost: z39.number().finite().nonnegative() }) })
21177
21482
  });
21178
21483
  function reportedCostUsd(metadata) {
21179
21484
  const parsed = perplexityCostSchema.safeParse(metadata);
21180
21485
  return parsed.success ? parsed.data.perplexity.cost.totalCost : void 0;
21181
21486
  }
21182
- function textUsageEvent(model, provider, usage6, providerMetadata) {
21183
- const inputTokens = usage6.inputTokens ?? 0;
21184
- const outputTokens = usage6.outputTokens ?? 0;
21185
- const total = usage6.totalTokens ?? inputTokens + outputTokens;
21487
+ function textUsageEvent(model, provider, usage7, providerMetadata) {
21488
+ const inputTokens = usage7.inputTokens ?? 0;
21489
+ const outputTokens = usage7.outputTokens ?? 0;
21490
+ const total = usage7.totalTokens ?? inputTokens + outputTokens;
21186
21491
  const event = {
21187
21492
  model: model.id,
21188
21493
  provider,
@@ -21217,7 +21522,7 @@ function createTextSteps(initial, resolve, callerProviderOptions) {
21217
21522
  return { ...prepared, providerOptions };
21218
21523
  };
21219
21524
  }
21220
- function usage6(results) {
21525
+ function usage7(results) {
21221
21526
  const grouped = /* @__PURE__ */ new Map();
21222
21527
  for (const [index, step] of results.entries()) {
21223
21528
  const target = steps.get(index) ?? initial;
@@ -21239,7 +21544,7 @@ function createTextSteps(initial, resolve, callerProviderOptions) {
21239
21544
  }
21240
21545
  return [...grouped.values()];
21241
21546
  }
21242
- return { wrap, usage: usage6 };
21547
+ return { wrap, usage: usage7 };
21243
21548
  }
21244
21549
 
21245
21550
  // src/client.ts
@@ -21251,7 +21556,7 @@ import {
21251
21556
  streamObject as aiStreamObject2,
21252
21557
  streamText as aiStreamText2
21253
21558
  } from "ai";
21254
- import { z as z39 } from "zod";
21559
+ import { z as z40 } from "zod";
21255
21560
 
21256
21561
  // src/generated-image.ts
21257
21562
  function toGeneratedImage(image) {
@@ -21373,9 +21678,9 @@ function providerJobMethods(kind, deps) {
21373
21678
  const { methods, adapter, ctx } = target(sub.model, rest);
21374
21679
  if (!methods.result) throw missing3(adapter, ctx.model);
21375
21680
  const result = await methods.result(sub, ctx, webhook);
21376
- const usage6 = deps.rowUsage(ctx, result.usage, sub.submittedAt);
21377
- await deps.emit(usage6);
21378
- return { ...result, usage: usage6 };
21681
+ const usage7 = deps.rowUsage(ctx, result.usage, sub.submittedAt);
21682
+ await deps.emit(usage7);
21683
+ return { ...result, usage: usage7 };
21379
21684
  },
21380
21685
  async cancel(sub, call = {}) {
21381
21686
  const { methods, adapter, ctx } = target(sub.model, call);
@@ -21615,10 +21920,10 @@ function audioNodeMethods(deps) {
21615
21920
  const startedAt = Date.now();
21616
21921
  const outcome = await adapter.dub(resolved, ctx);
21617
21922
  if (outcome.kind === "audio") {
21618
- const { audio, usage: usage6, raw } = outcome.result;
21923
+ const { audio, usage: usage7, raw } = outcome.result;
21619
21924
  return {
21620
21925
  audio,
21621
- usage: await deps.settle(ctx, usage6, startedAt),
21926
+ usage: await deps.settle(ctx, usage7, startedAt),
21622
21927
  ...raw !== void 0 && { raw }
21623
21928
  };
21624
21929
  }
@@ -21670,10 +21975,10 @@ function textAbortOptions(sdk, context) {
21670
21975
  if (abortSignal) return { abortSignal };
21671
21976
  return {};
21672
21977
  }
21673
- var catalogId = z39.string();
21674
- var exactSize = z39.templateLiteral([z39.number(), "x", z39.number()]);
21675
- var sdkRatio = z39.templateLiteral([z39.number(), ":", z39.number()]);
21676
- var sizeTier = z39.enum(["512", "1K", "2K", "4K", "8K"]);
21978
+ var catalogId = z40.string();
21979
+ var exactSize = z40.templateLiteral([z40.number(), "x", z40.number()]);
21980
+ var sdkRatio = z40.templateLiteral([z40.number(), ":", z40.number()]);
21981
+ var sizeTier = z40.enum(["512", "1K", "2K", "4K", "8K"]);
21677
21982
  function isCatalogId(model) {
21678
21983
  return catalogId.safeParse(model).success;
21679
21984
  }
@@ -21916,7 +22221,7 @@ function createModelKit(config, adapters) {
21916
22221
  const images = result.images.map(
21917
22222
  (file) => toGeneratedImage({ bytes: file.uint8Array, mime: file.mediaType })
21918
22223
  );
21919
- const usage6 = timed(
22224
+ const usage7 = timed(
21920
22225
  {
21921
22226
  model: model.modelId,
21922
22227
  provider: model.provider,
@@ -21926,8 +22231,8 @@ function createModelKit(config, adapters) {
21926
22231
  },
21927
22232
  startedAt
21928
22233
  );
21929
- await emit(usage6);
21930
- return { image: images[0], images, usage: usage6, raw: result, warnings };
22234
+ await emit(usage7);
22235
+ return { image: images[0], images, usage: usage7, raw: result, warnings };
21931
22236
  }
21932
22237
  function passthroughVideo(req, call) {
21933
22238
  const {
@@ -22003,7 +22308,7 @@ function createModelKit(config, adapters) {
22003
22308
  let settled;
22004
22309
  let failed = false;
22005
22310
  const done = pending.then(async (result) => {
22006
- const usage6 = timed(
22311
+ const usage7 = timed(
22007
22312
  {
22008
22313
  model: model.modelId,
22009
22314
  provider: model.provider,
@@ -22016,10 +22321,10 @@ function createModelKit(config, adapters) {
22016
22321
  );
22017
22322
  settled = {
22018
22323
  video: { bytes: result.video.uint8Array, mime: result.video.mediaType },
22019
- usage: usage6,
22324
+ usage: usage7,
22020
22325
  raw: result
22021
22326
  };
22022
- await emit(usage6);
22327
+ await emit(usage7);
22023
22328
  return settled;
22024
22329
  });
22025
22330
  done.catch(() => {
@@ -22046,9 +22351,9 @@ function createModelKit(config, adapters) {
22046
22351
  if (settled) return settled;
22047
22352
  const pending = result(opts).then(
22048
22353
  async (out) => {
22049
- const usage6 = rowUsage(ctx, out.usage, startedAt);
22050
- await emit(usage6);
22051
- return { ...out, usage: usage6 };
22354
+ const usage7 = rowUsage(ctx, out.usage, startedAt);
22355
+ await emit(usage7);
22356
+ return { ...out, usage: usage7 };
22052
22357
  },
22053
22358
  (cause) => {
22054
22359
  settled = void 0;
@@ -22068,9 +22373,9 @@ function createModelKit(config, adapters) {
22068
22373
  return context(model, signal ? { ...call, signal } : call, warnings);
22069
22374
  },
22070
22375
  async settle(ctx, event, startedAt) {
22071
- const usage6 = rowUsage(ctx, event, startedAt);
22072
- await emit(usage6);
22073
- return usage6;
22376
+ const usage7 = rowUsage(ctx, event, startedAt);
22377
+ await emit(usage7);
22378
+ return usage7;
22074
22379
  },
22075
22380
  wrapVideoJob
22076
22381
  });
@@ -22115,8 +22420,8 @@ function createModelKit(config, adapters) {
22115
22420
  throw billedFailure(ctx, err, err.usage, startedAt);
22116
22421
  throw err;
22117
22422
  }
22118
- const usage6 = rowUsage(ctx, result.usage, startedAt);
22119
- await emit(usage6);
22423
+ const usage7 = rowUsage(ctx, result.usage, startedAt);
22424
+ await emit(usage7);
22120
22425
  const images = result.images.map(toGeneratedImage);
22121
22426
  const first = images[0];
22122
22427
  if (!first)
@@ -22125,7 +22430,7 @@ function createModelKit(config, adapters) {
22125
22430
  message: `${model.id} returned no image`,
22126
22431
  model: model.id
22127
22432
  });
22128
- return { ...result, usage: usage6, image: first, images, warnings };
22433
+ return { ...result, usage: usage7, image: first, images, warnings };
22129
22434
  },
22130
22435
  async generateVideo(req, call = {}) {
22131
22436
  mediaRetryOptions(call);
@@ -22226,9 +22531,9 @@ function createModelKit(config, adapters) {
22226
22531
  }
22227
22532
  const startedAt = Date.now();
22228
22533
  const result = await adapter.generateAudio(resolved, ctx);
22229
- const usage6 = rowUsage(ctx, result.usage, startedAt);
22230
- await emit(usage6);
22231
- return { ...result, usage: usage6 };
22534
+ const usage7 = rowUsage(ctx, result.usage, startedAt);
22535
+ await emit(usage7);
22536
+ return { ...result, usage: usage7 };
22232
22537
  },
22233
22538
  async prepareMediaPart(modelId, ref, mediaType, call = {}) {
22234
22539
  mediaRetryOptions(call);
@@ -22309,8 +22614,8 @@ function createModelKit(config, adapters) {
22309
22614
  options.prepareStep ?? options.experimental_prepareStep
22310
22615
  ),
22311
22616
  onFinish: async (event) => {
22312
- for (const usage6 of steps.usage(event.steps))
22313
- await emit(textTimed(withRowUnit(usage6), event.steps.length, startedAt));
22617
+ for (const usage7 of steps.usage(event.steps))
22618
+ await emit(textTimed(withRowUnit(usage7), event.steps.length, startedAt));
22314
22619
  await callerOnFinish?.(event);
22315
22620
  }
22316
22621
  });
@@ -22516,6 +22821,7 @@ export {
22516
22821
  videoLengthViolation,
22517
22822
  videoSizeViolation,
22518
22823
  videoToolConstraints,
22824
+ wavespeedAdapter,
22519
22825
  withRetry,
22520
22826
  xaiVideoAdapter
22521
22827
  };