realtime-voice-agents 2.4.0 → 2.5.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 (46) hide show
  1. package/README.md +30 -11
  2. package/dist/{BaseRealtimeProvider-CWJ81HIt.d.mts → BaseRealtimeProvider-BJQO-hpu.d.mts} +44 -1
  3. package/dist/{BaseRealtimeProvider-BL75_HHh.d.cts → BaseRealtimeProvider-CO9N8jt-.d.cts} +44 -1
  4. package/dist/{BaseRealtimeProvider-C9C3s8jx.mjs → BaseRealtimeProvider-Cj6JWR2k.mjs} +1 -1
  5. package/dist/{BaseRealtimeProvider-C2mRn1V_.cjs → BaseRealtimeProvider-ZfFzijdr.cjs} +1 -1
  6. package/dist/{GeminiLiveProvider-Cc1dkxW6.d.cts → GeminiLiveProvider-C_LQCTX5.d.mts} +1 -1
  7. package/dist/{GeminiLiveProvider-TvY_cQQZ.d.mts → GeminiLiveProvider-DM-GwD0w.d.cts} +1 -1
  8. package/dist/{InMemorySessionStore-CRBmmCA6.d.cts → InMemorySessionStore-BlsyPnIp.d.cts} +2 -0
  9. package/dist/{InMemorySessionStore-CRBmmCA6.d.mts → InMemorySessionStore-BlsyPnIp.d.mts} +2 -0
  10. package/dist/{OpenAICompatibleProvider-D-2OOVBU.mjs → OpenAICompatibleProvider-Dqje-boq.mjs} +3 -3
  11. package/dist/{OpenAICompatibleProvider-Mp0Mefbh.cjs → OpenAICompatibleProvider-j2Nza2q2.cjs} +8 -2
  12. package/dist/{events-BylBSBW-.mjs → events-D-pvCH_F.mjs} +2 -1
  13. package/dist/{events-BxDTIKKq.cjs → events-DWX9535M.cjs} +2 -1
  14. package/dist/gemini.cjs +1 -1
  15. package/dist/gemini.d.cts +2 -2
  16. package/dist/gemini.d.mts +2 -2
  17. package/dist/gemini.mjs +1 -1
  18. package/dist/gpt-live.cjs +954 -0
  19. package/dist/gpt-live.d.cts +261 -0
  20. package/dist/gpt-live.d.mts +261 -0
  21. package/dist/gpt-live.mjs +936 -0
  22. package/dist/index.cjs +116 -19
  23. package/dist/index.d.cts +7 -3
  24. package/dist/index.d.mts +7 -3
  25. package/dist/index.mjs +116 -19
  26. package/dist/openai.cjs +2 -2
  27. package/dist/openai.d.cts +1 -1
  28. package/dist/openai.d.mts +1 -1
  29. package/dist/openai.mjs +2 -2
  30. package/dist/{rest-BYqiVOhe.mjs → rest-D-DWWVIj.mjs} +1 -1
  31. package/dist/{rest-BvUKut_k.cjs → rest-OR4VhEif.cjs} +1 -1
  32. package/dist/{session-config-CbifLlkV.mjs → session-config-C31WZESg.mjs} +1 -1
  33. package/dist/{session-config-CqJm2Kxz.cjs → session-config-CYjxBqpF.cjs} +1 -1
  34. package/dist/store.d.cts +1 -1
  35. package/dist/store.d.mts +1 -1
  36. package/dist/testing.cjs +376 -0
  37. package/dist/testing.d.cts +119 -2
  38. package/dist/testing.d.mts +119 -2
  39. package/dist/testing.mjs +374 -2
  40. package/dist/twilio.cjs +1 -1
  41. package/dist/twilio.mjs +1 -1
  42. package/dist/xai.cjs +3 -3
  43. package/dist/xai.d.cts +1 -1
  44. package/dist/xai.d.mts +1 -1
  45. package/dist/xai.mjs +3 -3
  46. package/package.json +14 -2
@@ -0,0 +1,936 @@
1
+ import { a as noopLogger, n as deepMerge, t as BaseRealtimeProvider } from "./BaseRealtimeProvider-Cj6JWR2k.mjs";
2
+ import { c as mulawToPcm16 } from "./mulaw--cwU2c9L.mjs";
3
+ import { t as resolveApiKey } from "./env-DUwUWTsg.mjs";
4
+ import { n as normalizeUsage } from "./OpenAICompatibleProvider-Dqje-boq.mjs";
5
+ import WebSocket$1 from "ws";
6
+ //#region src/providers/gpt-live/session-config.ts
7
+ /**
8
+ * `session.start` construction for GPT-Live (`/v1/live/sessions`).
9
+ *
10
+ * The session object is a STRICT schema: an unknown field rejects the whole
11
+ * start with `unknown_parameter` (field-verified Sept 2026), so every key
12
+ * here is a documented one and `providerOptions` / `extraSessionOptions`
13
+ * are deep-merged last as a deliberate escape hatch. Wire facts baked in:
14
+ * - one audio format for both directions, `{ type: 'audio/pcmu', rate: 8000 }`
15
+ * (Twilio's wire format — no transcoding)
16
+ * - instructions, voice, format and history are immutable after start
17
+ * - tools do not live on the voice model: they are `delegation.responses.tools`
18
+ * for the backend Responses model that reasons and calls them
19
+ * - history is `input`: ≤ 128 text messages / ≤ 8,192 rendered tokens
20
+ */
21
+ const GPT_LIVE_DEFAULT_BACKEND_MODEL = "gpt-5.6-terra";
22
+ const GPT_LIVE_AUDIO_FORMAT = {
23
+ type: "audio/pcmu",
24
+ rate: 8e3
25
+ };
26
+ const HISTORY_MAX_MESSAGES = 128;
27
+ /** ≈ 8,192 tokens at a conservative 2.5 chars/token (Hebrew and other dense scripts). */
28
+ const HISTORY_MAX_CHARS = 2e4;
29
+ function toBackendTool(tool) {
30
+ return {
31
+ type: "function",
32
+ name: tool.name,
33
+ description: tool.description ?? "",
34
+ parameters: tool.parameters
35
+ };
36
+ }
37
+ function buildDelegation(tools, options = {}) {
38
+ const responses = {
39
+ model: options.model ?? "gpt-5.6-terra",
40
+ tools: [...(tools ?? []).map(toBackendTool), ...options.extraTools ?? []],
41
+ tool_choice: options.toolChoice ?? "auto"
42
+ };
43
+ if (options.instructions !== void 0) responses.instructions = options.instructions;
44
+ if (options.parallelToolCalls !== void 0) responses.parallel_tool_calls = options.parallelToolCalls;
45
+ if (options.maxOutputTokens !== void 0) responses.max_output_tokens = options.maxOutputTokens;
46
+ if (options.reasoning !== void 0) responses.reasoning = options.reasoning;
47
+ if (options.serviceTier !== void 0) responses.service_tier = options.serviceTier;
48
+ if (options.text !== void 0) responses.text = options.text;
49
+ return {
50
+ type: "responses",
51
+ responses
52
+ };
53
+ }
54
+ /**
55
+ * History → `input` items, newest-first trimming to the API bounds. A leading
56
+ * `developer` entry (the engine's continuation note) is pinned so trimming
57
+ * never drops the context that explains the rest.
58
+ */
59
+ function buildHistoryItems(history, limits = {}) {
60
+ if (!history || history.length === 0) return {
61
+ items: [],
62
+ dropped: 0
63
+ };
64
+ const maxMessages = limits.maxMessages ?? HISTORY_MAX_MESSAGES;
65
+ const maxChars = limits.maxChars ?? HISTORY_MAX_CHARS;
66
+ const pinned = history[0].role === "developer" ? [history[0]] : [];
67
+ const rest = history.slice(pinned.length);
68
+ let chars = pinned.reduce((n, e) => n + e.text.length, 0);
69
+ const kept = [];
70
+ for (let i = rest.length - 1; i >= 0; i--) {
71
+ const entry = rest[i];
72
+ if (kept.length + pinned.length >= maxMessages) break;
73
+ if (chars + entry.text.length > maxChars) break;
74
+ chars += entry.text.length;
75
+ kept.unshift(entry);
76
+ }
77
+ return {
78
+ items: [...pinned, ...kept].map((entry) => ({
79
+ type: "message",
80
+ role: entry.role,
81
+ content: [{
82
+ type: entry.role === "assistant" ? "output_text" : "input_text",
83
+ text: entry.text
84
+ }]
85
+ })),
86
+ dropped: rest.length - kept.length
87
+ };
88
+ }
89
+ function buildSessionStart(init, config, eventId, model) {
90
+ const { items, dropped } = buildHistoryItems(init.history, {
91
+ maxMessages: config.historyMaxMessages,
92
+ maxChars: config.historyMaxChars
93
+ });
94
+ const voice = init.voice ?? config.defaultVoice;
95
+ let session = {
96
+ model,
97
+ instructions: init.instructions,
98
+ audio: {
99
+ format: { ...GPT_LIVE_AUDIO_FORMAT },
100
+ ...voice ? { output: { voice } } : {}
101
+ },
102
+ delegation: buildDelegation(init.tools, config.delegation),
103
+ ...items.length ? { input: items } : {},
104
+ ...config.store ? { store: true } : {}
105
+ };
106
+ session = deepMerge(session, init.providerOptions);
107
+ session = deepMerge(session, config.extraSessionOptions);
108
+ return {
109
+ frame: {
110
+ type: "session.start",
111
+ event_id: eventId,
112
+ session
113
+ },
114
+ droppedHistory: dropped
115
+ };
116
+ }
117
+ //#endregion
118
+ //#region src/providers/gpt-live/speech-gate.ts
119
+ /**
120
+ * Speech gate for full-duplex output streams.
121
+ *
122
+ * GPT-Live streams assistant audio continuously and in real time — silence
123
+ * included (≈100 ms μ-law deltas, digital 0xFF while the model is quiet) —
124
+ * and the wire has no response boundaries: no response.created, no
125
+ * output_audio.done. The engine's playback tracking, tool timing and hangup
126
+ * watchdog all key off `responseStarted` / `responseDone`, so this gate
127
+ * synthesizes utterances from the audio itself: one opens on the first loud
128
+ * 20 ms sub-frame and closes after `quietMs` of quiet AUDIO. Quiet is
129
+ * measured on the stream's own clock (bytes received), never wall-clock, so
130
+ * a stalled socket cannot fake a finished utterance and tests can script
131
+ * silence instantly. Field numbers (Sept 2026, 8 kHz μ-law): quiet frames
132
+ * p99 ≈ −50 dBFS, speech p05 ≈ −44 dBFS; LiveKit and Pipecat both close at
133
+ * 0.8 s.
134
+ */
135
+ const DEFAULT_GATE_THRESHOLD_RMS = .004;
136
+ const DEFAULT_GATE_QUIET_MS = 800;
137
+ const SUBFRAME_BYTES = 160;
138
+ const BYTES_PER_MS = 8;
139
+ var SpeechGate = class {
140
+ threshold;
141
+ quietLimitMs;
142
+ open = false;
143
+ quietMs = 0;
144
+ utteranceMs = 0;
145
+ constructor(options = {}) {
146
+ this.threshold = options.thresholdRms ?? .004;
147
+ this.quietLimitMs = options.quietMs ?? 800;
148
+ }
149
+ get isOpen() {
150
+ return this.open;
151
+ }
152
+ /** Feed one output delta; returns the transitions it caused, in order. */
153
+ feed(bytes) {
154
+ const events = [];
155
+ for (let offset = 0; offset < bytes.length; offset += SUBFRAME_BYTES) {
156
+ const frame = bytes.subarray(offset, Math.min(offset + SUBFRAME_BYTES, bytes.length));
157
+ const frameMs = frame.length / BYTES_PER_MS;
158
+ if (isSpeech(frame, this.threshold)) {
159
+ if (!this.open) {
160
+ this.open = true;
161
+ this.utteranceMs = 0;
162
+ events.push({ type: "open" });
163
+ }
164
+ this.quietMs = 0;
165
+ this.utteranceMs += frameMs;
166
+ } else if (this.open) {
167
+ this.quietMs += frameMs;
168
+ this.utteranceMs += frameMs;
169
+ if (this.quietMs >= this.quietLimitMs) {
170
+ events.push({
171
+ type: "close",
172
+ utteranceMs: this.utteranceMs - this.quietMs
173
+ });
174
+ this.open = false;
175
+ this.quietMs = 0;
176
+ this.utteranceMs = 0;
177
+ }
178
+ }
179
+ }
180
+ return events;
181
+ }
182
+ /** Force-close an open utterance (stream stalled, session closing). */
183
+ close() {
184
+ if (!this.open) return null;
185
+ const event = {
186
+ type: "close",
187
+ utteranceMs: this.utteranceMs - this.quietMs
188
+ };
189
+ this.open = false;
190
+ this.quietMs = 0;
191
+ this.utteranceMs = 0;
192
+ return event;
193
+ }
194
+ };
195
+ /** μ-law digital zero is 0xFF (some encoders emit 0x7F for negative zero). */
196
+ function isDigitalSilence(bytes) {
197
+ for (let i = 0; i < bytes.length; i++) {
198
+ const b = bytes[i];
199
+ if (b !== 255 && b !== 127) return false;
200
+ }
201
+ return true;
202
+ }
203
+ function isSpeech(frame, threshold) {
204
+ if (frame.length === 0 || isDigitalSilence(frame)) return false;
205
+ const pcm = mulawToPcm16(frame);
206
+ let acc = 0;
207
+ for (let i = 0; i < pcm.length; i++) {
208
+ const v = pcm[i] / 32768;
209
+ acc += v * v;
210
+ }
211
+ return Math.sqrt(acc / pcm.length) >= threshold;
212
+ }
213
+ //#endregion
214
+ //#region src/providers/gpt-live/transcript-grouper.ts
215
+ var TranscriptGrouper = class {
216
+ options;
217
+ current = null;
218
+ idleTimer = null;
219
+ constructor(options) {
220
+ this.options = options;
221
+ }
222
+ push(delta, startMs, endMs) {
223
+ if (this.current && startMs - this.current.endMs > this.options.gapMs) this.flush();
224
+ if (!this.current) this.current = {
225
+ text: "",
226
+ startMs,
227
+ endMs,
228
+ tag: this.options.tagFor?.()
229
+ };
230
+ this.current.text += delta;
231
+ this.current.endMs = Math.max(this.current.endMs, endMs);
232
+ this.armIdle();
233
+ }
234
+ /** Close the open turn now (session ending, utterance boundary reached). */
235
+ flush() {
236
+ this.clearIdle();
237
+ const turn = this.current;
238
+ this.current = null;
239
+ if (!turn) return;
240
+ const text = turn.text.trim();
241
+ if (text.length === 0) return;
242
+ this.options.onTurn({
243
+ ...turn,
244
+ text
245
+ });
246
+ }
247
+ dispose() {
248
+ this.clearIdle();
249
+ this.current = null;
250
+ }
251
+ armIdle() {
252
+ this.clearIdle();
253
+ this.idleTimer = setTimeout(() => {
254
+ this.idleTimer = null;
255
+ this.flush();
256
+ }, this.options.idleMs);
257
+ this.idleTimer.unref?.();
258
+ }
259
+ clearIdle() {
260
+ if (this.idleTimer) {
261
+ clearTimeout(this.idleTimer);
262
+ this.idleTimer = null;
263
+ }
264
+ }
265
+ };
266
+ //#endregion
267
+ //#region src/providers/gpt-live/GptLiveProvider.ts
268
+ /**
269
+ * GPT-Live provider (`/v1/live/sessions`, raw WebSocket) — OpenAI's
270
+ * full-duplex speech-to-speech model. A different API from Realtime, not a
271
+ * new Realtime model: its own handshake (`session.start` → `session.started`),
272
+ * its own events, and a different division of labour that this provider
273
+ * translates into the engine's normalized contract:
274
+ *
275
+ * - **Turn-taking is the model's.** It listens while it speaks and stops on
276
+ * its own when the caller talks. There is no VAD config, no cancel, no
277
+ * truncate, no speech_started/stopped; `capabilities.turnTaking: 'model'`
278
+ * tells the engine to keep its hands off (see parity tests).
279
+ * - **Output is a continuous real-time stream, silence included** (100 ms
280
+ * μ-law deltas, digital 0xFF when quiet). Response boundaries are
281
+ * synthesized by a speech gate on the audio itself (`speech-gate.ts`);
282
+ * silence between utterances is not forwarded.
283
+ * - **The backend does the thinking.** Tools are declared on a Responses
284
+ * model (`delegation.responses`), calls arrive wrapped in `response.event`
285
+ * envelopes, results go back as `response.item.create` + one
286
+ * `response.create`. The voice keeps talking meanwhile
287
+ * (`capabilities.decoupledBackend`).
288
+ * - **Text reaches the model only through appends** (≤ 500 tokens each):
289
+ * instructions (policy), thinking (quiet context), commentary (say this).
290
+ * `createResponse({ instructions })` maps to commentary — field-tested as
291
+ * the only append that reliably produces speech on demand (Sept 2026).
292
+ * - **Instructions, voice and history are immutable after start** — handoffs
293
+ * reconnect and seed the attributed transcript via `session.input`
294
+ * (`capabilities.startupHistory`).
295
+ * - **Billing is per second of session**, reported as cumulative
296
+ * `session.usage.updated` ticks; `close()` sends `session.close` and waits
297
+ * for `session.closed` so the final usage is confirmed.
298
+ */
299
+ const GPT_LIVE_DEFAULT_BASE_URL = "wss://api.openai.com/v1/live/sessions";
300
+ const NON_RETRIABLE_CLOSE_CODES = /* @__PURE__ */ new Set([
301
+ 1002,
302
+ 1003,
303
+ 1007,
304
+ 1008
305
+ ]);
306
+ /** Appends are capped at 500 tokens; split conservatively (dense scripts run ~2.5 chars/token). */
307
+ const APPEND_MAX_CHARS = 1200;
308
+ const TRANSCRIPT_IDLE_EXTRA_MS = 300;
309
+ const GATE_STALL_EXTRA_MS = 500;
310
+ const ACK_TYPES = {
311
+ "session.instructions.append": "session.instructions.appended",
312
+ "session.thinking.append": "session.thinking.appended",
313
+ "session.commentary.append": "session.commentary.appended",
314
+ "session.update": "session.updated",
315
+ "session.input_audio.mute": "session.input_audio.muted",
316
+ "session.input_audio.unmute": "session.input_audio.unmuted"
317
+ };
318
+ let eventSeq = 0;
319
+ const nextEventId = (prefix) => `${prefix}_${++eventSeq}`;
320
+ var GptLiveProvider = class extends BaseRealtimeProvider {
321
+ name;
322
+ capabilities = {
323
+ truncate: false,
324
+ sessionUpdate: false,
325
+ voiceChangeMidSession: false,
326
+ transcodeRequired: false,
327
+ resumption: false,
328
+ agentTranscriptDeltas: true,
329
+ vadInterruptControl: false,
330
+ turnTaking: "model",
331
+ startupHistory: true,
332
+ decoupledBackend: true
333
+ };
334
+ config;
335
+ logger;
336
+ ws = null;
337
+ ready = false;
338
+ intentionalClose = false;
339
+ sessionInit = null;
340
+ /** Server-assigned session id (sideband attach, forking, recording download). */
341
+ sessionId = null;
342
+ /** Unix seconds at which the server expires the session (120 min at launch). */
343
+ expiresAt = null;
344
+ gate;
345
+ gateStallTimer = null;
346
+ utteranceCounter = 0;
347
+ currentUtteranceId = null;
348
+ lastUtteranceId = null;
349
+ inputTranscript;
350
+ outputTranscript;
351
+ acks = /* @__PURE__ */ new Map();
352
+ seenCalls = /* @__PURE__ */ new Set();
353
+ sessionClosed = null;
354
+ closeListeners = [];
355
+ constructor(config, logger = noopLogger) {
356
+ super();
357
+ this.config = config;
358
+ this.logger = logger;
359
+ this.name = config.providerName ?? "gpt-live";
360
+ this.gate = new SpeechGate(config.speechGate);
361
+ const gapMs = config.transcriptGapMs ?? 800;
362
+ this.inputTranscript = new TranscriptGrouper({
363
+ gapMs,
364
+ idleMs: gapMs + TRANSCRIPT_IDLE_EXTRA_MS,
365
+ onTurn: (turn) => this.emit("userTranscript", { text: turn.text })
366
+ });
367
+ this.outputTranscript = new TranscriptGrouper({
368
+ gapMs,
369
+ idleMs: gapMs + TRANSCRIPT_IDLE_EXTRA_MS,
370
+ tagFor: () => this.currentUtteranceId ?? this.lastUtteranceId ?? void 0,
371
+ onTurn: (turn) => this.emit("agentTranscript", {
372
+ responseId: turn.tag ?? "",
373
+ text: turn.text
374
+ })
375
+ });
376
+ }
377
+ get isConnected() {
378
+ return this.ready && this.ws?.readyState === WebSocket$1.OPEN;
379
+ }
380
+ async connect(init) {
381
+ if (this.ws) await this.close();
382
+ this.sessionInit = init;
383
+ this.intentionalClose = false;
384
+ this.ready = false;
385
+ this.sessionClosed = null;
386
+ this.sessionId = null;
387
+ this.expiresAt = null;
388
+ this.resetUtteranceState();
389
+ if (init.vad !== void 0 || init.transcription !== void 0 || init.temperature !== void 0) this.logger.debug("gpt-live: vad/transcription/temperature are model-owned and ignored");
390
+ const startId = nextEventId("start");
391
+ const { frame, droppedHistory } = buildSessionStart(init, this.sessionConfig(), startId, this.config.model);
392
+ if (droppedHistory > 0) this.logger.warn("gpt-live: startup history trimmed to the API bounds", { dropped: droppedHistory });
393
+ const ws = new WebSocket$1(this.config.baseUrl ?? "wss://api.openai.com/v1/live/sessions", {
394
+ headers: {
395
+ Authorization: `Bearer ${this.config.apiKey}`,
396
+ ...this.config.headers
397
+ },
398
+ perMessageDeflate: false
399
+ });
400
+ this.ws = ws;
401
+ await new Promise((resolve, reject) => {
402
+ const timeoutMs = this.config.connectTimeoutMs ?? 15e3;
403
+ const timer = setTimeout(() => fail(/* @__PURE__ */ new Error(`${this.name} session not started within ${timeoutMs}ms`)), timeoutMs);
404
+ timer.unref?.();
405
+ let settled = false;
406
+ const fail = (error) => {
407
+ if (settled) return;
408
+ settled = true;
409
+ clearTimeout(timer);
410
+ try {
411
+ ws.close();
412
+ } catch {}
413
+ reject(error);
414
+ };
415
+ ws.on("unexpected-response", (_request, response) => {
416
+ let body = "";
417
+ response.setEncoding("utf8");
418
+ response.on("data", (chunk) => {
419
+ if (body.length < 512) body += chunk;
420
+ });
421
+ response.on("end", () => {
422
+ const detail = body.trim().slice(0, 500);
423
+ this.logger.error("provider rejected the WebSocket upgrade", {
424
+ status: response.statusCode,
425
+ body: detail
426
+ });
427
+ fail(/* @__PURE__ */ new Error(`${this.name} rejected the WebSocket upgrade: HTTP ${response.statusCode}${detail ? ` — ${detail}` : ""}`));
428
+ });
429
+ });
430
+ ws.on("open", () => {
431
+ this.emit("open");
432
+ this.send(frame);
433
+ });
434
+ ws.on("message", (raw) => {
435
+ const event = this.parseEvent(raw);
436
+ if (!event) return;
437
+ if (!settled) {
438
+ if (event.type === "session.started") {
439
+ settled = true;
440
+ clearTimeout(timer);
441
+ this.sessionId = event.session?.id ?? null;
442
+ this.expiresAt = typeof event.session?.expires_at === "number" ? event.session.expires_at : null;
443
+ this.ready = true;
444
+ this.logger.info("gpt-live session started", {
445
+ sessionId: this.sessionId,
446
+ expiresAt: this.expiresAt ? (/* @__PURE__ */ new Date(this.expiresAt * 1e3)).toISOString() : void 0
447
+ });
448
+ resolve();
449
+ return;
450
+ }
451
+ if (event.type === "error") {
452
+ fail(/* @__PURE__ */ new Error(`${this.name} session.start rejected: ${JSON.stringify(event.error ?? event)}`));
453
+ return;
454
+ }
455
+ return;
456
+ }
457
+ this.handleEvent(event);
458
+ });
459
+ ws.on("error", (error) => {
460
+ const err = error instanceof Error ? error : new Error(String(error));
461
+ if (!settled) fail(err);
462
+ else this.emit("error", err);
463
+ });
464
+ ws.on("close", (code, reasonBuf) => {
465
+ const reason = reasonBuf?.toString();
466
+ this.ready = false;
467
+ this.failPendingAcks();
468
+ this.finishUtteranceOnClose();
469
+ const listeners = this.closeListeners;
470
+ this.closeListeners = [];
471
+ for (const listener of listeners) listener();
472
+ if (!settled) {
473
+ fail(/* @__PURE__ */ new Error(`${this.name} socket closed during setup (${code} ${reason ?? ""})`));
474
+ return;
475
+ }
476
+ this.emit("close", {
477
+ code,
478
+ reason,
479
+ retriable: this.isRetriableClose(code)
480
+ });
481
+ });
482
+ });
483
+ }
484
+ async close() {
485
+ this.intentionalClose = true;
486
+ this.ready = false;
487
+ const ws = this.ws;
488
+ this.ws = null;
489
+ this.inputTranscript.dispose();
490
+ this.outputTranscript.dispose();
491
+ this.clearGateStall();
492
+ if (!ws || ws.readyState === WebSocket$1.CLOSED) return;
493
+ await new Promise((resolve) => {
494
+ const timer = setTimeout(() => finish(), this.config.closeTimeoutMs ?? 3e3);
495
+ timer.unref?.();
496
+ let done = false;
497
+ const finish = () => {
498
+ if (done) return;
499
+ done = true;
500
+ clearTimeout(timer);
501
+ try {
502
+ if (ws.readyState === WebSocket$1.OPEN || ws.readyState === WebSocket$1.CONNECTING) ws.close(1e3);
503
+ } catch {}
504
+ setTimeout(() => {
505
+ try {
506
+ ws.terminate();
507
+ } catch {}
508
+ }, 1e3).unref?.();
509
+ resolve();
510
+ };
511
+ this.closeListeners.push(finish);
512
+ if (ws.readyState === WebSocket$1.OPEN) try {
513
+ ws.send(JSON.stringify({
514
+ type: "session.close",
515
+ event_id: nextEventId("close")
516
+ }));
517
+ } catch {
518
+ finish();
519
+ }
520
+ else finish();
521
+ });
522
+ }
523
+ sendAudio(base64Mulaw) {
524
+ if (!this.isConnected) return;
525
+ this.send({
526
+ type: "session.input_audio.append",
527
+ audio: base64Mulaw
528
+ });
529
+ }
530
+ /**
531
+ * Text has three doors into a GPT-Live session, by intent rather than by
532
+ * conversation role: `system` → instructions (behaviour), `user` → thinking
533
+ * (quiet context: keypad entries, deferred results — the model decides how
534
+ * to react), `assistant` → thinking as well, worded as something already
535
+ * said (commentary would make the model say it again).
536
+ */
537
+ sendText(text, options = {}) {
538
+ const role = options.role ?? "user";
539
+ if (role === "system") this.append("session.instructions.append", text);
540
+ else if (role === "assistant") this.append("session.thinking.append", `You already said this to the caller earlier: "${text}"`);
541
+ else this.append("session.thinking.append", text);
542
+ }
543
+ sendToolResult(callId, output, options = {}) {
544
+ this.send({
545
+ type: "response.item.create",
546
+ event_id: nextEventId("tool"),
547
+ item: {
548
+ type: "function_call_output",
549
+ call_id: callId,
550
+ output: typeof output === "string" ? output : JSON.stringify(output ?? null)
551
+ }
552
+ });
553
+ if (options.triggerResponse !== false) this.send({
554
+ type: "response.create",
555
+ event_id: nextEventId("continue")
556
+ });
557
+ }
558
+ /**
559
+ * "Speak now" has no direct verb on this API. Commentary — information the
560
+ * model should say aloud, paraphrasing allowed — is the append that
561
+ * produced speech on demand in every field test, greeting and goodbye
562
+ * alike; an instruction-shaped text is followed rather than read out.
563
+ */
564
+ createResponse(options = {}) {
565
+ if (options.instructions) this.append("session.commentary.append", options.instructions);
566
+ else this.append("session.instructions.append", "Respond to the caller now, without waiting for them to speak.");
567
+ }
568
+ /**
569
+ * Only the backend delegation can change mid-session (`session.update` is
570
+ * sparse and limited to `delegation.responses`): tool lists land there;
571
+ * instructions / voice / vad are immutable and are reported, not applied.
572
+ */
573
+ async updateSession(patch, options = {}) {
574
+ if (!this.sessionInit) throw new Error("updateSession before connect");
575
+ const ignored = Object.keys(patch).filter((key) => key !== "tools" && key !== "providerOptions");
576
+ if (ignored.length > 0) this.logger.warn("gpt-live: session fields are immutable after start — ignored", { fields: ignored });
577
+ this.sessionInit = {
578
+ ...this.sessionInit,
579
+ ...patch
580
+ };
581
+ let responses = {};
582
+ if (patch.tools) responses.tools = [...patch.tools.map(toBackendTool), ...this.config.delegation?.extraTools ?? []];
583
+ const nativeResponses = patch.providerOptions?.delegation?.responses;
584
+ if (nativeResponses && typeof nativeResponses === "object") responses = deepMerge(responses, nativeResponses);
585
+ if (Object.keys(responses).length === 0) return false;
586
+ if (!this.isConnected) return false;
587
+ const eventId = nextEventId("update");
588
+ const acked = this.awaitAck(eventId, ACK_TYPES["session.update"]);
589
+ this.send({
590
+ type: "session.update",
591
+ event_id: eventId,
592
+ session: { delegation: {
593
+ type: "responses",
594
+ responses
595
+ } }
596
+ });
597
+ return options.awaitAck ? acked : true;
598
+ }
599
+ handleEvent(event) {
600
+ switch (event.type) {
601
+ case "session.output_audio.delta":
602
+ if (typeof event.delta !== "string" || event.delta.length === 0) break;
603
+ this.handleOutputAudio(event.delta);
604
+ break;
605
+ case "session.input_transcript.delta":
606
+ if (typeof event.delta === "string") this.inputTranscript.push(event.delta, numberOr(event.start_ms, 0), numberOr(event.end_ms, 0));
607
+ break;
608
+ case "session.output_transcript.delta":
609
+ if (typeof event.delta === "string") {
610
+ this.emit("agentTranscriptDelta", {
611
+ responseId: this.currentUtteranceId ?? this.lastUtteranceId ?? "",
612
+ delta: event.delta
613
+ });
614
+ this.outputTranscript.push(event.delta, numberOr(event.start_ms, 0), numberOr(event.end_ms, 0));
615
+ }
616
+ break;
617
+ case "session.delegation.created":
618
+ this.logger.debug("gpt-live delegation created", {
619
+ id: event.delegation?.id,
620
+ target: event.delegation?.target,
621
+ responseId: event.delegation?.response_id
622
+ });
623
+ break;
624
+ case "response.event":
625
+ this.handleBackendEvent(event.event ?? {}, event.delegation_id);
626
+ break;
627
+ case "session.usage.updated": {
628
+ const seconds = event.usage?.seconds;
629
+ if (typeof seconds === "number") this.emit("usage", {
630
+ inputTokens: 0,
631
+ outputTokens: 0,
632
+ totalTokens: 0,
633
+ audioSeconds: seconds,
634
+ raw: event
635
+ });
636
+ break;
637
+ }
638
+ case "session.instructions.appended":
639
+ case "session.thinking.appended":
640
+ case "session.commentary.appended":
641
+ case "session.updated":
642
+ case "session.input_audio.muted":
643
+ case "session.input_audio.unmuted":
644
+ this.resolveAck(event.client_event_id, true);
645
+ break;
646
+ case "session.closed": {
647
+ const seconds = event.usage?.seconds;
648
+ this.sessionClosed = {
649
+ reason: event.reason,
650
+ usageSeconds: typeof seconds === "number" ? seconds : void 0
651
+ };
652
+ this.logger.info("gpt-live session closed", {
653
+ reason: event.reason,
654
+ usageSeconds: seconds
655
+ });
656
+ if (typeof seconds === "number") this.emit("usage", {
657
+ inputTokens: 0,
658
+ outputTokens: 0,
659
+ totalTokens: 0,
660
+ audioSeconds: seconds,
661
+ raw: event
662
+ });
663
+ break;
664
+ }
665
+ case "error":
666
+ if (event.error?.client_event_id) this.resolveAck(event.error.client_event_id, false);
667
+ this.logger.warn("provider error event", { error: event.error });
668
+ this.emit("error", /* @__PURE__ */ new Error(`${this.name} error: ${JSON.stringify(event.error ?? event)}`));
669
+ break;
670
+ case "info": this.logger.debug("gpt-live info", {
671
+ code: event.code,
672
+ message: event.message
673
+ });
674
+ }
675
+ }
676
+ handleOutputAudio(delta) {
677
+ const bytes = Buffer.from(delta, "base64");
678
+ const wasOpen = this.gate.isOpen;
679
+ const events = this.gate.feed(bytes);
680
+ let forwardId = wasOpen ? this.currentUtteranceId : null;
681
+ let close = null;
682
+ for (const gateEvent of events) if (gateEvent.type === "open") {
683
+ this.beginUtterance();
684
+ forwardId = this.currentUtteranceId;
685
+ } else close = gateEvent;
686
+ if (forwardId) this.emit("audio", {
687
+ base64Mulaw: delta,
688
+ responseId: forwardId
689
+ });
690
+ if (close) this.endUtterance();
691
+ else if (this.gate.isOpen) this.armGateStall();
692
+ }
693
+ handleBackendEvent(inner, delegationId) {
694
+ const type = inner.type ?? "";
695
+ if (type === "response.output_item.done" && inner.item?.type === "function_call") {
696
+ const item = inner.item;
697
+ const callId = item.call_id ?? item.id ?? `call_${Date.now()}`;
698
+ if (this.seenCalls.has(callId)) return;
699
+ this.seenCalls.add(callId);
700
+ if (this.seenCalls.size > 1e3) this.seenCalls.delete(this.seenCalls.values().next().value);
701
+ this.emit("toolCall", {
702
+ id: callId,
703
+ name: item.name,
704
+ argumentsJson: typeof item.arguments === "string" ? item.arguments : "{}",
705
+ responseId: delegationId,
706
+ itemId: item.id
707
+ });
708
+ return;
709
+ }
710
+ if (type === "response.completed" || type === "response.done") {
711
+ const usage = normalizeUsage(inner.response?.usage);
712
+ if (usage) this.emit("usage", usage);
713
+ return;
714
+ }
715
+ if (type === "response.failed" || type === "response.incomplete") this.logger.warn("gpt-live backend response did not complete", {
716
+ type,
717
+ delegationId,
718
+ error: inner.response?.error
719
+ });
720
+ }
721
+ beginUtterance() {
722
+ this.currentUtteranceId = `live_utt_${++this.utteranceCounter}`;
723
+ this.lastUtteranceId = this.currentUtteranceId;
724
+ this.emit("responseStarted", { responseId: this.currentUtteranceId });
725
+ }
726
+ endUtterance() {
727
+ this.clearGateStall();
728
+ const id = this.currentUtteranceId;
729
+ this.currentUtteranceId = null;
730
+ if (id) this.emit("responseDone", { responseId: id });
731
+ }
732
+ /** The stream is real-time: no delta for a quiet window means it stalled — close the utterance. */
733
+ armGateStall() {
734
+ this.clearGateStall();
735
+ const quietMs = this.config.speechGate?.quietMs ?? 800;
736
+ this.gateStallTimer = setTimeout(() => {
737
+ this.gateStallTimer = null;
738
+ if (this.gate.close()) this.endUtterance();
739
+ }, quietMs + GATE_STALL_EXTRA_MS);
740
+ this.gateStallTimer.unref?.();
741
+ }
742
+ clearGateStall() {
743
+ if (this.gateStallTimer) {
744
+ clearTimeout(this.gateStallTimer);
745
+ this.gateStallTimer = null;
746
+ }
747
+ }
748
+ finishUtteranceOnClose() {
749
+ this.clearGateStall();
750
+ if (this.gate.close()) this.endUtterance();
751
+ this.inputTranscript.flush();
752
+ this.outputTranscript.flush();
753
+ }
754
+ resetUtteranceState() {
755
+ this.clearGateStall();
756
+ this.gate.close();
757
+ this.currentUtteranceId = null;
758
+ this.lastUtteranceId = null;
759
+ this.seenCalls.clear();
760
+ }
761
+ /** Send `content` as one or more appends (500-token cap); resolves with the last chunk's ack. */
762
+ async append(type, content, delegationId = null) {
763
+ if (!this.isConnected) return false;
764
+ const chunks = splitForAppend(content);
765
+ if (chunks.length > 1) this.logger.warn("gpt-live: append split to respect the 500-token cap", {
766
+ type,
767
+ chunks: chunks.length
768
+ });
769
+ let acked = false;
770
+ for (const chunk of chunks) {
771
+ const eventId = nextEventId("append");
772
+ const ack = this.awaitAck(eventId, ACK_TYPES[type]);
773
+ this.send({
774
+ type,
775
+ event_id: eventId,
776
+ delegation_id: delegationId,
777
+ content: chunk
778
+ });
779
+ acked = await ack;
780
+ if (!acked) break;
781
+ }
782
+ return acked;
783
+ }
784
+ awaitAck(eventId, ackType) {
785
+ return new Promise((resolve) => {
786
+ const timer = setTimeout(() => {
787
+ if (this.acks.delete(eventId)) {
788
+ this.logger.warn("gpt-live: no acknowledgement for client event", {
789
+ eventId,
790
+ ackType
791
+ });
792
+ resolve(false);
793
+ }
794
+ }, this.config.ackTimeoutMs ?? 5e3);
795
+ timer.unref?.();
796
+ this.acks.set(eventId, {
797
+ ackType,
798
+ resolve,
799
+ timer
800
+ });
801
+ });
802
+ }
803
+ resolveAck(clientEventId, acked) {
804
+ if (typeof clientEventId !== "string") return;
805
+ const waiter = this.acks.get(clientEventId);
806
+ if (!waiter) return;
807
+ this.acks.delete(clientEventId);
808
+ clearTimeout(waiter.timer);
809
+ waiter.resolve(acked);
810
+ }
811
+ failPendingAcks() {
812
+ for (const [id, waiter] of this.acks) {
813
+ clearTimeout(waiter.timer);
814
+ waiter.resolve(false);
815
+ this.acks.delete(id);
816
+ }
817
+ }
818
+ sessionConfig() {
819
+ return {
820
+ defaultVoice: this.config.voice,
821
+ delegation: this.config.delegation,
822
+ store: this.config.store,
823
+ extraSessionOptions: this.config.extraSessionOptions,
824
+ historyMaxMessages: this.config.historyMaxMessages,
825
+ historyMaxChars: this.config.historyMaxChars
826
+ };
827
+ }
828
+ isRetriableClose(code) {
829
+ if (this.intentionalClose) return false;
830
+ if (NON_RETRIABLE_CLOSE_CODES.has(code)) return false;
831
+ const reason = this.sessionClosed?.reason;
832
+ if (reason && reason !== "expired" && reason !== "connection_lost") return false;
833
+ return true;
834
+ }
835
+ parseEvent(raw) {
836
+ try {
837
+ return JSON.parse(raw.toString());
838
+ } catch {
839
+ this.logger.warn("unparseable provider frame");
840
+ return null;
841
+ }
842
+ }
843
+ send(payload) {
844
+ if (this.ws?.readyState !== WebSocket$1.OPEN) return;
845
+ try {
846
+ this.ws.send(JSON.stringify(payload));
847
+ } catch (error) {
848
+ this.emit("error", error instanceof Error ? error : new Error(String(error)));
849
+ }
850
+ }
851
+ };
852
+ function numberOr(value, fallback) {
853
+ return typeof value === "number" ? value : fallback;
854
+ }
855
+ /** Split on whitespace so no chunk exceeds the per-append cap. */
856
+ function splitForAppend(content, maxChars = APPEND_MAX_CHARS) {
857
+ const text = content.trim();
858
+ if (text.length <= maxChars) return [text];
859
+ const chunks = [];
860
+ let rest = text;
861
+ while (rest.length > maxChars) {
862
+ let cut = rest.lastIndexOf(" ", maxChars);
863
+ if (cut < maxChars / 2) cut = maxChars;
864
+ chunks.push(rest.slice(0, cut).trim());
865
+ rest = rest.slice(cut).trim();
866
+ }
867
+ if (rest.length) chunks.push(rest);
868
+ return chunks;
869
+ }
870
+ //#endregion
871
+ //#region src/gpt-live.ts
872
+ /** OpenAI GPT-Live provider (full-duplex Live API) — `realtime-voice-agents/gpt-live`. */
873
+ /** Env vars checked (in order) when no explicit apiKey is passed — the same project key as Realtime. */
874
+ const GPT_LIVE_KEY_ENV_VARS = [
875
+ "OPENAI_API_KEY",
876
+ "OPENAI_KEY",
877
+ "OPEN_AI_API_KEY"
878
+ ];
879
+ const GPT_LIVE_DEFAULT_MODEL = "gpt-live-1";
880
+ const GPT_LIVE_DEFAULT_VOICE = "marin";
881
+ /** Built-in voices accepted by the Live API (the SDK's enum, Sept 2026). */
882
+ const GPT_LIVE_VOICES = [
883
+ "marin",
884
+ "cedar",
885
+ "alloy",
886
+ "ash",
887
+ "ballad",
888
+ "beacon",
889
+ "bossa",
890
+ "cinder",
891
+ "coral",
892
+ "delta",
893
+ "echo",
894
+ "gleam",
895
+ "meridian",
896
+ "quartz",
897
+ "ripple",
898
+ "sage",
899
+ "shimmer",
900
+ "stone",
901
+ "tempo",
902
+ "verse",
903
+ "vesper",
904
+ "willow"
905
+ ];
906
+ /**
907
+ * Create a GPT-Live provider factory for the bridge (`provider: gptLive({...})`).
908
+ *
909
+ * Credentials are resolved per call, when the factory runs (see
910
+ * `openaiRealtime` — a missing key fails that call's connect so a fallback
911
+ * chain can absorb it instead of crashing config construction).
912
+ */
913
+ function gptLive(options = {}) {
914
+ const config = {
915
+ model: options.model ?? "gpt-live-1",
916
+ voice: options.voice ?? "marin",
917
+ delegation: options.delegation,
918
+ baseUrl: options.baseUrl,
919
+ headers: options.headers,
920
+ store: options.store,
921
+ extraSessionOptions: options.sessionOptions,
922
+ connectTimeoutMs: options.connectTimeoutMs,
923
+ speechGate: options.speechGate,
924
+ transcriptGapMs: options.transcriptGapMs
925
+ };
926
+ return ({ logger }) => {
927
+ const apiKey = resolveApiKey(options.apiKey, GPT_LIVE_KEY_ENV_VARS);
928
+ if (!apiKey) throw new Error(`gptLive: apiKey missing (pass apiKey or set one of ${GPT_LIVE_KEY_ENV_VARS.join("/")})`);
929
+ return new GptLiveProvider({
930
+ ...config,
931
+ apiKey
932
+ }, logger);
933
+ };
934
+ }
935
+ //#endregion
936
+ export { DEFAULT_GATE_QUIET_MS, DEFAULT_GATE_THRESHOLD_RMS, GPT_LIVE_AUDIO_FORMAT, GPT_LIVE_DEFAULT_BACKEND_MODEL, GPT_LIVE_DEFAULT_BASE_URL, GPT_LIVE_DEFAULT_MODEL, GPT_LIVE_DEFAULT_VOICE, GPT_LIVE_KEY_ENV_VARS, GPT_LIVE_VOICES, GptLiveProvider, SpeechGate, buildDelegation, buildHistoryItems, buildSessionStart, gptLive, splitForAppend };