@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/CHANGELOG.md +38 -0
- package/dist/index.d.ts +158 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1080 -8
- package/dist/index.js.map +1 -1
- package/docs/20-mistral.mdx +258 -8
- package/package.json +10 -3
- package/src/index.ts +5 -0
- package/src/mistral-chat-language-model-options.ts +5 -1
- package/src/mistral-model-catalog.ts +22 -1
- package/src/mistral-prepare-tools.ts +5 -7
- package/src/mistral-provider.ts +19 -0
- package/src/mistral-transcription-model-options.ts +30 -1
- package/src/mistral-transcription-model.ts +33 -0
- package/src/mistral-transcription-stream.ts +339 -0
- package/src/realtime/mistral-realtime-factory.ts +121 -0
- package/src/realtime/mistral-realtime-model-options.ts +199 -0
- package/src/realtime/mistral-realtime-model.ts +46 -0
- package/src/realtime/mistral-realtime-transport.ts +735 -0
|
@@ -0,0 +1,735 @@
|
|
|
1
|
+
import {
|
|
2
|
+
UnsupportedFunctionalityError,
|
|
3
|
+
type Experimental_RealtimeModelV4ClientEvent as ClientEvent,
|
|
4
|
+
type Experimental_RealtimeModelV4ServerEvent as ServerEvent,
|
|
5
|
+
type Experimental_RealtimeModelV4Transport as RealtimeTransport,
|
|
6
|
+
type Experimental_RealtimeModelV4TransportOptions as TransportOptions,
|
|
7
|
+
} from '@ai-sdk/provider';
|
|
8
|
+
import { safeParseJSON } from '@ai-sdk/provider-utils';
|
|
9
|
+
import type {
|
|
10
|
+
LocalAudioTrack,
|
|
11
|
+
RemoteParticipant,
|
|
12
|
+
RemoteTrack,
|
|
13
|
+
Room,
|
|
14
|
+
RpcInvocationData,
|
|
15
|
+
} from 'livekit-client';
|
|
16
|
+
import { z } from 'zod/v4';
|
|
17
|
+
import { buildMistralRealtimeSessionConfig } from './mistral-realtime-model-options';
|
|
18
|
+
|
|
19
|
+
const sessionSchema = z.object({
|
|
20
|
+
id: z.string().min(1),
|
|
21
|
+
participantToken: z.string().min(1),
|
|
22
|
+
serverUrl: z.string().min(1),
|
|
23
|
+
});
|
|
24
|
+
const transcriptSchema = z.object({
|
|
25
|
+
type: z.literal('transcription.segment'),
|
|
26
|
+
id: z.string(),
|
|
27
|
+
role: z.enum(['user', 'assistant']),
|
|
28
|
+
content: z.string(),
|
|
29
|
+
final: z.boolean(),
|
|
30
|
+
});
|
|
31
|
+
const errorSchema = z.object({
|
|
32
|
+
type: z.literal('error'),
|
|
33
|
+
message: z.string(),
|
|
34
|
+
code: z.string(),
|
|
35
|
+
fatal: z.boolean(),
|
|
36
|
+
});
|
|
37
|
+
const functionCallSchema = z.object({
|
|
38
|
+
name: z.string(),
|
|
39
|
+
arguments: z.record(z.string(), z.unknown()).optional(),
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
/** Voice transcripts contain replacement text, rather than append-only deltas. */
|
|
43
|
+
export function parseMistralRealtimeEvent(raw: unknown): ServerEvent[] {
|
|
44
|
+
const type =
|
|
45
|
+
raw != null && typeof raw === 'object' && 'type' in raw
|
|
46
|
+
? raw.type
|
|
47
|
+
: undefined;
|
|
48
|
+
switch (type) {
|
|
49
|
+
case 'transcription.segment': {
|
|
50
|
+
const segment = transcriptSchema.parse(raw);
|
|
51
|
+
if (!segment.final) return [];
|
|
52
|
+
return segment.role === 'user'
|
|
53
|
+
? [
|
|
54
|
+
{
|
|
55
|
+
type: 'input-transcription-completed',
|
|
56
|
+
itemId: segment.id,
|
|
57
|
+
transcript: segment.content,
|
|
58
|
+
raw,
|
|
59
|
+
},
|
|
60
|
+
]
|
|
61
|
+
: [
|
|
62
|
+
{ type: 'response-created', responseId: segment.id, raw },
|
|
63
|
+
{
|
|
64
|
+
type: 'audio-transcript-delta',
|
|
65
|
+
responseId: segment.id,
|
|
66
|
+
itemId: segment.id,
|
|
67
|
+
delta: segment.content,
|
|
68
|
+
raw,
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
type: 'audio-transcript-done',
|
|
72
|
+
responseId: segment.id,
|
|
73
|
+
itemId: segment.id,
|
|
74
|
+
transcript: segment.content,
|
|
75
|
+
raw,
|
|
76
|
+
},
|
|
77
|
+
{
|
|
78
|
+
type: 'response-done',
|
|
79
|
+
responseId: segment.id,
|
|
80
|
+
status: 'completed',
|
|
81
|
+
raw,
|
|
82
|
+
},
|
|
83
|
+
];
|
|
84
|
+
}
|
|
85
|
+
case 'session.updated':
|
|
86
|
+
return [{ type: 'session-updated', raw }];
|
|
87
|
+
case 'error': {
|
|
88
|
+
const error = errorSchema.parse(raw);
|
|
89
|
+
return [{ type: 'error', message: error.message, code: error.code, raw }];
|
|
90
|
+
}
|
|
91
|
+
default:
|
|
92
|
+
return [
|
|
93
|
+
{
|
|
94
|
+
type: 'custom',
|
|
95
|
+
rawType: typeof type === 'string' ? type : 'unknown',
|
|
96
|
+
raw,
|
|
97
|
+
},
|
|
98
|
+
];
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function asError(error: unknown): Error {
|
|
103
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function loadLiveKit() {
|
|
107
|
+
try {
|
|
108
|
+
// Catch the import directly so bundlers treat the peer as optional.
|
|
109
|
+
return await import('livekit-client');
|
|
110
|
+
} catch (cause) {
|
|
111
|
+
throw Object.assign(
|
|
112
|
+
new Error(
|
|
113
|
+
'Cannot load "livekit-client". Install it to use Mistral realtime voice connections.',
|
|
114
|
+
),
|
|
115
|
+
{ cause },
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** LiveKit stays inside the Mistral provider and is loaded only on connection. */
|
|
121
|
+
export class MistralRealtimeTransport implements RealtimeTransport {
|
|
122
|
+
private room?: Room;
|
|
123
|
+
private session?: z.infer<typeof sessionSchema>;
|
|
124
|
+
private api?: string;
|
|
125
|
+
private started = false;
|
|
126
|
+
private closed = false;
|
|
127
|
+
private accepting = true;
|
|
128
|
+
private ready = false;
|
|
129
|
+
private failed = false;
|
|
130
|
+
private reconnecting = false;
|
|
131
|
+
private agentDisconnected = false;
|
|
132
|
+
private agentCheckQueued = false;
|
|
133
|
+
private abort = new AbortController();
|
|
134
|
+
private setup?: Promise<void>;
|
|
135
|
+
private cleanup?: Promise<void>;
|
|
136
|
+
private removeAbortListener?: () => void;
|
|
137
|
+
private removeRoomListeners?: () => void;
|
|
138
|
+
private resolveAgent?: () => void;
|
|
139
|
+
private incoming = Promise.resolve();
|
|
140
|
+
private deliveries = Promise.resolve();
|
|
141
|
+
private pendingEvents: ServerEvent[] = [];
|
|
142
|
+
private pendingCount = 0;
|
|
143
|
+
private pendingBytes = 0;
|
|
144
|
+
private finalizedSegments = new Set<string>();
|
|
145
|
+
private captureVersion = 0;
|
|
146
|
+
private captureOperations = Promise.resolve();
|
|
147
|
+
private sourceStream?: MediaStream;
|
|
148
|
+
private ownedTracks = new Set<LocalAudioTrack>();
|
|
149
|
+
private microphone?: {
|
|
150
|
+
track: MediaStreamTrack;
|
|
151
|
+
owned?: LocalAudioTrack;
|
|
152
|
+
removeListener: () => void;
|
|
153
|
+
};
|
|
154
|
+
private playbackEnabled = true;
|
|
155
|
+
private agentSpeaking = false;
|
|
156
|
+
private remoteAudio = new Map<RemoteTrack, HTMLMediaElement>();
|
|
157
|
+
private pendingTools = new Map<
|
|
158
|
+
string,
|
|
159
|
+
{
|
|
160
|
+
resolve: (result: string) => void;
|
|
161
|
+
reject: (error: Error) => void;
|
|
162
|
+
timer: ReturnType<typeof setTimeout>;
|
|
163
|
+
}
|
|
164
|
+
>();
|
|
165
|
+
|
|
166
|
+
constructor(private readonly options: TransportOptions) {}
|
|
167
|
+
|
|
168
|
+
async connect({
|
|
169
|
+
api,
|
|
170
|
+
sessionConfig,
|
|
171
|
+
stream,
|
|
172
|
+
capture = true,
|
|
173
|
+
abortSignal,
|
|
174
|
+
}: Parameters<RealtimeTransport['connect']>[0]): Promise<void> {
|
|
175
|
+
if (this.started || this.closed)
|
|
176
|
+
throw new Error('Create a new Mistral transport for each connection.');
|
|
177
|
+
this.started = true;
|
|
178
|
+
this.api = api;
|
|
179
|
+
const onAbort = () => this.dispose();
|
|
180
|
+
abortSignal.addEventListener('abort', onAbort, { once: true });
|
|
181
|
+
this.removeAbortListener = () =>
|
|
182
|
+
abortSignal.removeEventListener('abort', onAbort);
|
|
183
|
+
if (abortSignal.aborted) {
|
|
184
|
+
this.dispose();
|
|
185
|
+
throw new Error('Mistral voice connection cancelled.');
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
this.setup = this.open({ sessionConfig, stream, capture });
|
|
189
|
+
try {
|
|
190
|
+
await this.setup;
|
|
191
|
+
} catch (error) {
|
|
192
|
+
await this.close().catch(cleanupError =>
|
|
193
|
+
this.options.onError(asError(cleanupError)),
|
|
194
|
+
);
|
|
195
|
+
throw error;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
private async open({
|
|
200
|
+
sessionConfig,
|
|
201
|
+
stream,
|
|
202
|
+
capture,
|
|
203
|
+
}: Pick<
|
|
204
|
+
Parameters<RealtimeTransport['connect']>[0],
|
|
205
|
+
'sessionConfig' | 'stream' | 'capture'
|
|
206
|
+
>): Promise<void> {
|
|
207
|
+
const livekit = await loadLiveKit();
|
|
208
|
+
this.assertOpen();
|
|
209
|
+
// Let an in-flight create request finish on cancellation, so its returned
|
|
210
|
+
// session can still be deleted. A bounded timeout covers an unresponsive app.
|
|
211
|
+
const timeout = new AbortController();
|
|
212
|
+
const timer = setTimeout(() => timeout.abort(), 30_000);
|
|
213
|
+
try {
|
|
214
|
+
const response = await fetch(this.api!, {
|
|
215
|
+
method: 'POST',
|
|
216
|
+
headers: { 'Content-Type': 'application/json' },
|
|
217
|
+
body: JSON.stringify({ sessionConfig }),
|
|
218
|
+
signal: timeout.signal,
|
|
219
|
+
});
|
|
220
|
+
if (!response.ok)
|
|
221
|
+
throw new Error(
|
|
222
|
+
`Failed to create Mistral voice session: ${response.status}`,
|
|
223
|
+
);
|
|
224
|
+
const parsed = await safeParseJSON({
|
|
225
|
+
text: await response.text(),
|
|
226
|
+
schema: sessionSchema,
|
|
227
|
+
});
|
|
228
|
+
if (!parsed.success) throw parsed.error;
|
|
229
|
+
this.session = parsed.value;
|
|
230
|
+
} finally {
|
|
231
|
+
clearTimeout(timer);
|
|
232
|
+
}
|
|
233
|
+
this.assertOpen();
|
|
234
|
+
|
|
235
|
+
const room = new livekit.Room();
|
|
236
|
+
this.room = room;
|
|
237
|
+
const agentReady = new Promise<void>(resolve => {
|
|
238
|
+
this.resolveAgent = resolve;
|
|
239
|
+
});
|
|
240
|
+
const onParticipantConnected = (participant: RemoteParticipant) => {
|
|
241
|
+
if (participant.isAgent) {
|
|
242
|
+
this.agentDisconnected = false;
|
|
243
|
+
this.resolveAgent?.();
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
const onParticipantDisconnected = (participant: RemoteParticipant) => {
|
|
247
|
+
if (participant.isAgent) {
|
|
248
|
+
this.agentDisconnected = true;
|
|
249
|
+
this.checkAgentDisconnect();
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
const onReconnecting = () => {
|
|
253
|
+
this.reconnecting = true;
|
|
254
|
+
};
|
|
255
|
+
const onReconnected = () => {
|
|
256
|
+
this.reconnecting = false;
|
|
257
|
+
this.checkAgentDisconnect();
|
|
258
|
+
};
|
|
259
|
+
const onDisconnected = () => {
|
|
260
|
+
if (!this.closed)
|
|
261
|
+
this.fail(new Error('Mistral voice connection disconnected.'));
|
|
262
|
+
};
|
|
263
|
+
const onTrackSubscribed = (
|
|
264
|
+
track: RemoteTrack,
|
|
265
|
+
_publication: unknown,
|
|
266
|
+
participant: RemoteParticipant,
|
|
267
|
+
) => {
|
|
268
|
+
if (
|
|
269
|
+
this.closed ||
|
|
270
|
+
!participant.isAgent ||
|
|
271
|
+
track.kind !== livekit.Track.Kind.Audio
|
|
272
|
+
)
|
|
273
|
+
return;
|
|
274
|
+
const element = track.attach();
|
|
275
|
+
this.remoteAudio.set(track, element);
|
|
276
|
+
if (this.playbackEnabled) {
|
|
277
|
+
void element.play().catch(error => {
|
|
278
|
+
if (!this.closed) this.options.onError(asError(error));
|
|
279
|
+
});
|
|
280
|
+
} else element.pause();
|
|
281
|
+
};
|
|
282
|
+
const onTrackUnsubscribed = (track: RemoteTrack) => {
|
|
283
|
+
this.removeRemoteTrack(track);
|
|
284
|
+
};
|
|
285
|
+
const onDataReceived = (
|
|
286
|
+
payload: Uint8Array,
|
|
287
|
+
participant?: RemoteParticipant,
|
|
288
|
+
_kind?: unknown,
|
|
289
|
+
topic?: string,
|
|
290
|
+
) => {
|
|
291
|
+
if (topic !== 'voice_agent.events' || !participant?.isAgent) return;
|
|
292
|
+
this.receive(payload);
|
|
293
|
+
};
|
|
294
|
+
room.on(livekit.RoomEvent.ParticipantConnected, onParticipantConnected);
|
|
295
|
+
room.on(
|
|
296
|
+
livekit.RoomEvent.ParticipantDisconnected,
|
|
297
|
+
onParticipantDisconnected,
|
|
298
|
+
);
|
|
299
|
+
room.on(livekit.RoomEvent.Disconnected, onDisconnected);
|
|
300
|
+
room.on(livekit.RoomEvent.Reconnecting, onReconnecting);
|
|
301
|
+
room.on(livekit.RoomEvent.Reconnected, onReconnected);
|
|
302
|
+
room.on(livekit.RoomEvent.TrackSubscribed, onTrackSubscribed);
|
|
303
|
+
room.on(livekit.RoomEvent.TrackUnsubscribed, onTrackUnsubscribed);
|
|
304
|
+
room.on(livekit.RoomEvent.DataReceived, onDataReceived);
|
|
305
|
+
this.removeRoomListeners = () => {
|
|
306
|
+
room.off(livekit.RoomEvent.ParticipantConnected, onParticipantConnected);
|
|
307
|
+
room.off(
|
|
308
|
+
livekit.RoomEvent.ParticipantDisconnected,
|
|
309
|
+
onParticipantDisconnected,
|
|
310
|
+
);
|
|
311
|
+
room.off(livekit.RoomEvent.Disconnected, onDisconnected);
|
|
312
|
+
room.off(livekit.RoomEvent.Reconnecting, onReconnecting);
|
|
313
|
+
room.off(livekit.RoomEvent.Reconnected, onReconnected);
|
|
314
|
+
room.off(livekit.RoomEvent.TrackSubscribed, onTrackSubscribed);
|
|
315
|
+
room.off(livekit.RoomEvent.TrackUnsubscribed, onTrackUnsubscribed);
|
|
316
|
+
room.off(livekit.RoomEvent.DataReceived, onDataReceived);
|
|
317
|
+
};
|
|
318
|
+
const connecting = room.connect(
|
|
319
|
+
this.session.serverUrl,
|
|
320
|
+
this.session.participantToken,
|
|
321
|
+
);
|
|
322
|
+
void connecting.then(
|
|
323
|
+
() => {
|
|
324
|
+
if (this.closed) void room.disconnect(false).catch(() => {});
|
|
325
|
+
},
|
|
326
|
+
() => {},
|
|
327
|
+
);
|
|
328
|
+
await this.untilAborted(connecting);
|
|
329
|
+
this.assertOpen();
|
|
330
|
+
room.localParticipant.registerRpcMethod(
|
|
331
|
+
'mistral.function_tool',
|
|
332
|
+
(data: RpcInvocationData) => this.handleToolCall(data),
|
|
333
|
+
);
|
|
334
|
+
if (this.findAgent() != null) this.resolveAgent?.();
|
|
335
|
+
if (capture) await this.untilAborted(this.startCapture(stream));
|
|
336
|
+
await this.untilAborted(agentReady);
|
|
337
|
+
this.assertOpen();
|
|
338
|
+
await this.options.onEvent({
|
|
339
|
+
type: 'session-created',
|
|
340
|
+
sessionId: this.session.id,
|
|
341
|
+
raw: { type: 'session.created', id: this.session.id },
|
|
342
|
+
});
|
|
343
|
+
this.assertOpen();
|
|
344
|
+
this.ready = true;
|
|
345
|
+
const events = this.pendingEvents.splice(0);
|
|
346
|
+
await Promise.all(events.map(event => this.emit(event)));
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
sendEvent(event: ClientEvent, shouldSend?: () => boolean): Promise<void> {
|
|
350
|
+
this.assertOpen();
|
|
351
|
+
if (shouldSend?.() === false) return Promise.resolve();
|
|
352
|
+
switch (event.type) {
|
|
353
|
+
case 'session-update':
|
|
354
|
+
return this.updateSession(event.config, shouldSend);
|
|
355
|
+
case 'input-audio-mute':
|
|
356
|
+
return this.stopCapture();
|
|
357
|
+
case 'input-audio-unmute':
|
|
358
|
+
return this.startCapture();
|
|
359
|
+
case 'conversation-item-create':
|
|
360
|
+
if (event.item.type === 'function-call-output') {
|
|
361
|
+
const pending = this.pendingTools.get(event.item.callId);
|
|
362
|
+
if (pending == null)
|
|
363
|
+
throw new Error('Mistral function call is no longer pending.');
|
|
364
|
+
this.pendingTools.delete(event.item.callId);
|
|
365
|
+
clearTimeout(pending.timer);
|
|
366
|
+
pending.resolve(event.item.output);
|
|
367
|
+
return Promise.resolve();
|
|
368
|
+
}
|
|
369
|
+
break;
|
|
370
|
+
case 'session-close':
|
|
371
|
+
return this.close();
|
|
372
|
+
}
|
|
373
|
+
throw new UnsupportedFunctionalityError({
|
|
374
|
+
functionality: `${event.type} in Mistral voice sessions`,
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
private async updateSession(
|
|
379
|
+
config: Parameters<typeof buildMistralRealtimeSessionConfig>[0],
|
|
380
|
+
shouldSend?: () => boolean,
|
|
381
|
+
): Promise<void> {
|
|
382
|
+
const payload = await buildMistralRealtimeSessionConfig(config, {
|
|
383
|
+
update: true,
|
|
384
|
+
});
|
|
385
|
+
this.assertOpen();
|
|
386
|
+
if (shouldSend?.() === false) return;
|
|
387
|
+
const agent = this.findAgent();
|
|
388
|
+
if (agent == null) throw new Error('Mistral voice agent is not connected.');
|
|
389
|
+
const response = await this.room!.localParticipant.performRpc({
|
|
390
|
+
destinationIdentity: agent.identity,
|
|
391
|
+
method: 'mistral.session_update',
|
|
392
|
+
payload: JSON.stringify(payload),
|
|
393
|
+
responseTimeout: 5000,
|
|
394
|
+
});
|
|
395
|
+
const parsed = await safeParseJSON({ text: response });
|
|
396
|
+
if (!parsed.success) throw parsed.error;
|
|
397
|
+
// The server also broadcasts session.updated. Its reply is an acknowledgement,
|
|
398
|
+
// not another event, so delivering both would duplicate the update.
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
private async handleToolCall(data: RpcInvocationData): Promise<string> {
|
|
402
|
+
this.assertOpen();
|
|
403
|
+
if (data.callerIdentity !== this.findAgent()?.identity)
|
|
404
|
+
throw new Error('Only the Mistral voice agent may call tools.');
|
|
405
|
+
const parsed = await safeParseJSON({
|
|
406
|
+
text: data.payload,
|
|
407
|
+
schema: functionCallSchema,
|
|
408
|
+
});
|
|
409
|
+
if (!parsed.success) throw parsed.error;
|
|
410
|
+
this.assertOpen();
|
|
411
|
+
const call = parsed.value;
|
|
412
|
+
if (this.pendingTools.has(data.requestId) || this.pendingTools.size >= 64)
|
|
413
|
+
throw new Error('Mistral voice has too many pending function calls.');
|
|
414
|
+
const result = new Promise<string>((resolve, reject) => {
|
|
415
|
+
const timer = setTimeout(() => {
|
|
416
|
+
this.pendingTools.delete(data.requestId);
|
|
417
|
+
reject(new Error(`Mistral function ${call.name} timed out.`));
|
|
418
|
+
}, data.responseTimeout);
|
|
419
|
+
this.pendingTools.set(data.requestId, { resolve, reject, timer });
|
|
420
|
+
});
|
|
421
|
+
// Attach a rejection handler before invoking application callbacks.
|
|
422
|
+
void result.catch(() => {});
|
|
423
|
+
await this.emit({
|
|
424
|
+
type: 'function-call-arguments-delta',
|
|
425
|
+
responseId: data.requestId,
|
|
426
|
+
itemId: data.requestId,
|
|
427
|
+
callId: data.requestId,
|
|
428
|
+
delta: '',
|
|
429
|
+
raw: call,
|
|
430
|
+
});
|
|
431
|
+
await this.emit({
|
|
432
|
+
type: 'function-call-arguments-done',
|
|
433
|
+
responseId: data.requestId,
|
|
434
|
+
itemId: data.requestId,
|
|
435
|
+
callId: data.requestId,
|
|
436
|
+
name: call.name,
|
|
437
|
+
arguments: JSON.stringify(call.arguments ?? {}),
|
|
438
|
+
raw: call,
|
|
439
|
+
});
|
|
440
|
+
return result;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
async startCapture(stream?: MediaStream): Promise<void> {
|
|
444
|
+
this.assertOpen();
|
|
445
|
+
const version = ++this.captureVersion;
|
|
446
|
+
this.sourceStream = stream ?? this.sourceStream;
|
|
447
|
+
const source = this.sourceStream;
|
|
448
|
+
let owned: LocalAudioTrack | undefined;
|
|
449
|
+
if (source == null) {
|
|
450
|
+
const { createLocalAudioTrack } = await loadLiveKit();
|
|
451
|
+
if (this.closed || version !== this.captureVersion) return;
|
|
452
|
+
owned = await createLocalAudioTrack({
|
|
453
|
+
echoCancellation: true,
|
|
454
|
+
noiseSuppression: true,
|
|
455
|
+
autoGainControl: true,
|
|
456
|
+
});
|
|
457
|
+
this.ownedTracks.add(owned);
|
|
458
|
+
}
|
|
459
|
+
const track =
|
|
460
|
+
owned?.mediaStreamTrack ??
|
|
461
|
+
source?.getAudioTracks().find(track => track.readyState === 'live');
|
|
462
|
+
if (this.closed || version !== this.captureVersion) {
|
|
463
|
+
this.stopOwnedTrack(owned);
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
if (track == null) {
|
|
467
|
+
this.stopOwnedTrack(owned);
|
|
468
|
+
throw new Error('Mistral voice requires a live audio track.');
|
|
469
|
+
}
|
|
470
|
+
const room = this.room;
|
|
471
|
+
if (room == null) {
|
|
472
|
+
this.stopOwnedTrack(owned);
|
|
473
|
+
throw new Error('Mistral voice is not connected.');
|
|
474
|
+
}
|
|
475
|
+
const operation = this.captureOperations.then(async () => {
|
|
476
|
+
try {
|
|
477
|
+
await this.releaseMicrophone();
|
|
478
|
+
const { Track } = await loadLiveKit();
|
|
479
|
+
if (this.closed || version !== this.captureVersion) {
|
|
480
|
+
this.stopOwnedTrack(owned);
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
await room.localParticipant.publishTrack(track, {
|
|
484
|
+
source: Track.Source.Microphone,
|
|
485
|
+
});
|
|
486
|
+
if (this.closed || version !== this.captureVersion) {
|
|
487
|
+
await room.localParticipant.unpublishTrack(track, false);
|
|
488
|
+
this.stopOwnedTrack(owned);
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
const onEnded = () => {
|
|
492
|
+
if (this.microphone?.track === track) this.options.onCapturing(false);
|
|
493
|
+
};
|
|
494
|
+
track.addEventListener('ended', onEnded);
|
|
495
|
+
this.microphone = {
|
|
496
|
+
track,
|
|
497
|
+
owned,
|
|
498
|
+
removeListener: () => track.removeEventListener('ended', onEnded),
|
|
499
|
+
};
|
|
500
|
+
this.options.onCapturing(track.enabled && !track.muted);
|
|
501
|
+
} catch (error) {
|
|
502
|
+
this.stopOwnedTrack(owned);
|
|
503
|
+
throw error;
|
|
504
|
+
}
|
|
505
|
+
});
|
|
506
|
+
this.captureOperations = operation.catch(() => {});
|
|
507
|
+
return operation;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
stopCapture(): Promise<void> {
|
|
511
|
+
++this.captureVersion;
|
|
512
|
+
const operation = this.captureOperations.then(() =>
|
|
513
|
+
this.releaseMicrophone(),
|
|
514
|
+
);
|
|
515
|
+
this.captureOperations = operation.catch(() => {});
|
|
516
|
+
return operation;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
private async releaseMicrophone(): Promise<void> {
|
|
520
|
+
const microphone = this.microphone;
|
|
521
|
+
this.microphone = undefined;
|
|
522
|
+
if (microphone != null) {
|
|
523
|
+
microphone.removeListener();
|
|
524
|
+
try {
|
|
525
|
+
await this.room?.localParticipant.unpublishTrack(
|
|
526
|
+
microphone.track,
|
|
527
|
+
false,
|
|
528
|
+
);
|
|
529
|
+
} finally {
|
|
530
|
+
this.stopOwnedTrack(microphone.owned);
|
|
531
|
+
this.options.onCapturing(false);
|
|
532
|
+
}
|
|
533
|
+
} else this.options.onCapturing(false);
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
private stopOwnedTrack(track?: LocalAudioTrack): void {
|
|
537
|
+
if (track != null && this.ownedTracks.delete(track)) track.stop();
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
stopPlayback(): void {
|
|
541
|
+
this.playbackEnabled = false;
|
|
542
|
+
for (const element of this.remoteAudio.values()) element.pause();
|
|
543
|
+
this.options.onPlaying(false);
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
async resumePlayback(): Promise<void> {
|
|
547
|
+
this.assertOpen();
|
|
548
|
+
this.playbackEnabled = true;
|
|
549
|
+
await this.room?.startAudio();
|
|
550
|
+
await Promise.all(
|
|
551
|
+
[...this.remoteAudio.values()].map(element => element.play()),
|
|
552
|
+
);
|
|
553
|
+
if (!this.closed) this.options.onPlaying(this.agentSpeaking);
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
private receive(payload: Uint8Array): void {
|
|
557
|
+
if (!this.accepting || this.closed) return;
|
|
558
|
+
if (
|
|
559
|
+
this.pendingCount >= 512 ||
|
|
560
|
+
this.pendingBytes + payload.byteLength > 8 * 1024 * 1024
|
|
561
|
+
) {
|
|
562
|
+
this.fail(new Error('Mistral voice event queue exceeded its limit.'));
|
|
563
|
+
return;
|
|
564
|
+
}
|
|
565
|
+
++this.pendingCount;
|
|
566
|
+
this.pendingBytes += payload.byteLength;
|
|
567
|
+
this.incoming = this.incoming
|
|
568
|
+
.then(async () => {
|
|
569
|
+
if (this.closed) return;
|
|
570
|
+
const parsed = await safeParseJSON({
|
|
571
|
+
text: new TextDecoder().decode(payload),
|
|
572
|
+
});
|
|
573
|
+
if (!parsed.success) throw parsed.error;
|
|
574
|
+
const raw = parsed.value;
|
|
575
|
+
const transcript = transcriptSchema.safeParse(raw);
|
|
576
|
+
if (transcript.success && transcript.data.final) {
|
|
577
|
+
if (this.finalizedSegments.has(transcript.data.id)) return;
|
|
578
|
+
this.finalizedSegments.add(transcript.data.id);
|
|
579
|
+
if (this.finalizedSegments.size > 500)
|
|
580
|
+
this.finalizedSegments.delete(
|
|
581
|
+
this.finalizedSegments.values().next().value!,
|
|
582
|
+
);
|
|
583
|
+
}
|
|
584
|
+
const state = z
|
|
585
|
+
.object({
|
|
586
|
+
type: z.literal('agent.state.changed'),
|
|
587
|
+
state: z.string(),
|
|
588
|
+
})
|
|
589
|
+
.safeParse(raw);
|
|
590
|
+
if (state.success) {
|
|
591
|
+
this.agentSpeaking = state.data.state === 'speaking';
|
|
592
|
+
this.options.onPlaying(this.playbackEnabled && this.agentSpeaking);
|
|
593
|
+
}
|
|
594
|
+
for (const event of parseMistralRealtimeEvent(raw))
|
|
595
|
+
await this.emit(event);
|
|
596
|
+
const error = errorSchema.safeParse(raw);
|
|
597
|
+
if (error.success && error.data.fatal)
|
|
598
|
+
this.fail(new Error(error.data.message));
|
|
599
|
+
})
|
|
600
|
+
.catch(error => this.fail(asError(error)))
|
|
601
|
+
.finally(() => {
|
|
602
|
+
--this.pendingCount;
|
|
603
|
+
this.pendingBytes -= payload.byteLength;
|
|
604
|
+
});
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
private async emit(event: ServerEvent): Promise<void> {
|
|
608
|
+
if (this.closed) return;
|
|
609
|
+
if (!this.ready) {
|
|
610
|
+
if (this.pendingEvents.length >= 512)
|
|
611
|
+
throw new Error('Mistral voice startup event queue is full.');
|
|
612
|
+
this.pendingEvents.push(event);
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
const delivery = this.deliveries.then(async () => {
|
|
616
|
+
if (this.closed) return;
|
|
617
|
+
try {
|
|
618
|
+
await this.options.onEvent(event);
|
|
619
|
+
} catch (error) {
|
|
620
|
+
this.options.onError(asError(error));
|
|
621
|
+
}
|
|
622
|
+
});
|
|
623
|
+
this.deliveries = delivery.catch(() => {});
|
|
624
|
+
return delivery;
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
private findAgent(): RemoteParticipant | undefined {
|
|
628
|
+
return [...(this.room?.remoteParticipants.values() ?? [])].find(
|
|
629
|
+
participant => participant.isAgent,
|
|
630
|
+
);
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
private checkAgentDisconnect(): void {
|
|
634
|
+
if (!this.agentDisconnected || this.agentCheckQueued) return;
|
|
635
|
+
this.agentCheckQueued = true;
|
|
636
|
+
queueMicrotask(() => {
|
|
637
|
+
this.agentCheckQueued = false;
|
|
638
|
+
if (this.closed || this.reconnecting) return;
|
|
639
|
+
if (this.findAgent() != null) this.agentDisconnected = false;
|
|
640
|
+
else this.fail(new Error('Mistral voice agent disconnected.'));
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
private assertOpen(): void {
|
|
645
|
+
if (this.closed || this.abort.signal.aborted)
|
|
646
|
+
throw new Error('Mistral voice connection is closed.');
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
private untilAborted<T>(operation: Promise<T>): Promise<T> {
|
|
650
|
+
if (this.abort.signal.aborted)
|
|
651
|
+
return Promise.reject(new Error('Mistral voice connection cancelled.'));
|
|
652
|
+
return new Promise<T>((resolve, reject) => {
|
|
653
|
+
const onAbort = () =>
|
|
654
|
+
reject(new Error('Mistral voice connection cancelled.'));
|
|
655
|
+
this.abort.signal.addEventListener('abort', onAbort, { once: true });
|
|
656
|
+
operation.then(resolve, reject).finally(() => {
|
|
657
|
+
this.abort.signal.removeEventListener('abort', onAbort);
|
|
658
|
+
});
|
|
659
|
+
});
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
private fail(error: Error): void {
|
|
663
|
+
if (this.closed || this.failed) return;
|
|
664
|
+
this.failed = true;
|
|
665
|
+
this.accepting = false;
|
|
666
|
+
this.options.onFatalError(error);
|
|
667
|
+
this.dispose();
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
async finish(): Promise<void> {
|
|
671
|
+
this.accepting = false;
|
|
672
|
+
await this.incoming;
|
|
673
|
+
await this.deliveries;
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
private removeRemoteTrack(track: RemoteTrack): void {
|
|
677
|
+
const element = this.remoteAudio.get(track);
|
|
678
|
+
if (element == null) return;
|
|
679
|
+
this.remoteAudio.delete(track);
|
|
680
|
+
element.pause();
|
|
681
|
+
element.srcObject = null;
|
|
682
|
+
track.detach(element);
|
|
683
|
+
element.remove();
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
close(): Promise<void> {
|
|
687
|
+
if (this.cleanup != null) return this.cleanup;
|
|
688
|
+
let disconnected: Promise<void> | undefined;
|
|
689
|
+
// Cache cleanup before callbacks: consumers may dispose again while a media
|
|
690
|
+
// state notification is being delivered.
|
|
691
|
+
this.cleanup = Promise.resolve().then(async () => {
|
|
692
|
+
try {
|
|
693
|
+
await disconnected;
|
|
694
|
+
} finally {
|
|
695
|
+
await this.setup?.catch(() => {});
|
|
696
|
+
if (this.session != null && this.api != null) {
|
|
697
|
+
const separator = this.api.includes('?') ? '&' : '?';
|
|
698
|
+
const response = await fetch(
|
|
699
|
+
`${this.api}${separator}sessionId=${encodeURIComponent(this.session.id)}`,
|
|
700
|
+
{ method: 'DELETE', keepalive: true },
|
|
701
|
+
);
|
|
702
|
+
if (!response.ok)
|
|
703
|
+
throw new Error(
|
|
704
|
+
`Failed to close Mistral voice session: ${response.status}`,
|
|
705
|
+
);
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
});
|
|
709
|
+
this.closed = true;
|
|
710
|
+
this.accepting = false;
|
|
711
|
+
++this.captureVersion;
|
|
712
|
+
this.abort.abort();
|
|
713
|
+
this.removeAbortListener?.();
|
|
714
|
+
this.removeRoomListeners?.();
|
|
715
|
+
this.pendingEvents = [];
|
|
716
|
+
for (const pending of this.pendingTools.values()) {
|
|
717
|
+
clearTimeout(pending.timer);
|
|
718
|
+
pending.reject(new Error('Mistral voice session closed.'));
|
|
719
|
+
}
|
|
720
|
+
this.pendingTools.clear();
|
|
721
|
+
for (const track of this.remoteAudio.keys()) this.removeRemoteTrack(track);
|
|
722
|
+
for (const track of this.ownedTracks) this.stopOwnedTrack(track);
|
|
723
|
+
this.microphone?.removeListener();
|
|
724
|
+
this.microphone = undefined;
|
|
725
|
+
this.options.onCapturing(false);
|
|
726
|
+
this.options.onPlaying(false);
|
|
727
|
+
// false is essential: LiveKit must not stop caller-owned microphone tracks.
|
|
728
|
+
disconnected = this.room?.disconnect(false);
|
|
729
|
+
return this.cleanup;
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
dispose(): void {
|
|
733
|
+
void this.close().catch(error => this.options.onError(asError(error)));
|
|
734
|
+
}
|
|
735
|
+
}
|