@broberg/ai-sdk 0.50.1 → 0.52.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.ts CHANGED
@@ -2425,6 +2425,12 @@ declare const ttsInputSchema: z.ZodObject<{
2425
2425
  rate?: number | undefined;
2426
2426
  }>;
2427
2427
  declare const aiConfigSchema: z.ZodObject<{
2428
+ /** F069.1 — customer-key mode. Every provider must be built with byokAdapter(), so no
2429
+ * call can fall back to the fleet's env keys; createAI throws at setup otherwise. */
2430
+ byok: z.ZodOptional<z.ZodBoolean>;
2431
+ /** F069.2 — attribution labels stamped on EVERY call's usage (and so on every cost-sink
2432
+ * row), e.g. { byok: "true", tenantId }. A call's own `labels` win on the same key. */
2433
+ labels: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
2428
2434
  /** F039.2 — client-wide opt-out from prompt caching (default: on where the
2429
2435
  * provider supports it). A per-call `promptCache` wins over this. */
2430
2436
  promptCache: z.ZodOptional<z.ZodBoolean>;
@@ -2468,6 +2474,8 @@ declare const aiConfigSchema: z.ZodObject<{
2468
2474
  }>>;
2469
2475
  }, "strip", z.ZodTypeAny, {
2470
2476
  promptCache?: boolean | undefined;
2477
+ labels?: Record<string, string> | undefined;
2478
+ byok?: boolean | undefined;
2471
2479
  defaults?: Partial<Record<"fast" | "smart" | "powerful" | "cheap" | "vision" | "video" | "embedding", {
2472
2480
  provider: string;
2473
2481
  model: string;
@@ -2485,6 +2493,8 @@ declare const aiConfigSchema: z.ZodObject<{
2485
2493
  } | undefined;
2486
2494
  }, {
2487
2495
  promptCache?: boolean | undefined;
2496
+ labels?: Record<string, string> | undefined;
2497
+ byok?: boolean | undefined;
2488
2498
  defaults?: Partial<Record<"fast" | "smart" | "powerful" | "cheap" | "vision" | "video" | "embedding", {
2489
2499
  provider: string;
2490
2500
  model: string;
@@ -2836,6 +2846,19 @@ interface OpenAICompatibleConfig {
2836
2846
  }
2837
2847
  declare function makeOpenAICompatibleAdapter(config: OpenAICompatibleConfig): ProviderAdapter;
2838
2848
 
2849
+ /** The key-carrying fields an adapter config may hold. `credentials` is Vertex's
2850
+ * service-account JSON; every other adapter takes `apiKey`. */
2851
+ interface KeyedConfig {
2852
+ apiKey?: string;
2853
+ credentials?: string;
2854
+ }
2855
+ /** Build an adapter that is guaranteed to use the key you pass and never the fleet's
2856
+ * env key. Throws at construction when the key is missing or blank — a blank string
2857
+ * is not a key, and treating it as one would only move the failure to a 401 later. */
2858
+ declare function byokAdapter<C extends KeyedConfig>(factory: (config: C) => ProviderAdapter, config: C): ProviderAdapter;
2859
+ /** True when the adapter was built by byokAdapter with a real key. */
2860
+ declare function isByokKeyed(adapter: ProviderAdapter): boolean;
2861
+
2839
2862
  declare const defaultProviders: Record<string, ProviderAdapter>;
2840
2863
 
2841
2864
  /** Anthropic adapter stub (HTTP path). */
@@ -2854,8 +2877,8 @@ declare const falStubAdapter: ProviderAdapter;
2854
2877
  * wires the live adapters. */
2855
2878
  declare const stubProviders: Record<string, ProviderAdapter>;
2856
2879
 
2857
- declare const VERSION: "0.50.1";
2858
- declare const SDK_TAG: "@broberg/ai-sdk@0.50.1";
2880
+ declare const VERSION: "0.52.0";
2881
+ declare const SDK_TAG: "@broberg/ai-sdk@0.52.0";
2859
2882
 
2860
2883
  /** Built-in defaults. Every entry is overridable via AiConfig.defaults or a
2861
2884
  * per-call override.
@@ -3366,4 +3389,4 @@ interface StreamTransportRequest extends TransportRequest {
3366
3389
  */
3367
3390
  declare function streamTransport(req: StreamTransportRequest): AsyncIterable<string>;
3368
3391
 
3369
- export { AZURE_DANISH_VOICES, AZURE_DANISH_VOICE_LIST, type AiClient, type AiConfig, type AlignedWordTimings, type AzureVoiceInfo, type AzureWordBoundary, type BatchJob, type BatchRequestItem, type BatchResultItem, type BflAdapterConfig, type BflCredits, type BudgetConfig, BudgetExceededError, BudgetGuard, type BudgetStore, CONFIG_DERIVED_HOSTS, type CallOptions, type Capability, type ChatInput, type ChatRequest, type ChatResult, type ChatStreamEvent, type CheckVoiceOptions, type ClassifyInput, type ClassifyResult, type ContentPart, type Contracts, type CostQuery, type CostSink, type CostSummary, type CostSummaryQuery, type CostTimeseriesQuery, DEFAULT_BASE_URLS, DEFAULT_TIER_MAP, type DesignInput, type DesignResult, type DialogueRequest, type DialogueTurn, type DiscordSinkConfig, ELEVENLABS_DANISH_VOICES, type EmbeddingInput, type EmbeddingRequest, type EmbeddingResult, type ExtractInput, type ExtractResult, type FalAdapterConfig, type FixedHostProvider, type HttpResponse, type ImageInput, type ImageRequest, type ImageResult, type JudgeAnswer, type JudgeChoiceAnswer, type JudgeInput, type JudgeNoulAnswer, type JudgeQuestion, type JudgeResult, type JudgeScoreAnswer, LOCALLY_PINNED_HOSTS, type LoraWeight, type Message, type MockupInput, type MockupResult, type ModerationInput, type ModerationItem, type ModerationRequest, type ModerationResult, type OcrInput, type OcrPage, type OcrRequest, type OcrResult, type OpenAICompatibleConfig, type PodcastInput, type PodcastResult, type PricingEntry, type ProviderAdapter, type RefreshOptions, type RefreshResult, type Region, type RerankInput, type RerankResult, type Role, type RouteForecast, SDK_TAG, type SqliteBudgetStoreConfig, type SqliteSinkConfig, StreamHttpError, type SubprocessResponse, type Tier, type TierSpec, type Tool, type ToolCall, type TrainStyleInput, type TrainStyleRequest, type TrainStyleResult, type TranscribeInput, type TranscribeRequest, type TranscribeResult, type TranslateInput, type TranslateResult, type Transport, type TransportRequest, type TransportResponse, type TtsInput, type TtsRequest, type UpmetricsCostClientConfig, UpmetricsCostError, type UpmetricsCostRow, type UpmetricsCostSummary, type UpmetricsCostTimeseries, type UpmetricsSink, type UpmetricsSinkConfig, type UpmetricsSinkStats, type Usage, VERSION, type VideoInput, type VisionInput, type VoiceInfo, type VoiceProvider, type VoiceResolveResult, type VoiceStatus, VoiceUnavailableError, type WordTiming, aiConfigSchema, alignWordTimings, anthropicAdapter, anthropicApiAdapter, anthropicSubprocessAdapter, azureAdapter, bflAdapter, bflCredits, chatInputSchema, checkVoice, classifyRegionName, computeCost, createAI, deepinfraAdapter, deeplAdapter, deepseekAdapter, defaultBaseUrl, defaultProviders, discordSink, elevenlabsAdapter, embeddingInputSchema, falAdapter, falStubAdapter, freshUsage, fromProviderToolCall, geminiAdapter, getCostSummary, getPrice, httpTransport, imageInputSchema, listAzureDanishVoices, listVoices, makeContracts, makeOpenAICompatibleAdapter, matchLabel, messageSchema, mistralAdapter, mistralStubAdapter, multiSink, noopSink, openaiAdapter, openaiStubAdapter, openrouterAdapter, parseClaudeCliJson, parseJsonLoose, refreshAvailability, regionOfHost, regionOfProvider, requestyAdapter, resetRefreshState, resetRegistry, resolveAzureVoice, resolveTier, resolveVoice, sqliteBudgetStore, sqliteSink, streamTransport, stubProviders, subprocessTransport, tierSpecSchema, toProviderTools, toolSchema, translateInputSchema, typesafeAdapter, upmetricsCostClient, upmetricsSink, usdFromMicro, vertexAdapter, visionInputSchema, wouldProviderRouteTo, wouldRouteTo };
3392
+ export { AZURE_DANISH_VOICES, AZURE_DANISH_VOICE_LIST, type AiClient, type AiConfig, type AlignedWordTimings, type AzureVoiceInfo, type AzureWordBoundary, type BatchJob, type BatchRequestItem, type BatchResultItem, type BflAdapterConfig, type BflCredits, type BudgetConfig, BudgetExceededError, BudgetGuard, type BudgetStore, CONFIG_DERIVED_HOSTS, type CallOptions, type Capability, type ChatInput, type ChatRequest, type ChatResult, type ChatStreamEvent, type CheckVoiceOptions, type ClassifyInput, type ClassifyResult, type ContentPart, type Contracts, type CostQuery, type CostSink, type CostSummary, type CostSummaryQuery, type CostTimeseriesQuery, DEFAULT_BASE_URLS, DEFAULT_TIER_MAP, type DesignInput, type DesignResult, type DialogueRequest, type DialogueTurn, type DiscordSinkConfig, ELEVENLABS_DANISH_VOICES, type EmbeddingInput, type EmbeddingRequest, type EmbeddingResult, type ExtractInput, type ExtractResult, type FalAdapterConfig, type FixedHostProvider, type HttpResponse, type ImageInput, type ImageRequest, type ImageResult, type JudgeAnswer, type JudgeChoiceAnswer, type JudgeInput, type JudgeNoulAnswer, type JudgeQuestion, type JudgeResult, type JudgeScoreAnswer, LOCALLY_PINNED_HOSTS, type LoraWeight, type Message, type MockupInput, type MockupResult, type ModerationInput, type ModerationItem, type ModerationRequest, type ModerationResult, type OcrInput, type OcrPage, type OcrRequest, type OcrResult, type OpenAICompatibleConfig, type PodcastInput, type PodcastResult, type PricingEntry, type ProviderAdapter, type RefreshOptions, type RefreshResult, type Region, type RerankInput, type RerankResult, type Role, type RouteForecast, SDK_TAG, type SqliteBudgetStoreConfig, type SqliteSinkConfig, StreamHttpError, type SubprocessResponse, type Tier, type TierSpec, type Tool, type ToolCall, type TrainStyleInput, type TrainStyleRequest, type TrainStyleResult, type TranscribeInput, type TranscribeRequest, type TranscribeResult, type TranslateInput, type TranslateResult, type Transport, type TransportRequest, type TransportResponse, type TtsInput, type TtsRequest, type UpmetricsCostClientConfig, UpmetricsCostError, type UpmetricsCostRow, type UpmetricsCostSummary, type UpmetricsCostTimeseries, type UpmetricsSink, type UpmetricsSinkConfig, type UpmetricsSinkStats, type Usage, VERSION, type VideoInput, type VisionInput, type VoiceInfo, type VoiceProvider, type VoiceResolveResult, type VoiceStatus, VoiceUnavailableError, type WordTiming, aiConfigSchema, alignWordTimings, anthropicAdapter, anthropicApiAdapter, anthropicSubprocessAdapter, azureAdapter, bflAdapter, bflCredits, byokAdapter, chatInputSchema, checkVoice, classifyRegionName, computeCost, createAI, deepinfraAdapter, deeplAdapter, deepseekAdapter, defaultBaseUrl, defaultProviders, discordSink, elevenlabsAdapter, embeddingInputSchema, falAdapter, falStubAdapter, freshUsage, fromProviderToolCall, geminiAdapter, getCostSummary, getPrice, httpTransport, imageInputSchema, isByokKeyed, listAzureDanishVoices, listVoices, makeContracts, makeOpenAICompatibleAdapter, matchLabel, messageSchema, mistralAdapter, mistralStubAdapter, multiSink, noopSink, openaiAdapter, openaiStubAdapter, openrouterAdapter, parseClaudeCliJson, parseJsonLoose, refreshAvailability, regionOfHost, regionOfProvider, requestyAdapter, resetRefreshState, resetRegistry, resolveAzureVoice, resolveTier, resolveVoice, sqliteBudgetStore, sqliteSink, streamTransport, stubProviders, subprocessTransport, tierSpecSchema, toProviderTools, toolSchema, translateInputSchema, typesafeAdapter, upmetricsCostClient, upmetricsSink, usdFromMicro, vertexAdapter, visionInputSchema, wouldProviderRouteTo, wouldRouteTo };
package/dist/index.js CHANGED
@@ -18,7 +18,7 @@ import {
18
18
  listMediaPrices,
19
19
  pricingFreshness,
20
20
  pricingGeneratedAt
21
- } from "./chunk-DCNONKOW.js";
21
+ } from "./chunk-O4LR6X4U.js";
22
22
 
23
23
  // src/cost/default-hosts.ts
24
24
  var DEFAULT_BASE_URLS = {
@@ -3495,6 +3495,12 @@ var availabilitySchema = z.object({
3495
3495
  fallback: z.union([z.string(), z.array(z.string())]).optional()
3496
3496
  });
3497
3497
  var aiConfigSchema = z.object({
3498
+ /** F069.1 — customer-key mode. Every provider must be built with byokAdapter(), so no
3499
+ * call can fall back to the fleet's env keys; createAI throws at setup otherwise. */
3500
+ byok: z.boolean().optional(),
3501
+ /** F069.2 — attribution labels stamped on EVERY call's usage (and so on every cost-sink
3502
+ * row), e.g. { byok: "true", tenantId }. A call's own `labels` win on the same key. */
3503
+ labels: z.record(z.string(), z.string()).optional(),
3498
3504
  /** F039.2 — client-wide opt-out from prompt caching (default: on where the
3499
3505
  * provider supports it). A per-call `promptCache` wins over this. */
3500
3506
  promptCache: z.boolean().optional(),
@@ -3514,8 +3520,8 @@ var aiConfigSchema = z.object({
3514
3520
  import { randomUUID } from "crypto";
3515
3521
 
3516
3522
  // src/version.ts
3517
- var VERSION = "0.50.1";
3518
- var SDK_TAG = "@broberg/ai-sdk@0.50.1";
3523
+ var VERSION = "0.52.0";
3524
+ var SDK_TAG = "@broberg/ai-sdk@0.52.0";
3519
3525
 
3520
3526
  // src/cost/sinks/upmetrics.ts
3521
3527
  function isRetryableStatus(status) {
@@ -3709,6 +3715,36 @@ function upmetricsSink(config) {
3709
3715
  };
3710
3716
  }
3711
3717
 
3718
+ // src/byok.ts
3719
+ var BYOK_KEYED = /* @__PURE__ */ Symbol.for("@broberg/ai-sdk/byok-keyed");
3720
+ function byokAdapter(factory, config) {
3721
+ const key = config.apiKey ?? config.credentials;
3722
+ if (typeof key !== "string" || key.trim() === "") {
3723
+ throw new Error(
3724
+ "byokAdapter: no customer key (apiKey/credentials is missing or blank). Refusing to build an adapter that would fall back to the fleet's env key."
3725
+ );
3726
+ }
3727
+ const adapter = factory(config);
3728
+ Object.defineProperty(adapter, BYOK_KEYED, { value: true, enumerable: false });
3729
+ return adapter;
3730
+ }
3731
+ function isByokKeyed(adapter) {
3732
+ return adapter[BYOK_KEYED] === true;
3733
+ }
3734
+ function assertByokProviders(providers) {
3735
+ if (!providers || Object.keys(providers).length === 0) {
3736
+ throw new Error(
3737
+ "createAI({ byok: true }) needs `providers` built with byokAdapter \u2014 without them the fleet's default adapters (and the fleet's keys) would be used."
3738
+ );
3739
+ }
3740
+ const unkeyed = Object.entries(providers).filter(([, a]) => !isByokKeyed(a)).map(([name]) => name);
3741
+ if (unkeyed.length > 0) {
3742
+ throw new Error(
3743
+ `createAI({ byok: true }): provider(s) ${unkeyed.join(", ")} were not built with byokAdapter, so they may read the fleet's env key. Build each one as byokAdapter(openaiAdapter, { apiKey }).`
3744
+ );
3745
+ }
3746
+ }
3747
+
3712
3748
  // src/client.ts
3713
3749
  var DEFAULT_IMAGE_SPEC = {
3714
3750
  provider: "fal",
@@ -3764,6 +3800,7 @@ function defaultCostSink() {
3764
3800
  }
3765
3801
  function createAI(config = {}) {
3766
3802
  const cfg = aiConfigSchema.parse(config);
3803
+ if (cfg.byok) assertByokProviders(cfg.providers);
3767
3804
  const providers = cfg.providers ?? defaultProviders;
3768
3805
  const costSink = cfg.costSink === void 0 ? defaultCostSink() : cfg.costSink ?? void 0;
3769
3806
  const budget = cfg.budget ? new BudgetGuard(cfg.budget) : void 0;
@@ -3797,7 +3834,8 @@ function createAI(config = {}) {
3797
3834
  usage.capability = capability;
3798
3835
  if (tier) usage.tier = tier;
3799
3836
  if (purpose) usage.purpose = purpose;
3800
- if (labels && Object.keys(labels).length > 0) usage.labels = labels;
3837
+ const merged = { ...cfg.labels, ...labels };
3838
+ if (Object.keys(merged).length > 0) usage.labels = merged;
3801
3839
  usage.latencyMs = Math.round(latencyMs);
3802
3840
  if (!usage.ts) usage.ts = (/* @__PURE__ */ new Date()).toISOString();
3803
3841
  return usage;
@@ -4714,6 +4752,7 @@ export {
4714
4752
  azureAdapter,
4715
4753
  bflAdapter,
4716
4754
  bflCredits,
4755
+ byokAdapter,
4717
4756
  chatInputSchema,
4718
4757
  checkVoice,
4719
4758
  classifyRegionName,
@@ -4737,6 +4776,7 @@ export {
4737
4776
  getPrice,
4738
4777
  httpTransport,
4739
4778
  imageInputSchema,
4779
+ isByokKeyed,
4740
4780
  listAzureDanishVoices,
4741
4781
  listMediaPrices,
4742
4782
  listModels,