segmind 0.6.0 → 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.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  The official JavaScript SDK for [Segmind](https://www.segmind.com): image, video, audio and LLM models through one API. It works in Node 22+, and in browsers and React Native through your own backend.
4
4
 
5
- > **0.x.** The API below is the 0.2 surface. Until 1.0, a breaking change bumps the minor version, so pin `segmind@~0.2` if you need it to hold still.
5
+ > **0.x.** Until 1.0, a breaking change bumps the minor version, so pin the minor you build on, such as `segmind@~0.6`, if you need the API to hold still.
6
6
 
7
7
  ## Install
8
8
 
@@ -103,6 +103,29 @@ const described = await segmind.chat('gpt-5.5', {
103
103
 
104
104
  `reply.text` reads the assistant text from OpenAI, Anthropic and Gemini replies alike; `reply.raw` is the provider's own JSON. `chatSync` makes one blocking call, and `submitChat` returns a job.
105
105
 
106
+ ## Ask a decision model
107
+
108
+ A decision model answers typed questions about a `state` with probabilities, not prose. Every decision model takes the same request, so one body can be compared across models.
109
+
110
+ ```ts
111
+ const decision = await segmind.decideSync('jev-1.14', {
112
+ state: "Customer email: 'I was charged twice this month, please refund one.'",
113
+ questions: {
114
+ is_bug: { type: 'noul', instructions: 'Is this a software bug report?' },
115
+ team: { type: 'choice', instructions: 'Which team should handle this?', options: { billing: 'Payments and refunds', support: null } },
116
+ urgency: { type: 'score', instructions: 'How urgent is this?', levels: ['low', 'medium', 'high'] },
117
+ },
118
+ });
119
+ decision.probability('is_bug'); // 0.24
120
+ decision.choice('team'); // 'billing'
121
+ decision.score('urgency'); // 1.22, the expected level index (0 = low)
122
+ console.log(decision.cost, decision.latencyMs, decision.answer('urgency'));
123
+ ```
124
+
125
+ A `box` question locates something in `images` and answers with `top`, `bottom`, `left` and `right` in [0, 1]. `state` can also be a JSON object, and `images`, `audio`, `video` and `files` take URLs. Each model takes different media and question types; a request it can't take is refused with a 400 that names the field.
126
+
127
+ A refused or errored answer has no number: `probability()`, `choice()`, `score()` and `box()` return `undefined` for it, never 0, and `decision.status(key)` says which. `decideSync` makes one blocking call, `decide` goes through the queue, and `submitDecision` returns a job.
128
+
106
129
  ## Files
107
130
 
108
131
  ```ts
@@ -228,13 +251,63 @@ From Node, mint with the client's own key:
228
251
  `upstream_error` and the rest. `close()` and `whenEnded()` resolve with the
229
252
  final usage.
230
253
  - **Refusals.** `connect()` rejects with a `SessionOpenError` (a
231
- `SegmindError`) whose `code` says why: `insufficient_credits`, `capacity`,
232
- `token_expired`, `unknown_model`, `service_unavailable`. `capacity` and
254
+ `SegmindError`) whose `code` says why, such as `insufficient_credits`,
255
+ `unauthorized` (a token minted for another model, for example),
256
+ `token_expired`, `unknown_model`, `capacity` or `service_unavailable`. The
257
+ `RefusalCode` type in `segmind/realtime` lists them all. `capacity` and
233
258
  `service_unavailable` are worth retrying shortly; the rest are not.
234
259
  - **No silent reconnect.** A dropped connection ends the session. A new one
235
260
  needs a new token, because it is a new paid session.
236
261
  - **Aborting.** Pass `signal` to cancel an open or end a live session.
237
262
 
263
+ ### Video sessions
264
+
265
+ A live video model streams over WebRTC, straight between the browser and the
266
+ model; the session socket carries only the negotiation, steering and billing.
267
+ Attach `attachVideo` before `open()`, because the service starts negotiating
268
+ right after `session.created`:
269
+
270
+ ```ts
271
+ import { RealtimeClient } from 'segmind/realtime';
272
+ import { attachVideo } from 'segmind/realtime/browser';
273
+
274
+ const session = new RealtimeClient({ tokenProvider }).session('your-video-model', {
275
+ params: { resolution: '768p' },
276
+ });
277
+ const video = attachVideo(session, { prompt: 'a drone shot over a forest' });
278
+ video.onEvent((e) => {
279
+ if (e.type === 'remote_stream') videoElement.srcObject = e.stream;
280
+ if (e.type === 'prompt_ack') console.log(e.applied ? 'applied' : `refused: ${e.reason}`);
281
+ if (e.type === 'failed') console.error(e.message); // the session is being closed
282
+ });
283
+ await session.open(); // call from a click: a camera model asks for the camera
284
+
285
+ video.prompt('the camera rises into the clouds'); // steer while it plays
286
+ await video.end(); // stops the model, then closes the session
287
+ ```
288
+
289
+ `session.created.control` says how a model is steered, and `attachVideo`
290
+ handles both:
291
+
292
+ - **`session`**: a camera model. The camera goes up (`getUserMedia` at the
293
+ size in `media.video`, or pass `localStream`) and the edited stream comes
294
+ back. `prompt()` and `setImage(base64)` go on the socket, and each gets a
295
+ `prompt_ack` in the order sent. The connection starts on one public STUN
296
+ server (`DEFAULT_ICE_SERVERS`); pass `iceServers` to use your own, such as
297
+ TURN servers for users behind a NAT that STUN can't cross.
298
+ - **`datachannel`**: a receive-only model. Steering goes on the model's own
299
+ data channel: `configure` when it opens (with the session's `resolution` and
300
+ `aspect_ratio` params), then each `prompt()` with a rising version. What the
301
+ model says there arrives as `channel` events.
302
+
303
+ Any negotiation or transport failure ends the session, so nothing keeps
304
+ billing for a stream nobody can see. A session whose credit ceiling can't
305
+ cover the model's minimum charge is refused with `ceiling_too_low`. Outside a
306
+ browser, pass `peerConnectionFactory`, `getUserMedia` and `createMediaStream`.
307
+
308
+ In React, [`@segmind/react`](https://www.npmjs.com/package/@segmind/react) wraps
309
+ a session in one hook: `useRealtimeSession` for voice, `useRealtimeVideo` for video.
310
+
238
311
  ## Credits
239
312
 
240
313
  ```ts
@@ -0,0 +1,342 @@
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;
2
+
3
+ var _chunk74UKKBOOcjs = require('./chunk-74UKKBOO.cjs');
4
+
5
+ // src/realtime/types.ts
6
+ var PROTOCOL_VERSION = 1;
7
+ var STREAM_TAGS = { audio: 1, video: 2 };
8
+
9
+ // src/realtime/protocol.ts
10
+ var SERVER_EVENT_TYPES = /* @__PURE__ */ new Set([
11
+ "session.created",
12
+ "session.updated",
13
+ "session.ended",
14
+ "input.speech_started",
15
+ "input.speech_stopped",
16
+ "turn.started",
17
+ "turn.ended",
18
+ "audio.delta",
19
+ "transcript.delta",
20
+ "segmind.usage",
21
+ "error",
22
+ "upstream.event",
23
+ "pong",
24
+ "webrtc.config",
25
+ "webrtc.answer",
26
+ "webrtc.candidate",
27
+ "webrtc.restart",
28
+ "video.started",
29
+ "video.progress",
30
+ "video.prompt_ack"
31
+ ]);
32
+ var ProtocolError = class extends _chunk74UKKBOOcjs.SegmindError {
33
+ constructor(message, raw) {
34
+ super(message, { body: raw });
35
+ this.raw = raw;
36
+ }
37
+
38
+ };
39
+ function decodeServerEvent(text) {
40
+ let parsed;
41
+ try {
42
+ parsed = JSON.parse(text);
43
+ } catch (e) {
44
+ throw new ProtocolError("server frame is not JSON", text);
45
+ }
46
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
47
+ throw new ProtocolError("server frame is not an object", parsed);
48
+ }
49
+ const type = parsed.type;
50
+ if (typeof type !== "string" || !SERVER_EVENT_TYPES.has(type)) {
51
+ throw new ProtocolError(`unknown server event type: ${String(type)}`, parsed);
52
+ }
53
+ return parsed;
54
+ }
55
+ function encodeClientEvent(event) {
56
+ return JSON.stringify(event);
57
+ }
58
+ var SERVER_ENDINGS = /* @__PURE__ */ new Set([
59
+ "client",
60
+ "ceiling",
61
+ "idle",
62
+ "max_length",
63
+ "balance_exhausted",
64
+ "upstream_error",
65
+ "server_shutdown",
66
+ "internal_error",
67
+ "metering_failed",
68
+ "content_policy"
69
+ ]);
70
+ var REFUSAL_CLOSE_CODES = {
71
+ bad_request: 4e3,
72
+ unauthorized: 4001,
73
+ insufficient_credits: 4002,
74
+ unknown_model: 4004,
75
+ capacity: 4029,
76
+ /** A dependency (Redis, Spot) is unreachable, or the server is draining; retry shortly. */
77
+ try_again: 1013
78
+ };
79
+ var REFUSAL_CODES = new Set(Object.values(REFUSAL_CLOSE_CODES));
80
+ function reasonFromCloseCode(code, closeReason) {
81
+ if (REFUSAL_CODES.has(code)) return "refused";
82
+ if (closeReason && SERVER_ENDINGS.has(closeReason)) return closeReason;
83
+ switch (code) {
84
+ case 1e3:
85
+ return "client";
86
+ case 4008:
87
+ return "limit";
88
+ case 1012:
89
+ return "server_shutdown";
90
+ case 1011:
91
+ return "internal_error";
92
+ default:
93
+ return "connection_lost";
94
+ }
95
+ }
96
+ function isRetryableRefusal(closeCode) {
97
+ return closeCode === REFUSAL_CLOSE_CODES.try_again;
98
+ }
99
+ function unsupportedSession(created) {
100
+ if (created.protocol !== PROTOCOL_VERSION) {
101
+ return `server speaks protocol ${String(created.protocol)}; this client speaks ${PROTOCOL_VERSION}`;
102
+ }
103
+ return null;
104
+ }
105
+ function audioFormat(created) {
106
+ const spec = _optionalChain([created, 'optionalAccess', _ => _.media, 'optionalAccess', _2 => _2.audio]);
107
+ if (!spec || spec.encoding !== "pcm_s16le" || typeof spec.rate !== "number") return null;
108
+ return {
109
+ ...spec,
110
+ encoding: "pcm_s16le",
111
+ rate: spec.rate,
112
+ channels: _nullishCoalesce(spec.channels, () => ( 1)),
113
+ tag: _nullishCoalesce(spec.tag, () => ( STREAM_TAGS.audio))
114
+ };
115
+ }
116
+ function webrtcVideo(created) {
117
+ const spec = _optionalChain([created, 'optionalAccess', _3 => _3.media, 'optionalAccess', _4 => _4.video]);
118
+ return spec && spec.transport === "webrtc" ? spec : null;
119
+ }
120
+ function videoControl(created) {
121
+ if (!webrtcVideo(created)) return null;
122
+ return _optionalChain([created, 'optionalAccess', _5 => _5.control]) === "datachannel" ? "datachannel" : "session";
123
+ }
124
+ function acceptsInput(format) {
125
+ return format !== null && (format.direction === "in" || format.direction === "duplex");
126
+ }
127
+ function mediaFrame(tag, payload) {
128
+ const bytes = payload instanceof ArrayBuffer ? new Uint8Array(payload) : new Uint8Array(payload.buffer, payload.byteOffset, payload.byteLength);
129
+ const frame = new Uint8Array(bytes.byteLength + 1);
130
+ frame[0] = tag;
131
+ frame.set(bytes, 1);
132
+ return frame.buffer;
133
+ }
134
+ function sessionUrl(root, slug, token, query, path) {
135
+ const base = root.replace(/\/+$/, "");
136
+ const segments = (_nullishCoalesce(path, () => ( slug))).split("/").filter(Boolean);
137
+ const encoded = (segments.length ? segments : [slug]).map(encodeURIComponent).join("/");
138
+ const params = new URLSearchParams({ token, ..._nullishCoalesce(query, () => ( {})) });
139
+ return `${base}/${encoded}?${params.toString()}`;
140
+ }
141
+
142
+ // src/realtime/pcm.ts
143
+ var SESSION_SAMPLE_RATE = 24e3;
144
+ function pcmSeconds(byteLength, sampleRate = SESSION_SAMPLE_RATE) {
145
+ return byteLength / (sampleRate * 2);
146
+ }
147
+ function encodePcm(pcm) {
148
+ const bytes = pcm instanceof Int16Array ? new Uint8Array(pcm.buffer, pcm.byteOffset, pcm.byteLength) : new Uint8Array(pcm);
149
+ let binary = "";
150
+ const chunk = 32768;
151
+ for (let i = 0; i < bytes.length; i += chunk) {
152
+ binary += String.fromCharCode.apply(null, Array.from(bytes.subarray(i, i + chunk)));
153
+ }
154
+ return btoa(binary);
155
+ }
156
+ function decodePcm(base64) {
157
+ const binary = atob(base64);
158
+ const bytes = new Uint8Array(binary.length);
159
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
160
+ if (bytes.byteLength % 2) throw new Error("audio payload is not whole 16-bit samples");
161
+ return new Int16Array(bytes.buffer);
162
+ }
163
+ function floatToInt16(samples) {
164
+ const out = new Int16Array(samples.length);
165
+ for (let i = 0; i < samples.length; i++) {
166
+ const s = Math.max(-1, Math.min(1, _nullishCoalesce(samples[i], () => ( 0))));
167
+ out[i] = s < 0 ? s * 32768 : s * 32767;
168
+ }
169
+ return out;
170
+ }
171
+ function rms(pcm) {
172
+ if (pcm.length === 0) return 0;
173
+ let sum = 0;
174
+ for (let i = 0; i < pcm.length; i++) {
175
+ const s = _nullishCoalesce(pcm[i], () => ( 0));
176
+ sum += s * s;
177
+ }
178
+ return Math.sqrt(sum / pcm.length);
179
+ }
180
+
181
+ // src/realtime/vad.ts
182
+ var EnergyVad = (_class = class {
183
+
184
+
185
+
186
+
187
+ __init() {this.speaking = false}
188
+ __init2() {this.loudRun = 0}
189
+ __init3() {this.silenceMs = 0}
190
+ __init4() {this._level = 0}
191
+ constructor(options = {}) {;_class.prototype.__init.call(this);_class.prototype.__init2.call(this);_class.prototype.__init3.call(this);_class.prototype.__init4.call(this);
192
+ this.threshold = _nullishCoalesce(options.threshold, () => ( 700));
193
+ this.startFrames = _nullishCoalesce(options.startFrames, () => ( 2));
194
+ this.endSilenceMs = _nullishCoalesce(options.endSilenceMs, () => ( 600));
195
+ this.sampleRate = _nullishCoalesce(options.sampleRate, () => ( 24e3));
196
+ }
197
+ /** The last frame's RMS, for a level meter. */
198
+ get level() {
199
+ return this._level;
200
+ }
201
+ get isSpeaking() {
202
+ return this.speaking;
203
+ }
204
+ feed(frame) {
205
+ const level = rms(frame);
206
+ this._level = level;
207
+ const frameMs = frame.length / this.sampleRate * 1e3;
208
+ const loud = level >= this.threshold;
209
+ if (loud) {
210
+ this.loudRun += 1;
211
+ this.silenceMs = 0;
212
+ if (!this.speaking && this.loudRun >= this.startFrames) {
213
+ this.speaking = true;
214
+ return "start";
215
+ }
216
+ return null;
217
+ }
218
+ this.loudRun = 0;
219
+ if (this.speaking) {
220
+ this.silenceMs += frameMs;
221
+ if (this.silenceMs >= this.endSilenceMs) {
222
+ this.speaking = false;
223
+ this.silenceMs = 0;
224
+ return "end";
225
+ }
226
+ }
227
+ return null;
228
+ }
229
+ reset() {
230
+ this.speaking = false;
231
+ this.loudRun = 0;
232
+ this.silenceMs = 0;
233
+ }
234
+ }, _class);
235
+
236
+ // src/realtime/barge-in.ts
237
+ function attachBargeIn(options) {
238
+ const { session, capture, playback } = options;
239
+ const format = session.audio;
240
+ if (format) {
241
+ for (const [name, rate] of [
242
+ ["capture", capture.sampleRate],
243
+ ["playback", playback.sampleRate]
244
+ ]) {
245
+ if (rate !== format.rate) {
246
+ throw new Error(`${name} runs at ${rate} Hz but the session's audio is ${format.rate} Hz`);
247
+ }
248
+ }
249
+ }
250
+ const vad = options.localVad === false ? null : new EnergyVad(typeof options.localVad === "object" ? options.localVad : {});
251
+ let currentTurn = null;
252
+ let replying = false;
253
+ const cut = () => {
254
+ playback.flush();
255
+ if (replying) {
256
+ session.interrupt();
257
+ replying = false;
258
+ }
259
+ };
260
+ const offFrame = capture.onFrame((frame) => {
261
+ if (options.shouldSend && !options.shouldSend()) {
262
+ if (_optionalChain([vad, 'optionalAccess', _6 => _6.isSpeaking])) {
263
+ vad.reset();
264
+ _optionalChain([options, 'access', _7 => _7.onLocalSpeech, 'optionalCall', _8 => _8(false)]);
265
+ }
266
+ return;
267
+ }
268
+ session.sendAudio(frame);
269
+ if (!vad) return;
270
+ const decision = vad.feed(frame);
271
+ _optionalChain([options, 'access', _9 => _9.onLevel, 'optionalCall', _10 => _10(vad.level)]);
272
+ if (decision === "start") {
273
+ _optionalChain([options, 'access', _11 => _11.onLocalSpeech, 'optionalCall', _12 => _12(true)]);
274
+ if (replying) cut();
275
+ } else if (decision === "end") {
276
+ _optionalChain([options, 'access', _13 => _13.onLocalSpeech, 'optionalCall', _14 => _14(false)]);
277
+ }
278
+ });
279
+ const offEvent = session.onEvent((event) => {
280
+ switch (event.type) {
281
+ case "turn.started":
282
+ currentTurn = event.turn_id;
283
+ replying = true;
284
+ break;
285
+ case "audio.delta":
286
+ if (event.turn_id === currentTurn) playback.enqueue(event.audio);
287
+ break;
288
+ case "turn.ended":
289
+ if (event.turn_id === currentTurn) {
290
+ replying = false;
291
+ if (event.reason === "interrupted") playback.flush();
292
+ }
293
+ break;
294
+ case "input.speech_started":
295
+ if (replying) cut();
296
+ else playback.flush();
297
+ break;
298
+ case "session.ended":
299
+ playback.flush();
300
+ replying = false;
301
+ break;
302
+ default:
303
+ break;
304
+ }
305
+ });
306
+ return {
307
+ detach: () => {
308
+ offFrame();
309
+ offEvent();
310
+ },
311
+ get replying() {
312
+ return replying;
313
+ }
314
+ };
315
+ }
316
+
317
+
318
+
319
+
320
+
321
+
322
+
323
+
324
+
325
+
326
+
327
+
328
+
329
+
330
+
331
+
332
+
333
+
334
+
335
+
336
+
337
+
338
+
339
+
340
+
341
+ exports.PROTOCOL_VERSION = PROTOCOL_VERSION; exports.STREAM_TAGS = STREAM_TAGS; exports.ProtocolError = ProtocolError; exports.decodeServerEvent = decodeServerEvent; exports.encodeClientEvent = encodeClientEvent; exports.REFUSAL_CLOSE_CODES = REFUSAL_CLOSE_CODES; exports.reasonFromCloseCode = reasonFromCloseCode; exports.isRetryableRefusal = isRetryableRefusal; exports.unsupportedSession = unsupportedSession; exports.audioFormat = audioFormat; exports.webrtcVideo = webrtcVideo; exports.videoControl = videoControl; exports.acceptsInput = acceptsInput; exports.mediaFrame = mediaFrame; exports.sessionUrl = sessionUrl; 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;
342
+ //# sourceMappingURL=chunk-B7VAGG2U.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/segmind-js/segmind-js/packages/segmind/dist/chunk-B7VAGG2U.cjs","../src/realtime/types.ts","../src/realtime/protocol.ts","../src/realtime/pcm.ts","../src/realtime/vad.ts","../src/realtime/barge-in.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACA;ACSO,IAAM,iBAAA,EAAmB,CAAA;AAGzB,IAAM,YAAA,EAAc,EAAE,KAAA,EAAO,CAAA,EAAM,KAAA,EAAO,EAAK,CAAA;ADTtD;AACA;AEKA,IAAM,mB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A;AACD,EAAA;AAE2C,EAAA;AACtB,IAAA;AACb,MAAA;AACiB,QAAA;AACT,QAAA;AACX,QAAA;AACG,MAAA;AAC4D,QAAA;AAC/D,QAAA;AACG,MAAA;AACgC,QAAA;AACtB,UAAA;AACwC,UAAA;AACrD,QAAA;AACA,QAAA;AACG,MAAA;AAEe,QAAA;AACE,QAAA;AACpB,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;AL8KuE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/segmind-js/segmind-js/packages/segmind/dist/chunk-B7VAGG2U.cjs","sourcesContent":[null,"/**\n * The wire vocabulary of a Segmind realtime session, as typed events.\n *\n * Mirrors Heimdall's `realtime/protocol.py`, session wire protocol v1.\n * Control is JSON text frames both ways. Media may also travel as binary\n * frames whose byte 0 names the stream (`0x01` audio, `0x02` video); the rest\n * is that stream's payload in the codec `session.created.media` declares.\n * The server sends audio as `audio.delta` JSON events. A video session's\n * streams travel over WebRTC instead (`transport: \"webrtc\"`), negotiated\n * through `webrtc.*` events on this socket; see `segmind/realtime/browser`.\n */\n\n/** The wire protocol version this client speaks (`session.created.protocol`). */\nexport const PROTOCOL_VERSION = 1;\n\n/** Byte 0 of a binary frame. Other values are reserved; the server refuses them. */\nexport const STREAM_TAGS = { audio: 0x01, video: 0x02 } as const;\n\nexport type SessionState = 'opening' | 'live' | 'closed';\n\n/** Why a session ended. The server's vocabulary, plus three the client adds. */\nexport type EndReason =\n | 'client'\n | 'ceiling'\n | 'idle'\n | 'max_length'\n | 'balance_exhausted'\n | 'upstream_error'\n | 'server_shutdown'\n | 'internal_error'\n | 'metering_failed'\n /** A video session's upstream moderation ended it (close 4008). */\n | 'content_policy'\n /**\n * Close code 4008 with no `session.ended` frame and no close reason: one of\n * the policy limits (ceiling, idle, max_length, balance_exhausted), which\n * one is unknown.\n */\n | 'limit'\n /** The socket closed without a `session.ended` frame. */\n | 'connection_lost'\n /**\n * The session was refused before it opened (auth, credits, model, capacity,\n * a dependency down) or spoke a protocol this client does not. The\n * refusal's `code` and close code are on `SessionEnd`.\n */\n | 'refused';\n\n/** Error codes the server refuses an open with, before a session exists. */\nexport type RefusalCode =\n | 'unauthorized'\n | 'token_expired'\n | 'token_replayed'\n | 'account_disabled'\n | 'auth_unavailable'\n | 'insufficient_credits'\n | 'unknown_model'\n | 'not_a_session_model'\n | 'model_deprecated'\n | 'bad_request'\n /** The credit ceiling cannot cover the model's minimum charge (close 4000). */\n | 'ceiling_too_low'\n /** The API key's scope excludes the model (close 4001). */\n | 'forbidden'\n | 'capacity'\n | 'service_unavailable'\n | 'internal_error'\n /** Client-side: `session.created.protocol` is not `PROTOCOL_VERSION`. */\n | 'unsupported_protocol';\n\nexport type TurnEndReason = 'completed' | 'interrupted' | 'error' | 'superseded' | 'session_closed';\n\n/**\n * One stream in `session.created.media`. A stream on the socket names its\n * binary `tag` and `encoding`; a stream with `transport: \"webrtc\"` flows\n * between the client and the upstream over WebRTC and names neither.\n */\nexport interface MediaStreamSpec {\n /** Byte 0 of a binary frame on this stream. Absent on a WebRTC stream. */\n tag?: number;\n /** `in` the client sends, `out` the server sends, `duplex` both. */\n direction: 'in' | 'out' | 'duplex';\n /** Absent on a WebRTC stream. */\n encoding?: string;\n /** `webrtc`: the stream never touches the socket. Absent means the socket. */\n transport?: 'webrtc' | (string & {});\n rate?: number;\n channels?: number;\n mime?: string;\n /** Video: the frame size and rate the upstream expects or sends. */\n width?: number;\n height?: number;\n fps?: number;\n [key: string]: unknown;\n}\n\n/** `media.audio` as the client uses it: 16-bit little-endian PCM. */\nexport interface AudioFormat extends MediaStreamSpec {\n tag: number;\n encoding: 'pcm_s16le';\n rate: number;\n channels: number;\n}\n\nexport interface SessionLimits {\n max_session_seconds: number;\n idle_seconds: number;\n credit_ceiling: number;\n slice_seconds: number;\n minimum_charge?: number;\n}\n\n/**\n * The measured facts a session is priced from. Which ones appear depends on\n * the model; a voice session reports audio seconds.\n */\nexport interface UsageFacts {\n input_audio_seconds?: number;\n output_audio_seconds?: number;\n input_tokens?: number;\n output_tokens?: number;\n output_video_seconds?: number;\n text_inputs?: number;\n [fact: string]: number | undefined;\n}\n\nexport interface Usage {\n /** Credits moved off the balance so far. */\n cost: number;\n credits_confirmed: boolean;\n /** Present only when the balance moved. */\n remaining_credits?: number;\n usage: UsageFacts;\n sequence: number;\n final: boolean;\n}\n\n// --- server → client ---------------------------------------------------------\n\nexport interface SessionCreatedEvent {\n type: 'session.created';\n protocol: number;\n session_id: string;\n request_id: string;\n model: string;\n provider: string;\n media: Record<string, MediaStreamSpec>;\n limits: SessionLimits;\n /**\n * Where a video session is steered: `session` (`video.prompt` /\n * `video.image` on this socket) or `datachannel` (the upstream's own\n * WebRTC data channel). Absent on a session without WebRTC streams.\n */\n control?: VideoControl;\n}\n\n/** Where a video session's steering goes; see `SessionCreatedEvent.control`. */\nexport type VideoControl = 'session' | 'datachannel';\n\nexport interface SessionUpdatedEvent {\n type: 'session.updated';\n session: Record<string, unknown>;\n}\n\nexport interface SessionEndedEvent {\n type: 'session.ended';\n reason: EndReason;\n usage?: Usage;\n message?: string;\n}\n\nexport interface InputSpeechStartedEvent {\n type: 'input.speech_started';\n}\n\nexport interface InputSpeechStoppedEvent {\n type: 'input.speech_stopped';\n}\n\nexport interface TurnStartedEvent {\n type: 'turn.started';\n turn_id: string;\n input: 'text' | 'speech';\n}\n\nexport interface TurnEndedEvent {\n type: 'turn.ended';\n turn_id: string;\n reason: TurnEndReason;\n output_seconds: number;\n time_to_first_byte?: number;\n upstream_usage?: Record<string, unknown>;\n}\n\nexport interface AudioDeltaEvent {\n type: 'audio.delta';\n turn_id: string;\n /** base64 of s16le PCM */\n audio: string;\n seconds: number;\n}\n\nexport interface TranscriptDeltaEvent {\n type: 'transcript.delta';\n turn_id: string;\n role: 'assistant' | 'user';\n text: string;\n}\n\nexport interface UsageEvent extends Usage {\n type: 'segmind.usage';\n}\n\nexport interface ErrorEvent {\n type: 'error';\n code: string;\n message: string;\n}\n\nexport interface UpstreamEvent {\n type: 'upstream.event';\n provider: string;\n event: Record<string, unknown>;\n}\n\nexport interface PongEvent {\n type: 'pong';\n}\n\n/** One ICE server, as `RTCConfiguration.iceServers` takes it. */\nexport interface IceServer {\n urls: string | string[];\n username?: string;\n credential?: string;\n}\n\n/** An ICE candidate, as `RTCIceCandidate.toJSON()` gives it. */\nexport interface IceCandidateJson {\n candidate?: string;\n sdpMid?: string | null;\n sdpMLineIndex?: number | null;\n usernameFragment?: string | null;\n}\n\n/** Gather with these ICE servers, then send the offer. */\nexport interface WebrtcConfigEvent {\n type: 'webrtc.config';\n ice_servers: IceServer[];\n /** True: gather every candidate, then send one offer; no trickle ICE. */\n complete_offer: boolean;\n}\n\nexport interface WebrtcAnswerEvent {\n type: 'webrtc.answer';\n sdp: string;\n ice_servers?: IceServer[];\n}\n\n/** A remote ICE candidate; null ends the upstream's candidates. */\nexport interface WebrtcCandidateEvent {\n type: 'webrtc.candidate';\n candidate: IceCandidateJson | null;\n}\n\n/** Reconfigure the peer with these servers and send a new offer with `iceRestart`. */\nexport interface WebrtcRestartEvent {\n type: 'webrtc.restart';\n ice_servers: IceServer[];\n}\n\n/** Generation began; video is flowing. */\nexport interface VideoStartedEvent {\n type: 'video.started';\n}\n\n/** Seconds of video generated so far, as billed. */\nexport interface VideoProgressEvent {\n type: 'video.progress';\n seconds: number;\n}\n\n/** The upstream's verdict on a `video.prompt` or `video.image`, in the order they were sent. */\nexport interface VideoPromptAckEvent {\n type: 'video.prompt_ack';\n kind: 'prompt' | 'image';\n applied: boolean;\n reason?: string;\n}\n\nexport type ServerEvent =\n | SessionCreatedEvent\n | SessionUpdatedEvent\n | SessionEndedEvent\n | InputSpeechStartedEvent\n | InputSpeechStoppedEvent\n | TurnStartedEvent\n | TurnEndedEvent\n | AudioDeltaEvent\n | TranscriptDeltaEvent\n | UsageEvent\n | ErrorEvent\n | UpstreamEvent\n | PongEvent\n | WebrtcConfigEvent\n | WebrtcAnswerEvent\n | WebrtcCandidateEvent\n | WebrtcRestartEvent\n | VideoStartedEvent\n | VideoProgressEvent\n | VideoPromptAckEvent;\n\nexport type ServerEventType = ServerEvent['type'];\n\n// --- client → server ---------------------------------------------------------\n\nexport interface SessionUpdateParams {\n voice?: string;\n instructions?: string;\n reasoning_effort?: string;\n speed?: number;\n vad?: boolean;\n upstream_events?: boolean;\n [key: string]: unknown;\n}\n\nexport type ClientEvent =\n | { type: 'session.update'; session: SessionUpdateParams }\n | { type: 'audio.append'; audio: string }\n | { type: 'audio.commit' }\n | { type: 'text'; text: string }\n | { type: 'interrupt' }\n | { type: 'ping' }\n | { type: 'close' }\n | { type: 'webrtc.offer'; sdp: string }\n /** null: the end of candidates. */\n | { type: 'webrtc.candidate'; candidate: IceCandidateJson | null }\n /** `text` up to 20,000 characters; `enhance` defaults to true on the server. */\n | { type: 'video.prompt'; text: string; enhance?: boolean }\n /** `image` base64 (no `data:` prefix), or null to clear the reference. */\n | { type: 'video.image'; image: string | null; text?: string; enhance?: boolean }\n /** An upstream data-channel event the client received, mirrored for the record. Never billed from. */\n | { type: 'video.report'; event: Record<string, unknown> };\n\n// --- tokens --------------------------------------------------------------------\n\n/** What `POST /v1/realtime/token` returns. */\nexport interface SessionToken {\n token: string;\n /** Unix seconds. */\n expires_at?: number;\n expires_in?: number;\n model?: string;\n credit_ceiling?: number;\n}\n\n/**\n * How the host application obtains a session token. The client never sees\n * an API key: the host's backend trades its key (or the signed-in user's\n * session) for a short-lived token scoped to one model and a credit ceiling.\n */\nexport type SessionTokenProvider = (slug: string) => Promise<SessionToken | string>;\n","import { SegmindError } from '../core/errors';\nimport {\n PROTOCOL_VERSION,\n STREAM_TAGS,\n type AudioFormat,\n type ClientEvent,\n type EndReason,\n type MediaStreamSpec,\n type ServerEvent,\n type SessionCreatedEvent,\n type VideoControl,\n} from './types';\n\nconst SERVER_EVENT_TYPES = new Set<string>([\n 'session.created',\n 'session.updated',\n 'session.ended',\n 'input.speech_started',\n 'input.speech_stopped',\n 'turn.started',\n 'turn.ended',\n 'audio.delta',\n 'transcript.delta',\n 'segmind.usage',\n 'error',\n 'upstream.event',\n 'pong',\n 'webrtc.config',\n 'webrtc.answer',\n 'webrtc.candidate',\n 'webrtc.restart',\n 'video.started',\n 'video.progress',\n 'video.prompt_ack',\n]);\n\n/** A server frame this client cannot read. The session ignores it; `decodeServerEvent` throws it. */\nexport class ProtocolError extends SegmindError {\n constructor(\n message: string,\n public readonly raw?: unknown,\n ) {\n super(message, { body: raw });\n }\n}\n\n/** One server text frame → a typed event, or a ProtocolError. */\nexport function decodeServerEvent(text: string): ServerEvent {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n throw new ProtocolError('server frame is not JSON', text);\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new ProtocolError('server frame is not an object', parsed);\n }\n const type = (parsed as { type?: unknown }).type;\n if (typeof type !== 'string' || !SERVER_EVENT_TYPES.has(type)) {\n throw new ProtocolError(`unknown server event type: ${String(type)}`, parsed);\n }\n return parsed as ServerEvent;\n}\n\nexport function encodeClientEvent(event: ClientEvent): string {\n return JSON.stringify(event);\n}\n\n/** `session.ended.reason` values; the server also puts one in the close reason. */\nconst SERVER_ENDINGS = new Set<string>([\n 'client',\n 'ceiling',\n 'idle',\n 'max_length',\n 'balance_exhausted',\n 'upstream_error',\n 'server_shutdown',\n 'internal_error',\n 'metering_failed',\n 'content_policy',\n]);\n\n/** Close codes the server refuses an open with. Nothing was reserved or billed. */\nexport const REFUSAL_CLOSE_CODES = {\n bad_request: 4000,\n unauthorized: 4001,\n insufficient_credits: 4002,\n unknown_model: 4004,\n capacity: 4029,\n /** A dependency (Redis, Spot) is unreachable, or the server is draining; retry shortly. */\n try_again: 1013,\n} as const;\n\nconst REFUSAL_CODES = new Set<number>(Object.values(REFUSAL_CLOSE_CODES));\n\n/**\n * The reason a socket close implies when no `session.ended` frame was seen.\n * The server closes with the ending as the close reason, so a known reason\n * wins; otherwise the code decides. Mirrors the server's `CLOSE_CODES`: 4008\n * is shared by every policy limit, so without a reason it is `limit`.\n * Anything unknown is a lost connection.\n */\nexport function reasonFromCloseCode(code: number, closeReason?: string): EndReason {\n if (REFUSAL_CODES.has(code)) return 'refused';\n if (closeReason && SERVER_ENDINGS.has(closeReason)) return closeReason as EndReason;\n switch (code) {\n case 1000:\n return 'client';\n case 4008:\n return 'limit';\n case 1012:\n return 'server_shutdown';\n case 1011:\n return 'internal_error';\n default:\n return 'connection_lost';\n }\n}\n\n/** True for a refusal the client may retry shortly (close code 1013). */\nexport function isRetryableRefusal(closeCode: number | undefined): boolean {\n return closeCode === REFUSAL_CLOSE_CODES.try_again;\n}\n\n/** Why a `session.created` cannot be used by this client, or null when it can. */\nexport function unsupportedSession(created: SessionCreatedEvent): string | null {\n if (created.protocol !== PROTOCOL_VERSION) {\n return `server speaks protocol ${String(created.protocol)}; this client speaks ${PROTOCOL_VERSION}`;\n }\n return null;\n}\n\n/**\n * The session's audio stream from `session.created.media`, or null when the\n * session carries no audio this client can handle (only 16-bit PCM).\n */\nexport function audioFormat(created: SessionCreatedEvent | null): AudioFormat | null {\n const spec = created?.media?.audio;\n if (!spec || spec.encoding !== 'pcm_s16le' || typeof spec.rate !== 'number') return null;\n return {\n ...spec,\n encoding: 'pcm_s16le',\n rate: spec.rate,\n channels: spec.channels ?? 1,\n tag: spec.tag ?? STREAM_TAGS.audio,\n };\n}\n\n/** The session's video stream when it travels over WebRTC, or null. */\nexport function webrtcVideo(created: SessionCreatedEvent | null): MediaStreamSpec | null {\n const spec = created?.media?.video;\n return spec && spec.transport === 'webrtc' ? spec : null;\n}\n\n/**\n * Where a video session is steered, or null for a session without a WebRTC\n * video stream. A WebRTC session that names no `control` is steered on the socket.\n */\nexport function videoControl(created: SessionCreatedEvent | null): VideoControl | null {\n if (!webrtcVideo(created)) return null;\n return created?.control === 'datachannel' ? 'datachannel' : 'session';\n}\n\n/** True when the client may send on this stream. */\nexport function acceptsInput(format: { direction: string } | null): boolean {\n return format !== null && (format.direction === 'in' || format.direction === 'duplex');\n}\n\n/** One binary frame: the stream tag, then the payload bytes. */\nexport function mediaFrame(tag: number, payload: ArrayBuffer | ArrayBufferView): ArrayBuffer {\n const bytes =\n payload instanceof ArrayBuffer\n ? new Uint8Array(payload)\n : new Uint8Array(payload.buffer, payload.byteOffset, payload.byteLength);\n const frame = new Uint8Array(bytes.byteLength + 1);\n frame[0] = tag;\n frame.set(bytes, 1);\n return frame.buffer;\n}\n\n/** Builds the socket URL for a slug, with the token on the query string\n * (a browser WebSocket cannot set headers). `path` is the session's path on\n * the service (the model record's `endpoints.session`); without one it is\n * `/<slug>`. Each path segment is encoded, so the URL stays under `root`. */\nexport function sessionUrl(\n root: string,\n slug: string,\n token: string,\n query?: Record<string, string>,\n path?: string,\n): string {\n const base = root.replace(/\\/+$/, '');\n const segments = (path ?? slug).split('/').filter(Boolean);\n const encoded = (segments.length ? segments : [slug]).map(encodeURIComponent).join('/');\n const params = new URLSearchParams({ token, ...(query ?? {}) });\n return `${base}/${encoded}?${params.toString()}`;\n}\n","/** 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"]}