@contractspec/integration.providers-impls 2.10.0 → 3.1.1

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