@ai-sdk/mistral 4.0.79 → 4.0.81

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 { InvalidArgumentError, NoSuchModelError, TooManyEmbeddingValuesForCallError, UnsupportedFunctionalityError } from "@ai-sdk/provider";
2
- import { StreamingToolCallTracker, WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE, combineHeaders, convertBase64ToUint8Array, convertToBase64, createEventSourceResponseHandler, createJsonErrorResponseHandler, createJsonResponseHandler, createLanguageModelResponseMetadata as getResponseMetadata, createNullLanguageModelUsage, createProviderExecutedToolFactory, createToolNameMapping, generateId, getTopLevelMediaType, injectJsonInstructionIntoMessages, isCustomReasoning, lazySchema, loadApiKey, mapReasoningToProviderEffort, mediaTypeToExtension, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, resolve, resolveFullMediaType, resolveWith, secureJsonParse, serializeModelOptions, stringifyWithBigIntAndCycles, withUserAgentSuffix, withoutTrailingSlash, zodSchema } from "@ai-sdk/provider-utils";
2
+ import { StreamingToolCallTracker, WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE, combineHeaders, connectToWebSocket, convertBase64ToUint8Array, convertToBase64, convertUint8ArrayToBase64, createEventSourceResponseHandler, createJsonErrorResponseHandler, createJsonResponseHandler, createLanguageModelResponseMetadata as getResponseMetadata, createNullLanguageModelUsage, createProviderExecutedToolFactory, createToolNameMapping, deleteFromApi, generateId, getTopLevelMediaType, injectJsonInstructionIntoMessages, isCustomReasoning, lazySchema, loadApiKey, mapReasoningToProviderEffort, mediaTypeToExtension, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, resolve, resolveFullMediaType, resolveWith, safeParseJSON, safeValidateTypes, secureJsonParse, serializeModelOptions, stringifyWithBigIntAndCycles, toWebSocketUrl, waitForWebSocketBufferDrain, withUserAgentSuffix, withoutTrailingSlash, zodSchema } from "@ai-sdk/provider-utils";
3
3
  import { z } from "zod/v4";
4
4
  //#region src/convert-mistral-usage.ts
5
5
  const mistralPromptTokensDetailsSchema = z.object({
@@ -225,6 +225,8 @@ const mistralLanguageModelChatOptions = () => z.object({
225
225
  *
226
226
  * - `'high'`: Enable reasoning
227
227
  * - `'none'`: Disable reasoning
228
+ * - `'medium'`: Medium reasoning effort for models that support it, e.g.
229
+ * `mistral-large-4`, which accepts `'low'`, `'medium'`, and `'high'`
228
230
  * - `'low'`, `'max'`: Lowest and highest reasoning effort for models that
229
231
  * support them, e.g. `zai-glm-5-3`, which accepts `'low'`, `'high'`, and
230
232
  * `'max'` but not `'none'`
@@ -233,6 +235,7 @@ const mistralLanguageModelChatOptions = () => z.object({
233
235
  "high",
234
236
  "none",
235
237
  "low",
238
+ "medium",
236
239
  "max"
237
240
  ]).optional()
238
241
  });
@@ -293,8 +296,11 @@ function prepareTools({ tools, toolChoice }) {
293
296
  toolWarnings
294
297
  };
295
298
  case "tool": return {
296
- tools: mistralTools.filter((tool) => tool.function.name === toolChoice.toolName),
297
- toolChoice: "any",
299
+ tools: mistralTools,
300
+ toolChoice: {
301
+ type: "function",
302
+ function: { name: toolChoice.toolName }
303
+ },
298
304
  toolWarnings
299
305
  };
300
306
  default: throw new UnsupportedFunctionalityError({ functionality: `tool choice type: ${type}` });
@@ -324,7 +330,10 @@ const mistralProviderOptions = {
324
330
  temperature: { description: "Sampling temperature." },
325
331
  timestampGranularities: { description: "Timestamp granularities to return." },
326
332
  diarize: { description: "Identify speakers in the transcription." },
327
- contextBias: { description: "Vocabulary and context to guide transcription." }
333
+ contextBias: { description: "Vocabulary and context to guide transcription." },
334
+ targetStreamingDelayMs: { description: "Target transcription delay in milliseconds. Realtime only." },
335
+ speakerReferences: { description: "Named audio clips for known speakers. Realtime only." },
336
+ turnDetection: { description: "Turn detection settings. Realtime only." }
328
337
  },
329
338
  speech: {
330
339
  refAudio: { description: "Reference audio for voice cloning, overriding voice." },
@@ -366,6 +375,7 @@ const modelsWithLowHighMaxReasoningEffort = /* @__PURE__ */ new Set([
366
375
  "zai-glm-5-3-flash",
367
376
  "zai-glm-latest"
368
377
  ]);
378
+ const modelsWithLowMediumHighReasoningEffort = /* @__PURE__ */ new Set(["mistral-large-4", "mistral-large-4-0"]);
369
379
  const reasoningEffortModelIds = /* @__PURE__ */ new Set([
370
380
  "glm-5-2",
371
381
  "labs-leanstral-1-5",
@@ -398,6 +408,10 @@ function createLanguageModelEntry(modelId, image) {
398
408
  "low",
399
409
  "high",
400
410
  "max"
411
+ ] : modelsWithLowMediumHighReasoningEffort.has(modelId) ? [
412
+ "low",
413
+ "medium",
414
+ "high"
401
415
  ] : ["none", "high"]);
402
416
  const conversationReasoning = reasoningCapabilities(reasoningEffortModelIds.has(modelId) ? ["none", "high"] : []);
403
417
  const chatOnly = { condition: "Only supported on the Chat API." };
@@ -450,6 +464,9 @@ function createTranscriptionModelEntry(modelId, declared) {
450
464
  contextBias: support
451
465
  } },
452
466
  providerOptions: { transcription: declareProviderOptions(mistralProviderOptions.transcription, support, {
467
+ targetStreamingDelayMs: false,
468
+ speakerReferences: false,
469
+ turnDetection: false,
453
470
  returnLanguage: { condition: "Only supported when language is not pinned." },
454
471
  timestampGranularities: languageWithTimestamps ? support : { condition: "Only supported when language is not pinned." }
455
472
  }) }
@@ -1798,7 +1815,8 @@ const mistralTranscriptionModelOptions = lazySchema(() => zodSchema(z.object({
1798
1815
  timestampGranularities: z.array(z.enum(["segment", "word"])).min(1).optional(),
1799
1816
  /**
1800
1817
  * Whether to identify speakers in the transcription.
1801
- * Voxtral 3 requires segment timestamps when diarization is enabled.
1818
+ * Offline Voxtral 3 requires segment timestamps when diarization is enabled.
1819
+ * Realtime diarization cannot be combined with turn detection.
1802
1820
  */
1803
1821
  diarize: z.boolean().optional(),
1804
1822
  /**
@@ -1809,9 +1827,273 @@ const mistralTranscriptionModelOptions = lazySchema(() => zodSchema(z.object({
1809
1827
  * including spaces and punctuation. Entries share the context window
1810
1828
  * with the audio.
1811
1829
  */
1812
- contextBias: z.array(z.string().min(1)).optional()
1830
+ contextBias: z.array(z.string().min(1)).optional(),
1831
+ /** Realtime only. Delay in milliseconds: 80–1200, or 2400. */
1832
+ targetStreamingDelayMs: z.union([z.number().int().min(80).max(1200), z.literal(2400)]).optional(),
1833
+ /**
1834
+ * Realtime only. Named base64-encoded audio clips for known speakers.
1835
+ * Requires diarize. Mistral accepts up to 8 clips of 3–15 seconds each.
1836
+ */
1837
+ speakerReferences: z.record(z.string(), z.string().min(1)).optional(),
1838
+ /**
1839
+ * Realtime only. Enable turn detection with an empty object for defaults.
1840
+ * Turn events are available through includeRawChunks. Mistral validates
1841
+ * threshold ordering and compatibility with diarization.
1842
+ */
1843
+ turnDetection: z.object({
1844
+ startThreshold: z.number().min(0).max(1).optional(),
1845
+ eagerEndThreshold: z.number().min(0).max(1).optional(),
1846
+ endThreshold: z.number().min(0).max(1).optional(),
1847
+ minSilenceMs: z.number().int().nonnegative().optional(),
1848
+ endTimeoutMs: z.number().int().nonnegative().optional()
1849
+ }).optional()
1813
1850
  })));
1814
1851
  //#endregion
1852
+ //#region src/mistral-transcription-stream.ts
1853
+ async function streamMistralTranscription({ modelId, baseURL, headers, webSocket, currentDate, ...options }) {
1854
+ const mistralOptions = await parseProviderOptions({
1855
+ provider: "mistral",
1856
+ providerOptions: options.providerOptions,
1857
+ schema: mistralTranscriptionModelOptions
1858
+ });
1859
+ const { type, rate = 16e3 } = options.inputAudioFormat;
1860
+ if (type !== "audio/pcm" || !Number.isInteger(rate) || rate <= 0) throw new InvalidArgumentError({
1861
+ argument: "inputAudioFormat",
1862
+ message: "Mistral realtime transcription requires audio/pcm (mono, signed 16-bit little-endian) with a positive integer sample rate."
1863
+ });
1864
+ const warnings = [];
1865
+ for (const option of [
1866
+ "returnLanguage",
1867
+ "temperature",
1868
+ "timestampGranularities"
1869
+ ]) if (mistralOptions?.[option] != null) warnings.push({
1870
+ type: "unsupported",
1871
+ feature: `providerOptions.mistral.${option}`,
1872
+ details: "This option is not supported for realtime transcription."
1873
+ });
1874
+ const turnDetection = mistralOptions?.turnDetection;
1875
+ const session = {
1876
+ audio_format: {
1877
+ encoding: "pcm_s16le",
1878
+ sample_rate: rate
1879
+ },
1880
+ target_streaming_delay_ms: mistralOptions?.targetStreamingDelayMs,
1881
+ language: mistralOptions?.language,
1882
+ context_bias: mistralOptions?.contextBias,
1883
+ diarize: mistralOptions?.diarize,
1884
+ speaker_references: mistralOptions?.speakerReferences,
1885
+ turn_detection: turnDetection == null ? void 0 : {
1886
+ start_threshold: turnDetection.startThreshold,
1887
+ eager_end_threshold: turnDetection.eagerEndThreshold,
1888
+ end_threshold: turnDetection.endThreshold,
1889
+ min_silence_ms: turnDetection.minSilenceMs,
1890
+ end_timeout_ms: turnDetection.endTimeoutMs
1891
+ }
1892
+ };
1893
+ const url = toWebSocketUrl(`${baseURL}/audio/transcriptions/realtime`);
1894
+ url.searchParams.set("model", modelId);
1895
+ let finished = false;
1896
+ let cleanup = () => {};
1897
+ return {
1898
+ request: { body: url.toString() },
1899
+ response: {
1900
+ timestamp: currentDate,
1901
+ modelId
1902
+ },
1903
+ stream: new ReadableStream({
1904
+ start(controller) {
1905
+ let connection;
1906
+ let reader;
1907
+ let configured = false;
1908
+ let sending = false;
1909
+ const stop = new AbortController();
1910
+ cleanup = () => {
1911
+ stop.abort();
1912
+ (reader != null ? reader.cancel() : options.audio.cancel()).catch(() => {});
1913
+ connection?.close(1e3);
1914
+ };
1915
+ const fail = (error) => {
1916
+ if (finished) return;
1917
+ finished = true;
1918
+ cleanup();
1919
+ controller.error(error);
1920
+ };
1921
+ const sendAudio = async () => {
1922
+ const socket = connection.socket;
1923
+ reader = options.audio.getReader();
1924
+ try {
1925
+ while (true) {
1926
+ if (finished) break;
1927
+ const { done, value } = await reader.read();
1928
+ if (finished || done) break;
1929
+ const bytes = typeof value === "string" ? convertBase64ToUint8Array(value) : value;
1930
+ for (let offset = 0; offset < bytes.length; offset += 65536) {
1931
+ if (finished) break;
1932
+ socket.send(JSON.stringify({
1933
+ type: "input_audio.append",
1934
+ audio: convertUint8ArrayToBase64(bytes.subarray(offset, offset + 65536))
1935
+ }));
1936
+ await waitForWebSocketBufferDrain(socket, { abortSignal: stop.signal });
1937
+ }
1938
+ }
1939
+ if (!finished) socket.send(JSON.stringify({ type: "input_audio.end" }));
1940
+ } finally {
1941
+ reader.releaseLock();
1942
+ reader = void 0;
1943
+ }
1944
+ };
1945
+ controller.enqueue({
1946
+ type: "stream-start",
1947
+ warnings
1948
+ });
1949
+ connection = connectToWebSocket({
1950
+ url,
1951
+ headers,
1952
+ webSocket,
1953
+ abortSignal: options.abortSignal,
1954
+ onAbort: fail,
1955
+ onProcessingError: fail,
1956
+ onMessageText: async (text) => {
1957
+ if (finished) return;
1958
+ const parsed = await safeParseJSON({
1959
+ text,
1960
+ schema: eventEnvelopeSchema
1961
+ });
1962
+ if (finished) return;
1963
+ if (!parsed.success) throw parsed.error;
1964
+ const raw = parsed.value;
1965
+ if (options.includeRawChunks) controller.enqueue({
1966
+ type: "raw",
1967
+ rawValue: raw
1968
+ });
1969
+ if (!handledEvents.has(raw.type)) return;
1970
+ const validated = await safeValidateTypes({
1971
+ value: raw,
1972
+ schema: transcriptionEventSchema
1973
+ });
1974
+ if (finished) return;
1975
+ if (!validated.success) throw validated.error;
1976
+ const event = validated.value;
1977
+ switch (event.type) {
1978
+ case "session.created":
1979
+ if (configured) break;
1980
+ configured = true;
1981
+ connection.socket.send(JSON.stringify({
1982
+ type: "session.update",
1983
+ session
1984
+ }));
1985
+ break;
1986
+ case "session.updated":
1987
+ if (!configured || sending) break;
1988
+ sending = true;
1989
+ sendAudio().catch(fail);
1990
+ break;
1991
+ case "transcription.text.delta":
1992
+ controller.enqueue({
1993
+ type: "transcript-delta",
1994
+ delta: event.text
1995
+ });
1996
+ break;
1997
+ case "transcription.segment":
1998
+ controller.enqueue({
1999
+ type: "transcript-final",
2000
+ text: event.text,
2001
+ startSecond: event.start ?? void 0,
2002
+ endSecond: event.end ?? void 0,
2003
+ ...event.speaker_id != null && { providerMetadata: { mistral: { speakerId: event.speaker_id } } }
2004
+ });
2005
+ break;
2006
+ case "transcription.done": {
2007
+ const segments = event.segments ?? [];
2008
+ controller.enqueue({
2009
+ type: "response-metadata",
2010
+ modelId: event.model ?? modelId,
2011
+ body: raw
2012
+ });
2013
+ controller.enqueue({
2014
+ type: "finish",
2015
+ text: event.text,
2016
+ segments: segments.flatMap((segment) => segment.start == null || segment.end == null ? [] : [{
2017
+ text: segment.text,
2018
+ startSecond: segment.start,
2019
+ endSecond: segment.end
2020
+ }]),
2021
+ language: event.language ?? void 0,
2022
+ durationInSeconds: typeof event.usage?.prompt_audio_seconds === "number" ? event.usage.prompt_audio_seconds : void 0,
2023
+ usage: event.usage ?? void 0,
2024
+ providerMetadata: { mistral: {
2025
+ ...event.usage != null && { usage: event.usage },
2026
+ segments: segments.map((segment) => ({
2027
+ text: segment.text,
2028
+ ...segment.start != null && { startSecond: segment.start },
2029
+ ...segment.end != null && { endSecond: segment.end },
2030
+ ...segment.speaker_id != null && { speakerId: segment.speaker_id }
2031
+ }))
2032
+ } }
2033
+ });
2034
+ finished = true;
2035
+ controller.close();
2036
+ cleanup();
2037
+ break;
2038
+ }
2039
+ case "error": fail(new Error(event.error.message));
2040
+ }
2041
+ },
2042
+ onSocketError: () => fail(/* @__PURE__ */ new Error("Mistral realtime transcription WebSocket error." + (webSocket == null ? " Pass a header-capable WebSocket implementation (e.g. ws) to createMistral({ webSocket }) to send the Authorization header." : ""))),
2043
+ onClose: ({ code, reason }) => fail(/* @__PURE__ */ new Error(`Mistral realtime transcription connection closed before transcription.done (code: ${code ?? "unknown"}${reason ? `, reason: ${reason}` : ""}).`))
2044
+ });
2045
+ if (finished) connection.close();
2046
+ },
2047
+ cancel() {
2048
+ if (finished) return;
2049
+ finished = true;
2050
+ cleanup();
2051
+ }
2052
+ })
2053
+ };
2054
+ }
2055
+ const handledEvents = /* @__PURE__ */ new Set([
2056
+ "session.created",
2057
+ "session.updated",
2058
+ "transcription.text.delta",
2059
+ "transcription.segment",
2060
+ "transcription.done",
2061
+ "error"
2062
+ ]);
2063
+ const eventEnvelopeSchema = lazySchema(() => zodSchema(z.looseObject({ type: z.string() })));
2064
+ const transcriptionEventSchema = lazySchema(() => {
2065
+ const segment = {
2066
+ text: z.string(),
2067
+ start: z.number().nullish(),
2068
+ end: z.number().nullish(),
2069
+ speaker_id: z.string().nullish()
2070
+ };
2071
+ return zodSchema(z.discriminatedUnion("type", [
2072
+ z.object({ type: z.literal("session.created") }),
2073
+ z.object({ type: z.literal("session.updated") }),
2074
+ z.object({
2075
+ type: z.literal("transcription.text.delta"),
2076
+ text: z.string()
2077
+ }),
2078
+ z.object({
2079
+ type: z.literal("transcription.segment"),
2080
+ ...segment
2081
+ }),
2082
+ z.object({
2083
+ type: z.literal("transcription.done"),
2084
+ text: z.string(),
2085
+ model: z.string().nullish(),
2086
+ language: z.string().nullish(),
2087
+ segments: z.array(z.object(segment)).nullish(),
2088
+ usage: z.record(z.string(), z.json()).nullish()
2089
+ }),
2090
+ z.object({
2091
+ type: z.literal("error"),
2092
+ error: z.object({ message: z.string() })
2093
+ })
2094
+ ]));
2095
+ });
2096
+ //#endregion
1815
2097
  //#region src/mistral-transcription-model.ts
1816
2098
  var MistralTranscriptionModel = class MistralTranscriptionModel {
1817
2099
  static [WORKFLOW_SERIALIZE](model) {
@@ -1838,6 +2120,15 @@ var MistralTranscriptionModel = class MistralTranscriptionModel {
1838
2120
  providerOptions,
1839
2121
  schema: mistralTranscriptionModelOptions
1840
2122
  });
2123
+ for (const option of [
2124
+ "targetStreamingDelayMs",
2125
+ "speakerReferences",
2126
+ "turnDetection"
2127
+ ]) if (mistralOptions?.[option] != null) warnings.push({
2128
+ type: "unsupported",
2129
+ feature: `providerOptions.mistral.${option}`,
2130
+ details: "This option is only supported for realtime transcription."
2131
+ });
1841
2132
  if (!getMistralTranscriptionModelEntry(this.modelId).capabilities.transcription.languageWithTimestamps && mistralOptions?.language != null && mistralOptions.timestampGranularities != null) throw new InvalidArgumentError({
1842
2133
  argument: "providerOptions",
1843
2134
  message: "providerOptions.mistral.language cannot be combined with providerOptions.mistral.timestampGranularities"
@@ -1863,6 +2154,16 @@ var MistralTranscriptionModel = class MistralTranscriptionModel {
1863
2154
  warnings
1864
2155
  };
1865
2156
  }
2157
+ async doStream(options) {
2158
+ return streamMistralTranscription({
2159
+ ...options,
2160
+ modelId: this.modelId,
2161
+ baseURL: this.config.baseURL,
2162
+ headers: combineHeaders(await resolve(this.config.headers), options.headers),
2163
+ webSocket: this.config.webSocket,
2164
+ currentDate: this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date()
2165
+ });
2166
+ }
1866
2167
  async doGenerate(options) {
1867
2168
  const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
1868
2169
  const { formData, warnings } = await this.getArgs(options);
@@ -1944,7 +2245,7 @@ const mistralTranscriptionResponseSchema = lazySchema(() => zodSchema(z.object({
1944
2245
  })));
1945
2246
  //#endregion
1946
2247
  //#region src/version.ts
1947
- const VERSION = "4.0.79";
2248
+ const VERSION = "4.0.81";
1948
2249
  //#endregion
1949
2250
  //#region src/tool/web-search.ts
1950
2251
  const inputSchema = lazySchema(() => zodSchema(z.object({ arguments: z.string() })));
@@ -1970,6 +2271,771 @@ const mistralTools = {
1970
2271
  webSearchPremium
1971
2272
  };
1972
2273
  //#endregion
2274
+ //#region src/realtime/mistral-realtime-model-options.ts
2275
+ const mistralRealtimeModelOptions = lazySchema(() => zodSchema(z.strictObject({
2276
+ /** Speech recognition settings for the managed voice agent. */
2277
+ stt: z.strictObject({
2278
+ model: z.string().min(1).optional(),
2279
+ language: z.string().min(1).optional(),
2280
+ contextBias: z.array(z.string().min(1)).optional(),
2281
+ targetStreamingDelayMs: z.number().int().min(80).max(1200).optional(),
2282
+ turnDetection: z.strictObject({
2283
+ startThreshold: z.number().min(0).max(1).optional(),
2284
+ eagerEndThreshold: z.number().min(0).max(1).optional(),
2285
+ endThreshold: z.number().min(0).max(1).optional(),
2286
+ minSilenceMs: z.number().int().nonnegative().optional(),
2287
+ endTimeoutMs: z.number().int().nonnegative().optional()
2288
+ }).optional()
2289
+ }).optional(),
2290
+ /** Speech synthesis settings. `sessionConfig.voice` overrides voiceId. */
2291
+ tts: z.strictObject({
2292
+ model: z.string().min(1).optional(),
2293
+ voiceId: z.string().min(1).optional(),
2294
+ phonemeHints: z.record(z.string(), z.array(z.string().min(1)).min(1)).optional()
2295
+ }).optional(),
2296
+ /** Interruptions and reminders during periods of silence. */
2297
+ turn: z.strictObject({
2298
+ allowInterruptions: z.boolean().optional(),
2299
+ inactivity: z.strictObject({
2300
+ timeoutMs: z.number().int().nonnegative().optional(),
2301
+ maxReminders: z.number().int().nonnegative().optional(),
2302
+ messages: z.array(z.string()).optional()
2303
+ }).optional()
2304
+ }).optional(),
2305
+ /** Text spoken when the session connects. */
2306
+ welcomeMessage: z.string().optional(),
2307
+ /** Saved agent whose configuration is overridden for this session. */
2308
+ agentId: z.string().min(1).optional(),
2309
+ /** Version of the saved agent. Omit to use its latest version. */
2310
+ agentVersion: z.number().int().nonnegative().optional()
2311
+ })));
2312
+ /** Builds the REST configuration or the subset accepted by session.update. */
2313
+ async function buildMistralRealtimeSessionConfig(config, { modelId, update = false } = {}) {
2314
+ const allowed = /* @__PURE__ */ new Set([
2315
+ "instructions",
2316
+ "tools",
2317
+ "providerOptions",
2318
+ ...!update ? [
2319
+ "voice",
2320
+ "inputAudioTranscription",
2321
+ "outputAudioTranscription",
2322
+ "outputModalities"
2323
+ ] : []
2324
+ ]);
2325
+ for (const [key, value] of Object.entries(config)) if (value !== void 0 && !allowed.has(key)) unsupported(key, update);
2326
+ if (config.inputAudioTranscription?.prompt != null) unsupported("inputAudioTranscription.prompt", update);
2327
+ if (config.outputAudioTranscription != null && Object.values(config.outputAudioTranscription).some((value) => value != null)) unsupported("outputAudioTranscription settings", update);
2328
+ if (config.outputModalities != null && (!config.outputModalities.includes("audio") || config.outputModalities.some((value) => value !== "audio" && value !== "text"))) unsupported("outputModalities without audio", update);
2329
+ const options = await parseProviderOptions({
2330
+ provider: "mistral",
2331
+ providerOptions: config.providerOptions,
2332
+ schema: mistralRealtimeModelOptions
2333
+ });
2334
+ if (update && options != null) {
2335
+ for (const [key, value] of Object.entries(options)) if (value !== void 0 && key !== "turn") unsupported(`providerOptions.mistral.${key}`, true);
2336
+ }
2337
+ if (options?.agentVersion != null && options.agentId == null) throw new InvalidArgumentError({
2338
+ argument: "providerOptions.mistral.agentVersion",
2339
+ message: "Mistral agentVersion requires agentId."
2340
+ });
2341
+ const stt = options?.stt;
2342
+ const turnDetection = stt?.turnDetection;
2343
+ const tts = options?.tts;
2344
+ const turn = options?.turn;
2345
+ const inactivity = turn?.inactivity;
2346
+ return {
2347
+ ...modelId != null && { llm: { model: modelId } },
2348
+ ...config.instructions != null && { instructions: config.instructions },
2349
+ ...config.tools != null && { tools: config.tools.map((tool) => ({
2350
+ type: "function",
2351
+ function: {
2352
+ name: tool.name,
2353
+ ...tool.description != null && { description: tool.description },
2354
+ parameters: tool.parameters
2355
+ }
2356
+ })) },
2357
+ ...(stt != null || config.inputAudioTranscription != null) && { stt: {
2358
+ model: config.inputAudioTranscription?.model ?? stt?.model,
2359
+ language: config.inputAudioTranscription?.language ?? stt?.language,
2360
+ context_bias: stt?.contextBias,
2361
+ target_streaming_delay_ms: stt?.targetStreamingDelayMs,
2362
+ ...turnDetection != null && { turn_detection: {
2363
+ start_threshold: turnDetection.startThreshold,
2364
+ eager_end_threshold: turnDetection.eagerEndThreshold,
2365
+ end_threshold: turnDetection.endThreshold,
2366
+ min_silence_ms: turnDetection.minSilenceMs,
2367
+ end_timeout_ms: turnDetection.endTimeoutMs
2368
+ } }
2369
+ } },
2370
+ ...(tts != null || config.voice != null) && { tts: {
2371
+ model: tts?.model,
2372
+ voice_id: config.voice ?? tts?.voiceId,
2373
+ phoneme_hints: tts?.phonemeHints
2374
+ } },
2375
+ ...turn != null && { turn: {
2376
+ allow_interruptions: turn.allowInterruptions,
2377
+ ...inactivity != null && { inactivity: {
2378
+ timeout_ms: inactivity.timeoutMs,
2379
+ max_reminders: inactivity.maxReminders,
2380
+ messages: inactivity.messages
2381
+ } }
2382
+ } },
2383
+ ...options?.welcomeMessage != null && { welcome_message: options.welcomeMessage },
2384
+ ...options?.agentId != null && { agent_id: options.agentId },
2385
+ ...options?.agentVersion != null && { agent_version: options.agentVersion }
2386
+ };
2387
+ }
2388
+ function unsupported(setting, update) {
2389
+ throw new UnsupportedFunctionalityError({ functionality: `Mistral voice agent ${update ? "live update of" : "setting"} ${setting}` });
2390
+ }
2391
+ //#endregion
2392
+ //#region src/realtime/mistral-realtime-transport.ts
2393
+ const sessionSchema$1 = z.object({
2394
+ id: z.string().min(1),
2395
+ participantToken: z.string().min(1),
2396
+ serverUrl: z.string().min(1)
2397
+ });
2398
+ const transcriptSchema = z.object({
2399
+ type: z.literal("transcription.segment"),
2400
+ id: z.string(),
2401
+ role: z.enum(["user", "assistant"]),
2402
+ content: z.string(),
2403
+ final: z.boolean()
2404
+ });
2405
+ const errorSchema = z.object({
2406
+ type: z.literal("error"),
2407
+ message: z.string(),
2408
+ code: z.string(),
2409
+ fatal: z.boolean()
2410
+ });
2411
+ const functionCallSchema = z.object({
2412
+ name: z.string(),
2413
+ arguments: z.record(z.string(), z.unknown()).optional()
2414
+ });
2415
+ /** Voice transcripts contain replacement text, rather than append-only deltas. */
2416
+ function parseMistralRealtimeEvent(raw) {
2417
+ const type = raw != null && typeof raw === "object" && "type" in raw ? raw.type : void 0;
2418
+ switch (type) {
2419
+ case "transcription.segment": {
2420
+ const segment = transcriptSchema.parse(raw);
2421
+ if (!segment.final) return [];
2422
+ return segment.role === "user" ? [{
2423
+ type: "input-transcription-completed",
2424
+ itemId: segment.id,
2425
+ transcript: segment.content,
2426
+ raw
2427
+ }] : [
2428
+ {
2429
+ type: "response-created",
2430
+ responseId: segment.id,
2431
+ raw
2432
+ },
2433
+ {
2434
+ type: "audio-transcript-delta",
2435
+ responseId: segment.id,
2436
+ itemId: segment.id,
2437
+ delta: segment.content,
2438
+ raw
2439
+ },
2440
+ {
2441
+ type: "audio-transcript-done",
2442
+ responseId: segment.id,
2443
+ itemId: segment.id,
2444
+ transcript: segment.content,
2445
+ raw
2446
+ },
2447
+ {
2448
+ type: "response-done",
2449
+ responseId: segment.id,
2450
+ status: "completed",
2451
+ raw
2452
+ }
2453
+ ];
2454
+ }
2455
+ case "session.updated": return [{
2456
+ type: "session-updated",
2457
+ raw
2458
+ }];
2459
+ case "error": {
2460
+ const error = errorSchema.parse(raw);
2461
+ return [{
2462
+ type: "error",
2463
+ message: error.message,
2464
+ code: error.code,
2465
+ raw
2466
+ }];
2467
+ }
2468
+ default: return [{
2469
+ type: "custom",
2470
+ rawType: typeof type === "string" ? type : "unknown",
2471
+ raw
2472
+ }];
2473
+ }
2474
+ }
2475
+ function asError(error) {
2476
+ return error instanceof Error ? error : new Error(String(error));
2477
+ }
2478
+ async function loadLiveKit() {
2479
+ try {
2480
+ return await import("livekit-client");
2481
+ } catch (cause) {
2482
+ throw Object.assign(/* @__PURE__ */ new Error("Cannot load \"livekit-client\". Install it to use Mistral realtime voice connections."), { cause });
2483
+ }
2484
+ }
2485
+ /** LiveKit stays inside the Mistral provider and is loaded only on connection. */
2486
+ var MistralRealtimeTransport = class {
2487
+ constructor(options) {
2488
+ this.options = options;
2489
+ this.started = false;
2490
+ this.closed = false;
2491
+ this.accepting = true;
2492
+ this.ready = false;
2493
+ this.failed = false;
2494
+ this.reconnecting = false;
2495
+ this.agentDisconnected = false;
2496
+ this.agentCheckQueued = false;
2497
+ this.abort = new AbortController();
2498
+ this.incoming = Promise.resolve();
2499
+ this.deliveries = Promise.resolve();
2500
+ this.pendingEvents = [];
2501
+ this.pendingCount = 0;
2502
+ this.pendingBytes = 0;
2503
+ this.finalizedSegments = /* @__PURE__ */ new Set();
2504
+ this.captureVersion = 0;
2505
+ this.captureOperations = Promise.resolve();
2506
+ this.ownedTracks = /* @__PURE__ */ new Set();
2507
+ this.playbackEnabled = true;
2508
+ this.agentSpeaking = false;
2509
+ this.remoteAudio = /* @__PURE__ */ new Map();
2510
+ this.pendingTools = /* @__PURE__ */ new Map();
2511
+ }
2512
+ async connect({ api, sessionConfig, stream, capture = true, abortSignal }) {
2513
+ if (this.started || this.closed) throw new Error("Create a new Mistral transport for each connection.");
2514
+ this.started = true;
2515
+ this.api = api;
2516
+ const onAbort = () => this.dispose();
2517
+ abortSignal.addEventListener("abort", onAbort, { once: true });
2518
+ this.removeAbortListener = () => abortSignal.removeEventListener("abort", onAbort);
2519
+ if (abortSignal.aborted) {
2520
+ this.dispose();
2521
+ throw new Error("Mistral voice connection cancelled.");
2522
+ }
2523
+ this.setup = this.open({
2524
+ sessionConfig,
2525
+ stream,
2526
+ capture
2527
+ });
2528
+ try {
2529
+ await this.setup;
2530
+ } catch (error) {
2531
+ await this.close().catch((cleanupError) => this.options.onError(asError(cleanupError)));
2532
+ throw error;
2533
+ }
2534
+ }
2535
+ async open({ sessionConfig, stream, capture }) {
2536
+ const livekit = await loadLiveKit();
2537
+ this.assertOpen();
2538
+ const timeout = new AbortController();
2539
+ const timer = setTimeout(() => timeout.abort(), 3e4);
2540
+ try {
2541
+ const response = await fetch(this.api, {
2542
+ method: "POST",
2543
+ headers: { "Content-Type": "application/json" },
2544
+ body: JSON.stringify({ sessionConfig }),
2545
+ signal: timeout.signal
2546
+ });
2547
+ if (!response.ok) throw new Error(`Failed to create Mistral voice session: ${response.status}`);
2548
+ const parsed = await safeParseJSON({
2549
+ text: await response.text(),
2550
+ schema: sessionSchema$1
2551
+ });
2552
+ if (!parsed.success) throw parsed.error;
2553
+ this.session = parsed.value;
2554
+ } finally {
2555
+ clearTimeout(timer);
2556
+ }
2557
+ this.assertOpen();
2558
+ const room = new livekit.Room();
2559
+ this.room = room;
2560
+ const agentReady = new Promise((resolve) => {
2561
+ this.resolveAgent = resolve;
2562
+ });
2563
+ const onParticipantConnected = (participant) => {
2564
+ if (participant.isAgent) {
2565
+ this.agentDisconnected = false;
2566
+ this.resolveAgent?.();
2567
+ }
2568
+ };
2569
+ const onParticipantDisconnected = (participant) => {
2570
+ if (participant.isAgent) {
2571
+ this.agentDisconnected = true;
2572
+ this.checkAgentDisconnect();
2573
+ }
2574
+ };
2575
+ const onReconnecting = () => {
2576
+ this.reconnecting = true;
2577
+ };
2578
+ const onReconnected = () => {
2579
+ this.reconnecting = false;
2580
+ this.checkAgentDisconnect();
2581
+ };
2582
+ const onDisconnected = () => {
2583
+ if (!this.closed) this.fail(/* @__PURE__ */ new Error("Mistral voice connection disconnected."));
2584
+ };
2585
+ const onTrackSubscribed = (track, _publication, participant) => {
2586
+ if (this.closed || !participant.isAgent || track.kind !== livekit.Track.Kind.Audio) return;
2587
+ const element = track.attach();
2588
+ this.remoteAudio.set(track, element);
2589
+ if (this.playbackEnabled) element.play().catch((error) => {
2590
+ if (!this.closed) this.options.onError(asError(error));
2591
+ });
2592
+ else element.pause();
2593
+ };
2594
+ const onTrackUnsubscribed = (track) => {
2595
+ this.removeRemoteTrack(track);
2596
+ };
2597
+ const onDataReceived = (payload, participant, _kind, topic) => {
2598
+ if (topic !== "voice_agent.events" || !participant?.isAgent) return;
2599
+ this.receive(payload);
2600
+ };
2601
+ room.on(livekit.RoomEvent.ParticipantConnected, onParticipantConnected);
2602
+ room.on(livekit.RoomEvent.ParticipantDisconnected, onParticipantDisconnected);
2603
+ room.on(livekit.RoomEvent.Disconnected, onDisconnected);
2604
+ room.on(livekit.RoomEvent.Reconnecting, onReconnecting);
2605
+ room.on(livekit.RoomEvent.Reconnected, onReconnected);
2606
+ room.on(livekit.RoomEvent.TrackSubscribed, onTrackSubscribed);
2607
+ room.on(livekit.RoomEvent.TrackUnsubscribed, onTrackUnsubscribed);
2608
+ room.on(livekit.RoomEvent.DataReceived, onDataReceived);
2609
+ this.removeRoomListeners = () => {
2610
+ room.off(livekit.RoomEvent.ParticipantConnected, onParticipantConnected);
2611
+ room.off(livekit.RoomEvent.ParticipantDisconnected, onParticipantDisconnected);
2612
+ room.off(livekit.RoomEvent.Disconnected, onDisconnected);
2613
+ room.off(livekit.RoomEvent.Reconnecting, onReconnecting);
2614
+ room.off(livekit.RoomEvent.Reconnected, onReconnected);
2615
+ room.off(livekit.RoomEvent.TrackSubscribed, onTrackSubscribed);
2616
+ room.off(livekit.RoomEvent.TrackUnsubscribed, onTrackUnsubscribed);
2617
+ room.off(livekit.RoomEvent.DataReceived, onDataReceived);
2618
+ };
2619
+ const connecting = room.connect(this.session.serverUrl, this.session.participantToken);
2620
+ connecting.then(() => {
2621
+ if (this.closed) room.disconnect(false).catch(() => {});
2622
+ }, () => {});
2623
+ await this.untilAborted(connecting);
2624
+ this.assertOpen();
2625
+ room.localParticipant.registerRpcMethod("mistral.function_tool", (data) => this.handleToolCall(data));
2626
+ if (this.findAgent() != null) this.resolveAgent?.();
2627
+ if (capture) await this.untilAborted(this.startCapture(stream));
2628
+ await this.untilAborted(agentReady);
2629
+ this.assertOpen();
2630
+ await this.options.onEvent({
2631
+ type: "session-created",
2632
+ sessionId: this.session.id,
2633
+ raw: {
2634
+ type: "session.created",
2635
+ id: this.session.id
2636
+ }
2637
+ });
2638
+ this.assertOpen();
2639
+ this.ready = true;
2640
+ const events = this.pendingEvents.splice(0);
2641
+ await Promise.all(events.map((event) => this.emit(event)));
2642
+ }
2643
+ sendEvent(event, shouldSend) {
2644
+ this.assertOpen();
2645
+ if (shouldSend?.() === false) return Promise.resolve();
2646
+ switch (event.type) {
2647
+ case "session-update": return this.updateSession(event.config, shouldSend);
2648
+ case "input-audio-mute": return this.stopCapture();
2649
+ case "input-audio-unmute": return this.startCapture();
2650
+ case "conversation-item-create":
2651
+ if (event.item.type === "function-call-output") {
2652
+ const pending = this.pendingTools.get(event.item.callId);
2653
+ if (pending == null) throw new Error("Mistral function call is no longer pending.");
2654
+ this.pendingTools.delete(event.item.callId);
2655
+ clearTimeout(pending.timer);
2656
+ pending.resolve(event.item.output);
2657
+ return Promise.resolve();
2658
+ }
2659
+ break;
2660
+ case "session-close": return this.close();
2661
+ }
2662
+ throw new UnsupportedFunctionalityError({ functionality: `${event.type} in Mistral voice sessions` });
2663
+ }
2664
+ async updateSession(config, shouldSend) {
2665
+ const payload = await buildMistralRealtimeSessionConfig(config, { update: true });
2666
+ this.assertOpen();
2667
+ if (shouldSend?.() === false) return;
2668
+ const agent = this.findAgent();
2669
+ if (agent == null) throw new Error("Mistral voice agent is not connected.");
2670
+ const response = await this.room.localParticipant.performRpc({
2671
+ destinationIdentity: agent.identity,
2672
+ method: "mistral.session_update",
2673
+ payload: JSON.stringify(payload),
2674
+ responseTimeout: 5e3
2675
+ });
2676
+ const parsed = await safeParseJSON({ text: response });
2677
+ if (!parsed.success) throw parsed.error;
2678
+ }
2679
+ async handleToolCall(data) {
2680
+ this.assertOpen();
2681
+ if (data.callerIdentity !== this.findAgent()?.identity) throw new Error("Only the Mistral voice agent may call tools.");
2682
+ const parsed = await safeParseJSON({
2683
+ text: data.payload,
2684
+ schema: functionCallSchema
2685
+ });
2686
+ if (!parsed.success) throw parsed.error;
2687
+ this.assertOpen();
2688
+ const call = parsed.value;
2689
+ if (this.pendingTools.has(data.requestId) || this.pendingTools.size >= 64) throw new Error("Mistral voice has too many pending function calls.");
2690
+ const result = new Promise((resolve, reject) => {
2691
+ const timer = setTimeout(() => {
2692
+ this.pendingTools.delete(data.requestId);
2693
+ reject(/* @__PURE__ */ new Error(`Mistral function ${call.name} timed out.`));
2694
+ }, data.responseTimeout);
2695
+ this.pendingTools.set(data.requestId, {
2696
+ resolve,
2697
+ reject,
2698
+ timer
2699
+ });
2700
+ });
2701
+ result.catch(() => {});
2702
+ await this.emit({
2703
+ type: "function-call-arguments-delta",
2704
+ responseId: data.requestId,
2705
+ itemId: data.requestId,
2706
+ callId: data.requestId,
2707
+ delta: "",
2708
+ raw: call
2709
+ });
2710
+ await this.emit({
2711
+ type: "function-call-arguments-done",
2712
+ responseId: data.requestId,
2713
+ itemId: data.requestId,
2714
+ callId: data.requestId,
2715
+ name: call.name,
2716
+ arguments: JSON.stringify(call.arguments ?? {}),
2717
+ raw: call
2718
+ });
2719
+ return result;
2720
+ }
2721
+ async startCapture(stream) {
2722
+ this.assertOpen();
2723
+ const version = ++this.captureVersion;
2724
+ this.sourceStream = stream ?? this.sourceStream;
2725
+ const source = this.sourceStream;
2726
+ let owned;
2727
+ if (source == null) {
2728
+ const { createLocalAudioTrack } = await loadLiveKit();
2729
+ if (this.closed || version !== this.captureVersion) return;
2730
+ owned = await createLocalAudioTrack({
2731
+ echoCancellation: true,
2732
+ noiseSuppression: true,
2733
+ autoGainControl: true
2734
+ });
2735
+ this.ownedTracks.add(owned);
2736
+ }
2737
+ const track = owned?.mediaStreamTrack ?? source?.getAudioTracks().find((track) => track.readyState === "live");
2738
+ if (this.closed || version !== this.captureVersion) {
2739
+ this.stopOwnedTrack(owned);
2740
+ return;
2741
+ }
2742
+ if (track == null) {
2743
+ this.stopOwnedTrack(owned);
2744
+ throw new Error("Mistral voice requires a live audio track.");
2745
+ }
2746
+ const room = this.room;
2747
+ if (room == null) {
2748
+ this.stopOwnedTrack(owned);
2749
+ throw new Error("Mistral voice is not connected.");
2750
+ }
2751
+ const operation = this.captureOperations.then(async () => {
2752
+ try {
2753
+ await this.releaseMicrophone();
2754
+ const { Track } = await loadLiveKit();
2755
+ if (this.closed || version !== this.captureVersion) {
2756
+ this.stopOwnedTrack(owned);
2757
+ return;
2758
+ }
2759
+ await room.localParticipant.publishTrack(track, { source: Track.Source.Microphone });
2760
+ if (this.closed || version !== this.captureVersion) {
2761
+ await room.localParticipant.unpublishTrack(track, false);
2762
+ this.stopOwnedTrack(owned);
2763
+ return;
2764
+ }
2765
+ const onEnded = () => {
2766
+ if (this.microphone?.track === track) this.options.onCapturing(false);
2767
+ };
2768
+ track.addEventListener("ended", onEnded);
2769
+ this.microphone = {
2770
+ track,
2771
+ owned,
2772
+ removeListener: () => track.removeEventListener("ended", onEnded)
2773
+ };
2774
+ this.options.onCapturing(track.enabled && !track.muted);
2775
+ } catch (error) {
2776
+ this.stopOwnedTrack(owned);
2777
+ throw error;
2778
+ }
2779
+ });
2780
+ this.captureOperations = operation.catch(() => {});
2781
+ return operation;
2782
+ }
2783
+ stopCapture() {
2784
+ ++this.captureVersion;
2785
+ const operation = this.captureOperations.then(() => this.releaseMicrophone());
2786
+ this.captureOperations = operation.catch(() => {});
2787
+ return operation;
2788
+ }
2789
+ async releaseMicrophone() {
2790
+ const microphone = this.microphone;
2791
+ this.microphone = void 0;
2792
+ if (microphone != null) {
2793
+ microphone.removeListener();
2794
+ try {
2795
+ await this.room?.localParticipant.unpublishTrack(microphone.track, false);
2796
+ } finally {
2797
+ this.stopOwnedTrack(microphone.owned);
2798
+ this.options.onCapturing(false);
2799
+ }
2800
+ } else this.options.onCapturing(false);
2801
+ }
2802
+ stopOwnedTrack(track) {
2803
+ if (track != null && this.ownedTracks.delete(track)) track.stop();
2804
+ }
2805
+ stopPlayback() {
2806
+ this.playbackEnabled = false;
2807
+ for (const element of this.remoteAudio.values()) element.pause();
2808
+ this.options.onPlaying(false);
2809
+ }
2810
+ async resumePlayback() {
2811
+ this.assertOpen();
2812
+ this.playbackEnabled = true;
2813
+ await this.room?.startAudio();
2814
+ await Promise.all([...this.remoteAudio.values()].map((element) => element.play()));
2815
+ if (!this.closed) this.options.onPlaying(this.agentSpeaking);
2816
+ }
2817
+ receive(payload) {
2818
+ if (!this.accepting || this.closed) return;
2819
+ if (this.pendingCount >= 512 || this.pendingBytes + payload.byteLength > 8388608) {
2820
+ this.fail(/* @__PURE__ */ new Error("Mistral voice event queue exceeded its limit."));
2821
+ return;
2822
+ }
2823
+ ++this.pendingCount;
2824
+ this.pendingBytes += payload.byteLength;
2825
+ this.incoming = this.incoming.then(async () => {
2826
+ if (this.closed) return;
2827
+ const parsed = await safeParseJSON({ text: new TextDecoder().decode(payload) });
2828
+ if (!parsed.success) throw parsed.error;
2829
+ const raw = parsed.value;
2830
+ const transcript = transcriptSchema.safeParse(raw);
2831
+ if (transcript.success && transcript.data.final) {
2832
+ if (this.finalizedSegments.has(transcript.data.id)) return;
2833
+ this.finalizedSegments.add(transcript.data.id);
2834
+ if (this.finalizedSegments.size > 500) this.finalizedSegments.delete(this.finalizedSegments.values().next().value);
2835
+ }
2836
+ const state = z.object({
2837
+ type: z.literal("agent.state.changed"),
2838
+ state: z.string()
2839
+ }).safeParse(raw);
2840
+ if (state.success) {
2841
+ this.agentSpeaking = state.data.state === "speaking";
2842
+ this.options.onPlaying(this.playbackEnabled && this.agentSpeaking);
2843
+ }
2844
+ for (const event of parseMistralRealtimeEvent(raw)) await this.emit(event);
2845
+ const error = errorSchema.safeParse(raw);
2846
+ if (error.success && error.data.fatal) this.fail(new Error(error.data.message));
2847
+ }).catch((error) => this.fail(asError(error))).finally(() => {
2848
+ --this.pendingCount;
2849
+ this.pendingBytes -= payload.byteLength;
2850
+ });
2851
+ }
2852
+ async emit(event) {
2853
+ if (this.closed) return;
2854
+ if (!this.ready) {
2855
+ if (this.pendingEvents.length >= 512) throw new Error("Mistral voice startup event queue is full.");
2856
+ this.pendingEvents.push(event);
2857
+ return;
2858
+ }
2859
+ const delivery = this.deliveries.then(async () => {
2860
+ if (this.closed) return;
2861
+ try {
2862
+ await this.options.onEvent(event);
2863
+ } catch (error) {
2864
+ this.options.onError(asError(error));
2865
+ }
2866
+ });
2867
+ this.deliveries = delivery.catch(() => {});
2868
+ return delivery;
2869
+ }
2870
+ findAgent() {
2871
+ return [...this.room?.remoteParticipants.values() ?? []].find((participant) => participant.isAgent);
2872
+ }
2873
+ checkAgentDisconnect() {
2874
+ if (!this.agentDisconnected || this.agentCheckQueued) return;
2875
+ this.agentCheckQueued = true;
2876
+ queueMicrotask(() => {
2877
+ this.agentCheckQueued = false;
2878
+ if (this.closed || this.reconnecting) return;
2879
+ if (this.findAgent() != null) this.agentDisconnected = false;
2880
+ else this.fail(/* @__PURE__ */ new Error("Mistral voice agent disconnected."));
2881
+ });
2882
+ }
2883
+ assertOpen() {
2884
+ if (this.closed || this.abort.signal.aborted) throw new Error("Mistral voice connection is closed.");
2885
+ }
2886
+ untilAborted(operation) {
2887
+ if (this.abort.signal.aborted) return Promise.reject(/* @__PURE__ */ new Error("Mistral voice connection cancelled."));
2888
+ return new Promise((resolve, reject) => {
2889
+ const onAbort = () => reject(/* @__PURE__ */ new Error("Mistral voice connection cancelled."));
2890
+ this.abort.signal.addEventListener("abort", onAbort, { once: true });
2891
+ operation.then(resolve, reject).finally(() => {
2892
+ this.abort.signal.removeEventListener("abort", onAbort);
2893
+ });
2894
+ });
2895
+ }
2896
+ fail(error) {
2897
+ if (this.closed || this.failed) return;
2898
+ this.failed = true;
2899
+ this.accepting = false;
2900
+ this.options.onFatalError(error);
2901
+ this.dispose();
2902
+ }
2903
+ async finish() {
2904
+ this.accepting = false;
2905
+ await this.incoming;
2906
+ await this.deliveries;
2907
+ }
2908
+ removeRemoteTrack(track) {
2909
+ const element = this.remoteAudio.get(track);
2910
+ if (element == null) return;
2911
+ this.remoteAudio.delete(track);
2912
+ element.pause();
2913
+ element.srcObject = null;
2914
+ track.detach(element);
2915
+ element.remove();
2916
+ }
2917
+ close() {
2918
+ if (this.cleanup != null) return this.cleanup;
2919
+ let disconnected;
2920
+ this.cleanup = Promise.resolve().then(async () => {
2921
+ try {
2922
+ await disconnected;
2923
+ } finally {
2924
+ await this.setup?.catch(() => {});
2925
+ if (this.session != null && this.api != null) {
2926
+ const separator = this.api.includes("?") ? "&" : "?";
2927
+ const response = await fetch(`${this.api}${separator}sessionId=${encodeURIComponent(this.session.id)}`, {
2928
+ method: "DELETE",
2929
+ keepalive: true
2930
+ });
2931
+ if (!response.ok) throw new Error(`Failed to close Mistral voice session: ${response.status}`);
2932
+ }
2933
+ }
2934
+ });
2935
+ this.closed = true;
2936
+ this.accepting = false;
2937
+ ++this.captureVersion;
2938
+ this.abort.abort();
2939
+ this.removeAbortListener?.();
2940
+ this.removeRoomListeners?.();
2941
+ this.pendingEvents = [];
2942
+ for (const pending of this.pendingTools.values()) {
2943
+ clearTimeout(pending.timer);
2944
+ pending.reject(/* @__PURE__ */ new Error("Mistral voice session closed."));
2945
+ }
2946
+ this.pendingTools.clear();
2947
+ for (const track of this.remoteAudio.keys()) this.removeRemoteTrack(track);
2948
+ for (const track of this.ownedTracks) this.stopOwnedTrack(track);
2949
+ this.microphone?.removeListener();
2950
+ this.microphone = void 0;
2951
+ this.options.onCapturing(false);
2952
+ this.options.onPlaying(false);
2953
+ disconnected = this.room?.disconnect(false);
2954
+ return this.cleanup;
2955
+ }
2956
+ dispose() {
2957
+ this.close().catch((error) => this.options.onError(asError(error)));
2958
+ }
2959
+ };
2960
+ //#endregion
2961
+ //#region src/realtime/mistral-realtime-model.ts
2962
+ /** A managed Mistral voice agent with provider-owned LiveKit transport. */
2963
+ var MistralRealtimeModel = class {
2964
+ constructor(modelId) {
2965
+ this.modelId = modelId;
2966
+ this.specificationVersion = "v4";
2967
+ this.provider = "mistral.realtime";
2968
+ this.capabilities = {
2969
+ conversation: "turn-based",
2970
+ transports: ["webrtc"],
2971
+ connections: ["provider"],
2972
+ startup: "session-update",
2973
+ finalization: "transport-close"
2974
+ };
2975
+ }
2976
+ createTransport(options) {
2977
+ return new MistralRealtimeTransport(options);
2978
+ }
2979
+ parseServerEvent(raw) {
2980
+ return parseMistralRealtimeEvent(raw);
2981
+ }
2982
+ serializeClientEvent(event) {
2983
+ throw new UnsupportedFunctionalityError({ functionality: `Mistral voice agent ${event.type} outside its provider transport` });
2984
+ }
2985
+ buildSessionConfig(config) {
2986
+ return buildMistralRealtimeSessionConfig(config, { modelId: this.modelId });
2987
+ }
2988
+ };
2989
+ //#endregion
2990
+ //#region src/realtime/mistral-realtime-factory.ts
2991
+ function createMistralRealtimeFactory(config) {
2992
+ return Object.assign((modelId) => new MistralRealtimeModel(modelId), {
2993
+ async createSession({ model, sessionConfig = {}, abortSignal }) {
2994
+ if (model.trim().length === 0) throw new InvalidArgumentError({
2995
+ argument: "model",
2996
+ message: "Mistral voice sessions require a model ID."
2997
+ });
2998
+ const body = await buildMistralRealtimeSessionConfig(sessionConfig, { modelId: model });
2999
+ const { value } = await postJsonToApi({
3000
+ url: `${config.baseURL}/audio/sessions`,
3001
+ headers: await resolve(config.headers),
3002
+ body,
3003
+ failedResponseHandler: mistralFailedResponseHandler,
3004
+ successfulResponseHandler: createJsonResponseHandler(sessionSchema),
3005
+ abortSignal,
3006
+ fetch: config.fetch
3007
+ });
3008
+ return {
3009
+ id: value.id,
3010
+ participantToken: value.participant_token,
3011
+ serverUrl: value.server_url
3012
+ };
3013
+ },
3014
+ async closeSession({ sessionId, abortSignal }) {
3015
+ if (sessionId.trim().length === 0 || sessionId === "." || sessionId === "..") throw new InvalidArgumentError({
3016
+ argument: "sessionId",
3017
+ message: "Mistral voice sessions require a valid session ID."
3018
+ });
3019
+ await deleteFromApi({
3020
+ url: `${config.baseURL}/audio/sessions/${encodeURIComponent(sessionId)}`,
3021
+ headers: await resolve(config.headers),
3022
+ failedResponseHandler: mistralFailedResponseHandler,
3023
+ successfulResponseHandler: async ({ response }) => {
3024
+ await response.body?.cancel();
3025
+ return { value: void 0 };
3026
+ },
3027
+ abortSignal,
3028
+ fetch: config.fetch
3029
+ });
3030
+ }
3031
+ });
3032
+ }
3033
+ const sessionSchema = lazySchema(() => zodSchema(z.object({
3034
+ id: z.string().min(1),
3035
+ participant_token: z.string().min(1),
3036
+ server_url: z.string().min(1)
3037
+ })));
3038
+ //#endregion
1973
3039
  //#region src/mistral-provider.ts
1974
3040
  /**
1975
3041
  * Create a Mistral AI provider instance.
@@ -2014,7 +3080,8 @@ function createMistral(options = {}) {
2014
3080
  provider: "mistral.transcription",
2015
3081
  baseURL,
2016
3082
  headers: getHeaders,
2017
- fetch: options.fetch
3083
+ fetch: options.fetch,
3084
+ webSocket: options.webSocket
2018
3085
  });
2019
3086
  const provider = function(modelId) {
2020
3087
  if (new.target) throw new Error("The Mistral model function cannot be called with the new keyword.");
@@ -2025,6 +3092,11 @@ function createMistral(options = {}) {
2025
3092
  provider.chat = createChatModel;
2026
3093
  provider.conversation = createConversationModel;
2027
3094
  provider.tools = mistralTools;
3095
+ provider.experimental_realtime = createMistralRealtimeFactory({
3096
+ baseURL,
3097
+ headers: getHeaders,
3098
+ fetch: options.fetch
3099
+ });
2028
3100
  provider.embedding = createEmbeddingModel;
2029
3101
  provider.embeddingModel = createEmbeddingModel;
2030
3102
  provider.textEmbedding = createEmbeddingModel;