@broberg/ai-sdk 0.75.0 → 0.76.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
@@ -1,5 +1,5 @@
1
- import { U as Usage, C as CostSink, T as Tier, a as ChatResult, b as ChatStreamEvent, c as TranslateResult, I as ImageResult, A as AnimateResult, d as TrainStyleResult, E as EmbeddingResult, e as TranscribeResult, O as OcrResult, M as ModerationResult, J as JudgeResult, V as VectorizeResult, P as PodcastResult, B as BatchRequestItem, f as TierSpec, g as BatchJob, h as BatchResultItem, i as ProviderAdapter, j as ToolCall, k as Tool, l as Transport, m as Capability, R as Region, n as BudgetConfig, o as BudgetStore } from './registry-CsDDEHEr.js';
2
- export { p as AlignedWordTimings, q as AvailabilitySource, r as AvailabilityStatus, s as AzureWordBoundary, t as CallOptions, u as ChatRequest, v as ContentPart, D as DialogueRequest, w as DialogueTurn, x as EmbeddingRequest, y as ImageRequest, z as JudgeAnswer, F as JudgeChoiceAnswer, G as JudgeNoulAnswer, H as JudgeQuestion, K as JudgeScoreAnswer, L as LoraWeight, N as Message, Q as ModelStatus, S as ModelUnavailableError, W as ModerationItem, X as ModerationRequest, Y as OcrPage, Z as OcrRequest, _ as ResolveOptions, $ as ResolveResult, a0 as Role, a1 as TierDescription, a2 as TrainStyleRequest, a3 as TranscribeRequest, a4 as TtsRequest, a5 as WordTiming, a6 as alignWordTimings, a7 as classifyRegionName, a8 as describeTier, a9 as listModels, aa as regionOfHost, ab as regionOfProvider, ac as resolveModel } from './registry-CsDDEHEr.js';
1
+ import { U as Usage, C as CostSink, T as Tier, a as ChatResult, b as ChatStreamEvent, c as TranslateResult, I as ImageResult, A as AnimateResult, d as TrainStyleResult, E as EmbeddingResult, e as TranscribeResult, O as OcrResult, M as ModerationResult, J as JudgeResult, V as VectorizeResult, P as PodcastResult, B as BatchRequestItem, f as TierSpec, g as BatchJob, h as BatchResultItem, i as ProviderAdapter, j as ToolCall, k as Tool, l as Transport, m as Capability, R as Region, n as BudgetConfig, o as BudgetStore } from './registry-Bkh7DUFZ.js';
2
+ export { p as AlignedWordTimings, q as AvailabilitySource, r as AvailabilityStatus, s as AzureWordBoundary, t as CallOptions, u as ChatRequest, v as ContentPart, D as DialogueRequest, w as DialogueTurn, x as EmbeddingRequest, y as ImageRequest, z as JudgeAnswer, F as JudgeChoiceAnswer, G as JudgeNoulAnswer, H as JudgeQuestion, K as JudgeScoreAnswer, L as LoraWeight, N as Message, Q as ModelStatus, S as ModelUnavailableError, W as ModerationItem, X as ModerationRequest, Y as OcrPage, Z as OcrRequest, _ as ResolveOptions, $ as ResolveResult, a0 as Role, a1 as TierDescription, a2 as TrainStyleRequest, a3 as TranscribeRequest, a4 as TtsRequest, a5 as WordTiming, a6 as alignWordTimings, a7 as classifyRegionName, a8 as describeTier, a9 as listModels, aa as regionOfHost, ab as regionOfProvider, ac as resolveModel } from './registry-Bkh7DUFZ.js';
3
3
  import { z } from 'zod';
4
4
  export { CheapestQuery, CheapestResult, CheapestRow, DEFAULT_CLIP_SEC, MEDIA_PRICING_CHECKED_AT, MediaPrice, MediaUnit, PRICING_STALE_AFTER_DAYS, PriceKind, PricingFreshness, UnitFreshness, UpstreamStatus, cheapestModels, classifyKind, getMediaPrice, listMediaPrices, pricingFreshness, pricingGeneratedAt } from './pricing.js';
5
5
 
@@ -1294,6 +1294,15 @@ interface OpenRouterAdapterConfig {
1294
1294
  }
1295
1295
  declare function openrouterAdapter(config?: OpenRouterAdapterConfig): ProviderAdapter;
1296
1296
 
1297
+ /** Ollama's OpenAI-compatible endpoint on the same machine. */
1298
+ declare const LOCAL_EMBEDDING_DEFAULT_URL = "http://127.0.0.1:11434/v1";
1299
+ interface LocalAdapterConfig {
1300
+ /** Server base URL incl. /v1. Else env LOCAL_EMBEDDING_URL, else Ollama on 127.0.0.1. */
1301
+ baseUrl?: string;
1302
+ fetch?: typeof fetch;
1303
+ }
1304
+ declare function localAdapter(config?: LocalAdapterConfig): ProviderAdapter;
1305
+
1297
1306
  declare function requestyAdapter(config?: {
1298
1307
  apiKey?: string;
1299
1308
  baseUrl?: string;
@@ -1587,8 +1596,8 @@ declare const falStubAdapter: ProviderAdapter;
1587
1596
  * wires the live adapters. */
1588
1597
  declare const stubProviders: Record<string, ProviderAdapter>;
1589
1598
 
1590
- declare const VERSION: "0.75.0";
1591
- declare const SDK_TAG: "@broberg/ai-sdk@0.75.0";
1599
+ declare const VERSION: "0.76.0";
1600
+ declare const SDK_TAG: "@broberg/ai-sdk@0.76.0";
1592
1601
 
1593
1602
  /** Built-in defaults. Every entry is overridable via AiConfig.defaults or a
1594
1603
  * per-call override.
@@ -2157,4 +2166,4 @@ declare function memorySearchCache(max?: number): SearchCache;
2157
2166
 
2158
2167
  declare function search(req: SearchRequest, opts?: SearchOptions): Promise<SearchResult>;
2159
2168
 
2160
- export { AZURE_DANISH_VOICES, AZURE_DANISH_VOICE_LIST, AiAbortError, type AiClient, type AiConfig, AiTimeoutError, type AzureVoiceInfo, BatchJob, BatchRequestItem, BatchResultItem, type BflAdapterConfig, type BflCredits, BudgetConfig, BudgetExceededError, BudgetGuard, BudgetStore, CONFIG_DERIVED_HOSTS, Capability, type ChatInput, ChatResult, ChatStreamEvent, type CheckVoiceOptions, type ClassifyInput, type ClassifyResult, type Contracts, type CostQuery, CostSink, type CostSummary, type CostSummaryQuery, type CostTimeseriesQuery, DEFAULT_BASE_URLS, DEFAULT_SEARCH_ROUTES, DEFAULT_TIER_MAP, type DesignInput, type DesignResult, type DiscordSinkConfig, ELEVENLABS_DANISH_VOICES, type EmbeddingInput, EmbeddingResult, type ExtractInput, type ExtractResult, type FalAdapterConfig, type FixedHostProvider, type HttpResponse, INPUT_LIMITS, type ImageInput, ImageResult, type JudgeInput, JudgeResult, LOCALLY_PINNED_HOSTS, MICROSOFT_DECISION_DEFAULT_DEPLOYMENT, type MockupInput, type MockupResult, type ModerationInput, ModerationResult, type OcrInput, OcrResult, type OpenAICompatibleConfig, type Opinion, type PanelMember, type PodcastInput, PodcastResult, type PriceDriftResult, type PriceDriftRow, type PricingEntry, ProviderAdapter, type RefreshOptions, type RefreshResult, Region, type RerankInput, type RerankResult, type RouteForecast, SDK_TAG, SEARCH_CACHE_TTL_MS, SEARCH_PRICE_USD, SECOND_OPINION_DEFAULT_TIMEOUT_MS, SECOND_OPINION_INSTRUCTION, SECOND_OPINION_PANEL, SECOND_OPINION_SYNTH, SECOND_OPINION_SYNTH_INSTRUCTION, SearchBudgetExceededError, type SearchCache, type SearchCapStore, type SearchCredentials, type SearchItem, SearchKeyMissingError, type SearchOptions, type SearchProviderId, type SearchPurpose, type SearchRequest, type SearchResult, type SearchRoute, type SecondOpinionInput, type SecondOpinionResult, type SqliteBudgetStoreConfig, type SqliteSinkConfig, StreamHttpError, type SubprocessResponse, Tier, TierSpec, Tool, ToolCall, type TrainStyleInput, TrainStyleResult, type TranscribeInput, TranscribeResult, type TranslateInput, TranslateResult, Transport, type TransportRequest, type TransportResponse, type TtsInput, type UpmetricsCostClientConfig, UpmetricsCostError, type UpmetricsCostRow, type UpmetricsCostSummary, type UpmetricsCostTimeseries, type UpmetricsSink, type UpmetricsSinkConfig, type UpmetricsSinkStats, Usage, VERSION, type VideoInput, type VisionInput, type VoiceInfo, type VoiceProvider, type VoiceResolveResult, type VoiceStatus, VoiceUnavailableError, type WebSearchContext, type WebSearchToolResult, ZDR_PROVIDERS, aiConfigSchema, anthropicAdapter, anthropicApiAdapter, anthropicSubprocessAdapter, azureAdapter, bflAdapter, bflCredits, byokAdapter, chatInputSchema, checkPriceDrift, checkVoice, 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, memorySearchCache, messageSchema, microsoftDecisionAdapter, mistralAdapter, mistralStubAdapter, multiSink, noopSink, openaiAdapter, openaiStubAdapter, openrouterAdapter, parseClaudeCliJson, parseJsonLoose, recraftAdapter, refreshAvailability, requestyAdapter, resetRefreshState, resetRegistry, resolveAzureVoice, resolveTier, resolveVoice, routeSearch, runWebSearch, search, sqliteBudgetStore, sqliteSink, streamTransport, stubProviders, subprocessTransport, tierSpecSchema, toProviderTools, toolSchema, translateInputSchema, typesafeAdapter, upmetricsCostClient, upmetricsSink, usdFromMicro, vertexAdapter, visionInputSchema, webSearchTool, wouldProviderRouteTo, wouldRouteTo };
2169
+ export { AZURE_DANISH_VOICES, AZURE_DANISH_VOICE_LIST, AiAbortError, type AiClient, type AiConfig, AiTimeoutError, type AzureVoiceInfo, BatchJob, BatchRequestItem, BatchResultItem, type BflAdapterConfig, type BflCredits, BudgetConfig, BudgetExceededError, BudgetGuard, BudgetStore, CONFIG_DERIVED_HOSTS, Capability, type ChatInput, ChatResult, ChatStreamEvent, type CheckVoiceOptions, type ClassifyInput, type ClassifyResult, type Contracts, type CostQuery, CostSink, type CostSummary, type CostSummaryQuery, type CostTimeseriesQuery, DEFAULT_BASE_URLS, DEFAULT_SEARCH_ROUTES, DEFAULT_TIER_MAP, type DesignInput, type DesignResult, type DiscordSinkConfig, ELEVENLABS_DANISH_VOICES, type EmbeddingInput, EmbeddingResult, type ExtractInput, type ExtractResult, type FalAdapterConfig, type FixedHostProvider, type HttpResponse, INPUT_LIMITS, type ImageInput, ImageResult, type JudgeInput, JudgeResult, LOCALLY_PINNED_HOSTS, LOCAL_EMBEDDING_DEFAULT_URL, type LocalAdapterConfig, MICROSOFT_DECISION_DEFAULT_DEPLOYMENT, type MockupInput, type MockupResult, type ModerationInput, ModerationResult, type OcrInput, OcrResult, type OpenAICompatibleConfig, type Opinion, type PanelMember, type PodcastInput, PodcastResult, type PriceDriftResult, type PriceDriftRow, type PricingEntry, ProviderAdapter, type RefreshOptions, type RefreshResult, Region, type RerankInput, type RerankResult, type RouteForecast, SDK_TAG, SEARCH_CACHE_TTL_MS, SEARCH_PRICE_USD, SECOND_OPINION_DEFAULT_TIMEOUT_MS, SECOND_OPINION_INSTRUCTION, SECOND_OPINION_PANEL, SECOND_OPINION_SYNTH, SECOND_OPINION_SYNTH_INSTRUCTION, SearchBudgetExceededError, type SearchCache, type SearchCapStore, type SearchCredentials, type SearchItem, SearchKeyMissingError, type SearchOptions, type SearchProviderId, type SearchPurpose, type SearchRequest, type SearchResult, type SearchRoute, type SecondOpinionInput, type SecondOpinionResult, type SqliteBudgetStoreConfig, type SqliteSinkConfig, StreamHttpError, type SubprocessResponse, Tier, TierSpec, Tool, ToolCall, type TrainStyleInput, TrainStyleResult, type TranscribeInput, TranscribeResult, type TranslateInput, TranslateResult, Transport, type TransportRequest, type TransportResponse, type TtsInput, type UpmetricsCostClientConfig, UpmetricsCostError, type UpmetricsCostRow, type UpmetricsCostSummary, type UpmetricsCostTimeseries, type UpmetricsSink, type UpmetricsSinkConfig, type UpmetricsSinkStats, Usage, VERSION, type VideoInput, type VisionInput, type VoiceInfo, type VoiceProvider, type VoiceResolveResult, type VoiceStatus, VoiceUnavailableError, type WebSearchContext, type WebSearchToolResult, ZDR_PROVIDERS, aiConfigSchema, anthropicAdapter, anthropicApiAdapter, anthropicSubprocessAdapter, azureAdapter, bflAdapter, bflCredits, byokAdapter, chatInputSchema, checkPriceDrift, checkVoice, computeCost, createAI, deepinfraAdapter, deeplAdapter, deepseekAdapter, defaultBaseUrl, defaultProviders, discordSink, elevenlabsAdapter, embeddingInputSchema, falAdapter, falStubAdapter, freshUsage, fromProviderToolCall, geminiAdapter, getCostSummary, getPrice, httpTransport, imageInputSchema, isByokKeyed, listAzureDanishVoices, listVoices, localAdapter, makeContracts, makeOpenAICompatibleAdapter, matchLabel, memorySearchCache, messageSchema, microsoftDecisionAdapter, mistralAdapter, mistralStubAdapter, multiSink, noopSink, openaiAdapter, openaiStubAdapter, openrouterAdapter, parseClaudeCliJson, parseJsonLoose, recraftAdapter, refreshAvailability, requestyAdapter, resetRefreshState, resetRegistry, resolveAzureVoice, resolveTier, resolveVoice, routeSearch, runWebSearch, search, sqliteBudgetStore, sqliteSink, streamTransport, stubProviders, subprocessTransport, tierSpecSchema, toProviderTools, toolSchema, translateInputSchema, typesafeAdapter, upmetricsCostClient, upmetricsSink, usdFromMicro, vertexAdapter, visionInputSchema, webSearchTool, wouldProviderRouteTo, wouldRouteTo };
package/dist/index.js CHANGED
@@ -220,6 +220,11 @@ var SearchBudgetExceededError = class extends Error {
220
220
  requestedUsd;
221
221
  };
222
222
 
223
+ // src/env.ts
224
+ function env() {
225
+ return typeof process !== "undefined" && process.env ? process.env : {};
226
+ }
227
+
223
228
  // src/search/tool.ts
224
229
  var PURPOSES = ["agent", "grounding", "discovery", "monitor"];
225
230
  var webSearchTool = {
@@ -282,31 +287,31 @@ var COOLDOWN_STATUS = /* @__PURE__ */ new Set(["401", "402", "403"]);
282
287
  var coolingUntil = /* @__PURE__ */ new Map();
283
288
  function cooldownKey(provider, opts) {
284
289
  const c = opts.credentials ?? {};
285
- const env = opts.byok ? {} : process.env;
286
- const secret = provider === "brave" ? c.braveApiKey ?? env.BRAVE_API_KEY : provider === "tavily" ? c.tavilyApiKey ?? env.TAVILY_API_KEY : `${c.cloudflareAccountId ?? env.CLOUDFLARE_ACCOUNT_ID}:${c.cloudflareApiToken ?? env.CLOUDFLARE_API_TOKEN}`;
290
+ const env2 = opts.byok ? {} : env();
291
+ const secret = provider === "brave" ? c.braveApiKey ?? env2.BRAVE_API_KEY : provider === "tavily" ? c.tavilyApiKey ?? env2.TAVILY_API_KEY : `${c.cloudflareAccountId ?? env2.CLOUDFLARE_ACCOUNT_ID}:${c.cloudflareApiToken ?? env2.CLOUDFLARE_API_TOKEN}`;
287
292
  return `${provider}:${createHash("sha256").update(String(secret)).digest("hex").slice(0, 16)}`;
288
293
  }
289
294
  var copenhagenDay = (d) => new Intl.DateTimeFormat("en-CA", { timeZone: "Europe/Copenhagen" }).format(d);
290
295
  async function callProvider(provider, req, opts) {
291
296
  const f = opts.fetch ?? fetch;
292
297
  const c = opts.credentials ?? {};
293
- const env = opts.byok ? {} : process.env;
298
+ const env2 = opts.byok ? {} : env();
294
299
  if (provider === "brave") {
295
- const key = c.braveApiKey ?? env.BRAVE_API_KEY;
300
+ const key = c.braveApiKey ?? env2.BRAVE_API_KEY;
296
301
  if (!key) throw new SearchKeyMissingError(provider, "BRAVE_API_KEY");
297
302
  return braveSearch({ ...req, provider }, key, f);
298
303
  }
299
304
  if (provider === "tavily") {
300
- const key = c.tavilyApiKey ?? env.TAVILY_API_KEY;
305
+ const key = c.tavilyApiKey ?? env2.TAVILY_API_KEY;
301
306
  if (!key) throw new SearchKeyMissingError(provider, "TAVILY_API_KEY");
302
307
  return tavilySearch({ ...req, provider }, key, f);
303
308
  }
304
309
  if (provider.startsWith("cloudflare:")) {
305
- const accountId = c.cloudflareAccountId ?? env.CLOUDFLARE_ACCOUNT_ID;
306
- const apiToken = c.cloudflareApiToken ?? env.CLOUDFLARE_API_TOKEN;
310
+ const accountId = c.cloudflareAccountId ?? env2.CLOUDFLARE_ACCOUNT_ID;
311
+ const apiToken = c.cloudflareApiToken ?? env2.CLOUDFLARE_API_TOKEN;
307
312
  if (!accountId) throw new SearchKeyMissingError(provider, "CLOUDFLARE_ACCOUNT_ID");
308
313
  if (!apiToken) throw new SearchKeyMissingError(provider, "CLOUDFLARE_API_TOKEN");
309
- const gatewayId = c.cloudflareGatewayId ?? env.CLOUDFLARE_GATEWAY_ID ?? "default";
314
+ const gatewayId = c.cloudflareGatewayId ?? env2.CLOUDFLARE_GATEWAY_ID ?? "default";
310
315
  return cloudflareSearch({ ...req, provider }, { accountId, apiToken, gatewayId }, f);
311
316
  }
312
317
  throw new Error(`search: unknown provider "${String(provider)}"`);
@@ -872,7 +877,7 @@ function anthropicAdapter(config = {}) {
872
877
  return body;
873
878
  }
874
879
  function apiKeyOrThrow() {
875
- const apiKey = config.apiKey ?? process.env.ANTHROPIC_API_KEY;
880
+ const apiKey = config.apiKey ?? env().ANTHROPIC_API_KEY;
876
881
  if (!apiKey) throw new Error("anthropic adapter: API key not set (env ANTHROPIC_API_KEY)");
877
882
  return apiKey;
878
883
  }
@@ -1162,7 +1167,7 @@ function buildChatBody(req, config) {
1162
1167
  }
1163
1168
  function makeOpenAICompatibleAdapter(config) {
1164
1169
  async function chat(req) {
1165
- const apiKey = config.apiKey ?? process.env[`${config.name.toUpperCase()}_API_KEY`];
1170
+ const apiKey = config.apiKey ?? env()[`${config.name.toUpperCase()}_API_KEY`];
1166
1171
  if (!apiKey) {
1167
1172
  throw new Error(`${config.name} adapter: API key not set (env ${config.name.toUpperCase()}_API_KEY)`);
1168
1173
  }
@@ -1222,7 +1227,7 @@ function makeOpenAICompatibleAdapter(config) {
1222
1227
  return result;
1223
1228
  }
1224
1229
  async function* chatStream(req) {
1225
- const apiKey = config.apiKey ?? process.env[`${config.name.toUpperCase()}_API_KEY`];
1230
+ const apiKey = config.apiKey ?? env()[`${config.name.toUpperCase()}_API_KEY`];
1226
1231
  if (!apiKey) {
1227
1232
  throw new Error(`${config.name} adapter: API key not set (env ${config.name.toUpperCase()}_API_KEY)`);
1228
1233
  }
@@ -1343,7 +1348,7 @@ function openaiAdapter(config = {}) {
1343
1348
  const baseUrl = config.baseUrl ?? DEFAULT_BASE_URLS.openai;
1344
1349
  const base = makeOpenAICompatibleAdapter({ name: "openai", baseUrl, apiKey: config.apiKey, fetch: config.fetch });
1345
1350
  async function embedding(req) {
1346
- const apiKey = config.apiKey ?? process.env.OPENAI_API_KEY;
1351
+ const apiKey = config.apiKey ?? env().OPENAI_API_KEY;
1347
1352
  if (!apiKey) throw new Error("openai adapter: API key not set (env OPENAI_API_KEY)");
1348
1353
  const res = await httpTransport({
1349
1354
  spec: req.spec,
@@ -1370,7 +1375,7 @@ function openaiAdapter(config = {}) {
1370
1375
  return { vectors, usage };
1371
1376
  }
1372
1377
  async function transcribe(req) {
1373
- const apiKey = config.apiKey ?? process.env.OPENAI_API_KEY;
1378
+ const apiKey = config.apiKey ?? env().OPENAI_API_KEY;
1374
1379
  if (!apiKey) throw new Error("openai adapter: API key not set (env OPENAI_API_KEY)");
1375
1380
  const form = new FormData();
1376
1381
  form.append("file", new Blob([req.audio]), "audio");
@@ -1469,7 +1474,7 @@ function partsFrom(content) {
1469
1474
  function geminiAdapter(config = {}) {
1470
1475
  const baseUrl = config.baseUrl ?? DEFAULT_BASE_URLS.gemini;
1471
1476
  function resolveKey() {
1472
- const apiKey = config.apiKey ?? process.env.GOOGLE_API_KEY ?? process.env.GEMINI_API_KEY;
1477
+ const apiKey = config.apiKey ?? env().GOOGLE_API_KEY ?? env().GEMINI_API_KEY;
1473
1478
  if (!apiKey) throw new Error("gemini adapter: API key not set (env GOOGLE_API_KEY or GEMINI_API_KEY)");
1474
1479
  return apiKey;
1475
1480
  }
@@ -1727,7 +1732,7 @@ function openrouterAdapter(config = {}) {
1727
1732
  costFromResponseField: true
1728
1733
  });
1729
1734
  async function image(req) {
1730
- const apiKey = config.apiKey ?? process.env.OPENROUTER_API_KEY;
1735
+ const apiKey = config.apiKey ?? env().OPENROUTER_API_KEY;
1731
1736
  if (!apiKey) throw new Error("openrouter adapter: OPENROUTER_API_KEY not set");
1732
1737
  const doFetch = config.fetch ?? fetch;
1733
1738
  const body = { model: req.spec.model, prompt: req.prompt };
@@ -1856,7 +1861,7 @@ function mistralAdapter(config = {}) {
1856
1861
  const baseUrl = config.baseUrl ?? DEFAULT_BASE_URLS.mistral;
1857
1862
  const base = makeOpenAICompatibleAdapter({ name: "mistral", baseUrl, apiKey: config.apiKey, fetch: config.fetch, supportsPromptCacheKey: true, supportsPrefix: true, supportsReasoningEffort: true });
1858
1863
  function key() {
1859
- const k = config.apiKey ?? process.env.MISTRAL_API_KEY;
1864
+ const k = config.apiKey ?? env().MISTRAL_API_KEY;
1860
1865
  if (!k) throw new Error("mistral adapter: API key not set (env MISTRAL_API_KEY)");
1861
1866
  return k;
1862
1867
  }
@@ -2168,7 +2173,7 @@ function elevenlabsAdapter(config = {}) {
2168
2173
  const baseUrl = config.baseUrl ?? DEFAULT_BASE_URLS.elevenlabs;
2169
2174
  const fetchImpl = config.fetch ?? fetch;
2170
2175
  function key() {
2171
- const k = config.apiKey ?? process.env.ELEVENLABS_API_KEY;
2176
+ const k = config.apiKey ?? env().ELEVENLABS_API_KEY;
2172
2177
  if (!k) throw new Error("elevenlabs adapter: API key not set (env ELEVENLABS_API_KEY)");
2173
2178
  return k;
2174
2179
  }
@@ -2397,22 +2402,22 @@ function localeOf(voice) {
2397
2402
  function azureAdapter(config = {}) {
2398
2403
  const fetchImpl = config.fetch ?? fetch;
2399
2404
  function key() {
2400
- const k = config.apiKey ?? process.env.AZURE_SPEECH_KEY;
2405
+ const k = config.apiKey ?? env().AZURE_SPEECH_KEY;
2401
2406
  if (!k) throw new Error("azure adapter: API key not set (env AZURE_SPEECH_KEY)");
2402
2407
  return k;
2403
2408
  }
2404
2409
  function region() {
2405
- return config.region ?? process.env.AZURE_SPEECH_REGION ?? DEFAULT_REGION;
2410
+ return config.region ?? env().AZURE_SPEECH_REGION ?? DEFAULT_REGION;
2406
2411
  }
2407
2412
  function sttRegion() {
2408
- if (config.sttBaseUrl || config.resource || process.env.AZURE_SPEECH_RESOURCE) {
2409
- return config.region ?? process.env.AZURE_SPEECH_REGION ? classifyRegionName(region()) : "unknown";
2413
+ if (config.sttBaseUrl || config.resource || env().AZURE_SPEECH_RESOURCE) {
2414
+ return config.region ?? env().AZURE_SPEECH_REGION ? classifyRegionName(region()) : "unknown";
2410
2415
  }
2411
2416
  return classifyRegionName(region());
2412
2417
  }
2413
2418
  function sttHost() {
2414
2419
  if (config.sttBaseUrl) return { url: config.sttBaseUrl.replace(/\/$/, ""), source: "explicit" };
2415
- const resource = config.resource ?? process.env.AZURE_SPEECH_RESOURCE;
2420
+ const resource = config.resource ?? env().AZURE_SPEECH_RESOURCE;
2416
2421
  if (resource) return { url: `https://${resource}.cognitiveservices.azure.com`, source: "resource" };
2417
2422
  return { url: `https://${region()}.api.cognitive.microsoft.com`, source: "regional-fallback" };
2418
2423
  }
@@ -2622,7 +2627,7 @@ function base64url(input) {
2622
2627
  return buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
2623
2628
  }
2624
2629
  function resolveCredentials(config) {
2625
- const inline = config.credentials ?? process.env.GOOGLE_VERTEX_CREDENTIALS;
2630
+ const inline = config.credentials ?? env().GOOGLE_VERTEX_CREDENTIALS;
2626
2631
  if (inline) {
2627
2632
  try {
2628
2633
  return JSON.parse(inline);
@@ -2630,7 +2635,7 @@ function resolveCredentials(config) {
2630
2635
  throw new Error("vertex adapter: GOOGLE_VERTEX_CREDENTIALS is not valid JSON");
2631
2636
  }
2632
2637
  }
2633
- const path = process.env.GOOGLE_APPLICATION_CREDENTIALS;
2638
+ const path = env().GOOGLE_APPLICATION_CREDENTIALS;
2634
2639
  if (path) {
2635
2640
  let raw;
2636
2641
  try {
@@ -2676,10 +2681,10 @@ function vertexAdapter(config = {}) {
2676
2681
  const fetchImpl = config.fetch ?? fetch;
2677
2682
  let cached = null;
2678
2683
  function region() {
2679
- return config.region ?? process.env.GOOGLE_VERTEX_REGION ?? DEFAULT_REGION2;
2684
+ return config.region ?? env().GOOGLE_VERTEX_REGION ?? DEFAULT_REGION2;
2680
2685
  }
2681
2686
  function project() {
2682
- const p = config.project ?? process.env.GOOGLE_VERTEX_PROJECT ?? resolveCredentials(config).project_id;
2687
+ const p = config.project ?? env().GOOGLE_VERTEX_PROJECT ?? resolveCredentials(config).project_id;
2683
2688
  if (!p) throw new Error("vertex adapter: project not set (config.project, env GOOGLE_VERTEX_PROJECT, or project_id in the credentials)");
2684
2689
  return p;
2685
2690
  }
@@ -2814,7 +2819,7 @@ function vertexAdapter(config = {}) {
2814
2819
  function deeplAdapter(config = {}) {
2815
2820
  const fetchImpl = config.fetch ?? fetch;
2816
2821
  function key() {
2817
- const k = config.apiKey ?? process.env.DEEPL_API_KEY;
2822
+ const k = config.apiKey ?? env().DEEPL_API_KEY;
2818
2823
  if (!k) throw new Error("deepl adapter: API key not set (env DEEPL_API_KEY)");
2819
2824
  return k;
2820
2825
  }
@@ -2889,7 +2894,7 @@ function typesafeAdapter(config = {}) {
2889
2894
  const fetchImpl = config.fetch ?? fetch;
2890
2895
  const base = (config.baseUrl ?? DEFAULT_BASE_URLS.typesafe).replace(/\/$/, "");
2891
2896
  function key() {
2892
- const k = config.apiKey ?? process.env.TYPESAFE_API_KEY;
2897
+ const k = config.apiKey ?? env().TYPESAFE_API_KEY;
2893
2898
  if (!k) throw new Error("typesafe adapter: API key not set (env TYPESAFE_API_KEY)");
2894
2899
  return k;
2895
2900
  }
@@ -2930,19 +2935,19 @@ function microsoftDecisionAdapter(config = {}) {
2930
2935
  if (config.apiKey !== void 0 && config.endpoint === void 0) {
2931
2936
  throw new Error("microsoft-decision adapter: an explicit apiKey needs its own endpoint \u2014 pass both (never the env endpoint with a caller's key)");
2932
2937
  }
2933
- const e = config.endpoint ?? process.env.AZURE_DECISION_ENDPOINT;
2938
+ const e = config.endpoint ?? env().AZURE_DECISION_ENDPOINT;
2934
2939
  if (!e) throw new Error("microsoft-decision adapter: endpoint not set (env AZURE_DECISION_ENDPOINT)");
2935
2940
  return e.replace(/\/$/, "");
2936
2941
  }
2937
2942
  function key() {
2938
- const k = config.apiKey ?? process.env.AZURE_DECISION_API_KEY;
2943
+ const k = config.apiKey ?? env().AZURE_DECISION_API_KEY;
2939
2944
  if (!k) throw new Error("microsoft-decision adapter: API key not set (env AZURE_DECISION_API_KEY)");
2940
2945
  return k;
2941
2946
  }
2942
2947
  async function judge(req) {
2943
2948
  const url = `${endpoint()}/providers/microsoft/v1/systemone`;
2944
2949
  const apiKey = key();
2945
- const deployment = config.deployment ?? process.env.AZURE_DECISION_DEPLOYMENT ?? MICROSOFT_DECISION_DEFAULT_DEPLOYMENT;
2950
+ const deployment = config.deployment ?? env().AZURE_DECISION_DEPLOYMENT ?? MICROSOFT_DECISION_DEFAULT_DEPLOYMENT;
2946
2951
  const res = await fetchImpl(url, {
2947
2952
  method: "POST",
2948
2953
  headers: { "content-type": "application/json", "api-key": apiKey },
@@ -2981,7 +2986,7 @@ function falAdapter(config = {}) {
2981
2986
  const queueBase = config.queueBaseUrl ?? "https://queue.fal.run";
2982
2987
  const pollIntervalMs = config.pollIntervalMs ?? 2e3;
2983
2988
  const timeoutMs = config.timeoutMs ?? 6e4;
2984
- const resolveKey = () => config.apiKey ?? process.env.FAL_KEY ?? process.env.FAL_API_KEY;
2989
+ const resolveKey = () => config.apiKey ?? env().FAL_KEY ?? env().FAL_API_KEY;
2985
2990
  const authHeaders = (apiKey) => ({
2986
2991
  "content-type": "application/json",
2987
2992
  Authorization: `Key ${apiKey}`
@@ -3305,7 +3310,7 @@ function gcd(a, b) {
3305
3310
  return b === 0 ? a : gcd(b, a % b);
3306
3311
  }
3307
3312
  async function bflCredits(opts = {}) {
3308
- const apiKey = opts.apiKey ?? process.env.BFL_API_KEY;
3313
+ const apiKey = opts.apiKey ?? env().BFL_API_KEY;
3309
3314
  if (!apiKey) throw new Error("bflCredits: BFL_API_KEY not set");
3310
3315
  const doFetch = opts.fetch ?? fetch;
3311
3316
  const res = await doFetch(`${opts.baseUrl ?? EU_BASE2}/v1/credits`, { headers: { "x-key": apiKey } });
@@ -3328,7 +3333,7 @@ function bflAdapter(config = {}) {
3328
3333
  const base = config.baseUrl ?? EU_BASE2;
3329
3334
  const pollIntervalMs = config.pollIntervalMs ?? 1500;
3330
3335
  const timeoutMs = config.timeoutMs ?? 12e4;
3331
- const resolveKey = () => config.apiKey ?? process.env.BFL_API_KEY;
3336
+ const resolveKey = () => config.apiKey ?? env().BFL_API_KEY;
3332
3337
  async function image(req) {
3333
3338
  const apiKey = resolveKey();
3334
3339
  if (!apiKey) throw new Error("bfl adapter: BFL_API_KEY not set");
@@ -3493,7 +3498,7 @@ function recraftAdapter(config = {}) {
3493
3498
  const fetchImpl = config.fetch ?? fetch;
3494
3499
  const baseUrl = config.baseUrl ?? DEFAULT_BASE_URLS.recraft;
3495
3500
  function key() {
3496
- const k = config.apiKey ?? process.env.RECRAFT_API_TOKEN;
3501
+ const k = config.apiKey ?? env().RECRAFT_API_TOKEN;
3497
3502
  if (!k) throw new Error("recraft adapter: API token not set (env RECRAFT_API_TOKEN)");
3498
3503
  return k;
3499
3504
  }
@@ -3534,6 +3539,52 @@ function recraftAdapter(config = {}) {
3534
3539
  return { name: "recraft", vectorize };
3535
3540
  }
3536
3541
 
3542
+ // src/providers/local.ts
3543
+ var LOCAL_EMBEDDING_DEFAULT_URL = "http://127.0.0.1:11434/v1";
3544
+ function localAdapter(config = {}) {
3545
+ const baseUrl = () => (config.baseUrl ?? env().LOCAL_EMBEDDING_URL ?? LOCAL_EMBEDDING_DEFAULT_URL).replace(/\/$/, "");
3546
+ async function embedding(req) {
3547
+ const url = baseUrl();
3548
+ const model = req.spec.model;
3549
+ let res;
3550
+ try {
3551
+ res = await httpTransport({
3552
+ spec: req.spec,
3553
+ fetch: config.fetch,
3554
+ // No key: a local server needs none, and none is ever sent.
3555
+ http: { url: `${url}/embeddings`, headers: { "content-type": "application/json" }, body: { model, input: req.input } }
3556
+ });
3557
+ } catch (e) {
3558
+ throw new Error(
3559
+ `local embedding server not reachable at ${url} (${e.message}). Start it (e.g. \`ollama serve\`) or set LOCAL_EMBEDDING_URL. Nothing was sent to any other provider.`,
3560
+ { cause: e }
3561
+ );
3562
+ }
3563
+ if (res.status === 404) {
3564
+ throw new Error(`local embedding model "${model}" is not available at ${url} \u2014 pull it first: \`ollama pull ${model}\`. (${errorBody(res.json, res.text)})`);
3565
+ }
3566
+ if (!res.ok) throw new Error(`local embedding ${res.status} at ${url}: ${errorBody(res.json, res.text)}`);
3567
+ const data = res.json;
3568
+ const vectors = (data.data ?? []).map((d) => d.embedding);
3569
+ if (vectors.length !== req.input.length) {
3570
+ throw new Error(`local embedding at ${url} returned ${vectors.length} vectors for ${req.input.length} inputs`);
3571
+ }
3572
+ const usage = freshUsage({
3573
+ provider: "local",
3574
+ model,
3575
+ transport: "http",
3576
+ capability: "embedding",
3577
+ region: regionOfHost(url),
3578
+ inputTokens: data.usage?.prompt_tokens ?? 0,
3579
+ outputTokens: 0
3580
+ });
3581
+ usage.costUsd = 0;
3582
+ usage.costBasis = "computed";
3583
+ return { vectors, usage };
3584
+ }
3585
+ return { name: "local", embedding };
3586
+ }
3587
+
3537
3588
  // src/providers/registry.ts
3538
3589
  var defaultProviders = {
3539
3590
  anthropic: anthropicAdapter(),
@@ -3552,7 +3603,9 @@ var defaultProviders = {
3552
3603
  "microsoft-decision": microsoftDecisionAdapter(),
3553
3604
  fal: falAdapter(),
3554
3605
  bfl: bflAdapter(),
3555
- recraft: recraftAdapter()
3606
+ recraft: recraftAdapter(),
3607
+ // F095 — embeddings on our own machines (Ollama), $0. Only via override; never a default.
3608
+ local: localAdapter()
3556
3609
  };
3557
3610
 
3558
3611
  // src/cost/budget.ts
@@ -4521,8 +4574,8 @@ var aiConfigSchema = z.object({
4521
4574
  import { randomUUID } from "crypto";
4522
4575
 
4523
4576
  // src/version.ts
4524
- var VERSION = "0.75.0";
4525
- var SDK_TAG = "@broberg/ai-sdk@0.75.0";
4577
+ var VERSION = "0.76.0";
4578
+ var SDK_TAG = "@broberg/ai-sdk@0.76.0";
4526
4579
 
4527
4580
  // src/cost/sinks/upmetrics.ts
4528
4581
  function isRetryableStatus(status) {
@@ -4851,7 +4904,7 @@ var EU_JUDGE_SPEC = { provider: "microsoft-decision", model: "microsoft-decision
4851
4904
  var DEFAULT_JUDGE_SPEC = EU_JUDGE_SPEC;
4852
4905
  var JUDGE_SPECS = { typesafe: JEV_JUDGE_SPEC, "microsoft-decision": EU_JUDGE_SPEC };
4853
4906
  function judgeSpecFromEnv() {
4854
- const v = process.env.AI_JUDGE_PROVIDER;
4907
+ const v = env().AI_JUDGE_PROVIDER;
4855
4908
  if (v === void 0 || v === "") return DEFAULT_JUDGE_SPEC;
4856
4909
  const spec = JUDGE_SPECS[v];
4857
4910
  if (!spec) throw new Error(`createAI: AI_JUDGE_PROVIDER="${v}" is not a judge route \u2014 use ${Object.keys(JUDGE_SPECS).join(" or ")}`);
@@ -4889,17 +4942,17 @@ var ROUTED_SPECS = [
4889
4942
  DEFAULT_TRANSCRIBE_SPEC
4890
4943
  ];
4891
4944
  function defaultCostSink(agentName) {
4892
- const apiKey = process.env.UPMETRICS_API_KEY;
4945
+ const apiKey = env().UPMETRICS_API_KEY;
4893
4946
  if (!apiKey) return void 0;
4894
4947
  return upmetricsSink({
4895
- baseUrl: process.env.UPMETRICS_BASE_URL ?? "https://upmetrics.org",
4948
+ baseUrl: env().UPMETRICS_BASE_URL ?? "https://upmetrics.org",
4896
4949
  apiKey,
4897
4950
  agentName,
4898
- complianceMode: process.env.UPMETRICS_COMPLIANCE === "1"
4951
+ complianceMode: env().UPMETRICS_COMPLIANCE === "1"
4899
4952
  });
4900
4953
  }
4901
4954
  function requireAgentName(configured) {
4902
- const name = (configured ?? process.env.UPMETRICS_AGENT_NAME ?? "").trim();
4955
+ const name = (configured ?? env().UPMETRICS_AGENT_NAME ?? "").trim();
4903
4956
  if (name) return name;
4904
4957
  throw new Error(
4905
4958
  'createAI(): no agent name \u2014 every AI call must say who made it (owner order 2026-10-15). Set UPMETRICS_AGENT_NAME=<your repo> (production AND test env), or pass createAI({ agentName: "<your repo>" }). Not needed with an explicit costSink, or costSink: null.'
@@ -5490,7 +5543,8 @@ function createAI(config = {}) {
5490
5543
  invoke: async (spec) => {
5491
5544
  const adapter = pickProvider(spec.provider);
5492
5545
  if (!adapter.embedding) throw new Error(`createAI: provider "${spec.provider}" does not support embedding`);
5493
- return adapter.embedding({ input: text, spec });
5546
+ const r = await adapter.embedding({ input: text, spec });
5547
+ return { ...r, model: r.usage.model, dimensions: r.vectors[0]?.length ?? 0 };
5494
5548
  }
5495
5549
  });
5496
5550
  },
@@ -5829,7 +5883,7 @@ async function refreshAvailability(opts = {}) {
5829
5883
  const now = opts.now ?? Date.now();
5830
5884
  const last = lastRefreshAt.get(provider);
5831
5885
  if (last !== void 0 && now - last < ttl) return NOT_REFRESHED;
5832
- const apiKey = opts.apiKey ?? process.env.ANTHROPIC_API_KEY;
5886
+ const apiKey = opts.apiKey ?? env().ANTHROPIC_API_KEY;
5833
5887
  if (!apiKey) return NOT_REFRESHED;
5834
5888
  const f = opts.fetch ?? fetch;
5835
5889
  let liveIds;
@@ -6143,6 +6197,7 @@ export {
6143
6197
  ELEVENLABS_DANISH_VOICES,
6144
6198
  INPUT_LIMITS,
6145
6199
  LOCALLY_PINNED_HOSTS,
6200
+ LOCAL_EMBEDDING_DEFAULT_URL,
6146
6201
  MEDIA_PRICING_CHECKED_AT,
6147
6202
  MICROSOFT_DECISION_DEFAULT_DEPLOYMENT,
6148
6203
  ModelUnavailableError,
@@ -6203,6 +6258,7 @@ export {
6203
6258
  listMediaPrices,
6204
6259
  listModels,
6205
6260
  listVoices,
6261
+ localAdapter,
6206
6262
  makeContracts,
6207
6263
  makeOpenAICompatibleAdapter,
6208
6264
  matchLabel,