@shop-os/modelkit 0.32.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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
  }
@@ -5158,6 +5158,22 @@ var TEXT_MODELS = [
5158
5158
  contextWindow: 1e6
5159
5159
  }
5160
5160
  }),
5161
+ text("claude-sonnet-5-5", "Claude Sonnet 5.5", "claude-sonnet-5-5", {
5162
+ exposure: [],
5163
+ // Sonnet 5.5 rejects a forced tool_choice, which is how Bedrock's SDK asks for JSON on Sonnet 5.
5164
+ providerOptions: { modelkit: { structuredOutputMode: "outputFormat" } },
5165
+ display: {
5166
+ chat: { providerOptions: ANTHROPIC_ADAPTIVE },
5167
+ provider: "anthropic",
5168
+ costTier: 3,
5169
+ description: "Anthropic Claude Sonnet 5.5 balanced model; text and image input, 1M-token context."
5170
+ },
5171
+ capabilities: {
5172
+ reasoning: true,
5173
+ vision: true,
5174
+ contextWindow: 1e6
5175
+ }
5176
+ }),
5161
5177
  text("claude-opus-4-8", "Claude Opus 4.8", "claude-opus-4-8", {
5162
5178
  exposure: ["cowork", "space_builder"],
5163
5179
  aliases: ["claude-opus-4.8", "claude-opus-4", "claude-opus-4.0", "claude-opus-4-20250514"],
@@ -6465,6 +6481,7 @@ var GROK_RATIOS = ["1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3"];
6465
6481
  var H3_RATIOS2 = ["21:9", "16:9", "4:3", "1:1", "3:4", "9:16"];
6466
6482
  var H3_REFERENCE_RATIOS = ["adaptive", ...H3_RATIOS2];
6467
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"];
6468
6485
  var NEGATIVE_PROMPT = "blur, distort, and low quality";
6469
6486
  var FRAMES_EXCLUDE_REFERENCES = { framesExcludeReferences: true };
6470
6487
  var KLING_PROMPT2 = { referenceSyntax: "numbered", maxChars: 2500 };
@@ -7394,6 +7411,48 @@ var VIDEO_MODELS = [
7394
7411
  },
7395
7412
  capabilities: {}
7396
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
+ },
7397
7456
  ...VIDEO_FAMILY_MODELS,
7398
7457
  ...VIDEO_AVATAR_MODELS,
7399
7458
  ...LUMA_VIDEO_MODELS
@@ -8626,7 +8685,8 @@ var ADAPTER_IDS = [
8626
8685
  "luma",
8627
8686
  "alibaba",
8628
8687
  "fish",
8629
- "elevenlabs"
8688
+ "elevenlabs",
8689
+ "wavespeed"
8630
8690
  ];
8631
8691
  var ModelTypeSchema = z3.enum([
8632
8692
  "text",
@@ -9311,9 +9371,20 @@ function missingKey(ctx, name) {
9311
9371
  }
9312
9372
  function bedrockMiddleware(ctx, canonicalModelId) {
9313
9373
  let warned = false;
9374
+ const structuredOutputMode = ctx.model.providerOptions?.["modelkit"]?.["structuredOutputMode"];
9314
9375
  return {
9315
9376
  specificationVersion: "v3",
9316
- transformParams: async ({ params }) => {
9377
+ transformParams: async ({ params: incoming }) => {
9378
+ const params = typeof structuredOutputMode === "string" && incoming.responseFormat?.type === "json" && incoming.providerOptions?.["anthropic"]?.["structuredOutputMode"] === void 0 ? {
9379
+ ...incoming,
9380
+ providerOptions: {
9381
+ ...incoming.providerOptions,
9382
+ anthropic: {
9383
+ ...incoming.providerOptions?.["anthropic"],
9384
+ structuredOutputMode
9385
+ }
9386
+ }
9387
+ } : incoming;
9317
9388
  const anthropic = params.providerOptions?.["anthropic"];
9318
9389
  if (typeof anthropic !== "object" || anthropic === null || !("cacheControl" in anthropic))
9319
9390
  return params;
@@ -9414,9 +9485,9 @@ var aiSdkTextAdapter = {
9414
9485
  if (route2.client === "bedrock-anthropic") return bedrockLanguageModel(ctx, route2);
9415
9486
  const { keyName } = route2;
9416
9487
  if (keyName === "aws") throw missingKey(ctx, keyName);
9417
- const apiKey = ctx.keys[keyName];
9418
- if (!apiKey) throw missingKey(ctx, keyName);
9419
- 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 };
9420
9491
  if (route2.baseURL !== void 0) settings.baseURL = route2.baseURL;
9421
9492
  if (route2.headers !== void 0) settings.headers = route2.headers;
9422
9493
  switch (route2.client) {
@@ -9435,7 +9506,7 @@ var aiSdkTextAdapter = {
9435
9506
  case "openai-compatible": {
9436
9507
  const model = createOpenAICompatible({
9437
9508
  name: route2.provider,
9438
- apiKey,
9509
+ apiKey: apiKey2,
9439
9510
  baseURL: route2.baseURL,
9440
9511
  fetch: ctx.fetch,
9441
9512
  ...route2.headers ? { headers: route2.headers } : {}
@@ -9891,16 +9962,16 @@ function classifyHttpError(status, body, provider, model) {
9891
9962
  else if (status === 408 || status === 504) code = "timeout";
9892
9963
  else if (status !== void 0 && status >= 500) code = "network";
9893
9964
  const retryable = code === "rate_limited" || code === "timeout" || code === "network";
9894
- const init = {
9965
+ const init2 = {
9895
9966
  code,
9896
9967
  message: `${provider} responded ${status ?? "?"}: ${text2.slice(0, 500)}`,
9897
9968
  provider,
9898
9969
  body,
9899
9970
  retryable
9900
9971
  };
9901
- if (status !== void 0) init.status = status;
9902
- if (model !== void 0) init.model = model;
9903
- 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);
9904
9975
  }
9905
9976
  function shouldRetry(err) {
9906
9977
  if (err instanceof ModelKitError) return err.retryable;
@@ -9991,15 +10062,15 @@ function throwAborted() {
9991
10062
  function transportError(provider, cause, model) {
9992
10063
  const message = cause instanceof Error ? cause.message : String(cause);
9993
10064
  const aborted = cause instanceof Error && cause.name === "AbortError";
9994
- const init = {
10065
+ const init2 = {
9995
10066
  code: aborted ? "timeout" : "network",
9996
10067
  message: `${provider} request failed before a response: ${message}`,
9997
10068
  provider,
9998
10069
  retryable: !aborted,
9999
10070
  cause
10000
10071
  };
10001
- if (model !== void 0) init.model = model;
10002
- return new ModelKitError(init);
10072
+ if (model !== void 0) init2.model = model;
10073
+ return new ModelKitError(init2);
10003
10074
  }
10004
10075
  function classifyThrown(provider, cause, model, override = {}) {
10005
10076
  if (cause instanceof ModelKitError) return cause;
@@ -10093,7 +10164,7 @@ function alibabaError(status, body, model, code = alibabaErrorCode(body)) {
10093
10164
  }
10094
10165
  const parsed = z7.string().safeParse(body);
10095
10166
  const text2 = parsed.success ? parsed.data : JSON.stringify(body ?? "");
10096
- const init = {
10167
+ const init2 = {
10097
10168
  // A verdict with no HTTP status (a failed task) is not a transport failure.
10098
10169
  code: rule ?? "provider_rejected",
10099
10170
  message: `alibaba rejected the request${code ? ` (${code})` : ""}: ${text2.slice(0, 500)}`,
@@ -10102,11 +10173,11 @@ function alibabaError(status, body, model, code = alibabaErrorCode(body)) {
10102
10173
  body,
10103
10174
  retryable: false
10104
10175
  };
10105
- if (status !== void 0) init.status = status;
10106
- return new ModelKitError(init);
10176
+ if (status !== void 0) init2.status = status;
10177
+ return new ModelKitError(init2);
10107
10178
  }
10108
- function alibabaFetch(ctx, url, init) {
10109
- 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 };
10110
10181
  return ctx.fetch(url, withSignal).catch((cause) => {
10111
10182
  throw classifyThrown("alibaba", cause, ctx.model.id);
10112
10183
  });
@@ -10163,9 +10234,9 @@ async function readBody(res) {
10163
10234
  }
10164
10235
  async function mediaRefToBytes(ref, fetch2, options = {}) {
10165
10236
  if (!isUrlRef(ref)) return { bytes: ref.bytes, mime: ref.mime };
10166
- const init = {};
10167
- if (options.signal !== void 0) init.signal = options.signal;
10168
- 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);
10169
10240
  if (!res.ok) {
10170
10241
  const text2 = await res.text().catch(() => "");
10171
10242
  throw classifyHttpError(
@@ -10207,15 +10278,15 @@ function applyInputSpec(spec, req, refToUrl2, opts) {
10207
10278
  out[providerField] = mapped ?? serialised;
10208
10279
  }
10209
10280
  for (const [providerField, keys] of Object.entries(spec.arrays ?? {})) {
10210
- const urls2 = [];
10281
+ const urls3 = [];
10211
10282
  for (const key of keys) {
10212
10283
  if (!isArrayInputSpecKey(key)) continue;
10213
10284
  const value = canonicalValue(req, key);
10214
10285
  if (value === void 0) continue;
10215
- if (Array.isArray(value)) urls2.push(...value.map(refToUrl2));
10216
- 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));
10217
10288
  }
10218
- if (urls2.length > 0) out[providerField] = urls2;
10289
+ if (urls3.length > 0) out[providerField] = urls3;
10219
10290
  }
10220
10291
  if (spec.dimensions !== void 0) {
10221
10292
  const dims = dimensionsFor(spec.dimensions, req);
@@ -10383,19 +10454,19 @@ async function generateAlibabaImage(req, ctx) {
10383
10454
  },
10384
10455
  mediaRetryOptions(ctx.call, ctx.signal)
10385
10456
  );
10386
- const urls2 = (data.output?.choices ?? []).flatMap(
10457
+ const urls3 = (data.output?.choices ?? []).flatMap(
10387
10458
  (choice) => (choice.message?.content ?? []).flatMap((part) => part.image ? [part.image] : [])
10388
10459
  );
10389
- 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);
10390
10461
  const images = await Promise.all(
10391
- urls2.map(async (url) => {
10462
+ urls3.map(async (url) => {
10392
10463
  const res = await alibabaFetch(ctx, url, {});
10393
10464
  if (!res.ok) throw alibabaError(res.status, await res.text().catch(() => ""), modelId);
10394
10465
  const mime = res.headers.get("content-type") ?? "image/png";
10395
10466
  return { bytes: new Uint8Array(await res.arrayBuffer()), mime };
10396
10467
  })
10397
10468
  );
10398
- const usage6 = {
10469
+ const usage7 = {
10399
10470
  model: modelId,
10400
10471
  provider: "alibaba",
10401
10472
  modality: "IMAGE",
@@ -10403,9 +10474,9 @@ async function generateAlibabaImage(req, ctx) {
10403
10474
  quantity: data.usage?.output_image_count ?? images.length
10404
10475
  };
10405
10476
  const tier = billedTier(data.usage?.output_image_type, req.size);
10406
- if (tier !== void 0) usage6.imageSize = tier;
10407
- if (req.quality !== void 0) usage6.imageQuality = req.quality;
10408
- 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 };
10409
10480
  }
10410
10481
 
10411
10482
  // src/adapters/alibaba-video.ts
@@ -10867,17 +10938,17 @@ var RENDERED = /* @__PURE__ */ new Map([
10867
10938
  [720, "720p"],
10868
10939
  [1080, "1080p"]
10869
10940
  ]);
10870
- function settleUsage(usage6, task) {
10941
+ function settleUsage(usage7, task) {
10871
10942
  const reported = task.usage;
10872
10943
  if (reported?.duration !== void 0 && reported.duration > 0) {
10873
- usage6.quantity = reported.duration;
10944
+ usage7.quantity = reported.duration;
10874
10945
  }
10875
10946
  const output = reported?.output_video_duration;
10876
- if (output !== void 0 && output > 0) usage6.durationSeconds = output;
10947
+ if (output !== void 0 && output > 0) usage7.durationSeconds = output;
10877
10948
  const rendered = reported?.SR === void 0 ? void 0 : RENDERED.get(reported.SR);
10878
- if (rendered !== void 0) usage6.resolution = rendered;
10949
+ if (rendered !== void 0) usage7.resolution = rendered;
10879
10950
  }
10880
- function alibabaVideoJob(ctx, jobId, usage6) {
10951
+ function alibabaVideoJob(ctx, jobId, usage7) {
10881
10952
  const { key } = alibabaCredentials(ctx);
10882
10953
  const modelId = ctx.model.id;
10883
10954
  const fetchTask = async () => {
@@ -10921,10 +10992,10 @@ function alibabaVideoJob(ctx, jobId, usage6) {
10921
10992
  if (!url) {
10922
10993
  throw alibabaError(void 0, "task succeeded with no video_url", modelId);
10923
10994
  }
10924
- settleUsage(usage6, task);
10995
+ settleUsage(usage7, task);
10925
10996
  return {
10926
10997
  video: { url, expiresAt: new Date(Date.now() + VIDEO_URL_TTL_MS) },
10927
- usage: usage6,
10998
+ usage: usage7,
10928
10999
  raw: task
10929
11000
  };
10930
11001
  }
@@ -11098,7 +11169,7 @@ function throwArkError(status, body, model, code = arkErrorCode(body)) {
11098
11169
  const parsed = z10.string().safeParse(body);
11099
11170
  const text2 = parsed.success ? parsed.data : JSON.stringify(body ?? "");
11100
11171
  if (/sensitive.?content|human.?face/i.test(`${code ?? ""} ${text2}`)) {
11101
- const init = {
11172
+ const init2 = {
11102
11173
  code: "content_blocked",
11103
11174
  message: `ark rejected the request: ${text2.slice(0, 500)}`,
11104
11175
  provider: "ark",
@@ -11106,12 +11177,12 @@ function throwArkError(status, body, model, code = arkErrorCode(body)) {
11106
11177
  body,
11107
11178
  retryable: false
11108
11179
  };
11109
- if (status !== void 0) init.status = status;
11110
- throw new ModelKitError(init);
11180
+ if (status !== void 0) init2.status = status;
11181
+ throw new ModelKitError(init2);
11111
11182
  }
11112
11183
  const rule = arkCodeRule(status, code);
11113
11184
  if (rule || status === void 0) {
11114
- const init = {
11185
+ const init2 = {
11115
11186
  code: rule?.code ?? "provider_rejected",
11116
11187
  message: `ark rejected the request${code ? ` (${code})` : ""}: ${text2.slice(0, 500)}`,
11117
11188
  provider: "ark",
@@ -11119,8 +11190,8 @@ function throwArkError(status, body, model, code = arkErrorCode(body)) {
11119
11190
  body,
11120
11191
  retryable: false
11121
11192
  };
11122
- if (status !== void 0) init.status = status;
11123
- throw new ModelKitError(init);
11193
+ if (status !== void 0) init2.status = status;
11194
+ throw new ModelKitError(init2);
11124
11195
  }
11125
11196
  throw classifyHttpError(status, body, "ark", model);
11126
11197
  }
@@ -11144,12 +11215,12 @@ var SeedreamResponseSchema = z10.object({
11144
11215
  data: z10.array(SeedreamImageSchema).optional(),
11145
11216
  error: z10.object({ message: z10.string().optional(), code: z10.string().optional() }).optional()
11146
11217
  });
11147
- function fetchInitFor(ctx, init) {
11148
- if (ctx.signal !== void 0) init.signal = ctx.signal;
11149
- return init;
11218
+ function fetchInitFor(ctx, init2) {
11219
+ if (ctx.signal !== void 0) init2.signal = ctx.signal;
11220
+ return init2;
11150
11221
  }
11151
- function arkFetch(ctx, url, init) {
11152
- 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) => {
11153
11224
  throw classifyThrown("ark", cause, ctx.model.id);
11154
11225
  });
11155
11226
  }
@@ -11226,16 +11297,16 @@ async function generateSeedreamImage(req, ctx) {
11226
11297
  } else {
11227
11298
  throwArkError(void 0, "Seedream returned no image URL or base64 data", modelId);
11228
11299
  }
11229
- const usage6 = {
11300
+ const usage7 = {
11230
11301
  model: modelId,
11231
11302
  provider: "ark",
11232
11303
  modality: "IMAGE",
11233
11304
  unit: "images",
11234
11305
  quantity: 1
11235
11306
  };
11236
- if (req.size !== void 0) usage6.imageSize = req.size;
11237
- if (req.quality !== void 0) usage6.imageQuality = req.quality;
11238
- 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 };
11239
11310
  }
11240
11311
  var SeedanceUsageSchema = z10.object({
11241
11312
  total_tokens: z10.number().optional(),
@@ -11290,7 +11361,7 @@ function seedanceErrorCode(error) {
11290
11361
  const parsed = SeedanceErrorSchema.safeParse(error);
11291
11362
  return parsed.success ? parsed.data.code : void 0;
11292
11363
  }
11293
- function seedanceJob(ctx, key, jobId, usage6) {
11364
+ function seedanceJob(ctx, key, jobId, usage7) {
11294
11365
  const modelId = ctx.model.id;
11295
11366
  const fetchStatus = async () => {
11296
11367
  const res = await arkFetch(ctx, `${arkBaseUrl(ctx)}${SUBMIT_PATH2}/${jobId}`, {
@@ -11340,21 +11411,21 @@ function seedanceJob(ctx, key, jobId, usage6) {
11340
11411
  modelId
11341
11412
  );
11342
11413
  if (polled.duration !== void 0 && polled.duration > 0) {
11343
- usage6.quantity = polled.duration;
11344
- usage6.durationSeconds = polled.duration;
11414
+ usage7.quantity = polled.duration;
11415
+ usage7.durationSeconds = polled.duration;
11345
11416
  }
11346
11417
  const rendered = VideoResolutionSchema.safeParse(
11347
11418
  polled.resolution?.toLowerCase()
11348
11419
  );
11349
- if (rendered.success) usage6.resolution = rendered.data;
11420
+ if (rendered.success) usage7.resolution = rendered.data;
11350
11421
  const tokens = polled.usage;
11351
11422
  if (tokens?.total_tokens !== void 0 && tokens.completion_tokens !== void 0) {
11352
- usage6.inputTokens = tokens.total_tokens - tokens.completion_tokens;
11353
- usage6.outputTokens = tokens.completion_tokens;
11423
+ usage7.inputTokens = tokens.total_tokens - tokens.completion_tokens;
11424
+ usage7.outputTokens = tokens.completion_tokens;
11354
11425
  }
11355
11426
  return {
11356
11427
  video: { url, expiresAt: new Date(Date.now() + VIDEO_URL_TTL_MS2) },
11357
- usage: usage6,
11428
+ usage: usage7,
11358
11429
  raw: polled
11359
11430
  };
11360
11431
  }
@@ -11507,8 +11578,8 @@ async function generateSeedanceVideo(req, ctx) {
11507
11578
  if (req.watermark !== void 0) body.watermark = req.watermark;
11508
11579
  if (ctx.model.constraints.draft) body.draft = true;
11509
11580
  const jobId = await submitSeedanceTask(ctx, key, body);
11510
- const usage6 = seedanceUsage(ctx, req, taskType === "edit" ? requestedDuration : duration);
11511
- return seedanceJob(ctx, key, jobId, usage6);
11581
+ const usage7 = seedanceUsage(ctx, req, taskType === "edit" ? requestedDuration : duration);
11582
+ return seedanceJob(ctx, key, jobId, usage7);
11512
11583
  }
11513
11584
 
11514
11585
  // src/adapters/fal.ts
@@ -11652,15 +11723,15 @@ function gatewayConfig(ctx) {
11652
11723
  if (ctx.signal !== void 0) config.signal = ctx.signal;
11653
11724
  return config;
11654
11725
  }
11655
- async function gatewayFetch(cfg, fetchImpl, targetUrl, init) {
11726
+ async function gatewayFetch(cfg, fetchImpl, targetUrl, init2) {
11656
11727
  const headers2 = { "x-fal-target-url": targetUrl };
11657
11728
  if (cfg.falKey) headers2.Authorization = `Bearer ${cfg.falKey}`;
11658
- if (init.body) headers2["Content-Type"] = "application/json";
11729
+ if (init2.body) headers2["Content-Type"] = "application/json";
11659
11730
  if (cfg.cfToken) headers2["cf-aig-authorization"] = `Bearer ${cfg.cfToken}`;
11660
11731
  if (cfg.singleAttempt) headers2["cf-aig-max-attempts"] = "1";
11661
- const request = { method: init.method, headers: headers2 };
11732
+ const request = { method: init2.method, headers: headers2 };
11662
11733
  if (cfg.signal !== void 0) request.signal = cfg.signal;
11663
- if (init.body !== void 0) request.body = init.body;
11734
+ if (init2.body !== void 0) request.body = init2.body;
11664
11735
  return fetchImpl(cfg.baseUrl, request);
11665
11736
  }
11666
11737
 
@@ -12651,7 +12722,7 @@ async function collectFalPlanImages(payload, plan5, ctx, req) {
12651
12722
  return { bytes, mime: mime || "image/png" };
12652
12723
  })
12653
12724
  );
12654
- const usage6 = {
12725
+ const usage7 = {
12655
12726
  model: ctx.model.id,
12656
12727
  provider: "fal",
12657
12728
  modality: "IMAGE",
@@ -12659,9 +12730,9 @@ async function collectFalPlanImages(payload, plan5, ctx, req) {
12659
12730
  quantity: images.length
12660
12731
  };
12661
12732
  const billedSize = plan5.imageSize ?? req.size;
12662
- if (billedSize !== void 0 && ctx.model.type === "image") usage6.imageSize = billedSize;
12663
- if (plan5.imageQuality !== void 0) usage6.imageQuality = plan5.imageQuality;
12664
- 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 };
12665
12736
  const remote = files.find((f) => !f.url.startsWith("data:"));
12666
12737
  if (remote !== void 0) result.outputUrl = remote.url;
12667
12738
  return result;
@@ -14402,14 +14473,14 @@ async function collectFalImages(payload, ctx, req, label) {
14402
14473
  retryable: false
14403
14474
  });
14404
14475
  }
14405
- const usage6 = imageUsage(ctx, req, delivered.length);
14476
+ const usage7 = imageUsage(ctx, req, delivered.length);
14406
14477
  if (isIdeogram46(ctx.model.providerModelId)) {
14407
14478
  const billed = ideogramBilledSize(delivered, req.size);
14408
- if (billed !== void 0) usage6.imageSize = billed;
14479
+ if (billed !== void 0) usage7.imageSize = billed;
14409
14480
  }
14410
14481
  return {
14411
14482
  images: delivered.map(({ bytes, mime }) => ({ bytes, mime })),
14412
- usage: usage6,
14483
+ usage: usage7,
14413
14484
  raw: payload
14414
14485
  };
14415
14486
  }
@@ -14744,13 +14815,13 @@ function classifyResponse(ctx, status, body) {
14744
14815
  }
14745
14816
  return error;
14746
14817
  }
14747
- async function elevenLabsFetch(ctx, path, init) {
14818
+ async function elevenLabsFetch(ctx, path, init2) {
14748
14819
  throwIfAborted(ctx.signal);
14749
14820
  const request = {
14750
- method: init.method,
14751
- headers: { "xi-api-key": elevenLabsKey(ctx), ...init.headers }
14821
+ method: init2.method,
14822
+ headers: { "xi-api-key": elevenLabsKey(ctx), ...init2.headers }
14752
14823
  };
14753
- if (init.body !== void 0) request.body = init.body;
14824
+ if (init2.body !== void 0) request.body = init2.body;
14754
14825
  if (ctx.signal !== void 0) request.signal = ctx.signal;
14755
14826
  let res;
14756
14827
  try {
@@ -15040,13 +15111,13 @@ function fishKey(ctx) {
15040
15111
  function fishUrl(ctx, path) {
15041
15112
  return `${ctx.endpoints?.fish ?? DEFAULT_BASE_URL2}${path}`;
15042
15113
  }
15043
- async function fishFetch(ctx, path, init) {
15114
+ async function fishFetch(ctx, path, init2) {
15044
15115
  throwIfAborted(ctx.signal);
15045
15116
  const request = {
15046
- method: init.method,
15047
- headers: { Authorization: `Bearer ${fishKey(ctx)}`, ...init.headers }
15117
+ method: init2.method,
15118
+ headers: { Authorization: `Bearer ${fishKey(ctx)}`, ...init2.headers }
15048
15119
  };
15049
- if (init.body !== void 0) request.body = init.body;
15120
+ if (init2.body !== void 0) request.body = init2.body;
15050
15121
  if (ctx.signal !== void 0) request.signal = ctx.signal;
15051
15122
  let res;
15052
15123
  try {
@@ -15297,13 +15368,13 @@ function googleKey(ctx) {
15297
15368
  if (!key) throw refuse(ctx, "auth", "Missing Google API key");
15298
15369
  return key;
15299
15370
  }
15300
- async function googleFetch(ctx, path, init) {
15371
+ async function googleFetch(ctx, path, init2) {
15301
15372
  throwIfAborted(ctx.signal);
15302
15373
  const request = {
15303
- method: init.method,
15374
+ method: init2.method,
15304
15375
  headers: { "x-goog-api-key": googleKey(ctx), "Content-Type": "application/json" }
15305
15376
  };
15306
- if (init.body !== void 0) request.body = JSON.stringify(init.body);
15377
+ if (init2.body !== void 0) request.body = JSON.stringify(init2.body);
15307
15378
  if (ctx.signal !== void 0) request.signal = ctx.signal;
15308
15379
  let res;
15309
15380
  try {
@@ -15525,20 +15596,20 @@ function fileNameFromUri(fileUri, model) {
15525
15596
  return name;
15526
15597
  }
15527
15598
  function oversizeError(bytes, label, model) {
15528
- const init = {
15599
+ const init2 = {
15529
15600
  code: "unsupported_option",
15530
15601
  message: `${label}: source is ${bytes} bytes, over the Files API limit of ${GOOGLE_FILES_MAX_BYTES}`,
15531
15602
  provider: "google-genai",
15532
15603
  retryable: false
15533
15604
  };
15534
- if (model !== void 0) init.model = model;
15535
- return new ModelKitError(init);
15605
+ if (model !== void 0) init2.model = model;
15606
+ return new ModelKitError(init2);
15536
15607
  }
15537
15608
  async function resolveSource(source2, fetchImpl, signal, label, model) {
15538
15609
  if ("bytes" in source2) return { bytes: source2.bytes, mimeType: source2.mime };
15539
- const init = {};
15540
- if (signal !== void 0) init.signal = signal;
15541
- 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);
15542
15613
  if (!res.ok) {
15543
15614
  const text2 = await res.text().catch(() => "");
15544
15615
  throw classifyHttpError(res.status, text2, "google-genai", model);
@@ -15644,11 +15715,11 @@ async function waitForActive(fileName3, opts) {
15644
15715
  throw classifyHttpError(res.status, text2, "google-genai", opts.model);
15645
15716
  }, pollOptions2);
15646
15717
  }
15647
- async function deleteGoogleFile(fileName3, apiKey, fetchImpl) {
15718
+ async function deleteGoogleFile(fileName3, apiKey2, fetchImpl) {
15648
15719
  try {
15649
15720
  await fetchImpl(`${GOOGLE_FILES_BASE}/v1beta/${fileName3}`, {
15650
15721
  method: "DELETE",
15651
- headers: { "x-goog-api-key": apiKey }
15722
+ headers: { "x-goog-api-key": apiKey2 }
15652
15723
  });
15653
15724
  } catch {
15654
15725
  }
@@ -15797,9 +15868,9 @@ function toBase64(bytes) {
15797
15868
  }
15798
15869
  async function resolveMedia(ref, fetchImpl, signal, defaultMime, model) {
15799
15870
  if ("bytes" in ref) return { bytes: ref.bytes, mime: ref.mime };
15800
- const init = {};
15801
- if (signal !== void 0) init.signal = signal;
15802
- 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);
15803
15874
  if (!res.ok) {
15804
15875
  const text2 = await res.text().catch(() => "");
15805
15876
  throw classifyHttpError(res.status, text2, "google-genai", model);
@@ -15809,10 +15880,10 @@ async function resolveMedia(ref, fetchImpl, signal, defaultMime, model) {
15809
15880
  mime: res.headers.get("content-type")?.split(";")[0]?.trim() || defaultMime
15810
15881
  };
15811
15882
  }
15812
- async function downloadVideo(ctx, url, apiKey, signal) {
15813
- const init = { headers: { "x-goog-api-key": apiKey } };
15814
- if (signal !== void 0) init.signal = signal;
15815
- 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);
15816
15887
  if (!res.ok) {
15817
15888
  const text2 = await res.text().catch(() => "");
15818
15889
  throw classifyHttpError(res.status, text2, "google-genai", ctx.model.id);
@@ -15835,7 +15906,7 @@ function videoUsage2(ctx, duration, resolution) {
15835
15906
  return event;
15836
15907
  }
15837
15908
  async function generateVeoVideo(req, ctx, createGenAIClient) {
15838
- const apiKey = googleKey2(ctx);
15909
+ const apiKey2 = googleKey2(ctx);
15839
15910
  const modelId = ctx.model.id;
15840
15911
  const refs = req.referenceImages ?? [];
15841
15912
  if (req.firstFrame && refs.length > 0) {
@@ -15888,7 +15959,7 @@ async function generateVeoVideo(req, ctx, createGenAIClient) {
15888
15959
  }));
15889
15960
  }
15890
15961
  const client2 = createGenAIClient({
15891
- apiKey,
15962
+ apiKey: apiKey2,
15892
15963
  ...ctx.call.maxRetries !== void 0 ? { maxRetries: ctx.call.maxRetries } : {},
15893
15964
  ...ctx.signal !== void 0 ? { signal: ctx.signal } : {}
15894
15965
  });
@@ -15925,7 +15996,7 @@ async function generateVeoVideo(req, ctx, createGenAIClient) {
15925
15996
  }
15926
15997
  };
15927
15998
  const jobId = operation.name ?? crypto.randomUUID();
15928
- const usage6 = videoUsage2(ctx, duration, req.resolution ?? "720p");
15999
+ const usage7 = videoUsage2(ctx, duration, req.resolution ?? "720p");
15929
16000
  return {
15930
16001
  jobId,
15931
16002
  async poll() {
@@ -15963,7 +16034,7 @@ async function generateVeoVideo(req, ctx, createGenAIClient) {
15963
16034
  modelId
15964
16035
  );
15965
16036
  }
15966
- 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 };
15967
16038
  }
15968
16039
  };
15969
16040
  }
@@ -16000,7 +16071,7 @@ function extractOmniVideo(interaction, model) {
16000
16071
  );
16001
16072
  }
16002
16073
  async function generateOmniVideo(req, ctx, createGenAIClient) {
16003
- const apiKey = googleKey2(ctx);
16074
+ const apiKey2 = googleKey2(ctx);
16004
16075
  const modelId = ctx.model.id;
16005
16076
  const providerModelId = ctx.model.providerModelId;
16006
16077
  const extend = req.taskType === "extend";
@@ -16060,7 +16131,7 @@ async function generateOmniVideo(req, ctx, createGenAIClient) {
16060
16131
  if (omniResolution !== void 0) responseFormat.resolution = omniResolution;
16061
16132
  if (req.durationSeconds !== void 0) responseFormat.duration = `${req.durationSeconds}s`;
16062
16133
  const client2 = createGenAIClient({
16063
- apiKey,
16134
+ apiKey: apiKey2,
16064
16135
  ...ctx.call.maxRetries !== void 0 ? { maxRetries: ctx.call.maxRetries } : {},
16065
16136
  ...ctx.signal !== void 0 ? { signal: ctx.signal } : {}
16066
16137
  });
@@ -16068,7 +16139,7 @@ async function generateOmniVideo(req, ctx, createGenAIClient) {
16068
16139
  const uploadedNames = [];
16069
16140
  const uploadOne = async (kind, bytes, mime) => {
16070
16141
  const uploadOptions = {
16071
- apiKey,
16142
+ apiKey: apiKey2,
16072
16143
  fetchImpl: ctx.fetch,
16073
16144
  model: modelId,
16074
16145
  label: "gemini-omni"
@@ -16081,7 +16152,7 @@ async function generateOmniVideo(req, ctx, createGenAIClient) {
16081
16152
  return file.fileUri;
16082
16153
  };
16083
16154
  const cleanupUploads = async () => {
16084
- for (const fileName3 of uploadedNames) await deleteGoogleFile(fileName3, apiKey, ctx.fetch);
16155
+ for (const fileName3 of uploadedNames) await deleteGoogleFile(fileName3, apiKey2, ctx.fetch);
16085
16156
  };
16086
16157
  const callCreate = (input) => client2.interactions.create(
16087
16158
  previousId !== void 0 ? {
@@ -16175,7 +16246,7 @@ async function generateOmniVideo(req, ctx, createGenAIClient) {
16175
16246
  if (!(extend && !chained)) await cleanupUploads();
16176
16247
  }
16177
16248
  const jobId = interaction.id ?? crypto.randomUUID();
16178
- const usage6 = videoUsage2(ctx, duration, omniResolution ?? "720p");
16249
+ const usage7 = videoUsage2(ctx, duration, omniResolution ?? "720p");
16179
16250
  const getInteraction = async () => {
16180
16251
  try {
16181
16252
  const getParams = { stream: false };
@@ -16223,15 +16294,15 @@ async function generateOmniVideo(req, ctx, createGenAIClient) {
16223
16294
  bytes: Buffer.from(video.data, "base64"),
16224
16295
  mime: video.mime_type ?? "video/mp4"
16225
16296
  },
16226
- usage: usage6,
16297
+ usage: usage7,
16227
16298
  raw: done,
16228
16299
  providerRef
16229
16300
  };
16230
16301
  }
16231
16302
  if (video.uri)
16232
16303
  return {
16233
- video: await downloadVideo(ctx, video.uri, apiKey, signal),
16234
- usage: usage6,
16304
+ video: await downloadVideo(ctx, video.uri, apiKey2, signal),
16305
+ usage: usage7,
16235
16306
  raw: done,
16236
16307
  providerRef
16237
16308
  };
@@ -16258,7 +16329,7 @@ function lyriaUsage(ctx, req, meta) {
16258
16329
  return event;
16259
16330
  }
16260
16331
  async function generateLyriaAudio(req, ctx, createGenAIClient) {
16261
- const apiKey = googleKey2(ctx);
16332
+ const apiKey2 = googleKey2(ctx);
16262
16333
  const modelId = ctx.model.id;
16263
16334
  const parts = [{ text: req.prompt }];
16264
16335
  for (const ref of req.references ?? []) {
@@ -16266,7 +16337,7 @@ async function generateLyriaAudio(req, ctx, createGenAIClient) {
16266
16337
  parts.push({ inlineData: { mimeType: image.mime, data: toBase64(image.bytes) } });
16267
16338
  }
16268
16339
  const client2 = createGenAIClient({
16269
- apiKey,
16340
+ apiKey: apiKey2,
16270
16341
  ...ctx.call.maxRetries !== void 0 ? { maxRetries: ctx.call.maxRetries } : {},
16271
16342
  ...ctx.signal !== void 0 ? { signal: ctx.signal } : {}
16272
16343
  });
@@ -16320,14 +16391,14 @@ async function generateLyriaAudio(req, ctx, createGenAIClient) {
16320
16391
  return result;
16321
16392
  }
16322
16393
  async function generateLyriaInteraction(req, ctx, createGenAIClient) {
16323
- const apiKey = googleKey2(ctx);
16394
+ const apiKey2 = googleKey2(ctx);
16324
16395
  const modelId = ctx.model.id;
16325
16396
  const input = [{ type: "text", text: req.prompt }];
16326
16397
  for (const ref of req.references ?? []) {
16327
16398
  const image = await resolveMedia(ref, ctx.fetch, ctx.signal, "image/jpeg", modelId);
16328
16399
  input.push({ type: "image", mime_type: image.mime, data: toBase64(image.bytes) });
16329
16400
  }
16330
- const clientOptions = { apiKey };
16401
+ const clientOptions = { apiKey: apiKey2 };
16331
16402
  if (ctx.call.maxRetries !== void 0) clientOptions.maxRetries = ctx.call.maxRetries;
16332
16403
  if (ctx.signal !== void 0) clientOptions.signal = ctx.signal;
16333
16404
  const client2 = createGenAIClient(clientOptions);
@@ -16380,9 +16451,9 @@ async function prepareGoogleMediaPart(ref, mediaType, ctx) {
16380
16451
  if (ref.bytes.length <= MEDIA_PART_INLINE_LIMIT_BYTES) {
16381
16452
  return { type: "file", data: ref.bytes, mediaType };
16382
16453
  }
16383
- const apiKey = googleKey2(ctx);
16454
+ const apiKey2 = googleKey2(ctx);
16384
16455
  const uploadOptions = {
16385
- apiKey,
16456
+ apiKey: apiKey2,
16386
16457
  fetchImpl: ctx.fetch,
16387
16458
  model: ctx.model.id,
16388
16459
  label: "media-part"
@@ -16394,7 +16465,7 @@ async function prepareGoogleMediaPart(ref, mediaType, ctx) {
16394
16465
  type: "file",
16395
16466
  data: file.fileUri,
16396
16467
  mediaType: file.mimeType,
16397
- cleanup: () => deleteGoogleFile(file.fileName, apiKey, ctx.fetch)
16468
+ cleanup: () => deleteGoogleFile(file.fileName, apiKey2, ctx.fetch)
16398
16469
  };
16399
16470
  }
16400
16471
 
@@ -16429,9 +16500,9 @@ function extractBlockReason(cause) {
16429
16500
  current = parsed.data.cause ?? null;
16430
16501
  }
16431
16502
  }
16432
- function billedTokens(model, usage6) {
16433
- const inputTokens = usage6?.inputTokens;
16434
- const outputTokens = usage6?.outputTokens;
16503
+ function billedTokens(model, usage7) {
16504
+ const inputTokens = usage7?.inputTokens;
16505
+ const outputTokens = usage7?.outputTokens;
16435
16506
  if (inputTokens === void 0 && outputTokens === void 0) return void 0;
16436
16507
  const event = {
16437
16508
  model,
@@ -16465,8 +16536,8 @@ function createGoogleImageAdapter(deps = defaultGoogleImageDeps) {
16465
16536
  return {
16466
16537
  id: "google-image",
16467
16538
  async generateImage(req, ctx) {
16468
- const apiKey = ctx.keys.google;
16469
- if (!apiKey)
16539
+ const apiKey2 = ctx.keys.google;
16540
+ if (!apiKey2)
16470
16541
  throw new ModelKitError({
16471
16542
  code: "auth",
16472
16543
  message: "Missing API key for google",
@@ -16474,7 +16545,7 @@ function createGoogleImageAdapter(deps = defaultGoogleImageDeps) {
16474
16545
  model: ctx.model.id,
16475
16546
  retryable: false
16476
16547
  });
16477
- const google = deps.createGoogleClient({ apiKey, fetch: ctx.fetch });
16548
+ const google = deps.createGoogleClient({ apiKey: apiKey2, fetch: ctx.fetch });
16478
16549
  const model = google(ctx.model.providerModelId);
16479
16550
  const content = [];
16480
16551
  for (const ref of req.references ?? []) {
@@ -16515,7 +16586,7 @@ function createGoogleImageAdapter(deps = defaultGoogleImageDeps) {
16515
16586
  const images = (result.files ?? []).filter((file) => file.mediaType.startsWith("image/")).map((file) => ({ bytes: file.uint8Array, mime: file.mediaType }));
16516
16587
  if (images.length === 0) {
16517
16588
  const filtered = result.finishReason === "content-filter" || result.finishReason === "other";
16518
- const init = {
16589
+ const init2 = {
16519
16590
  code: filtered ? "content_blocked" : "provider_rejected",
16520
16591
  message: `google-image returned no image (finishReason: ${result.finishReason}). ${result.text}`.trim(),
16521
16592
  provider: "google-image",
@@ -16527,12 +16598,12 @@ function createGoogleImageAdapter(deps = defaultGoogleImageDeps) {
16527
16598
  },
16528
16599
  retryable: false
16529
16600
  };
16530
- if (result.finishReason !== void 0) init.finishReason = result.finishReason;
16601
+ if (result.finishReason !== void 0) init2.finishReason = result.finishReason;
16531
16602
  const billed = billedTokens(ctx.model.id, result.usage);
16532
- if (billed !== void 0) init.usage = billed;
16533
- throw new ModelKitError(init);
16603
+ if (billed !== void 0) init2.usage = billed;
16604
+ throw new ModelKitError(init2);
16534
16605
  }
16535
- const usage6 = {
16606
+ const usage7 = {
16536
16607
  model: ctx.model.id,
16537
16608
  provider: "google-image",
16538
16609
  modality: "IMAGE",
@@ -16540,12 +16611,12 @@ function createGoogleImageAdapter(deps = defaultGoogleImageDeps) {
16540
16611
  quantity: images.length,
16541
16612
  imageQuality: "auto"
16542
16613
  };
16543
- if (req.size !== void 0) usage6.imageSize = req.size;
16614
+ if (req.size !== void 0) usage7.imageSize = req.size;
16544
16615
  if (result.usage?.inputTokens !== void 0)
16545
- usage6.inputTokens = result.usage.inputTokens;
16616
+ usage7.inputTokens = result.usage.inputTokens;
16546
16617
  if (result.usage?.outputTokens !== void 0)
16547
- usage6.outputTokens = result.usage.outputTokens;
16548
- return { images, usage: usage6, raw: result };
16618
+ usage7.outputTokens = result.usage.outputTokens;
16619
+ return { images, usage: usage7, raw: result };
16549
16620
  }
16550
16621
  };
16551
16622
  }
@@ -16787,16 +16858,16 @@ function klingErrorDetail(error) {
16787
16858
  if (asObject.success) return asObject.data.message ?? "unknown_error";
16788
16859
  return "unknown_error";
16789
16860
  }
16790
- function requestInit(ctx, init) {
16791
- const request = { method: init.method, headers: headers(ctx) };
16792
- 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;
16793
16864
  if (ctx.signal !== void 0) request.signal = ctx.signal;
16794
16865
  return request;
16795
16866
  }
16796
- async function createRequest(ctx, url, init) {
16867
+ async function createRequest(ctx, url, init2) {
16797
16868
  let res;
16798
16869
  try {
16799
- res = await ctx.fetch(url, requestInit(ctx, init));
16870
+ res = await ctx.fetch(url, requestInit(ctx, init2));
16800
16871
  } catch (cause) {
16801
16872
  throw classifyThrown("higgsfield", cause, ctx.model.id);
16802
16873
  }
@@ -17392,13 +17463,13 @@ function lumaFailure(ctx, code, reason) {
17392
17463
  }
17393
17464
  }
17394
17465
  function requestInit2(ctx, key, body) {
17395
- const init = {
17466
+ const init2 = {
17396
17467
  method: body !== void 0 ? "POST" : "GET",
17397
17468
  headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" }
17398
17469
  };
17399
- if (body !== void 0) init.body = body;
17400
- if (ctx.signal !== void 0) init.signal = ctx.signal;
17401
- return init;
17470
+ if (body !== void 0) init2.body = body;
17471
+ if (ctx.signal !== void 0) init2.signal = ctx.signal;
17472
+ return init2;
17402
17473
  }
17403
17474
  async function lumaRequest(ctx, url, body) {
17404
17475
  const key = lumaKey(ctx);
@@ -17887,8 +17958,8 @@ var openaiImageAdapter = {
17887
17958
  id: "openai-image",
17888
17959
  async generateImage(req, ctx) {
17889
17960
  throwIfAborted(ctx.signal);
17890
- const apiKey = ctx.keys.openai;
17891
- if (!apiKey)
17961
+ const apiKey2 = ctx.keys.openai;
17962
+ if (!apiKey2)
17892
17963
  throw new ModelKitError({
17893
17964
  code: "auth",
17894
17965
  message: "Missing API key for openai",
@@ -17903,7 +17974,7 @@ var openaiImageAdapter = {
17903
17974
  message: "openai-image cannot express reference labels; ignoring them"
17904
17975
  });
17905
17976
  }
17906
- const client2 = new OpenAI({ apiKey, fetch: ctx.fetch, maxRetries: 0 });
17977
+ const client2 = new OpenAI({ apiKey: apiKey2, fetch: ctx.fetch, maxRetries: 0 });
17907
17978
  const size = req.exactSize !== void 0 ? req.exactSize : req.aspectRatio === void 0 || req.aspectRatio === "adaptive" ? void 0 : aspectRatioToSize(req.aspectRatio, req.size ?? "1K");
17908
17979
  const refs = req.references ?? [];
17909
17980
  const isEdit = refs.length > 0;
@@ -17993,7 +18064,7 @@ var openaiImageAdapter = {
17993
18064
  const usageParsed = openaiUsageSchema.safeParse(response.usage);
17994
18065
  const inputTokens = usageParsed.success ? usageParsed.data.input_tokens : void 0;
17995
18066
  const outputTokens = usageParsed.success ? usageParsed.data.output_tokens : void 0;
17996
- const usage6 = {
18067
+ const usage7 = {
17997
18068
  model: ctx.model.id,
17998
18069
  provider: "openai-image",
17999
18070
  modality: "IMAGE",
@@ -18001,10 +18072,10 @@ var openaiImageAdapter = {
18001
18072
  quantity: images.length,
18002
18073
  imageQuality: quality
18003
18074
  };
18004
- if (inputTokens !== void 0) usage6.inputTokens = inputTokens;
18005
- if (outputTokens !== void 0) usage6.outputTokens = outputTokens;
18006
- if (req.size !== void 0) usage6.imageSize = req.size;
18007
- 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 };
18008
18079
  }
18009
18080
  };
18010
18081
 
@@ -18237,13 +18308,13 @@ async function generateProdiaImage(req, ctx) {
18237
18308
  res = await withRetry(async () => {
18238
18309
  let attemptRes;
18239
18310
  try {
18240
- const init = {
18311
+ const init2 = {
18241
18312
  method: "POST",
18242
18313
  headers: { Authorization: `Bearer ${key}`, Accept: accept },
18243
18314
  body: form
18244
18315
  };
18245
- if (ctx.signal !== void 0) init.signal = ctx.signal;
18246
- 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);
18247
18318
  } catch (err) {
18248
18319
  throw classifyThrown("prodia", err, ctx.model.id);
18249
18320
  }
@@ -18260,16 +18331,16 @@ async function generateProdiaImage(req, ctx) {
18260
18331
  new Uint8Array(await res.arrayBuffer()),
18261
18332
  res.headers.get("content-type")
18262
18333
  );
18263
- const usage6 = {
18334
+ const usage7 = {
18264
18335
  model: ctx.model.id,
18265
18336
  provider: "prodia",
18266
18337
  modality: "IMAGE",
18267
18338
  unit: "images",
18268
18339
  quantity: 1
18269
18340
  };
18270
- if (req.size !== void 0) usage6.imageSize = req.size;
18271
- if (req.quality !== void 0) usage6.imageQuality = req.quality;
18272
- 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 };
18273
18344
  }
18274
18345
  var prodiaAdapter = {
18275
18346
  id: "prodia",
@@ -18725,9 +18796,9 @@ async function generateReplicateImage(req, ctx, deps) {
18725
18796
  }
18726
18797
  const { url, predictTime, raw } = await runPrediction(ctx, input, deps);
18727
18798
  const file = await download(ctx, url);
18728
- const usage6 = imageUsage3(ctx, req);
18729
- usage6.quantity = predictTime;
18730
- 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 };
18731
18802
  }
18732
18803
  function klingInput(req) {
18733
18804
  const images = (req.firstFrame ? [req.firstFrame] : []).map(refToUrl);
@@ -18851,9 +18922,9 @@ async function generateReplicateVideo(req, ctx, deps) {
18851
18922
  return void 0;
18852
18923
  };
18853
18924
  const toResult = (done) => {
18854
- const usage6 = videoUsage5(ctx, req);
18855
- usage6.quantity = done.predictTime;
18856
- 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 };
18857
18928
  };
18858
18929
  return {
18859
18930
  jobId,
@@ -18960,23 +19031,277 @@ async function generateReplicateAudio(req, ctx, deps) {
18960
19031
  input = specResult.input;
18961
19032
  }
18962
19033
  const { url, predictTime, raw } = await runPrediction(ctx, input, deps);
18963
- const usage6 = audioUsage(ctx, req);
19034
+ const usage7 = audioUsage(ctx, req);
18964
19035
  if (ctx.model.usage.unit === "seconds") {
18965
19036
  const seconds3 = elevenLabsMusicDuration(req.durationSeconds);
18966
- usage6.quantity = seconds3;
18967
- usage6.durationSeconds = seconds3;
19037
+ usage7.quantity = seconds3;
19038
+ usage7.durationSeconds = seconds3;
19039
+ } else {
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");
18968
19089
  } else {
18969
- usage6.quantity = predictTime;
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";
18970
19141
  }
18971
- return { audio: { url }, usage: usage6, raw: predictionRaw(raw) };
19142
+ const parsed = taskSchema.safeParse(raw);
19143
+ return parsed.success ? parsed.data : void 0;
18972
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;
19175
+ }
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;
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
+ };
18973
19298
 
18974
19299
  // src/adapters/xai-video.ts
18975
19300
  import { experimental_generateVideo } from "ai";
18976
19301
  import { createXai as createXai2 } from "@ai-sdk/xai";
18977
- import { z as z35 } from "zod";
18978
- var POLL_INTERVAL_MS3 = 1e4;
18979
- 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;
18980
19305
  var defaultXaiDeps = {
18981
19306
  createXaiClient: () => ({ generateVideo: experimental_generateVideo })
18982
19307
  };
@@ -18987,8 +19312,8 @@ function createXaiVideoAdapter(deps = defaultXaiDeps) {
18987
19312
  };
18988
19313
  }
18989
19314
  var xaiVideoAdapter = createXaiVideoAdapter();
18990
- var xaiResponseStatusSchema = z35.object({
18991
- response: z35.object({ status: z35.number() }).partial()
19315
+ var xaiResponseStatusSchema = z36.object({
19316
+ response: z36.object({ status: z36.number() }).partial()
18992
19317
  });
18993
19318
  function xaiError(cause, ctx) {
18994
19319
  const info = describeThrown(cause);
@@ -18996,12 +19321,12 @@ function xaiError(cause, ctx) {
18996
19321
  const status = info.status ?? (nested.success ? nested.data.response?.status : void 0);
18997
19322
  return classifyThrown("xai-video", cause, ctx.model.id, { status, body: info.body });
18998
19323
  }
18999
- var xaiMetaSchema = z35.object({
19324
+ var xaiMetaSchema = z36.object({
19000
19325
  videoUrl: JsonValueSchema.optional(),
19001
19326
  costInUsdTicks: JsonValueSchema.optional(),
19002
19327
  duration: JsonValueSchema.optional()
19003
19328
  });
19004
- var xaiProviderMetadataSchema = z35.object({ xai: xaiMetaSchema });
19329
+ var xaiProviderMetadataSchema = z36.object({ xai: xaiMetaSchema });
19005
19330
  function metaOf(result) {
19006
19331
  const parsed = xaiProviderMetadataSchema.partial().safeParse(result.providerMetadata);
19007
19332
  if (!parsed.success) return {};
@@ -19009,8 +19334,8 @@ function metaOf(result) {
19009
19334
  }
19010
19335
  var SDK_REFERENCE_CAP = 7;
19011
19336
  async function generateXaiVideo(req, ctx, deps) {
19012
- const apiKey = ctx.keys.xai;
19013
- if (!apiKey) {
19337
+ const apiKey2 = ctx.keys.xai;
19338
+ if (!apiKey2) {
19014
19339
  throw new ModelKitError({
19015
19340
  code: "auth",
19016
19341
  message: "Missing API key for xai",
@@ -19025,8 +19350,8 @@ async function generateXaiVideo(req, ctx, deps) {
19025
19350
  const takesLastFrame = (ctx.model.constraints.supports ?? []).includes("lastFrame");
19026
19351
  const lastFrame = takesLastFrame && req.lastFrame ? refToUrl(req.lastFrame) : void 0;
19027
19352
  const xaiOptions = {
19028
- pollIntervalMs: POLL_INTERVAL_MS3,
19029
- pollTimeoutMs: POLL_TIMEOUT_MS2
19353
+ pollIntervalMs: POLL_INTERVAL_MS4,
19354
+ pollTimeoutMs: POLL_TIMEOUT_MS3
19030
19355
  };
19031
19356
  const resolution = xaiResolution(req, ctx, refs);
19032
19357
  if (resolution !== void 0) xaiOptions.resolution = resolution;
@@ -19046,8 +19371,8 @@ async function generateXaiVideo(req, ctx, deps) {
19046
19371
  message: "xai-video does not support lastFrame; ignored"
19047
19372
  });
19048
19373
  }
19049
- const client2 = deps.createXaiClient({ apiKey });
19050
- 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);
19051
19376
  const callBody = {
19052
19377
  model,
19053
19378
  prompt: req.prompt,
@@ -19100,8 +19425,8 @@ async function generateXaiVideo(req, ctx, deps) {
19100
19425
  async result(opts) {
19101
19426
  const resultSignal = opts?.signal ?? ctx.signal;
19102
19427
  const resultOpts = {
19103
- intervalMs: opts?.pollIntervalMs ?? POLL_INTERVAL_MS3,
19104
- timeoutMs: opts?.timeoutMs ?? POLL_TIMEOUT_MS2
19428
+ intervalMs: opts?.pollIntervalMs ?? POLL_INTERVAL_MS4,
19429
+ timeoutMs: opts?.timeoutMs ?? POLL_TIMEOUT_MS3
19105
19430
  };
19106
19431
  if (resultSignal) resultOpts.signal = resultSignal;
19107
19432
  return pollUntil(check, resultOpts);
@@ -19113,12 +19438,12 @@ async function mapResult(ctx, req, result) {
19113
19438
  if (first) {
19114
19439
  return {
19115
19440
  video: { bytes: Uint8Array.from(first.uint8Array), mime: first.mediaType },
19116
- usage: usage5(ctx, req, metaOf(result)),
19441
+ usage: usage6(ctx, req, metaOf(result)),
19117
19442
  raw: result.providerMetadata
19118
19443
  };
19119
19444
  }
19120
19445
  const meta = metaOf(result);
19121
- const videoUrl = z35.string().safeParse(meta.videoUrl);
19446
+ const videoUrl = z36.string().safeParse(meta.videoUrl);
19122
19447
  if (videoUrl.success && videoUrl.data) {
19123
19448
  const res = await ctx.fetch(videoUrl.data);
19124
19449
  if (!res.ok) {
@@ -19128,7 +19453,7 @@ async function mapResult(ctx, req, result) {
19128
19453
  const mime = res.headers.get("content-type") ?? "video/mp4";
19129
19454
  return {
19130
19455
  video: { bytes: new Uint8Array(await res.arrayBuffer()), mime },
19131
- usage: usage5(ctx, req, meta),
19456
+ usage: usage6(ctx, req, meta),
19132
19457
  raw: result.providerMetadata
19133
19458
  };
19134
19459
  }
@@ -19140,8 +19465,8 @@ async function mapResult(ctx, req, result) {
19140
19465
  retryable: false
19141
19466
  });
19142
19467
  }
19143
- function usage5(ctx, req, meta) {
19144
- const costTicks = z35.number().safeParse(meta.costInUsdTicks);
19468
+ function usage6(ctx, req, meta) {
19469
+ const costTicks = z36.number().safeParse(meta.costInUsdTicks);
19145
19470
  const cost = costTicks.success ? costTicks.data / 1e10 : void 0;
19146
19471
  const event = {
19147
19472
  model: ctx.model.id,
@@ -19183,7 +19508,8 @@ var DEFAULT_ADAPTERS = {
19183
19508
  luma: lumaAdapter,
19184
19509
  alibaba: alibabaAdapter,
19185
19510
  fish: fishAdapter,
19186
- elevenlabs: elevenLabsAdapter
19511
+ elevenlabs: elevenLabsAdapter,
19512
+ wavespeed: wavespeedAdapter
19187
19513
  };
19188
19514
 
19189
19515
  // src/catalog/data-only.ts
@@ -19326,6 +19652,10 @@ function dataOnlyCapable(row2) {
19326
19652
  const reason = elevenLabsRowRefusal(row2);
19327
19653
  return reason === void 0 ? { ok: true } : { ok: false, reason };
19328
19654
  }
19655
+ case "wavespeed": {
19656
+ const reason = wavespeedRowRefusal(row2);
19657
+ return reason === void 0 ? { ok: true } : { ok: false, reason };
19658
+ }
19329
19659
  default: {
19330
19660
  return assertNever(row2.adapter);
19331
19661
  }
@@ -19345,22 +19675,22 @@ var liveState = store[KEY] ??= {
19345
19675
  var liveCatalog = liveState.catalog;
19346
19676
 
19347
19677
  // src/catalog/load.ts
19348
- import { z as z36 } from "zod";
19678
+ import { z as z37 } from "zod";
19349
19679
  function rowCount() {
19350
19680
  return liveCatalog.list({ lifecycle: ["active", "deprecated", "retired"] }).length;
19351
19681
  }
19352
19682
  function authHeaders2(auth) {
19353
19683
  return "bearer" in auth ? { Authorization: `Bearer ${auth.bearer}` } : { "x-api-key": auth.apiKey };
19354
19684
  }
19355
- var EnvelopeSchema = z36.object({
19356
- rows: z36.array(JsonValueSchema),
19357
- revision: z36.string().optional()
19685
+ var EnvelopeSchema = z37.object({
19686
+ rows: z37.array(JsonValueSchema),
19687
+ revision: z37.string().optional()
19358
19688
  });
19359
19689
  function dropReason(path, message) {
19360
19690
  return path.length === 0 ? message : `${path.map((part) => String(part)).join(".")} ${message}`;
19361
19691
  }
19362
19692
  function rowId(raw) {
19363
- 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);
19364
19694
  if (!parsed.success) return "?";
19365
19695
  return parsed.data.id;
19366
19696
  }
@@ -19577,7 +19907,7 @@ function fileCatalogCache(path) {
19577
19907
  }
19578
19908
 
19579
19909
  // src/catalog/input-billing.ts
19580
- import { z as z37 } from "zod";
19910
+ import { z as z38 } from "zod";
19581
19911
  var DATA_ONLY_INPUT_BILLING = /* @__PURE__ */ new Map([
19582
19912
  ["flux-3", "source-video-rate"]
19583
19913
  ]);
@@ -19586,7 +19916,7 @@ var KIT_INPUT_BILLING = new Map(
19586
19916
  (row2) => row2.constraints.inputBilling ? [[row2.id, row2.constraints.inputBilling]] : []
19587
19917
  )
19588
19918
  );
19589
- var ConstraintsReadView2 = z37.looseObject({
19919
+ var ConstraintsReadView2 = z38.looseObject({
19590
19920
  inputBilling: InputBillingSchema.optional().catch(void 0)
19591
19921
  });
19592
19922
  function inputBillingOf(row2) {
@@ -20891,7 +21221,8 @@ var ADAPTER_KEYS = {
20891
21221
  luma: ["luma"],
20892
21222
  alibaba: ["alibaba"],
20893
21223
  fish: ["fish"],
20894
- elevenlabs: ["elevenlabs"]
21224
+ elevenlabs: ["elevenlabs"],
21225
+ wavespeed: ["wavespeed"]
20895
21226
  };
20896
21227
  var PAIRED = {
20897
21228
  higgsfield: "higgsfieldSecret",
@@ -20995,6 +21326,7 @@ function keysFromEnv(env, prefix = "") {
20995
21326
  set("alibabaWorkspace", pick2("DASHSCOPE_WORKSPACE_ID"));
20996
21327
  set("fish", pick2("FISH_AUDIO_API_KEY"));
20997
21328
  set("elevenlabs", pick2("ELEVENLABS_API_KEY"));
21329
+ set("wavespeed", pick2("WAVESPEED_API_KEY"));
20998
21330
  set("cloudflare", pick2("CF_AIG_TOKEN"));
20999
21331
  const bearer2 = pick2("AWS_BEARER_TOKEN_BEDROCK");
21000
21332
  const accessKeyId = pick2("AWS_ACCESS_KEY_ID");
@@ -21049,12 +21381,12 @@ function modelsPoweredBy(provider, catalog) {
21049
21381
  function keyOverrideFor(secrets) {
21050
21382
  const override = {};
21051
21383
  for (const provider of Object.values(BYOK_PROVIDERS)) {
21052
- const apiKey = secrets[provider.id]?.apiKey?.trim();
21053
- if (apiKey) override[provider.keyName] = apiKey;
21384
+ const apiKey2 = secrets[provider.id]?.apiKey?.trim();
21385
+ if (apiKey2) override[provider.keyName] = apiKey2;
21054
21386
  }
21055
21387
  return override;
21056
21388
  }
21057
- var bearer = (apiKey) => ({ Authorization: `Bearer ${apiKey}` });
21389
+ var bearer = (apiKey2) => ({ Authorization: `Bearer ${apiKey2}` });
21058
21390
  var PROBES = {
21059
21391
  ark: {
21060
21392
  url: (endpoints) => `${endpoints.ark ?? ARK_BASE_URL}/contents/generations/tasks?page_num=1&page_size=1`,
@@ -21062,7 +21394,7 @@ var PROBES = {
21062
21394
  },
21063
21395
  fal: {
21064
21396
  url: () => "https://api.fal.ai/v1/assets/collections?limit=1",
21065
- headers: (apiKey) => ({ Authorization: `Key ${apiKey}` }),
21397
+ headers: (apiKey2) => ({ Authorization: `Key ${apiKey2}` }),
21066
21398
  unverifiableStatus: 403
21067
21399
  },
21068
21400
  replicate: {
@@ -21076,20 +21408,20 @@ var PROBES = {
21076
21408
  },
21077
21409
  google: {
21078
21410
  url: () => "https://generativelanguage.googleapis.com/v1beta/models?pageSize=1",
21079
- headers: (apiKey) => ({ "x-goog-api-key": apiKey }),
21411
+ headers: (apiKey2) => ({ "x-goog-api-key": apiKey2 }),
21080
21412
  unverifiableStatus: 403
21081
21413
  }
21082
21414
  };
21083
21415
  async function testProviderKey(provider, secret, opts = {}) {
21084
- const apiKey = secret.apiKey?.trim();
21085
- if (!apiKey) return { ok: false, reason: "invalid" };
21416
+ const apiKey2 = secret.apiKey?.trim();
21417
+ if (!apiKey2) return { ok: false, reason: "invalid" };
21086
21418
  const probe = PROBES[provider];
21087
21419
  const fetchImpl = opts.fetch ?? globalThis.fetch;
21088
21420
  let res;
21089
21421
  try {
21090
21422
  res = await fetchImpl(probe.url(opts.endpoints ?? {}), {
21091
21423
  method: "GET",
21092
- headers: probe.headers(apiKey),
21424
+ headers: probe.headers(apiKey2),
21093
21425
  ...opts.signal !== void 0 && { signal: opts.signal }
21094
21426
  });
21095
21427
  } catch (cause) {
@@ -21106,7 +21438,7 @@ async function testProviderKey(provider, secret, opts = {}) {
21106
21438
 
21107
21439
  // src/text.ts
21108
21440
  import "ai";
21109
- import { z as z38 } from "zod";
21441
+ import { z as z39 } from "zod";
21110
21442
  function mergeTextProviderOptions(catalog, caller) {
21111
21443
  const merged = {};
21112
21444
  const catalogOptions = catalog.providerOptions ?? {};
@@ -21145,17 +21477,17 @@ function passthroughTextModel(model) {
21145
21477
  pricingKind: "token"
21146
21478
  };
21147
21479
  }
21148
- var perplexityCostSchema = z38.object({
21149
- 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() }) })
21150
21482
  });
21151
21483
  function reportedCostUsd(metadata) {
21152
21484
  const parsed = perplexityCostSchema.safeParse(metadata);
21153
21485
  return parsed.success ? parsed.data.perplexity.cost.totalCost : void 0;
21154
21486
  }
21155
- function textUsageEvent(model, provider, usage6, providerMetadata) {
21156
- const inputTokens = usage6.inputTokens ?? 0;
21157
- const outputTokens = usage6.outputTokens ?? 0;
21158
- 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;
21159
21491
  const event = {
21160
21492
  model: model.id,
21161
21493
  provider,
@@ -21190,7 +21522,7 @@ function createTextSteps(initial, resolve, callerProviderOptions) {
21190
21522
  return { ...prepared, providerOptions };
21191
21523
  };
21192
21524
  }
21193
- function usage6(results) {
21525
+ function usage7(results) {
21194
21526
  const grouped = /* @__PURE__ */ new Map();
21195
21527
  for (const [index, step] of results.entries()) {
21196
21528
  const target = steps.get(index) ?? initial;
@@ -21212,7 +21544,7 @@ function createTextSteps(initial, resolve, callerProviderOptions) {
21212
21544
  }
21213
21545
  return [...grouped.values()];
21214
21546
  }
21215
- return { wrap, usage: usage6 };
21547
+ return { wrap, usage: usage7 };
21216
21548
  }
21217
21549
 
21218
21550
  // src/client.ts
@@ -21224,7 +21556,7 @@ import {
21224
21556
  streamObject as aiStreamObject2,
21225
21557
  streamText as aiStreamText2
21226
21558
  } from "ai";
21227
- import { z as z39 } from "zod";
21559
+ import { z as z40 } from "zod";
21228
21560
 
21229
21561
  // src/generated-image.ts
21230
21562
  function toGeneratedImage(image) {
@@ -21346,9 +21678,9 @@ function providerJobMethods(kind, deps) {
21346
21678
  const { methods, adapter, ctx } = target(sub.model, rest);
21347
21679
  if (!methods.result) throw missing3(adapter, ctx.model);
21348
21680
  const result = await methods.result(sub, ctx, webhook);
21349
- const usage6 = deps.rowUsage(ctx, result.usage, sub.submittedAt);
21350
- await deps.emit(usage6);
21351
- return { ...result, usage: usage6 };
21681
+ const usage7 = deps.rowUsage(ctx, result.usage, sub.submittedAt);
21682
+ await deps.emit(usage7);
21683
+ return { ...result, usage: usage7 };
21352
21684
  },
21353
21685
  async cancel(sub, call = {}) {
21354
21686
  const { methods, adapter, ctx } = target(sub.model, call);
@@ -21588,10 +21920,10 @@ function audioNodeMethods(deps) {
21588
21920
  const startedAt = Date.now();
21589
21921
  const outcome = await adapter.dub(resolved, ctx);
21590
21922
  if (outcome.kind === "audio") {
21591
- const { audio, usage: usage6, raw } = outcome.result;
21923
+ const { audio, usage: usage7, raw } = outcome.result;
21592
21924
  return {
21593
21925
  audio,
21594
- usage: await deps.settle(ctx, usage6, startedAt),
21926
+ usage: await deps.settle(ctx, usage7, startedAt),
21595
21927
  ...raw !== void 0 && { raw }
21596
21928
  };
21597
21929
  }
@@ -21643,10 +21975,10 @@ function textAbortOptions(sdk, context) {
21643
21975
  if (abortSignal) return { abortSignal };
21644
21976
  return {};
21645
21977
  }
21646
- var catalogId = z39.string();
21647
- var exactSize = z39.templateLiteral([z39.number(), "x", z39.number()]);
21648
- var sdkRatio = z39.templateLiteral([z39.number(), ":", z39.number()]);
21649
- 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"]);
21650
21982
  function isCatalogId(model) {
21651
21983
  return catalogId.safeParse(model).success;
21652
21984
  }
@@ -21889,7 +22221,7 @@ function createModelKit(config, adapters) {
21889
22221
  const images = result.images.map(
21890
22222
  (file) => toGeneratedImage({ bytes: file.uint8Array, mime: file.mediaType })
21891
22223
  );
21892
- const usage6 = timed(
22224
+ const usage7 = timed(
21893
22225
  {
21894
22226
  model: model.modelId,
21895
22227
  provider: model.provider,
@@ -21899,8 +22231,8 @@ function createModelKit(config, adapters) {
21899
22231
  },
21900
22232
  startedAt
21901
22233
  );
21902
- await emit(usage6);
21903
- 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 };
21904
22236
  }
21905
22237
  function passthroughVideo(req, call) {
21906
22238
  const {
@@ -21976,7 +22308,7 @@ function createModelKit(config, adapters) {
21976
22308
  let settled;
21977
22309
  let failed = false;
21978
22310
  const done = pending.then(async (result) => {
21979
- const usage6 = timed(
22311
+ const usage7 = timed(
21980
22312
  {
21981
22313
  model: model.modelId,
21982
22314
  provider: model.provider,
@@ -21989,10 +22321,10 @@ function createModelKit(config, adapters) {
21989
22321
  );
21990
22322
  settled = {
21991
22323
  video: { bytes: result.video.uint8Array, mime: result.video.mediaType },
21992
- usage: usage6,
22324
+ usage: usage7,
21993
22325
  raw: result
21994
22326
  };
21995
- await emit(usage6);
22327
+ await emit(usage7);
21996
22328
  return settled;
21997
22329
  });
21998
22330
  done.catch(() => {
@@ -22019,9 +22351,9 @@ function createModelKit(config, adapters) {
22019
22351
  if (settled) return settled;
22020
22352
  const pending = result(opts).then(
22021
22353
  async (out) => {
22022
- const usage6 = rowUsage(ctx, out.usage, startedAt);
22023
- await emit(usage6);
22024
- return { ...out, usage: usage6 };
22354
+ const usage7 = rowUsage(ctx, out.usage, startedAt);
22355
+ await emit(usage7);
22356
+ return { ...out, usage: usage7 };
22025
22357
  },
22026
22358
  (cause) => {
22027
22359
  settled = void 0;
@@ -22041,9 +22373,9 @@ function createModelKit(config, adapters) {
22041
22373
  return context(model, signal ? { ...call, signal } : call, warnings);
22042
22374
  },
22043
22375
  async settle(ctx, event, startedAt) {
22044
- const usage6 = rowUsage(ctx, event, startedAt);
22045
- await emit(usage6);
22046
- return usage6;
22376
+ const usage7 = rowUsage(ctx, event, startedAt);
22377
+ await emit(usage7);
22378
+ return usage7;
22047
22379
  },
22048
22380
  wrapVideoJob
22049
22381
  });
@@ -22088,8 +22420,8 @@ function createModelKit(config, adapters) {
22088
22420
  throw billedFailure(ctx, err, err.usage, startedAt);
22089
22421
  throw err;
22090
22422
  }
22091
- const usage6 = rowUsage(ctx, result.usage, startedAt);
22092
- await emit(usage6);
22423
+ const usage7 = rowUsage(ctx, result.usage, startedAt);
22424
+ await emit(usage7);
22093
22425
  const images = result.images.map(toGeneratedImage);
22094
22426
  const first = images[0];
22095
22427
  if (!first)
@@ -22098,7 +22430,7 @@ function createModelKit(config, adapters) {
22098
22430
  message: `${model.id} returned no image`,
22099
22431
  model: model.id
22100
22432
  });
22101
- return { ...result, usage: usage6, image: first, images, warnings };
22433
+ return { ...result, usage: usage7, image: first, images, warnings };
22102
22434
  },
22103
22435
  async generateVideo(req, call = {}) {
22104
22436
  mediaRetryOptions(call);
@@ -22199,9 +22531,9 @@ function createModelKit(config, adapters) {
22199
22531
  }
22200
22532
  const startedAt = Date.now();
22201
22533
  const result = await adapter.generateAudio(resolved, ctx);
22202
- const usage6 = rowUsage(ctx, result.usage, startedAt);
22203
- await emit(usage6);
22204
- return { ...result, usage: usage6 };
22534
+ const usage7 = rowUsage(ctx, result.usage, startedAt);
22535
+ await emit(usage7);
22536
+ return { ...result, usage: usage7 };
22205
22537
  },
22206
22538
  async prepareMediaPart(modelId, ref, mediaType, call = {}) {
22207
22539
  mediaRetryOptions(call);
@@ -22282,8 +22614,8 @@ function createModelKit(config, adapters) {
22282
22614
  options.prepareStep ?? options.experimental_prepareStep
22283
22615
  ),
22284
22616
  onFinish: async (event) => {
22285
- for (const usage6 of steps.usage(event.steps))
22286
- 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));
22287
22619
  await callerOnFinish?.(event);
22288
22620
  }
22289
22621
  });
@@ -22489,6 +22821,7 @@ export {
22489
22821
  videoLengthViolation,
22490
22822
  videoSizeViolation,
22491
22823
  videoToolConstraints,
22824
+ wavespeedAdapter,
22492
22825
  withRetry,
22493
22826
  xaiVideoAdapter
22494
22827
  };