@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.d.cts CHANGED
@@ -987,6 +987,12 @@ interface UsageEvent {
987
987
  * submission carries no `submittedAt`).
988
988
  */
989
989
  latencyMs?: number;
990
+ /**
991
+ * Whose provider account paid: "byok" when any required key came from the call's
992
+ * `keyOverride`, else the tier that served (an enterprise call that fell back to pro is
993
+ * "pro"). Unset on pass-through provider instances, whose keys the kit never sees.
994
+ */
995
+ keySource?: KeySource;
990
996
  raw?: unknown;
991
997
  }
992
998
  type ProviderKeyName = "openai" | "anthropic" | "google" | "xai" | "perplexity" | "deepseek" | "moonshot" | "minimax" | "ark" | "fal" | "replicate" | "prodia" | "higgsfield" | "luma" | "fish" | "elevenlabs" | "cloudflare";
@@ -1012,6 +1018,8 @@ type ProviderKeys = Partial<Record<ProviderKeyName, string>> & {
1012
1018
  };
1013
1019
  /** Which key set a call uses. Enterprise falls back to pro; sloosh never falls back. */
1014
1020
  type KeyTier = "pro" | "enterprise" | "sloosh";
1021
+ /** Which key set paid for a call; "byok" is the customer's own key (`CallContext.keyOverride`). */
1022
+ type KeySource = KeyTier | "byok";
1015
1023
  /** Key names a call can require, including the Bedrock credentials object. */
1016
1024
  type RequiredKeyName = ProviderKeyName | "aws";
1017
1025
  /** True when region is set AND (apiKey OR credentialProvider OR both static keys). */
@@ -1064,6 +1072,21 @@ interface ModelKitConfig {
1064
1072
  interface CallContext {
1065
1073
  /** "enterprise" picks keys.enterprise when every key for the provider is set, else falls back to pro. "sloosh" uses keys.sloosh only and never falls back. */
1066
1074
  tier?: KeyTier;
1075
+ /**
1076
+ * Customer keys for this one call (BYOK). A required name held here is used instead of
1077
+ * the tier's key and never falls back to it; names it does not hold resolve through
1078
+ * `tier` as usual. A blank value counts as absent. Higgsfield needs key and secret
1079
+ * together. `aws` is ignored: BYOK never covers Bedrock. A call served from these keys
1080
+ * goes direct to the provider, never through the Cloudflare gateway.
1081
+ */
1082
+ keyOverride?: Partial<ProviderKeys>;
1083
+ /**
1084
+ * The call was billed at the customer-key price, so it must not run on our key. When no
1085
+ * required key name comes from `keyOverride`, the call throws `byok_key_missing` before any
1086
+ * provider request. A call on a model outside the catalog always throws: the kit resolves no
1087
+ * key for it.
1088
+ */
1089
+ requireOverride?: boolean;
1067
1090
  signal?: AbortSignal;
1068
1091
  /** Media retries after the initial request. Set 0 when a durable host owns recovery.
1069
1092
  * Unset preserves adapter defaults. Successful pending-job polls are not retries.
@@ -1077,7 +1100,12 @@ interface CallContext {
1077
1100
  type ProviderErrorBody = string | JsonValue;
1078
1101
  type ModelKitErrorCode = "unknown_model" | "unsupported_option" | "missing_input" | "content_blocked" | "provider_rejected"
1079
1102
  /** The provider account is out of credit or quota (HTTP 402 and its body spellings). Never retried. */
1080
- | "provider_billing" | "timeout" | "auth" | "network" | "rate_limited";
1103
+ | "provider_billing" | "timeout" | "auth"
1104
+ /**
1105
+ * A call with `requireOverride` had no required key in `keyOverride`. Never retried, and not a
1106
+ * provider auth failure: the customer's key was never sent, so it says nothing about that key.
1107
+ */
1108
+ | "byok_key_missing" | "network" | "rate_limited";
1081
1109
  interface ModelKitErrorInit {
1082
1110
  code: ModelKitErrorCode;
1083
1111
  message: string;
@@ -1736,6 +1764,8 @@ type FalWebhookBody = z.infer<typeof falWebhookBodySchema>;
1736
1764
  interface AdapterContext {
1737
1765
  model: CatalogModel;
1738
1766
  keys: ProviderKeys;
1767
+ /** Which key set `keys` came from; the client stamps it on the call's usage events. */
1768
+ keySource?: KeySource;
1739
1769
  routing: Routing;
1740
1770
  /** Resolved transport of an Anthropic text row (see anthropic-transport.ts); unset means direct. */
1741
1771
  anthropicTransport?: AnthropicTransport;
@@ -1931,6 +1961,64 @@ declare function resolveKeys(config: ModelKitConfig, names: RequiredKeyName[], t
1931
1961
  /** Build a ProviderKeys map from env with the given prefix ("" for pro, "ENTERPRISE_" for enterprise). */
1932
1962
  declare function keysFromEnv(env: NodeJS.ProcessEnv, prefix?: string): ProviderKeys;
1933
1963
 
1964
+ type ByokProviderId = "ark" | "fal" | "replicate" | "openai" | "google";
1965
+ type ByokFieldId = "apiKey" | "accessKeyId" | "secretAccessKey" | "assetGroupId";
1966
+ interface ByokField {
1967
+ id: ByokFieldId;
1968
+ label: string;
1969
+ required: boolean;
1970
+ /** Never shown back after save. */
1971
+ secret: boolean;
1972
+ }
1973
+ interface ByokProvider {
1974
+ id: ByokProviderId;
1975
+ label: string;
1976
+ /** The kit key name `apiKey` fills in `CallContext.keyOverride`. */
1977
+ keyName: ProviderKeyName;
1978
+ fields: readonly ByokField[];
1979
+ }
1980
+ /** What a workspace stores for one provider. Only `apiKey` reaches the kit. */
1981
+ type ByokSecret = Partial<Record<ByokFieldId, string>> & {
1982
+ apiKey: string;
1983
+ };
1984
+ /**
1985
+ * Providers a workspace may bring its own key for. Claude (Anthropic and Bedrock) is not
1986
+ * offered. The Ark asset fields are for the BytePlus asset API (verified assets), which
1987
+ * the consumer calls itself; the kit uses only the ModelArk API key.
1988
+ */
1989
+ declare const BYOK_PROVIDERS: Readonly<Record<ByokProviderId, ByokProvider>>;
1990
+ /** The BYOK provider whose key runs this model, or null when the model cannot use one. */
1991
+ declare function byokProviderForModel(model: CatalogModel): ByokProviderId | null;
1992
+ /** The catalog rows a provider's key runs (Settings: "Powers N models"). */
1993
+ declare function modelsPoweredBy(provider: ByokProviderId, catalog: Iterable<CatalogModel>): CatalogModel[];
1994
+ /** A decrypted stored row, which may lack `apiKey` (an Ark row with only the asset fields). */
1995
+ type StoredSecret = Partial<Record<ByokFieldId, string>>;
1996
+ /** The `CallContext.keyOverride` for a workspace's stored secrets. Blank or missing keys are left out. */
1997
+ declare function keyOverrideFor(secrets: Partial<Record<ByokProviderId, StoredSecret>>): Partial<ProviderKeys>;
1998
+ /**
1999
+ * `credit` says whether the probe proved the account can pay for work. `"unknown"` means it
2000
+ * proved only the key: no current probe can see a balance (each answers 200 for a valid key
2001
+ * on an account with none), so a caller must not treat `ok` as "has credit".
2002
+ */
2003
+ type ByokTestResult = {
2004
+ ok: true;
2005
+ credit: "available" | "unknown";
2006
+ } | {
2007
+ ok: false;
2008
+ reason: "invalid" | "denied" | "unreachable" | "unverifiable";
2009
+ };
2010
+ /**
2011
+ * Checks a customer key with one free, read-only call. 400 and 401 are a bad key (Google
2012
+ * answers 400 `API_KEY_INVALID`); 402 and 403 are a real key the account refuses; 429,
2013
+ * 5xx and network failures are unreachable. A caller abort rethrows. Pass the kit's
2014
+ * `config.endpoints` so the Ark probe reaches the region the adapter calls.
2015
+ */
2016
+ declare function testProviderKey(provider: ByokProviderId, secret: StoredSecret, opts?: {
2017
+ fetch?: typeof fetch;
2018
+ signal?: AbortSignal;
2019
+ endpoints?: AdapterEndpoints;
2020
+ }): Promise<ByokTestResult>;
2021
+
1934
2022
  /**
1935
2023
  * One classifier for every adapter. Never retry safety blocks,
1936
2024
  * content_policy_violation, billing failures, or 4xx other than 429. Retry 429, 5xx, timeouts
@@ -2120,6 +2208,8 @@ interface LanguageModelHandle {
2120
2208
  catalog: CatalogModel;
2121
2209
  /** Usage-event `provider`: "bedrock" on Bedrock, else the vendor. */
2122
2210
  usageProvider: string;
2211
+ /** Usage-event `keySource`: `"byok"` when the model runs on the call's `keyOverride`. */
2212
+ keySource?: KeySource;
2123
2213
  }
2124
2214
  type AdapterRegistry = Partial<Record<AdapterId, Adapter>>;
2125
2215
  declare function createModelKit(config: ModelKitConfig, adapters: AdapterRegistry): ModelKit;
@@ -2293,4 +2383,4 @@ declare function describeThrown(cause: unknown): ThrownErrorInfo;
2293
2383
  /** Add the AI SDK `GeneratedFile` accessors to adapter image bytes. base64 is computed on first read. */
2294
2384
  declare function toGeneratedImage(image: ImageBytes): GeneratedImage;
2295
2385
 
2296
- export { ADAPTER_IDS, ADAPTER_KEYS, ARRAY_INPUT_SPEC_KEYS, AUDIO_INPUT_SPEC_KEYS, type Adapter, type AdapterContext, type AdapterEndpoints, type AdapterId, type AdapterRegistry, type AiTextProviderOptions, type ArrayInputSpecKey, type AspectRatio, type AudioNodeMethods, type AudioOutput, type AudioRequest, type AudioResult, type CallContext, Catalog, type CatalogAuth, type CatalogCache, type CatalogCapabilities, type CatalogDisplay, type CatalogEnvelope, type CatalogModel, CatalogModelSchema, CatalogModelSchemaBase, type CatalogOrigin, CatalogSchema, type CatalogSource, type CatalogTextModel, DEFAULT_ADAPTERS, type DataOnlyRow, type DataOnlyVerdict, type DefaultObjectOutput, type DubbingOutcome, type DubbingRequest, type DubbingResult, type Exposure, ExposureSchema, type FalWebhookBody, type GeneratedImage, IMAGE_INPUT_SPEC_KEYS, INPUT_SPEC_SUPPORTS_KEYS, type ImageBytes, type ImageCallOptions, type ImageCallResult, type ImageQuality, type ImageRequest, type ImageResult, type ImageSafetySetting, type ImageSize, type InputSpec, type InputSpecDimensions, type InputSpecIssue, type InputSpecKey, InputSpecSchema, type JsonObject, JsonObjectSchema, type JsonPrimitive, type JsonValue, JsonValueSchema, type KeyTier, type LanguageModelHandle, type LanguageOption, type Lifecycle, type LipsyncRequest, type LipsyncResult, type LiveCatalogState, MODEL3D_IMAGE_SLOTS, MODEL3D_MODELS, MODELS, type MaskBox, type MaskPoint, type MediaJobCallContext, type MediaNodeDefaults, type MediaOutput, type MediaPart, type MediaRef, type Model3dCall, type Model3dConstraints, type Model3dEndpoints, type Model3dFamily, type Model3dInputRefusal, type Model3dPricedInputs, type Model3dPricedOptions, type Model3dRequest, type Model3dResult, type Model3dStatus, type Model3dSubmission, type Model3dTexture, type Model3dViews, type Model3dWired, type ModelConstraints, type ModelKit, type ModelKitConfig, ModelKitError, type ModelKitErrorCode, type ModelKitErrorInit, type ModelType, type ModelkitGenerateObjectOptions, type ModelkitGenerateTextOptions, type ModelkitStreamObjectOptions, type ModelkitStreamTextOptions, type ObjectOutput, type ObjectResult, type OnUnsupported, type OutputFormat, type PricingKind, type PrimeCatalogResult, type PromptConventions, type ProviderErrorBody, type ProviderKeyName, type ProviderKeys, type ProviderOptionValue, type ProviderOptions, type QuarantineResult, type ReferenceLimits, type ReferenceSyntax, type RequiredInput, type RequiredKeyName, type ResolveResult, type Routing, SURFACES, type SpeechRequest, type SubtitleOptions, type SubtitleTextStyle, type SupportedOption, type Surface, SurfaceSchema, type TextMethods, type TextModelInstance, type TranscriptWord, type TranscriptionRequest, type TranscriptionResult, type UpscaleOptions, type UsageEvent, type UsageModality, type UsageUnit, VIDEO_INPUT_SPEC_KEYS, VIDEO_TOOL_MODELS, type VideoCallJob, type VideoCallOptions, type VideoJob, type VideoModel, type VideoPixelLimits, type VideoRequest, type VideoResolution, VideoResolutionSchema, type VideoResult, type VideoSecondsLimits, type VideoToolCallContext, type VideoToolConstraints, type VideoToolKind, type VideoToolOutputFormat, type VideoToolOutputSpec, type VideoToolPlan, type VideoToolRequest, type VideoToolResult, type VideoToolSource, type VideoToolStatus, type VideoToolSubmission, type VoiceCandidate, type VoiceChangeRequest, type VoiceCloneRequest, type VoiceCloneResult, type VoiceCloneState, type VoiceDeleteRequest, type VoiceDesignRequest, type VoiceDesignResult, type VoiceGender, type VoiceOption, type VoiceSample, type Warning, adapterServesType, aiSdkTextAdapter, arkAdapter, aspectRatioToSize, classifyHttpError, compareCatalogOrder, createDefaultModelKit, createModelKit, dataOnlyCapable, describe, describeThrown, elevenLabsAdapter, generateImage as experimental_generateImage, falAdapter, falWebhookBodySchema, fileCatalogCache, fishAdapter, generateAudio, generateImage, generateObject, generateText, generateVideo, googleGenaiAdapter, googleImageAdapter, hasAwsCredentials, higgsfieldAdapter, isArrayInputSpecKey, isInputSpecKey, isListed, isListedOn, isModelKitError, keysFromEnv, languageModel, liveCatalog, liveState, lumaAdapter, lumaReframeTooTall, mergeTextProviderOptions, missingTierKeys, model3dCall, model3dConstraints, model3dInputRefusal, model3dPricingSku, model3dResolution, model3dSeedFits, model3dSkus, model3dTexture, nearestAspectRatio, normalizeExposure, openaiImageAdapter, passthroughTextModel, planVideoTool, pollUntil, prepareMediaPart, primeCatalog, prodiaAdapter, readErrorBody, replicateAdapter, resetLiveCatalog, resolutionTier, resolveAudioOptions, resolveDubbingOptions, resolveImageOptions, resolveKeys, resolveLipsyncOptions, resolveSpeechOptions, resolveTranscriptionOptions, resolveVideoOptions, resolveVoiceChangeOptions, resolveVoiceCloneOptions, resolveVoiceDesignOptions, shouldRetry, sleep, sortCatalogRows, streamObject, streamText, takesTargetAspectRatio, textUsageEvent, toGeneratedImage, validateInputSpec, videoLengthViolation, videoSizeViolation, videoToolConstraints, withRetry, xaiVideoAdapter };
2386
+ export { ADAPTER_IDS, ADAPTER_KEYS, ARRAY_INPUT_SPEC_KEYS, AUDIO_INPUT_SPEC_KEYS, type Adapter, type AdapterContext, type AdapterEndpoints, type AdapterId, type AdapterRegistry, type AiTextProviderOptions, type ArrayInputSpecKey, type AspectRatio, type AudioNodeMethods, type AudioOutput, type AudioRequest, type AudioResult, BYOK_PROVIDERS, type ByokField, type ByokFieldId, type ByokProvider, type ByokProviderId, type ByokSecret, type ByokTestResult, type CallContext, Catalog, type CatalogAuth, type CatalogCache, type CatalogCapabilities, type CatalogDisplay, type CatalogEnvelope, type CatalogModel, CatalogModelSchema, CatalogModelSchemaBase, type CatalogOrigin, CatalogSchema, type CatalogSource, type CatalogTextModel, DEFAULT_ADAPTERS, type DataOnlyRow, type DataOnlyVerdict, type DefaultObjectOutput, type DubbingOutcome, type DubbingRequest, type DubbingResult, type Exposure, ExposureSchema, type FalWebhookBody, type GeneratedImage, IMAGE_INPUT_SPEC_KEYS, INPUT_SPEC_SUPPORTS_KEYS, type ImageBytes, type ImageCallOptions, type ImageCallResult, type ImageQuality, type ImageRequest, type ImageResult, type ImageSafetySetting, type ImageSize, type InputSpec, type InputSpecDimensions, type InputSpecIssue, type InputSpecKey, InputSpecSchema, type JsonObject, JsonObjectSchema, type JsonPrimitive, type JsonValue, JsonValueSchema, type KeySource, type KeyTier, type LanguageModelHandle, type LanguageOption, type Lifecycle, type LipsyncRequest, type LipsyncResult, type LiveCatalogState, MODEL3D_IMAGE_SLOTS, MODEL3D_MODELS, MODELS, type MaskBox, type MaskPoint, type MediaJobCallContext, type MediaNodeDefaults, type MediaOutput, type MediaPart, type MediaRef, type Model3dCall, type Model3dConstraints, type Model3dEndpoints, type Model3dFamily, type Model3dInputRefusal, type Model3dPricedInputs, type Model3dPricedOptions, type Model3dRequest, type Model3dResult, type Model3dStatus, type Model3dSubmission, type Model3dTexture, type Model3dViews, type Model3dWired, type ModelConstraints, type ModelKit, type ModelKitConfig, ModelKitError, type ModelKitErrorCode, type ModelKitErrorInit, type ModelType, type ModelkitGenerateObjectOptions, type ModelkitGenerateTextOptions, type ModelkitStreamObjectOptions, type ModelkitStreamTextOptions, type ObjectOutput, type ObjectResult, type OnUnsupported, type OutputFormat, type PricingKind, type PrimeCatalogResult, type PromptConventions, type ProviderErrorBody, type ProviderKeyName, type ProviderKeys, type ProviderOptionValue, type ProviderOptions, type QuarantineResult, type ReferenceLimits, type ReferenceSyntax, type RequiredInput, type RequiredKeyName, type ResolveResult, type Routing, SURFACES, type SpeechRequest, type SubtitleOptions, type SubtitleTextStyle, type SupportedOption, type Surface, SurfaceSchema, type TextMethods, type TextModelInstance, type TranscriptWord, type TranscriptionRequest, type TranscriptionResult, type UpscaleOptions, type UsageEvent, type UsageModality, type UsageUnit, VIDEO_INPUT_SPEC_KEYS, VIDEO_TOOL_MODELS, type VideoCallJob, type VideoCallOptions, type VideoJob, type VideoModel, type VideoPixelLimits, type VideoRequest, type VideoResolution, VideoResolutionSchema, type VideoResult, type VideoSecondsLimits, type VideoToolCallContext, type VideoToolConstraints, type VideoToolKind, type VideoToolOutputFormat, type VideoToolOutputSpec, type VideoToolPlan, type VideoToolRequest, type VideoToolResult, type VideoToolSource, type VideoToolStatus, type VideoToolSubmission, type VoiceCandidate, type VoiceChangeRequest, type VoiceCloneRequest, type VoiceCloneResult, type VoiceCloneState, type VoiceDeleteRequest, type VoiceDesignRequest, type VoiceDesignResult, type VoiceGender, type VoiceOption, type VoiceSample, type Warning, adapterServesType, aiSdkTextAdapter, arkAdapter, aspectRatioToSize, byokProviderForModel, classifyHttpError, compareCatalogOrder, createDefaultModelKit, createModelKit, dataOnlyCapable, describe, describeThrown, elevenLabsAdapter, generateImage as experimental_generateImage, falAdapter, falWebhookBodySchema, fileCatalogCache, fishAdapter, generateAudio, generateImage, generateObject, generateText, generateVideo, googleGenaiAdapter, googleImageAdapter, hasAwsCredentials, higgsfieldAdapter, isArrayInputSpecKey, isInputSpecKey, isListed, isListedOn, isModelKitError, keyOverrideFor, keysFromEnv, languageModel, liveCatalog, liveState, lumaAdapter, lumaReframeTooTall, mergeTextProviderOptions, missingTierKeys, model3dCall, model3dConstraints, model3dInputRefusal, model3dPricingSku, model3dResolution, model3dSeedFits, model3dSkus, model3dTexture, modelsPoweredBy, nearestAspectRatio, normalizeExposure, openaiImageAdapter, passthroughTextModel, planVideoTool, pollUntil, prepareMediaPart, primeCatalog, prodiaAdapter, readErrorBody, replicateAdapter, resetLiveCatalog, resolutionTier, resolveAudioOptions, resolveDubbingOptions, resolveImageOptions, resolveKeys, resolveLipsyncOptions, resolveSpeechOptions, resolveTranscriptionOptions, resolveVideoOptions, resolveVoiceChangeOptions, resolveVoiceCloneOptions, resolveVoiceDesignOptions, shouldRetry, sleep, sortCatalogRows, streamObject, streamText, takesTargetAspectRatio, testProviderKey, textUsageEvent, toGeneratedImage, validateInputSpec, videoLengthViolation, videoSizeViolation, videoToolConstraints, withRetry, xaiVideoAdapter };
package/dist/index.d.ts CHANGED
@@ -987,6 +987,12 @@ interface UsageEvent {
987
987
  * submission carries no `submittedAt`).
988
988
  */
989
989
  latencyMs?: number;
990
+ /**
991
+ * Whose provider account paid: "byok" when any required key came from the call's
992
+ * `keyOverride`, else the tier that served (an enterprise call that fell back to pro is
993
+ * "pro"). Unset on pass-through provider instances, whose keys the kit never sees.
994
+ */
995
+ keySource?: KeySource;
990
996
  raw?: unknown;
991
997
  }
992
998
  type ProviderKeyName = "openai" | "anthropic" | "google" | "xai" | "perplexity" | "deepseek" | "moonshot" | "minimax" | "ark" | "fal" | "replicate" | "prodia" | "higgsfield" | "luma" | "fish" | "elevenlabs" | "cloudflare";
@@ -1012,6 +1018,8 @@ type ProviderKeys = Partial<Record<ProviderKeyName, string>> & {
1012
1018
  };
1013
1019
  /** Which key set a call uses. Enterprise falls back to pro; sloosh never falls back. */
1014
1020
  type KeyTier = "pro" | "enterprise" | "sloosh";
1021
+ /** Which key set paid for a call; "byok" is the customer's own key (`CallContext.keyOverride`). */
1022
+ type KeySource = KeyTier | "byok";
1015
1023
  /** Key names a call can require, including the Bedrock credentials object. */
1016
1024
  type RequiredKeyName = ProviderKeyName | "aws";
1017
1025
  /** True when region is set AND (apiKey OR credentialProvider OR both static keys). */
@@ -1064,6 +1072,21 @@ interface ModelKitConfig {
1064
1072
  interface CallContext {
1065
1073
  /** "enterprise" picks keys.enterprise when every key for the provider is set, else falls back to pro. "sloosh" uses keys.sloosh only and never falls back. */
1066
1074
  tier?: KeyTier;
1075
+ /**
1076
+ * Customer keys for this one call (BYOK). A required name held here is used instead of
1077
+ * the tier's key and never falls back to it; names it does not hold resolve through
1078
+ * `tier` as usual. A blank value counts as absent. Higgsfield needs key and secret
1079
+ * together. `aws` is ignored: BYOK never covers Bedrock. A call served from these keys
1080
+ * goes direct to the provider, never through the Cloudflare gateway.
1081
+ */
1082
+ keyOverride?: Partial<ProviderKeys>;
1083
+ /**
1084
+ * The call was billed at the customer-key price, so it must not run on our key. When no
1085
+ * required key name comes from `keyOverride`, the call throws `byok_key_missing` before any
1086
+ * provider request. A call on a model outside the catalog always throws: the kit resolves no
1087
+ * key for it.
1088
+ */
1089
+ requireOverride?: boolean;
1067
1090
  signal?: AbortSignal;
1068
1091
  /** Media retries after the initial request. Set 0 when a durable host owns recovery.
1069
1092
  * Unset preserves adapter defaults. Successful pending-job polls are not retries.
@@ -1077,7 +1100,12 @@ interface CallContext {
1077
1100
  type ProviderErrorBody = string | JsonValue;
1078
1101
  type ModelKitErrorCode = "unknown_model" | "unsupported_option" | "missing_input" | "content_blocked" | "provider_rejected"
1079
1102
  /** The provider account is out of credit or quota (HTTP 402 and its body spellings). Never retried. */
1080
- | "provider_billing" | "timeout" | "auth" | "network" | "rate_limited";
1103
+ | "provider_billing" | "timeout" | "auth"
1104
+ /**
1105
+ * A call with `requireOverride` had no required key in `keyOverride`. Never retried, and not a
1106
+ * provider auth failure: the customer's key was never sent, so it says nothing about that key.
1107
+ */
1108
+ | "byok_key_missing" | "network" | "rate_limited";
1081
1109
  interface ModelKitErrorInit {
1082
1110
  code: ModelKitErrorCode;
1083
1111
  message: string;
@@ -1736,6 +1764,8 @@ type FalWebhookBody = z.infer<typeof falWebhookBodySchema>;
1736
1764
  interface AdapterContext {
1737
1765
  model: CatalogModel;
1738
1766
  keys: ProviderKeys;
1767
+ /** Which key set `keys` came from; the client stamps it on the call's usage events. */
1768
+ keySource?: KeySource;
1739
1769
  routing: Routing;
1740
1770
  /** Resolved transport of an Anthropic text row (see anthropic-transport.ts); unset means direct. */
1741
1771
  anthropicTransport?: AnthropicTransport;
@@ -1931,6 +1961,64 @@ declare function resolveKeys(config: ModelKitConfig, names: RequiredKeyName[], t
1931
1961
  /** Build a ProviderKeys map from env with the given prefix ("" for pro, "ENTERPRISE_" for enterprise). */
1932
1962
  declare function keysFromEnv(env: NodeJS.ProcessEnv, prefix?: string): ProviderKeys;
1933
1963
 
1964
+ type ByokProviderId = "ark" | "fal" | "replicate" | "openai" | "google";
1965
+ type ByokFieldId = "apiKey" | "accessKeyId" | "secretAccessKey" | "assetGroupId";
1966
+ interface ByokField {
1967
+ id: ByokFieldId;
1968
+ label: string;
1969
+ required: boolean;
1970
+ /** Never shown back after save. */
1971
+ secret: boolean;
1972
+ }
1973
+ interface ByokProvider {
1974
+ id: ByokProviderId;
1975
+ label: string;
1976
+ /** The kit key name `apiKey` fills in `CallContext.keyOverride`. */
1977
+ keyName: ProviderKeyName;
1978
+ fields: readonly ByokField[];
1979
+ }
1980
+ /** What a workspace stores for one provider. Only `apiKey` reaches the kit. */
1981
+ type ByokSecret = Partial<Record<ByokFieldId, string>> & {
1982
+ apiKey: string;
1983
+ };
1984
+ /**
1985
+ * Providers a workspace may bring its own key for. Claude (Anthropic and Bedrock) is not
1986
+ * offered. The Ark asset fields are for the BytePlus asset API (verified assets), which
1987
+ * the consumer calls itself; the kit uses only the ModelArk API key.
1988
+ */
1989
+ declare const BYOK_PROVIDERS: Readonly<Record<ByokProviderId, ByokProvider>>;
1990
+ /** The BYOK provider whose key runs this model, or null when the model cannot use one. */
1991
+ declare function byokProviderForModel(model: CatalogModel): ByokProviderId | null;
1992
+ /** The catalog rows a provider's key runs (Settings: "Powers N models"). */
1993
+ declare function modelsPoweredBy(provider: ByokProviderId, catalog: Iterable<CatalogModel>): CatalogModel[];
1994
+ /** A decrypted stored row, which may lack `apiKey` (an Ark row with only the asset fields). */
1995
+ type StoredSecret = Partial<Record<ByokFieldId, string>>;
1996
+ /** The `CallContext.keyOverride` for a workspace's stored secrets. Blank or missing keys are left out. */
1997
+ declare function keyOverrideFor(secrets: Partial<Record<ByokProviderId, StoredSecret>>): Partial<ProviderKeys>;
1998
+ /**
1999
+ * `credit` says whether the probe proved the account can pay for work. `"unknown"` means it
2000
+ * proved only the key: no current probe can see a balance (each answers 200 for a valid key
2001
+ * on an account with none), so a caller must not treat `ok` as "has credit".
2002
+ */
2003
+ type ByokTestResult = {
2004
+ ok: true;
2005
+ credit: "available" | "unknown";
2006
+ } | {
2007
+ ok: false;
2008
+ reason: "invalid" | "denied" | "unreachable" | "unverifiable";
2009
+ };
2010
+ /**
2011
+ * Checks a customer key with one free, read-only call. 400 and 401 are a bad key (Google
2012
+ * answers 400 `API_KEY_INVALID`); 402 and 403 are a real key the account refuses; 429,
2013
+ * 5xx and network failures are unreachable. A caller abort rethrows. Pass the kit's
2014
+ * `config.endpoints` so the Ark probe reaches the region the adapter calls.
2015
+ */
2016
+ declare function testProviderKey(provider: ByokProviderId, secret: StoredSecret, opts?: {
2017
+ fetch?: typeof fetch;
2018
+ signal?: AbortSignal;
2019
+ endpoints?: AdapterEndpoints;
2020
+ }): Promise<ByokTestResult>;
2021
+
1934
2022
  /**
1935
2023
  * One classifier for every adapter. Never retry safety blocks,
1936
2024
  * content_policy_violation, billing failures, or 4xx other than 429. Retry 429, 5xx, timeouts
@@ -2120,6 +2208,8 @@ interface LanguageModelHandle {
2120
2208
  catalog: CatalogModel;
2121
2209
  /** Usage-event `provider`: "bedrock" on Bedrock, else the vendor. */
2122
2210
  usageProvider: string;
2211
+ /** Usage-event `keySource`: `"byok"` when the model runs on the call's `keyOverride`. */
2212
+ keySource?: KeySource;
2123
2213
  }
2124
2214
  type AdapterRegistry = Partial<Record<AdapterId, Adapter>>;
2125
2215
  declare function createModelKit(config: ModelKitConfig, adapters: AdapterRegistry): ModelKit;
@@ -2293,4 +2383,4 @@ declare function describeThrown(cause: unknown): ThrownErrorInfo;
2293
2383
  /** Add the AI SDK `GeneratedFile` accessors to adapter image bytes. base64 is computed on first read. */
2294
2384
  declare function toGeneratedImage(image: ImageBytes): GeneratedImage;
2295
2385
 
2296
- export { ADAPTER_IDS, ADAPTER_KEYS, ARRAY_INPUT_SPEC_KEYS, AUDIO_INPUT_SPEC_KEYS, type Adapter, type AdapterContext, type AdapterEndpoints, type AdapterId, type AdapterRegistry, type AiTextProviderOptions, type ArrayInputSpecKey, type AspectRatio, type AudioNodeMethods, type AudioOutput, type AudioRequest, type AudioResult, type CallContext, Catalog, type CatalogAuth, type CatalogCache, type CatalogCapabilities, type CatalogDisplay, type CatalogEnvelope, type CatalogModel, CatalogModelSchema, CatalogModelSchemaBase, type CatalogOrigin, CatalogSchema, type CatalogSource, type CatalogTextModel, DEFAULT_ADAPTERS, type DataOnlyRow, type DataOnlyVerdict, type DefaultObjectOutput, type DubbingOutcome, type DubbingRequest, type DubbingResult, type Exposure, ExposureSchema, type FalWebhookBody, type GeneratedImage, IMAGE_INPUT_SPEC_KEYS, INPUT_SPEC_SUPPORTS_KEYS, type ImageBytes, type ImageCallOptions, type ImageCallResult, type ImageQuality, type ImageRequest, type ImageResult, type ImageSafetySetting, type ImageSize, type InputSpec, type InputSpecDimensions, type InputSpecIssue, type InputSpecKey, InputSpecSchema, type JsonObject, JsonObjectSchema, type JsonPrimitive, type JsonValue, JsonValueSchema, type KeyTier, type LanguageModelHandle, type LanguageOption, type Lifecycle, type LipsyncRequest, type LipsyncResult, type LiveCatalogState, MODEL3D_IMAGE_SLOTS, MODEL3D_MODELS, MODELS, type MaskBox, type MaskPoint, type MediaJobCallContext, type MediaNodeDefaults, type MediaOutput, type MediaPart, type MediaRef, type Model3dCall, type Model3dConstraints, type Model3dEndpoints, type Model3dFamily, type Model3dInputRefusal, type Model3dPricedInputs, type Model3dPricedOptions, type Model3dRequest, type Model3dResult, type Model3dStatus, type Model3dSubmission, type Model3dTexture, type Model3dViews, type Model3dWired, type ModelConstraints, type ModelKit, type ModelKitConfig, ModelKitError, type ModelKitErrorCode, type ModelKitErrorInit, type ModelType, type ModelkitGenerateObjectOptions, type ModelkitGenerateTextOptions, type ModelkitStreamObjectOptions, type ModelkitStreamTextOptions, type ObjectOutput, type ObjectResult, type OnUnsupported, type OutputFormat, type PricingKind, type PrimeCatalogResult, type PromptConventions, type ProviderErrorBody, type ProviderKeyName, type ProviderKeys, type ProviderOptionValue, type ProviderOptions, type QuarantineResult, type ReferenceLimits, type ReferenceSyntax, type RequiredInput, type RequiredKeyName, type ResolveResult, type Routing, SURFACES, type SpeechRequest, type SubtitleOptions, type SubtitleTextStyle, type SupportedOption, type Surface, SurfaceSchema, type TextMethods, type TextModelInstance, type TranscriptWord, type TranscriptionRequest, type TranscriptionResult, type UpscaleOptions, type UsageEvent, type UsageModality, type UsageUnit, VIDEO_INPUT_SPEC_KEYS, VIDEO_TOOL_MODELS, type VideoCallJob, type VideoCallOptions, type VideoJob, type VideoModel, type VideoPixelLimits, type VideoRequest, type VideoResolution, VideoResolutionSchema, type VideoResult, type VideoSecondsLimits, type VideoToolCallContext, type VideoToolConstraints, type VideoToolKind, type VideoToolOutputFormat, type VideoToolOutputSpec, type VideoToolPlan, type VideoToolRequest, type VideoToolResult, type VideoToolSource, type VideoToolStatus, type VideoToolSubmission, type VoiceCandidate, type VoiceChangeRequest, type VoiceCloneRequest, type VoiceCloneResult, type VoiceCloneState, type VoiceDeleteRequest, type VoiceDesignRequest, type VoiceDesignResult, type VoiceGender, type VoiceOption, type VoiceSample, type Warning, adapterServesType, aiSdkTextAdapter, arkAdapter, aspectRatioToSize, classifyHttpError, compareCatalogOrder, createDefaultModelKit, createModelKit, dataOnlyCapable, describe, describeThrown, elevenLabsAdapter, generateImage as experimental_generateImage, falAdapter, falWebhookBodySchema, fileCatalogCache, fishAdapter, generateAudio, generateImage, generateObject, generateText, generateVideo, googleGenaiAdapter, googleImageAdapter, hasAwsCredentials, higgsfieldAdapter, isArrayInputSpecKey, isInputSpecKey, isListed, isListedOn, isModelKitError, keysFromEnv, languageModel, liveCatalog, liveState, lumaAdapter, lumaReframeTooTall, mergeTextProviderOptions, missingTierKeys, model3dCall, model3dConstraints, model3dInputRefusal, model3dPricingSku, model3dResolution, model3dSeedFits, model3dSkus, model3dTexture, nearestAspectRatio, normalizeExposure, openaiImageAdapter, passthroughTextModel, planVideoTool, pollUntil, prepareMediaPart, primeCatalog, prodiaAdapter, readErrorBody, replicateAdapter, resetLiveCatalog, resolutionTier, resolveAudioOptions, resolveDubbingOptions, resolveImageOptions, resolveKeys, resolveLipsyncOptions, resolveSpeechOptions, resolveTranscriptionOptions, resolveVideoOptions, resolveVoiceChangeOptions, resolveVoiceCloneOptions, resolveVoiceDesignOptions, shouldRetry, sleep, sortCatalogRows, streamObject, streamText, takesTargetAspectRatio, textUsageEvent, toGeneratedImage, validateInputSpec, videoLengthViolation, videoSizeViolation, videoToolConstraints, withRetry, xaiVideoAdapter };
2386
+ export { ADAPTER_IDS, ADAPTER_KEYS, ARRAY_INPUT_SPEC_KEYS, AUDIO_INPUT_SPEC_KEYS, type Adapter, type AdapterContext, type AdapterEndpoints, type AdapterId, type AdapterRegistry, type AiTextProviderOptions, type ArrayInputSpecKey, type AspectRatio, type AudioNodeMethods, type AudioOutput, type AudioRequest, type AudioResult, BYOK_PROVIDERS, type ByokField, type ByokFieldId, type ByokProvider, type ByokProviderId, type ByokSecret, type ByokTestResult, type CallContext, Catalog, type CatalogAuth, type CatalogCache, type CatalogCapabilities, type CatalogDisplay, type CatalogEnvelope, type CatalogModel, CatalogModelSchema, CatalogModelSchemaBase, type CatalogOrigin, CatalogSchema, type CatalogSource, type CatalogTextModel, DEFAULT_ADAPTERS, type DataOnlyRow, type DataOnlyVerdict, type DefaultObjectOutput, type DubbingOutcome, type DubbingRequest, type DubbingResult, type Exposure, ExposureSchema, type FalWebhookBody, type GeneratedImage, IMAGE_INPUT_SPEC_KEYS, INPUT_SPEC_SUPPORTS_KEYS, type ImageBytes, type ImageCallOptions, type ImageCallResult, type ImageQuality, type ImageRequest, type ImageResult, type ImageSafetySetting, type ImageSize, type InputSpec, type InputSpecDimensions, type InputSpecIssue, type InputSpecKey, InputSpecSchema, type JsonObject, JsonObjectSchema, type JsonPrimitive, type JsonValue, JsonValueSchema, type KeySource, type KeyTier, type LanguageModelHandle, type LanguageOption, type Lifecycle, type LipsyncRequest, type LipsyncResult, type LiveCatalogState, MODEL3D_IMAGE_SLOTS, MODEL3D_MODELS, MODELS, type MaskBox, type MaskPoint, type MediaJobCallContext, type MediaNodeDefaults, type MediaOutput, type MediaPart, type MediaRef, type Model3dCall, type Model3dConstraints, type Model3dEndpoints, type Model3dFamily, type Model3dInputRefusal, type Model3dPricedInputs, type Model3dPricedOptions, type Model3dRequest, type Model3dResult, type Model3dStatus, type Model3dSubmission, type Model3dTexture, type Model3dViews, type Model3dWired, type ModelConstraints, type ModelKit, type ModelKitConfig, ModelKitError, type ModelKitErrorCode, type ModelKitErrorInit, type ModelType, type ModelkitGenerateObjectOptions, type ModelkitGenerateTextOptions, type ModelkitStreamObjectOptions, type ModelkitStreamTextOptions, type ObjectOutput, type ObjectResult, type OnUnsupported, type OutputFormat, type PricingKind, type PrimeCatalogResult, type PromptConventions, type ProviderErrorBody, type ProviderKeyName, type ProviderKeys, type ProviderOptionValue, type ProviderOptions, type QuarantineResult, type ReferenceLimits, type ReferenceSyntax, type RequiredInput, type RequiredKeyName, type ResolveResult, type Routing, SURFACES, type SpeechRequest, type SubtitleOptions, type SubtitleTextStyle, type SupportedOption, type Surface, SurfaceSchema, type TextMethods, type TextModelInstance, type TranscriptWord, type TranscriptionRequest, type TranscriptionResult, type UpscaleOptions, type UsageEvent, type UsageModality, type UsageUnit, VIDEO_INPUT_SPEC_KEYS, VIDEO_TOOL_MODELS, type VideoCallJob, type VideoCallOptions, type VideoJob, type VideoModel, type VideoPixelLimits, type VideoRequest, type VideoResolution, VideoResolutionSchema, type VideoResult, type VideoSecondsLimits, type VideoToolCallContext, type VideoToolConstraints, type VideoToolKind, type VideoToolOutputFormat, type VideoToolOutputSpec, type VideoToolPlan, type VideoToolRequest, type VideoToolResult, type VideoToolSource, type VideoToolStatus, type VideoToolSubmission, type VoiceCandidate, type VoiceChangeRequest, type VoiceCloneRequest, type VoiceCloneResult, type VoiceCloneState, type VoiceDeleteRequest, type VoiceDesignRequest, type VoiceDesignResult, type VoiceGender, type VoiceOption, type VoiceSample, type Warning, adapterServesType, aiSdkTextAdapter, arkAdapter, aspectRatioToSize, byokProviderForModel, classifyHttpError, compareCatalogOrder, createDefaultModelKit, createModelKit, dataOnlyCapable, describe, describeThrown, elevenLabsAdapter, generateImage as experimental_generateImage, falAdapter, falWebhookBodySchema, fileCatalogCache, fishAdapter, generateAudio, generateImage, generateObject, generateText, generateVideo, googleGenaiAdapter, googleImageAdapter, hasAwsCredentials, higgsfieldAdapter, isArrayInputSpecKey, isInputSpecKey, isListed, isListedOn, isModelKitError, keyOverrideFor, keysFromEnv, languageModel, liveCatalog, liveState, lumaAdapter, lumaReframeTooTall, mergeTextProviderOptions, missingTierKeys, model3dCall, model3dConstraints, model3dInputRefusal, model3dPricingSku, model3dResolution, model3dSeedFits, model3dSkus, model3dTexture, modelsPoweredBy, nearestAspectRatio, normalizeExposure, openaiImageAdapter, passthroughTextModel, planVideoTool, pollUntil, prepareMediaPart, primeCatalog, prodiaAdapter, readErrorBody, replicateAdapter, resetLiveCatalog, resolutionTier, resolveAudioOptions, resolveDubbingOptions, resolveImageOptions, resolveKeys, resolveLipsyncOptions, resolveSpeechOptions, resolveTranscriptionOptions, resolveVideoOptions, resolveVoiceChangeOptions, resolveVoiceCloneOptions, resolveVoiceDesignOptions, shouldRetry, sleep, sortCatalogRows, streamObject, streamText, takesTargetAspectRatio, testProviderKey, textUsageEvent, toGeneratedImage, validateInputSpec, videoLengthViolation, videoSizeViolation, videoToolConstraints, withRetry, xaiVideoAdapter };