@contractspec/integration.providers-impls 2.9.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +59 -0
  2. package/dist/health.d.ts +1 -0
  3. package/dist/health.js +3 -0
  4. package/dist/impls/async-event-queue.d.ts +8 -0
  5. package/dist/impls/async-event-queue.js +47 -0
  6. package/dist/impls/health/base-health-provider.d.ts +98 -0
  7. package/dist/impls/health/base-health-provider.js +616 -0
  8. package/dist/impls/health/hybrid-health-providers.d.ts +34 -0
  9. package/dist/impls/health/hybrid-health-providers.js +1088 -0
  10. package/dist/impls/health/official-health-providers.d.ts +78 -0
  11. package/dist/impls/health/official-health-providers.js +968 -0
  12. package/dist/impls/health/provider-normalizers.d.ts +28 -0
  13. package/dist/impls/health/provider-normalizers.js +287 -0
  14. package/dist/impls/health/providers.d.ts +2 -0
  15. package/dist/impls/health/providers.js +1094 -0
  16. package/dist/impls/health-provider-factory.d.ts +3 -0
  17. package/dist/impls/health-provider-factory.js +1308 -0
  18. package/dist/impls/index.d.ts +8 -0
  19. package/dist/impls/index.js +2356 -176
  20. package/dist/impls/messaging-github.d.ts +17 -0
  21. package/dist/impls/messaging-github.js +110 -0
  22. package/dist/impls/messaging-slack.d.ts +14 -0
  23. package/dist/impls/messaging-slack.js +80 -0
  24. package/dist/impls/messaging-whatsapp-meta.d.ts +13 -0
  25. package/dist/impls/messaging-whatsapp-meta.js +52 -0
  26. package/dist/impls/messaging-whatsapp-twilio.d.ts +13 -0
  27. package/dist/impls/messaging-whatsapp-twilio.js +82 -0
  28. package/dist/impls/mistral-conversational.d.ts +23 -0
  29. package/dist/impls/mistral-conversational.js +476 -0
  30. package/dist/impls/mistral-conversational.session.d.ts +32 -0
  31. package/dist/impls/mistral-conversational.session.js +206 -0
  32. package/dist/impls/mistral-stt.d.ts +17 -0
  33. package/dist/impls/mistral-stt.js +167 -0
  34. package/dist/impls/provider-factory.d.ts +7 -1
  35. package/dist/impls/provider-factory.js +2338 -176
  36. package/dist/impls/stripe-payments.js +1 -1
  37. package/dist/index.d.ts +2 -0
  38. package/dist/index.js +2360 -174
  39. package/dist/messaging.d.ts +1 -0
  40. package/dist/messaging.js +3 -0
  41. package/dist/node/health.js +2 -0
  42. package/dist/node/impls/async-event-queue.js +46 -0
  43. package/dist/node/impls/health/base-health-provider.js +615 -0
  44. package/dist/node/impls/health/hybrid-health-providers.js +1087 -0
  45. package/dist/node/impls/health/official-health-providers.js +967 -0
  46. package/dist/node/impls/health/provider-normalizers.js +286 -0
  47. package/dist/node/impls/health/providers.js +1093 -0
  48. package/dist/node/impls/health-provider-factory.js +1307 -0
  49. package/dist/node/impls/index.js +2356 -176
  50. package/dist/node/impls/messaging-github.js +109 -0
  51. package/dist/node/impls/messaging-slack.js +79 -0
  52. package/dist/node/impls/messaging-whatsapp-meta.js +51 -0
  53. package/dist/node/impls/messaging-whatsapp-twilio.js +81 -0
  54. package/dist/node/impls/mistral-conversational.js +475 -0
  55. package/dist/node/impls/mistral-conversational.session.js +205 -0
  56. package/dist/node/impls/mistral-stt.js +166 -0
  57. package/dist/node/impls/provider-factory.js +2338 -176
  58. package/dist/node/impls/stripe-payments.js +1 -1
  59. package/dist/node/index.js +2360 -174
  60. package/dist/node/messaging.js +2 -0
  61. package/package.json +204 -12
@@ -0,0 +1,476 @@
1
+ // @bun
2
+ // src/impls/async-event-queue.ts
3
+ class AsyncEventQueue {
4
+ values = [];
5
+ waiters = [];
6
+ done = false;
7
+ push(value) {
8
+ if (this.done) {
9
+ return;
10
+ }
11
+ const waiter = this.waiters.shift();
12
+ if (waiter) {
13
+ waiter({ value, done: false });
14
+ return;
15
+ }
16
+ this.values.push(value);
17
+ }
18
+ close() {
19
+ if (this.done) {
20
+ return;
21
+ }
22
+ this.done = true;
23
+ for (const waiter of this.waiters) {
24
+ waiter({ value: undefined, done: true });
25
+ }
26
+ this.waiters.length = 0;
27
+ }
28
+ [Symbol.asyncIterator]() {
29
+ return {
30
+ next: async () => {
31
+ const value = this.values.shift();
32
+ if (value != null) {
33
+ return { value, done: false };
34
+ }
35
+ if (this.done) {
36
+ return { value: undefined, done: true };
37
+ }
38
+ return new Promise((resolve) => {
39
+ this.waiters.push(resolve);
40
+ });
41
+ }
42
+ };
43
+ }
44
+ }
45
+
46
+ // src/impls/mistral-stt.ts
47
+ var DEFAULT_BASE_URL = "https://api.mistral.ai/v1";
48
+ var DEFAULT_MODEL = "voxtral-mini-latest";
49
+ var AUDIO_MIME_BY_FORMAT = {
50
+ mp3: "audio/mpeg",
51
+ wav: "audio/wav",
52
+ ogg: "audio/ogg",
53
+ pcm: "audio/pcm",
54
+ opus: "audio/opus"
55
+ };
56
+
57
+ class MistralSttProvider {
58
+ apiKey;
59
+ defaultModel;
60
+ defaultLanguage;
61
+ baseUrl;
62
+ fetchImpl;
63
+ constructor(options) {
64
+ if (!options.apiKey) {
65
+ throw new Error("MistralSttProvider requires an apiKey");
66
+ }
67
+ this.apiKey = options.apiKey;
68
+ this.defaultModel = options.defaultModel ?? DEFAULT_MODEL;
69
+ this.defaultLanguage = options.defaultLanguage;
70
+ this.baseUrl = normalizeBaseUrl(options.serverURL ?? DEFAULT_BASE_URL);
71
+ this.fetchImpl = options.fetchImpl ?? fetch;
72
+ }
73
+ async transcribe(input) {
74
+ const formData = new FormData;
75
+ const model = input.model ?? this.defaultModel;
76
+ const mimeType = AUDIO_MIME_BY_FORMAT[input.audio.format] ?? "audio/wav";
77
+ const fileName = `audio.${input.audio.format}`;
78
+ const audioBytes = new Uint8Array(input.audio.data);
79
+ const blob = new Blob([audioBytes], { type: mimeType });
80
+ formData.append("file", blob, fileName);
81
+ formData.append("model", model);
82
+ formData.append("response_format", "verbose_json");
83
+ const language = input.language ?? this.defaultLanguage;
84
+ if (language) {
85
+ formData.append("language", language);
86
+ }
87
+ const response = await this.fetchImpl(`${this.baseUrl}/audio/transcriptions`, {
88
+ method: "POST",
89
+ headers: {
90
+ Authorization: `Bearer ${this.apiKey}`
91
+ },
92
+ body: formData
93
+ });
94
+ if (!response.ok) {
95
+ const body = await response.text();
96
+ throw new Error(`Mistral transcription request failed (${response.status}): ${body}`);
97
+ }
98
+ const payload = await response.json();
99
+ return toTranscriptionResult(payload, input);
100
+ }
101
+ }
102
+ function toTranscriptionResult(payload, input) {
103
+ const record = asRecord(payload);
104
+ const text = readString(record, "text") ?? "";
105
+ const language = readString(record, "language") ?? input.language ?? "unknown";
106
+ const segments = parseSegments(record);
107
+ if (segments.length === 0 && text.length > 0) {
108
+ segments.push({
109
+ text,
110
+ startMs: 0,
111
+ endMs: input.audio.durationMs ?? 0
112
+ });
113
+ }
114
+ const durationMs = input.audio.durationMs ?? segments.reduce((max, segment) => Math.max(max, segment.endMs), 0);
115
+ const topLevelWords = parseWordTimings(record.words);
116
+ const flattenedWords = segments.flatMap((segment) => segment.wordTimings ?? []);
117
+ const wordTimings = topLevelWords.length > 0 ? topLevelWords : flattenedWords.length > 0 ? flattenedWords : undefined;
118
+ const speakers = dedupeSpeakers(segments);
119
+ return {
120
+ text,
121
+ segments,
122
+ language,
123
+ durationMs,
124
+ speakers: speakers.length > 0 ? speakers : undefined,
125
+ wordTimings
126
+ };
127
+ }
128
+ function parseSegments(record) {
129
+ if (!Array.isArray(record.segments)) {
130
+ return [];
131
+ }
132
+ const parsed = [];
133
+ for (const entry of record.segments) {
134
+ const segmentRecord = asRecord(entry);
135
+ const text = readString(segmentRecord, "text");
136
+ if (!text) {
137
+ continue;
138
+ }
139
+ const startSeconds = readNumber(segmentRecord, "start") ?? 0;
140
+ const endSeconds = readNumber(segmentRecord, "end") ?? startSeconds;
141
+ parsed.push({
142
+ text,
143
+ startMs: secondsToMs(startSeconds),
144
+ endMs: secondsToMs(endSeconds),
145
+ speakerId: readString(segmentRecord, "speaker") ?? undefined,
146
+ confidence: readNumber(segmentRecord, "confidence"),
147
+ wordTimings: parseWordTimings(segmentRecord.words)
148
+ });
149
+ }
150
+ return parsed;
151
+ }
152
+ function parseWordTimings(value) {
153
+ if (!Array.isArray(value)) {
154
+ return [];
155
+ }
156
+ const words = [];
157
+ for (const entry of value) {
158
+ const wordRecord = asRecord(entry);
159
+ const word = readString(wordRecord, "word");
160
+ const startSeconds = readNumber(wordRecord, "start");
161
+ const endSeconds = readNumber(wordRecord, "end");
162
+ if (!word || startSeconds == null || endSeconds == null) {
163
+ continue;
164
+ }
165
+ words.push({
166
+ word,
167
+ startMs: secondsToMs(startSeconds),
168
+ endMs: secondsToMs(endSeconds),
169
+ confidence: readNumber(wordRecord, "confidence")
170
+ });
171
+ }
172
+ return words;
173
+ }
174
+ function dedupeSpeakers(segments) {
175
+ const seen = new Set;
176
+ const speakers = [];
177
+ for (const segment of segments) {
178
+ if (!segment.speakerId || seen.has(segment.speakerId)) {
179
+ continue;
180
+ }
181
+ seen.add(segment.speakerId);
182
+ speakers.push({
183
+ id: segment.speakerId,
184
+ name: segment.speakerName
185
+ });
186
+ }
187
+ return speakers;
188
+ }
189
+ function normalizeBaseUrl(url) {
190
+ return url.endsWith("/") ? url.slice(0, -1) : url;
191
+ }
192
+ function asRecord(value) {
193
+ if (value && typeof value === "object") {
194
+ return value;
195
+ }
196
+ return {};
197
+ }
198
+ function readString(record, key) {
199
+ const value = record[key];
200
+ return typeof value === "string" ? value : undefined;
201
+ }
202
+ function readNumber(record, key) {
203
+ const value = record[key];
204
+ return typeof value === "number" ? value : undefined;
205
+ }
206
+ function secondsToMs(value) {
207
+ return Math.round(value * 1000);
208
+ }
209
+
210
+ // src/impls/mistral-conversational.session.ts
211
+ class MistralConversationSession {
212
+ events;
213
+ queue = new AsyncEventQueue;
214
+ turns = [];
215
+ history = [];
216
+ sessionId = crypto.randomUUID();
217
+ startedAt = Date.now();
218
+ sessionConfig;
219
+ defaultModel;
220
+ complete;
221
+ sttProvider;
222
+ pending = Promise.resolve();
223
+ closed = false;
224
+ closedSummary;
225
+ constructor(options) {
226
+ this.sessionConfig = options.sessionConfig;
227
+ this.defaultModel = options.defaultModel;
228
+ this.complete = options.complete;
229
+ this.sttProvider = options.sttProvider;
230
+ this.events = this.queue;
231
+ this.queue.push({
232
+ type: "session_started",
233
+ sessionId: this.sessionId
234
+ });
235
+ }
236
+ sendAudio(chunk) {
237
+ if (this.closed) {
238
+ return;
239
+ }
240
+ this.pending = this.pending.then(async () => {
241
+ const transcription = await this.sttProvider.transcribe({
242
+ audio: {
243
+ data: chunk,
244
+ format: this.sessionConfig.inputFormat ?? "pcm",
245
+ sampleRateHz: 16000
246
+ },
247
+ language: this.sessionConfig.language
248
+ });
249
+ const transcriptText = transcription.text.trim();
250
+ if (transcriptText.length > 0) {
251
+ await this.handleUserText(transcriptText);
252
+ }
253
+ }).catch((error) => {
254
+ this.emitError(error);
255
+ });
256
+ }
257
+ sendText(text) {
258
+ if (this.closed) {
259
+ return;
260
+ }
261
+ const normalized = text.trim();
262
+ if (normalized.length === 0) {
263
+ return;
264
+ }
265
+ this.pending = this.pending.then(() => this.handleUserText(normalized)).catch((error) => {
266
+ this.emitError(error);
267
+ });
268
+ }
269
+ interrupt() {
270
+ if (this.closed) {
271
+ return;
272
+ }
273
+ this.queue.push({
274
+ type: "error",
275
+ error: new Error("Interrupt is not supported for non-streaming sessions.")
276
+ });
277
+ }
278
+ async close() {
279
+ if (this.closedSummary) {
280
+ return this.closedSummary;
281
+ }
282
+ this.closed = true;
283
+ await this.pending;
284
+ const durationMs = Date.now() - this.startedAt;
285
+ const summary = {
286
+ sessionId: this.sessionId,
287
+ durationMs,
288
+ turns: this.turns.map((turn) => ({
289
+ role: turn.role === "assistant" ? "agent" : turn.role,
290
+ text: turn.text,
291
+ startMs: turn.startMs,
292
+ endMs: turn.endMs
293
+ })),
294
+ transcript: this.turns.map((turn) => `${turn.role}: ${turn.text}`).join(`
295
+ `)
296
+ };
297
+ this.closedSummary = summary;
298
+ this.queue.push({
299
+ type: "session_ended",
300
+ reason: "closed_by_client",
301
+ durationMs
302
+ });
303
+ this.queue.close();
304
+ return summary;
305
+ }
306
+ async handleUserText(text) {
307
+ if (this.closed) {
308
+ return;
309
+ }
310
+ const userStart = Date.now();
311
+ this.queue.push({ type: "user_speech_started" });
312
+ this.queue.push({ type: "user_speech_ended", transcript: text });
313
+ this.queue.push({
314
+ type: "transcript",
315
+ role: "user",
316
+ text,
317
+ timestamp: userStart
318
+ });
319
+ this.turns.push({
320
+ role: "user",
321
+ text,
322
+ startMs: userStart,
323
+ endMs: Date.now()
324
+ });
325
+ this.history.push({ role: "user", content: text });
326
+ const assistantStart = Date.now();
327
+ const assistantText = await this.complete(this.history, {
328
+ ...this.sessionConfig,
329
+ llmModel: this.sessionConfig.llmModel ?? this.defaultModel
330
+ });
331
+ if (this.closed) {
332
+ return;
333
+ }
334
+ const normalizedAssistantText = assistantText.trim();
335
+ const finalAssistantText = normalizedAssistantText.length > 0 ? normalizedAssistantText : "I was unable to produce a response.";
336
+ this.queue.push({
337
+ type: "agent_speech_started",
338
+ text: finalAssistantText
339
+ });
340
+ this.queue.push({
341
+ type: "transcript",
342
+ role: "agent",
343
+ text: finalAssistantText,
344
+ timestamp: assistantStart
345
+ });
346
+ this.queue.push({ type: "agent_speech_ended" });
347
+ this.turns.push({
348
+ role: "assistant",
349
+ text: finalAssistantText,
350
+ startMs: assistantStart,
351
+ endMs: Date.now()
352
+ });
353
+ this.history.push({ role: "assistant", content: finalAssistantText });
354
+ }
355
+ emitError(error) {
356
+ if (this.closed) {
357
+ return;
358
+ }
359
+ this.queue.push({ type: "error", error: toError(error) });
360
+ }
361
+ }
362
+ function toError(error) {
363
+ if (error instanceof Error) {
364
+ return error;
365
+ }
366
+ return new Error(String(error));
367
+ }
368
+
369
+ // src/impls/mistral-conversational.ts
370
+ var DEFAULT_BASE_URL2 = "https://api.mistral.ai/v1";
371
+ var DEFAULT_MODEL2 = "mistral-small-latest";
372
+ var DEFAULT_VOICE = "default";
373
+
374
+ class MistralConversationalProvider {
375
+ apiKey;
376
+ defaultModel;
377
+ defaultVoiceId;
378
+ baseUrl;
379
+ fetchImpl;
380
+ sttProvider;
381
+ constructor(options) {
382
+ if (!options.apiKey) {
383
+ throw new Error("MistralConversationalProvider requires an apiKey");
384
+ }
385
+ this.apiKey = options.apiKey;
386
+ this.defaultModel = options.defaultModel ?? DEFAULT_MODEL2;
387
+ this.defaultVoiceId = options.defaultVoiceId ?? DEFAULT_VOICE;
388
+ this.baseUrl = normalizeBaseUrl2(options.serverURL ?? DEFAULT_BASE_URL2);
389
+ this.fetchImpl = options.fetchImpl ?? fetch;
390
+ this.sttProvider = options.sttProvider ?? new MistralSttProvider({
391
+ apiKey: options.apiKey,
392
+ defaultModel: options.sttOptions?.defaultModel,
393
+ defaultLanguage: options.sttOptions?.defaultLanguage,
394
+ serverURL: options.sttOptions?.serverURL ?? options.serverURL,
395
+ fetchImpl: this.fetchImpl
396
+ });
397
+ }
398
+ async startSession(config) {
399
+ return new MistralConversationSession({
400
+ sessionConfig: {
401
+ ...config,
402
+ voiceId: config.voiceId || this.defaultVoiceId
403
+ },
404
+ defaultModel: this.defaultModel,
405
+ complete: (history, sessionConfig) => this.completeConversation(history, sessionConfig),
406
+ sttProvider: this.sttProvider
407
+ });
408
+ }
409
+ async listVoices() {
410
+ return [
411
+ {
412
+ id: this.defaultVoiceId,
413
+ name: "Mistral Default Voice",
414
+ description: "Default conversational voice profile.",
415
+ capabilities: ["conversational"]
416
+ }
417
+ ];
418
+ }
419
+ async completeConversation(history, sessionConfig) {
420
+ const model = sessionConfig.llmModel ?? this.defaultModel;
421
+ const messages = [];
422
+ if (sessionConfig.systemPrompt) {
423
+ messages.push({ role: "system", content: sessionConfig.systemPrompt });
424
+ }
425
+ for (const item of history) {
426
+ messages.push({ role: item.role, content: item.content });
427
+ }
428
+ const response = await this.fetchImpl(`${this.baseUrl}/chat/completions`, {
429
+ method: "POST",
430
+ headers: {
431
+ Authorization: `Bearer ${this.apiKey}`,
432
+ "Content-Type": "application/json"
433
+ },
434
+ body: JSON.stringify({
435
+ model,
436
+ messages
437
+ })
438
+ });
439
+ if (!response.ok) {
440
+ const body = await response.text();
441
+ throw new Error(`Mistral conversational request failed (${response.status}): ${body}`);
442
+ }
443
+ const payload = await response.json();
444
+ return readAssistantText(payload);
445
+ }
446
+ }
447
+ function normalizeBaseUrl2(url) {
448
+ return url.endsWith("/") ? url.slice(0, -1) : url;
449
+ }
450
+ function readAssistantText(payload) {
451
+ const record = asRecord2(payload);
452
+ const choices = Array.isArray(record.choices) ? record.choices : [];
453
+ const firstChoice = asRecord2(choices[0]);
454
+ const message = asRecord2(firstChoice.message);
455
+ if (typeof message.content === "string") {
456
+ return message.content;
457
+ }
458
+ if (Array.isArray(message.content)) {
459
+ const textParts = message.content.map((part) => {
460
+ const entry = asRecord2(part);
461
+ const text = entry.text;
462
+ return typeof text === "string" ? text : "";
463
+ }).filter((text) => text.length > 0);
464
+ return textParts.join("");
465
+ }
466
+ return "";
467
+ }
468
+ function asRecord2(value) {
469
+ if (value && typeof value === "object") {
470
+ return value;
471
+ }
472
+ return {};
473
+ }
474
+ export {
475
+ MistralConversationalProvider
476
+ };
@@ -0,0 +1,32 @@
1
+ import type { ConversationalEvent, ConversationalSession, ConversationalSessionConfig, ConversationalSessionSummary, STTProvider } from '../voice';
2
+ export interface ConversationMessage {
3
+ role: 'user' | 'assistant';
4
+ content: string;
5
+ }
6
+ export declare class MistralConversationSession implements ConversationalSession {
7
+ readonly events: AsyncIterable<ConversationalEvent>;
8
+ private readonly queue;
9
+ private readonly turns;
10
+ private readonly history;
11
+ private readonly sessionId;
12
+ private readonly startedAt;
13
+ private readonly sessionConfig;
14
+ private readonly defaultModel;
15
+ private readonly complete;
16
+ private readonly sttProvider;
17
+ private pending;
18
+ private closed;
19
+ private closedSummary?;
20
+ constructor(options: {
21
+ sessionConfig: ConversationalSessionConfig;
22
+ defaultModel: string;
23
+ complete: (history: ConversationMessage[], sessionConfig: ConversationalSessionConfig) => Promise<string>;
24
+ sttProvider: STTProvider;
25
+ });
26
+ sendAudio(chunk: Uint8Array): void;
27
+ sendText(text: string): void;
28
+ interrupt(): void;
29
+ close(): Promise<ConversationalSessionSummary>;
30
+ private handleUserText;
31
+ private emitError;
32
+ }
@@ -0,0 +1,206 @@
1
+ // @bun
2
+ // src/impls/async-event-queue.ts
3
+ class AsyncEventQueue {
4
+ values = [];
5
+ waiters = [];
6
+ done = false;
7
+ push(value) {
8
+ if (this.done) {
9
+ return;
10
+ }
11
+ const waiter = this.waiters.shift();
12
+ if (waiter) {
13
+ waiter({ value, done: false });
14
+ return;
15
+ }
16
+ this.values.push(value);
17
+ }
18
+ close() {
19
+ if (this.done) {
20
+ return;
21
+ }
22
+ this.done = true;
23
+ for (const waiter of this.waiters) {
24
+ waiter({ value: undefined, done: true });
25
+ }
26
+ this.waiters.length = 0;
27
+ }
28
+ [Symbol.asyncIterator]() {
29
+ return {
30
+ next: async () => {
31
+ const value = this.values.shift();
32
+ if (value != null) {
33
+ return { value, done: false };
34
+ }
35
+ if (this.done) {
36
+ return { value: undefined, done: true };
37
+ }
38
+ return new Promise((resolve) => {
39
+ this.waiters.push(resolve);
40
+ });
41
+ }
42
+ };
43
+ }
44
+ }
45
+
46
+ // src/impls/mistral-conversational.session.ts
47
+ class MistralConversationSession {
48
+ events;
49
+ queue = new AsyncEventQueue;
50
+ turns = [];
51
+ history = [];
52
+ sessionId = crypto.randomUUID();
53
+ startedAt = Date.now();
54
+ sessionConfig;
55
+ defaultModel;
56
+ complete;
57
+ sttProvider;
58
+ pending = Promise.resolve();
59
+ closed = false;
60
+ closedSummary;
61
+ constructor(options) {
62
+ this.sessionConfig = options.sessionConfig;
63
+ this.defaultModel = options.defaultModel;
64
+ this.complete = options.complete;
65
+ this.sttProvider = options.sttProvider;
66
+ this.events = this.queue;
67
+ this.queue.push({
68
+ type: "session_started",
69
+ sessionId: this.sessionId
70
+ });
71
+ }
72
+ sendAudio(chunk) {
73
+ if (this.closed) {
74
+ return;
75
+ }
76
+ this.pending = this.pending.then(async () => {
77
+ const transcription = await this.sttProvider.transcribe({
78
+ audio: {
79
+ data: chunk,
80
+ format: this.sessionConfig.inputFormat ?? "pcm",
81
+ sampleRateHz: 16000
82
+ },
83
+ language: this.sessionConfig.language
84
+ });
85
+ const transcriptText = transcription.text.trim();
86
+ if (transcriptText.length > 0) {
87
+ await this.handleUserText(transcriptText);
88
+ }
89
+ }).catch((error) => {
90
+ this.emitError(error);
91
+ });
92
+ }
93
+ sendText(text) {
94
+ if (this.closed) {
95
+ return;
96
+ }
97
+ const normalized = text.trim();
98
+ if (normalized.length === 0) {
99
+ return;
100
+ }
101
+ this.pending = this.pending.then(() => this.handleUserText(normalized)).catch((error) => {
102
+ this.emitError(error);
103
+ });
104
+ }
105
+ interrupt() {
106
+ if (this.closed) {
107
+ return;
108
+ }
109
+ this.queue.push({
110
+ type: "error",
111
+ error: new Error("Interrupt is not supported for non-streaming sessions.")
112
+ });
113
+ }
114
+ async close() {
115
+ if (this.closedSummary) {
116
+ return this.closedSummary;
117
+ }
118
+ this.closed = true;
119
+ await this.pending;
120
+ const durationMs = Date.now() - this.startedAt;
121
+ const summary = {
122
+ sessionId: this.sessionId,
123
+ durationMs,
124
+ turns: this.turns.map((turn) => ({
125
+ role: turn.role === "assistant" ? "agent" : turn.role,
126
+ text: turn.text,
127
+ startMs: turn.startMs,
128
+ endMs: turn.endMs
129
+ })),
130
+ transcript: this.turns.map((turn) => `${turn.role}: ${turn.text}`).join(`
131
+ `)
132
+ };
133
+ this.closedSummary = summary;
134
+ this.queue.push({
135
+ type: "session_ended",
136
+ reason: "closed_by_client",
137
+ durationMs
138
+ });
139
+ this.queue.close();
140
+ return summary;
141
+ }
142
+ async handleUserText(text) {
143
+ if (this.closed) {
144
+ return;
145
+ }
146
+ const userStart = Date.now();
147
+ this.queue.push({ type: "user_speech_started" });
148
+ this.queue.push({ type: "user_speech_ended", transcript: text });
149
+ this.queue.push({
150
+ type: "transcript",
151
+ role: "user",
152
+ text,
153
+ timestamp: userStart
154
+ });
155
+ this.turns.push({
156
+ role: "user",
157
+ text,
158
+ startMs: userStart,
159
+ endMs: Date.now()
160
+ });
161
+ this.history.push({ role: "user", content: text });
162
+ const assistantStart = Date.now();
163
+ const assistantText = await this.complete(this.history, {
164
+ ...this.sessionConfig,
165
+ llmModel: this.sessionConfig.llmModel ?? this.defaultModel
166
+ });
167
+ if (this.closed) {
168
+ return;
169
+ }
170
+ const normalizedAssistantText = assistantText.trim();
171
+ const finalAssistantText = normalizedAssistantText.length > 0 ? normalizedAssistantText : "I was unable to produce a response.";
172
+ this.queue.push({
173
+ type: "agent_speech_started",
174
+ text: finalAssistantText
175
+ });
176
+ this.queue.push({
177
+ type: "transcript",
178
+ role: "agent",
179
+ text: finalAssistantText,
180
+ timestamp: assistantStart
181
+ });
182
+ this.queue.push({ type: "agent_speech_ended" });
183
+ this.turns.push({
184
+ role: "assistant",
185
+ text: finalAssistantText,
186
+ startMs: assistantStart,
187
+ endMs: Date.now()
188
+ });
189
+ this.history.push({ role: "assistant", content: finalAssistantText });
190
+ }
191
+ emitError(error) {
192
+ if (this.closed) {
193
+ return;
194
+ }
195
+ this.queue.push({ type: "error", error: toError(error) });
196
+ }
197
+ }
198
+ function toError(error) {
199
+ if (error instanceof Error) {
200
+ return error;
201
+ }
202
+ return new Error(String(error));
203
+ }
204
+ export {
205
+ MistralConversationSession
206
+ };