@shop-os/modelkit 0.15.1 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -35,6 +35,7 @@ __export(index_exports, {
35
35
  ADAPTER_KEYS: () => ADAPTER_KEYS,
36
36
  ARRAY_INPUT_SPEC_KEYS: () => ARRAY_INPUT_SPEC_KEYS,
37
37
  AUDIO_INPUT_SPEC_KEYS: () => AUDIO_INPUT_SPEC_KEYS,
38
+ BYOK_PROVIDERS: () => BYOK_PROVIDERS,
38
39
  Catalog: () => Catalog,
39
40
  CatalogModelSchema: () => CatalogModelSchema,
40
41
  CatalogModelSchemaBase: () => CatalogModelSchemaBase,
@@ -59,6 +60,7 @@ __export(index_exports, {
59
60
  aiSdkTextAdapter: () => aiSdkTextAdapter,
60
61
  arkAdapter: () => arkAdapter,
61
62
  aspectRatioToSize: () => aspectRatioToSize,
63
+ byokProviderForModel: () => byokProviderForModel,
62
64
  classifyHttpError: () => classifyHttpError,
63
65
  compareCatalogOrder: () => compareCatalogOrder,
64
66
  createDefaultModelKit: () => createDefaultModelKit,
@@ -86,6 +88,7 @@ __export(index_exports, {
86
88
  isListed: () => isListed,
87
89
  isListedOn: () => isListedOn,
88
90
  isModelKitError: () => isModelKitError,
91
+ keyOverrideFor: () => keyOverrideFor,
89
92
  keysFromEnv: () => keysFromEnv,
90
93
  languageModel: () => languageModel,
91
94
  liveCatalog: () => liveCatalog,
@@ -102,6 +105,7 @@ __export(index_exports, {
102
105
  model3dSeedFits: () => model3dSeedFits,
103
106
  model3dSkus: () => model3dSkus,
104
107
  model3dTexture: () => model3dTexture,
108
+ modelsPoweredBy: () => modelsPoweredBy,
105
109
  nearestAspectRatio: () => nearestAspectRatio,
106
110
  normalizeExposure: () => normalizeExposure,
107
111
  openaiImageAdapter: () => openaiImageAdapter,
@@ -132,6 +136,7 @@ __export(index_exports, {
132
136
  streamObject: () => streamObject,
133
137
  streamText: () => streamText,
134
138
  takesTargetAspectRatio: () => takesTargetAspectRatio,
139
+ testProviderKey: () => testProviderKey,
135
140
  textUsageEvent: () => textUsageEvent,
136
141
  toGeneratedImage: () => toGeneratedImage,
137
142
  validateInputSpec: () => validateInputSpec,
@@ -283,8 +288,8 @@ function normalizeExposure(value) {
283
288
  if (value.every(
284
289
  (entry) => SURFACES.includes(entry)
285
290
  )) {
286
- const present2 = new Set(value);
287
- return SURFACES.filter((surface) => present2.has(surface));
291
+ const present3 = new Set(value);
292
+ return SURFACES.filter((surface) => present3.has(surface));
288
293
  }
289
294
  return value;
290
295
  }
@@ -5217,6 +5222,7 @@ var KLING_PROMPT = { referenceSyntax: "numbered", maxChars: 2500 };
5217
5222
  var H3_PROMPT = { referenceSyntax: "numbered", maxChars: 5e4 };
5218
5223
  var KLING_V4_PROMPT = { referenceSyntax: "numbered", maxChars: 2500 };
5219
5224
  var KLING_V4_AUDIO = "always";
5225
+ var KLING_V4_FLASH_PROMPT = { referenceSyntax: "numbered", maxChars: 26e3 };
5220
5226
  var NO_REFERENCES = { images: 0, videos: 0, audios: 0 };
5221
5227
  function klingMotionControl(tier) {
5222
5228
  const label = tier === "pro" ? "Pro" : "Standard";
@@ -5394,6 +5400,85 @@ var VIDEO_FAMILY_MODELS = [
5394
5400
  },
5395
5401
  capabilities: { acceptsSourceVideo: true, videoEdit: true }
5396
5402
  },
5403
+ {
5404
+ // https://fal.ai/models/kling/v4/flash/reference-to-video/api (+ /text-to-video,
5405
+ // /image-to-video): routed like kling-4.0, at 720p only and 3-20 s. image-to-video takes
5406
+ // a start frame (300 px min, ratio 0.40-2.50) and no end frame; its prompt is optional.
5407
+ // Reference images: 10, the start frame included. Reference videos: 5, 3-20.05 s each
5408
+ // and 20 s combined, 700 px min. Prompts up to 26,000 characters. No sound switch.
5409
+ id: "kling-4.0-flash",
5410
+ aliases: ["kling-4-flash", "kling-v4-flash"],
5411
+ label: "Kling 4.0 Flash",
5412
+ type: "video",
5413
+ adapter: "fal",
5414
+ providerModelId: "kling/v4/flash",
5415
+ lifecycle: "active",
5416
+ exposure: ["cowork", "space_builder"],
5417
+ constraints: {
5418
+ aspectRatios: ["adaptive", "16:9", "9:16", "1:1", "21:9"],
5419
+ resolutions: ["720p"],
5420
+ durations: { min: 3, max: 20 },
5421
+ durationPresets: [5, 10, 15, 20],
5422
+ references: {
5423
+ ...NO_REFERENCES,
5424
+ images: 10,
5425
+ videos: 5,
5426
+ videoSeconds: { min: 3, max: 20.05, total: 20 },
5427
+ videoPixels: { minWidth: 700, minHeight: 700 }
5428
+ },
5429
+ supports: [],
5430
+ prompt: KLING_V4_FLASH_PROMPT,
5431
+ audio: KLING_V4_AUDIO
5432
+ },
5433
+ defaults: { durationSeconds: 5, resolution: "720p", aspectRatio: "16:9" },
5434
+ usage: { ...VIDEO_USAGE },
5435
+ pricingKind: "video_per_second",
5436
+ display: {
5437
+ provider: "kuaishou",
5438
+ logo: KLING_LOGO,
5439
+ description: "Kuaishou Kling 4.0 Flash: fast text-to-video, a start frame, or reference-to-video from up to 10 images and 5 videos (20 seconds combined), 3 to 20 seconds at 720p. Prompts name references @Image1, @Video1."
5440
+ }
5441
+ },
5442
+ {
5443
+ // https://fal.ai/models/kling/v4/flash/video-to-video/api: source 3-20.05 s (700 px
5444
+ // min, 23.9-60.05 fps), up to 10 reference images and 4 reference videos; the source
5445
+ // and reference videos total 20 s at most. duration 3-20, or left out for the source's
5446
+ // length. The prompt names the source @Video1, reference videos @Video2 on, images @Image1.
5447
+ id: "kling-4.0-flash-edit",
5448
+ aliases: ["kling-4-flash-edit", "kling-v4-flash-edit"],
5449
+ label: "Kling 4.0 Flash Edit",
5450
+ type: "video",
5451
+ adapter: "fal",
5452
+ providerModelId: "kling/v4/flash/video-to-video",
5453
+ lifecycle: "active",
5454
+ exposure: ["cowork", "space_builder"],
5455
+ constraints: {
5456
+ resolutions: ["720p"],
5457
+ durations: { min: 3, max: 20 },
5458
+ references: {
5459
+ ...NO_REFERENCES,
5460
+ images: 10,
5461
+ videos: 4,
5462
+ videoSeconds: { min: 3, max: 20.05, total: 20 },
5463
+ videoPixels: { minWidth: 700, minHeight: 700 }
5464
+ },
5465
+ requires: ["sourceVideo"],
5466
+ sourceVideoSeconds: { min: 3, max: 20.05, inReferenceTotal: true },
5467
+ sourceVideoPixels: { minWidth: 700, minHeight: 700 },
5468
+ supports: [],
5469
+ prompt: KLING_V4_FLASH_PROMPT,
5470
+ audio: KLING_V4_AUDIO
5471
+ },
5472
+ defaults: { resolution: "720p" },
5473
+ usage: { ...VIDEO_USAGE },
5474
+ pricingKind: "video_per_second",
5475
+ display: {
5476
+ provider: "kuaishou",
5477
+ logo: KLING_LOGO,
5478
+ description: "Kuaishou Kling 4.0 Flash video edit: change a 3-20 second clip with a prompt, up to 10 reference images and 4 reference videos (20 seconds in all with the source), at 720p, as long as the source or a set 3-20 seconds. Prompts name the source @Video1."
5479
+ },
5480
+ capabilities: { acceptsSourceVideo: true, videoEdit: true }
5481
+ },
5397
5482
  {
5398
5483
  // https://fal.ai/models/minimax/h3-max-turbo/text-to-video/api (+ /image-to-video).
5399
5484
  // image-to-video takes a start frame, an end frame, or both, and no aspect_ratio.
@@ -8589,9 +8674,6 @@ var aiSdkTextAdapter = {
8589
8674
  // src/adapters/ark.ts
8590
8675
  var import_zod7 = require("zod");
8591
8676
 
8592
- // src/retry.ts
8593
- var import_zod6 = require("zod");
8594
-
8595
8677
  // src/json.ts
8596
8678
  var import_zod5 = require("zod");
8597
8679
  var JsonValueSchema = import_zod5.z.lazy(
@@ -8628,6 +8710,7 @@ function describeThrown(cause) {
8628
8710
  }
8629
8711
 
8630
8712
  // src/retry.ts
8713
+ var import_zod6 = require("zod");
8631
8714
  var textBody = import_zod6.z.string();
8632
8715
  var BILLING_CODES = /* @__PURE__ */ new Set([
8633
8716
  "insufficient_quota",
@@ -8924,10 +9007,36 @@ function arkKey(ctx) {
8924
9007
  }
8925
9008
  return key;
8926
9009
  }
8927
- function throwArkError(status, body, model) {
9010
+ var ARK_CODES = /* @__PURE__ */ new Map([
9011
+ ["AccountOverdueError", { status: 403, code: "provider_billing" }],
9012
+ ["OperationDenied.ServiceOverdue", { status: 403, code: "provider_billing" }],
9013
+ ["QuotaExceeded", { status: 429, code: "provider_billing" }],
9014
+ ["ModelNotOpen", { status: 404, code: "provider_rejected" }],
9015
+ ["InvalidEndpointOrModel.NotFound", { status: 404, code: "provider_rejected" }]
9016
+ ]);
9017
+ var ArkErrorBodySchema = import_zod7.z.object({ error: import_zod7.z.object({ code: import_zod7.z.string() }) });
9018
+ function arkErrorCode(body) {
9019
+ const text2 = import_zod7.z.string().safeParse(body);
9020
+ let decoded = body;
9021
+ if (text2.success) {
9022
+ try {
9023
+ decoded = JsonValueSchema.parse(JSON.parse(text2.data));
9024
+ } catch {
9025
+ return void 0;
9026
+ }
9027
+ }
9028
+ const parsed = ArkErrorBodySchema.safeParse(decoded);
9029
+ return parsed.success ? parsed.data.error.code : void 0;
9030
+ }
9031
+ function arkCodeRule(status, code) {
9032
+ const rule = code === void 0 ? void 0 : ARK_CODES.get(code);
9033
+ if (!rule || status !== void 0 && status !== rule.status) return void 0;
9034
+ return rule;
9035
+ }
9036
+ function throwArkError(status, body, model, code = arkErrorCode(body)) {
8928
9037
  const parsed = import_zod7.z.string().safeParse(body);
8929
9038
  const text2 = parsed.success ? parsed.data : JSON.stringify(body ?? "");
8930
- if (/sensitive.?content|human.?face/i.test(text2)) {
9039
+ if (/sensitive.?content|human.?face/i.test(`${code ?? ""} ${text2}`)) {
8931
9040
  const init = {
8932
9041
  code: "content_blocked",
8933
9042
  message: `ark rejected the request: ${text2.slice(0, 500)}`,
@@ -8939,15 +9048,18 @@ function throwArkError(status, body, model) {
8939
9048
  if (status !== void 0) init.status = status;
8940
9049
  throw new ModelKitError(init);
8941
9050
  }
8942
- if (status === void 0) {
8943
- throw new ModelKitError({
8944
- code: "provider_rejected",
8945
- message: `ark rejected the request: ${text2.slice(0, 500)}`,
9051
+ const rule = arkCodeRule(status, code);
9052
+ if (rule || status === void 0) {
9053
+ const init = {
9054
+ code: rule?.code ?? "provider_rejected",
9055
+ message: `ark rejected the request${code ? ` (${code})` : ""}: ${text2.slice(0, 500)}`,
8946
9056
  provider: "ark",
8947
9057
  model,
8948
9058
  body,
8949
9059
  retryable: false
8950
- });
9060
+ };
9061
+ if (status !== void 0) init.status = status;
9062
+ throw new ModelKitError(init);
8951
9063
  }
8952
9064
  throw classifyHttpError(status, body, "ark", model);
8953
9065
  }
@@ -9063,9 +9175,15 @@ var SeedanceResponseSchema = import_zod7.z.object({
9063
9175
  duration: import_zod7.z.number().optional(),
9064
9176
  framespersecond: import_zod7.z.number().optional(),
9065
9177
  resolution: import_zod7.z.string().optional(),
9066
- error: import_zod7.z.union([import_zod7.z.string(), import_zod7.z.object({ message: import_zod7.z.string().optional() })]).optional()
9178
+ error: import_zod7.z.union([
9179
+ import_zod7.z.string(),
9180
+ import_zod7.z.object({ code: import_zod7.z.string().optional(), message: import_zod7.z.string().optional() })
9181
+ ]).optional()
9182
+ });
9183
+ var SeedanceErrorSchema = import_zod7.z.object({
9184
+ code: import_zod7.z.string().optional(),
9185
+ message: import_zod7.z.string().optional()
9067
9186
  });
9068
- var SeedanceErrorMessageSchema = import_zod7.z.object({ message: import_zod7.z.string().optional() });
9069
9187
  function seedanceResolution(req) {
9070
9188
  return req.resolution ?? "720p";
9071
9189
  }
@@ -9086,10 +9204,14 @@ function seedanceInitialDuration(req) {
9086
9204
  function seedanceErrorMessage(error, status) {
9087
9205
  const asString = import_zod7.z.string().safeParse(error);
9088
9206
  if (asString.success) return asString.data;
9089
- const asObject = SeedanceErrorMessageSchema.safeParse(error);
9207
+ const asObject = SeedanceErrorSchema.safeParse(error);
9090
9208
  if (asObject.success && asObject.data.message !== void 0) return asObject.data.message;
9091
9209
  return `Seedance task ${status}`;
9092
9210
  }
9211
+ function seedanceErrorCode(error) {
9212
+ const parsed = SeedanceErrorSchema.safeParse(error);
9213
+ return parsed.success ? parsed.data.code : void 0;
9214
+ }
9093
9215
  function seedanceJob(ctx, key, jobId, usage5) {
9094
9216
  const modelId = ctx.model.id;
9095
9217
  const fetchStatus = async () => {
@@ -9097,9 +9219,9 @@ function seedanceJob(ctx, key, jobId, usage5) {
9097
9219
  headers: { Authorization: `Bearer ${key}` }
9098
9220
  });
9099
9221
  if (!res.ok) {
9100
- if (ctx.call.maxRetries !== 0 && (res.status === 429 || res.status >= 500))
9101
- return void 0;
9102
9222
  const text2 = await res.text().catch(() => "");
9223
+ const transient = (res.status === 429 || res.status >= 500) && !arkCodeRule(res.status, arkErrorCode(text2));
9224
+ if (ctx.call.maxRetries !== 0 && transient) return void 0;
9103
9225
  throwArkError(res.status, text2, modelId);
9104
9226
  }
9105
9227
  const parsed = SeedanceResponseSchema.safeParse(await res.json());
@@ -9159,7 +9281,12 @@ function seedanceJob(ctx, key, jobId, usage5) {
9159
9281
  };
9160
9282
  }
9161
9283
  if (status === "failed" || status === "expired" || status === "cancelled") {
9162
- throwArkError(void 0, seedanceErrorMessage(polled.error, status), modelId);
9284
+ throwArkError(
9285
+ void 0,
9286
+ seedanceErrorMessage(polled.error, status),
9287
+ modelId,
9288
+ seedanceErrorCode(polled.error)
9289
+ );
9163
9290
  }
9164
9291
  return void 0;
9165
9292
  }, pollOpts);
@@ -10942,8 +11069,8 @@ function falMediaError(row2, message, code) {
10942
11069
  retryable: false
10943
11070
  });
10944
11071
  }
10945
- function refuseMedia(row2, present2) {
10946
- const extra = Object.entries(present2).find(([, set]) => set);
11072
+ function refuseMedia(row2, present3) {
11073
+ const extra = Object.entries(present3).find(([, set]) => set);
10947
11074
  if (extra) throw falMediaError(row2, `does not take ${extra[0]}`, "unsupported_option");
10948
11075
  }
10949
11076
  function setIf(input, key, value) {
@@ -11807,8 +11934,13 @@ var MOTION_PRO = "fal-ai/kling-video/v3/pro/motion-control";
11807
11934
  var MOTION_STANDARD = "fal-ai/kling-video/v3/standard/motion-control";
11808
11935
  var O3_REFERENCE = "fal-ai/kling-video/o3/pro/reference-to-video";
11809
11936
  var O3_EDIT = "fal-ai/kling-video/o3/pro/video-to-video/edit";
11810
- var V4_FAMILY = "kling/v4";
11811
- var V4_EDIT = "kling/v4/video-to-video/edit";
11937
+ var V4 = { generate: "kling/v4", edit: "kling/v4/video-to-video/edit", flash: false };
11938
+ var V4_FLASH = {
11939
+ generate: "kling/v4/flash",
11940
+ edit: "kling/v4/flash/video-to-video",
11941
+ flash: true
11942
+ };
11943
+ var V4_VARIANTS = [V4, V4_FLASH];
11812
11944
  function motionControl(endpoint, req, ctx) {
11813
11945
  const [character] = req.referenceImages ?? [];
11814
11946
  const [motion] = req.referenceVideos ?? [];
@@ -11868,15 +12000,18 @@ var klingV3Family = {
11868
12000
  return motionControl(id, req, ctx);
11869
12001
  }
11870
12002
  };
11871
- function v4Generate(req, ctx) {
12003
+ function v4Generate(variant, req, ctx) {
11872
12004
  const images = urls(req.referenceImages);
11873
12005
  const videos = urls(req.referenceVideos);
11874
12006
  const duration = wholeSeconds(req, ctx);
11875
12007
  const resolution = resolutionOf(req, ctx);
11876
- const input = { prompt: req.prompt.trim(), duration, resolution };
12008
+ const references = images.length + videos.length > 0;
12009
+ const input = { duration, resolution };
12010
+ if (variant.flash && !references && req.firstFrame) optionalPrompt(input, req);
12011
+ else input["prompt"] = req.prompt.trim();
11877
12012
  let endpoint;
11878
- if (images.length + videos.length > 0) {
11879
- endpoint = `${V4_FAMILY}/reference-to-video`;
12013
+ if (references) {
12014
+ endpoint = `${variant.generate}/reference-to-video`;
11880
12015
  if (images.length > 0) input["image_urls"] = images;
11881
12016
  if (videos.length > 0) input["video_urls"] = videos;
11882
12017
  if (req.firstFrame) input["start_image_url"] = refToUrl(req.firstFrame);
@@ -11884,17 +12019,17 @@ function v4Generate(req, ctx) {
11884
12019
  input["aspect_ratio"] = req.aspectRatio === "adaptive" ? "auto" : req.aspectRatio;
11885
12020
  }
11886
12021
  } else if (req.firstFrame) {
11887
- endpoint = `${V4_FAMILY}/image-to-video`;
12022
+ endpoint = `${variant.generate}/image-to-video`;
11888
12023
  input["start_image_url"] = refToUrl(req.firstFrame);
11889
12024
  if (req.lastFrame) input["end_image_url"] = refToUrl(req.lastFrame);
11890
12025
  } else {
11891
- endpoint = `${V4_FAMILY}/text-to-video`;
12026
+ endpoint = `${variant.generate}/text-to-video`;
11892
12027
  const ratio = concreteRatio(req);
11893
12028
  if (ratio !== void 0) input["aspect_ratio"] = ratio;
11894
12029
  }
11895
12030
  return { endpoint, input, resolution, seconds: requestedSeconds(duration) };
11896
12031
  }
11897
- function v4Edit(req, ctx) {
12032
+ function v4Edit(variant, req, ctx) {
11898
12033
  if (req.sourceVideo === void 0) throw refusal(ctx, "needs a source video", "missing_input");
11899
12034
  const resolution = resolutionOf(req, ctx);
11900
12035
  const input = {
@@ -11904,9 +12039,11 @@ function v4Edit(req, ctx) {
11904
12039
  };
11905
12040
  const images = urls(req.referenceImages);
11906
12041
  if (images.length > 0) input["image_urls"] = images;
12042
+ const videos = urls(req.referenceVideos);
12043
+ if (variant.flash && videos.length > 0) input["video_urls"] = videos;
11907
12044
  if (req.durationSeconds === void 0) {
11908
12045
  return {
11909
- endpoint: V4_EDIT,
12046
+ endpoint: variant.edit,
11910
12047
  input,
11911
12048
  resolution,
11912
12049
  seconds: inputLengthSeconds(req, req.sourceVideo)
@@ -11914,13 +12051,18 @@ function v4Edit(req, ctx) {
11914
12051
  }
11915
12052
  const duration = wholeSeconds(req, ctx);
11916
12053
  input["duration"] = duration;
11917
- return { endpoint: V4_EDIT, input, resolution, seconds: requestedSeconds(duration) };
12054
+ return { endpoint: variant.edit, input, resolution, seconds: requestedSeconds(duration) };
11918
12055
  }
11919
- var KLING_V4_VIDEO_IDS = /* @__PURE__ */ new Set([V4_FAMILY, V4_EDIT]);
12056
+ var KLING_V4_VIDEO_IDS = new Set(
12057
+ V4_VARIANTS.flatMap((v) => [v.generate, v.edit])
12058
+ );
11920
12059
  var klingV4Family = {
11921
12060
  ids: KLING_V4_VIDEO_IDS,
11922
12061
  plan(req, ctx) {
11923
- return ctx.model.providerModelId.toLowerCase() === V4_EDIT ? v4Edit(req, ctx) : v4Generate(req, ctx);
12062
+ const id = ctx.model.providerModelId.toLowerCase();
12063
+ const edit2 = V4_VARIANTS.find((v) => v.edit === id);
12064
+ if (edit2 !== void 0) return v4Edit(edit2, req, ctx);
12065
+ return v4Generate(V4_VARIANTS.find((v) => v.generate === id) ?? V4, req, ctx);
11924
12066
  }
11925
12067
  };
11926
12068
 
@@ -11995,6 +12137,8 @@ var O3_REFERENCE2 = "fal-ai/kling-video/o3/pro/reference-to-video";
11995
12137
  var O3_EDIT2 = "fal-ai/kling-video/o3/pro/video-to-video/edit";
11996
12138
  var KLING_V4 = "kling/v4";
11997
12139
  var KLING_V4_EDIT = "kling/v4/video-to-video/edit";
12140
+ var KLING_V4_FLASH = "kling/v4/flash";
12141
+ var KLING_V4_FLASH_EDIT = "kling/v4/flash/video-to-video";
11998
12142
  var H3_TURBO = "minimax/h3-max-turbo";
11999
12143
  var H3_RECAST = "minimax/h3-max/recast";
12000
12144
  var H3_RELIGHT = "minimax/h3-max/relight";
@@ -12076,6 +12220,11 @@ function klingV4(req) {
12076
12220
  }
12077
12221
  return needsPrompt(req);
12078
12222
  }
12223
+ function klingV4Flash(req) {
12224
+ if (req.lastFrame !== void 0) return unsupported2("takes no end frame");
12225
+ if (!hasReferences(req) && req.firstFrame !== void 0) return void 0;
12226
+ return klingV4(req);
12227
+ }
12079
12228
  function h3Turbo(req) {
12080
12229
  if (count(req.referenceImages) + count(req.referenceVideos) > 0) {
12081
12230
  return unsupported2("takes no reference images or videos");
@@ -12156,6 +12305,8 @@ var RULES = /* @__PURE__ */ new Map([
12156
12305
  [O3_EDIT2, (req) => needsSource(req) ?? needsPrompt(req)],
12157
12306
  [KLING_V4, klingV4],
12158
12307
  [KLING_V4_EDIT, (req) => needsSource(req) ?? needsPrompt(req)],
12308
+ [KLING_V4_FLASH, klingV4Flash],
12309
+ [KLING_V4_FLASH_EDIT, (req) => needsSource(req) ?? needsPrompt(req)],
12159
12310
  [H3_TURBO, h3Turbo],
12160
12311
  [MINIMAX_H3_INSERT, h3Insert],
12161
12312
  [H3_RECAST, h3Recast],
@@ -12205,7 +12356,7 @@ function applyFalVideoRules(model, req, callerRatio, warnings) {
12205
12356
  warnings.push(viduSilentWarning(model));
12206
12357
  req.generateAudio = false;
12207
12358
  }
12208
- if (id === KLING_V4 && req.firstFrame !== void 0 && !hasReferences(req)) {
12359
+ if ((id === KLING_V4 || id === KLING_V4_FLASH) && req.firstFrame !== void 0 && !hasReferences(req)) {
12209
12360
  if (req.aspectRatio !== void 0) {
12210
12361
  if (callerRatio !== void 0) {
12211
12362
  warnings.push({
@@ -18094,16 +18245,16 @@ function resolveVideoOptions(model, request, onUnsupported = "error") {
18094
18245
  }
18095
18246
  function checkVideoRequired(model, req) {
18096
18247
  const c = model.constraints;
18097
- const present2 = (input) => input === "references" ? compact(req.referenceImages).length + compact(req.referenceVideos).length + compact(req.referenceAudios).length > 0 : input !== "sourceAudio" && req[input] !== void 0;
18248
+ const present3 = (input) => input === "references" ? compact(req.referenceImages).length + compact(req.referenceVideos).length + compact(req.referenceAudios).length > 0 : input !== "sourceAudio" && req[input] !== void 0;
18098
18249
  for (const input of c.requires ?? []) {
18099
- if (!present2(input))
18250
+ if (!present3(input))
18100
18251
  throw new ModelKitError({
18101
18252
  code: "missing_input",
18102
18253
  message: `${model.id} requires ${input}`,
18103
18254
  model: model.id
18104
18255
  });
18105
18256
  }
18106
- if (c.requiresOneOf && !c.requiresOneOf.some(present2)) {
18257
+ if (c.requiresOneOf && !c.requiresOneOf.some(present3)) {
18107
18258
  throw new ModelKitError({
18108
18259
  code: "missing_input",
18109
18260
  message: `${model.id} requires one of: ${c.requiresOneOf.join(", ")}`,
@@ -18151,8 +18302,8 @@ function resolveAudioOptions(model, request, onUnsupported = "error") {
18151
18302
  if (references.length > 0) merged.references = references;
18152
18303
  else delete merged.references;
18153
18304
  for (const input of c.requires ?? []) {
18154
- const present2 = input === "references" ? references.length > 0 : input === "sourceVideo" && merged.sourceVideo !== void 0;
18155
- if (!present2)
18305
+ const present3 = input === "references" ? references.length > 0 : input === "sourceVideo" && merged.sourceVideo !== void 0;
18306
+ if (!present3)
18156
18307
  throw new ModelKitError({
18157
18308
  code: "missing_input",
18158
18309
  message: `${model.id} requires ${input}`,
@@ -18206,12 +18357,12 @@ function unsupported3(model, message) {
18206
18357
  model: model.id
18207
18358
  });
18208
18359
  }
18209
- function checkRequired(model, present2) {
18360
+ function checkRequired(model, present3) {
18210
18361
  for (const input of model.constraints.requires ?? []) {
18211
- if (present2[input] !== true) throw missing2(model, input);
18362
+ if (present3[input] !== true) throw missing2(model, input);
18212
18363
  }
18213
18364
  const oneOf = model.constraints.requiresOneOf;
18214
- if (oneOf !== void 0 && !oneOf.some((input) => present2[input] === true)) {
18365
+ if (oneOf !== void 0 && !oneOf.some((input) => present3[input] === true)) {
18215
18366
  throw missing2(model, `one of ${oneOf.join(", ")}`);
18216
18367
  }
18217
18368
  }
@@ -18543,6 +18694,39 @@ function resolveKeys(config, names, tier = "pro") {
18543
18694
  }
18544
18695
  return config.keys.pro;
18545
18696
  }
18697
+ function present2(value) {
18698
+ return value !== void 0 && value.trim() !== "";
18699
+ }
18700
+ function overrideHolds(override, name) {
18701
+ if (!override || name === "aws" || !present2(override[name])) return false;
18702
+ return name !== "higgsfield" || present2(override.higgsfieldSecret);
18703
+ }
18704
+ function overrideCovers(override, names) {
18705
+ return names.filter((name) => overrideHolds(override, name));
18706
+ }
18707
+ function resolveCallKeys(config, names, tier = "pro", override) {
18708
+ const covered = overrideCovers(override, names);
18709
+ const tierNames = names.filter((name) => !covered.includes(name));
18710
+ const base = resolveKeys(config, tierNames, tier);
18711
+ if (!override || covered.length === 0)
18712
+ return { keys: base, source: tierSource(config, tierNames, tier), tierNames };
18713
+ const keys = { ...base };
18714
+ for (const name of covered) {
18715
+ const value = name === "aws" ? void 0 : override[name];
18716
+ if (name === "aws" || !present2(value)) continue;
18717
+ keys[name] = value;
18718
+ if (name === "higgsfield" && present2(override.higgsfieldSecret))
18719
+ keys.higgsfieldSecret = override.higgsfieldSecret;
18720
+ }
18721
+ return { keys, source: "byok", tierNames };
18722
+ }
18723
+ function keySourceField(source2) {
18724
+ return source2 === void 0 ? {} : { keySource: source2 };
18725
+ }
18726
+ function tierSource(config, names, tier) {
18727
+ if (tier === "enterprise") return hasAll(config.keys.enterprise, names) ? "enterprise" : "pro";
18728
+ return tier;
18729
+ }
18546
18730
  function keysFromEnv(env, prefix = "") {
18547
18731
  const pick2 = (...names) => names.map((n) => env[`${prefix}${n}`]).find((v) => v && v.length > 0);
18548
18732
  const keys = {};
@@ -18567,10 +18751,10 @@ function keysFromEnv(env, prefix = "") {
18567
18751
  set("fish", pick2("FISH_AUDIO_API_KEY"));
18568
18752
  set("elevenlabs", pick2("ELEVENLABS_API_KEY"));
18569
18753
  set("cloudflare", pick2("CF_AIG_TOKEN"));
18570
- const bearer = pick2("AWS_BEARER_TOKEN_BEDROCK");
18754
+ const bearer2 = pick2("AWS_BEARER_TOKEN_BEDROCK");
18571
18755
  const accessKeyId = pick2("AWS_ACCESS_KEY_ID");
18572
18756
  const secretAccessKey = pick2("AWS_SECRET_ACCESS_KEY");
18573
- if (bearer || accessKeyId && secretAccessKey) {
18757
+ if (bearer2 || accessKeyId && secretAccessKey) {
18574
18758
  const aws = {
18575
18759
  region: env[`${prefix}BEDROCK_REGION`] || "us-east-1"
18576
18760
  };
@@ -18580,12 +18764,101 @@ function keysFromEnv(env, prefix = "") {
18580
18764
  }
18581
18765
  const sessionToken = pick2("AWS_SESSION_TOKEN");
18582
18766
  if (sessionToken) aws.sessionToken = sessionToken;
18583
- if (bearer) aws.apiKey = bearer;
18767
+ if (bearer2) aws.apiKey = bearer2;
18584
18768
  keys.aws = aws;
18585
18769
  }
18586
18770
  return keys;
18587
18771
  }
18588
18772
 
18773
+ // src/byok.ts
18774
+ var API_KEY = { id: "apiKey", label: "API key", required: true, secret: true };
18775
+ var BYOK_PROVIDERS = {
18776
+ ark: {
18777
+ id: "ark",
18778
+ label: "BytePlus ModelArk",
18779
+ keyName: "ark",
18780
+ fields: [
18781
+ API_KEY,
18782
+ { id: "accessKeyId", label: "Access key ID", required: false, secret: true },
18783
+ { id: "secretAccessKey", label: "Secret access key", required: false, secret: true },
18784
+ { id: "assetGroupId", label: "Asset group ID", required: false, secret: false }
18785
+ ]
18786
+ },
18787
+ fal: { id: "fal", label: "fal", keyName: "fal", fields: [API_KEY] },
18788
+ replicate: { id: "replicate", label: "Replicate", keyName: "replicate", fields: [API_KEY] },
18789
+ openai: { id: "openai", label: "OpenAI", keyName: "openai", fields: [API_KEY] },
18790
+ google: { id: "google", label: "Google AI Studio", keyName: "google", fields: [API_KEY] }
18791
+ };
18792
+ var BY_KEY_NAME = new Map(
18793
+ Object.values(BYOK_PROVIDERS).map((provider) => [provider.keyName, provider.id])
18794
+ );
18795
+ function byokProviderForModel(model) {
18796
+ const names = model.adapter === "ai-sdk-text" ? [textKeyName(model)] : ADAPTER_KEYS[model.adapter];
18797
+ const [name, ...rest] = names;
18798
+ if (name === void 0 || rest.length > 0) return null;
18799
+ return BY_KEY_NAME.get(name) ?? null;
18800
+ }
18801
+ function modelsPoweredBy(provider, catalog) {
18802
+ return [...catalog].filter((model) => byokProviderForModel(model) === provider);
18803
+ }
18804
+ function keyOverrideFor(secrets) {
18805
+ const override = {};
18806
+ for (const provider of Object.values(BYOK_PROVIDERS)) {
18807
+ const apiKey = secrets[provider.id]?.apiKey?.trim();
18808
+ if (apiKey) override[provider.keyName] = apiKey;
18809
+ }
18810
+ return override;
18811
+ }
18812
+ var bearer = (apiKey) => ({ Authorization: `Bearer ${apiKey}` });
18813
+ var PROBES = {
18814
+ ark: {
18815
+ url: (endpoints) => `${endpoints.ark ?? ARK_BASE_URL}/contents/generations/tasks?page_num=1&page_size=1`,
18816
+ headers: bearer
18817
+ },
18818
+ fal: {
18819
+ url: () => "https://api.fal.ai/v1/assets/collections?limit=1",
18820
+ headers: (apiKey) => ({ Authorization: `Key ${apiKey}` }),
18821
+ unverifiableStatus: 403
18822
+ },
18823
+ replicate: {
18824
+ url: () => "https://api.replicate.com/v1/account",
18825
+ headers: bearer
18826
+ },
18827
+ openai: {
18828
+ url: () => "https://api.openai.com/v1/models",
18829
+ headers: bearer,
18830
+ unverifiableStatus: 403
18831
+ },
18832
+ google: {
18833
+ url: () => "https://generativelanguage.googleapis.com/v1beta/models?pageSize=1",
18834
+ headers: (apiKey) => ({ "x-goog-api-key": apiKey }),
18835
+ unverifiableStatus: 403
18836
+ }
18837
+ };
18838
+ async function testProviderKey(provider, secret, opts = {}) {
18839
+ const apiKey = secret.apiKey?.trim();
18840
+ if (!apiKey) return { ok: false, reason: "invalid" };
18841
+ const probe = PROBES[provider];
18842
+ const fetchImpl = opts.fetch ?? globalThis.fetch;
18843
+ let res;
18844
+ try {
18845
+ res = await fetchImpl(probe.url(opts.endpoints ?? {}), {
18846
+ method: "GET",
18847
+ headers: probe.headers(apiKey),
18848
+ ...opts.signal !== void 0 && { signal: opts.signal }
18849
+ });
18850
+ } catch (cause) {
18851
+ if (opts.signal?.aborted) throw cause;
18852
+ return { ok: false, reason: "unreachable" };
18853
+ }
18854
+ await res.body?.cancel().catch(() => void 0);
18855
+ if (res.ok) return { ok: true, credit: "unknown" };
18856
+ if (res.status === probe.unverifiableStatus) return { ok: false, reason: "unverifiable" };
18857
+ if (res.status === 400 || res.status === 401) return { ok: false, reason: "invalid" };
18858
+ if (res.status === 402 || res.status === 403) return { ok: false, reason: "denied" };
18859
+ return { ok: false, reason: "unreachable" };
18860
+ }
18861
+
18589
18862
  // src/text.ts
18590
18863
  var import_ai4 = require("ai");
18591
18864
  var import_zod33 = require("zod");
@@ -18676,12 +18949,10 @@ function createTextSteps(initial, resolve, callerProviderOptions) {
18676
18949
  const grouped = /* @__PURE__ */ new Map();
18677
18950
  for (const [index, step] of results.entries()) {
18678
18951
  const target = steps.get(index) ?? initial;
18679
- const event = textUsageEvent(
18680
- target.entry,
18681
- target.provider,
18682
- step.usage,
18683
- step.providerMetadata
18684
- );
18952
+ const event = {
18953
+ ...textUsageEvent(target.entry, target.provider, step.usage, step.providerMetadata),
18954
+ ...keySourceField(target.keySource)
18955
+ };
18685
18956
  const previous = grouped.get(target.entry.id);
18686
18957
  if (previous) {
18687
18958
  previous.quantity += event.quantity;
@@ -18732,8 +19003,9 @@ function preferredAnthropicTransport(model, routing) {
18732
19003
  if (isAnthropicTransport(row2)) return row2;
18733
19004
  return routing.anthropic ?? "direct";
18734
19005
  }
18735
- function resolveAnthropicTransport(model, config, tier, warn) {
19006
+ function resolveAnthropicTransport(model, config, tier, warn, keyOverride) {
18736
19007
  if (model.adapter !== "ai-sdk-text" || textProviderOf(model) !== "anthropic") return void 0;
19008
+ if (overrideCovers(keyOverride, ["anthropic"]).length > 0) return "direct";
18737
19009
  const rowValue = model.providerOptions?.["modelkit"]?.["transport"];
18738
19010
  if (rowValue !== void 0 && !isAnthropicTransport(rowValue))
18739
19011
  warn(
@@ -18822,8 +19094,7 @@ function providerJobMethods(kind, deps) {
18822
19094
  const { methods, adapter, ctx } = target(sub.model, rest);
18823
19095
  if (!methods.result) throw missing3(adapter, ctx.model);
18824
19096
  const result = await methods.result(sub, ctx, webhook);
18825
- const base = { ...result.usage, model: ctx.model.id, unit: ctx.model.usage.unit };
18826
- const usage5 = sub.submittedAt === void 0 ? base : deps.timed(base, sub.submittedAt);
19097
+ const usage5 = deps.rowUsage(ctx, result.usage, sub.submittedAt);
18827
19098
  await deps.emit(usage5);
18828
19099
  return { ...result, usage: usage5 };
18829
19100
  },
@@ -18951,7 +19222,7 @@ function audioNodeMethods(deps) {
18951
19222
  if (!adapter.generateSpeech) throw noMethod(adapter, model, "generate speech");
18952
19223
  const startedAt = Date.now();
18953
19224
  const result = await adapter.generateSpeech(resolved, ctx);
18954
- return { ...result, usage: await deps.settle(model, result.usage, startedAt) };
19225
+ return { ...result, usage: await deps.settle(ctx, result.usage, startedAt) };
18955
19226
  },
18956
19227
  async changeVoice(req, call = {}) {
18957
19228
  mediaRetryOptions(call);
@@ -18966,7 +19237,7 @@ function audioNodeMethods(deps) {
18966
19237
  if (!adapter.changeVoice) throw noMethod(adapter, model, "change a voice");
18967
19238
  const startedAt = Date.now();
18968
19239
  const result = await adapter.changeVoice(resolved, ctx);
18969
- return { ...result, usage: await deps.settle(model, result.usage, startedAt) };
19240
+ return { ...result, usage: await deps.settle(ctx, result.usage, startedAt) };
18970
19241
  },
18971
19242
  async lipsync(req, call = {}) {
18972
19243
  mediaRetryOptions(call);
@@ -18981,7 +19252,7 @@ function audioNodeMethods(deps) {
18981
19252
  if (!adapter.lipsync) throw noMethod(adapter, model, "lipsync");
18982
19253
  const startedAt = Date.now();
18983
19254
  const job = deps.wrapVideoJob(
18984
- model,
19255
+ ctx,
18985
19256
  await adapter.lipsync(resolved, ctx),
18986
19257
  warnings,
18987
19258
  startedAt
@@ -19006,7 +19277,7 @@ function audioNodeMethods(deps) {
19006
19277
  if (!adapter.transcribe) throw noMethod(adapter, model, "transcribe");
19007
19278
  const startedAt = Date.now();
19008
19279
  const result = await adapter.transcribe(resolved, ctx);
19009
- return { ...result, usage: await deps.settle(model, result.usage, startedAt) };
19280
+ return { ...result, usage: await deps.settle(ctx, result.usage, startedAt) };
19010
19281
  },
19011
19282
  async createVoice(req, call = {}) {
19012
19283
  mediaRetryOptions(call);
@@ -19017,7 +19288,7 @@ function audioNodeMethods(deps) {
19017
19288
  if (!adapter.createVoice) throw noMethod(adapter, model, "clone a voice");
19018
19289
  const startedAt = Date.now();
19019
19290
  const result = await adapter.createVoice(resolved, ctx);
19020
- return { ...result, usage: await deps.settle(model, result.usage, startedAt) };
19291
+ return { ...result, usage: await deps.settle(ctx, result.usage, startedAt) };
19021
19292
  },
19022
19293
  async designVoice(req, call = {}) {
19023
19294
  mediaRetryOptions(call);
@@ -19032,7 +19303,7 @@ function audioNodeMethods(deps) {
19032
19303
  if (!adapter.designVoice) throw noMethod(adapter, model, "design a voice");
19033
19304
  const startedAt = Date.now();
19034
19305
  const result = await adapter.designVoice(resolved, ctx);
19035
- return { ...result, usage: await deps.settle(model, result.usage, startedAt) };
19306
+ return { ...result, usage: await deps.settle(ctx, result.usage, startedAt) };
19036
19307
  },
19037
19308
  async deleteVoice(req, call = {}) {
19038
19309
  mediaRetryOptions(call);
@@ -19068,11 +19339,11 @@ function audioNodeMethods(deps) {
19068
19339
  const { audio, usage: usage5, raw } = outcome.result;
19069
19340
  return {
19070
19341
  audio,
19071
- usage: await deps.settle(model, usage5, startedAt),
19342
+ usage: await deps.settle(ctx, usage5, startedAt),
19072
19343
  ...raw !== void 0 && { raw }
19073
19344
  };
19074
19345
  }
19075
- const job = deps.wrapVideoJob(model, outcome.job, warnings, startedAt);
19346
+ const job = deps.wrapVideoJob(ctx, outcome.job, warnings, startedAt);
19076
19347
  const out = await job.result(waitOptions(call, ctx.signal));
19077
19348
  return {
19078
19349
  video: out.video,
@@ -19084,14 +19355,28 @@ function audioNodeMethods(deps) {
19084
19355
  }
19085
19356
 
19086
19357
  // src/client.ts
19087
- function routingFor(config, tier) {
19088
- const routing = config.routing ?? {};
19089
- if (tier !== "sloosh") return routing;
19358
+ function directRouting(routing) {
19090
19359
  const direct = { ...routing };
19091
19360
  if (direct.text === "cloudflare") direct.text = "direct";
19092
19361
  if (direct.fal === "cloudflare-passthrough") direct.fal = "direct";
19093
19362
  return direct;
19094
19363
  }
19364
+ function routingFor(config, model, call, transport) {
19365
+ const routing = config.routing ?? {};
19366
+ const direct = directRouting(routing);
19367
+ if (call.tier === "sloosh") return direct;
19368
+ const byok = overrideCovers(call.keyOverride, requiredKeys(model, direct, transport));
19369
+ return byok.length > 0 ? direct : routing;
19370
+ }
19371
+ function byokKeyMissing(provider, model) {
19372
+ return new ModelKitError({
19373
+ code: "byok_key_missing",
19374
+ message: `${model} needs the customer's ${provider} key and the call has none`,
19375
+ provider,
19376
+ model,
19377
+ retryable: false
19378
+ });
19379
+ }
19095
19380
  function requiredKeys(model, routing, transport) {
19096
19381
  if (model.adapter === "fal" && routing.fal === "cloudflare-passthrough") return ["cloudflare"];
19097
19382
  if (model.adapter === "ai-sdk-text") {
@@ -19193,21 +19478,35 @@ function createModelKit(config, adapters) {
19193
19478
  message: `No adapter registered for ${model.adapter}`,
19194
19479
  model: model.id
19195
19480
  });
19196
- const transport = resolveAnthropicTransport(model, config, call.tier, warnOnce);
19197
- const routing = routingFor(config, call.tier);
19481
+ const transport = resolveAnthropicTransport(
19482
+ model,
19483
+ config,
19484
+ call.tier,
19485
+ warnOnce,
19486
+ call.keyOverride
19487
+ );
19488
+ const routing = routingFor(config, model, call, transport);
19198
19489
  const names = requiredKeys(model, routing, transport);
19490
+ if (call.requireOverride && overrideCovers(call.keyOverride, names).length === 0)
19491
+ throw byokKeyMissing(names[0] ?? model.adapter, model.id);
19492
+ const { keys, source: source2, tierNames } = resolveCallKeys(
19493
+ config,
19494
+ names,
19495
+ call.tier,
19496
+ call.keyOverride
19497
+ );
19199
19498
  if (call.tier === "enterprise") {
19200
- const missing3 = missingEnterpriseKeys(config, names);
19499
+ const missing3 = missingEnterpriseKeys(config, tierNames);
19201
19500
  if (missing3.length > 0)
19202
19501
  logger.warn(
19203
19502
  `[modelkit] enterprise keys incomplete for ${model.adapter}; using pro`,
19204
19503
  { missing: missing3 }
19205
19504
  );
19206
19505
  }
19207
- const keys = resolveKeys(config, names, call.tier);
19208
19506
  const ctx = {
19209
19507
  model,
19210
19508
  keys,
19509
+ keySource: source2,
19211
19510
  routing,
19212
19511
  fetch: fetchImpl,
19213
19512
  logger,
@@ -19222,7 +19521,7 @@ function createModelKit(config, adapters) {
19222
19521
  const jobDeps = {
19223
19522
  catalog,
19224
19523
  context: (model, call) => context(model, call, []),
19225
- timed,
19524
+ rowUsage,
19226
19525
  emit
19227
19526
  };
19228
19527
  const videoToolJobs = providerJobMethods(VIDEO_TOOL_JOB, jobDeps);
@@ -19231,6 +19530,15 @@ function createModelKit(config, adapters) {
19231
19530
  if (event.latencyMs !== void 0) return event;
19232
19531
  return { ...event, latencyMs: Math.max(0, Date.now() - startedAt) };
19233
19532
  }
19533
+ function rowUsage(ctx, event, startedAt) {
19534
+ const stamped = {
19535
+ ...event,
19536
+ model: ctx.model.id,
19537
+ unit: ctx.model.usage.unit,
19538
+ ...keySourceField(ctx.keySource)
19539
+ };
19540
+ return startedAt === void 0 ? stamped : timed(stamped, startedAt);
19541
+ }
19234
19542
  function textTimed(event, stepCount, startedAt) {
19235
19543
  return stepCount === 1 ? timed(event, startedAt) : event;
19236
19544
  }
@@ -19247,6 +19555,7 @@ function createModelKit(config, adapters) {
19247
19555
  }
19248
19556
  function textTarget(model, call) {
19249
19557
  if (!isCatalogId(model)) {
19558
+ if (call.requireOverride) throw byokKeyMissing(model.provider, model.modelId);
19250
19559
  return {
19251
19560
  entry: passthroughTextModel(model),
19252
19561
  languageModel: model,
@@ -19270,7 +19579,8 @@ function createModelKit(config, adapters) {
19270
19579
  return {
19271
19580
  entry,
19272
19581
  languageModel: adapter.languageModel(ctx),
19273
- provider: textUsageProvider(entry, ctx.anthropicTransport)
19582
+ provider: textUsageProvider(entry, ctx.anthropicTransport),
19583
+ ...keySourceField(ctx.keySource)
19274
19584
  };
19275
19585
  }
19276
19586
  async function passthroughImage(req, call) {
@@ -19442,7 +19752,7 @@ function createModelKit(config, adapters) {
19442
19752
  result: () => done
19443
19753
  };
19444
19754
  }
19445
- function wrapVideoJob(model, job, warnings, startedAt) {
19755
+ function wrapVideoJob(ctx, job, warnings, startedAt) {
19446
19756
  const result = job.result.bind(job);
19447
19757
  let settled;
19448
19758
  return {
@@ -19452,10 +19762,7 @@ function createModelKit(config, adapters) {
19452
19762
  if (settled) return settled;
19453
19763
  const pending = result(opts).then(
19454
19764
  async (out) => {
19455
- const usage5 = timed(
19456
- { ...out.usage, model: model.id, unit: model.usage.unit },
19457
- startedAt
19458
- );
19765
+ const usage5 = rowUsage(ctx, out.usage, startedAt);
19459
19766
  await emit(usage5);
19460
19767
  return { ...out, usage: usage5 };
19461
19768
  },
@@ -19476,8 +19783,8 @@ function createModelKit(config, adapters) {
19476
19783
  const signal = combineSignals(abortSignal, call.signal);
19477
19784
  return context(model, signal ? { ...call, signal } : call, warnings);
19478
19785
  },
19479
- async settle(model, event, startedAt) {
19480
- const usage5 = timed({ ...event, model: model.id, unit: model.usage.unit }, startedAt);
19786
+ async settle(ctx, event, startedAt) {
19787
+ const usage5 = rowUsage(ctx, event, startedAt);
19481
19788
  await emit(usage5);
19482
19789
  return usage5;
19483
19790
  },
@@ -19490,6 +19797,8 @@ function createModelKit(config, adapters) {
19490
19797
  async generateImage(req, call = {}) {
19491
19798
  mediaRetryOptions(call);
19492
19799
  if (!isCatalogId(req.model)) {
19800
+ if (call.requireOverride)
19801
+ throw byokKeyMissing(req.model.provider, req.model.modelId);
19493
19802
  return passthroughImage({ ...req, model: req.model }, call);
19494
19803
  }
19495
19804
  const model = catalog.require(req.model);
@@ -19515,10 +19824,7 @@ function createModelKit(config, adapters) {
19515
19824
  });
19516
19825
  const startedAt = Date.now();
19517
19826
  const result = await adapter.generateImage(request, ctx);
19518
- const usage5 = timed(
19519
- { ...result.usage, model: model.id, unit: model.usage.unit },
19520
- startedAt
19521
- );
19827
+ const usage5 = rowUsage(ctx, result.usage, startedAt);
19522
19828
  await emit(usage5);
19523
19829
  const images = result.images.map(toGeneratedImage);
19524
19830
  const first = images[0];
@@ -19533,6 +19839,8 @@ function createModelKit(config, adapters) {
19533
19839
  async generateVideo(req, call = {}) {
19534
19840
  mediaRetryOptions(call);
19535
19841
  if (!isCatalogId(req.model)) {
19842
+ if (call.requireOverride)
19843
+ throw byokKeyMissing(req.model.provider, req.model.modelId);
19536
19844
  return passthroughVideo({ ...req, model: req.model }, call);
19537
19845
  }
19538
19846
  const model = catalog.require(req.model);
@@ -19558,7 +19866,7 @@ function createModelKit(config, adapters) {
19558
19866
  });
19559
19867
  const startedAt = Date.now();
19560
19868
  const job = await adapter.generateVideo(request, ctx);
19561
- return wrapVideoJob(model, job, warnings, startedAt);
19869
+ return wrapVideoJob(ctx, job, warnings, startedAt);
19562
19870
  },
19563
19871
  async resumeVideo(req, jobId, call = {}) {
19564
19872
  mediaRetryOptions(call);
@@ -19603,7 +19911,7 @@ function createModelKit(config, adapters) {
19603
19911
  });
19604
19912
  const startedAt = Date.now();
19605
19913
  const job = adapter.resumeVideo(request, jobId, ctx);
19606
- return wrapVideoJob(model, { ...job, jobId }, warnings, startedAt);
19914
+ return wrapVideoJob(ctx, { ...job, jobId }, warnings, startedAt);
19607
19915
  },
19608
19916
  async generateAudio(req, call = {}) {
19609
19917
  mediaRetryOptions(call);
@@ -19627,10 +19935,7 @@ function createModelKit(config, adapters) {
19627
19935
  }
19628
19936
  const startedAt = Date.now();
19629
19937
  const result = await adapter.generateAudio(resolved, ctx);
19630
- const usage5 = timed(
19631
- { ...result.usage, model: model.id, unit: model.usage.unit },
19632
- startedAt
19633
- );
19938
+ const usage5 = rowUsage(ctx, result.usage, startedAt);
19634
19939
  await emit(usage5);
19635
19940
  return { ...result, usage: usage5 };
19636
19941
  },
@@ -19643,7 +19948,7 @@ function createModelKit(config, adapters) {
19643
19948
  return "url" in ref ? { type: "file", data: ref.url, mediaType } : { type: "file", data: ref.bytes, mediaType };
19644
19949
  },
19645
19950
  languageModel(modelId, call = {}) {
19646
- const { entry, languageModel: model, provider } = textTarget(modelId, call);
19951
+ const { entry, languageModel: model, provider, keySource } = textTarget(modelId, call);
19647
19952
  if (model.specificationVersion !== "v3")
19648
19953
  throw new ModelKitError({
19649
19954
  code: "unsupported_option",
@@ -19654,7 +19959,8 @@ function createModelKit(config, adapters) {
19654
19959
  model,
19655
19960
  providerOptions: withoutModelkit(entry.providerOptions),
19656
19961
  catalog: entry,
19657
- usageProvider: provider
19962
+ usageProvider: provider,
19963
+ ...keySourceField(keySource)
19658
19964
  };
19659
19965
  },
19660
19966
  submitVideoTool: videoToolJobs.submit,
@@ -19670,7 +19976,7 @@ function createModelKit(config, adapters) {
19670
19976
  if (entry.type !== "text") return entry.adapter;
19671
19977
  return textUsageProvider(
19672
19978
  entry,
19673
- resolveAnthropicTransport(entry, config, call.tier, warnOnce)
19979
+ resolveAnthropicTransport(entry, config, call.tier, warnOnce, call.keyOverride)
19674
19980
  );
19675
19981
  },
19676
19982
  async generateText(options, call = {}) {
@@ -19719,7 +20025,7 @@ function createModelKit(config, adapters) {
19719
20025
  });
19720
20026
  },
19721
20027
  async generateObject(options, call = {}) {
19722
- const { entry, languageModel: languageModel2, provider } = textTarget(options.model, call);
20028
+ const { entry, languageModel: languageModel2, provider, keySource } = textTarget(options.model, call);
19723
20029
  const sdkOptions = {
19724
20030
  ...options,
19725
20031
  ...textAbortOptions(options.abortSignal, call.signal),
@@ -19730,16 +20036,17 @@ function createModelKit(config, adapters) {
19730
20036
  const result = await (0, import_ai5.generateObject)(sdkOptions);
19731
20037
  await emit(
19732
20038
  timed(
19733
- withRowUnit(
19734
- textUsageEvent(entry, provider, result.usage, result.providerMetadata)
19735
- ),
20039
+ withRowUnit({
20040
+ ...textUsageEvent(entry, provider, result.usage, result.providerMetadata),
20041
+ ...keySourceField(keySource)
20042
+ }),
19736
20043
  startedAt
19737
20044
  )
19738
20045
  );
19739
20046
  return result;
19740
20047
  },
19741
20048
  streamObject(options, call = {}) {
19742
- const { entry, languageModel: languageModel2, provider } = textTarget(options.model, call);
20049
+ const { entry, languageModel: languageModel2, provider, keySource } = textTarget(options.model, call);
19743
20050
  const callerOnFinish = options.onFinish;
19744
20051
  const startedAt = Date.now();
19745
20052
  const sdkOptions = {
@@ -19750,14 +20057,15 @@ function createModelKit(config, adapters) {
19750
20057
  onFinish: async (event) => {
19751
20058
  await emit(
19752
20059
  timed(
19753
- withRowUnit(
19754
- textUsageEvent(
20060
+ withRowUnit({
20061
+ ...textUsageEvent(
19755
20062
  entry,
19756
20063
  provider,
19757
20064
  event.usage,
19758
20065
  event.providerMetadata
19759
- )
19760
- ),
20066
+ ),
20067
+ ...keySourceField(keySource)
20068
+ }),
19761
20069
  startedAt
19762
20070
  )
19763
20071
  );
@@ -19801,6 +20109,7 @@ var describe = (modelId) => createDefaultModelKit().describe(modelId);
19801
20109
  ADAPTER_KEYS,
19802
20110
  ARRAY_INPUT_SPEC_KEYS,
19803
20111
  AUDIO_INPUT_SPEC_KEYS,
20112
+ BYOK_PROVIDERS,
19804
20113
  Catalog,
19805
20114
  CatalogModelSchema,
19806
20115
  CatalogModelSchemaBase,
@@ -19825,6 +20134,7 @@ var describe = (modelId) => createDefaultModelKit().describe(modelId);
19825
20134
  aiSdkTextAdapter,
19826
20135
  arkAdapter,
19827
20136
  aspectRatioToSize,
20137
+ byokProviderForModel,
19828
20138
  classifyHttpError,
19829
20139
  compareCatalogOrder,
19830
20140
  createDefaultModelKit,
@@ -19852,6 +20162,7 @@ var describe = (modelId) => createDefaultModelKit().describe(modelId);
19852
20162
  isListed,
19853
20163
  isListedOn,
19854
20164
  isModelKitError,
20165
+ keyOverrideFor,
19855
20166
  keysFromEnv,
19856
20167
  languageModel,
19857
20168
  liveCatalog,
@@ -19868,6 +20179,7 @@ var describe = (modelId) => createDefaultModelKit().describe(modelId);
19868
20179
  model3dSeedFits,
19869
20180
  model3dSkus,
19870
20181
  model3dTexture,
20182
+ modelsPoweredBy,
19871
20183
  nearestAspectRatio,
19872
20184
  normalizeExposure,
19873
20185
  openaiImageAdapter,
@@ -19898,6 +20210,7 @@ var describe = (modelId) => createDefaultModelKit().describe(modelId);
19898
20210
  streamObject,
19899
20211
  streamText,
19900
20212
  takesTargetAspectRatio,
20213
+ testProviderKey,
19901
20214
  textUsageEvent,
19902
20215
  toGeneratedImage,
19903
20216
  validateInputSpec,