@broberg/ai-sdk 0.73.0 → 0.74.1

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-CCKJyveA.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-CCKJyveA.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-Dwe4cmUM.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-Dwe4cmUM.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
 
@@ -30,9 +30,10 @@ interface SecondOpinionInput {
30
30
  synthesize?: boolean;
31
31
  maxTokens?: number;
32
32
  /** F088.5 — per-model time limit. A model that has not answered by then gets an
33
- * error row ("timeout") and the others are delivered. Default 5 min. The provider
34
- * request is not cancelled, so a late answer may still be billed — it is just not
35
- * waited for. */
33
+ * error row ("timeout") and the others are delivered. Default 5 min. Since F090
34
+ * (v0.74) the provider request itself is aborted — the connection closes, so a late
35
+ * answer is not billed. The race below stays as a backstop for an adapter that does
36
+ * not forward the signal. */
36
37
  timeoutMs?: number;
37
38
  /** USD→DKK rate for the price line. Omitted: the ECB reference rate is fetched. */
38
39
  usdToDkk?: number;
@@ -460,6 +461,8 @@ declare const chatInputSchema: z.ZodObject<{
460
461
  text: "text";
461
462
  json: "json";
462
463
  }>>;
464
+ timeoutMs: z.ZodOptional<z.ZodNumber>;
465
+ signal: z.ZodOptional<z.ZodInstanceOf<AbortSignal>>;
463
466
  }, z.core.$strip>;
464
467
  declare const visionInputSchema: z.ZodObject<{
465
468
  tier: z.ZodOptional<z.ZodEnum<{
@@ -1233,6 +1236,16 @@ type ChatVision = Pick<AiClient, "chat" | "vision">;
1233
1236
  declare function matchLabel(answer: unknown, labels: string[]): string | null;
1234
1237
  declare function makeContracts(client: ChatVision): Contracts;
1235
1238
 
1239
+ /** The call ran longer than the caller's `timeoutMs`; the request was aborted. */
1240
+ declare class AiTimeoutError extends Error {
1241
+ readonly timeoutMs: number;
1242
+ constructor(timeoutMs: number, what?: string);
1243
+ }
1244
+ /** The caller's own `signal` aborted the call. */
1245
+ declare class AiAbortError extends Error {
1246
+ constructor(what?: string);
1247
+ }
1248
+
1236
1249
  /** Convert SDK tools to a provider's request format. */
1237
1250
  declare function toProviderTools(tools: Tool[], provider: string): unknown;
1238
1251
  /** Parse a single provider-shaped tool call back into the SDK ToolCall shape. */
@@ -1267,6 +1280,7 @@ declare function geminiAdapter(config?: {
1267
1280
  declare function deepinfraAdapter(config?: {
1268
1281
  apiKey?: string;
1269
1282
  baseUrl?: string;
1283
+ fetch?: typeof fetch;
1270
1284
  }): ProviderAdapter;
1271
1285
 
1272
1286
  interface OpenRouterAdapterConfig {
@@ -1488,6 +1502,10 @@ interface OpenAICompatibleConfig {
1488
1502
  * response's `usage.cost` (USD) as costUsd, falling back to the pricing table.
1489
1503
  * Only OpenRouter returns this field — openai/deepinfra leave it false. */
1490
1504
  costFromResponseField?: boolean;
1505
+ /** F091 — the provider reports its own price under this `usage` field (USD) WITHOUT
1506
+ * being asked: DeepInfra's `estimated_cost`. Read in chat and stream; wins over the
1507
+ * pricing table. Unlike costFromResponseField nothing is added to the request. */
1508
+ reportedCostField?: "estimated_cost";
1491
1509
  /** F039.2 — this provider accepts `prompt_cache_key` and caches a shared prefix
1492
1510
  * on it. Mistral only, deliberately: an unknown field is ignored by some
1493
1511
  * OpenAI-compatible servers and rejected with a 400 by others, so sending it
@@ -1569,8 +1587,8 @@ declare const falStubAdapter: ProviderAdapter;
1569
1587
  * wires the live adapters. */
1570
1588
  declare const stubProviders: Record<string, ProviderAdapter>;
1571
1589
 
1572
- declare const VERSION: "0.73.0";
1573
- declare const SDK_TAG: "@broberg/ai-sdk@0.73.0";
1590
+ declare const VERSION: "0.74.1";
1591
+ declare const SDK_TAG: "@broberg/ai-sdk@0.74.1";
1574
1592
 
1575
1593
  /** Built-in defaults. Every entry is overridable via AiConfig.defaults or a
1576
1594
  * per-call override.
@@ -2036,6 +2054,8 @@ interface TransportRequest {
2036
2054
  * config MUST pass it here, or a test's fake fetch is silently bypassed and the call
2037
2055
  * reaches the real provider with whatever key is in the environment. */
2038
2056
  fetch?: typeof fetch;
2057
+ /** F090 — aborts the fetch itself (timeoutMs / caller signal). */
2058
+ signal?: AbortSignal;
2039
2059
  http?: {
2040
2060
  url: string;
2041
2061
  method?: string;
@@ -2137,4 +2157,4 @@ declare function memorySearchCache(max?: number): SearchCache;
2137
2157
 
2138
2158
  declare function search(req: SearchRequest, opts?: SearchOptions): Promise<SearchResult>;
2139
2159
 
2140
- export { AZURE_DANISH_VOICES, AZURE_DANISH_VOICE_LIST, type AiClient, type AiConfig, 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 };
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 };
package/dist/index.js CHANGED
@@ -23,7 +23,7 @@ import {
23
23
  listMediaPrices,
24
24
  pricingFreshness,
25
25
  pricingGeneratedAt
26
- } from "./chunk-XKN2PYBQ.js";
26
+ } from "./chunk-WDGXCBD2.js";
27
27
  import {
28
28
  PRICING,
29
29
  getPrice
@@ -170,7 +170,8 @@ function classifyFailure(err) {
170
170
  const e = err;
171
171
  const name = e?.name ?? "";
172
172
  const message = String(e?.message ?? "");
173
- if (name === "AbortError" || name === "TimeoutError" || /timed? ?out/i.test(message.split("\n")[0] ?? "")) {
173
+ if (name === "AiAbortError") return { errorCode: "aborted", errorKind: "other" };
174
+ if (name === "AbortError" || name === "TimeoutError" || name === "AiTimeoutError" || /timed? ?out/i.test(message.split("\n")[0] ?? "")) {
174
175
  return { errorCode: "timeout", errorKind: "timeout" };
175
176
  }
176
177
  let status = typeof e?.status === "number" ? e.status : void 0;
@@ -437,6 +438,7 @@ async function httpTransport(req) {
437
438
  const res = await (req.fetch ?? fetch)(url, {
438
439
  method,
439
440
  headers,
441
+ signal: req.signal,
440
442
  body: body === void 0 ? void 0 : typeof body === "string" ? body : JSON.stringify(body)
441
443
  });
442
444
  const text = await res.text().catch(() => "");
@@ -529,6 +531,7 @@ async function* streamTransport(req) {
529
531
  const res = await fetchImpl(url, {
530
532
  method,
531
533
  headers,
534
+ signal: req.signal,
532
535
  body: body === void 0 ? void 0 : typeof body === "string" ? body : JSON.stringify(body)
533
536
  });
534
537
  if (!res.ok || !res.body) {
@@ -879,6 +882,7 @@ function anthropicAdapter(config = {}) {
879
882
  const res = await httpTransport({
880
883
  spec: req.spec,
881
884
  fetch: config.fetch,
885
+ signal: req.signal,
882
886
  http: {
883
887
  url: `${baseUrl}/v1/messages`,
884
888
  headers: {
@@ -937,6 +941,7 @@ function anthropicAdapter(config = {}) {
937
941
  const stream = streamTransport({
938
942
  spec: req.spec,
939
943
  fetch: config.fetch,
944
+ signal: req.signal,
940
945
  http: {
941
946
  url: `${baseUrl}/v1/messages`,
942
947
  headers: {
@@ -1165,6 +1170,7 @@ function makeOpenAICompatibleAdapter(config) {
1165
1170
  const res = await httpTransport({
1166
1171
  spec: req.spec,
1167
1172
  fetch: config.fetch,
1173
+ signal: req.signal,
1168
1174
  http: {
1169
1175
  url: `${config.baseUrl}/chat/completions`,
1170
1176
  headers: {
@@ -1203,6 +1209,12 @@ function makeOpenAICompatibleAdapter(config) {
1203
1209
  });
1204
1210
  if (config.costFromResponseField && typeof data.usage?.cost === "number") {
1205
1211
  usage.costUsd = data.usage.cost;
1212
+ usage.costBasis = "reported";
1213
+ }
1214
+ const reported = config.reportedCostField ? data.usage?.[config.reportedCostField] : void 0;
1215
+ if (typeof reported === "number") {
1216
+ usage.costUsd = reported;
1217
+ usage.costBasis = "reported";
1206
1218
  }
1207
1219
  if (typeof data.model === "string" && data.model) usage.servedModel = data.model;
1208
1220
  const result = { text, usage };
@@ -1223,6 +1235,7 @@ function makeOpenAICompatibleAdapter(config) {
1223
1235
  const stream = streamTransport({
1224
1236
  spec: req.spec,
1225
1237
  fetch: config.fetch,
1238
+ signal: req.signal,
1226
1239
  http: {
1227
1240
  url: `${config.baseUrl}/chat/completions`,
1228
1241
  headers: {
@@ -1271,6 +1284,12 @@ function makeOpenAICompatibleAdapter(config) {
1271
1284
  });
1272
1285
  if (config.costFromResponseField && typeof chunk.usage.cost === "number") {
1273
1286
  usage.costUsd = chunk.usage.cost;
1287
+ usage.costBasis = "reported";
1288
+ }
1289
+ const reportedChunk = config.reportedCostField ? chunk.usage[config.reportedCostField] : void 0;
1290
+ if (typeof reportedChunk === "number") {
1291
+ usage.costUsd = reportedChunk;
1292
+ usage.costBasis = "reported";
1274
1293
  }
1275
1294
  if (typeof chunk.model === "string" && chunk.model) usage.servedModel = chunk.model;
1276
1295
  yield { type: "usage", costUsd: usage.costUsd, model: usage.model, usage };
@@ -1482,6 +1501,7 @@ function geminiAdapter(config = {}) {
1482
1501
  const res = await httpTransport({
1483
1502
  spec: req.spec,
1484
1503
  fetch: config.fetch,
1504
+ signal: req.signal,
1485
1505
  http: {
1486
1506
  url: `${baseUrl}/models/${req.spec.model}:generateContent?key=${encodeURIComponent(apiKey)}`,
1487
1507
  headers: { "content-type": "application/json" },
@@ -1513,6 +1533,7 @@ function geminiAdapter(config = {}) {
1513
1533
  const stream = streamTransport({
1514
1534
  spec: req.spec,
1515
1535
  fetch: config.fetch,
1536
+ signal: req.signal,
1516
1537
  http: {
1517
1538
  url: `${baseUrl}/models/${req.spec.model}:streamGenerateContent?alt=sse&key=${encodeURIComponent(apiKey)}`,
1518
1539
  headers: { "content-type": "application/json" },
@@ -1679,7 +1700,10 @@ function deepinfraAdapter(config = {}) {
1679
1700
  return makeOpenAICompatibleAdapter({
1680
1701
  name: "deepinfra",
1681
1702
  baseUrl: config.baseUrl ?? DEFAULT_BASE_URLS.deepinfra,
1682
- apiKey: config.apiKey
1703
+ apiKey: config.apiKey,
1704
+ fetch: config.fetch,
1705
+ // F091 — DeepInfra puts its own price in usage.estimated_cost (measured 2026-11-17).
1706
+ reportedCostField: "estimated_cost"
1683
1707
  });
1684
1708
  }
1685
1709
 
@@ -3918,7 +3942,8 @@ Write your entire answer in ${input.language ?? "Danish"}.`;
3918
3942
  prompt,
3919
3943
  maxTokens,
3920
3944
  override: override(m),
3921
- purpose: "second-opinion"
3945
+ purpose: "second-opinion",
3946
+ timeoutMs
3922
3947
  }),
3923
3948
  timeoutMs,
3924
3949
  m.label
@@ -3942,7 +3967,8 @@ ${o.text}
3942
3967
  prompt: reviews,
3943
3968
  maxTokens: 6e3,
3944
3969
  override: override(SECOND_OPINION_SYNTH),
3945
- purpose: "second-opinion-synthesis"
3970
+ purpose: "second-opinion-synthesis",
3971
+ timeoutMs
3946
3972
  }),
3947
3973
  timeoutMs,
3948
3974
  SECOND_OPINION_SYNTH.label
@@ -3989,6 +4015,38 @@ function toMarkdown(input, opinions, synthesis, cost) {
3989
4015
  return lines.join("\n");
3990
4016
  }
3991
4017
 
4018
+ // src/transport/abort.ts
4019
+ var AiTimeoutError = class extends Error {
4020
+ timeoutMs;
4021
+ constructor(timeoutMs, what = "ai call") {
4022
+ super(`${what} timed out after ${timeoutMs} ms \u2014 the request was aborted`);
4023
+ this.name = "AiTimeoutError";
4024
+ this.timeoutMs = timeoutMs;
4025
+ }
4026
+ };
4027
+ var AiAbortError = class extends Error {
4028
+ constructor(what = "ai call") {
4029
+ super(`${what} was aborted by the caller's signal`);
4030
+ this.name = "AiAbortError";
4031
+ }
4032
+ };
4033
+ function callAbort(callerSignal, timeoutMs) {
4034
+ const timeout = timeoutMs !== void 0 ? AbortSignal.timeout(timeoutMs) : void 0;
4035
+ const parts = [callerSignal, timeout].filter((s) => !!s);
4036
+ const signal = parts.length === 0 ? void 0 : parts.length === 1 ? parts[0] : AbortSignal.any(parts);
4037
+ return {
4038
+ signal,
4039
+ translate(e, what) {
4040
+ if (!signal?.aborted) return e;
4041
+ if (timeout?.aborted && !callerSignal?.aborted) return new AiTimeoutError(timeoutMs, what);
4042
+ return new AiAbortError(what);
4043
+ }
4044
+ };
4045
+ }
4046
+ function isCallerAbort(e) {
4047
+ return e instanceof AiTimeoutError || e instanceof AiAbortError;
4048
+ }
4049
+
3992
4050
  // src/voices/registry.ts
3993
4051
  var CHECKED_AT = {
3994
4052
  // All 5 curated ids confirmed by SYNTHESIS — POST /v1/text-to-speech/{id} returned
@@ -4225,6 +4283,11 @@ var chatInputSchema = z.object({
4225
4283
  reasoningEffort: z.enum(["none", "low", "medium", "high"]).optional(),
4226
4284
  /** "json" requests JSON-object output (OpenAI-compatible response_format). */
4227
4285
  responseFormat: z.enum(["json", "text"]).optional(),
4286
+ /** F090 — abort the request after this many ms (the connection is closed, not just
4287
+ * abandoned). Throws AiTimeoutError. */
4288
+ timeoutMs: z.number().int().positive().optional(),
4289
+ /** F090 — abort the request from outside. Throws AiAbortError. */
4290
+ signal: z.instanceof(AbortSignal).optional(),
4228
4291
  ...callOptions
4229
4292
  });
4230
4293
  var visionInputSchema = z.object({
@@ -4458,8 +4521,8 @@ var aiConfigSchema = z.object({
4458
4521
  import { randomUUID } from "crypto";
4459
4522
 
4460
4523
  // src/version.ts
4461
- var VERSION = "0.73.0";
4462
- var SDK_TAG = "@broberg/ai-sdk@0.73.0";
4524
+ var VERSION = "0.74.1";
4525
+ var SDK_TAG = "@broberg/ai-sdk@0.74.1";
4463
4526
 
4464
4527
  // src/cost/sinks/upmetrics.ts
4465
4528
  function isRetryableStatus(status) {
@@ -4980,6 +5043,7 @@ function createAI(config = {}) {
4980
5043
  },
4981
5044
  e
4982
5045
  );
5046
+ if (isCallerAbort(e)) throw e;
4983
5047
  }
4984
5048
  }
4985
5049
  throw lastErr;
@@ -5000,6 +5064,7 @@ function createAI(config = {}) {
5000
5064
  }
5001
5065
  async function* chatStreamImpl(input) {
5002
5066
  input = chatInputSchema.parse(input);
5067
+ const abort = callAbort(input.signal, input.timeoutMs);
5003
5068
  const tier = input.tier ?? "smart";
5004
5069
  const messages = toMessages(input);
5005
5070
  const estIn = messages.reduce(
@@ -5026,6 +5091,7 @@ function createAI(config = {}) {
5026
5091
  let emitted = false;
5027
5092
  try {
5028
5093
  for await (const ev of adapter.chatStream({
5094
+ signal: abort.signal,
5029
5095
  messages,
5030
5096
  spec,
5031
5097
  tools: input.tools,
@@ -5050,7 +5116,8 @@ function createAI(config = {}) {
5050
5116
  yield ev;
5051
5117
  }
5052
5118
  return;
5053
- } catch (e) {
5119
+ } catch (raw) {
5120
+ const e = abort.translate(raw, "ai.chatStream");
5054
5121
  lastErr = e;
5055
5122
  await reportFailure(
5056
5123
  {
@@ -5065,7 +5132,7 @@ function createAI(config = {}) {
5065
5132
  },
5066
5133
  e
5067
5134
  );
5068
- if (emitted || !eligibleForFallback(e)) {
5135
+ if (emitted || isCallerAbort(e) || !eligibleForFallback(e)) {
5069
5136
  yield errorEvent(e);
5070
5137
  return;
5071
5138
  }
@@ -5076,6 +5143,7 @@ function createAI(config = {}) {
5076
5143
  const client = {
5077
5144
  async chat(input) {
5078
5145
  input = chatInputSchema.parse(input);
5146
+ const abort = callAbort(input.signal, input.timeoutMs);
5079
5147
  const tier = input.tier ?? "smart";
5080
5148
  const messages = toMessages(input);
5081
5149
  const estIn = messages.reduce(
@@ -5095,7 +5163,11 @@ function createAI(config = {}) {
5095
5163
  invoke: async (spec) => {
5096
5164
  const adapter = pickProvider(spec.provider);
5097
5165
  if (!adapter.chat) throw new Error(`createAI: provider "${spec.provider}" does not support chat`);
5098
- return adapter.chat({ messages, spec, tools: input.tools, maxTokens: input.maxTokens, temperature: input.temperature, reasoningEffort: input.reasoningEffort, responseFormat: input.responseFormat, promptCacheKey: input.promptCacheKey, promptCache: input.promptCache ?? cfg.promptCache });
5166
+ try {
5167
+ return await adapter.chat({ signal: abort.signal, messages, spec, tools: input.tools, maxTokens: input.maxTokens, temperature: input.temperature, reasoningEffort: input.reasoningEffort, responseFormat: input.responseFormat, promptCacheKey: input.promptCacheKey, promptCache: input.promptCache ?? cfg.promptCache });
5168
+ } catch (e) {
5169
+ throw abort.translate(e, "ai.chat");
5170
+ }
5099
5171
  }
5100
5172
  });
5101
5173
  },
@@ -6059,6 +6131,8 @@ function wouldRouteTo(tier) {
6059
6131
  export {
6060
6132
  AZURE_DANISH_VOICES,
6061
6133
  AZURE_DANISH_VOICE_LIST,
6134
+ AiAbortError,
6135
+ AiTimeoutError,
6062
6136
  BudgetExceededError,
6063
6137
  BudgetGuard,
6064
6138
  CONFIG_DERIVED_HOSTS,