segmind 0.5.0 → 0.6.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.
@@ -0,0 +1,186 @@
1
+ // 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, 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 = 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 {
42
+ threshold;
43
+ startFrames;
44
+ endSilenceMs;
45
+ sampleRate;
46
+ speaking = false;
47
+ loudRun = 0;
48
+ silenceMs = 0;
49
+ _level = 0;
50
+ constructor(options = {}) {
51
+ this.threshold = options.threshold ?? 700;
52
+ this.startFrames = options.startFrames ?? 2;
53
+ this.endSilenceMs = options.endSilenceMs ?? 600;
54
+ this.sampleRate = 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
+ };
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 (vad?.isSpeaking) {
122
+ vad.reset();
123
+ options.onLocalSpeech?.(false);
124
+ }
125
+ return;
126
+ }
127
+ session.sendAudio(frame);
128
+ if (!vad) return;
129
+ const decision = vad.feed(frame);
130
+ options.onLevel?.(vad.level);
131
+ if (decision === "start") {
132
+ options.onLocalSpeech?.(true);
133
+ if (replying) cut();
134
+ } else if (decision === "end") {
135
+ options.onLocalSpeech?.(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
+ export {
177
+ SESSION_SAMPLE_RATE,
178
+ pcmSeconds,
179
+ encodePcm,
180
+ decodePcm,
181
+ floatToInt16,
182
+ rms,
183
+ EnergyVad,
184
+ attachBargeIn
185
+ };
186
+ //# sourceMappingURL=chunk-USGY6G4C.js.map
@@ -0,0 +1 @@
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,SAAS,KAAK,MAAM;AAC1B,QAAM,QAAQ,IAAI,WAAW,OAAO,MAAM;AAC1C,WAAS,IAAI,GAAG,IAAI,OAAO,QAAQ,IAAK,OAAM,CAAC,IAAI,OAAO,WAAW,CAAC;AACtE,MAAI,MAAM,aAAa,EAAG,OAAM,IAAI,MAAM,2CAA2C;AACrF,SAAO,IAAI,WAAW,MAAM,MAAM;AACpC;AAGO,SAAS,aAAa,SAAmC;AAC9D,QAAM,MAAM,IAAI,WAAW,QAAQ,MAAM;AACzC,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACv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,IACpB,WAAW,aAAa,OAAO;AAC7B,cAAQ,gBAAgB,KAAK;AAAA,IAC/B;AAAA,EACF,CAAC;AAED,QAAM,WAAW,QAAQ,QAAQ,CAAC,UAAU;AAC1C,YAAQ,MAAM,MAAM;AAAA,MAClB,KAAK;AACH,sBAAc,MAAM;AACpB,mBAAW;AACX;AAAA,MACF,KAAK;AACH,YAAI,MAAM,YAAY,YAAa,UAAS,QAAQ,MAAM,KAAK;AAC/D;AAAA,MACF,KAAK;AACH,YAAI,MAAM,YAAY,aAAa;AACjC,qBAAW;AACX,cAAI,MAAM,WAAW,cAAe,UAAS,MAAM;AAAA,QACrD;AACA;AAAA,MACF,KAAK;AAEH,YAAI,SAAU,KAAI;AAAA,YACb,UAAS,MAAM;AACpB;AAAA,MACF,KAAK;AACH,iBAAS,MAAM;AACf,mBAAW;AACX;AAAA,MACF;AACE;AAAA,IACJ;AAAA,EACF,CAAC;AAED,SAAO;AAAA,IACL,QAAQ,MAAM;AACZ,eAAS;AACT,eAAS;AAAA,IACX;AAAA,IACA,IAAI,WAAW;AACb,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,258 @@
1
+ /**
2
+ * The wire vocabulary of a Segmind realtime session, as typed events.
3
+ *
4
+ * Mirrors Heimdall's `realtime/protocol.py`, session wire protocol v1.
5
+ * Control is JSON text frames both ways. Media may also travel as binary
6
+ * frames whose byte 0 names the stream (`0x01` audio, `0x02` video); the rest
7
+ * is that stream's payload in the codec `session.created.media` declares.
8
+ * The server sends audio as `audio.delta` JSON events.
9
+ */
10
+ /** The wire protocol version this client speaks (`session.created.protocol`). */
11
+ declare const PROTOCOL_VERSION = 1;
12
+ /** Byte 0 of a binary frame. Other values are reserved; the server refuses them. */
13
+ declare const STREAM_TAGS: {
14
+ readonly audio: 1;
15
+ readonly video: 2;
16
+ };
17
+ type SessionState = 'opening' | 'live' | 'closed';
18
+ /** Why a session ended. The server's vocabulary, plus three the client adds. */
19
+ type EndReason = 'client' | 'ceiling' | 'idle' | 'max_length' | 'balance_exhausted' | 'upstream_error' | 'server_shutdown' | 'internal_error' | 'metering_failed'
20
+ /**
21
+ * Close code 4008 with no `session.ended` frame and no close reason: one of
22
+ * the policy limits (ceiling, idle, max_length, balance_exhausted), which
23
+ * one is unknown.
24
+ */
25
+ | 'limit'
26
+ /** The socket closed without a `session.ended` frame. */
27
+ | 'connection_lost'
28
+ /**
29
+ * The session was refused before it opened (auth, credits, model, capacity,
30
+ * a dependency down) or spoke a protocol this client does not. The
31
+ * refusal's `code` and close code are on `SessionEnd`.
32
+ */
33
+ | 'refused';
34
+ /** Error codes the server refuses an open with, before a session exists. */
35
+ type RefusalCode = 'unauthorized' | 'token_expired' | 'token_replayed' | 'account_disabled' | 'auth_unavailable' | 'insufficient_credits' | 'unknown_model' | 'not_a_session_model' | 'model_deprecated' | 'bad_request' | 'capacity' | 'service_unavailable' | 'internal_error'
36
+ /** Client-side: `session.created.protocol` is not `PROTOCOL_VERSION`. */
37
+ | 'unsupported_protocol';
38
+ type TurnEndReason = 'completed' | 'interrupted' | 'error' | 'superseded' | 'session_closed';
39
+ /** One stream in `session.created.media`. */
40
+ interface MediaStreamSpec {
41
+ /** Byte 0 of a binary frame on this stream. */
42
+ tag: number;
43
+ /** `in` the client sends, `out` the server sends, `duplex` both. */
44
+ direction: 'in' | 'out' | 'duplex';
45
+ encoding: string;
46
+ rate?: number;
47
+ channels?: number;
48
+ mime?: string;
49
+ [key: string]: unknown;
50
+ }
51
+ /** `media.audio` as the client uses it: 16-bit little-endian PCM. */
52
+ interface AudioFormat extends MediaStreamSpec {
53
+ encoding: 'pcm_s16le';
54
+ rate: number;
55
+ channels: number;
56
+ }
57
+ interface SessionLimits {
58
+ max_session_seconds: number;
59
+ idle_seconds: number;
60
+ credit_ceiling: number;
61
+ slice_seconds: number;
62
+ minimum_charge?: number;
63
+ }
64
+ /**
65
+ * The measured facts a session is priced from. Which ones appear depends on
66
+ * the model; a voice session reports audio seconds.
67
+ */
68
+ interface UsageFacts {
69
+ input_audio_seconds?: number;
70
+ output_audio_seconds?: number;
71
+ input_tokens?: number;
72
+ output_tokens?: number;
73
+ output_video_seconds?: number;
74
+ text_inputs?: number;
75
+ [fact: string]: number | undefined;
76
+ }
77
+ interface Usage {
78
+ /** Credits moved off the balance so far. */
79
+ cost: number;
80
+ credits_confirmed: boolean;
81
+ /** Present only when the balance moved. */
82
+ remaining_credits?: number;
83
+ usage: UsageFacts;
84
+ sequence: number;
85
+ final: boolean;
86
+ }
87
+ interface SessionCreatedEvent {
88
+ type: 'session.created';
89
+ protocol: number;
90
+ session_id: string;
91
+ request_id: string;
92
+ model: string;
93
+ provider: string;
94
+ media: Record<string, MediaStreamSpec>;
95
+ limits: SessionLimits;
96
+ }
97
+ interface SessionUpdatedEvent {
98
+ type: 'session.updated';
99
+ session: Record<string, unknown>;
100
+ }
101
+ interface SessionEndedEvent {
102
+ type: 'session.ended';
103
+ reason: EndReason;
104
+ usage?: Usage;
105
+ message?: string;
106
+ }
107
+ interface InputSpeechStartedEvent {
108
+ type: 'input.speech_started';
109
+ }
110
+ interface InputSpeechStoppedEvent {
111
+ type: 'input.speech_stopped';
112
+ }
113
+ interface TurnStartedEvent {
114
+ type: 'turn.started';
115
+ turn_id: string;
116
+ input: 'text' | 'speech';
117
+ }
118
+ interface TurnEndedEvent {
119
+ type: 'turn.ended';
120
+ turn_id: string;
121
+ reason: TurnEndReason;
122
+ output_seconds: number;
123
+ time_to_first_byte?: number;
124
+ upstream_usage?: Record<string, unknown>;
125
+ }
126
+ interface AudioDeltaEvent {
127
+ type: 'audio.delta';
128
+ turn_id: string;
129
+ /** base64 of s16le PCM */
130
+ audio: string;
131
+ seconds: number;
132
+ }
133
+ interface TranscriptDeltaEvent {
134
+ type: 'transcript.delta';
135
+ turn_id: string;
136
+ role: 'assistant' | 'user';
137
+ text: string;
138
+ }
139
+ interface UsageEvent extends Usage {
140
+ type: 'segmind.usage';
141
+ }
142
+ interface ErrorEvent {
143
+ type: 'error';
144
+ code: string;
145
+ message: string;
146
+ }
147
+ interface UpstreamEvent {
148
+ type: 'upstream.event';
149
+ provider: string;
150
+ event: Record<string, unknown>;
151
+ }
152
+ interface PongEvent {
153
+ type: 'pong';
154
+ }
155
+ type ServerEvent = SessionCreatedEvent | SessionUpdatedEvent | SessionEndedEvent | InputSpeechStartedEvent | InputSpeechStoppedEvent | TurnStartedEvent | TurnEndedEvent | AudioDeltaEvent | TranscriptDeltaEvent | UsageEvent | ErrorEvent | UpstreamEvent | PongEvent;
156
+ type ServerEventType = ServerEvent['type'];
157
+ interface SessionUpdateParams {
158
+ voice?: string;
159
+ instructions?: string;
160
+ reasoning_effort?: string;
161
+ speed?: number;
162
+ vad?: boolean;
163
+ upstream_events?: boolean;
164
+ [key: string]: unknown;
165
+ }
166
+ type ClientEvent = {
167
+ type: 'session.update';
168
+ session: SessionUpdateParams;
169
+ } | {
170
+ type: 'audio.append';
171
+ audio: string;
172
+ } | {
173
+ type: 'audio.commit';
174
+ } | {
175
+ type: 'text';
176
+ text: string;
177
+ } | {
178
+ type: 'interrupt';
179
+ } | {
180
+ type: 'ping';
181
+ } | {
182
+ type: 'close';
183
+ };
184
+ /** What `POST /v1/realtime/token` returns. */
185
+ interface SessionToken {
186
+ token: string;
187
+ /** Unix seconds. */
188
+ expires_at?: number;
189
+ expires_in?: number;
190
+ model?: string;
191
+ credit_ceiling?: number;
192
+ }
193
+ /**
194
+ * How the host application obtains a session token. The client never sees
195
+ * an API key: the host's backend trades its key (or the signed-in user's
196
+ * session) for a short-lived token scoped to one model and a credit ceiling.
197
+ */
198
+ type SessionTokenProvider = (slug: string) => Promise<SessionToken | string>;
199
+
200
+ interface SegmindErrorOptions {
201
+ status?: number;
202
+ detail?: string;
203
+ requestId?: string;
204
+ body?: unknown;
205
+ cause?: unknown;
206
+ }
207
+ /** Base class of every error the SDK throws (except an `AbortSignal`'s own reason). */
208
+ declare class SegmindError extends Error {
209
+ /** HTTP status, when the error came from a response. */
210
+ readonly status: number | undefined;
211
+ /** The server's error text (`error` in the response body), when it sent one. */
212
+ readonly detail: string | undefined;
213
+ /** The v2 request id the error belongs to, when there is one. */
214
+ readonly requestId: string | undefined;
215
+ /** The parsed response body, or its text when it was not JSON. */
216
+ readonly body: unknown;
217
+ constructor(message: string, options?: SegmindErrorOptions);
218
+ /** Reads the response body and builds the error. Consumes the body. */
219
+ static fromResponse(response: Response, requestId?: string): Promise<SegmindError>;
220
+ }
221
+ /** The request never got a response: DNS, TLS, connection reset, or the client's timeout. */
222
+ declare class APIConnectionError extends SegmindError {
223
+ }
224
+ /**
225
+ * The account cannot pay for the request. The gateway reports this at submit, or
226
+ * as a failed job when the balance is positive but below the model's cost, so
227
+ * this one class covers both. `detail` holds the server's message.
228
+ */
229
+ declare class InsufficientCredits extends SegmindError {
230
+ }
231
+ /**
232
+ * Too many requests, after the SDK's own retries for calls that are safe to
233
+ * repeat. `retryAfterMs` is set when the server sent `Retry-After` and the
234
+ * runtime could read it: a browser only sees the header if the server exposes it.
235
+ */
236
+ declare class RateLimited extends SegmindError {
237
+ readonly retryAfterMs: number | undefined;
238
+ constructor(message: string, options?: SegmindErrorOptions & {
239
+ retryAfterMs?: number;
240
+ });
241
+ }
242
+ /** A v2 request reached `FAILED`. The server's error text is in `detail`. */
243
+ declare class InferenceFailed extends SegmindError {
244
+ /** The status body that reported the failure. */
245
+ readonly statusBody: Record<string, unknown>;
246
+ constructor(requestId: string, statusBody: Record<string, unknown>, detail?: string);
247
+ }
248
+ /**
249
+ * `wait()` ran past its timeout. The request may still finish on the server:
250
+ * `job.status()` or a new `wait()` picks it up again.
251
+ */
252
+ declare class InferenceTimeout extends SegmindError {
253
+ readonly elapsedMs: number;
254
+ constructor(requestId: string, elapsedMs: number);
255
+ }
256
+
257
+ export { APIConnectionError as A, InferenceFailed as I, PROTOCOL_VERSION as P, RateLimited as R, InferenceTimeout as b, InsufficientCredits as c, SegmindError as d, STREAM_TAGS as n };
258
+ export type { ClientEvent as C, EndReason as E, MediaStreamSpec as M, SessionToken as S, TranscriptDeltaEvent as T, UpstreamEvent as U, SessionTokenProvider as a, SessionCreatedEvent as e, AudioFormat as f, ServerEvent as g, AudioDeltaEvent as h, ErrorEvent as i, InputSpeechStartedEvent as j, InputSpeechStoppedEvent as k, PongEvent as l, RefusalCode as m, ServerEventType as o, SessionEndedEvent as p, SessionLimits as q, SessionState as r, SessionUpdateParams as s, SessionUpdatedEvent as t, TurnEndReason as u, TurnEndedEvent as v, TurnStartedEvent as w, Usage as x, UsageEvent as y, UsageFacts as z };