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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/realtime/types.ts","../src/realtime/protocol.ts","../src/realtime/pcm.ts","../src/realtime/vad.ts","../src/realtime/barge-in.ts"],"sourcesContent":["/**\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"],"mappings":";;;;;AAaO,IAAM,mBAAmB;AAGzB,IAAM,cAAc,EAAE,OAAO,GAAM,OAAO,EAAK;;;ACHtD,IAAM,qBAAqB,oBAAI,IAAY;AAAA,EACzC;AAAA,EACA;AA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AK;AAC/B,YAAQ,UAAU,IAAI,KAAK;AAC3B,QAAI,aAAa,SAAS;AACxB,cAAQ,gBAAgB,IAAI;AAC5B,UAAI,SAAU,KAAI;AAAA,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":[]}
@@ -5,7 +5,9 @@
5
5
  * Control is JSON text frames both ways. Media may also travel as binary
6
6
  * frames whose byte 0 names the stream (`0x01` audio, `0x02` video); the rest
7
7
  * is that stream's payload in the codec `session.created.media` declares.
8
- * The server sends audio as `audio.delta` JSON events.
8
+ * The server sends audio as `audio.delta` JSON events. A video session's
9
+ * streams travel over WebRTC instead (`transport: "webrtc"`), negotiated
10
+ * through `webrtc.*` events on this socket; see `segmind/realtime/browser`.
9
11
  */
10
12
  /** The wire protocol version this client speaks (`session.created.protocol`). */
11
13
  declare const PROTOCOL_VERSION = 1;
@@ -17,6 +19,8 @@ declare const STREAM_TAGS: {
17
19
  type SessionState = 'opening' | 'live' | 'closed';
18
20
  /** Why a session ended. The server's vocabulary, plus three the client adds. */
19
21
  type EndReason = 'client' | 'ceiling' | 'idle' | 'max_length' | 'balance_exhausted' | 'upstream_error' | 'server_shutdown' | 'internal_error' | 'metering_failed'
22
+ /** A video session's upstream moderation ended it (close 4008). */
23
+ | 'content_policy'
20
24
  /**
21
25
  * Close code 4008 with no `session.ended` frame and no close reason: one of
22
26
  * the policy limits (ceiling, idle, max_length, balance_exhausted), which
@@ -32,24 +36,40 @@ type EndReason = 'client' | 'ceiling' | 'idle' | 'max_length' | 'balance_exhaust
32
36
  */
33
37
  | 'refused';
34
38
  /** 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'
39
+ type RefusalCode = 'unauthorized' | 'token_expired' | 'token_replayed' | 'account_disabled' | 'auth_unavailable' | 'insufficient_credits' | 'unknown_model' | 'not_a_session_model' | 'model_deprecated' | 'bad_request'
40
+ /** The credit ceiling cannot cover the model's minimum charge (close 4000). */
41
+ | 'ceiling_too_low'
42
+ /** The API key's scope excludes the model (close 4001). */
43
+ | 'forbidden' | 'capacity' | 'service_unavailable' | 'internal_error'
36
44
  /** Client-side: `session.created.protocol` is not `PROTOCOL_VERSION`. */
37
45
  | 'unsupported_protocol';
38
46
  type TurnEndReason = 'completed' | 'interrupted' | 'error' | 'superseded' | 'session_closed';
39
- /** One stream in `session.created.media`. */
47
+ /**
48
+ * One stream in `session.created.media`. A stream on the socket names its
49
+ * binary `tag` and `encoding`; a stream with `transport: "webrtc"` flows
50
+ * between the client and the upstream over WebRTC and names neither.
51
+ */
40
52
  interface MediaStreamSpec {
41
- /** Byte 0 of a binary frame on this stream. */
42
- tag: number;
53
+ /** Byte 0 of a binary frame on this stream. Absent on a WebRTC stream. */
54
+ tag?: number;
43
55
  /** `in` the client sends, `out` the server sends, `duplex` both. */
44
56
  direction: 'in' | 'out' | 'duplex';
45
- encoding: string;
57
+ /** Absent on a WebRTC stream. */
58
+ encoding?: string;
59
+ /** `webrtc`: the stream never touches the socket. Absent means the socket. */
60
+ transport?: 'webrtc' | (string & {});
46
61
  rate?: number;
47
62
  channels?: number;
48
63
  mime?: string;
64
+ /** Video: the frame size and rate the upstream expects or sends. */
65
+ width?: number;
66
+ height?: number;
67
+ fps?: number;
49
68
  [key: string]: unknown;
50
69
  }
51
70
  /** `media.audio` as the client uses it: 16-bit little-endian PCM. */
52
71
  interface AudioFormat extends MediaStreamSpec {
72
+ tag: number;
53
73
  encoding: 'pcm_s16le';
54
74
  rate: number;
55
75
  channels: number;
@@ -93,7 +113,15 @@ interface SessionCreatedEvent {
93
113
  provider: string;
94
114
  media: Record<string, MediaStreamSpec>;
95
115
  limits: SessionLimits;
116
+ /**
117
+ * Where a video session is steered: `session` (`video.prompt` /
118
+ * `video.image` on this socket) or `datachannel` (the upstream's own
119
+ * WebRTC data channel). Absent on a session without WebRTC streams.
120
+ */
121
+ control?: VideoControl;
96
122
  }
123
+ /** Where a video session's steering goes; see `SessionCreatedEvent.control`. */
124
+ type VideoControl = 'session' | 'datachannel';
97
125
  interface SessionUpdatedEvent {
98
126
  type: 'session.updated';
99
127
  session: Record<string, unknown>;
@@ -152,7 +180,58 @@ interface UpstreamEvent {
152
180
  interface PongEvent {
153
181
  type: 'pong';
154
182
  }
155
- type ServerEvent = SessionCreatedEvent | SessionUpdatedEvent | SessionEndedEvent | InputSpeechStartedEvent | InputSpeechStoppedEvent | TurnStartedEvent | TurnEndedEvent | AudioDeltaEvent | TranscriptDeltaEvent | UsageEvent | ErrorEvent | UpstreamEvent | PongEvent;
183
+ /** One ICE server, as `RTCConfiguration.iceServers` takes it. */
184
+ interface IceServer {
185
+ urls: string | string[];
186
+ username?: string;
187
+ credential?: string;
188
+ }
189
+ /** An ICE candidate, as `RTCIceCandidate.toJSON()` gives it. */
190
+ interface IceCandidateJson {
191
+ candidate?: string;
192
+ sdpMid?: string | null;
193
+ sdpMLineIndex?: number | null;
194
+ usernameFragment?: string | null;
195
+ }
196
+ /** Gather with these ICE servers, then send the offer. */
197
+ interface WebrtcConfigEvent {
198
+ type: 'webrtc.config';
199
+ ice_servers: IceServer[];
200
+ /** True: gather every candidate, then send one offer; no trickle ICE. */
201
+ complete_offer: boolean;
202
+ }
203
+ interface WebrtcAnswerEvent {
204
+ type: 'webrtc.answer';
205
+ sdp: string;
206
+ ice_servers?: IceServer[];
207
+ }
208
+ /** A remote ICE candidate; null ends the upstream's candidates. */
209
+ interface WebrtcCandidateEvent {
210
+ type: 'webrtc.candidate';
211
+ candidate: IceCandidateJson | null;
212
+ }
213
+ /** Reconfigure the peer with these servers and send a new offer with `iceRestart`. */
214
+ interface WebrtcRestartEvent {
215
+ type: 'webrtc.restart';
216
+ ice_servers: IceServer[];
217
+ }
218
+ /** Generation began; video is flowing. */
219
+ interface VideoStartedEvent {
220
+ type: 'video.started';
221
+ }
222
+ /** Seconds of video generated so far, as billed. */
223
+ interface VideoProgressEvent {
224
+ type: 'video.progress';
225
+ seconds: number;
226
+ }
227
+ /** The upstream's verdict on a `video.prompt` or `video.image`, in the order they were sent. */
228
+ interface VideoPromptAckEvent {
229
+ type: 'video.prompt_ack';
230
+ kind: 'prompt' | 'image';
231
+ applied: boolean;
232
+ reason?: string;
233
+ }
234
+ type ServerEvent = SessionCreatedEvent | SessionUpdatedEvent | SessionEndedEvent | InputSpeechStartedEvent | InputSpeechStoppedEvent | TurnStartedEvent | TurnEndedEvent | AudioDeltaEvent | TranscriptDeltaEvent | UsageEvent | ErrorEvent | UpstreamEvent | PongEvent | WebrtcConfigEvent | WebrtcAnswerEvent | WebrtcCandidateEvent | WebrtcRestartEvent | VideoStartedEvent | VideoProgressEvent | VideoPromptAckEvent;
156
235
  type ServerEventType = ServerEvent['type'];
157
236
  interface SessionUpdateParams {
158
237
  voice?: string;
@@ -180,6 +259,32 @@ type ClientEvent = {
180
259
  type: 'ping';
181
260
  } | {
182
261
  type: 'close';
262
+ } | {
263
+ type: 'webrtc.offer';
264
+ sdp: string;
265
+ }
266
+ /** null: the end of candidates. */
267
+ | {
268
+ type: 'webrtc.candidate';
269
+ candidate: IceCandidateJson | null;
270
+ }
271
+ /** `text` up to 20,000 characters; `enhance` defaults to true on the server. */
272
+ | {
273
+ type: 'video.prompt';
274
+ text: string;
275
+ enhance?: boolean;
276
+ }
277
+ /** `image` base64 (no `data:` prefix), or null to clear the reference. */
278
+ | {
279
+ type: 'video.image';
280
+ image: string | null;
281
+ text?: string;
282
+ enhance?: boolean;
283
+ }
284
+ /** An upstream data-channel event the client received, mirrored for the record. Never billed from. */
285
+ | {
286
+ type: 'video.report';
287
+ event: Record<string, unknown>;
183
288
  };
184
289
  /** What `POST /v1/realtime/token` returns. */
185
290
  interface SessionToken {
@@ -254,5 +359,5 @@ declare class InferenceTimeout extends SegmindError {
254
359
  constructor(requestId: string, elapsedMs: number);
255
360
  }
256
361
 
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 };
362
+ 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 p };
363
+ export type { UsageEvent as B, ClientEvent as C, UsageFacts as D, EndReason as E, VideoProgressEvent as F, VideoPromptAckEvent as G, VideoStartedEvent as H, WebrtcCandidateEvent as J, WebrtcConfigEvent as K, WebrtcRestartEvent as L, MediaStreamSpec as M, SessionToken as S, TranscriptDeltaEvent as T, UpstreamEvent as U, VideoControl as V, WebrtcAnswerEvent as W, SessionTokenProvider as a, IceCandidateJson as e, IceServer as f, SessionCreatedEvent as g, AudioFormat as h, ServerEvent as i, AudioDeltaEvent as j, ErrorEvent as k, InputSpeechStartedEvent as l, InputSpeechStoppedEvent as m, PongEvent as n, RefusalCode as o, ServerEventType as q, SessionEndedEvent as r, SessionLimits as s, SessionState as t, SessionUpdateParams as u, SessionUpdatedEvent as v, TurnEndReason as w, TurnEndedEvent as x, TurnStartedEvent as y, Usage as z };
@@ -5,7 +5,9 @@
5
5
  * Control is JSON text frames both ways. Media may also travel as binary
6
6
  * frames whose byte 0 names the stream (`0x01` audio, `0x02` video); the rest
7
7
  * is that stream's payload in the codec `session.created.media` declares.
8
- * The server sends audio as `audio.delta` JSON events.
8
+ * The server sends audio as `audio.delta` JSON events. A video session's
9
+ * streams travel over WebRTC instead (`transport: "webrtc"`), negotiated
10
+ * through `webrtc.*` events on this socket; see `segmind/realtime/browser`.
9
11
  */
10
12
  /** The wire protocol version this client speaks (`session.created.protocol`). */
11
13
  declare const PROTOCOL_VERSION = 1;
@@ -17,6 +19,8 @@ declare const STREAM_TAGS: {
17
19
  type SessionState = 'opening' | 'live' | 'closed';
18
20
  /** Why a session ended. The server's vocabulary, plus three the client adds. */
19
21
  type EndReason = 'client' | 'ceiling' | 'idle' | 'max_length' | 'balance_exhausted' | 'upstream_error' | 'server_shutdown' | 'internal_error' | 'metering_failed'
22
+ /** A video session's upstream moderation ended it (close 4008). */
23
+ | 'content_policy'
20
24
  /**
21
25
  * Close code 4008 with no `session.ended` frame and no close reason: one of
22
26
  * the policy limits (ceiling, idle, max_length, balance_exhausted), which
@@ -32,24 +36,40 @@ type EndReason = 'client' | 'ceiling' | 'idle' | 'max_length' | 'balance_exhaust
32
36
  */
33
37
  | 'refused';
34
38
  /** 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'
39
+ type RefusalCode = 'unauthorized' | 'token_expired' | 'token_replayed' | 'account_disabled' | 'auth_unavailable' | 'insufficient_credits' | 'unknown_model' | 'not_a_session_model' | 'model_deprecated' | 'bad_request'
40
+ /** The credit ceiling cannot cover the model's minimum charge (close 4000). */
41
+ | 'ceiling_too_low'
42
+ /** The API key's scope excludes the model (close 4001). */
43
+ | 'forbidden' | 'capacity' | 'service_unavailable' | 'internal_error'
36
44
  /** Client-side: `session.created.protocol` is not `PROTOCOL_VERSION`. */
37
45
  | 'unsupported_protocol';
38
46
  type TurnEndReason = 'completed' | 'interrupted' | 'error' | 'superseded' | 'session_closed';
39
- /** One stream in `session.created.media`. */
47
+ /**
48
+ * One stream in `session.created.media`. A stream on the socket names its
49
+ * binary `tag` and `encoding`; a stream with `transport: "webrtc"` flows
50
+ * between the client and the upstream over WebRTC and names neither.
51
+ */
40
52
  interface MediaStreamSpec {
41
- /** Byte 0 of a binary frame on this stream. */
42
- tag: number;
53
+ /** Byte 0 of a binary frame on this stream. Absent on a WebRTC stream. */
54
+ tag?: number;
43
55
  /** `in` the client sends, `out` the server sends, `duplex` both. */
44
56
  direction: 'in' | 'out' | 'duplex';
45
- encoding: string;
57
+ /** Absent on a WebRTC stream. */
58
+ encoding?: string;
59
+ /** `webrtc`: the stream never touches the socket. Absent means the socket. */
60
+ transport?: 'webrtc' | (string & {});
46
61
  rate?: number;
47
62
  channels?: number;
48
63
  mime?: string;
64
+ /** Video: the frame size and rate the upstream expects or sends. */
65
+ width?: number;
66
+ height?: number;
67
+ fps?: number;
49
68
  [key: string]: unknown;
50
69
  }
51
70
  /** `media.audio` as the client uses it: 16-bit little-endian PCM. */
52
71
  interface AudioFormat extends MediaStreamSpec {
72
+ tag: number;
53
73
  encoding: 'pcm_s16le';
54
74
  rate: number;
55
75
  channels: number;
@@ -93,7 +113,15 @@ interface SessionCreatedEvent {
93
113
  provider: string;
94
114
  media: Record<string, MediaStreamSpec>;
95
115
  limits: SessionLimits;
116
+ /**
117
+ * Where a video session is steered: `session` (`video.prompt` /
118
+ * `video.image` on this socket) or `datachannel` (the upstream's own
119
+ * WebRTC data channel). Absent on a session without WebRTC streams.
120
+ */
121
+ control?: VideoControl;
96
122
  }
123
+ /** Where a video session's steering goes; see `SessionCreatedEvent.control`. */
124
+ type VideoControl = 'session' | 'datachannel';
97
125
  interface SessionUpdatedEvent {
98
126
  type: 'session.updated';
99
127
  session: Record<string, unknown>;
@@ -152,7 +180,58 @@ interface UpstreamEvent {
152
180
  interface PongEvent {
153
181
  type: 'pong';
154
182
  }
155
- type ServerEvent = SessionCreatedEvent | SessionUpdatedEvent | SessionEndedEvent | InputSpeechStartedEvent | InputSpeechStoppedEvent | TurnStartedEvent | TurnEndedEvent | AudioDeltaEvent | TranscriptDeltaEvent | UsageEvent | ErrorEvent | UpstreamEvent | PongEvent;
183
+ /** One ICE server, as `RTCConfiguration.iceServers` takes it. */
184
+ interface IceServer {
185
+ urls: string | string[];
186
+ username?: string;
187
+ credential?: string;
188
+ }
189
+ /** An ICE candidate, as `RTCIceCandidate.toJSON()` gives it. */
190
+ interface IceCandidateJson {
191
+ candidate?: string;
192
+ sdpMid?: string | null;
193
+ sdpMLineIndex?: number | null;
194
+ usernameFragment?: string | null;
195
+ }
196
+ /** Gather with these ICE servers, then send the offer. */
197
+ interface WebrtcConfigEvent {
198
+ type: 'webrtc.config';
199
+ ice_servers: IceServer[];
200
+ /** True: gather every candidate, then send one offer; no trickle ICE. */
201
+ complete_offer: boolean;
202
+ }
203
+ interface WebrtcAnswerEvent {
204
+ type: 'webrtc.answer';
205
+ sdp: string;
206
+ ice_servers?: IceServer[];
207
+ }
208
+ /** A remote ICE candidate; null ends the upstream's candidates. */
209
+ interface WebrtcCandidateEvent {
210
+ type: 'webrtc.candidate';
211
+ candidate: IceCandidateJson | null;
212
+ }
213
+ /** Reconfigure the peer with these servers and send a new offer with `iceRestart`. */
214
+ interface WebrtcRestartEvent {
215
+ type: 'webrtc.restart';
216
+ ice_servers: IceServer[];
217
+ }
218
+ /** Generation began; video is flowing. */
219
+ interface VideoStartedEvent {
220
+ type: 'video.started';
221
+ }
222
+ /** Seconds of video generated so far, as billed. */
223
+ interface VideoProgressEvent {
224
+ type: 'video.progress';
225
+ seconds: number;
226
+ }
227
+ /** The upstream's verdict on a `video.prompt` or `video.image`, in the order they were sent. */
228
+ interface VideoPromptAckEvent {
229
+ type: 'video.prompt_ack';
230
+ kind: 'prompt' | 'image';
231
+ applied: boolean;
232
+ reason?: string;
233
+ }
234
+ type ServerEvent = SessionCreatedEvent | SessionUpdatedEvent | SessionEndedEvent | InputSpeechStartedEvent | InputSpeechStoppedEvent | TurnStartedEvent | TurnEndedEvent | AudioDeltaEvent | TranscriptDeltaEvent | UsageEvent | ErrorEvent | UpstreamEvent | PongEvent | WebrtcConfigEvent | WebrtcAnswerEvent | WebrtcCandidateEvent | WebrtcRestartEvent | VideoStartedEvent | VideoProgressEvent | VideoPromptAckEvent;
156
235
  type ServerEventType = ServerEvent['type'];
157
236
  interface SessionUpdateParams {
158
237
  voice?: string;
@@ -180,6 +259,32 @@ type ClientEvent = {
180
259
  type: 'ping';
181
260
  } | {
182
261
  type: 'close';
262
+ } | {
263
+ type: 'webrtc.offer';
264
+ sdp: string;
265
+ }
266
+ /** null: the end of candidates. */
267
+ | {
268
+ type: 'webrtc.candidate';
269
+ candidate: IceCandidateJson | null;
270
+ }
271
+ /** `text` up to 20,000 characters; `enhance` defaults to true on the server. */
272
+ | {
273
+ type: 'video.prompt';
274
+ text: string;
275
+ enhance?: boolean;
276
+ }
277
+ /** `image` base64 (no `data:` prefix), or null to clear the reference. */
278
+ | {
279
+ type: 'video.image';
280
+ image: string | null;
281
+ text?: string;
282
+ enhance?: boolean;
283
+ }
284
+ /** An upstream data-channel event the client received, mirrored for the record. Never billed from. */
285
+ | {
286
+ type: 'video.report';
287
+ event: Record<string, unknown>;
183
288
  };
184
289
  /** What `POST /v1/realtime/token` returns. */
185
290
  interface SessionToken {
@@ -254,5 +359,5 @@ declare class InferenceTimeout extends SegmindError {
254
359
  constructor(requestId: string, elapsedMs: number);
255
360
  }
256
361
 
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 };
362
+ 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 p };
363
+ export type { UsageEvent as B, ClientEvent as C, UsageFacts as D, EndReason as E, VideoProgressEvent as F, VideoPromptAckEvent as G, VideoStartedEvent as H, WebrtcCandidateEvent as J, WebrtcConfigEvent as K, WebrtcRestartEvent as L, MediaStreamSpec as M, SessionToken as S, TranscriptDeltaEvent as T, UpstreamEvent as U, VideoControl as V, WebrtcAnswerEvent as W, SessionTokenProvider as a, IceCandidateJson as e, IceServer as f, SessionCreatedEvent as g, AudioFormat as h, ServerEvent as i, AudioDeltaEvent as j, ErrorEvent as k, InputSpeechStartedEvent as l, InputSpeechStoppedEvent as m, PongEvent as n, RefusalCode as o, ServerEventType as q, SessionEndedEvent as r, SessionLimits as s, SessionState as t, SessionUpdateParams as u, SessionUpdatedEvent as v, TurnEndReason as w, TurnEndedEvent as x, TurnStartedEvent as y, Usage as z };