segmind 0.6.1 → 0.7.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.
@@ -1,4 +1,4 @@
1
- import { a as SessionTokenProvider, r as SessionState, E as EndReason, x as Usage, e as SessionCreatedEvent, f as AudioFormat, g as ServerEvent, o as ServerEventType, s as SessionUpdateParams, C as ClientEvent, d as SegmindError } from './errors-CcHEuSmR.cjs';
1
+ import { a as SessionTokenProvider, t as SessionState, E as EndReason, z as Usage, g as SessionCreatedEvent, h as AudioFormat, i as ServerEvent, q as ServerEventType, u as SessionUpdateParams, C as ClientEvent, d as SegmindError } from './errors-DsVQfts3.cjs';
2
2
 
3
3
  /**
4
4
  * A managed realtime session: one primitive, explicit states, typed events,
@@ -124,6 +124,8 @@ declare class RealtimeSession {
124
124
  get usage(): Usage | null;
125
125
  /** How the session ended (reason, usage, refusal code, close code), once closed. */
126
126
  get end(): SessionEnd | null;
127
+ /** The session options sent on the URL at open (`SessionOptions.params`). */
128
+ get params(): Readonly<Record<string, string>>;
127
129
  /** The `session.created` frame, once live. */
128
130
  get created(): SessionCreatedEvent | null;
129
131
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "segmind",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "description": "Official JavaScript SDK for the Segmind API: image, video, audio and LLM models from Node, browsers and React Native.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Segmind <support@segmind.com>",
@@ -1,186 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;// src/realtime/pcm.ts
2
- var SESSION_SAMPLE_RATE = 24e3;
3
- function pcmSeconds(byteLength, sampleRate = SESSION_SAMPLE_RATE) {
4
- return byteLength / (sampleRate * 2);
5
- }
6
- function encodePcm(pcm) {
7
- const bytes = pcm instanceof Int16Array ? new Uint8Array(pcm.buffer, pcm.byteOffset, pcm.byteLength) : new Uint8Array(pcm);
8
- let binary = "";
9
- const chunk = 32768;
10
- for (let i = 0; i < bytes.length; i += chunk) {
11
- binary += String.fromCharCode.apply(null, Array.from(bytes.subarray(i, i + chunk)));
12
- }
13
- return btoa(binary);
14
- }
15
- function decodePcm(base64) {
16
- const binary = atob(base64);
17
- const bytes = new Uint8Array(binary.length);
18
- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
19
- if (bytes.byteLength % 2) throw new Error("audio payload is not whole 16-bit samples");
20
- return new Int16Array(bytes.buffer);
21
- }
22
- function floatToInt16(samples) {
23
- const out = new Int16Array(samples.length);
24
- for (let i = 0; i < samples.length; i++) {
25
- const s = Math.max(-1, Math.min(1, _nullishCoalesce(samples[i], () => ( 0))));
26
- out[i] = s < 0 ? s * 32768 : s * 32767;
27
- }
28
- return out;
29
- }
30
- function rms(pcm) {
31
- if (pcm.length === 0) return 0;
32
- let sum = 0;
33
- for (let i = 0; i < pcm.length; i++) {
34
- const s = _nullishCoalesce(pcm[i], () => ( 0));
35
- sum += s * s;
36
- }
37
- return Math.sqrt(sum / pcm.length);
38
- }
39
-
40
- // src/realtime/vad.ts
41
- var EnergyVad = (_class = class {
42
-
43
-
44
-
45
-
46
- __init() {this.speaking = false}
47
- __init2() {this.loudRun = 0}
48
- __init3() {this.silenceMs = 0}
49
- __init4() {this._level = 0}
50
- constructor(options = {}) {;_class.prototype.__init.call(this);_class.prototype.__init2.call(this);_class.prototype.__init3.call(this);_class.prototype.__init4.call(this);
51
- this.threshold = _nullishCoalesce(options.threshold, () => ( 700));
52
- this.startFrames = _nullishCoalesce(options.startFrames, () => ( 2));
53
- this.endSilenceMs = _nullishCoalesce(options.endSilenceMs, () => ( 600));
54
- this.sampleRate = _nullishCoalesce(options.sampleRate, () => ( 24e3));
55
- }
56
- /** The last frame's RMS, for a level meter. */
57
- get level() {
58
- return this._level;
59
- }
60
- get isSpeaking() {
61
- return this.speaking;
62
- }
63
- feed(frame) {
64
- const level = rms(frame);
65
- this._level = level;
66
- const frameMs = frame.length / this.sampleRate * 1e3;
67
- const loud = level >= this.threshold;
68
- if (loud) {
69
- this.loudRun += 1;
70
- this.silenceMs = 0;
71
- if (!this.speaking && this.loudRun >= this.startFrames) {
72
- this.speaking = true;
73
- return "start";
74
- }
75
- return null;
76
- }
77
- this.loudRun = 0;
78
- if (this.speaking) {
79
- this.silenceMs += frameMs;
80
- if (this.silenceMs >= this.endSilenceMs) {
81
- this.speaking = false;
82
- this.silenceMs = 0;
83
- return "end";
84
- }
85
- }
86
- return null;
87
- }
88
- reset() {
89
- this.speaking = false;
90
- this.loudRun = 0;
91
- this.silenceMs = 0;
92
- }
93
- }, _class);
94
-
95
- // src/realtime/barge-in.ts
96
- function attachBargeIn(options) {
97
- const { session, capture, playback } = options;
98
- const format = session.audio;
99
- if (format) {
100
- for (const [name, rate] of [
101
- ["capture", capture.sampleRate],
102
- ["playback", playback.sampleRate]
103
- ]) {
104
- if (rate !== format.rate) {
105
- throw new Error(`${name} runs at ${rate} Hz but the session's audio is ${format.rate} Hz`);
106
- }
107
- }
108
- }
109
- const vad = options.localVad === false ? null : new EnergyVad(typeof options.localVad === "object" ? options.localVad : {});
110
- let currentTurn = null;
111
- let replying = false;
112
- const cut = () => {
113
- playback.flush();
114
- if (replying) {
115
- session.interrupt();
116
- replying = false;
117
- }
118
- };
119
- const offFrame = capture.onFrame((frame) => {
120
- if (options.shouldSend && !options.shouldSend()) {
121
- if (_optionalChain([vad, 'optionalAccess', _ => _.isSpeaking])) {
122
- vad.reset();
123
- _optionalChain([options, 'access', _2 => _2.onLocalSpeech, 'optionalCall', _3 => _3(false)]);
124
- }
125
- return;
126
- }
127
- session.sendAudio(frame);
128
- if (!vad) return;
129
- const decision = vad.feed(frame);
130
- _optionalChain([options, 'access', _4 => _4.onLevel, 'optionalCall', _5 => _5(vad.level)]);
131
- if (decision === "start") {
132
- _optionalChain([options, 'access', _6 => _6.onLocalSpeech, 'optionalCall', _7 => _7(true)]);
133
- if (replying) cut();
134
- } else if (decision === "end") {
135
- _optionalChain([options, 'access', _8 => _8.onLocalSpeech, 'optionalCall', _9 => _9(false)]);
136
- }
137
- });
138
- const offEvent = session.onEvent((event) => {
139
- switch (event.type) {
140
- case "turn.started":
141
- currentTurn = event.turn_id;
142
- replying = true;
143
- break;
144
- case "audio.delta":
145
- if (event.turn_id === currentTurn) playback.enqueue(event.audio);
146
- break;
147
- case "turn.ended":
148
- if (event.turn_id === currentTurn) {
149
- replying = false;
150
- if (event.reason === "interrupted") playback.flush();
151
- }
152
- break;
153
- case "input.speech_started":
154
- if (replying) cut();
155
- else playback.flush();
156
- break;
157
- case "session.ended":
158
- playback.flush();
159
- replying = false;
160
- break;
161
- default:
162
- break;
163
- }
164
- });
165
- return {
166
- detach: () => {
167
- offFrame();
168
- offEvent();
169
- },
170
- get replying() {
171
- return replying;
172
- }
173
- };
174
- }
175
-
176
-
177
-
178
-
179
-
180
-
181
-
182
-
183
-
184
-
185
- exports.SESSION_SAMPLE_RATE = SESSION_SAMPLE_RATE; exports.pcmSeconds = pcmSeconds; exports.encodePcm = encodePcm; exports.decodePcm = decodePcm; exports.floatToInt16 = floatToInt16; exports.rms = rms; exports.EnergyVad = EnergyVad; exports.attachBargeIn = attachBargeIn;
186
- //# sourceMappingURL=chunk-HWZJ36WC.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/home/runner/work/segmind-js/segmind-js/packages/segmind/dist/chunk-HWZJ36WC.cjs","../src/realtime/pcm.ts","../src/realtime/v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;AACF,wBAAA;AACV,MAAA;AACA,MAAA;AACF,IAAA;AACkB,IAAA;AACR,IAAA;AACW,IAAA;AACH,oBAAA;AACD,IAAA;AACP,sBAAA;AACU,MAAA;AACT,IAAA;AACD,sBAAA;AACV,IAAA;AACD,EAAA;AAEgB,EAAA;AACK,IAAA;AACb,MAAA;AACW,QAAA;AACH,QAAA;AACX,QAAA;AACG,MAAA;AACO,QAAA;AACV,QAAA;AACG,MAAA;AACO,QAAA;AACG,UAAA;AACD,UAAA;AACZ,QAAA;AACA,QAAA;AACG,MAAA;AAEW,QAAA;AACA,QAAA;AACd,QAAA;AACG,MAAA;AACY,QAAA;AACJ,QAAA;AACX,QAAA;AACF,MAAA;AACE,QAAA;AACJ,IAAA;AACD,EAAA;AAEM,EAAA;AACS,IAAA;AACH,MAAA;AACA,MAAA;AACX,IAAA;AACe,IAAA;AACN,MAAA;AACT,IAAA;AACF,EAAA;AACF;AHiCyB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/segmind-js/segmind-js/packages/segmind/dist/chunk-HWZJ36WC.cjs","sourcesContent":[null,"/** PCM helpers shared by the session and the audio primitives. */\n\nexport const SESSION_SAMPLE_RATE = 24000;\n\nexport function pcmSeconds(byteLength: number, sampleRate = SESSION_SAMPLE_RATE): number {\n return byteLength / (sampleRate * 2);\n}\n\nexport function encodePcm(pcm: Int16Array | ArrayBuffer): string {\n const bytes =\n pcm instanceof Int16Array\n ? new Uint8Array(pcm.buffer, pcm.byteOffset, pcm.byteLength)\n : new Uint8Array(pcm);\n let binary = '';\n const chunk = 0x8000;\n for (let i = 0; i < bytes.length; i += chunk) {\n binary += String.fromCharCode.apply(null, Array.from(bytes.subarray(i, i + chunk)));\n }\n return btoa(binary);\n}\n\nexport function decodePcm(base64: string): Int16Array {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n if (bytes.byteLength % 2) throw new Error('audio payload is not whole 16-bit samples');\n return new Int16Array(bytes.buffer);\n}\n\n/** Float32 [-1, 1] → Int16 little-endian (the platform's byte order is little-endian everywhere a browser runs). */\nexport function floatToInt16(samples: Float32Array): Int16Array {\n const out = new Int16Array(samples.length);\n for (let i = 0; i < samples.length; i++) {\n const s = Math.max(-1, Math.min(1, samples[i] ?? 0));\n out[i] = s < 0 ? s * 0x8000 : s * 0x7fff;\n }\n return out;\n}\n\n/** Root mean square of a PCM frame, on the Int16 scale (0–32767). */\nexport function rms(pcm: Int16Array): number {\n if (pcm.length === 0) return 0;\n let sum = 0;\n for (let i = 0; i < pcm.length; i++) {\n const s = pcm[i] ?? 0;\n sum += s * s;\n }\n return Math.sqrt(sum / pcm.length);\n}\n","/**\n * A small energy-based voice activity detector, run on the client's own\n * microphone frames.\n *\n * Why it exists: the upstream's VAD reports that the user started speaking\n * only after a delay, and the upstream generates faster than real time, so a\n * short reply has been fully generated by then (the README has the figures).\n * Detecting speech locally lets the client flush playback and send\n * `interrupt` within one frame of the user opening their mouth.\n *\n * Pure: feed it frames, get `start` / `end` decisions. Measured in audio\n * time, not wall-clock time, so it behaves the same from a file as from a\n * microphone.\n */\n\nimport { rms } from './pcm';\n\nexport interface VadOptions {\n /** RMS on the Int16 scale above which a frame counts as speech. Default 700. */\n threshold?: number;\n /** Consecutive speech frames before `start`. Default 2 (200 ms at 100 ms frames). */\n startFrames?: number;\n /** Silent audio after speech before `end`. Default 600 ms. */\n endSilenceMs?: number;\n sampleRate?: number;\n}\n\nexport type VadDecision = 'start' | 'end' | null;\n\nexport class EnergyVad {\n private readonly threshold: number;\n private readonly startFrames: number;\n private readonly endSilenceMs: number;\n private readonly sampleRate: number;\n private speaking = false;\n private loudRun = 0;\n private silenceMs = 0;\n private _level = 0;\n\n constructor(options: VadOptions = {}) {\n this.threshold = options.threshold ?? 700;\n this.startFrames = options.startFrames ?? 2;\n this.endSilenceMs = options.endSilenceMs ?? 600;\n this.sampleRate = options.sampleRate ?? 24000;\n }\n\n /** The last frame's RMS, for a level meter. */\n get level(): number {\n return this._level;\n }\n\n get isSpeaking(): boolean {\n return this.speaking;\n }\n\n feed(frame: Int16Array): VadDecision {\n const level = rms(frame);\n this._level = level;\n const frameMs = (frame.length / this.sampleRate) * 1000;\n const loud = level >= this.threshold;\n if (loud) {\n this.loudRun += 1;\n this.silenceMs = 0;\n if (!this.speaking && this.loudRun >= this.startFrames) {\n this.speaking = true;\n return 'start';\n }\n return null;\n }\n this.loudRun = 0;\n if (this.speaking) {\n this.silenceMs += frameMs;\n if (this.silenceMs >= this.endSilenceMs) {\n this.speaking = false;\n this.silenceMs = 0;\n return 'end';\n }\n }\n return null;\n }\n\n reset(): void {\n this.speaking = false;\n this.loudRun = 0;\n this.silenceMs = 0;\n }\n}\n","/**\n * Wires a session, a microphone and a playback buffer into a conversation:\n * every mic frame goes to the session; incoming audio goes to playback;\n * the user speaking over a reply flushes playback and interrupts upstream.\n *\n * Two triggers end a reply early, and both flush: local speech detection\n * (fast — within a frame or two of the user speaking) and the server's own\n * `input.speech_started` (slower, but authoritative). Audio for a turn the\n * server has already ended is dropped on the floor rather than played late.\n */\n\nimport type { RealtimeSession } from './session';\nimport { EnergyVad, type VadOptions } from './vad';\n\n/**\n * Where microphone audio comes from: s16le frames at `sampleRate`. The\n * browser's `MicrophoneCapture` is one; a React Native module can be another.\n */\nexport interface AudioSource {\n readonly sampleRate: number;\n onFrame(listener: (frame: Int16Array) => void): () => void;\n}\n\n/** Where reply audio goes: base64 or raw s16le at `sampleRate`, flushed on barge-in. */\nexport interface AudioSink {\n readonly sampleRate: number;\n enqueue(audio: string | Int16Array): void;\n flush(): void;\n}\n\nexport interface BargeInOptions {\n session: RealtimeSession;\n capture: AudioSource;\n playback: AudioSink;\n /** Detect speech locally and interrupt before the upstream's VAD reports it. Default on. */\n localVad?: boolean | VadOptions;\n /** Called with the level meter value on every mic frame. */\n onLevel?: (rms: number) => void;\n /** Called when the local detector decides speech started / ended. */\n onLocalSpeech?: (speaking: boolean) => void;\n /**\n * Push-to-talk gate: when it returns false, microphone frames are dropped\n * (not sent, not fed to the detector) so the capture can stay running\n * between presses without the latency of reopening the device.\n */\n shouldSend?: () => boolean;\n}\n\nexport interface BargeIn {\n detach(): void;\n /** True while a reply is being delivered (between turn.started and turn.ended). */\n readonly replying: boolean;\n}\n\nexport function attachBargeIn(options: BargeInOptions): BargeIn {\n const { session, capture, playback } = options;\n const format = session.audio;\n if (format) {\n // PCM carries no rate: a mismatch would play and send at the wrong speed.\n for (const [name, rate] of [\n ['capture', capture.sampleRate],\n ['playback', playback.sampleRate],\n ] as const) {\n if (rate !== format.rate) {\n throw new Error(`${name} runs at ${rate} Hz but the session's audio is ${format.rate} Hz`);\n }\n }\n }\n const vad =\n options.localVad === false\n ? null\n : new EnergyVad(typeof options.localVad === 'object' ? options.localVad : {});\n let currentTurn: string | null = null;\n let replying = false;\n\n const cut = () => {\n playback.flush();\n if (replying) {\n session.interrupt();\n replying = false;\n }\n };\n\n const offFrame = capture.onFrame((frame) => {\n if (options.shouldSend && !options.shouldSend()) {\n if (vad?.isSpeaking) {\n vad.reset();\n options.onLocalSpeech?.(false);\n }\n return;\n }\n session.sendAudio(frame);\n if (!vad) return;\n const decision = vad.feed(frame);\n options.onLevel?.(vad.level);\n if (decision === 'start') {\n options.onLocalSpeech?.(true);\n if (replying) cut();\n } else if (decision === 'end') {\n options.onLocalSpeech?.(false);\n }\n });\n\n const offEvent = session.onEvent((event) => {\n switch (event.type) {\n case 'turn.started':\n currentTurn = event.turn_id;\n replying = true;\n break;\n case 'audio.delta':\n if (event.turn_id === currentTurn) playback.enqueue(event.audio);\n break;\n case 'turn.ended':\n if (event.turn_id === currentTurn) {\n replying = false;\n if (event.reason === 'interrupted') playback.flush();\n }\n break;\n case 'input.speech_started':\n // The server heard the user: whatever is still buffered is stale.\n if (replying) cut();\n else playback.flush();\n break;\n case 'session.ended':\n playback.flush();\n replying = false;\n break;\n default:\n break;\n }\n });\n\n return {\n detach: () => {\n offFrame();\n offEvent();\n },\n get replying() {\n return replying;\n },\n };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/realtime/pcm.ts","../src/realtime/vad.ts","../src/realtime/barge-in.ts"],"sourcesContent":["/** PCM helpers shared by the session and the audio primitives. */\n\nexport const SESSION_SAMPLE_RATE = 24000;\n\nexport function pcmSeconds(byteLength: number, sampleRate = SESSION_SAMPLE_RATE): number {\n return byteLength / (sampleRate * 2);\n}\n\nexport function encodePcm(pcm: Int16Array | ArrayBuffer): string {\n const bytes =\n pcm instanceof Int16Array\n ? new Uint8Array(pcm.buffer, pcm.byteOffset, pcm.byteLength)\n : new Uint8Array(pcm);\n let binary = '';\n const chunk = 0x8000;\n for (let i = 0; i < bytes.length; i += chunk) {\n binary += String.fromCharCode.apply(null, Array.from(bytes.subarray(i, i + chunk)));\n }\n return btoa(binary);\n}\n\nexport function decodePcm(base64: string): Int16Array {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n if (bytes.byteLength % 2) throw new Error('audio payload is not whole 16-bit samples');\n return new Int16Array(bytes.buffer);\n}\n\n/** Float32 [-1, 1] → Int16 little-endian (the platform's byte order is little-endian everywhere a browser runs). */\nexport function floatToInt16(samples: Float32Array): Int16Array {\n const out = new Int16Array(samples.length);\n for (let i = 0; i < samples.length; i++) {\n const s = Math.max(-1, Math.min(1, samples[i] ?? 0));\n out[i] = s < 0 ? s * 0x8000 : s * 0x7fff;\n }\n return out;\n}\n\n/** Root mean square of a PCM frame, on the Int16 scale (0–32767). */\nexport function rms(pcm: Int16Array): number {\n if (pcm.length === 0) return 0;\n let sum = 0;\n for (let i = 0; i < pcm.length; i++) {\n const s = pcm[i] ?? 0;\n sum += s * s;\n }\n return Math.sqrt(sum / pcm.length);\n}\n","/**\n * A small energy-based voice activity detector, run on the client's own\n * microphone frames.\n *\n * Why it exists: the upstream's VAD reports that the user started speaking\n * only after a delay, and the upstream generates faster than real time, so a\n * short reply has been fully generated by then (the README has the figures).\n * Detecting speech locally lets the client flush playback and send\n * `interrupt` within one frame of the user opening their mouth.\n *\n * Pure: feed it frames, get `start` / `end` decisions. Measured in audio\n * time, not wall-clock time, so it behaves the same from a file as from a\n * microphone.\n */\n\nimport { rms } from './pcm';\n\nexport interface VadOptions {\n /** RMS on the Int16 scale above which a frame counts as speech. Default 700. */\n threshold?: number;\n /** Consecutive speech frames before `start`. Default 2 (200 ms at 100 ms frames). */\n startFrames?: number;\n /** Silent audio after speech before `end`. Default 600 ms. */\n endSilenceMs?: number;\n sampleRate?: number;\n}\n\nexport type VadDecision = 'start' | 'end' | null;\n\nexport class EnergyVad {\n private readonly threshold: number;\n private readonly startFrames: number;\n private readonly endSilenceMs: number;\n private readonly sampleRate: number;\n private speaking = false;\n private loudRun = 0;\n private silenceMs = 0;\n private _level = 0;\n\n constructor(options: VadOptions = {}) {\n this.threshold = options.threshold ?? 700;\n this.startFrames = options.startFrames ?? 2;\n this.endSilenceMs = options.endSilenceMs ?? 600;\n this.sampleRate = options.sampleRate ?? 24000;\n }\n\n /** The last frame's RMS, for a level meter. */\n get level(): number {\n return this._level;\n }\n\n get isSpeaking(): boolean {\n return this.speaking;\n }\n\n feed(frame: Int16Array): VadDecision {\n const level = rms(frame);\n this._level = level;\n const frameMs = (frame.length / this.sampleRate) * 1000;\n const loud = level >= this.threshold;\n if (loud) {\n this.loudRun += 1;\n this.silenceMs = 0;\n if (!this.speaking && this.loudRun >= this.startFrames) {\n this.speaking = true;\n return 'start';\n }\n return null;\n }\n this.loudRun = 0;\n if (this.speaking) {\n this.silenceMs += frameMs;\n if (this.silenceMs >= this.endSilenceMs) {\n this.speaking = false;\n this.silenceMs = 0;\n return 'end';\n }\n }\n return null;\n }\n\n reset(): void {\n this.speaking = false;\n this.loudRun = 0;\n this.silenceMs = 0;\n }\n}\n","/**\n * Wires a session, a microphone and a playback buffer into a conversation:\n * every mic frame goes to the session; incoming audio goes to playback;\n * the user speaking over a reply flushes playback and interrupts upstream.\n *\n * Two triggers end a reply early, and both flush: local speech detection\n * (fast — within a frame or two of the user speaking) and the server's own\n * `input.speech_started` (slower, but authoritative). Audio for a turn the\n * server has already ended is dropped on the floor rather than played late.\n */\n\nimport type { RealtimeSession } from './session';\nimport { EnergyVad, type VadOptions } from './vad';\n\n/**\n * Where microphone audio comes from: s16le frames at `sampleRate`. The\n * browser's `MicrophoneCapture` is one; a React Native module can be another.\n */\nexport interface AudioSource {\n readonly sampleRate: number;\n onFrame(listener: (frame: Int16Array) => void): () => void;\n}\n\n/** Where reply audio goes: base64 or raw s16le at `sampleRate`, flushed on barge-in. */\nexport interface AudioSink {\n readonly sampleRate: number;\n enqueue(audio: string | Int16Array): void;\n flush(): void;\n}\n\nexport interface BargeInOptions {\n session: RealtimeSession;\n capture: AudioSource;\n playback: AudioSink;\n /** Detect speech locally and interrupt before the upstream's VAD reports it. Default on. */\n localVad?: boolean | VadOptions;\n /** Called with the level meter value on every mic frame. */\n onLevel?: (rms: number) => void;\n /** Called when the local detector decides speech started / ended. */\n onLocalSpeech?: (speaking: boolean) => void;\n /**\n * Push-to-talk gate: when it returns false, microphone frames are dropped\n * (not sent, not fed to the detector) so the capture can stay running\n * between presses without the latency of reopening the device.\n */\n shouldSend?: () => boolean;\n}\n\nexport interface BargeIn {\n detach(): void;\n /** True while a reply is being delivered (between turn.started and turn.ended). */\n readonly replying: boolean;\n}\n\nexport function attachBargeIn(options: BargeInOptions): BargeIn {\n const { session, capture, playback } = options;\n const format = session.audio;\n if (format) {\n // PCM carries no rate: a mismatch would play and send at the wrong speed.\n for (const [name, rate] of [\n ['capture', capture.sampleRate],\n ['playback', playback.sampleRate],\n ] as const) {\n if (rate !== format.rate) {\n throw new Error(`${name} runs at ${rate} Hz but the session's audio is ${format.rate} Hz`);\n }\n }\n }\n const vad =\n options.localVad === false\n ? null\n : new EnergyVad(typeof options.localVad === 'object' ? options.localVad : {});\n let currentTurn: string | null = null;\n let replying = false;\n\n const cut = () => {\n playback.flush();\n if (replying) {\n session.interrupt();\n replying = false;\n }\n };\n\n const offFrame = capture.onFrame((frame) => {\n if (options.shouldSend && !options.shouldSend()) {\n if (vad?.isSpeaking) {\n vad.reset();\n options.onLocalSpeech?.(false);\n }\n return;\n }\n session.sendAudio(frame);\n if (!vad) return;\n const decision = vad.feed(frame);\n options.onLevel?.(vad.level);\n if (decision === 'start') {\n options.onLocalSpeech?.(true);\n if (replying) cut();\n } else if (decision === 'end') {\n options.onLocalSpeech?.(false);\n }\n });\n\n const offEvent = session.onEvent((event) => {\n switch (event.type) {\n case 'turn.started':\n currentTurn = event.turn_id;\n replying = true;\n break;\n case 'audio.delta':\n if (event.turn_id === currentTurn) playback.enqueue(event.audio);\n break;\n case 'turn.ended':\n if (event.turn_id === currentTurn) {\n replying = false;\n if (event.reason === 'interrupted') playback.flush();\n }\n break;\n case 'input.speech_started':\n // The server heard the user: whatever is still buffered is stale.\n if (replying) cut();\n else playback.flush();\n break;\n case 'session.ended':\n playback.flush();\n replying = false;\n break;\n default:\n break;\n }\n });\n\n return {\n detach: () => {\n offFrame();\n offEvent();\n },\n get replying() {\n return replying;\n },\n };\n}\n"],"mappings":";AAEO,IAAM,sBAAsB;AAE5B,SAAS,WAAW,YAAoB,aAAa,qBAA6B;AACvF,SAAO,cAAc,aAAa;AACpC;AAEO,SAAS,UAAU,KAAuC;AAC/D,QAAM,QACJ,eAAe,aACX,IAAI,WAAW,IAAI,QAAQ,IAAI,YAAY,IAAI,UAAU,IACzD,IAAI,WAAW,GAAG;AACxB,MAAI,SAAS;AACb,QAAM,QAAQ;AACd,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,OAAO;AAC5C,cAAU,OAAO,aAAa,MAAM,MAAM,MAAM,KAAK,MAAM,SAAS,GAAG,IAAI,KAAK,CAAC,CAAC;AAAA,EACpF;AACA,SAAO,KAAK,MAAM;AACpB;AAEO,SAAS,UAAU,QAA4B;AACpD,QAAM,S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