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.
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/segmind-js/segmind-js/packages/segmind/dist/realtime/index.cjs","../../src/realtime/types.ts","../../src/realtime/protocol.ts","../../src/realtime/session.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACF,yDAA8B;AAC9B;AACA;ACHO,IAAM,iBAAA,EAAmB,CAAA;AAGzB,IAAM,YAAA,EAAc,EAAE,KAAA,EAAO,CAAA,EAAM,KAAA,EAAO,EAAK,CAAA;ADGtD;AACA;AEPA,IAAM,mBAAA,kBAAqB,IAAI,GAAA,CAAY;AAAA,EACzC,iBAAA;AAAA,EACA,iBAAA;AAAA,EACA,eAAA;AAAA,EACA,sBAAA;AAAA,EACA,sBAAA;AAAA,EACA,cAAA;AAAA,EACA,YAAA;AAAA,EACA,aAAA;AAAA,EACA,kBAAA;AAAA,EACA,eAAA;AAAA,EACA,OAAA;AAAA,EACA,gBAAA;AAAA,EACA;AACF,CAAC,CAAA;AAGM,IAAM,cAAA,EAAN,MAAA,QAA4B,+BAAa;AAAA,EAC9C,WAAA,CACE,OAAA,EACgB,GAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAA,EAAS,EAAE,IAAA,EAAM,IAAI,CAAC,CAAA;AAFZ,IAAA,IAAA,CAAA,IAAA,EAAA,GAAA;AAAA,EAGlB;AAAA,EAHkB;AAIpB,CAAA;AAGO,SAAS,iBAAA,CAAkB,IAAA,EAA2B;AAC3D,EAAA,IAAI,MAAA;AACJ,EAAA,IAAI;AACF,IAAA,OAAA,EAAS,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA;AAAA,EAC1B,EAAA,UAAQ;AACN,IAAA,MAAM,IAAI,aAAA,CAAc,0BAAA,EAA4B,IAAI,CAAA;AAAA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,IAAA;AACN,IAAA;AAC+B,IAAA;AACvC,MAAA;AACyB,QAAA;AACrB,MAAA;AAER,MAAA;AACF,IAAA;AACiD,IAAA;AACA,IAAA;AACU,IAAA;AAC/C,IAAA;AACkB,IAAA;AACT,IAAA;AACvB,EAAA;AAE+B,EAAA;AACU,IAAA;AAC1B,IAAA;AAC+B,IAAA;AACZ,IAAA;AACkB,MAAA;AAC7C,IAAA;AACP,EAAA;AAE8B,EAAA;AACC,IAAA;AACgC,MAAA;AAC1C,MAAA;AACnB,IAAA;AACF,EAAA;AAEgE,EAAA;AAChD,IAAA;AACoD,IAAA;AACpE,EAAA;AAEuC,EAAA;AACqB,IAAA;AAC5D,EAAA;AACF;AAM4B;AAC2B,EAAA;AAAxB,IAAA;AACiC,IAAA;AAC9D,EAAA;AAF6B,EAAA;AAAA;AAKoC,EAAA;AACT,IAAA;AACxD,EAAA;AAAA;AAGgF,EAAA;AACpC,IAAA;AACvB,IAAA;AACZ,IAAA;AACT,EAAA;AACF;AAgByG;AAClC,EAAA;AACL,EAAA;AAClE;AHpDuE;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;AACA;AACA","file":"/home/runner/work/segmind-js/segmind-js/packages/segmind/dist/realtime/index.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.\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 /**\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 | '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/** One stream in `session.created.media`. */\nexport interface MediaStreamSpec {\n /** Byte 0 of a binary frame on this stream. */\n tag: number;\n /** `in` the client sends, `out` the server sends, `duplex` both. */\n direction: 'in' | 'out' | 'duplex';\n encoding: string;\n rate?: number;\n channels?: number;\n mime?: string;\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 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\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\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\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\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 ServerEvent,\n type SessionCreatedEvent,\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]);\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]);\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/** 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","/**\n * A managed realtime session: one primitive, explicit states, typed events,\n * and a `close()` that resolves with what the session cost.\n *\n * `opening` the token is being minted and the socket is connecting; sends\n * are queued (bounded) and flushed once the server says\n * `session.created`.\n * `live` sends go straight to the socket; a `ping` keeps the connection\n * warm.\n * `closed` terminal. Every ending reaches it exactly once: the server's\n * `session.ended`, a refusal before the session opened, or a\n * socket close with no frame (reason from the close code).\n *\n * A handle that has closed can never write again: `send*` after `closed`\n * returns false and does nothing.\n *\n * Nothing here touches the DOM or a browser global: the socket comes from\n * `webSocketFactory` (the runtime's `WebSocket` when none is given), so the\n * same core runs in a browser, React Native or Node.\n */\n\nimport { SegmindError } from '../core/errors';\nimport {\n acceptsInput,\n audioFormat,\n decodeServerEvent,\n encodeClientEvent,\n mediaFrame,\n reasonFromCloseCode,\n sessionUrl,\n unsupportedSession,\n} from './protocol';\nimport type {\n AudioFormat,\n ClientEvent,\n EndReason,\n ServerEvent,\n SessionCreatedEvent,\n SessionState,\n ServerEventType,\n SessionTokenProvider,\n SessionUpdateParams,\n Usage,\n} from './types';\n\n/** The production session service. */\nexport const DEFAULT_REALTIME_URL = 'wss://rt.segmind.com';\n\nexport interface SessionOptions {\n /** Session parameters sent on the query string (voice, instructions, vad…). */\n params?: Record<string, string>;\n /** The session's path on the service, from the model record's\n * `endpoints.session`. Default `/<slug>`. */\n path?: string;\n /** Milliseconds between `ping` frames while live. 0 disables. Default 15000. */\n heartbeatMs?: number;\n /** Sends queued while opening, beyond which `send*` returns false. Default 64. */\n maxQueuedSends?: number;\n /** Aborting closes the session, or cancels the open while it is still opening. */\n signal?: AbortSignal;\n}\n\nexport interface ClientOptions {\n /** Where the session service lives. Default `wss://rt.segmind.com`. */\n realtimeRoot?: string;\n /**\n * Trades the app's credentials for a short-lived session token. In a browser\n * or a phone app it calls the app's own backend, which calls\n * `segmind.realtime.createToken()`; the API key never leaves the server.\n */\n tokenProvider: SessionTokenProvider;\n /** How to open the socket. Default: the runtime's global `WebSocket`. */\n webSocketFactory?: (url: string) => WebSocketLike;\n /** Injectable clock for tests. */\n setInterval?: typeof setInterval;\n clearInterval?: typeof clearInterval;\n}\n\n/** The subset of WebSocket the session needs, so tests can fake it. */\nexport interface WebSocketLike {\n readonly readyState: number;\n binaryType?: string;\n send(data: string | ArrayBuffer): void;\n close(code?: number, reason?: string): void;\n onopen: ((ev: unknown) => void) | null;\n onmessage: ((ev: { data: unknown }) => void) | null;\n onclose: ((ev: { code: number; reason: string }) => void) | null;\n onerror: ((ev: unknown) => void) | null;\n}\n\nconst WS_OPEN = 1;\n\nexport type EventListener = (event: ServerEvent) => void;\n/** A listener for one event type, typed by it. */\nexport type TypedEventListener<T extends ServerEventType> = (event: Extract<ServerEvent, { type: T }>) => void;\nexport type StateListener = (state: SessionState, reason?: EndReason) => void;\n\nexport interface SessionEnd {\n reason: EndReason;\n usage: Usage | null;\n message?: string;\n /**\n * For a refusal, the server's error code (`insufficient_credits`,\n * `capacity`, `service_unavailable`…), or `unsupported_protocol`.\n */\n code?: string;\n /** The socket close code, when the ending came from a close rather than `session.ended`. */\n closeCode?: number;\n}\n\n/** A send made while opening: a JSON frame, or microphone PCM tagged once the stream is known. */\ntype QueuedSend = { text: string } | { pcm: ArrayBuffer };\n\n/**\n * `open()` rejects with this when the session ends before it is live. `end`\n * keeps the refusal's code and close code: branch on `end.code`\n * (`insufficient_credits`, `capacity`…) rather than parsing the message.\n */\nexport class SessionOpenError extends SegmindError {\n constructor(public readonly end: SessionEnd) {\n super(\n `session ${end.reason} before it opened` +\n (end.code ? ` (${end.code}${end.message ? `: ${end.message}` : ''})` : ''),\n { status: end.closeCode, detail: end.message },\n );\n }\n\n /** The server's refusal code (`insufficient_credits`, `capacity`, `token_expired`…), when there is one. */\n get code(): string | undefined {\n return this.end.code;\n }\n}\n\nfunction defaultWebSocket(url: string): WebSocketLike {\n const Ctor = (globalThis as { WebSocket?: new (url: string) => unknown }).WebSocket;\n if (!Ctor) throw new SegmindError('no global WebSocket in this runtime: pass webSocketFactory');\n return new Ctor(url) as WebSocketLike;\n}\n\nfunction pcmBytes(pcm: Int16Array | ArrayBuffer): ArrayBuffer {\n return pcm instanceof Int16Array\n ? (pcm.buffer.slice(pcm.byteOffset, pcm.byteOffset + pcm.byteLength) as ArrayBuffer)\n : pcm;\n}\n\nexport class RealtimeSession {\n private _state: SessionState = 'opening';\n private _reason: EndReason | null = null;\n private _usage: Usage | null = null;\n private _end: SessionEnd | null = null;\n private _created: SessionCreatedEvent | null = null;\n private socket: WebSocketLike | null = null;\n private readonly queue: QueuedSend[] = [];\n private readonly eventListeners = new Set<EventListener>();\n private readonly stateListeners = new Set<StateListener>();\n private readonly ended: Promise<SessionEnd>;\n private resolveEnded!: (end: SessionEnd) => void;\n private heartbeat: ReturnType<typeof setInterval> | null = null;\n private sawEndedFrame = false;\n private opening = false;\n private closeRequested = false;\n /** The `error` frame of a refusal, held until the close that follows carries its code. */\n private refusal: { code: string; message: string } | null = null;\n\n constructor(\n public readonly slug: string,\n private readonly client: ClientOptions,\n private readonly options: SessionOptions = {},\n ) {\n this.ended = new Promise<SessionEnd>((resolve) => {\n this.resolveEnded = resolve;\n });\n }\n\n // --- observable state -------------------------------------------------------\n\n get state(): SessionState {\n return this._state;\n }\n\n get reason(): EndReason | null {\n return this._reason;\n }\n\n /** The final usage, once the session has closed. */\n get usage(): Usage | null {\n return this._usage;\n }\n\n /** How the session ended (reason, usage, refusal code, close code), once closed. */\n get end(): SessionEnd | null {\n return this._end;\n }\n\n /** The `session.created` frame, once live. */\n get created(): SessionCreatedEvent | null {\n return this._created;\n }\n\n /**\n * The session's audio stream (`session.created.media.audio`): its rate,\n * channels and binary tag. Null before live, or for a session without\n * 16-bit PCM audio. Size capture and playback from it.\n */\n get audio(): AudioFormat | null {\n return audioFormat(this._created);\n }\n\n /** Every server event. Returns a function that removes the listener. */\n onEvent(listener: EventListener): () => void {\n this.eventListeners.add(listener);\n return () => this.eventListeners.delete(listener);\n }\n\n /** One event type, typed by it: `session.on('transcript.delta', (e) => e.text)`. */\n on<T extends ServerEventType>(type: T, listener: TypedEventListener<T>): () => void {\n return this.onEvent((event) => {\n if (event.type === type) listener(event as Extract<ServerEvent, { type: T }>);\n });\n }\n\n onState(listener: StateListener): () => void {\n this.stateListeners.add(listener);\n return () => this.stateListeners.delete(listener);\n }\n\n /** Every server event as an async iterable; ends when the session closes. */\n events(): AsyncIterable<ServerEvent> {\n const buffer: ServerEvent[] = [];\n let wake: (() => void) | null = null;\n let done = this._state === 'closed';\n const unsubscribe = this.onEvent((event) => {\n buffer.push(event);\n wake?.();\n });\n const unsubscribeState = this.onState((state) => {\n if (state === 'closed') {\n done = true;\n wake?.();\n }\n });\n return {\n [Symbol.asyncIterator]: () => ({\n next: async (): Promise<IteratorResult<ServerEvent>> => {\n while (buffer.length === 0 && !done) {\n await new Promise<void>((resolve) => {\n wake = resolve;\n });\n wake = null;\n }\n const event = buffer.shift();\n if (event) return { value: event, done: false };\n unsubscribe();\n unsubscribeState();\n return { value: undefined, done: true };\n },\n return: async (): Promise<IteratorResult<ServerEvent>> => {\n unsubscribe();\n unsubscribeState();\n return { value: undefined, done: true };\n },\n }),\n };\n }\n\n // --- lifecycle --------------------------------------------------------------\n\n /** Mint a token and connect. Resolves when the session is live, rejects when refused. */\n async open(): Promise<SessionCreatedEvent> {\n if (this._state !== 'opening' || this.socket || this.opening) {\n throw new SegmindError('session can only be opened once');\n }\n this.opening = true;\n const { signal } = this.options;\n if (signal) {\n if (signal.aborted) {\n this.finish('client', null, 'aborted before it opened');\n throw new SessionOpenError(this._end!);\n }\n signal.addEventListener('abort', () => void this.close(), { once: true });\n }\n let token: string;\n try {\n const minted = await this.client.tokenProvider(this.slug);\n token = typeof minted === 'string' ? minted : minted.token;\n // A token opens one session and lives about two minutes. Refusing a stale\n // one here gives the caller a clear code instead of a socket refusal.\n const expiresAt = typeof minted === 'string' ? undefined : minted.expires_at;\n if (!token || (expiresAt !== undefined && expiresAt * 1000 <= Date.now())) {\n this.finish('refused', null, token ? 'the session token has expired' : 'the token provider returned no token', {\n code: token ? 'token_expired' : 'unauthorized',\n });\n throw new SessionOpenError(this._end!);\n }\n } catch (error) {\n if (error instanceof SessionOpenError) throw error;\n this.finish('refused', null, `token mint failed: ${String(error)}`);\n throw error;\n }\n if ((this._state as SessionState) === 'closed') {\n // close() was called while the token was being minted.\n throw new SessionOpenError(this._end ?? { reason: 'client', usage: null });\n }\n const url = sessionUrl(\n this.client.realtimeRoot ?? DEFAULT_REALTIME_URL,\n this.slug,\n token,\n this.options.params,\n this.options.path,\n );\n const socket = (this.client.webSocketFactory ?? defaultWebSocket)(url);\n socket.binaryType = 'arraybuffer';\n this.socket = socket;\n socket.onmessage = (ev) => this.handleMessage(ev.data);\n socket.onclose = (ev) => this.handleClose(ev.code, ev.reason);\n socket.onerror = () => {\n /* the close that follows carries the reason */\n };\n\n return new Promise<SessionCreatedEvent>((resolve, reject) => {\n const offEvent = this.onEvent((event) => {\n if (event.type === 'session.created') {\n offEvent();\n offState();\n resolve(event);\n }\n });\n const offState = this.onState((state, reason) => {\n if (state === 'closed') {\n offEvent();\n offState();\n reject(new SessionOpenError(this._end ?? { reason: reason ?? 'refused', usage: null }));\n }\n });\n });\n }\n\n /**\n * Resolves when the session has closed, whichever side ended it, with the\n * final usage. Unlike `close()` it asks for nothing: use it to await the\n * ending of a session something else will end.\n */\n whenEnded(): Promise<SessionEnd> {\n return this.ended;\n }\n\n /** Ask the server to end the session. Resolves with the final usage after settlement. */\n close(): Promise<SessionEnd> {\n if (this._state === 'closed') return this.ended;\n this.closeRequested = true;\n if (this._state === 'live' && this.socket && this.socket.readyState === WS_OPEN) {\n this.rawSend(encodeClientEvent({ type: 'close' }));\n } else if (this.socket) {\n this.socket.close(1000, 'client');\n } else {\n // Still minting the token: nothing was reserved, nothing to settle.\n this.finish('client', null);\n }\n return this.ended;\n }\n\n // --- sends ------------------------------------------------------------------\n\n /**\n * Raw s16le PCM at the session rate (`audio.rate`), sent as a binary frame\n * tagged with the audio stream's tag. Before live it is queued and tagged\n * once `session.created` names the stream. Returns false when the session\n * takes no audio input.\n */\n sendAudio(pcm: Int16Array | ArrayBuffer): boolean {\n if (this._state === 'closed') return false;\n if (this._state === 'opening') return this.enqueue({ pcm: pcmBytes(pcm) });\n const format = this.audio;\n if (!acceptsInput(format)) return false;\n return this.rawSend(mediaFrame(format!.tag, pcmBytes(pcm)));\n }\n\n commitAudio(): boolean {\n return this.send({ type: 'audio.commit' });\n }\n\n sendText(text: string): boolean {\n return this.send({ type: 'text', text });\n }\n\n interrupt(): boolean {\n return this.send({ type: 'interrupt' });\n }\n\n update(session: SessionUpdateParams): boolean {\n return this.send({ type: 'session.update', session });\n }\n\n send(event: ClientEvent): boolean {\n if (this._state === 'closed') return false;\n const frame = encodeClientEvent(event);\n if (this._state === 'opening') return this.enqueue({ text: frame });\n return this.rawSend(frame);\n }\n\n private enqueue(item: QueuedSend): boolean {\n const limit = this.options.maxQueuedSends ?? 64;\n if (this.queue.length >= limit) return false;\n this.queue.push(item);\n return true;\n }\n\n private flushQueue(): void {\n const format = this.audio;\n for (const item of this.queue.splice(0)) {\n if ('text' in item) this.rawSend(item.text);\n else if (acceptsInput(format)) this.rawSend(mediaFrame(format!.tag, item.pcm));\n }\n }\n\n private rawSend(frame: string | ArrayBuffer): boolean {\n const socket = this.socket;\n if (!socket || socket.readyState !== WS_OPEN || this._state === 'closed') return false;\n try {\n socket.send(frame);\n return true;\n } catch {\n return false;\n }\n }\n\n // --- socket handlers ----------------------------------------------------------\n\n private handleMessage(data: unknown): void {\n if (typeof data !== 'string') return; // the server never sends binary\n let event: ServerEvent;\n try {\n event = decodeServerEvent(data);\n } catch {\n return; // forward-compatible: an event we do not know is not fatal\n }\n if (event.type === 'session.created') {\n const unsupported = unsupportedSession(event);\n if (unsupported) {\n // Live on the server: ask it to settle, and never speak a protocol we do not know.\n this.rawSend(encodeClientEvent({ type: 'close' }));\n this.finish('refused', null, unsupported, { code: 'unsupported_protocol' });\n return;\n }\n this._created = event;\n this.setState('live');\n this.flushQueue();\n this.startHeartbeat();\n }\n this.emit(event);\n if (event.type === 'session.ended') {\n this.sawEndedFrame = true;\n this.finish(event.reason, event.usage ?? null, event.message);\n } else if (event.type === 'error' && this._state === 'opening') {\n // A refusal. The server follows it with a close whose code says which\n // kind (4001, 4002, 4029, 1013…); the ending waits for that close.\n this.refusal = { code: event.code, message: event.message };\n }\n }\n\n private handleClose(code: number, reason: string): void {\n if (this._state === 'closed') return;\n if (this.sawEndedFrame) return;\n if (this.refusal) {\n this.finish('refused', null, this.refusal.message, {\n code: this.refusal.code,\n closeCode: code,\n });\n return;\n }\n const inferred =\n this.closeRequested && code === 1000 ? 'client' : reasonFromCloseCode(code, reason);\n this.finish(inferred, null, reason || undefined, {\n // A refusal without its frame still names its code in the close reason.\n code: inferred === 'refused' && reason ? reason : undefined,\n closeCode: code,\n });\n }\n\n private finish(\n reason: EndReason,\n usage: Usage | null,\n message?: string,\n detail: { code?: string; closeCode?: number } = {},\n ): void {\n if (this._state === 'closed') return;\n this.stopHeartbeat();\n this._reason = reason;\n this._usage = usage;\n this.queue.length = 0;\n const socket = this.socket;\n this.socket = null;\n if (socket && socket.readyState === WS_OPEN) {\n try {\n socket.close(1000, 'client');\n } catch {\n /* already closing */\n }\n }\n const end: SessionEnd = { reason, usage, message };\n if (detail.code !== undefined) end.code = detail.code;\n if (detail.closeCode !== undefined) end.closeCode = detail.closeCode;\n this._end = end;\n this.setState('closed', reason);\n this.resolveEnded(end);\n }\n\n private startHeartbeat(): void {\n const ms = this.options.heartbeatMs ?? 15000;\n if (ms <= 0) return;\n const schedule = this.client.setInterval ?? setInterval;\n this.heartbeat = schedule(() => {\n this.rawSend(encodeClientEvent({ type: 'ping' }));\n }, ms);\n }\n\n private stopHeartbeat(): void {\n if (this.heartbeat !== null) {\n (this.client.clearInterval ?? clearInterval)(this.heartbeat);\n this.heartbeat = null;\n }\n }\n\n private setState(state: SessionState, reason?: EndReason): void {\n this._state = state;\n for (const listener of this.stateListeners) listener(state, reason);\n }\n\n private emit(event: ServerEvent): void {\n for (const listener of this.eventListeners) listener(event);\n }\n}\n\n/**\n * Holds the service root and the token provider, and hands out sessions.\n * `connect()` is the shorthand for one session.\n */\nexport class RealtimeClient {\n constructor(private readonly options: ClientOptions) {\n if (typeof options?.tokenProvider !== 'function') throw new SegmindError('realtime: tokenProvider is required');\n }\n\n /** A session handle in `opening`; call `open()` to connect. */\n session(slug: string, options?: SessionOptions): RealtimeSession {\n return new RealtimeSession(slug, this.options, options);\n }\n\n /** Mint, connect and resolve once live. */\n async connect(slug: string, options?: SessionOptions): Promise<RealtimeSession> {\n const session = this.session(slug, options);\n await session.open();\n return session;\n }\n}\n\n/**\n * Opens one session and resolves once it is live.\n *\n * ```ts\n * import { connect } from 'segmind/realtime';\n *\n * const session = await connect('your-session-model', {\n * tokenProvider: () => fetch('/api/realtime-token', { method: 'POST' }).then((r) => r.json()),\n * });\n * session.on('transcript.delta', (e) => console.log(e.role, e.text));\n * session.sendText('Hello');\n * const { usage } = await session.close();\n * ```\n */\nexport function connect(slug: string, options: ClientOptions & SessionOptions): Promise<RealtimeSession> {\n const { params, path, heartbeatMs, maxQueuedSends, signal, ...client } = options;\n return new RealtimeClient(client).connect(slug, { params, path, heartbeatMs, maxQueuedSends, signal });\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/segmind-js/segmind-js/packages/segmind/dist/realtime/index.cjs","../../src/realtime/session.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACF,yDAA8B;AAC9B;AACA;ACiBO,IAAM,qBAAA,EAAuB,sBAAA;AA4CpC,IAAM,QAAA,EAAU,CAAA;AA4BT,IAAM,iBAAA,EAAN,MAAA,QAA+B,+BAAa;AAAA,EACjD,WAAA,CAA4B,GAAA,EAAiB;AAC3C,IAAA,KAAA;AAAA,MACE,CAAA,QAAA,EA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,EAAA;AACwB,IAAA;AACX,IAAA;AACJ,IAAA;AACD,IAAA;AACM,IAAA;AACA,IAAA;AACN,IAAA;AAC+B,IAAA;AACvC,MAAA;AACyB,QAAA;AACrB,MAAA;AAER,MAAA;AACF,IAAA;AACiD,IAAA;AACA,IAAA;AACU,IAAA;AAC/C,IAAA;AACkB,IAAA;AACT,IAAA;AACvB,EAAA;AAE+B,EAAA;AACU,IAAA;AAC1B,IAAA;AAC+B,IAAA;AACZ,IAAA;AACkB,MAAA;AAC7C,IAAA;AACP,EAAA;AAE8B,EAAA;AACC,IAAA;AACgC,MAAA;AAC1C,MAAA;AACnB,IAAA;AACF,EAAA;AAEgE,EAAA;AAChD,IAAA;AACoD,IAAA;AACpE,EAAA;AAEuC,EAAA;AACqB,IAAA;AAC5D,EAAA;AACF;AAM4B;AAC2B,EAAA;AAAxB,IAAA;AACiC,IAAA;AAC9D,EAAA;AAF6B,EAAA;AAAA;AAKoC,EAAA;AACT,IAAA;AACxD,EAAA;AAAA;AAGgF,EAAA;AACpC,IAAA;AACvB,IAAA;AACZ,IAAA;AACT,EAAA;AACF;AAgByG;AAC9B,EAAA;AACT,EAAA;AAClE;AD/J2E;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;AACA;AACA;AACA;AACA","file":"/home/runner/work/segmind-js/segmind-js/packages/segmind/dist/realtime/index.cjs","sourcesContent":[null,"/**\n * A managed realtime session: one primitive, explicit states, typed events,\n * and a `close()` that resolves with what the session cost.\n *\n * `opening` the token is being minted and the socket is connecting; sends\n * are queued (bounded) and flushed once the server says\n * `session.created`.\n * `live` sends go straight to the socket; a `ping` keeps the connection\n * warm.\n * `closed` terminal. Every ending reaches it exactly once: the server's\n * `session.ended`, a refusal before the session opened, or a\n * socket close with no frame (reason from the close code).\n *\n * A handle that has closed can never write again: `send*` after `closed`\n * returns false and does nothing.\n *\n * Nothing here touches the DOM or a browser global: the socket comes from\n * `webSocketFactory` (the runtime's `WebSocket` when none is given), so the\n * same core runs in a browser, React Native or Node.\n */\n\nimport { SegmindError } from '../core/errors';\nimport {\n acceptsInput,\n audioFormat,\n decodeServerEvent,\n encodeClientEvent,\n mediaFrame,\n reasonFromCloseCode,\n sessionUrl,\n unsupportedSession,\n} from './protocol';\nimport type {\n AudioFormat,\n ClientEvent,\n EndReason,\n ServerEvent,\n SessionCreatedEvent,\n SessionState,\n ServerEventType,\n SessionTokenProvider,\n SessionUpdateParams,\n Usage,\n} from './types';\n\n/** The production session service. */\nexport const DEFAULT_REALTIME_URL = 'wss://rt.segmind.com';\n\nexport interface SessionOptions {\n /** Session parameters sent on the query string (voice, instructions, vad…). */\n params?: Record<string, string>;\n /** The session's path on the service, from the model record's\n * `endpoints.session`. Default `/<slug>`. */\n path?: string;\n /** Milliseconds between `ping` frames while live. 0 disables. Default 15000. */\n heartbeatMs?: number;\n /** Sends queued while opening, beyond which `send*` returns false. Default 64. */\n maxQueuedSends?: number;\n /** Aborting closes the session, or cancels the open while it is still opening. */\n signal?: AbortSignal;\n}\n\nexport interface ClientOptions {\n /** Where the session service lives. Default `wss://rt.segmind.com`. */\n realtimeRoot?: string;\n /**\n * Trades the app's credentials for a short-lived session token. In a browser\n * or a phone app it calls the app's own backend, which calls\n * `segmind.realtime.createToken()`; the API key never leaves the server.\n */\n tokenProvider: SessionTokenProvider;\n /** How to open the socket. Default: the runtime's global `WebSocket`. */\n webSocketFactory?: (url: string) => WebSocketLike;\n /** Injectable clock for tests. */\n setInterval?: typeof setInterval;\n clearInterval?: typeof clearInterval;\n}\n\n/** The subset of WebSocket the session needs, so tests can fake it. */\nexport interface WebSocketLike {\n readonly readyState: number;\n binaryType?: string;\n send(data: string | ArrayBuffer): void;\n close(code?: number, reason?: string): void;\n onopen: ((ev: unknown) => void) | null;\n onmessage: ((ev: { data: unknown }) => void) | null;\n onclose: ((ev: { code: number; reason: string }) => void) | null;\n onerror: ((ev: unknown) => void) | null;\n}\n\nconst WS_OPEN = 1;\n\nexport type EventListener = (event: ServerEvent) => void;\n/** A listener for one event type, typed by it. */\nexport type TypedEventListener<T extends ServerEventType> = (event: Extract<ServerEvent, { type: T }>) => void;\nexport type StateListener = (state: SessionState, reason?: EndReason) => void;\n\nexport interface SessionEnd {\n reason: EndReason;\n usage: Usage | null;\n message?: string;\n /**\n * For a refusal, the server's error code (`insufficient_credits`,\n * `capacity`, `service_unavailable`…), or `unsupported_protocol`.\n */\n code?: string;\n /** The socket close code, when the ending came from a close rather than `session.ended`. */\n closeCode?: number;\n}\n\n/** A send made while opening: a JSON frame, or microphone PCM tagged once the stream is known. */\ntype QueuedSend = { text: string } | { pcm: ArrayBuffer };\n\n/**\n * `open()` rejects with this when the session ends before it is live. `end`\n * keeps the refusal's code and close code: branch on `end.code`\n * (`insufficient_credits`, `capacity`…) rather than parsing the message.\n */\nexport class SessionOpenError extends SegmindError {\n constructor(public readonly end: SessionEnd) {\n super(\n `session ${end.reason} before it opened` +\n (end.code ? ` (${end.code}${end.message ? `: ${end.message}` : ''})` : ''),\n { status: end.closeCode, detail: end.message },\n );\n }\n\n /** The server's refusal code (`insufficient_credits`, `capacity`, `token_expired`…), when there is one. */\n get code(): string | undefined {\n return this.end.code;\n }\n}\n\nfunction defaultWebSocket(url: string): WebSocketLike {\n const Ctor = (globalThis as { WebSocket?: new (url: string) => unknown }).WebSocket;\n if (!Ctor) throw new SegmindError('no global WebSocket in this runtime: pass webSocketFactory');\n return new Ctor(url) as WebSocketLike;\n}\n\nfunction pcmBytes(pcm: Int16Array | ArrayBuffer): ArrayBuffer {\n return pcm instanceof Int16Array\n ? (pcm.buffer.slice(pcm.byteOffset, pcm.byteOffset + pcm.byteLength) as ArrayBuffer)\n : pcm;\n}\n\nexport class RealtimeSession {\n private _state: SessionState = 'opening';\n private _reason: EndReason | null = null;\n private _usage: Usage | null = null;\n private _end: SessionEnd | null = null;\n private _created: SessionCreatedEvent | null = null;\n private socket: WebSocketLike | null = null;\n private readonly queue: QueuedSend[] = [];\n private readonly eventListeners = new Set<EventListener>();\n private readonly stateListeners = new Set<StateListener>();\n private readonly ended: Promise<SessionEnd>;\n private resolveEnded!: (end: SessionEnd) => void;\n private heartbeat: ReturnType<typeof setInterval> | null = null;\n private sawEndedFrame = false;\n private opening = false;\n private closeRequested = false;\n /** The `error` frame of a refusal, held until the close that follows carries its code. */\n private refusal: { code: string; message: string } | null = null;\n\n constructor(\n public readonly slug: string,\n private readonly client: ClientOptions,\n private readonly options: SessionOptions = {},\n ) {\n this.ended = new Promise<SessionEnd>((resolve) => {\n this.resolveEnded = resolve;\n });\n }\n\n // --- observable state -------------------------------------------------------\n\n get state(): SessionState {\n return this._state;\n }\n\n get reason(): EndReason | null {\n return this._reason;\n }\n\n /** The final usage, once the session has closed. */\n get usage(): Usage | null {\n return this._usage;\n }\n\n /** How the session ended (reason, usage, refusal code, close code), once closed. */\n get end(): SessionEnd | null {\n return this._end;\n }\n\n /** The session options sent on the URL at open (`SessionOptions.params`). */\n get params(): Readonly<Record<string, string>> {\n return this.options.params ?? {};\n }\n\n /** The `session.created` frame, once live. */\n get created(): SessionCreatedEvent | null {\n return this._created;\n }\n\n /**\n * The session's audio stream (`session.created.media.audio`): its rate,\n * channels and binary tag. Null before live, or for a session without\n * 16-bit PCM audio. Size capture and playback from it.\n */\n get audio(): AudioFormat | null {\n return audioFormat(this._created);\n }\n\n /** Every server event. Returns a function that removes the listener. */\n onEvent(listener: EventListener): () => void {\n this.eventListeners.add(listener);\n return () => this.eventListeners.delete(listener);\n }\n\n /** One event type, typed by it: `session.on('transcript.delta', (e) => e.text)`. */\n on<T extends ServerEventType>(type: T, listener: TypedEventListener<T>): () => void {\n return this.onEvent((event) => {\n if (event.type === type) listener(event as Extract<ServerEvent, { type: T }>);\n });\n }\n\n onState(listener: StateListener): () => void {\n this.stateListeners.add(listener);\n return () => this.stateListeners.delete(listener);\n }\n\n /** Every server event as an async iterable; ends when the session closes. */\n events(): AsyncIterable<ServerEvent> {\n const buffer: ServerEvent[] = [];\n let wake: (() => void) | null = null;\n let done = this._state === 'closed';\n const unsubscribe = this.onEvent((event) => {\n buffer.push(event);\n wake?.();\n });\n const unsubscribeState = this.onState((state) => {\n if (state === 'closed') {\n done = true;\n wake?.();\n }\n });\n return {\n [Symbol.asyncIterator]: () => ({\n next: async (): Promise<IteratorResult<ServerEvent>> => {\n while (buffer.length === 0 && !done) {\n await new Promise<void>((resolve) => {\n wake = resolve;\n });\n wake = null;\n }\n const event = buffer.shift();\n if (event) return { value: event, done: false };\n unsubscribe();\n unsubscribeState();\n return { value: undefined, done: true };\n },\n return: async (): Promise<IteratorResult<ServerEvent>> => {\n unsubscribe();\n unsubscribeState();\n return { value: undefined, done: true };\n },\n }),\n };\n }\n\n // --- lifecycle --------------------------------------------------------------\n\n /** Mint a token and connect. Resolves when the session is live, rejects when refused. */\n async open(): Promise<SessionCreatedEvent> {\n if (this._state !== 'opening' || this.socket || this.opening) {\n throw new SegmindError('session can only be opened once');\n }\n this.opening = true;\n const { signal } = this.options;\n if (signal) {\n if (signal.aborted) {\n this.finish('client', null, 'aborted before it opened');\n throw new SessionOpenError(this._end!);\n }\n signal.addEventListener('abort', () => void this.close(), { once: true });\n }\n let token: string;\n try {\n const minted = await this.client.tokenProvider(this.slug);\n token = typeof minted === 'string' ? minted : minted.token;\n // A token opens one session and lives about two minutes. Refusing a stale\n // one here gives the caller a clear code instead of a socket refusal.\n const expiresAt = typeof minted === 'string' ? undefined : minted.expires_at;\n if (!token || (expiresAt !== undefined && expiresAt * 1000 <= Date.now())) {\n this.finish('refused', null, token ? 'the session token has expired' : 'the token provider returned no token', {\n code: token ? 'token_expired' : 'unauthorized',\n });\n throw new SessionOpenError(this._end!);\n }\n } catch (error) {\n if (error instanceof SessionOpenError) throw error;\n this.finish('refused', null, `token mint failed: ${String(error)}`);\n throw error;\n }\n if ((this._state as SessionState) === 'closed') {\n // close() was called while the token was being minted.\n throw new SessionOpenError(this._end ?? { reason: 'client', usage: null });\n }\n const url = sessionUrl(\n this.client.realtimeRoot ?? DEFAULT_REALTIME_URL,\n this.slug,\n token,\n this.options.params,\n this.options.path,\n );\n const socket = (this.client.webSocketFactory ?? defaultWebSocket)(url);\n socket.binaryType = 'arraybuffer';\n this.socket = socket;\n socket.onmessage = (ev) => this.handleMessage(ev.data);\n socket.onclose = (ev) => this.handleClose(ev.code, ev.reason);\n socket.onerror = () => {\n /* the close that follows carries the reason */\n };\n\n return new Promise<SessionCreatedEvent>((resolve, reject) => {\n const offEvent = this.onEvent((event) => {\n if (event.type === 'session.created') {\n offEvent();\n offState();\n resolve(event);\n }\n });\n const offState = this.onState((state, reason) => {\n if (state === 'closed') {\n offEvent();\n offState();\n reject(new SessionOpenError(this._end ?? { reason: reason ?? 'refused', usage: null }));\n }\n });\n });\n }\n\n /**\n * Resolves when the session has closed, whichever side ended it, with the\n * final usage. Unlike `close()` it asks for nothing: use it to await the\n * ending of a session something else will end.\n */\n whenEnded(): Promise<SessionEnd> {\n return this.ended;\n }\n\n /** Ask the server to end the session. Resolves with the final usage after settlement. */\n close(): Promise<SessionEnd> {\n if (this._state === 'closed') return this.ended;\n this.closeRequested = true;\n if (this._state === 'live' && this.socket && this.socket.readyState === WS_OPEN) {\n this.rawSend(encodeClientEvent({ type: 'close' }));\n } else if (this.socket) {\n this.socket.close(1000, 'client');\n } else {\n // Still minting the token: nothing was reserved, nothing to settle.\n this.finish('client', null);\n }\n return this.ended;\n }\n\n // --- sends ------------------------------------------------------------------\n\n /**\n * Raw s16le PCM at the session rate (`audio.rate`), sent as a binary frame\n * tagged with the audio stream's tag. Before live it is queued and tagged\n * once `session.created` names the stream. Returns false when the session\n * takes no audio input.\n */\n sendAudio(pcm: Int16Array | ArrayBuffer): boolean {\n if (this._state === 'closed') return false;\n if (this._state === 'opening') return this.enqueue({ pcm: pcmBytes(pcm) });\n const format = this.audio;\n if (!acceptsInput(format)) return false;\n return this.rawSend(mediaFrame(format!.tag, pcmBytes(pcm)));\n }\n\n commitAudio(): boolean {\n return this.send({ type: 'audio.commit' });\n }\n\n sendText(text: string): boolean {\n return this.send({ type: 'text', text });\n }\n\n interrupt(): boolean {\n return this.send({ type: 'interrupt' });\n }\n\n update(session: SessionUpdateParams): boolean {\n return this.send({ type: 'session.update', session });\n }\n\n send(event: ClientEvent): boolean {\n if (this._state === 'closed') return false;\n const frame = encodeClientEvent(event);\n if (this._state === 'opening') return this.enqueue({ text: frame });\n return this.rawSend(frame);\n }\n\n private enqueue(item: QueuedSend): boolean {\n const limit = this.options.maxQueuedSends ?? 64;\n if (this.queue.length >= limit) return false;\n this.queue.push(item);\n return true;\n }\n\n private flushQueue(): void {\n const format = this.audio;\n for (const item of this.queue.splice(0)) {\n if ('text' in item) this.rawSend(item.text);\n else if (acceptsInput(format)) this.rawSend(mediaFrame(format!.tag, item.pcm));\n }\n }\n\n private rawSend(frame: string | ArrayBuffer): boolean {\n const socket = this.socket;\n if (!socket || socket.readyState !== WS_OPEN || this._state === 'closed') return false;\n try {\n socket.send(frame);\n return true;\n } catch {\n return false;\n }\n }\n\n // --- socket handlers ----------------------------------------------------------\n\n private handleMessage(data: unknown): void {\n if (typeof data !== 'string') return; // the server never sends binary\n let event: ServerEvent;\n try {\n event = decodeServerEvent(data);\n } catch {\n return; // forward-compatible: an event we do not know is not fatal\n }\n if (event.type === 'session.created') {\n const unsupported = unsupportedSession(event);\n if (unsupported) {\n // Live on the server: ask it to settle, and never speak a protocol we do not know.\n this.rawSend(encodeClientEvent({ type: 'close' }));\n this.finish('refused', null, unsupported, { code: 'unsupported_protocol' });\n return;\n }\n this._created = event;\n this.setState('live');\n this.flushQueue();\n this.startHeartbeat();\n }\n this.emit(event);\n if (event.type === 'session.ended') {\n this.sawEndedFrame = true;\n this.finish(event.reason, event.usage ?? null, event.message);\n } else if (event.type === 'error' && this._state === 'opening') {\n // A refusal. The server follows it with a close whose code says which\n // kind (4001, 4002, 4029, 1013…); the ending waits for that close.\n this.refusal = { code: event.code, message: event.message };\n }\n }\n\n private handleClose(code: number, reason: string): void {\n if (this._state === 'closed') return;\n if (this.sawEndedFrame) return;\n if (this.refusal) {\n this.finish('refused', null, this.refusal.message, {\n code: this.refusal.code,\n closeCode: code,\n });\n return;\n }\n const inferred =\n this.closeRequested && code === 1000 ? 'client' : reasonFromCloseCode(code, reason);\n this.finish(inferred, null, reason || undefined, {\n // A refusal without its frame still names its code in the close reason.\n code: inferred === 'refused' && reason ? reason : undefined,\n closeCode: code,\n });\n }\n\n private finish(\n reason: EndReason,\n usage: Usage | null,\n message?: string,\n detail: { code?: string; closeCode?: number } = {},\n ): void {\n if (this._state === 'closed') return;\n this.stopHeartbeat();\n this._reason = reason;\n this._usage = usage;\n this.queue.length = 0;\n const socket = this.socket;\n this.socket = null;\n if (socket && socket.readyState === WS_OPEN) {\n try {\n socket.close(1000, 'client');\n } catch {\n /* already closing */\n }\n }\n const end: SessionEnd = { reason, usage, message };\n if (detail.code !== undefined) end.code = detail.code;\n if (detail.closeCode !== undefined) end.closeCode = detail.closeCode;\n this._end = end;\n this.setState('closed', reason);\n this.resolveEnded(end);\n }\n\n private startHeartbeat(): void {\n const ms = this.options.heartbeatMs ?? 15000;\n if (ms <= 0) return;\n const schedule = this.client.setInterval ?? setInterval;\n this.heartbeat = schedule(() => {\n this.rawSend(encodeClientEvent({ type: 'ping' }));\n }, ms);\n }\n\n private stopHeartbeat(): void {\n if (this.heartbeat !== null) {\n (this.client.clearInterval ?? clearInterval)(this.heartbeat);\n this.heartbeat = null;\n }\n }\n\n private setState(state: SessionState, reason?: EndReason): void {\n this._state = state;\n for (const listener of this.stateListeners) listener(state, reason);\n }\n\n private emit(event: ServerEvent): void {\n for (const listener of this.eventListeners) listener(event);\n }\n}\n\n/**\n * Holds the service root and the token provider, and hands out sessions.\n * `connect()` is the shorthand for one session.\n */\nexport class RealtimeClient {\n constructor(private readonly options: ClientOptions) {\n if (typeof options?.tokenProvider !== 'function') throw new SegmindError('realtime: tokenProvider is required');\n }\n\n /** A session handle in `opening`; call `open()` to connect. */\n session(slug: string, options?: SessionOptions): RealtimeSession {\n return new RealtimeSession(slug, this.options, options);\n }\n\n /** Mint, connect and resolve once live. */\n async connect(slug: string, options?: SessionOptions): Promise<RealtimeSession> {\n const session = this.session(slug, options);\n await session.open();\n return session;\n }\n}\n\n/**\n * Opens one session and resolves once it is live.\n *\n * ```ts\n * import { connect } from 'segmind/realtime';\n *\n * const session = await connect('your-session-model', {\n * tokenProvider: () => fetch('/api/realtime-token', { method: 'POST' }).then((r) => r.json()),\n * });\n * session.on('transcript.delta', (e) => console.log(e.role, e.text));\n * session.sendText('Hello');\n * const { usage } = await session.close();\n * ```\n */\nexport function connect(slug: string, options: ClientOptions & SessionOptions): Promise<RealtimeSession> {\n const { params, path, heartbeatMs, maxQueuedSends, signal, ...client } = options;\n return new RealtimeClient(client).connect(slug, { params, path, heartbeatMs, maxQueuedSends, signal });\n}\n"]}
@@ -1,8 +1,8 @@
1
- import { R as RealtimeSession, V as VadOptions } from '../vad-B-BeifvT.cjs';
2
- export { C as ClientOptions, D as DEFAULT_REALTIME_URL, E as EnergyVad, a as EventListener, b as RealtimeClient, S as SessionEnd, c as SessionOpenError, d as SessionOptions, e as StateListener, T as TypedEventListener, f as VadDecision, W as WebSocketLike, g as connect } from '../vad-B-BeifvT.cjs';
3
- import { e as SessionCreatedEvent, f as AudioFormat, g as ServerEvent, C as ClientEvent, E as EndReason } from '../errors-CcHEuSmR.cjs';
1
+ import { R as RealtimeSession, V as VadOptions } from '../vad-xeCHdSHo.cjs';
2
+ export { C as ClientOptions, D as DEFAULT_REALTIME_URL, E as EnergyVad, a as EventListener, b as RealtimeClient, S as SessionEnd, c as SessionOpenError, d as SessionOptions, e as StateListener, T as TypedEventListener, f as VadDecision, W as WebSocketLike, g as connect } from '../vad-xeCHdSHo.cjs';
3
+ import { g as SessionCreatedEvent, h as AudioFormat, i as ServerEvent, C as ClientEvent, E as EndReason, V as VideoControl, M as MediaStreamSpec } from '../errors-DsVQfts3.cjs';
4
4
  import { SegmindError } from '../index.cjs';
5
- export { h as AudioDeltaEvent, i as ErrorEvent, j as InputSpeechStartedEvent, k as InputSpeechStoppedEvent, M as MediaStreamSpec, P as PROTOCOL_VERSION, l as PongEvent, m as RefusalCode, n as STREAM_TAGS, o as ServerEventType, p as SessionEndedEvent, q as SessionLimits, r as SessionState, S as SessionToken, a as SessionTokenProvider, s as SessionUpdateParams, t as SessionUpdatedEvent, T as TranscriptDeltaEvent, u as TurnEndReason, v as TurnEndedEvent, w as TurnStartedEvent, U as UpstreamEvent, x as Usage, y as UsageEvent, z as UsageFacts } from '../errors-CcHEuSmR.cjs';
5
+ export { j as AudioDeltaEvent, k as ErrorEvent, e as IceCandidateJson, f as IceServer, l as InputSpeechStartedEvent, m as InputSpeechStoppedEvent, P as PROTOCOL_VERSION, n as PongEvent, o as RefusalCode, p as STREAM_TAGS, q as ServerEventType, r as SessionEndedEvent, s as SessionLimits, t as SessionState, S as SessionToken, a as SessionTokenProvider, u as SessionUpdateParams, v as SessionUpdatedEvent, T as TranscriptDeltaEvent, w as TurnEndReason, x as TurnEndedEvent, y as TurnStartedEvent, U as UpstreamEvent, z as Usage, B as UsageEvent, D as UsageFacts, F as VideoProgressEvent, G as VideoPromptAckEvent, H as VideoStartedEvent, W as WebrtcAnswerEvent, J as WebrtcCandidateEvent, K as WebrtcConfigEvent, L as WebrtcRestartEvent } from '../errors-DsVQfts3.cjs';
6
6
 
7
7
  /** A server frame this client cannot read. The session ignores it; `decodeServerEvent` throws it. */
8
8
  declare class ProtocolError extends SegmindError {
@@ -39,6 +39,13 @@ declare function unsupportedSession(created: SessionCreatedEvent): string | null
39
39
  * session carries no audio this client can handle (only 16-bit PCM).
40
40
  */
41
41
  declare function audioFormat(created: SessionCreatedEvent | null): AudioFormat | null;
42
+ /** The session's video stream when it travels over WebRTC, or null. */
43
+ declare function webrtcVideo(created: SessionCreatedEvent | null): MediaStreamSpec | null;
44
+ /**
45
+ * Where a video session is steered, or null for a session without a WebRTC
46
+ * video stream. A WebRTC session that names no `control` is steered on the socket.
47
+ */
48
+ declare function videoControl(created: SessionCreatedEvent | null): VideoControl | null;
42
49
  /** True when the client may send on this stream. */
43
50
  declare function acceptsInput(format: {
44
51
  direction: string;
@@ -110,5 +117,5 @@ declare function floatToInt16(samples: Float32Array): Int16Array;
110
117
  /** Root mean square of a PCM frame, on the Int16 scale (0–32767). */
111
118
  declare function rms(pcm: Int16Array): number;
112
119
 
113
- export { AudioFormat, ClientEvent, EndReason, ProtocolError, REFUSAL_CLOSE_CODES, RealtimeSession, SESSION_SAMPLE_RATE, ServerEvent, SessionCreatedEvent, VadOptions, acceptsInput, attachBargeIn, audioFormat, decodePcm, decodeServerEvent, encodeClientEvent, encodePcm, floatToInt16, isRetryableRefusal, mediaFrame, pcmSeconds, reasonFromCloseCode, rms, sessionUrl, unsupportedSession };
120
+ export { AudioFormat, ClientEvent, EndReason, MediaStreamSpec, ProtocolError, REFUSAL_CLOSE_CODES, RealtimeSession, SESSION_SAMPLE_RATE, ServerEvent, SessionCreatedEvent, VadOptions, VideoControl, acceptsInput, attachBargeIn, audioFormat, decodePcm, decodeServerEvent, encodeClientEvent, encodePcm, floatToInt16, isRetryableRefusal, mediaFrame, pcmSeconds, reasonFromCloseCode, rms, sessionUrl, unsupportedSession, videoControl, webrtcVideo };
114
121
  export type { AudioSink, AudioSource, BargeIn, BargeInOptions };
@@ -1,8 +1,8 @@
1
- import { R as RealtimeSession, V as VadOptions } from '../vad-BcBkqh2p.js';
2
- export { C as ClientOptions, D as DEFAULT_REALTIME_URL, E as EnergyVad, a as EventListener, b as RealtimeClient, S as SessionEnd, c as SessionOpenError, d as SessionOptions, e as StateListener, T as TypedEventListener, f as VadDecision, W as WebSocketLike, g as connect } from '../vad-BcBkqh2p.js';
3
- import { e as SessionCreatedEvent, f as AudioFormat, g as ServerEvent, C as ClientEvent, E as EndReason } from '../errors-CcHEuSmR.js';
1
+ import { R as RealtimeSession, V as VadOptions } from '../vad-dy0g4f3R.js';
2
+ export { C as ClientOptions, D as DEFAULT_REALTIME_URL, E as EnergyVad, a as EventListener, b as RealtimeClient, S as SessionEnd, c as SessionOpenError, d as SessionOptions, e as StateListener, T as TypedEventListener, f as VadDecision, W as WebSocketLike, g as connect } from '../vad-dy0g4f3R.js';
3
+ import { g as SessionCreatedEvent, h as AudioFormat, i as ServerEvent, C as ClientEvent, E as EndReason, V as VideoControl, M as MediaStreamSpec } from '../errors-DsVQfts3.js';
4
4
  import { SegmindError } from '../index.js';
5
- export { h as AudioDeltaEvent, i as ErrorEvent, j as InputSpeechStartedEvent, k as InputSpeechStoppedEvent, M as MediaStreamSpec, P as PROTOCOL_VERSION, l as PongEvent, m as RefusalCode, n as STREAM_TAGS, o as ServerEventType, p as SessionEndedEvent, q as SessionLimits, r as SessionState, S as SessionToken, a as SessionTokenProvider, s as SessionUpdateParams, t as SessionUpdatedEvent, T as TranscriptDeltaEvent, u as TurnEndReason, v as TurnEndedEvent, w as TurnStartedEvent, U as UpstreamEvent, x as Usage, y as UsageEvent, z as UsageFacts } from '../errors-CcHEuSmR.js';
5
+ export { j as AudioDeltaEvent, k as ErrorEvent, e as IceCandidateJson, f as IceServer, l as InputSpeechStartedEvent, m as InputSpeechStoppedEvent, P as PROTOCOL_VERSION, n as PongEvent, o as RefusalCode, p as STREAM_TAGS, q as ServerEventType, r as SessionEndedEvent, s as SessionLimits, t as SessionState, S as SessionToken, a as SessionTokenProvider, u as SessionUpdateParams, v as SessionUpdatedEvent, T as TranscriptDeltaEvent, w as TurnEndReason, x as TurnEndedEvent, y as TurnStartedEvent, U as UpstreamEvent, z as Usage, B as UsageEvent, D as UsageFacts, F as VideoProgressEvent, G as VideoPromptAckEvent, H as VideoStartedEvent, W as WebrtcAnswerEvent, J as WebrtcCandidateEvent, K as WebrtcConfigEvent, L as WebrtcRestartEvent } from '../errors-DsVQfts3.js';
6
6
 
7
7
  /** A server frame this client cannot read. The session ignores it; `decodeServerEvent` throws it. */
8
8
  declare class ProtocolError extends SegmindError {
@@ -39,6 +39,13 @@ declare function unsupportedSession(created: SessionCreatedEvent): string | null
39
39
  * session carries no audio this client can handle (only 16-bit PCM).
40
40
  */
41
41
  declare function audioFormat(created: SessionCreatedEvent | null): AudioFormat | null;
42
+ /** The session's video stream when it travels over WebRTC, or null. */
43
+ declare function webrtcVideo(created: SessionCreatedEvent | null): MediaStreamSpec | null;
44
+ /**
45
+ * Where a video session is steered, or null for a session without a WebRTC
46
+ * video stream. A WebRTC session that names no `control` is steered on the socket.
47
+ */
48
+ declare function videoControl(created: SessionCreatedEvent | null): VideoControl | null;
42
49
  /** True when the client may send on this stream. */
43
50
  declare function acceptsInput(format: {
44
51
  direction: string;
@@ -110,5 +117,5 @@ declare function floatToInt16(samples: Float32Array): Int16Array;
110
117
  /** Root mean square of a PCM frame, on the Int16 scale (0–32767). */
111
118
  declare function rms(pcm: Int16Array): number;
112
119
 
113
- export { AudioFormat, ClientEvent, EndReason, ProtocolError, REFUSAL_CLOSE_CODES, RealtimeSession, SESSION_SAMPLE_RATE, ServerEvent, SessionCreatedEvent, VadOptions, acceptsInput, attachBargeIn, audioFormat, decodePcm, decodeServerEvent, encodeClientEvent, encodePcm, floatToInt16, isRetryableRefusal, mediaFrame, pcmSeconds, reasonFromCloseCode, rms, sessionUrl, unsupportedSession };
120
+ export { AudioFormat, ClientEvent, EndReason, MediaStreamSpec, ProtocolError, REFUSAL_CLOSE_CODES, RealtimeSession, SESSION_SAMPLE_RATE, ServerEvent, SessionCreatedEvent, VadOptions, VideoControl, acceptsInput, attachBargeIn, audioFormat, decodePcm, decodeServerEvent, encodeClientEvent, encodePcm, floatToInt16, isRetryableRefusal, mediaFrame, pcmSeconds, reasonFromCloseCode, rms, sessionUrl, unsupportedSession, videoControl, webrtcVideo };
114
121
  export type { AudioSink, AudioSource, BargeIn, BargeInOptions };
@@ -1,138 +1,32 @@
1
1
  import {
2
2
  EnergyVad,
3
+ PROTOCOL_VERSION,
4
+ ProtocolError,
5
+ REFUSAL_CLOSE_CODES,
3
6
  SESSION_SAMPLE_RATE,
7
+ STREAM_TAGS,
8
+ acceptsInput,
4
9
  attachBargeIn,
10
+ audioFormat,
5
11
  decodePcm,
12
+ decodeServerEvent,
13
+ encodeClientEvent,
6
14
  encodePcm,
7
15
  floatToInt16,
16
+ isRetryableRefusal,
17
+ mediaFrame,
8
18
  pcmSeconds,
9
- rms
10
- } from "../chunk-USGY6G4C.js";
19
+ reasonFromCloseCode,
20
+ rms,
21
+ sessionUrl,
22
+ unsupportedSession,
23
+ videoControl,
24
+ webrtcVideo
25
+ } from "../chunk-YSAOJ3YL.js";
11
26
  import {
12
27
  SegmindError
13
28
  } from "../chunk-PS5KUT7P.js";
14
29
 
15
- // src/realtime/types.ts
16
- var PROTOCOL_VERSION = 1;
17
- var STREAM_TAGS = { audio: 1, video: 2 };
18
-
19
- // src/realtime/protocol.ts
20
- var SERVER_EVENT_TYPES = /* @__PURE__ */ new Set([
21
- "session.created",
22
- "session.updated",
23
- "session.ended",
24
- "input.speech_started",
25
- "input.speech_stopped",
26
- "turn.started",
27
- "turn.ended",
28
- "audio.delta",
29
- "transcript.delta",
30
- "segmind.usage",
31
- "error",
32
- "upstream.event",
33
- "pong"
34
- ]);
35
- var ProtocolError = class extends SegmindError {
36
- constructor(message, raw) {
37
- super(message, { body: raw });
38
- this.raw = raw;
39
- }
40
- raw;
41
- };
42
- function decodeServerEvent(text) {
43
- let parsed;
44
- try {
45
- parsed = JSON.parse(text);
46
- } catch {
47
- throw new ProtocolError("server frame is not JSON", text);
48
- }
49
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
50
- throw new ProtocolError("server frame is not an object", parsed);
51
- }
52
- const type = parsed.type;
53
- if (typeof type !== "string" || !SERVER_EVENT_TYPES.has(type)) {
54
- throw new ProtocolError(`unknown server event type: ${String(type)}`, parsed);
55
- }
56
- return parsed;
57
- }
58
- function encodeClientEvent(event) {
59
- return JSON.stringify(event);
60
- }
61
- var SERVER_ENDINGS = /* @__PURE__ */ new Set([
62
- "client",
63
- "ceiling",
64
- "idle",
65
- "max_length",
66
- "balance_exhausted",
67
- "upstream_error",
68
- "server_shutdown",
69
- "internal_error",
70
- "metering_failed"
71
- ]);
72
- var REFUSAL_CLOSE_CODES = {
73
- bad_request: 4e3,
74
- unauthorized: 4001,
75
- insufficient_credits: 4002,
76
- unknown_model: 4004,
77
- capacity: 4029,
78
- /** A dependency (Redis, Spot) is unreachable, or the server is draining; retry shortly. */
79
- try_again: 1013
80
- };
81
- var REFUSAL_CODES = new Set(Object.values(REFUSAL_CLOSE_CODES));
82
- function reasonFromCloseCode(code, closeReason) {
83
- if (REFUSAL_CODES.has(code)) return "refused";
84
- if (closeReason && SERVER_ENDINGS.has(closeReason)) return closeReason;
85
- switch (code) {
86
- case 1e3:
87
- return "client";
88
- case 4008:
89
- return "limit";
90
- case 1012:
91
- return "server_shutdown";
92
- case 1011:
93
- return "internal_error";
94
- default:
95
- return "connection_lost";
96
- }
97
- }
98
- function isRetryableRefusal(closeCode) {
99
- return closeCode === REFUSAL_CLOSE_CODES.try_again;
100
- }
101
- function unsupportedSession(created) {
102
- if (created.protocol !== PROTOCOL_VERSION) {
103
- return `server speaks protocol ${String(created.protocol)}; this client speaks ${PROTOCOL_VERSION}`;
104
- }
105
- return null;
106
- }
107
- function audioFormat(created) {
108
- const spec = created?.media?.audio;
109
- if (!spec || spec.encoding !== "pcm_s16le" || typeof spec.rate !== "number") return null;
110
- return {
111
- ...spec,
112
- encoding: "pcm_s16le",
113
- rate: spec.rate,
114
- channels: spec.channels ?? 1,
115
- tag: spec.tag ?? STREAM_TAGS.audio
116
- };
117
- }
118
- function acceptsInput(format) {
119
- return format !== null && (format.direction === "in" || format.direction === "duplex");
120
- }
121
- function mediaFrame(tag, payload) {
122
- const bytes = payload instanceof ArrayBuffer ? new Uint8Array(payload) : new Uint8Array(payload.buffer, payload.byteOffset, payload.byteLength);
123
- const frame = new Uint8Array(bytes.byteLength + 1);
124
- frame[0] = tag;
125
- frame.set(bytes, 1);
126
- return frame.buffer;
127
- }
128
- function sessionUrl(root, slug, token, query, path) {
129
- const base = root.replace(/\/+$/, "");
130
- const segments = (path ?? slug).split("/").filter(Boolean);
131
- const encoded = (segments.length ? segments : [slug]).map(encodeURIComponent).join("/");
132
- const params = new URLSearchParams({ token, ...query ?? {} });
133
- return `${base}/${encoded}?${params.toString()}`;
134
- }
135
-
136
30
  // src/realtime/session.ts
137
31
  var DEFAULT_REALTIME_URL = "wss://rt.segmind.com";
138
32
  var WS_OPEN = 1;
@@ -202,6 +96,10 @@ var RealtimeSession = class {
202
96
  get end() {
203
97
  return this._end;
204
98
  }
99
+ /** The session options sent on the URL at open (`SessionOptions.params`). */
100
+ get params() {
101
+ return this.options.params ?? {};
102
+ }
205
103
  /** The `session.created` frame, once live. */
206
104
  get created() {
207
105
  return this._created;
@@ -544,6 +442,8 @@ export {
544
442
  reasonFromCloseCode,
545
443
  rms,
546
444
  sessionUrl,
547
- unsupportedSession
445
+ unsupportedSession,
446
+ videoControl,
447
+ webrtcVideo
548
448
  };
549
449
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/realtime/types.ts","../../src/realtime/protocol.ts","../../src/realtime/session.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.\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 /**\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 | '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/** One stream in `session.created.media`. */\nexport interface MediaStreamSpec {\n /** Byte 0 of a binary frame on this stream. */\n tag: number;\n /** `in` the client sends, `out` the server sends, `duplex` both. */\n direction: 'in' | 'out' | 'duplex';\n encoding: string;\n rate?: number;\n channels?: number;\n mime?: string;\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 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\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\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\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\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 ServerEvent,\n type SessionCreatedEvent,\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]);\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]);\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/** 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","/**\n * A managed realtime session: one primitive, explicit states, typed events,\n * and a `close()` that resolves with what the session cost.\n *\n * `opening` the token is being minted and the socket is connecting; sends\n * are queued (bounded) and flushed once the server says\n * `session.created`.\n * `live` sends go straight to the socket; a `ping` keeps the connection\n * warm.\n * `closed` terminal. Every ending reaches it exactly once: the server's\n * `session.ended`, a refusal before the session opened, or a\n * socket close with no frame (reason from the close code).\n *\n * A handle that has closed can never write again: `send*` after `closed`\n * returns false and does nothing.\n *\n * Nothing here touches the DOM or a browser global: the socket comes from\n * `webSocketFactory` (the runtime's `WebSocket` when none is given), so the\n * same core runs in a browser, React Native or Node.\n */\n\nimport { SegmindError } from '../core/errors';\nimport {\n acceptsInput,\n audioFormat,\n decodeServerEvent,\n encodeClientEvent,\n mediaFrame,\n reasonFromCloseCode,\n sessionUrl,\n unsupportedSession,\n} from './protocol';\nimport type {\n AudioFormat,\n ClientEvent,\n EndReason,\n ServerEvent,\n SessionCreatedEvent,\n SessionState,\n ServerEventType,\n SessionTokenProvider,\n SessionUpdateParams,\n Usage,\n} from './types';\n\n/** The production session service. */\nexport const DEFAULT_REALTIME_URL = 'wss://rt.segmind.com';\n\nexport interface SessionOptions {\n /** Session parameters sent on the query string (voice, instructions, vad…). */\n params?: Record<string, string>;\n /** The session's path on the service, from the model record's\n * `endpoints.session`. Default `/<slug>`. */\n path?: string;\n /** Milliseconds between `ping` frames while live. 0 disables. Default 15000. */\n heartbeatMs?: number;\n /** Sends queued while opening, beyond which `send*` returns false. Default 64. */\n maxQueuedSends?: number;\n /** Aborting closes the session, or cancels the open while it is still opening. */\n signal?: AbortSignal;\n}\n\nexport interface ClientOptions {\n /** Where the session service lives. Default `wss://rt.segmind.com`. */\n realtimeRoot?: string;\n /**\n * Trades the app's credentials for a short-lived session token. In a browser\n * or a phone app it calls the app's own backend, which calls\n * `segmind.realtime.createToken()`; the API key never leaves the server.\n */\n tokenProvider: SessionTokenProvider;\n /** How to open the socket. Default: the runtime's global `WebSocket`. */\n webSocketFactory?: (url: string) => WebSocketLike;\n /** Injectable clock for tests. */\n setInterval?: typeof setInterval;\n clearInterval?: typeof clearInterval;\n}\n\n/** The subset of WebSocket the session needs, so tests can fake it. */\nexport interface WebSocketLike {\n readonly readyState: number;\n binaryType?: string;\n send(data: string | ArrayBuffer): void;\n close(code?: number, reason?: string): void;\n onopen: ((ev: unknown) => void) | null;\n onmessage: ((ev: { data: unknown }) => void) | null;\n onclose: ((ev: { code: number; reason: string }) => void) | null;\n onerror: ((ev: unknown) => void) | null;\n}\n\nconst WS_OPEN = 1;\n\nexport type EventListener = (event: ServerEvent) => void;\n/** A listener for one event type, typed by it. */\nexport type TypedEventListener<T extends ServerEventType> = (event: Extract<ServerEvent, { type: T }>) => void;\nexport type StateListener = (state: SessionState, reason?: EndReason) => void;\n\nexport interface SessionEnd {\n reason: EndReason;\n usage: Usage | null;\n message?: string;\n /**\n * For a refusal, the server's error code (`insufficient_credits`,\n * `capacity`, `service_unavailable`…), or `unsupported_protocol`.\n */\n code?: string;\n /** The socket close code, when the ending came from a close rather than `session.ended`. */\n closeCode?: number;\n}\n\n/** A send made while opening: a JSON frame, or microphone PCM tagged once the stream is known. */\ntype QueuedSend = { text: string } | { pcm: ArrayBuffer };\n\n/**\n * `open()` rejects with this when the session ends before it is live. `end`\n * keeps the refusal's code and close code: branch on `end.code`\n * (`insufficient_credits`, `capacity`…) rather than parsing the message.\n */\nexport class SessionOpenError extends SegmindError {\n constructor(public readonly end: SessionEnd) {\n super(\n `session ${end.reason} before it opened` +\n (end.code ? ` (${end.code}${end.message ? `: ${end.message}` : ''})` : ''),\n { status: end.closeCode, detail: end.message },\n );\n }\n\n /** The server's refusal code (`insufficient_credits`, `capacity`, `token_expired`…), when there is one. */\n get code(): string | undefined {\n return this.end.code;\n }\n}\n\nfunction defaultWebSocket(url: string): WebSocketLike {\n const Ctor = (globalThis as { WebSocket?: new (url: string) => unknown }).WebSocket;\n if (!Ctor) throw new SegmindError('no global WebSocket in this runtime: pass webSocketFactory');\n return new Ctor(url) as WebSocketLike;\n}\n\nfunction pcmBytes(pcm: Int16Array | ArrayBuffer): ArrayBuffer {\n return pcm instanceof Int16Array\n ? (pcm.buffer.slice(pcm.byteOffset, pcm.byteOffset + pcm.byteLength) as ArrayBuffer)\n : pcm;\n}\n\nexport class RealtimeSession {\n private _state: SessionState = 'opening';\n private _reason: EndReason | null = null;\n private _usage: Usage | null = null;\n private _end: SessionEnd | null = null;\n private _created: SessionCreatedEvent | null = null;\n private socket: WebSocketLike | null = null;\n private readonly queue: QueuedSend[] = [];\n private readonly eventListeners = new Set<EventListener>();\n private readonly stateListeners = new Set<StateListener>();\n private readonly ended: Promise<SessionEnd>;\n private resolveEnded!: (end: SessionEnd) => void;\n private heartbeat: ReturnType<typeof setInterval> | null = null;\n private sawEndedFrame = false;\n private opening = false;\n private closeRequested = false;\n /** The `error` frame of a refusal, held until the close that follows carries its code. */\n private refusal: { code: string; message: string } | null = null;\n\n constructor(\n public readonly slug: string,\n private readonly client: ClientOptions,\n private readonly options: SessionOptions = {},\n ) {\n this.ended = new Promise<SessionEnd>((resolve) => {\n this.resolveEnded = resolve;\n });\n }\n\n // --- observable state -------------------------------------------------------\n\n get state(): SessionState {\n return this._state;\n }\n\n get reason(): EndReason | null {\n return this._reason;\n }\n\n /** The final usage, once the session has closed. */\n get usage(): Usage | null {\n return this._usage;\n }\n\n /** How the session ended (reason, usage, refusal code, close code), once closed. */\n get end(): SessionEnd | null {\n return this._end;\n }\n\n /** The `session.created` frame, once live. */\n get created(): SessionCreatedEvent | null {\n return this._created;\n }\n\n /**\n * The session's audio stream (`session.created.media.audio`): its rate,\n * channels and binary tag. Null before live, or for a session without\n * 16-bit PCM audio. Size capture and playback from it.\n */\n get audio(): AudioFormat | null {\n return audioFormat(this._created);\n }\n\n /** Every server event. Returns a function that removes the listener. */\n onEvent(listener: EventListener): () => void {\n this.eventListeners.add(listener);\n return () => this.eventListeners.delete(listener);\n }\n\n /** One event type, typed by it: `session.on('transcript.delta', (e) => e.text)`. */\n on<T extends ServerEventType>(type: T, listener: TypedEventListener<T>): () => void {\n return this.onEvent((event) => {\n if (event.type === type) listener(event as Extract<ServerEvent, { type: T }>);\n });\n }\n\n onState(listener: StateListener): () => void {\n this.stateListeners.add(listener);\n return () => this.stateListeners.delete(listener);\n }\n\n /** Every server event as an async iterable; ends when the session closes. */\n events(): AsyncIterable<ServerEvent> {\n const buffer: ServerEvent[] = [];\n let wake: (() => void) | null = null;\n let done = this._state === 'closed';\n const unsubscribe = this.onEvent((event) => {\n buffer.push(event);\n wake?.();\n });\n const unsubscribeState = this.onState((state) => {\n if (state === 'closed') {\n done = true;\n wake?.();\n }\n });\n return {\n [Symbol.asyncIterator]: () => ({\n next: async (): Promise<IteratorResult<ServerEvent>> => {\n while (buffer.length === 0 && !done) {\n await new Promise<void>((resolve) => {\n wake = resolve;\n });\n wake = null;\n }\n const event = buffer.shift();\n if (event) return { value: event, done: false };\n unsubscribe();\n unsubscribeState();\n return { value: undefined, done: true };\n },\n return: async (): Promise<IteratorResult<ServerEvent>> => {\n unsubscribe();\n unsubscribeState();\n return { value: undefined, done: true };\n },\n }),\n };\n }\n\n // --- lifecycle --------------------------------------------------------------\n\n /** Mint a token and connect. Resolves when the session is live, rejects when refused. */\n async open(): Promise<SessionCreatedEvent> {\n if (this._state !== 'opening' || this.socket || this.opening) {\n throw new SegmindError('session can only be opened once');\n }\n this.opening = true;\n const { signal } = this.options;\n if (signal) {\n if (signal.aborted) {\n this.finish('client', null, 'aborted before it opened');\n throw new SessionOpenError(this._end!);\n }\n signal.addEventListener('abort', () => void this.close(), { once: true });\n }\n let token: string;\n try {\n const minted = await this.client.tokenProvider(this.slug);\n token = typeof minted === 'string' ? minted : minted.token;\n // A token opens one session and lives about two minutes. Refusing a stale\n // one here gives the caller a clear code instead of a socket refusal.\n const expiresAt = typeof minted === 'string' ? undefined : minted.expires_at;\n if (!token || (expiresAt !== undefined && expiresAt * 1000 <= Date.now())) {\n this.finish('refused', null, token ? 'the session token has expired' : 'the token provider returned no token', {\n code: token ? 'token_expired' : 'unauthorized',\n });\n throw new SessionOpenError(this._end!);\n }\n } catch (error) {\n if (error instanceof SessionOpenError) throw error;\n this.finish('refused', null, `token mint failed: ${String(error)}`);\n throw error;\n }\n if ((this._state as SessionState) === 'closed') {\n // close() was called while the token was being minted.\n throw new SessionOpenError(this._end ?? { reason: 'client', usage: null });\n }\n const url = sessionUrl(\n this.client.realtimeRoot ?? DEFAULT_REALTIME_URL,\n this.slug,\n token,\n this.options.params,\n this.options.path,\n );\n const socket = (this.client.webSocketFactory ?? defaultWebSocket)(url);\n socket.binaryType = 'arraybuffer';\n this.socket = socket;\n socket.onmessage = (ev) => this.handleMessage(ev.data);\n socket.onclose = (ev) => this.handleClose(ev.code, ev.reason);\n socket.onerror = () => {\n /* the close that follows carries the reason */\n };\n\n return new Promise<SessionCreatedEvent>((resolve, reject) => {\n const offEvent = this.onEvent((event) => {\n if (event.type === 'session.created') {\n offEvent();\n offState();\n resolve(event);\n }\n });\n const offState = this.onState((state, reason) => {\n if (state === 'closed') {\n offEvent();\n offState();\n reject(new SessionOpenError(this._end ?? { reason: reason ?? 'refused', usage: null }));\n }\n });\n });\n }\n\n /**\n * Resolves when the session has closed, whichever side ended it, with the\n * final usage. Unlike `close()` it asks for nothing: use it to await the\n * ending of a session something else will end.\n */\n whenEnded(): Promise<SessionEnd> {\n return this.ended;\n }\n\n /** Ask the server to end the session. Resolves with the final usage after settlement. */\n close(): Promise<SessionEnd> {\n if (this._state === 'closed') return this.ended;\n this.closeRequested = true;\n if (this._state === 'live' && this.socket && this.socket.readyState === WS_OPEN) {\n this.rawSend(encodeClientEvent({ type: 'close' }));\n } else if (this.socket) {\n this.socket.close(1000, 'client');\n } else {\n // Still minting the token: nothing was reserved, nothing to settle.\n this.finish('client', null);\n }\n return this.ended;\n }\n\n // --- sends ------------------------------------------------------------------\n\n /**\n * Raw s16le PCM at the session rate (`audio.rate`), sent as a binary frame\n * tagged with the audio stream's tag. Before live it is queued and tagged\n * once `session.created` names the stream. Returns false when the session\n * takes no audio input.\n */\n sendAudio(pcm: Int16Array | ArrayBuffer): boolean {\n if (this._state === 'closed') return false;\n if (this._state === 'opening') return this.enqueue({ pcm: pcmBytes(pcm) });\n const format = this.audio;\n if (!acceptsInput(format)) return false;\n return this.rawSend(mediaFrame(format!.tag, pcmBytes(pcm)));\n }\n\n commitAudio(): boolean {\n return this.send({ type: 'audio.commit' });\n }\n\n sendText(text: string): boolean {\n return this.send({ type: 'text', text });\n }\n\n interrupt(): boolean {\n return this.send({ type: 'interrupt' });\n }\n\n update(session: SessionUpdateParams): boolean {\n return this.send({ type: 'session.update', session });\n }\n\n send(event: ClientEvent): boolean {\n if (this._state === 'closed') return false;\n const frame = encodeClientEvent(event);\n if (this._state === 'opening') return this.enqueue({ text: frame });\n return this.rawSend(frame);\n }\n\n private enqueue(item: QueuedSend): boolean {\n const limit = this.options.maxQueuedSends ?? 64;\n if (this.queue.length >= limit) return false;\n this.queue.push(item);\n return true;\n }\n\n private flushQueue(): void {\n const format = this.audio;\n for (const item of this.queue.splice(0)) {\n if ('text' in item) this.rawSend(item.text);\n else if (acceptsInput(format)) this.rawSend(mediaFrame(format!.tag, item.pcm));\n }\n }\n\n private rawSend(frame: string | ArrayBuffer): boolean {\n const socket = this.socket;\n if (!socket || socket.readyState !== WS_OPEN || this._state === 'closed') return false;\n try {\n socket.send(frame);\n return true;\n } catch {\n return false;\n }\n }\n\n // --- socket handlers ----------------------------------------------------------\n\n private handleMessage(data: unknown): void {\n if (typeof data !== 'string') return; // the server never sends binary\n let event: ServerEvent;\n try {\n event = decodeServerEvent(data);\n } catch {\n return; // forward-compatible: an event we do not know is not fatal\n }\n if (event.type === 'session.created') {\n const unsupported = unsupportedSession(event);\n if (unsupported) {\n // Live on the server: ask it to settle, and never speak a protocol we do not know.\n this.rawSend(encodeClientEvent({ type: 'close' }));\n this.finish('refused', null, unsupported, { code: 'unsupported_protocol' });\n return;\n }\n this._created = event;\n this.setState('live');\n this.flushQueue();\n this.startHeartbeat();\n }\n this.emit(event);\n if (event.type === 'session.ended') {\n this.sawEndedFrame = true;\n this.finish(event.reason, event.usage ?? null, event.message);\n } else if (event.type === 'error' && this._state === 'opening') {\n // A refusal. The server follows it with a close whose code says which\n // kind (4001, 4002, 4029, 1013…); the ending waits for that close.\n this.refusal = { code: event.code, message: event.message };\n }\n }\n\n private handleClose(code: number, reason: string): void {\n if (this._state === 'closed') return;\n if (this.sawEndedFrame) return;\n if (this.refusal) {\n this.finish('refused', null, this.refusal.message, {\n code: this.refusal.code,\n closeCode: code,\n });\n return;\n }\n const inferred =\n this.closeRequested && code === 1000 ? 'client' : reasonFromCloseCode(code, reason);\n this.finish(inferred, null, reason || undefined, {\n // A refusal without its frame still names its code in the close reason.\n code: inferred === 'refused' && reason ? reason : undefined,\n closeCode: code,\n });\n }\n\n private finish(\n reason: EndReason,\n usage: Usage | null,\n message?: string,\n detail: { code?: string; closeCode?: number } = {},\n ): void {\n if (this._state === 'closed') return;\n this.stopHeartbeat();\n this._reason = reason;\n this._usage = usage;\n this.queue.length = 0;\n const socket = this.socket;\n this.socket = null;\n if (socket && socket.readyState === WS_OPEN) {\n try {\n socket.close(1000, 'client');\n } catch {\n /* already closing */\n }\n }\n const end: SessionEnd = { reason, usage, message };\n if (detail.code !== undefined) end.code = detail.code;\n if (detail.closeCode !== undefined) end.closeCode = detail.closeCode;\n this._end = end;\n this.setState('closed', reason);\n this.resolveEnded(end);\n }\n\n private startHeartbeat(): void {\n const ms = this.options.heartbeatMs ?? 15000;\n if (ms <= 0) return;\n const schedule = this.client.setInterval ?? setInterval;\n this.heartbeat = schedule(() => {\n this.rawSend(encodeClientEvent({ type: 'ping' }));\n }, ms);\n }\n\n private stopHeartbeat(): void {\n if (this.heartbeat !== null) {\n (this.client.clearInterval ?? clearInterval)(this.heartbeat);\n this.heartbeat = null;\n }\n }\n\n private setState(state: SessionState, reason?: EndReason): void {\n this._state = state;\n for (const listener of this.stateListeners) listener(state, reason);\n }\n\n private emit(event: ServerEvent): void {\n for (const listener of this.eventListeners) listener(event);\n }\n}\n\n/**\n * Holds the service root and the token provider, and hands out sessions.\n * `connect()` is the shorthand for one session.\n */\nexport class RealtimeClient {\n constructor(private readonly options: ClientOptions) {\n if (typeof options?.tokenProvider !== 'function') throw new SegmindError('realtime: tokenProvider is required');\n }\n\n /** A session handle in `opening`; call `open()` to connect. */\n session(slug: string, options?: SessionOptions): RealtimeSession {\n return new RealtimeSession(slug, this.options, options);\n }\n\n /** Mint, connect and resolve once live. */\n async connect(slug: string, options?: SessionOptions): Promise<RealtimeSession> {\n const session = this.session(slug, options);\n await session.open();\n return session;\n }\n}\n\n/**\n * Opens one session and resolves once it is live.\n *\n * ```ts\n * import { connect } from 'segmind/realtime';\n *\n * const session = await connect('your-session-model', {\n * tokenProvider: () => fetch('/api/realtime-token', { method: 'POST' }).then((r) => r.json()),\n * });\n * session.on('transcript.delta', (e) => console.log(e.role, e.text));\n * session.sendText('Hello');\n * const { usage } = await session.close();\n * ```\n */\nexport function connect(slug: string, options: ClientOptions & SessionOptions): Promise<RealtimeSession> {\n const { params, path, heartbeatMs, maxQueuedSends, signal, ...client } = options;\n return new RealtimeClient(client).connect(slug, { params, path, heartbeatMs, maxQueuedSends, signal });\n}\n"],"mappings":";;;;;;;;;;;;;;;AAWO,IAAM,mBAAmB;AAGzB,IAAM,cAAc,EAAE,OAAO,GAAM,OAAO,EAAK;;;ACHtD,IAAM,qBAAqB,oBAAI,IAAY;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAGM,IAAM,gBAAN,cAA4B,aAAa;AAAA,EAC9C,YACE,SACgB,KAChB;AACA,UAAM,SAAS,EAAE,MAAM,IAAI,CAAC;AAFZ;AAAA,EAGlB;AAAA,EAHkB;AAIpB;AAGO,SAAS,kBAAkB,MAA2B;AAC3D,MAAI;AACJ,MAAI;AACF,aAAS,KAAK,MAAM,IAAI;AAAA,EAC1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e,KAAK,SAAS;AAC3D,WAAK,YAAY;AAAA,IACnB;AAAA,EACF;AAAA,EAEQ,SAAS,OAAqB,QAA0B;AAC9D,SAAK,SAAS;AACd,eAAW,YAAY,KAAK,eAAgB,UAAS,OAAO,MAAM;AAAA,EACpE;AAAA,EAEQ,KAAK,OAA0B;AACrC,eAAW,YAAY,KAAK,eAAgB,UAAS,KAAK;AAAA,EAC5D;AACF;AAMO,IAAM,iBAAN,MAAqB;AAAA,EAC1B,YAA6B,SAAwB;AAAxB;AAC3B,QAAI,OAAO,SAAS,kBAAkB,WAAY,OAAM,IAAI,aAAa,qCAAqC;AAAA,EAChH;AAAA,EAF6B;AAAA;AAAA,EAK7B,QAAQ,MAAc,SAA2C;AAC/D,WAAO,IAAI,gBAAgB,MAAM,KAAK,SAAS,OAAO;AAAA,EACxD;AAAA;AAAA,EAGA,MAAM,QAAQ,MAAc,SAAoD;AAC9E,UAAM,UAAU,KAAK,QAAQ,MAAM,OAAO;AAC1C,UAAM,QAAQ,KAAK;AACnB,WAAO;AAAA,EACT;AACF;AAgBO,SAAS,QAAQ,MAAc,SAAmE;AACvG,QAAM,EAAE,QAAQ,MAAM,aAAa,gBAAgB,QAAQ,GAAG,OAAO,IAAI;AACzE,SAAO,IAAI,eAAe,MAAM,EAAE,QAAQ,MAAM,EAAE,QAAQ,MAAM,aAAa,gBAAgB,OAAO,CAAC;AACvG;","names":[]}
1
+ {"version":3,"sources":["../../src/realtime/session.ts"],"sourcesContent":["/**\n * A managed realtime session: one primitive, explicit states, typed events,\n * and a `close()` that resolves with what the session cost.\n *\n * `opening` the token is being minted and the socket is connecting; sends\n * are queued (bounded) and flushed once the server says\n * `session.created`.\n * `live` sends go straight to the socket; a `ping` keeps the connection\n * warm.\n * `closed` terminal. Every ending reaches it exactly once: the server's\n * `session.ended`, a refusal before the session opened, or a\n * socket close with no frame (reason from the close code).\n *\n * A handle that has closed can never write again: `send*` after `closed`\n * returns false and does nothing.\n *\n * Nothing here touches the DOM or a browser global: the socket comes from\n * `webSocketFactory` (the runtime's `WebSocket` when none is given), so the\n * same core runs in a browser, React Native or Node.\n */\n\nimport { SegmindError } from '../core/errors';\nimport {\n acceptsInput,\n audioFormat,\n decodeServerEvent,\n encodeClientEvent,\n mediaFrame,\n reasonFromCloseCode,\n sessionUrl,\n unsupportedSession,\n} from './protocol';\nimport type {\n AudioFormat,\n ClientEvent,\n EndReason,\n ServerEvent,\n SessionCreatedEvent,\n SessionState,\n ServerEventType,\n SessionTokenProvider,\n SessionUpdateParams,\n Usage,\n} from './types';\n\n/** The production session service. */\nexport const DEFAULT_REALTIME_URL = 'wss://rt.segmind.com';\n\nexport interface SessionOptions {\n /** Session parameters sent on the query string (voice, instructions, vad…). */\n params?: Record<string, string>;\n /** The session's path on the service, from the model record's\n * `endpoints.session`. Default `/<slug>`. */\n path?: string;\n /** Milliseconds between `ping` frames while live. 0 disables. Default 15000. */\n heartbeatMs?: number;\n /** Sends queued while opening, beyond which `send*` returns false. Default 64. */\n maxQueuedSends?: number;\n /** Aborting closes the session, or cancels the open while it is still opening. */\n signal?: AbortSignal;\n}\n\nexport interface ClientOptions {\n /** Where the session service lives. Default `wss://rt.segmind.com`. */\n realtimeRoot?: string;\n /**\n * Trades the app's credentials for a short-lived session token. In a browser\n * or a phone app it calls the app's own backend, which calls\n * `segmind.realtime.createToken()`; the API key never leaves the server.\n */\n tokenProvider: SessionTokenProvider;\n /** How to open the socket. Default: the runtime's global `WebSocket`. */\n webSocketFactory?: (url: string) => WebSocketLike;\n /** Injectable clock for tests. */\n setInterval?: typeof setInterval;\n clearInterval?: typeof clearInterval;\n}\n\n/** The subset of WebSocket the session needs, so tests can fake it. */\nexport interface WebSocketLike {\n readonly readyState: number;\n binaryType?: string;\n send(data: string | ArrayBuffer): void;\n close(code?: number, reason?: string): void;\n onopen: ((ev: unknown) => void) | null;\n onmessage: ((ev: { data: unknown }) => void) | null;\n onclose: ((ev: { code: number; reason: string }) => void) | null;\n onerror: ((ev: unknown) => void) | null;\n}\n\nconst WS_OPEN = 1;\n\nexport type EventListener = (event: ServerEvent) => void;\n/** A listener for one event type, typed by it. */\nexport type TypedEventListener<T extends ServerEventType> = (event: Extract<ServerEvent, { type: T }>) => void;\nexport type StateListener = (state: SessionState, reason?: EndReason) => void;\n\nexport interface SessionEnd {\n reason: EndReason;\n usage: Usage | null;\n message?: string;\n /**\n * For a refusal, the server's error code (`insufficient_credits`,\n * `capacity`, `service_unavailable`…), or `unsupported_protocol`.\n */\n code?: string;\n /** The socket close code, when the ending came from a close rather than `session.ended`. */\n closeCode?: number;\n}\n\n/** A send made while opening: a JSON frame, or microphone PCM tagged once the stream is known. */\ntype QueuedSend = { text: string } | { pcm: ArrayBuffer };\n\n/**\n * `open()` rejects with this when the session ends before it is live. `end`\n * keeps the refusal's code and close code: branch on `end.code`\n * (`insufficient_credits`, `capacity`…) rather than parsing the message.\n */\nexport class SessionOpenError extends SegmindError {\n constructor(public readonly end: SessionEnd) {\n super(\n `session ${end.reason} before it opened` +\n (end.code ? ` (${end.code}${end.message ? `: ${end.message}` : ''})` : ''),\n { status: end.closeCode, detail: end.message },\n );\n }\n\n /** The server's refusal code (`insufficient_credits`, `capacity`, `token_expired`…), when there is one. */\n get code(): string | undefined {\n return this.end.code;\n }\n}\n\nfunction defaultWebSocket(url: string): WebSocketLike {\n const Ctor = (globalThis as { WebSocket?: new (url: string) => unknown }).WebSocket;\n if (!Ctor) throw new SegmindError('no global WebSocket in this runtime: pass webSocketFactory');\n return new Ctor(url) as WebSocketLike;\n}\n\nfunction pcmBytes(pcm: Int16Array | ArrayBuffer): ArrayBuffer {\n return pcm instanceof Int16Array\n ? (pcm.buffer.slice(pcm.byteOffset, pcm.byteOffset + pcm.byteLength) as ArrayBuffer)\n : pcm;\n}\n\nexport class RealtimeSession {\n private _state: SessionState = 'opening';\n private _reason: EndReason | null = null;\n private _usage: Usage | null = null;\n private _end: SessionEnd | null = null;\n private _created: SessionCreatedEvent | null = null;\n private socket: WebSocketLike | null = null;\n private readonly queue: QueuedSend[] = [];\n private readonly eventListeners = new Set<EventListener>();\n private readonly stateListeners = new Set<StateListener>();\n private readonly ended: Promise<SessionEnd>;\n private resolveEnded!: (end: SessionEnd) => void;\n private heartbeat: ReturnType<typeof setInterval> | null = null;\n private sawEndedFrame = false;\n private opening = false;\n private closeRequested = false;\n /** The `error` frame of a refusal, held until the close that follows carries its code. */\n private refusal: { code: string; message: string } | null = null;\n\n constructor(\n public readonly slug: string,\n private readonly client: ClientOptions,\n private readonly options: SessionOptions = {},\n ) {\n this.ended = new Promise<SessionEnd>((resolve) => {\n this.resolveEnded = resolve;\n });\n }\n\n // --- observable state -------------------------------------------------------\n\n get state(): SessionState {\n return this._state;\n }\n\n get reason(): EndReason | null {\n return this._reason;\n }\n\n /** The final usage, once the session has closed. */\n get usage(): Usage | null {\n return this._usage;\n }\n\n /** How the session ended (reason, usage, refusal code, close code), once closed. */\n get end(): SessionEnd | null {\n return this._end;\n }\n\n /** The session options sent on the URL at open (`SessionOptions.params`). */\n get params(): Readonly<Record<string, string>> {\n return this.options.params ?? {};\n }\n\n /** The `session.created` frame, once live. */\n get created(): SessionCreatedEvent | null {\n return this._created;\n }\n\n /**\n * The session's audio stream (`session.created.media.audio`): its rate,\n * channels and binary tag. Null before live, or for a session without\n * 16-bit PCM audio. Size capture and playback from it.\n */\n get audio(): AudioFormat | null {\n return audioFormat(this._created);\n }\n\n /** Every server event. Returns a function that removes the listener. */\n onEvent(listener: EventListener): () => void {\n this.eventListeners.add(listener);\n return () => this.eventListeners.delete(listener);\n }\n\n /** One event type, typed by it: `session.on('transcript.delta', (e) => e.text)`. */\n on<T extends ServerEventType>(type: T, listener: TypedEventListener<T>): () => void {\n return this.onEvent((event) => {\n if (event.type === type) listener(event as Extract<ServerEvent, { type: T }>);\n });\n }\n\n onState(listener: StateListener): () => void {\n this.stateListeners.add(listener);\n return () => this.stateListeners.delete(listener);\n }\n\n /** Every server event as an async iterable; ends when the session closes. */\n events(): AsyncIterable<ServerEvent> {\n const buffer: ServerEvent[] = [];\n let wake: (() => void) | null = null;\n let done = this._state === 'closed';\n const unsubscribe = this.onEvent((event) => {\n buffer.push(event);\n wake?.();\n });\n const unsubscribeState = this.onState((state) => {\n if (state === 'closed') {\n done = true;\n wake?.();\n }\n });\n return {\n [Symbol.asyncIterator]: () => ({\n next: async (): Promise<IteratorResult<ServerEvent>> => {\n while (buffer.length === 0 && !done) {\n await new Promise<void>((resolve) => {\n wake = resolve;\n });\n wake = null;\n }\n const event = buffer.shift();\n if (event) return { value: event, done: false };\n unsubscribe();\n unsubscribeState();\n return { value: undefined, done: true };\n },\n return: async (): Promise<IteratorResult<ServerEvent>> => {\n unsubscribe();\n unsubscribeState();\n return { value: undefined, done: true };\n },\n }),\n };\n }\n\n // --- lifecycle --------------------------------------------------------------\n\n /** Mint a token and connect. Resolves when the session is live, rejects when refused. */\n async open(): Promise<SessionCreatedEvent> {\n if (this._state !== 'opening' || this.socket || this.opening) {\n throw new SegmindError('session can only be opened once');\n }\n this.opening = true;\n const { signal } = this.options;\n if (signal) {\n if (signal.aborted) {\n this.finish('client', null, 'aborted before it opened');\n throw new SessionOpenError(this._end!);\n }\n signal.addEventListener('abort', () => void this.close(), { once: true });\n }\n let token: string;\n try {\n const minted = await this.client.tokenProvider(this.slug);\n token = typeof minted === 'string' ? minted : minted.token;\n // A token opens one session and lives about two minutes. Refusing a stale\n // one here gives the caller a clear code instead of a socket refusal.\n const expiresAt = typeof minted === 'string' ? undefined : minted.expires_at;\n if (!token || (expiresAt !== undefined && expiresAt * 1000 <= Date.now())) {\n this.finish('refused', null, token ? 'the session token has expired' : 'the token provider returned no token', {\n code: token ? 'token_expired' : 'unauthorized',\n });\n throw new SessionOpenError(this._end!);\n }\n } catch (error) {\n if (error instanceof SessionOpenError) throw error;\n this.finish('refused', null, `token mint failed: ${String(error)}`);\n throw error;\n }\n if ((this._state as SessionState) === 'closed') {\n // close() was called while the token was being minted.\n throw new SessionOpenError(this._end ?? { reason: 'client', usage: null });\n }\n const url = sessionUrl(\n this.client.realtimeRoot ?? DEFAULT_REALTIME_URL,\n this.slug,\n token,\n this.options.params,\n this.options.path,\n );\n const socket = (this.client.webSocketFactory ?? defaultWebSocket)(url);\n socket.binaryType = 'arraybuffer';\n this.socket = socket;\n socket.onmessage = (ev) => this.handleMessage(ev.data);\n socket.onclose = (ev) => this.handleClose(ev.code, ev.reason);\n socket.onerror = () => {\n /* the close that follows carries the reason */\n };\n\n return new Promise<SessionCreatedEvent>((resolve, reject) => {\n const offEvent = this.onEvent((event) => {\n if (event.type === 'session.created') {\n offEvent();\n offState();\n resolve(event);\n }\n });\n const offState = this.onState((state, reason) => {\n if (state === 'closed') {\n offEvent();\n offState();\n reject(new SessionOpenError(this._end ?? { reason: reason ?? 'refused', usage: null }));\n }\n });\n });\n }\n\n /**\n * Resolves when the session has closed, whichever side ended it, with the\n * final usage. Unlike `close()` it asks for nothing: use it to await the\n * ending of a session something else will end.\n */\n whenEnded(): Promise<SessionEnd> {\n return this.ended;\n }\n\n /** Ask the server to end the session. Resolves with the final usage after settlement. */\n close(): Promise<SessionEnd> {\n if (this._state === 'closed') return this.ended;\n this.closeRequested = true;\n if (this._state === 'live' && this.socket && this.socket.readyState === WS_OPEN) {\n this.rawSend(encodeClientEvent({ type: 'close' }));\n } else if (this.socket) {\n this.socket.close(1000, 'client');\n } else {\n // Still minting the token: nothing was reserved, nothing to settle.\n this.finish('client', null);\n }\n return this.ended;\n }\n\n // --- sends ------------------------------------------------------------------\n\n /**\n * Raw s16le PCM at the session rate (`audio.rate`), sent as a binary frame\n * tagged with the audio stream's tag. Before live it is queued and tagged\n * once `session.created` names the stream. Returns false when the session\n * takes no audio input.\n */\n sendAudio(pcm: Int16Array | ArrayBuffer): boolean {\n if (this._state === 'closed') return false;\n if (this._state === 'opening') return this.enqueue({ pcm: pcmBytes(pcm) });\n const format = this.audio;\n if (!acceptsInput(format)) return false;\n return this.rawSend(mediaFrame(format!.tag, pcmBytes(pcm)));\n }\n\n commitAudio(): boolean {\n return this.send({ type: 'audio.commit' });\n }\n\n sendText(text: string): boolean {\n return this.send({ type: 'text', text });\n }\n\n interrupt(): boolean {\n return this.send({ type: 'interrupt' });\n }\n\n update(session: SessionUpdateParams): boolean {\n return this.send({ type: 'session.update', session });\n }\n\n send(event: ClientEvent): boolean {\n if (this._state === 'closed') return false;\n const frame = encodeClientEvent(event);\n if (this._state === 'opening') return this.enqueue({ text: frame });\n return this.rawSend(frame);\n }\n\n private enqueue(item: QueuedSend): boolean {\n const limit = this.options.maxQueuedSends ?? 64;\n if (this.queue.length >= limit) return false;\n this.queue.push(item);\n return true;\n }\n\n private flushQueue(): void {\n const format = this.audio;\n for (const item of this.queue.splice(0)) {\n if ('text' in item) this.rawSend(item.text);\n else if (acceptsInput(format)) this.rawSend(mediaFrame(format!.tag, item.pcm));\n }\n }\n\n private rawSend(frame: string | ArrayBuffer): boolean {\n const socket = this.socket;\n if (!socket || socket.readyState !== WS_OPEN || this._state === 'closed') return false;\n try {\n socket.send(frame);\n return true;\n } catch {\n return false;\n }\n }\n\n // --- socket handlers ----------------------------------------------------------\n\n private handleMessage(data: unknown): void {\n if (typeof data !== 'string') return; // the server never sends binary\n let event: ServerEvent;\n try {\n event = decodeServerEvent(data);\n } catch {\n return; // forward-compatible: an event we do not know is not fatal\n }\n if (event.type === 'session.created') {\n const unsupported = unsupportedSession(event);\n if (unsupported) {\n // Live on the server: ask it to settle, and never speak a protocol we do not know.\n this.rawSend(encodeClientEvent({ type: 'close' }));\n this.finish('refused', null, unsupported, { code: 'unsupported_protocol' });\n return;\n }\n this._created = event;\n this.setState('live');\n this.flushQueue();\n this.startHeartbeat();\n }\n this.emit(event);\n if (event.type === 'session.ended') {\n this.sawEndedFrame = true;\n this.finish(event.reason, event.usage ?? null, event.message);\n } else if (event.type === 'error' && this._state === 'opening') {\n // A refusal. The server follows it with a close whose code says which\n // kind (4001, 4002, 4029, 1013…); the ending waits for that close.\n this.refusal = { code: event.code, message: event.message };\n }\n }\n\n private handleClose(code: number, reason: string): void {\n if (this._state === 'closed') return;\n if (this.sawEndedFrame) return;\n if (this.refusal) {\n this.finish('refused', null, this.refusal.message, {\n code: this.refusal.code,\n closeCode: code,\n });\n return;\n }\n const inferred =\n this.closeRequested && code === 1000 ? 'client' : reasonFromCloseCode(code, reason);\n this.finish(inferred, null, reason || undefined, {\n // A refusal without its frame still names its code in the close reason.\n code: inferred === 'refused' && reason ? reason : undefined,\n closeCode: code,\n });\n }\n\n private finish(\n reason: EndReason,\n usage: Usage | null,\n message?: string,\n detail: { code?: string; closeCode?: number } = {},\n ): void {\n if (this._state === 'closed') return;\n this.stopHeartbeat();\n this._reason = reason;\n this._usage = usage;\n this.queue.length = 0;\n const socket = this.socket;\n this.socket = null;\n if (socket && socket.readyState === WS_OPEN) {\n try {\n socket.close(1000, 'client');\n } catch {\n /* already closing */\n }\n }\n const end: SessionEnd = { reason, usage, message };\n if (detail.code !== undefined) end.code = detail.code;\n if (detail.closeCode !== undefined) end.closeCode = detail.closeCode;\n this._end = end;\n this.setState('closed', reason);\n this.resolveEnded(end);\n }\n\n private startHeartbeat(): void {\n const ms = this.options.heartbeatMs ?? 15000;\n if (ms <= 0) return;\n const schedule = this.client.setInterval ?? setInterval;\n this.heartbeat = schedule(() => {\n this.rawSend(encodeClientEvent({ type: 'ping' }));\n }, ms);\n }\n\n private stopHeartbeat(): void {\n if (this.heartbeat !== null) {\n (this.client.clearInterval ?? clearInterval)(this.heartbeat);\n this.heartbeat = null;\n }\n }\n\n private setState(state: SessionState, reason?: EndReason): void {\n this._state = state;\n for (const listener of this.stateListeners) listener(state, reason);\n }\n\n private emit(event: ServerEvent): void {\n for (const listener of this.eventListeners) listener(event);\n }\n}\n\n/**\n * Holds the service root and the token provider, and hands out sessions.\n * `connect()` is the shorthand for one session.\n */\nexport class RealtimeClient {\n constructor(private readonly options: ClientOptions) {\n if (typeof options?.tokenProvider !== 'function') throw new SegmindError('realtime: tokenProvider is required');\n }\n\n /** A session handle in `opening`; call `open()` to connect. */\n session(slug: string, options?: SessionOptions): RealtimeSession {\n return new RealtimeSession(slug, this.options, options);\n }\n\n /** Mint, connect and resolve once live. */\n async connect(slug: string, options?: SessionOptions): Promise<RealtimeSession> {\n const session = this.session(slug, options);\n await session.open();\n return session;\n }\n}\n\n/**\n * Opens one session and resolves once it is live.\n *\n * ```ts\n * import { connect } from 'segmind/realtime';\n *\n * const session = await connect('your-session-model', {\n * tokenProvider: () => fetch('/api/realtime-token', { method: 'POST' }).then((r) => r.json()),\n * });\n * session.on('transcript.delta', (e) => console.log(e.role, e.text));\n * session.sendText('Hello');\n * const { usage } = await session.close();\n * ```\n */\nexport function connect(slug: string, options: ClientOptions & SessionOptions): Promise<RealtimeSession> {\n const { params, path, heartbeatMs, maxQueuedSends, signal, ...client } = options;\n return new RealtimeClient(client).connect(slug, { params, path, heartbeatMs, maxQueuedSends, signal });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CO,IAAM,uBAAuB;AA4CpC,IAAM,UAAU;AA4BT,IAAM,mBAAN,cAA+B,aAAa;AAAA,EACjD,YAA4B,KAAiB;AAC3C;AAAA,MACE,WAAW,IAAI,MAAM,uBAClB,IAAI,OAAO,KAAK,IAAI,IAAI,GAAG,IAAI,UAAU,KAAK,IAAI,OAAO,KAAK,EAAE,MAAM;AAAA,MACzE,EAAE,QAAQ,IAAI,WAAW,QAAQ,IAAI,QAAQ;AAAA,IAC/C;AAL0B;AAAA,EAM5B;AAAA,EAN4B;AAAA;AAAA,EAS5B,IAAI,OAA2B;AAC7B,WAAO,KAAK,IAAI;AAAA,EAClB;AACF;AAEA,SAAS,iBAAiB,KAA4B;AACpD,QAAM,OAAQ,WAA4D;AAC1E,MAAI,CAAC,KAAM,OAAM,IAAI,aAAa,4DAA4D;AAC9F,SAAO,IAAI,KAAK,GAAG;AACrB;AAEA,SAAS,SAAS,KAA4C;AAC5D,SAAO,eAAe,aACjB,IAAI,OAAO,MAAM,IAAI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aAAa,qCAAqC;AAAA,EAChH;AAAA,EAF6B;AAAA;AAAA,EAK7B,QAAQ,MAAc,SAA2C;AAC/D,WAAO,IAAI,gBAAgB,MAAM,KAAK,SAAS,OAAO;AAAA,EACxD;AAAA;AAAA,EAGA,MAAM,QAAQ,MAAc,SAAoD;AAC9E,UAAM,UAAU,KAAK,QAAQ,MAAM,OAAO;AAC1C,UAAM,QAAQ,KAAK;AACnB,WAAO;AAAA,EACT;AACF;AAgBO,SAAS,QAAQ,MAAc,SAAmE;AACvG,QAAM,EAAE,QAAQ,MAAM,aAAa,gBAAgB,QAAQ,GAAG,OAAO,IAAI;AACzE,SAAO,IAAI,eAAe,MAAM,EAAE,QAAQ,MAAM,EAAE,QAAQ,MAAM,aAAa,gBAAgB,OAAO,CAAC;AACvG;","names":[]}
@@ -1,4 +1,4 @@
1
- import { a as SessionTokenProvider, r as SessionState, E as EndReason, x as Usage, e as SessionCreatedEvent, f as AudioFormat, g as ServerEvent, o as ServerEventType, s as SessionUpdateParams, C as ClientEvent, d as SegmindError } from './errors-CcHEuSmR.js';
1
+ import { a as SessionTokenProvider, t as SessionState, E as EndReason, z as Usage, g as SessionCreatedEvent, h as AudioFormat, i as ServerEvent, q as ServerEventType, u as SessionUpdateParams, C as ClientEvent, d as SegmindError } from './errors-DsVQfts3.js';
2
2
 
3
3
  /**
4
4
  * A managed realtime session: one primitive, explicit states, typed events,
@@ -124,6 +124,8 @@ declare class RealtimeSession {
124
124
  get usage(): Usage | null;
125
125
  /** How the session ended (reason, usage, refusal code, close code), once closed. */
126
126
  get end(): SessionEnd | null;
127
+ /** The session options sent on the URL at open (`SessionOptions.params`). */
128
+ get params(): Readonly<Record<string, string>>;
127
129
  /** The `session.created` frame, once live. */
128
130
  get created(): SessionCreatedEvent | null;
129
131
  /**