ai 7.0.178 → 7.0.180

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.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
- import { $ as convertToLanguageModelPrompt, A as toolSearch, At as UnsupportedModelVersionError, B as setAbortTimeout, C as resolveToolApproval, Ct as asLanguageModelV4, D as convertToReasoningOutputs, Dt as RetryError, E as DefaultGenerateTextResult, Et as logWarnings, F as resolveGeneratedFileData, Ft as ToolCallNotFoundForApprovalError, G as addLanguageModelUsage, H as mergeAbortSignals, I as DefaultGeneratedFile, It as InvalidToolInputError, J as standardizePrompt, K as asLanguageModelUsage, L as DefaultGeneratedFileWithType, Lt as InvalidToolApprovalSignatureError, M as prepareToolsForToolCallers, Mt as NoSuchToolError, N as resolveToolCallerConfiguration, Nt as NoOutputGeneratedError, O as validateToolContext, Ot as InvalidMessageRoleError, P as convertLanguageModelContent, Pt as MissingToolResultsError, Q as createToolModelOutput, R as collectToolApprovals, Rt as InvalidToolApprovalError, S as filterIncludedContext, St as asVideoModelV4, T as getToolCallInputSchemaInput, Tt as asEmbeddingModelV4, U as getOwn, V as prepareRetries, W as addImageModelUsage, X as prepareToolChoice, Y as prepareTools, Z as prepareLanguageModelCallOptions, _ as createTelemetryDispatcher, _t as resolveSpeechModel, a as createAsyncIterableStream, at as convertDataContentToUint8Array, b as AI_SDK_TELEMETRY_TRACING_CHANNEL, bt as resolveVideoModel, c as validateApprovedToolApprovals, ct as download, dt as resolveDecisionModel, f as hashCanonical, ft as resolveEmbeddingModel, g as DefaultStepResult, gt as resolveRerankingModel, h as createRestrictedTelemetryDispatcher$4, ht as resolveLanguageModel, i as asAsyncIterableStream, it as convertDataContentToBase64String, j as appendToolCallerMessages, jt as ToolCallRepairError, k as createToolSearchState, kt as InvalidDataContentError, l as maybeSignApproval, lt as VERSION, m as isDeepEqualData, mt as resolveImageModel, nt as convertToLanguageModelV4FilePart, o as mapWithConcurrency, ot as mergeObjects, p as toResponseMessages, pt as resolveExtractionModel, q as createNullLanguageModelUsage, r as isOutputChunk$1, rt as splitDataUrl, s as prepareToolCallConcurrency, t as createDefaultStopCondition, ut as asEvaluationModel, v as getGlobalTelemetryIntegrations, vt as resolveSpeechTranslationModel, w as parseToolCall, wt as asImageModelV4, x as mergeCallbacks, xt as asProviderV4, y as registerTelemetry, yt as resolveTranscriptionModel, z as calculateTokensPerSecond, zt as InvalidArgumentError } from "./default-stop-condition-BskNu2xj.js";
2
+ import { $ as convertToLanguageModelPrompt, A as toolSearch, At as UnsupportedModelVersionError, B as setAbortTimeout, C as resolveToolApproval, Ct as asLanguageModelV4, D as convertToReasoningOutputs, Dt as RetryError, E as DefaultGenerateTextResult, Et as logWarnings, F as resolveGeneratedFileData, Ft as ToolCallNotFoundForApprovalError, G as addLanguageModelUsage, H as mergeAbortSignals, I as DefaultGeneratedFile, It as InvalidToolInputError, J as standardizePrompt, K as asLanguageModelUsage, L as DefaultGeneratedFileWithType, Lt as InvalidToolApprovalSignatureError, M as prepareToolsForToolCallers, Mt as NoSuchToolError, N as resolveToolCallerConfiguration, Nt as NoOutputGeneratedError, O as validateToolContext, Ot as InvalidMessageRoleError, P as convertLanguageModelContent, Pt as MissingToolResultsError, Q as createToolModelOutput, R as collectToolApprovals, Rt as InvalidToolApprovalError, S as filterIncludedContext, St as asVideoModelV4, T as getToolCallInputSchemaInput, Tt as asEmbeddingModelV4, U as getOwn, V as prepareRetries, W as addImageModelUsage, X as prepareToolChoice, Y as prepareTools, Z as prepareLanguageModelCallOptions, _ as createTelemetryDispatcher, _t as resolveSpeechModel, a as createAsyncIterableStream, at as convertDataContentToUint8Array, b as AI_SDK_TELEMETRY_TRACING_CHANNEL, bt as resolveVideoModel, c as validateApprovedToolApprovals, ct as download, dt as resolveDecisionModel, f as hashCanonical, ft as resolveEmbeddingModel, g as DefaultStepResult, gt as resolveRerankingModel, h as createRestrictedTelemetryDispatcher$4, ht as resolveLanguageModel, i as asAsyncIterableStream, it as convertDataContentToBase64String, j as appendToolCallerMessages, jt as ToolCallRepairError, k as createToolSearchState, kt as InvalidDataContentError, l as maybeSignApproval, lt as VERSION, m as isDeepEqualData, mt as resolveImageModel, nt as convertToLanguageModelV4FilePart, o as mapWithConcurrency, ot as mergeObjects, p as toResponseMessages, pt as resolveExtractionModel, q as createNullLanguageModelUsage, r as isOutputChunk$1, rt as splitDataUrl, s as prepareToolCallConcurrency, t as createDefaultStopCondition, ut as asEvaluationModel, v as getGlobalTelemetryIntegrations, vt as resolveSpeechTranslationModel, w as parseToolCall, wt as asImageModelV4, x as mergeCallbacks, xt as asProviderV4, y as registerTelemetry, yt as resolveTranscriptionModel, z as calculateTokensPerSecond, zt as InvalidArgumentError } from "./default-stop-condition-vtYEJcnz.js";
3
3
  import { t as simulateReadableStream } from "./simulate-readable-stream-Bi5kQKbv.js";
4
4
  import { GatewayAuthenticationError, createGateway, gateway, gateway as gateway$1 } from "@ai-sdk/gateway";
5
5
  import { DelayedPromise, DownloadError, DownloadError as DownloadError$1, EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL, EXPERIMENTAL_EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER, asArray, asSchema, asSchema as asSchema$1, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertUint8ArrayToBase64, createIdGenerator, createIdGenerator as createIdGenerator$1, delay, detectMediaType, dynamicTool, executeTool, experimental_toolCaller, filterNullable, generateId, generateId as generateId$1, getErrorMessage, getRuntimeEnvironmentUserAgent, getTopLevelMediaType, getWebSocketConstructor, isAbortError, isArrayBuffer, isBuffer, isExecutableTool, isFullMediaType, isNonNullable, isProviderReference, isProviderStreamError, isUint8Array, jsonSchema, lazySchema, normalizeHeaders, parseJsonEventStream, parseJsonEventStream as parseJsonEventStream$1, readWebSocketMessageText, resolve, safeParseJSON, safeValidateTypes, toWebSocketUrl, tool, validateTypes, waitForWebSocketBufferDrain, withUserAgentSuffix, zodSchema, zodSchema as zodSchema$1 } from "@ai-sdk/provider-utils";
@@ -14632,7 +14632,7 @@ var BrowserRealtimeTransport = class {
14632
14632
  };
14633
14633
  //#endregion
14634
14634
  //#region src/realtime/browser-realtime-live-websocket.ts
14635
- /** Continuous PCM16 audio-chunk media for an application-owned WebSocket relay. */
14635
+ /** Continuous PCM16 audio-chunk media over a WebSocket relay or client-secret connection. */
14636
14636
  var BrowserRealtimeLiveWebSocket = class {
14637
14637
  constructor(options) {
14638
14638
  this.options = options;
@@ -14683,9 +14683,18 @@ var BrowserRealtimeLiveWebSocket = class {
14683
14683
  });
14684
14684
  }
14685
14685
  connect(options) {
14686
+ if (this.prepare(options) !== this.generation) return;
14687
+ this.open({
14688
+ mode: "relay",
14689
+ url: options.url,
14690
+ protocols: options.protocols
14691
+ });
14692
+ }
14693
+ /** Resets media and primes playback; call while still in the user gesture. */
14694
+ prepare(options) {
14686
14695
  const generation = this.generation + 1;
14687
14696
  this.dispose();
14688
- if (generation !== this.generation) return;
14697
+ if (generation !== this.generation) return generation;
14689
14698
  for (const format of [this.config.inputAudioFormat, this.config.outputAudioFormat]) {
14690
14699
  if (format?.type !== "audio/pcm") throw new UnsupportedFunctionalityError$1({ functionality: "Continuous browser WebSocket audio supports PCM16 only" });
14691
14700
  if (format.rate == null || !Number.isFinite(format.rate) || format.rate < 8e3 || format.rate > 96e3) throw new Error("Invalid realtime PCM sample rate");
@@ -14696,10 +14705,12 @@ var BrowserRealtimeLiveWebSocket = class {
14696
14705
  this.audio.resumePlayback().catch((error) => {
14697
14706
  if (generation === this.generation) this.options.onError(error);
14698
14707
  });
14708
+ return generation;
14709
+ }
14710
+ /** Opens the socket through an application relay or with a client secret. */
14711
+ open(connection) {
14699
14712
  this.transport.connect({
14700
- mode: "relay",
14701
- url: options.url,
14702
- protocols: options.protocols,
14713
+ ...connection,
14703
14714
  onOpen: () => {
14704
14715
  return this.transport.sendEvent({
14705
14716
  type: this.options.model.capabilities?.startup ?? "session-update",
@@ -15746,7 +15757,7 @@ var AbstractRealtimeSession = class {
15746
15757
  if (model.getWebRTCConfig == null) throw new Error("Realtime model does not support WebRTC configuration");
15747
15758
  return;
15748
15759
  }
15749
- if (this.continuous && api.websocket == null) throw new Error("Continuous PCM sessions require an application WebSocket relay");
15760
+ if (this.continuous && api.token != null && !model.capabilities?.connections?.includes("client-secret-websocket")) throw new Error("Realtime model does not support client-secret-websocket");
15750
15761
  if (api.token != null && model.getWebSocketConfig == null) throw new Error("Realtime model does not support client-secret WebSocket configuration");
15751
15762
  }
15752
15763
  async connect(connectOptions) {
@@ -15873,38 +15884,42 @@ var AbstractRealtimeSession = class {
15873
15884
  capture: connectOptions?.capture,
15874
15885
  timeoutMs: this.options.startupTimeoutMs ?? 3e4
15875
15886
  });
15876
- } else if (api.websocket != null && model.capabilities?.conversation === "continuous") {
15877
- this.pcm = new BrowserRealtimeLiveWebSocket({
15887
+ } else if (this.continuous) {
15888
+ const pcm = new BrowserRealtimeLiveWebSocket({
15878
15889
  ...callbacks,
15879
15890
  sessionConfig,
15880
15891
  sampleRate: this.options.sampleRate,
15881
15892
  maxPlaybackBufferSeconds: this.options.maxPlaybackBufferSeconds
15882
15893
  });
15883
- this.pcm.connect({
15894
+ this.pcm = pcm;
15895
+ if (api.websocket != null) pcm.connect({
15884
15896
  url: api.websocket,
15885
15897
  protocols: api.protocols,
15886
15898
  stream: connectOptions?.stream,
15887
15899
  capture: connectOptions?.capture
15888
15900
  });
15901
+ else if (api.token != null) {
15902
+ pcm.prepare({
15903
+ stream: connectOptions?.stream,
15904
+ capture: connectOptions?.capture
15905
+ });
15906
+ const setup = await this.fetchRealtimeSetup(api.token, sessionConfig, attempt);
15907
+ if (setup == null || !current() || this.pcm !== pcm) return;
15908
+ if (setup.tools != null && setup.tools.length > 0) throw new UnsupportedFunctionalityError$1({ functionality: "Realtime setup tools for continuous sessions; client delegation is application-owned" });
15909
+ pcm.open({
15910
+ mode: "client-secret",
15911
+ token: setup.token,
15912
+ url: setup.url
15913
+ });
15914
+ }
15889
15915
  } else {
15890
15916
  this.ensureAudio();
15891
15917
  let config = sessionConfig ?? {};
15892
15918
  let token;
15893
15919
  let url = api.websocket;
15894
15920
  if (api.token != null) {
15895
- const response = await fetch(api.token, {
15896
- method: "POST",
15897
- headers: { "Content-Type": "application/json" },
15898
- body: JSON.stringify({ sessionConfig }),
15899
- signal: attempt.abort.signal
15900
- });
15901
- if (!current()) return;
15902
- if (!response.ok) throw new Error(`Failed to fetch realtime setup: ${response.status}`);
15903
- const payload = await response.json().catch(() => {
15904
- throw new Error("Invalid realtime setup response");
15905
- });
15906
- if (!current() || attempt.closing) return;
15907
- const setup = validateRealtimeSetup(payload);
15921
+ const setup = await this.fetchRealtimeSetup(api.token, sessionConfig, attempt);
15922
+ if (setup == null) return;
15908
15923
  token = setup.token;
15909
15924
  url = setup.url;
15910
15925
  config = {
@@ -15943,6 +15958,23 @@ var AbstractRealtimeSession = class {
15943
15958
  if (current()) this.fail(error);
15944
15959
  }
15945
15960
  }
15961
+ /** Fetches the application's token setup; undefined when the attempt ended. */
15962
+ async fetchRealtimeSetup(endpoint, sessionConfig, attempt) {
15963
+ const current = () => this.attempt === attempt && attempt.active;
15964
+ const response = await fetch(endpoint, {
15965
+ method: "POST",
15966
+ headers: { "Content-Type": "application/json" },
15967
+ body: JSON.stringify({ sessionConfig }),
15968
+ signal: attempt.abort.signal
15969
+ });
15970
+ if (!current()) return void 0;
15971
+ if (!response.ok) throw new Error(`Failed to fetch realtime setup: ${response.status}`);
15972
+ const payload = await response.json().catch(() => {
15973
+ throw new Error("Invalid realtime setup response");
15974
+ });
15975
+ if (!current() || attempt.closing) return void 0;
15976
+ return validateRealtimeSetup(payload);
15977
+ }
15946
15978
  fail(error, drain, report = true) {
15947
15979
  const attempt = this.attempt;
15948
15980
  if (attempt == null || !attempt.active || attempt.cause != null) return;