@siphon-project/control 0.1.3 → 0.2.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":["../src/errors.ts","../src/protocol.ts","../src/internal.ts","../src/session.ts","../src/client.ts","../src/server.ts","../src/sip.ts"],"names":["WebSocket","WebSocketServer"],"mappings":";;;;;;;;;AAwCO,IAAM,YAAA,GAAN,MAAM,aAAA,SAAqB,KAAA,CAAM;AAAA;AAAA,EAE7B,IAAA;AAAA;AAAA,EAEA,IAAA;AAAA;AAAA,EAEA,MAAA;AAAA,EAET,WAAA,CACE,IAAA,EACA,OAAA,EACA,OAAA,EACA;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,cAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,OAAO,OAAA,EAAS,IAAA;AACrB,IAAA,IAAA,CAAK,SAAS,OAAA,EAAS,MAAA;AAEvB,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,aAAA,CAAa,SAAS,CAAA;AAAA,EACpD;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,iBAAA,GAA6B;AAC3B,IAAA,OAAO,IAAA,CAAK,IAAA,KAAS,SAAA,IAAa,IAAA,CAAK,IAAA,KAAS,kBAAA;AAAA,EAClD;AAAA;AAAA,EAGA,OAAO,OAAA,CAAQ,IAAA,EAAwB,OAAA,EAA+B;AACpE,IAAA,OAAO,IAAI,aAAA,CAAa,SAAA,EAAW,6BAA6B,IAAI,CAAA,GAAA,EAAM,OAAO,CAAA,CAAA,EAAI;AAAA,MACnF;AAAA,KACD,CAAA;AAAA,EACH;AAAA;AAAA,EAGA,OAAO,aAAa,MAAA,EAA8B;AAChD,IAAA,OAAO,IAAI,aAAA;AAAA,MACT,cAAA;AAAA,MACA,sDAAsD,MAAM,CAAA,CAAA,CAAA;A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AA,EAC/B;AAAA;AAAA,EAGA,eAAe,OAAA,EAA4B;AACzC,IAAA,IAAA,CAAK,MAAA,CAAO,WAAW,OAAO,CAAA;AAAA,EAChC;AAAA;AAAA,EAGA,KAAA,GAAoB;AAClB,IAAA,OAAO,IAAA,CAAK,OAAO,SAAA,EAAU;AAAA,EAC/B;AAAA;AAAA,EAGA,OAAO,OAAA,EAAqC;AAC1C,IAAA,IAAA,CAAK,eAAe,OAAO,CAAA;AAC3B,IAAA,OAAO,IAAA,CAAK,OAAO,GAAA,EAAI;AAAA,EACzB;AAAA;AAAA,EAGA,GAAA,GAAqB;AACnB,IAAA,OAAO,IAAA,CAAK,OAAO,GAAA,EAAI;AAAA,EACzB;AAAA;AAAA,EAGA,KAAA,GAAuB;AACrB,IAAA,OAAO,IAAA,CAAK,OAAO,KAAA,EAAM;AAAA,EAC3B;AACF","file":"index.cjs","sourcesContent":["/**\n * The client error type for the SIPhon control plane.\n *\n * The load-bearing case is a server `status:\"error\"` reply, which becomes a\n * {@link ControlError} carrying the stable {@link ControlErrorCode} in `.code`\n * so callers can branch on the cause (e.g. treat `unsupported_verb` as \"the\n * server doesn't do media yet\" rather than a hard failure). Mirrors the Rust\n * `ControlError` enum and the Python `ControlError` exception.\n */\n\n/** Stable machine-readable error codes returned in a reply's `error.code`. */\nexport type ControlErrorCode =\n | \"unauthorized\"\n | \"forbidden\"\n | \"not_found\"\n | \"bad_request\"\n | \"conflict\"\n | \"invalid_state\"\n | \"rate_limited\"\n | \"originate_denied\"\n | \"unsupported_verb\"\n | \"unsupported_version\"\n | \"protocol_error\"\n | \"unavailable\";\n\n/**\n * How a {@link ControlError} arose. `command` is the wire-level rejection (it\n * carries a {@link ControlErrorCode}); the rest are transport / local failures\n * that never had a wire code.\n */\nexport type ControlErrorKind =\n | \"command\"\n | \"unauthorized\"\n | \"handshake\"\n | \"closed\"\n | \"timeout\"\n | \"websocket\"\n | \"config\";\n\n/** Everything that can go wrong driving the control plane. */\nexport class ControlError extends Error {\n /** The classification of this error. */\n readonly kind: ControlErrorKind;\n /** The stable wire code, present only for a `command` rejection. */\n readonly code?: ControlErrorCode;\n /** The HTTP status of a rejected upgrade, present only for `unauthorized`. */\n readonly status?: number;\n\n constructor(\n kind: ControlErrorKind,\n message: string,\n options?: { code?: ControlErrorCode; status?: number },\n ) {\n super(message);\n this.name = \"ControlError\";\n this.kind = kind;\n this.code = options?.code;\n this.status = options?.status;\n // Restore the prototype chain across the transpiled `extends Error`.\n Object.setPrototypeOf(this, ControlError.prototype);\n }\n\n /**\n * True when this is a server-side `unsupported_verb` rejection — the state a\n * media verb (`playFile`/`dtmf`/…) lands in until the server implements it.\n */\n isUnsupportedVerb(): boolean {\n return this.kind === \"command\" && this.code === \"unsupported_verb\";\n }\n\n /** A server `status:\"error\"` reply. */\n static command(code: ControlErrorCode, message: string): ControlError {\n return new ControlError(\"command\", `control command rejected (${code}): ${message}`, {\n code,\n });\n }\n\n /** The WebSocket upgrade was rejected before it opened (bad/missing token). */\n static unauthorized(status: number): ControlError {\n return new ControlError(\n \"unauthorized\",\n `unauthorized: the control token was rejected (HTTP ${status})`,\n { status },\n );\n }\n\n /** The `hello` handshake (or subprotocol negotiation) failed. */\n static handshake(detail: string): ControlError {\n return new ControlError(\"handshake\", `handshake failed: ${detail}`);\n }\n\n /** The connection is closed (or was never established). */\n static closed(): ControlError {\n return new ControlError(\"closed\", \"control connection is closed\");\n }\n\n /** A command was sent but no reply arrived within the configured window. */\n static timeout(timeoutMs: number): ControlError {\n return new ControlError(\"timeout\", `timed out awaiting a reply after ${timeoutMs}ms`);\n }\n\n /** A transport-level WebSocket error. */\n static websocket(detail: string): ControlError {\n return new ControlError(\"websocket\", `websocket error: ${detail}`);\n }\n\n /** A configuration value was invalid (bad URL, bad listen address, …). */\n static config(detail: string): ControlError {\n return new ControlError(\"config\", `configuration error: ${detail}`);\n }\n}\n","/**\n * Wire protocol for the SIPhon external control plane (`siphon-control.v1`).\n *\n * This module is the TypeScript mirror of the Rust `siphon-control-proto` crate\n * and the server's inline `src/control/protocol.rs`. The frame shapes here are\n * **byte-identical** to what the server emits and parses:\n *\n * - **command** (client → siphon): `{id, type:\"command\", module?, verb, target, args}`\n * - **reply** (siphon → client, `id` echoed): `{id, type:\"reply\", status, result|error}`\n * - **event** (siphon → client, un-id'd, pushed): `{type:\"event\", event, channel?, app?, call_id?, sip_call_id?, payload?}`\n *\n * `module` routes a command to the registered adapter (`sip`|`smpp`|`ss7`);\n * substrate verbs (`hello`, `resync`, `describe`, `set_var`, `get_var`) omit it.\n */\n\n/** The WebSocket subprotocol token this rail speaks. */\nexport const SUBPROTOCOL = \"siphon-control.v1\";\n\n/** The protocol version this build implements. */\nexport const PROTOCOL_VERSION = 1;\n\n/** Adapter routing key for the built-in SIP adapter. */\nexport const MODULE_SIP = \"sip\";\n/** Adapter routing key for an SMPP adapter (registered by a host binary). */\nexport const MODULE_SMPP = \"smpp\";\n/** Adapter routing key for an SS7 adapter (registered by a host binary). */\nexport const MODULE_SS7 = \"ss7\";\n\n/** The mandatory first-frame handshake verb. */\nexport const HELLO = \"hello\";\n/** Substrate verb: re-enumerate the channels this connection owns. */\nexport const RESYNC = \"resync\";\n/** Substrate verb: fetch the registered adapters' schema. */\nexport const DESCRIBE = \"describe\";\n/** Substrate verb: set a per-channel variable. */\nexport const SET_VAR = \"set_var\";\n/** Substrate verb: read a per-channel variable. */\nexport const GET_VAR = \"get_var\";\n\n/** The `type` discriminator on every frame. */\nexport type FrameType = \"command\" | \"reply\" | \"event\";\n\n/** The status of a reply. */\nexport type ReplyStatus = \"ok\" | \"error\";\n\nimport type { ControlErrorCode } from \"./errors\";\n\n/** The error body of a failed reply. */\nexport interface ReplyError {\n code: ControlErrorCode;\n message: string;\n}\n\n/** A reply frame (siphon → client, `id` echoed). */\nexport interface ReplyFrame {\n id: string;\n type: \"reply\";\n status: ReplyStatus;\n /** Present on success. */\n result?: unknown;\n /** Present on failure. */\n error?: ReplyError;\n}\n\n/**\n * A pushed event frame (siphon → client, un-id'd).\n *\n * Carries the stable id triple `{channel, call_id, sip_call_id}` so a controller\n * joins CDR + HEP with no mapping table: `sip_call_id` is byte-identical to the\n * CDR `call_id` and the HEP correlation chunk.\n */\nexport interface EventFrame {\n type: \"event\";\n /** Event name (e.g. `\"StasisStart\"`, `\"StasisEnd\"`). */\n event: string;\n /** The channel this event concerns (leg-scoped id), when applicable. */\n channel?: string;\n /** The application the channel was handed to. */\n app?: string;\n /** The internal call UUID (`CallActor.id`) — the grouping key across legs. */\n call_id?: string;\n /** The per-leg SIP Call-ID — the CDR / HEP join key. */\n sip_call_id?: string;\n /** Event-specific payload. */\n payload?: unknown;\n}\n\n/** Arguments of the `hello` handshake command. */\nexport interface HelloArgs {\n app: string;\n protocol?: number;\n}\n\n/** The `result` of a successful `hello` reply. */\nexport interface HelloResult {\n app: string;\n protocol: number;\n subprotocol: string;\n}\n\n/** One channel in a `resync` reply — the id triple plus its state + vars. */\nexport interface ChannelSnapshot {\n channel: string;\n call_id: string;\n sip_call_id: string;\n state: string;\n vars: Record<string, string>;\n}\n\n/** The `result` of a successful `resync` reply. */\nexport interface ResyncResult {\n channels: ChannelSnapshot[];\n}\n\n/**\n * Serialize a command frame to the exact JSON bytes the server parses.\n *\n * Field order follows the server's struct declaration order — `id`, `type`,\n * `module` (omitted when absent), `verb`, `target`, `args` — so the bytes are\n * identical to the Rust `CommandFrame` serialization. `target`/`args` are always\n * emitted (defaulting to JSON `null`); `module` is dropped when null/undefined.\n */\nexport function encodeCommand(\n id: string,\n module: string | null | undefined,\n verb: string,\n target: unknown,\n args: unknown,\n): string {\n const frame: Record<string, unknown> = { id, type: \"command\" };\n if (module != null) {\n frame.module = module;\n }\n frame.verb = verb;\n frame.target = target ?? null;\n frame.args = args ?? null;\n return JSON.stringify(frame);\n}\n\n/** Parse an inbound text frame into a {@link ReplyFrame} or {@link EventFrame}. */\nexport function parseInboundFrame(text: string): ReplyFrame | EventFrame | null {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n return null;\n }\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n const frameType = (value as { type?: unknown }).type;\n if (frameType === \"reply\") {\n return value as ReplyFrame;\n }\n if (frameType === \"event\") {\n return value as EventFrame;\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// SIP adapter (`module = \"sip\"`) verb + event helper names.\n// ---------------------------------------------------------------------------\n\n/**\n * The verbs the built-in SIP adapter accepts (`module = \"sip\"`).\n *\n * These are the exact wire tokens. The media verbs\n * (`play`/`stop`/`dtmf`/`hold`/`unhold`/`stream_start`/`stream_stop`) dispatch\n * against the configured media backend; the WebSocket-tee pair is\n * siphon-rtp-only, so a non-siphon-rtp backend answers them `unsupported_verb`.\n */\nexport const SipVerb = {\n Answer: \"answer\",\n /**\n * `180 Ringing` — alerting only, no early media (RFC 3261 §13.2.1). A body is\n * refused: SDP on an 18x is early media (RFC 3960 §3.1), which is\n * {@link SipVerb.Progress}'s job.\n */\n Ring: \"ring\",\n Progress: \"progress\",\n Reject: \"reject\",\n Hangup: \"hangup\",\n Refer: \"refer\",\n Route: \"route\",\n SetHeader: \"set_header\",\n GetHeader: \"get_header\",\n RemoveHeader: \"remove_header\",\n AcceptRefer: \"accept_refer\",\n RejectRefer: \"reject_refer\",\n Bridge: \"bridge\",\n Unbridge: \"unbridge\",\n Play: \"play\",\n Stop: \"stop\",\n Dtmf: \"dtmf\",\n Hold: \"hold\",\n Unhold: \"unhold\",\n StreamStart: \"stream_start\",\n StreamStop: \"stream_stop\",\n} as const;\n\n/** A value of {@link SipVerb}. */\nexport type SipVerbToken = (typeof SipVerb)[keyof typeof SipVerb];\n\n/** The well-known SIP-adapter event names (the ARI *Stasis* model). */\nexport type SipEventKind =\n | \"StasisStart\"\n | \"StasisEnd\"\n | \"ChannelStateChange\"\n | \"ChannelHangupRequest\"\n | \"ChannelDtmfReceived\"\n | \"PlayStarted\"\n | \"TransferRequested\"\n | \"TransferProgress\"\n | \"TransferCompleted\"\n | \"TransferFailed\"\n | \"ChannelBridged\"\n | \"BridgeFailed\"\n | \"ChannelUnbridged\"\n | \"PlayFinished\"\n | \"WsTeeStarted\"\n | \"WsTeeEnded\"\n | \"WsBridgeStarted\"\n | \"WsBridgeEnded\"\n | (string & {});\n\n/** Parse a wire event name; unknown names pass through verbatim (forward-compatible). */\nexport function sipEventKind(name: string): SipEventKind {\n return name as SipEventKind;\n}\n\n/**\n * The `payload` of a `ChannelDtmfReceived` event — an in-band DTMF digit the\n * media engine detected on a controlled call's leg. Cast a\n * {@link import(\"./sip\").CallEvent}'s `payload` to this when\n * `kind === \"ChannelDtmfReceived\"`.\n */\nexport interface ChannelDtmfPayload {\n /** The single detected digit (`0`–`9`, `*`, `#`, `A`–`D`). */\n digit: string;\n /** The tone duration in milliseconds. */\n duration_ms: number;\n /** The tone volume in dBm0 (negative). */\n volume: number;\n /** The From-tag of the leg the digit came from. */\n from_tag: string;\n}\n\n/**\n * The `payload` of a `PlayStarted` event — a `play` the media backend accepted\n * and started. Cast a {@link import(\"./sip\").CallEvent}'s `payload` to this when\n * `kind === \"PlayStarted\"`.\n *\n * `play_id` is the engine's handle on that one playback — what a targeted `stop`\n * ends and what a gain change addresses — and is the same value the `play`\n * command reply carried, which is how the event correlates with the command.\n * The media contract answers `play` accept-on-start, so this event is the\n * playback beginning, not a claim that audio has reached the wire: a fetched\n * source (`source: \"url\"`) accepts before its body has arrived, which is why\n * `duration_ms` can be absent.\n */\nexport interface PlayStartedPayload {\n /** Which source it started from: `file`, `blob`, `db_id`, `tone` or `url`. */\n source: string;\n /** The engine's handle on this playback, when it assigned one. */\n play_id?: number | null;\n /** The playback's length in ms, when the engine knew it at accept time. */\n duration_ms?: number | null;\n}\n\n/** The RFC 3891 `Replaces` triple embedded in a {@link TransferRequestedPayload}. */\nexport interface TransferReplaces {\n call_id: string;\n from_tag: string;\n to_tag: string;\n early_only: boolean;\n}\n\n/**\n * The `payload` of a `TransferRequested` event — an inbound REFER on a\n * controlled call, handed to the app to accept / reject. Cast a\n * {@link import(\"./sip\").CallEvent}'s `payload` to this when\n * `kind === \"TransferRequested\"`.\n */\nexport interface TransferRequestedPayload {\n /** The Refer-To URI (the transfer target). */\n refer_to: string;\n /** The embedded `Replaces` triple for an attended transfer, if present. */\n replaces?: TransferReplaces | null;\n /** The From-tag of the referring party, if known. */\n from_tag?: string | null;\n}\n\n/**\n * Where a verdict on an *outbound* REFER came from — the `stage` of a\n * {@link TransferOutcomePayload}. Unknown tokens pass through verbatim\n * (forward-compatible).\n */\nexport type TransferStage =\n /** `2xx` to the REFER: accepted for processing only (RFC 3515 §2.4.4). */\n | \"accepted\"\n /** `401`/`407` answered with credentials; `attempt` says which try. */\n | \"challenged\"\n /** A non-terminating `message/sipfrag` NOTIFY reported progress. */\n | \"notify\"\n /** A terminating sipfrag NOTIFY reported a `2xx`: the transfer completed. */\n | \"transferred\"\n /** A terminating sipfrag NOTIFY reported `3xx`+: the target failed. */\n | \"refused\"\n /** The referee refused the REFER itself: the transfer never started. */\n | \"rejected\"\n /** Challenged with no way to answer (no credentials / retry cap). */\n | \"unauthorized\"\n /** The subscription ended with no usable status — never read as success. */\n | \"no_outcome\"\n /** The call ended with the transfer still outstanding. */\n | \"call_ended\"\n | (string & {});\n\n/**\n * The `payload` shared by the `TransferProgress`, `TransferCompleted` and\n * `TransferFailed` events — one verdict on a transfer this app asked for with\n * the `refer` verb.\n *\n * The `refer` command resolves as soon as siphon has sent the REFER; RFC 3515\n * §2.4.4 puts the real outcome on the implicit subscription that follows. Expect\n * zero or more `TransferProgress`, then exactly one `TransferCompleted` /\n * `TransferFailed`. Cast a {@link import(\"./sip\").CallEvent}'s `payload` to this\n * when `kind` is one of those three.\n */\nexport interface TransferOutcomePayload {\n /** Where this verdict came from. */\n stage: TransferStage;\n /** The Refer-To URI the REFER carried, when known. */\n refer_to?: string | null;\n /**\n * The SIP status this verdict rests on: the REFER's own response status for\n * `accepted` / `challenged` / `rejected` / `unauthorized`, the sipfrag status\n * for the NOTIFY-driven stages.\n */\n code?: number | null;\n /** That status's reason phrase, when the peer supplied one. */\n reason?: string | null;\n /**\n * Which REFER attempt this verdict is about, 1-based. `null` once the REFER\n * transaction is over (the NOTIFY-driven stages).\n */\n attempt?: number | null;\n}\n\n/**\n * Whether an event name ends a transfer this app asked for. Exactly one such\n * event arrives per `refer`, so this is the signal to stop waiting.\n */\nexport function isTransferFinal(name: string): boolean {\n return name === \"TransferCompleted\" || name === \"TransferFailed\";\n}\n\n/**\n * What happens to the surviving leg when its bridge partner hangs up — the\n * `onPeerHangup` option of {@link import(\"./sip\").Call.bridge}.\n *\n * `\"hangup\"` (the default) tears the survivor down too: a bridged pair behaves\n * like one call. `\"hold\"` keeps it up, held (RFC 3264 §8.4) and still owned, so\n * the app can bridge it to somebody else — the supervisor / attended-hand-off\n * case. A closed set: the server refuses anything else with\n * `code === \"bad_request\"` rather than guessing at a teardown policy.\n */\nexport type PeerHangupPolicy = \"hangup\" | \"hold\";\n\n/**\n * Which side of a bridge a leg is — the `role` of a\n * {@link ChannelBridgedPayload}. The `anchor` is the channel the `bridge` was\n * addressed to and keeps its media session; the `peer` is the one named by\n * `with`, whose own media session was deleted when it joined. Unknown tokens\n * pass through verbatim (forward-compatible).\n */\nexport type BridgeRole = \"anchor\" | \"peer\" | (string & {});\n\n/**\n * Which of a bridge's two re-INVITEs was refused — the `stage` of a\n * {@link BridgeFailedPayload}. `offering_peer` means the `with` leg refused the\n * anchor's media and the anchor was never touched; `offering_anchor` means the\n * peer answered but the anchor refused what it was re-offered. Unknown tokens\n * pass through verbatim (forward-compatible).\n */\nexport type BridgeStage = \"offering_peer\" | \"offering_anchor\" | (string & {});\n\n/**\n * The `payload` of a `ChannelBridged` event — the bridge formed and the two\n * parties can hear each other.\n *\n * A bridge is two RFC 3261 §14 re-INVITEs across two dialogs, so the `bridge`\n * command reply reports only the local action (the media re-pointed, the first\n * re-INVITE on the wire) and this event is the outcome. It is pushed on **both**\n * bridged channels, each copy naming the other leg. Cast a\n * {@link import(\"./sip\").CallEvent}'s `payload` to this when\n * `kind === \"ChannelBridged\"`.\n */\nexport interface ChannelBridgedPayload {\n /** The internal `CallActor` id of the leg on the other side. */\n peer_call_id: string;\n /** That leg's SIP `Call-ID` — the CDR / HEP join key for the other party. */\n peer_sip_call_id: string;\n /** Which side *this* channel is. */\n role: BridgeRole;\n /** Whether the bridged pair lives on the media engine (the anchor's session). */\n anchored: boolean;\n}\n\n/**\n * The `payload` of a `BridgeFailed` event — one of the bridge's two re-INVITEs\n * was refused and both legs were left exactly as they were. Never a teardown:\n * the app still owns both calls and can retry, bridge elsewhere, or hang up.\n */\nexport interface BridgeFailedPayload {\n /** Which re-INVITE was refused. */\n stage: BridgeStage;\n /** The SIP status the refusing leg answered with (`488`, `491`, `500`, …). */\n code?: number | null;\n /** The SIP `Call-ID` of the other leg in the attempt. */\n peer_sip_call_id?: string | null;\n}\n\n/**\n * The `payload` of a `ChannelUnbridged` event — the bridge was broken. Both legs\n * stay answered, owned and held (RFC 3264 §8.4 `a=sendonly`); neither is hung\n * up, because that would be indistinguishable from two hangups. Pushed on both\n * channels.\n */\nexport interface ChannelUnbridgedPayload {\n /** The internal `CallActor` id of the leg that was on the other side. */\n peer_call_id: string;\n /** That leg's SIP `Call-ID`. */\n peer_sip_call_id: string;\n /** The reason the `unbridge` carried (default `\"unbridged\"`). */\n reason: string;\n}\n\n/**\n * The `payload` of a `PlayFinished` event — a playback ended.\n *\n * `completed` is the field to branch on: a stop, a supersede and an error all\n * end a playback without the prompt having been heard in full, and the accept's\n * estimated duration says nothing about which happened.\n */\nexport interface PlayFinishedPayload {\n from_tag: string;\n to_tag?: string | null;\n /** Correlates with the `play` accept and the `PlayStarted` event. */\n play_id: number;\n /** `completed`, `stopped`, `superseded` or `error`. */\n reason: string;\n /** Whether the prompt drained naturally — the only reason it was heard in full. */\n completed: boolean;\n played_ms?: number | null;\n}\n\n/**\n * The `payload` of a `WsTeeStarted` event — a WebSocket audio **tee** began\n * streaming a copy of the channel's audio. Additive: the call relays on\n * regardless, so a tee never affects the parties.\n *\n * `streamId` correlates this event with the `start` frame on the socket, and\n * the wire shape is stated so a consumer decodes the binary frames without\n * guessing.\n */\nexport interface WsTeeStartedPayload {\n from_tag: string;\n stream_id: string;\n ws_uri: string;\n /** `both`, `caller` or `callee`. */\n direction: string;\n /** 1 = mono/mixed, 2 = caller/callee interleaved. */\n channels: number;\n /** Wire sample rate in Hz (L16, little-endian). */\n sample_rate: number;\n}\n\n/**\n * The `payload` of a `WsTeeEnded` event. Exactly one arrives per\n * `WsTeeStarted`, including when the *server* ends it, so a consumer learns\n * the stream died rather than silently losing the audio.\n *\n * `frames_dropped > 0` means the consumer could not keep up; the call itself\n * was never affected.\n */\nexport interface WsTeeEndedPayload {\n from_tag: string;\n stream_id: string;\n /** `detached`, `server_closed`, `server_stopped`, `call_ended` or `transport_error`. */\n reason: string;\n /** `detached` is the only orderly end; anything else stopped the audio mid-call. */\n unexpected: boolean;\n frames_sent?: number | null;\n frames_dropped?: number | null;\n}\n\n/**\n * The `payload` of a `WsBridgeStarted` event — a WebSocket **takeover** bridge\n * began. Unlike a tee this *replaced* the call's audio path: the WebSocket\n * server is now the leg's far side and A-to-B is unwired.\n */\nexport interface WsBridgeStartedPayload {\n from_tag: string;\n stream_id: string;\n ws_uri: string;\n /** Wire sample rate in Hz (L16, little-endian). */\n sample_rate: number;\n}\n\n/**\n * The `payload` of a `WsBridgeEnded` event. Exactly one per\n * `WsBridgeStarted`; a re-point arrives as an ended (reason `detached`)\n * followed by a fresh started.\n *\n * `unexpected` matters more here than on a tee: a bridge *is* the call's media\n * path, so anything but `detached` leaves both parties up and hearing nothing.\n */\nexport interface WsBridgeEndedPayload {\n from_tag: string;\n stream_id: string;\n /** `detached`, `server_closed`, `server_stopped`, `call_ended` or `transport_error`. */\n reason: string;\n unexpected: boolean;\n}\n\n/**\n * Whether an event name ends a bridge this app asked for. Exactly one such event\n * arrives per `bridge`, so this is the signal to stop waiting. `ChannelUnbridged`\n * is not one of them — it ends a bridge that already formed.\n */\nexport function isBridgeFinal(name: string): boolean {\n return name === \"ChannelBridged\" || name === \"BridgeFailed\";\n}\n","/** Small internal utilities shared by the client, server, and SIP facade. */\n\n/**\n * An unbounded, single-consumer async queue (the TypeScript analogue of Rust's\n * `tokio::sync::mpsc::unbounded_channel`). `push` never blocks; `next` resolves\n * with the next item, or `null` once the queue is closed and drained.\n */\nexport class AsyncQueue<T> {\n private readonly items: T[] = [];\n private readonly waiters: Array<(value: T | null) => void> = [];\n private closed = false;\n\n /** Enqueue an item (or hand it directly to a waiting consumer). */\n push(item: T): void {\n if (this.closed) {\n return;\n }\n const waiter = this.waiters.shift();\n if (waiter) {\n waiter(item);\n } else {\n this.items.push(item);\n }\n }\n\n /** Await the next item, or `null` once the queue is closed and drained. */\n next(): Promise<T | null> {\n if (this.items.length > 0) {\n return Promise.resolve(this.items.shift() as T);\n }\n if (this.closed) {\n return Promise.resolve(null);\n }\n return new Promise((resolve) => this.waiters.push(resolve));\n }\n\n /** Close the queue: pending and future `next()` calls resolve with `null`. */\n close(): void {\n if (this.closed) {\n return;\n }\n this.closed = true;\n for (const waiter of this.waiters.splice(0)) {\n waiter(null);\n }\n }\n\n /** Async-iterate the queue until it closes. */\n async *[Symbol.asyncIterator](): AsyncIterableIterator<T> {\n for (;;) {\n const item = await this.next();\n if (item === null) {\n return;\n }\n yield item;\n }\n }\n}\n\n/** A shared, mutable request-id counter (Rust's `Arc<AtomicU64>`). */\nexport interface IdCounter {\n value: number;\n}\n\n/** Resolve after `ms` milliseconds. */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/**\n * One live WebSocket connection: request-id correlation, the read path, and\n * generic event fan-out. Knows nothing about SIP — it moves opaque `{module,\n * verb, target, args}` frames and hands every event to a sink.\n *\n * Shared verbatim by the inbound client and the per-call-connect server; only\n * how the socket is *acquired* differs. Mirrors the Rust `SessionCore`.\n */\n\nimport type { RawData, WebSocket } from \"ws\";\n\nimport { ControlError } from \"./errors\";\nimport type { IdCounter } from \"./internal\";\nimport { encodeCommand, parseInboundFrame } from \"./protocol\";\nimport type { EventFrame } from \"./protocol\";\n\n/** A sink the read path calls for every inbound event frame (any module). */\nexport type EventSink = (frame: EventFrame) => void;\n\n/**\n * Anything that can send a control command and await its correlated reply.\n *\n * Implemented by {@link Session} (bound to one connection — the per-call-connect\n * server) and by the client's commander (routes to the current session,\n * surviving reconnects — the inbound client). Lets a facade's handle command its\n * call without caring which mode it runs in.\n */\nexport interface CommandTransport {\n command(\n module: string | null,\n verb: string,\n target: unknown,\n args: unknown,\n ): Promise<unknown>;\n}\n\ninterface Pending {\n resolve: (result: unknown) => void;\n reject: (error: ControlError) => void;\n timer: ReturnType<typeof setTimeout>;\n}\n\n/** The shared, transport-agnostic state of one connection. */\nexport class Session implements CommandTransport {\n private readonly pending = new Map<string, Pending>();\n private closed = false;\n private readonly closeWaiters: Array<() => void> = [];\n\n constructor(\n private readonly socket: WebSocket,\n private readonly nextId: IdCounter,\n private readonly replyTimeoutMs: number,\n private readonly eventSink: EventSink,\n ) {\n socket.on(\"message\", (data: RawData) => this.onMessage(data.toString()));\n socket.on(\"close\", () => this.markClosed());\n socket.on(\"error\", () => this.markClosed());\n }\n\n /**\n * Send a command and await its correlated reply. Maps a `status:\"error\"`\n * reply to a rejected {@link ControlError} carrying the wire code.\n */\n command(\n module: string | null,\n verb: string,\n target: unknown,\n args: unknown,\n ): Promise<unknown> {\n if (this.closed) {\n return Promise.reject(ControlError.closed());\n }\n const id = `c-${this.nextId.value++}`;\n const text = encodeCommand(id, module, verb, target, args);\n return new Promise<unknown>((resolve, reject) => {\n const timer = setTimeout(() => {\n this.pending.delete(id);\n reject(ControlError.timeout(this.replyTimeoutMs));\n }, this.replyTimeoutMs);\n this.pending.set(id, { resolve, reject, timer });\n try {\n this.socket.send(text);\n } catch (error) {\n this.pending.delete(id);\n clearTimeout(timer);\n reject(ControlError.websocket(String(error)));\n }\n });\n }\n\n private onMessage(text: string): void {\n const frame = parseInboundFrame(text);\n if (frame === null) {\n return;\n }\n if (frame.type === \"reply\") {\n const pending = this.pending.get(frame.id);\n if (!pending) {\n return; // reply for an unknown / expired id — drop.\n }\n this.pending.delete(frame.id);\n clearTimeout(pending.timer);\n if (frame.status === \"ok\") {\n pending.resolve(frame.result ?? null);\n } else {\n const code = frame.error?.code ?? \"protocol_error\";\n const message = frame.error?.message ?? \"error reply without an error body\";\n pending.reject(ControlError.command(code, message));\n }\n } else {\n this.eventSink(frame);\n }\n }\n\n /** Explicitly close the connection. */\n close(): void {\n try {\n this.socket.close();\n } catch {\n // ignore — already closing / closed.\n }\n this.markClosed();\n }\n\n private markClosed(): void {\n if (this.closed) {\n return;\n }\n this.closed = true;\n for (const pending of this.pending.values()) {\n clearTimeout(pending.timer);\n pending.reject(ControlError.closed());\n }\n this.pending.clear();\n for (const waiter of this.closeWaiters.splice(0)) {\n waiter();\n }\n }\n\n isClosed(): boolean {\n return this.closed;\n }\n\n /** Resolve once the connection is closed. */\n waitClosed(): Promise<void> {\n if (this.closed) {\n return Promise.resolve();\n }\n return new Promise((resolve) => this.closeWaiters.push(resolve));\n }\n}\n","/**\n * The protocol-agnostic inbound-persistent control client.\n *\n * Knows nothing about SIP: it owns the transport, the `hello` handshake,\n * request-id correlation, reconnect + `resync`, and a generic event stream. Its\n * headline primitive is {@link ControlClient.command} over `{module, verb,\n * target, args}`, which works for any adapter with zero changes. Typed\n * per-protocol facades (see {@link SipClient}) are built on top. Mirrors the\n * Rust `ControlClient`.\n */\n\nimport WebSocket from \"ws\";\n\nimport { ControlError } from \"./errors\";\nimport type { IdCounter } from \"./internal\";\nimport { AsyncQueue, sleep } from \"./internal\";\nimport {\n DESCRIBE,\n HELLO,\n PROTOCOL_VERSION,\n RESYNC,\n SUBPROTOCOL,\n} from \"./protocol\";\nimport type {\n ChannelSnapshot,\n EventFrame,\n HelloResult,\n ResyncResult,\n} from \"./protocol\";\nimport type { CommandTransport } from \"./session\";\nimport { Session } from \"./session\";\n\n/** How a {@link ControlClient} connects and behaves. */\nexport interface ClientConfig {\n /** The control-plane URL, e.g. `ws://siphon:9090/control/ws` (or `wss://…`). */\n url: string;\n /** The application name — must equal the token's configured app. */\n app: string;\n /** The bearer token presented on the upgrade. */\n token: string;\n /** Protocol version to advertise in `hello` (defaults to {@link PROTOCOL_VERSION}). */\n protocol?: number;\n /** How long a command waits for its reply before a timeout (default 10 000 ms). */\n replyTimeoutMs?: number;\n /** Backoff between reconnect attempts in {@link ControlClient.run} (default 1 000 ms). */\n reconnectBackoffMs?: number;\n}\n\ntype ResolvedConfig = Required<ClientConfig>;\n\nfunction resolveConfig(config: ClientConfig): ResolvedConfig {\n return {\n url: config.url,\n app: config.app,\n token: config.token,\n protocol: config.protocol ?? PROTOCOL_VERSION,\n replyTimeoutMs: config.replyTimeoutMs ?? 10_000,\n reconnectBackoffMs: config.reconnectBackoffMs ?? 1_000,\n };\n}\n\n/** An item on the client's generic event stream. */\nexport type ClientEvent =\n | { type: \"event\"; frame: EventFrame }\n | { type: \"reattach\"; snapshot: ChannelSnapshot };\n\ntype EventCallback = (event: ClientEvent) => void;\n\n/** A generic subscription to the client's event stream (see {@link ControlClient.events}). */\nexport class EventStream {\n constructor(private readonly queue: AsyncQueue<ClientEvent>) {}\n\n /** Await the next event. `null` once the client shuts down. */\n next(): Promise<ClientEvent | null> {\n return this.queue.next();\n }\n\n [Symbol.asyncIterator](): AsyncIterableIterator<ClientEvent> {\n return this.queue[Symbol.asyncIterator]();\n }\n}\n\n/**\n * The protocol-agnostic inbound-persistent control client.\n *\n * Use {@link ControlClient.command} directly for any module, or wrap it in a\n * typed facade such as {@link SipClient}.\n */\nexport class ControlClient {\n private readonly config: ResolvedConfig;\n private readonly nextId: IdCounter = { value: 1 };\n private current: Session | null = null;\n private eventCallback: EventCallback | null = null;\n private shutdownRequested = false;\n private readonly shutdownWaiters: Array<() => void> = [];\n\n private constructor(config: ClientConfig) {\n this.config = resolveConfig(config);\n }\n\n /**\n * Connect + `hello`. A bad token surfaces as a {@link ControlError} of kind\n * `unauthorized` (the upgrade is rejected 401 before the socket opens).\n */\n static async connect(config: ClientConfig): Promise<ControlClient> {\n const client = new ControlClient(config);\n client.current = await client.connectAndHandshake();\n return client;\n }\n\n /**\n * Register a callback for every event (pushed events + reconnect reattach).\n * Overwrites any previous callback / stream. Facades set this internally.\n */\n onEvent(callback: EventCallback): void {\n this.eventCallback = callback;\n }\n\n /** A pull-style stream of every event. Overwrites any previous callback. */\n events(): EventStream {\n const queue = new AsyncQueue<ClientEvent>();\n this.eventCallback = (event) => queue.push(event);\n return new EventStream(queue);\n }\n\n /**\n * Send a raw command on the current session and return the reply's `result`.\n * The generic primitive every facade is built on.\n */\n async command(\n module: string | null,\n verb: string,\n target: unknown,\n args: unknown,\n ): Promise<unknown> {\n const session = this.current;\n if (!session || session.isClosed()) {\n throw ControlError.closed();\n }\n return session.command(module, verb, target, args);\n }\n\n /** Fetch the registered adapters' verb/event schema (`describe`). */\n async describe(): Promise<unknown> {\n return this.command(null, DESCRIBE, null, null);\n }\n\n /** Re-enumerate the channels this connection owns (`resync`). */\n async resync(): Promise<ChannelSnapshot[]> {\n const value = (await this.command(null, RESYNC, null, null)) as ResyncResult | null;\n return value?.channels ?? [];\n }\n\n /**\n * A {@link CommandTransport} that routes to the client's *current* session (so\n * a facade handle keeps working across reconnects). Used by {@link SipClient}.\n */\n commander(): CommandTransport {\n return {\n command: (module, verb, target, args) => this.command(module, verb, target, args),\n };\n }\n\n /**\n * Drive the client: keep the connection alive, reconnecting with backoff and\n * re-attaching owned channels (`resync`, delivered as `reattach` events) after\n * each reconnect. Resolves on {@link ControlClient.shutdown}, or rejects on a\n * fatal error (token revoked → `unauthorized`).\n */\n async run(): Promise<void> {\n for (;;) {\n let session = this.current;\n if (!session || session.isClosed()) {\n if (this.shutdownRequested) {\n return;\n }\n try {\n session = await this.connectAndHandshake();\n } catch (error) {\n if (error instanceof ControlError && error.kind === \"unauthorized\") {\n throw error;\n }\n await Promise.race([sleep(this.config.reconnectBackoffMs), this.shutdownSignal()]);\n if (this.shutdownRequested) {\n return;\n }\n continue;\n }\n this.current = session;\n await this.resyncAndReattach(session);\n }\n\n await Promise.race([session.waitClosed(), this.shutdownSignal()]);\n if (this.shutdownRequested) {\n return;\n }\n this.current = null;\n }\n }\n\n /** Stop the client: close the current session and unblock {@link ControlClient.run}. */\n shutdown(): void {\n this.shutdownRequested = true;\n for (const waiter of this.shutdownWaiters.splice(0)) {\n waiter();\n }\n if (this.current) {\n this.current.close();\n this.current = null;\n }\n }\n\n private shutdownSignal(): Promise<void> {\n if (this.shutdownRequested) {\n return Promise.resolve();\n }\n return new Promise((resolve) => this.shutdownWaiters.push(resolve));\n }\n\n private emit(event: ClientEvent): void {\n this.eventCallback?.(event);\n }\n\n private async connectAndHandshake(): Promise<Session> {\n const socket = await this.openSocket();\n const session = new Session(\n socket,\n this.nextId,\n this.config.replyTimeoutMs,\n (frame) => this.emit({ type: \"event\", frame }),\n );\n const result = (await session.command(null, HELLO, null, {\n app: this.config.app,\n protocol: this.config.protocol,\n })) as HelloResult | null;\n if (!result || result.subprotocol !== SUBPROTOCOL) {\n session.close();\n throw ControlError.handshake(\n `server negotiated subprotocol ${JSON.stringify(result?.subprotocol)}, expected ${JSON.stringify(SUBPROTOCOL)}`,\n );\n }\n return session;\n }\n\n private openSocket(): Promise<WebSocket> {\n return new Promise<WebSocket>((resolve, reject) => {\n const socket = new WebSocket(this.config.url, [SUBPROTOCOL], {\n headers: { Authorization: `Bearer ${this.config.token}` },\n });\n let settled = false;\n const settle = (): void => {\n settled = true;\n socket.off(\"open\", onOpen);\n socket.off(\"unexpected-response\", onUnexpected);\n };\n const onOpen = (): void => {\n settle();\n resolve(socket);\n };\n const onUnexpected = (\n request: { destroy: () => void },\n response: { statusCode?: number },\n ): void => {\n settle();\n // Free the aborted upgrade's socket without the \"closed before the\n // connection was established\" that `socket.terminate()` throws here.\n request.destroy();\n reject(ControlError.unauthorized(response.statusCode ?? 0));\n };\n const onError = (error: Error): void => {\n if (!settled) {\n settle();\n reject(ControlError.websocket(error.message));\n }\n // Post-settle errors (e.g. the destroyed handshake socket hanging up)\n // are swallowed here so a stray `error` never crashes the process.\n };\n socket.on(\"open\", onOpen);\n socket.on(\"unexpected-response\", onUnexpected);\n socket.on(\"error\", onError);\n });\n }\n\n private async resyncAndReattach(session: Session): Promise<void> {\n try {\n const value = (await session.command(null, RESYNC, null, null)) as ResyncResult | null;\n for (const snapshot of value?.channels ?? []) {\n this.emit({ type: \"reattach\", snapshot });\n }\n } catch {\n // A failed resync is non-fatal — the connection stays up.\n }\n }\n}\n","/**\n * Outbound per-call-connect mode: siphon *dials the application* at handover,\n * so the app is a WebSocket **server**. This is the documented default for\n * multi-pod controllers — the accepting socket owns exactly that one call, so\n * \"the audio lands on the wrong pod\" is structurally impossible.\n *\n * No `hello` is exchanged: siphon presents the token in the dial headers, and\n * the first frame the app receives is a pushed event (`StasisStart` for SIP).\n * Mirrors the Rust `ControlServer`.\n */\n\nimport type { AddressInfo } from \"node:net\";\n\nimport WebSocket, { WebSocketServer } from \"ws\";\n\nimport { ControlError } from \"./errors\";\nimport type { IdCounter } from \"./internal\";\nimport { SUBPROTOCOL } from \"./protocol\";\nimport type { EventFrame } from \"./protocol\";\nimport type { CommandTransport, EventSink } from \"./session\";\nimport { Session } from \"./session\";\n\n/** How a {@link ControlServer} listens for siphon's per-call dials. */\nexport interface ServerConfig {\n /** The host to bind (e.g. `0.0.0.0`). */\n host: string;\n /** The port to bind (`0` picks a free port — read it back via `localAddr`). */\n port: number;\n /** The application name (context / logging). */\n app: string;\n /** The bearer token siphon must present on the dial. */\n token: string;\n /** How long a command waits for its reply before a timeout (default 10 000 ms). */\n replyTimeoutMs?: number;\n}\n\n/** A sink the server calls for each event, carrying the {@link CommandTransport}\n * of the connection that produced it (so a facade commands back on the right one). */\nexport type ConnectionEventSink = (frame: EventFrame, transport: CommandTransport) => void;\n\n/** The protocol-agnostic per-call-connect control server. */\nexport class ControlServer {\n private readonly nextId: IdCounter = { value: 1 };\n private eventSink: ConnectionEventSink | null = null;\n private readonly closeWaiters: Array<() => void> = [];\n private readonly sockets = new Set<WebSocket>();\n private closed = false;\n\n private constructor(\n private readonly config: ServerConfig,\n private readonly wss: WebSocketServer,\n ) {\n wss.on(\"connection\", (socket, request) => this.onConnection(socket, request));\n wss.on(\"close\", () => this.markClosed());\n }\n\n /** Bind the listener (so the assigned port is known before accepting). */\n static bind(config: ServerConfig): Promise<ControlServer> {\n const token = config.token;\n return new Promise<ControlServer>((resolve, reject) => {\n const wss = new WebSocketServer({\n host: config.host,\n port: config.port,\n // Echo the subprotocol siphon offers on the dial (required — the client\n // rejects the handshake otherwise).\n handleProtocols: (protocols) => (protocols.has(SUBPROTOCOL) ? SUBPROTOCOL : false),\n // Verify the bearer token siphon presents (the app's own policy).\n verifyClient: ({ req }, done) => {\n const ok = req.headers[\"authorization\"] === `Bearer ${token}`;\n done(ok, 401, \"unauthorized\");\n },\n });\n const onError = (error: Error): void => {\n wss.off(\"listening\", onListening);\n reject(ControlError.config(`bind ${config.host}:${config.port}: ${error.message}`));\n };\n const onListening = (): void => {\n wss.off(\"error\", onError);\n resolve(new ControlServer(config, wss));\n };\n wss.once(\"listening\", onListening);\n wss.once(\"error\", onError);\n });\n }\n\n /** The actual bound address (useful when binding to port 0 in tests). */\n localAddr(): AddressInfo {\n const address = this.wss.address();\n if (typeof address === \"string\" || address === null) {\n throw ControlError.config(\"server is not bound to a TCP address\");\n }\n return address;\n }\n\n /** Register the sink for `(event, connection-commander)` pairs. Facades set this internally. */\n onConnectionEvent(sink: ConnectionEventSink): void {\n this.eventSink = sink;\n }\n\n /** Resolve once the server has been closed (`run` resolves at the same time). */\n run(): Promise<void> {\n if (this.closed) {\n return Promise.resolve();\n }\n return new Promise((resolve) => this.closeWaiters.push(resolve));\n }\n\n /** Stop accepting dials, drop live connections, and close the listener. */\n close(): Promise<void> {\n // Terminate live connections first: the underlying HTTP server's `close`\n // does not fire until every connection has ended.\n for (const socket of this.sockets) {\n socket.terminate();\n }\n this.sockets.clear();\n return new Promise((resolve) => {\n this.wss.close(() => {\n this.markClosed();\n resolve();\n });\n });\n }\n\n private markClosed(): void {\n if (this.closed) {\n return;\n }\n this.closed = true;\n for (const waiter of this.closeWaiters.splice(0)) {\n waiter();\n }\n }\n\n private onConnection(socket: WebSocket, _request: unknown): void {\n this.sockets.add(socket);\n socket.on(\"close\", () => this.sockets.delete(socket));\n // The event sink needs this connection's commander, which is the session\n // itself. `session` is assigned synchronously here, before any inbound\n // message can be delivered (those arrive on later ticks).\n let session: Session;\n const sink: EventSink = (frame) => {\n this.eventSink?.(frame, session);\n };\n session = new Session(socket, this.nextId, this.config.replyTimeoutMs ?? 10_000, sink);\n }\n}\n","/**\n * The **SIP facade** over the protocol-agnostic core.\n *\n * {@link Call} is a typed handle whose verbs (`answer`/`progress`/`reject`/\n * `terminate`/`refer`/…) are thin wrappers that send `command(\"sip\", …)` on the\n * underlying core and await the correlated reply. The method names mirror the\n * in-process siphon scripting API (`call.answer()`, `call.terminate()`,\n * `call.transfer()`, `call.setHeader()`, …), so an out-of-process controller\n * reads like an in-process script. The `StasisStart`→{@link Call} dispatch and\n * the `onCall` handler live here (they are SIP/ARI concepts) on top of the\n * core's generic event stream, so a future `smpp` / `ss7` facade is an additive\n * sibling over the same core.\n */\n\nimport type { ControlClient, ClientConfig, ClientEvent } from \"./client\";\nimport { ControlClient as ControlClientImpl } from \"./client\";\nimport { AsyncQueue } from \"./internal\";\nimport {\n MODULE_SIP,\n SET_VAR,\n GET_VAR,\n SipVerb,\n sipEventKind,\n} from \"./protocol\";\nimport type {\n ChannelSnapshot,\n EventFrame,\n PeerHangupPolicy,\n SipEventKind,\n} from \"./protocol\";\nimport type { ControlServer, ServerConfig } from \"./server\";\nimport { ControlServer as ControlServerImpl } from \"./server\";\nimport type { CommandTransport } from \"./session\";\n\n// ---------------------------------------------------------------------------\n// Call handle\n// ---------------------------------------------------------------------------\n\n/** One event delivered to a call's stream (`ChannelStateChange`,\n * `ChannelHangupRequest`, `ChannelDtmfReceived`, `TransferRequested`,\n * `TransferProgress`, `TransferCompleted`, `TransferFailed`, `ChannelBridged`,\n * `BridgeFailed`, `ChannelUnbridged`, `StasisEnd`, …).\n * Cast `payload` to\n * {@link import(\"./protocol\").ChannelDtmfPayload} /\n * {@link import(\"./protocol\").TransferRequestedPayload} /\n * {@link import(\"./protocol\").TransferOutcomePayload} /\n * {@link import(\"./protocol\").ChannelBridgedPayload} /\n * {@link import(\"./protocol\").BridgeFailedPayload} /\n * {@link import(\"./protocol\").ChannelUnbridgedPayload} by `kind`. */\nexport interface CallEvent {\n /** The parsed event kind. */\n kind: SipEventKind;\n /** The event-specific payload. */\n payload: unknown;\n /** The raw frame (for fields not surfaced above). */\n frame: EventFrame;\n}\n\nfunction callEventFromFrame(frame: EventFrame): CallEvent {\n return { kind: sipEventKind(frame.event), payload: frame.payload ?? null, frame };\n}\n\n/** Options for a UAS provisional / final response (`answer` / `progress`). */\nexport interface ResponseOptions {\n code?: number;\n reason?: string;\n body?: string;\n contentType?: string;\n}\n\nfunction responseArgs(options: ResponseOptions): Record<string, unknown> {\n const args: Record<string, unknown> = {};\n if (options.code !== undefined) {\n args.code = options.code;\n }\n if (options.reason !== undefined) {\n args.reason = options.reason;\n }\n if (options.body !== undefined) {\n args.body = options.body;\n }\n if (options.contentType !== undefined) {\n args.content_type = options.contentType;\n }\n return args;\n}\n\n/** The RFC 3891 `Replaces` triple for an attended transfer. */\nexport interface ReferReplaces {\n callId: string;\n fromTag: string;\n toTag: string;\n earlyOnly?: boolean;\n}\n\n/** Options for {@link Call.acceptRefer}. */\nexport interface AcceptReferOptions {\n target?: string;\n nextHop?: string;\n mode?: \"terminate\" | \"transparent\";\n /**\n * Media profile for the pairing the transfer creates.\n *\n * **Required when the call is anchored with a direction-bound profile** — one\n * whose offer and answer halves describe different sides, such as\n * `srtp_to_rtp` at an SRTP edge. A transfer moves the party that half was\n * written for out of the call, so inheriting the profile re-offers *that\n * party's* transport to whoever remains: SRTP toward a plain-RTP carrier,\n * which answers `m=audio 0`. The call connects and carries no audio in either\n * direction while the SIP trace looks healthy.\n *\n * Pass the profile for the pair that remains (commonly `\"rtp_passthrough\"`).\n * Omitted inherits the call's profile, which is correct only when it is\n * symmetric.\n */\n profile?: string;\n}\n\n/** Options for {@link Call.bridge}. */\nexport interface BridgeOptions {\n /**\n * What happens to the surviving leg when its bridge partner hangs up —\n * `\"hangup\"` (the default) tears it down too, `\"hold\"` keeps it up, held and\n * still owned so it can be bridged to somebody else. See\n * {@link import(\"./protocol\").PeerHangupPolicy}.\n */\n onPeerHangup?: PeerHangupPolicy;\n}\n\n/** A {@link Call.route} target carrying per-target overrides. */\nexport interface RouteTargetObject {\n /** The B-leg request URI to dial. */\n uri: string;\n /** Route egress to this next hop instead of resolving `uri`. */\n nextHop?: string;\n /** Headers injected on this attempt's B-leg INVITE. */\n headers?: Record<string, string>;\n /** Per-target ring timeout in seconds. */\n timeout?: number;\n}\n\n/**\n * One entry in a {@link Call.route} target list: a bare URI string, or a\n * {@link RouteTargetObject} with per-target overrides.\n */\nexport type RouteTarget = string | RouteTargetObject;\n\nfunction routeTargetToWire(target: RouteTarget): unknown {\n if (typeof target === \"string\") {\n return target;\n }\n const object: Record<string, unknown> = { uri: target.uri };\n if (target.nextHop !== undefined) {\n object.next_hop = target.nextHop;\n }\n if (target.headers !== undefined) {\n object.headers = target.headers;\n }\n if (target.timeout !== undefined) {\n object.timeout = target.timeout;\n }\n return object;\n}\n\nfunction stringValue(result: unknown): string | null {\n if (typeof result === \"object\" && result !== null) {\n const value = (result as { value?: unknown }).value;\n if (typeof value === \"string\") {\n return value;\n }\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// play() / dtmf() / streamStart() args\n// ---------------------------------------------------------------------------\n\n/**\n * The audio source for {@link Call.play}: exactly one of a server-side file\n * path, an rtpengine media-DB id, or an inline blob. A blob is base64-encoded on\n * the wire (the control rail is JSON text).\n */\nexport type PlaySource =\n | { file: string }\n | { dbId: number }\n | { blob: Uint8Array };\n\n/** Optional shaping for {@link Call.play}. */\nexport interface PlayOptions {\n /** Repeat the prompt this many times (0/undefined → play once). */\n repeat?: number;\n /** Start playback at this offset into the source, in milliseconds. */\n startMs?: number;\n /** Cap playback to this duration, in milliseconds. */\n durationMs?: number;\n /** Scope the prompt to one peer of an MPTY bridge (its To-tag). */\n toTag?: string;\n}\n\n/** Optional shaping for {@link Call.dtmf}. */\nexport interface DtmfOptions {\n /** Per-digit tone duration, in milliseconds. */\n durationMs?: number;\n /** Tone volume in dBm0 (negative). */\n volumeDbm0?: number;\n /** Inter-digit pause, in milliseconds. */\n pauseMs?: number;\n /** Scope the tones to one peer of an MPTY bridge (its To-tag). */\n toTag?: string;\n}\n\n/** Options for {@link Call.streamStart} (the WebSocket audio tee). */\nexport interface StreamOptions {\n /** Which leg(s) to tee — `\"both\"` (default), `\"caller\"`, or `\"callee\"`. */\n direction?: \"both\" | \"caller\" | \"callee\";\n /** `1` = mixed mono, `2` = caller/callee stereo (only with `\"both\"`). */\n channels?: 1 | 2;\n}\n\nfunction playArgs(source: PlaySource, options?: PlayOptions): Record<string, unknown> {\n const args: Record<string, unknown> = {};\n if (\"file\" in source) {\n args.file = source.file;\n } else if (\"dbId\" in source) {\n args.db_id = source.dbId;\n } else {\n args.blob = Buffer.from(source.blob).toString(\"base64\");\n }\n if (options?.repeat !== undefined) {\n args.repeat = options.repeat;\n }\n if (options?.startMs !== undefined) {\n args.start_ms = options.startMs;\n }\n if (options?.durationMs !== undefined) {\n args.duration_ms = options.durationMs;\n }\n if (options?.toTag !== undefined) {\n args.to_tag = options.toTag;\n }\n return args;\n}\n\nfunction dtmfArgs(digits: string, options?: DtmfOptions): Record<string, unknown> {\n const args: Record<string, unknown> = { digits };\n if (options?.durationMs !== undefined) {\n args.duration_ms = options.durationMs;\n }\n if (options?.volumeDbm0 !== undefined) {\n args.volume_dbm0 = options.volumeDbm0;\n }\n if (options?.pauseMs !== undefined) {\n args.pause_ms = options.pauseMs;\n }\n if (options?.toTag !== undefined) {\n args.to_tag = options.toTag;\n }\n return args;\n}\n\n/**\n * A handed-over SIP call. Cheap to hold (shares one connection + event stream).\n * Verb names mirror the in-process `call.*` scripting API.\n */\nexport class Call {\n constructor(\n private readonly transport: CommandTransport,\n /** The leg-scoped channel id — the address for every verb on this call. */\n readonly channelId: string,\n /** The internal `CallActor` id (the grouping key across legs), if known. */\n readonly callId: string | null,\n /** The per-leg SIP `Call-ID` — byte-identical to the CDR / HEP join key. */\n readonly sipCallId: string | null,\n /** The application this call was handed to. */\n readonly app: string | null,\n /** The `StasisStart` payload (full SIP context), or the `resync` snapshot. */\n readonly payload: unknown,\n /** True when this call came from a `resync` re-attach after a reconnect. */\n readonly reattached: boolean,\n private readonly eventQueue: AsyncQueue<CallEvent>,\n ) {}\n\n private target(): { channel: string } {\n return { channel: this.channelId };\n }\n\n private sip(verb: string, args: unknown): Promise<unknown> {\n return this.transport.command(MODULE_SIP, verb, this.target(), args);\n }\n\n private substrate(verb: string, args: unknown): Promise<unknown> {\n return this.transport.command(null, verb, this.target(), args);\n }\n\n // --- SIP verbs (mirror the in-process scripting API) -------------------\n\n /** Send a UAS 2xx to the parked A-leg (default `200 OK`). */\n async answer(options?: ResponseOptions): Promise<void> {\n await this.sip(SipVerb.Answer, options ? responseArgs(options) : {});\n }\n\n /**\n * Send `180 Ringing`: alerting only, no early media.\n *\n * RFC 3261 §13.2.1 makes the 180 the \"callee is being alerted\" signal, and\n * RFC 3960 §3.1 puts early media on a response that carries SDP — two\n * different acts, so two verbs. Ring for as long as your own policy says,\n * then {@link Call.answer}; open an early-media path with\n * {@link Call.progress}.\n */\n async ring(reason?: string): Promise<void> {\n await this.sip(SipVerb.Ring, reason !== undefined ? { reason } : {});\n }\n\n /**\n * Send a UAS 1xx, optionally opening an early-media path with SDP (default\n * `183 Session Progress`). For plain alerting use {@link Call.ring}.\n */\n async progress(options?: ResponseOptions): Promise<void> {\n await this.sip(SipVerb.Progress, options ? responseArgs(options) : {});\n }\n\n /** Send a final non-2xx and tear the call down. */\n async reject(code: number, reason?: string): Promise<void> {\n const args: Record<string, unknown> = { code };\n if (reason !== undefined) {\n args.reason = reason;\n }\n await this.sip(SipVerb.Reject, args);\n }\n\n /**\n * Tear the call down: BYE an answered call (full teardown funnel), or reject\n * an unanswered one. Mirrors the in-process `call.terminate()`.\n */\n async terminate(reason?: string): Promise<void> {\n await this.sip(SipVerb.Hangup, reason !== undefined ? { reason } : {});\n }\n\n /** Alias for {@link Call.terminate}. */\n async hangup(reason?: string): Promise<void> {\n await this.terminate(reason);\n }\n\n /**\n * Send an in-dialog REFER on the A-leg (blind transfer).\n *\n * Resolves as soon as siphon has sent the REFER — that is *sent*, not\n * *transferred*. RFC 3515 §2.4.4 delivers the outcome afterwards on the\n * implicit subscription, so read it off {@link Call.events}: zero or more\n * `TransferProgress`, then exactly one `TransferCompleted` /\n * `TransferFailed`, each carrying a\n * {@link import(\"./protocol\").TransferOutcomePayload}. Use\n * {@link import(\"./protocol\").isTransferFinal} to know when to stop waiting.\n */\n async refer(to: string): Promise<void> {\n await this.sip(SipVerb.Refer, { to });\n }\n\n /** Blind-transfer alias for {@link Call.refer}. */\n async transfer(to: string): Promise<void> {\n await this.refer(to);\n }\n\n /** Attended transfer — REFER with a `Replaces` triple (RFC 3891). */\n async referReplaces(to: string, replaces: ReferReplaces): Promise<void> {\n await this.sip(SipVerb.Refer, {\n to,\n replaces: {\n call_id: replaces.callId,\n from_tag: replaces.fromTag,\n to_tag: replaces.toTag,\n early_only: replaces.earlyOnly ?? false,\n },\n });\n }\n\n /**\n * Un-park this controlled call and dial the B-leg via siphon's LCR\n * sequential-failover engine, returning control to siphon.\n *\n * `targets` is a non-empty list of carriers tried cheapest-first: each entry\n * is a bare URI string or a {@link RouteTargetObject}\n * (`{uri, nextHop?, headers?, timeout?}`). `strategy` defaults to\n * `\"sequential\"` (v1 supports only sequential/single — anything else rejects\n * with `code === \"unsupported_verb\"`). `headers` is applied to every\n * attempt's B-leg INVITE.\n *\n * Resolves to the reply `result` (`{channel, state: \"routing\", targets}`). An\n * empty / invalid `targets` list rejects with `code === \"bad_request\"`; a call\n * that is already gone rejects with `code === \"not_found\"`.\n */\n async route(\n targets: RouteTarget[],\n strategy = \"sequential\",\n headers?: Record<string, string>,\n ): Promise<unknown> {\n const args: Record<string, unknown> = {\n targets: targets.map(routeTargetToWire),\n strategy,\n };\n if (headers !== undefined) {\n args.headers = headers;\n }\n return this.sip(SipVerb.Route, args);\n }\n\n /**\n * Accept a *pending inbound* REFER (surfaced as a `TransferRequested` event)\n * and run the transfer. `target` overrides the Refer-To URI, `nextHop` steers\n * egress, and `mode` (`\"terminate\"` / `\"transparent\"`) overrides\n * `b2bua.default_refer_mode`. No pending REFER (already decided, timed out, or\n * the call is gone) rejects with `code === \"not_found\"`.\n *\n * `profile` names the media profile for the pairing the transfer creates —\n * see {@link AcceptReferOptions.profile}, which is required at an SRTP edge.\n */\n async acceptRefer(options?: AcceptReferOptions): Promise<void> {\n const args: Record<string, unknown> = {};\n if (options?.target !== undefined) {\n args.target = options.target;\n }\n if (options?.nextHop !== undefined) {\n args.next_hop = options.nextHop;\n }\n if (options?.mode !== undefined) {\n args.mode = options.mode;\n }\n if (options?.profile !== undefined) {\n args.profile = options.profile;\n }\n await this.sip(SipVerb.AcceptRefer, args);\n }\n\n /**\n * Reject a *pending inbound* REFER with a final non-2xx (default\n * `603 Decline`). No pending REFER rejects with `code === \"not_found\"`.\n */\n async rejectRefer(code: number, reason?: string): Promise<void> {\n const args: Record<string, unknown> = { code };\n if (reason !== undefined) {\n args.reason = reason;\n }\n await this.sip(SipVerb.RejectRefer, args);\n }\n\n /**\n * Join this call to another leg the app owns, so the two parties hear each\n * other.\n *\n * **This call is the anchor.** It keeps its media session — its ports and\n * everything attached to them; the `withChannel` leg's own media session is\n * deleted and it becomes the second party on this one's. So bridge *into* the\n * leg whose media you want to keep (the one being recorded, teed, or carrying\n * the prompt).\n *\n * Both legs must already be answered. `options.onPeerHangup` says what happens\n * to the survivor when its partner hangs up (see\n * {@link import(\"./protocol\").PeerHangupPolicy}); omitted means `\"hangup\"`.\n *\n * Resolves as soon as the media has been re-pointed and the first re-INVITE is\n * on the wire — that is *offered*, not *bridged*. A bridge is two RFC 3261 §14\n * re-INVITEs across two dialogs, so the outcome arrives on {@link Call.events}\n * instead: exactly one `ChannelBridged`\n * ({@link import(\"./protocol\").ChannelBridgedPayload}) / `BridgeFailed`\n * ({@link import(\"./protocol\").BridgeFailedPayload}), on **both** channels.\n * {@link import(\"./protocol\").isBridgeFinal} says when to stop waiting.\n *\n * Resolves to the reply `result` (`{channel, with, call_id, peer_call_id,\n * anchored, on_peer_hangup, state: \"bridging\"}`). Rejects with a `code` a\n * caller can act on: `\"not_found\"` (no such leg), `\"invalid_state\"` (a leg has\n * not answered, is already bridged, has a re-INVITE outstanding, or carries no\n * media description), `\"bad_request\"` (the same leg named twice, or a bad\n * `onPeerHangup`), `\"forbidden\"` (the other channel belongs to another app),\n * `\"unsupported_verb\"` (the media backend cannot express it).\n */\n async bridge(withChannel: string, options?: BridgeOptions): Promise<unknown> {\n const args: Record<string, unknown> = { with: withChannel };\n if (options?.onPeerHangup !== undefined) {\n args.on_peer_hangup = options.onPeerHangup;\n }\n return this.sip(SipVerb.Bridge, args);\n }\n\n /**\n * Break this call's bridge.\n *\n * Both legs stay answered, owned and held — re-offered `a=sendonly`\n * (RFC 3264 §8.4, which RFC 6337 §3.1 prefers to `c=0.0.0.0`). Neither is hung\n * up: that would be indistinguishable from two hangups and would take away the\n * calls the app still owns. A later {@link Call.bridge} re-offers `sendrecv`.\n *\n * `reason` is free text carried on the `ChannelUnbridged`\n * ({@link import(\"./protocol\").ChannelUnbridgedPayload}) event both channels\n * receive; omitted means `\"unbridged\"`. Resolves to the reply `result`\n * (`{channel, with, reason, state: \"unbridged\"}`), where `with` is the channel\n * id of the leg that was on the other side. A call that is not bridged rejects\n * with `code === \"invalid_state\"`.\n */\n async unbridge(reason?: string): Promise<unknown> {\n return this.sip(SipVerb.Unbridge, reason !== undefined ? { reason } : {});\n }\n\n /** Set a header on the stored A-leg INVITE. */\n async setHeader(name: string, value: string): Promise<void> {\n await this.sip(SipVerb.SetHeader, { name, value });\n }\n\n /** Read a header from the stored A-leg INVITE (`null` when absent). */\n async getHeader(name: string): Promise<string | null> {\n const result = await this.sip(SipVerb.GetHeader, { name });\n return stringValue(result);\n }\n\n /** Remove a header from the stored A-leg INVITE. */\n async removeHeader(name: string): Promise<void> {\n await this.sip(SipVerb.RemoveHeader, { name });\n }\n\n // --- per-call variables (substrate verbs, no module) -------------------\n\n /** Set a per-call variable (survives a reconnect via `resync`). */\n async setVar(key: string, value: string): Promise<void> {\n await this.substrate(SET_VAR, { key, value });\n }\n\n /** Read a per-call variable (`null` when unset). */\n async getVar(key: string): Promise<string | null> {\n const result = await this.substrate(GET_VAR, { key });\n return stringValue(result);\n }\n\n // --- media -------------------------------------------------------------\n\n /**\n * Play an announcement on the A-leg media (fire-and-forget). `source` is a\n * {@link PlaySource} (a blob is base64-encoded on the wire); `options` shapes\n * playback. A call with no anchored media session rejects with\n * `code === \"not_found\"`.\n */\n async play(source: PlaySource, options?: PlayOptions): Promise<void> {\n await this.sip(SipVerb.Play, playArgs(source, options));\n }\n\n /** Convenience for {@link Call.play} of a server-side file with default options. */\n async playFile(file: string): Promise<void> {\n await this.play({ file });\n }\n\n /** Stop the announcement currently playing on the A-leg media. */\n async stop(): Promise<void> {\n await this.sip(SipVerb.Stop, {});\n }\n\n /**\n * Inject DTMF digits toward the A-leg (fire-and-forget). `options` carries the\n * optional `durationMs` / `volumeDbm0` / `pauseMs` / `toTag` shaping.\n */\n async dtmf(digits: string, options?: DtmfOptions): Promise<void> {\n await this.sip(SipVerb.Dtmf, dtmfArgs(digits, options));\n }\n\n /** Hold the A-leg media via silence. */\n async hold(): Promise<void> {\n await this.sip(SipVerb.Hold, {});\n }\n\n /** Resume the A-leg media after a {@link Call.hold}. */\n async unhold(): Promise<void> {\n await this.sip(SipVerb.Unhold, {});\n }\n\n /**\n * Attach a WebSocket audio tee — stream a copy of the call's decoded audio to\n * `wsUri` while the call keeps relaying. siphon-rtp backend only: rtpengine /\n * rtpproxy reject with `code === \"unsupported_verb\"` (`error.isUnsupportedVerb()`).\n */\n async streamStart(wsUri: string, options?: StreamOptions): Promise<void> {\n const args: Record<string, unknown> = { ws_uri: wsUri };\n if (options?.direction !== undefined) {\n args.direction = options.direction;\n }\n if (options?.channels !== undefined) {\n args.channels = options.channels;\n }\n await this.sip(SipVerb.StreamStart, args);\n }\n\n /** Detach the WebSocket audio tee (idempotent on siphon-rtp). */\n async streamStop(): Promise<void> {\n await this.sip(SipVerb.StreamStop, {});\n }\n\n // --- escape hatch + events --------------------------------------------\n\n /** Send an arbitrary SIP-adapter verb + args and return the raw result. */\n async command(verb: string, args?: unknown): Promise<unknown> {\n return this.sip(verb, args ?? {});\n }\n\n /**\n * Await the next event for this call (`ChannelStateChange`,\n * `ChannelHangupRequest`, `ChannelBridged`, `BridgeFailed`,\n * `ChannelUnbridged`, `StasisEnd`). `null` once the stream closes.\n */\n nextEvent(): Promise<CallEvent | null> {\n return this.eventQueue.next();\n }\n\n /** Async-iterate this call's events until the stream closes. */\n events(): AsyncIterableIterator<CallEvent> {\n return this.eventQueue[Symbol.asyncIterator]();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Call dispatch (handler or pull stream) + per-channel event routing\n// ---------------------------------------------------------------------------\n\n/** A per-call handler. Both sync (`void`) and async (`Promise<void>`) supported. */\nexport type CallHandler = (call: Call) => void | Promise<void>;\n\n/** A pull-style stream of handed-over calls (alternative to a handler). */\nexport class CallStream {\n constructor(private readonly queue: AsyncQueue<Call>) {}\n\n /** Await the next handed-over call. `null` once the client/server shuts down. */\n next(): Promise<Call | null> {\n return this.queue.next();\n }\n\n [Symbol.asyncIterator](): AsyncIterableIterator<Call> {\n return this.queue[Symbol.asyncIterator]();\n }\n}\n\n/**\n * The SIP facade's event router: builds `Call`s from `StasisStart`/reattach,\n * routes channel-scoped events to the owning call, and dispatches new calls to a\n * handler or pull stream. Mirrors the Rust `SipFacade`.\n */\nclass SipFacade {\n private handler: CallHandler | null = null;\n private callQueue: AsyncQueue<Call> | null = null;\n private readonly channels = new Map<string, AsyncQueue<CallEvent>>();\n\n setHandler(handler: CallHandler): void {\n this.handler = handler;\n }\n\n setStream(): CallStream {\n const queue = new AsyncQueue<Call>();\n this.callQueue = queue;\n return new CallStream(queue);\n }\n\n handleClientEvent(event: ClientEvent, transport: CommandTransport): void {\n if (event.type === \"event\") {\n this.handleEvent(event.frame, transport);\n } else {\n this.reattach(event.snapshot, transport);\n }\n }\n\n handleEvent(frame: EventFrame, transport: CommandTransport): void {\n const kind = sipEventKind(frame.event);\n if (kind === \"StasisStart\") {\n if (!frame.channel) {\n return; // StasisStart without a channel — drop.\n }\n const queue = new AsyncQueue<CallEvent>();\n this.channels.set(frame.channel, queue);\n const call = new Call(\n transport,\n frame.channel,\n frame.call_id ?? null,\n frame.sip_call_id ?? null,\n frame.app ?? null,\n frame.payload ?? null,\n false,\n queue,\n );\n this.dispatch(call);\n } else if (kind === \"StasisEnd\") {\n if (frame.channel) {\n this.route(frame.channel, callEventFromFrame(frame));\n const queue = this.channels.get(frame.channel);\n queue?.close();\n this.channels.delete(frame.channel);\n }\n } else if (frame.channel) {\n this.route(frame.channel, callEventFromFrame(frame));\n }\n }\n\n private reattach(snapshot: ChannelSnapshot, transport: CommandTransport): void {\n const queue = new AsyncQueue<CallEvent>();\n this.channels.set(snapshot.channel, queue);\n const call = new Call(\n transport,\n snapshot.channel,\n snapshot.call_id,\n snapshot.sip_call_id,\n null,\n snapshot,\n true,\n queue,\n );\n this.dispatch(call);\n }\n\n private route(channel: string, event: CallEvent): void {\n this.channels.get(channel)?.push(event);\n }\n\n private dispatch(call: Call): void {\n if (this.handler) {\n const handler = this.handler;\n void Promise.resolve()\n .then(() => handler(call))\n .catch((error: unknown) => {\n // A handler error must never take down the router.\n void error;\n });\n } else if (this.callQueue) {\n this.callQueue.push(call);\n }\n // No handler / stream → the call is dropped (nothing owns it).\n }\n}\n\n// ---------------------------------------------------------------------------\n// Inbound-persistent SIP facade\n// ---------------------------------------------------------------------------\n\n/**\n * The SIP facade over an inbound-persistent {@link ControlClient}.\n *\n * ```ts\n * const client = await SipClient.connect({\n * url: \"ws://siphon:9090/control/ws\",\n * app: \"ivr-app\",\n * token: \"s3cr3t\",\n * });\n * await client.onCall(async (call) => {\n * await call.answer();\n * await call.transfer(\"sip:agent@pbx\");\n * });\n * ```\n */\nexport class SipClient {\n private readonly facade = new SipFacade();\n\n private constructor(private readonly client: ControlClient) {\n const commander = client.commander();\n client.onEvent((event) => this.facade.handleClientEvent(event, commander));\n }\n\n /** Connect + `hello`, then install the SIP event router. */\n static async connect(config: ClientConfig): Promise<SipClient> {\n const client = await ControlClientImpl.connect(config);\n return new SipClient(client);\n }\n\n /** Wrap an already-connected generic client with the SIP facade. */\n static wrap(client: ControlClient): SipClient {\n return new SipClient(client);\n }\n\n /** The underlying generic client (for raw `command` on any module). */\n get controlClient(): ControlClient {\n return this.client;\n }\n\n /** Register a call handler (does not block). */\n setCallHandler(handler: CallHandler): void {\n this.facade.setHandler(handler);\n }\n\n /**\n * Register a call handler **and drive the client to completion** (the\n * supervised reconnect + resync loop).\n */\n onCall(handler: CallHandler): Promise<void> {\n this.setCallHandler(handler);\n return this.client.run();\n }\n\n /** A pull-style stream of handed-over calls (alternative to a handler). */\n calls(): CallStream {\n return this.facade.setStream();\n }\n\n /** Drive the supervised connection loop (reconnect + resync). */\n run(): Promise<void> {\n return this.client.run();\n }\n\n /** Fetch the registered adapters' schema (`describe`). */\n describe(): Promise<unknown> {\n return this.client.describe();\n }\n\n /** Send a raw command on any module (the generic escape hatch). */\n command(\n module: string | null,\n verb: string,\n target: unknown,\n args: unknown,\n ): Promise<unknown> {\n return this.client.command(module, verb, target, args);\n }\n\n /** Stop the client. */\n shutdown(): void {\n this.client.shutdown();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Per-call-connect SIP facade\n// ---------------------------------------------------------------------------\n\n/** The SIP facade over a per-call-connect {@link ControlServer}. */\nexport class SipServer {\n private readonly facade = new SipFacade();\n\n private constructor(private readonly server: ControlServer) {\n server.onConnectionEvent((frame, transport) => this.facade.handleEvent(frame, transport));\n }\n\n /** Bind the listener and install the SIP event router. */\n static async bind(config: ServerConfig): Promise<SipServer> {\n const server = await ControlServerImpl.bind(config);\n return new SipServer(server);\n }\n\n /** The actual bound address (useful when binding to port 0 in tests). */\n localAddr(): import(\"node:net\").AddressInfo {\n return this.server.localAddr();\n }\n\n /** Register a call handler (does not block). */\n setCallHandler(handler: CallHandler): void {\n this.facade.setHandler(handler);\n }\n\n /** A pull-style stream of dialed-in calls (alternative to a handler). */\n calls(): CallStream {\n return this.facade.setStream();\n }\n\n /** Register a call handler **and run the accept loop** to completion. */\n onCall(handler: CallHandler): Promise<void> {\n this.setCallHandler(handler);\n return this.server.run();\n }\n\n /** Accept siphon's per-call dials until the server is closed. */\n run(): Promise<void> {\n return this.server.run();\n }\n\n /** Stop accepting dials and close the listener. */\n close(): Promise<void> {\n return this.server.close();\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/protocol.ts","../src/internal.ts","../src/session.ts","../src/client.ts","../src/server.ts","../src/sip.ts"],"names":["WebSocket","WebSocketServer"],"mappings":";;;;;;;;;AAwCO,IAAM,YAAA,GAAN,MAAM,aAAA,SAAqB,KAAA,CAAM;AAAA;AAAA,EAE7B,IAAA;AAAA;AAAA,EAEA,IAAA;AAAA;AAAA,EAEA,MAAA;AAAA,EAET,WAAA,CACE,IAAA,EACA,OAAA,EACA,OAAA,EACA;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,cAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,O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e,OAAA,EAA4B;AACzC,IAAA,IAAA,CAAK,MAAA,CAAO,WAAW,OAAO,CAAA;AAAA,EAChC;AAAA;AAAA,EAGA,KAAA,GAAoB;AAClB,IAAA,OAAO,IAAA,CAAK,OAAO,SAAA,EAAU;AAAA,EAC/B;AAAA;AAAA,EAGA,OAAO,OAAA,EAAqC;AAC1C,IAAA,IAAA,CAAK,eAAe,OAAO,CAAA;AAC3B,IAAA,OAAO,IAAA,CAAK,OAAO,GAAA,EAAI;AAAA,EACzB;AAAA;AAAA,EAGA,GAAA,GAAqB;AACnB,IAAA,OAAO,IAAA,CAAK,OAAO,GAAA,EAAI;AAAA,EACzB;AAAA;AAAA,EAGA,KAAA,GAAuB;AACrB,IAAA,OAAO,IAAA,CAAK,OAAO,KAAA,EAAM;AAAA,EAC3B;AACF","file":"index.cjs","sourcesContent":["/**\n * The client error type for the SIPhon control plane.\n *\n * The load-bearing case is a server `status:\"error\"` reply, which becomes a\n * {@link ControlError} carrying the stable {@link ControlErrorCode} in `.code`\n * so callers can branch on the cause (e.g. treat `unsupported_verb` as \"the\n * server doesn't do media yet\" rather than a hard failure). Mirrors the Rust\n * `ControlError` enum and the Python `ControlError` exception.\n */\n\n/** Stable machine-readable error codes returned in a reply's `error.code`. */\nexport type ControlErrorCode =\n | \"unauthorized\"\n | \"forbidden\"\n | \"not_found\"\n | \"bad_request\"\n | \"conflict\"\n | \"invalid_state\"\n | \"rate_limited\"\n | \"originate_denied\"\n | \"unsupported_verb\"\n | \"unsupported_version\"\n | \"protocol_error\"\n | \"unavailable\";\n\n/**\n * How a {@link ControlError} arose. `command` is the wire-level rejection (it\n * carries a {@link ControlErrorCode}); the rest are transport / local failures\n * that never had a wire code.\n */\nexport type ControlErrorKind =\n | \"command\"\n | \"unauthorized\"\n | \"handshake\"\n | \"closed\"\n | \"timeout\"\n | \"websocket\"\n | \"config\";\n\n/** Everything that can go wrong driving the control plane. */\nexport class ControlError extends Error {\n /** The classification of this error. */\n readonly kind: ControlErrorKind;\n /** The stable wire code, present only for a `command` rejection. */\n readonly code?: ControlErrorCode;\n /** The HTTP status of a rejected upgrade, present only for `unauthorized`. */\n readonly status?: number;\n\n constructor(\n kind: ControlErrorKind,\n message: string,\n options?: { code?: ControlErrorCode; status?: number },\n ) {\n super(message);\n this.name = \"ControlError\";\n this.kind = kind;\n this.code = options?.code;\n this.status = options?.status;\n // Restore the prototype chain across the transpiled `extends Error`.\n Object.setPrototypeOf(this, ControlError.prototype);\n }\n\n /**\n * True when this is a server-side `unsupported_verb` rejection — the state a\n * media verb (`playFile`/`dtmf`/…) lands in until the server implements it.\n */\n isUnsupportedVerb(): boolean {\n return this.kind === \"command\" && this.code === \"unsupported_verb\";\n }\n\n /** A server `status:\"error\"` reply. */\n static command(code: ControlErrorCode, message: string): ControlError {\n return new ControlError(\"command\", `control command rejected (${code}): ${message}`, {\n code,\n });\n }\n\n /** The WebSocket upgrade was rejected before it opened (bad/missing token). */\n static unauthorized(status: number): ControlError {\n return new ControlError(\n \"unauthorized\",\n `unauthorized: the control token was rejected (HTTP ${status})`,\n { status },\n );\n }\n\n /** The `hello` handshake (or subprotocol negotiation) failed. */\n static handshake(detail: string): ControlError {\n return new ControlError(\"handshake\", `handshake failed: ${detail}`);\n }\n\n /** The connection is closed (or was never established). */\n static closed(): ControlError {\n return new ControlError(\"closed\", \"control connection is closed\");\n }\n\n /** A command was sent but no reply arrived within the configured window. */\n static timeout(timeoutMs: number): ControlError {\n return new ControlError(\"timeout\", `timed out awaiting a reply after ${timeoutMs}ms`);\n }\n\n /** A transport-level WebSocket error. */\n static websocket(detail: string): ControlError {\n return new ControlError(\"websocket\", `websocket error: ${detail}`);\n }\n\n /** A configuration value was invalid (bad URL, bad listen address, …). */\n static config(detail: string): ControlError {\n return new ControlError(\"config\", `configuration error: ${detail}`);\n }\n}\n","/**\n * Wire protocol for the SIPhon external control plane (`siphon-control.v1`).\n *\n * This module is the TypeScript mirror of the Rust `siphon-control-proto` crate\n * and the server's inline `src/control/protocol.rs`. The frame shapes here are\n * **byte-identical** to what the server emits and parses:\n *\n * - **command** (client → siphon): `{id, type:\"command\", module?, verb, target, args}`\n * - **reply** (siphon → client, `id` echoed): `{id, type:\"reply\", status, result|error}`\n * - **event** (siphon → client, un-id'd, pushed): `{type:\"event\", event, channel?, app?, call_id?, sip_call_id?, payload?}`\n *\n * `module` routes a command to the registered adapter (`sip`|`smpp`|`ss7`);\n * substrate verbs (`hello`, `resync`, `describe`, `set_var`, `get_var`) omit it.\n */\n\n/** The WebSocket subprotocol token this rail speaks. */\nexport const SUBPROTOCOL = \"siphon-control.v1\";\n\n/** The protocol version this build implements. */\nexport const PROTOCOL_VERSION = 1;\n\n/** Adapter routing key for the built-in SIP adapter. */\nexport const MODULE_SIP = \"sip\";\n/** Adapter routing key for an SMPP adapter (registered by a host binary). */\nexport const MODULE_SMPP = \"smpp\";\n/** Adapter routing key for an SS7 adapter (registered by a host binary). */\nexport const MODULE_SS7 = \"ss7\";\n\n/** The mandatory first-frame handshake verb. */\nexport const HELLO = \"hello\";\n/** Substrate verb: re-enumerate the channels this connection owns. */\nexport const RESYNC = \"resync\";\n/** Substrate verb: fetch the registered adapters' schema. */\nexport const DESCRIBE = \"describe\";\n/** Substrate verb: set a per-channel variable. */\nexport const SET_VAR = \"set_var\";\n/** Substrate verb: read a per-channel variable. */\nexport const GET_VAR = \"get_var\";\n\n/** The `type` discriminator on every frame. */\nexport type FrameType = \"command\" | \"reply\" | \"event\";\n\n/** The status of a reply. */\nexport type ReplyStatus = \"ok\" | \"error\";\n\nimport type { ControlErrorCode } from \"./errors\";\n\n/** The error body of a failed reply. */\nexport interface ReplyError {\n code: ControlErrorCode;\n message: string;\n}\n\n/** A reply frame (siphon → client, `id` echoed). */\nexport interface ReplyFrame {\n id: string;\n type: \"reply\";\n status: ReplyStatus;\n /** Present on success. */\n result?: unknown;\n /** Present on failure. */\n error?: ReplyError;\n}\n\n/**\n * A pushed event frame (siphon → client, un-id'd).\n *\n * Carries the stable id triple `{channel, call_id, sip_call_id}` so a controller\n * joins CDR + HEP with no mapping table: `sip_call_id` is byte-identical to the\n * CDR `call_id` and the HEP correlation chunk.\n */\nexport interface EventFrame {\n type: \"event\";\n /** Event name (e.g. `\"StasisStart\"`, `\"StasisEnd\"`). */\n event: string;\n /** The channel this event concerns (leg-scoped id), when applicable. */\n channel?: string;\n /** The application the channel was handed to. */\n app?: string;\n /** The internal call UUID (`CallActor.id`) — the grouping key across legs. */\n call_id?: string;\n /** The per-leg SIP Call-ID — the CDR / HEP join key. */\n sip_call_id?: string;\n /** Event-specific payload. */\n payload?: unknown;\n}\n\n/** Arguments of the `hello` handshake command. */\nexport interface HelloArgs {\n app: string;\n protocol?: number;\n}\n\n/** The `result` of a successful `hello` reply. */\nexport interface HelloResult {\n app: string;\n protocol: number;\n subprotocol: string;\n}\n\n/** One channel in a `resync` reply — the id triple plus its state + vars. */\nexport interface ChannelSnapshot {\n channel: string;\n call_id: string;\n sip_call_id: string;\n state: string;\n vars: Record<string, string>;\n}\n\n/** The `result` of a successful `resync` reply. */\nexport interface ResyncResult {\n channels: ChannelSnapshot[];\n}\n\n/**\n * Serialize a command frame to the exact JSON bytes the server parses.\n *\n * Field order follows the server's struct declaration order — `id`, `type`,\n * `module` (omitted when absent), `verb`, `target`, `args` — so the bytes are\n * identical to the Rust `CommandFrame` serialization. `target`/`args` are always\n * emitted (defaulting to JSON `null`); `module` is dropped when null/undefined.\n */\nexport function encodeCommand(\n id: string,\n module: string | null | undefined,\n verb: string,\n target: unknown,\n args: unknown,\n): string {\n const frame: Record<string, unknown> = { id, type: \"command\" };\n if (module != null) {\n frame.module = module;\n }\n frame.verb = verb;\n frame.target = target ?? null;\n frame.args = args ?? null;\n return JSON.stringify(frame);\n}\n\n/** Parse an inbound text frame into a {@link ReplyFrame} or {@link EventFrame}. */\nexport function parseInboundFrame(text: string): ReplyFrame | EventFrame | null {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n return null;\n }\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n const frameType = (value as { type?: unknown }).type;\n if (frameType === \"reply\") {\n return value as ReplyFrame;\n }\n if (frameType === \"event\") {\n return value as EventFrame;\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// SIP adapter (`module = \"sip\"`) verb + event helper names.\n// ---------------------------------------------------------------------------\n\n/**\n * The verbs the built-in SIP adapter accepts (`module = \"sip\"`).\n *\n * These are the exact wire tokens. The media verbs\n * (`play`/`stop`/`dtmf`/`hold`/`unhold`/`stream_start`/`stream_stop`) dispatch\n * against the configured media backend; the WebSocket-tee pair is\n * siphon-rtp-only, so a non-siphon-rtp backend answers them `unsupported_verb`.\n */\nexport const SipVerb = {\n Answer: \"answer\",\n /**\n * `180 Ringing` — alerting only, no early media (RFC 3261 §13.2.1). A body is\n * refused: SDP on an 18x is early media (RFC 3960 §3.1), which is\n * {@link SipVerb.Progress}'s job.\n */\n Ring: \"ring\",\n Progress: \"progress\",\n Reject: \"reject\",\n Hangup: \"hangup\",\n Refer: \"refer\",\n Route: \"route\",\n SetHeader: \"set_header\",\n GetHeader: \"get_header\",\n RemoveHeader: \"remove_header\",\n AcceptRefer: \"accept_refer\",\n RejectRefer: \"reject_refer\",\n Bridge: \"bridge\",\n Unbridge: \"unbridge\",\n ReplacePeer: \"replace_peer\",\n Play: \"play\",\n Stop: \"stop\",\n Dtmf: \"dtmf\",\n Hold: \"hold\",\n Unhold: \"unhold\",\n StreamStart: \"stream_start\",\n StreamStop: \"stream_stop\",\n} as const;\n\n/** A value of {@link SipVerb}. */\nexport type SipVerbToken = (typeof SipVerb)[keyof typeof SipVerb];\n\n/** The well-known SIP-adapter event names (the ARI *Stasis* model). */\nexport type SipEventKind =\n | \"StasisStart\"\n | \"StasisEnd\"\n | \"ChannelStateChange\"\n | \"ChannelHangupRequest\"\n | \"ChannelDtmfReceived\"\n | \"PlayStarted\"\n | \"TransferRequested\"\n | \"TransferProgress\"\n | \"TransferCompleted\"\n | \"TransferFailed\"\n | \"ChannelBridged\"\n | \"BridgeFailed\"\n | \"ChannelUnbridged\"\n | \"PeerReplaced\"\n | \"ReplaceFailed\"\n | \"PlayFinished\"\n | \"WsTeeStarted\"\n | \"WsTeeEnded\"\n | \"WsBridgeStarted\"\n | \"WsBridgeEnded\"\n | (string & {});\n\n/** Parse a wire event name; unknown names pass through verbatim (forward-compatible). */\nexport function sipEventKind(name: string): SipEventKind {\n return name as SipEventKind;\n}\n\n/**\n * The `payload` of a `ChannelDtmfReceived` event — an in-band DTMF digit the\n * media engine detected on a controlled call's leg. Cast a\n * {@link import(\"./sip\").CallEvent}'s `payload` to this when\n * `kind === \"ChannelDtmfReceived\"`.\n */\nexport interface ChannelDtmfPayload {\n /** The single detected digit (`0`–`9`, `*`, `#`, `A`–`D`). */\n digit: string;\n /** The tone duration in milliseconds. */\n duration_ms: number;\n /** The tone volume in dBm0 (negative). */\n volume: number;\n /** The From-tag of the leg the digit came from. */\n from_tag: string;\n}\n\n/**\n * The `payload` of a `PlayStarted` event — a `play` the media backend accepted\n * and started. Cast a {@link import(\"./sip\").CallEvent}'s `payload` to this when\n * `kind === \"PlayStarted\"`.\n *\n * `play_id` is the engine's handle on that one playback — what a targeted `stop`\n * ends and what a gain change addresses — and is the same value the `play`\n * command reply carried, which is how the event correlates with the command.\n * The media contract answers `play` accept-on-start, so this event is the\n * playback beginning, not a claim that audio has reached the wire: a fetched\n * source (`source: \"url\"`) accepts before its body has arrived, which is why\n * `duration_ms` can be absent.\n */\nexport interface PlayStartedPayload {\n /** Which source it started from: `file`, `blob`, `db_id`, `tone` or `url`. */\n source: string;\n /** The engine's handle on this playback, when it assigned one. */\n play_id?: number | null;\n /** The playback's length in ms, when the engine knew it at accept time. */\n duration_ms?: number | null;\n}\n\n/** The RFC 3891 `Replaces` triple embedded in a {@link TransferRequestedPayload}. */\nexport interface TransferReplaces {\n call_id: string;\n from_tag: string;\n to_tag: string;\n early_only: boolean;\n}\n\n/**\n * The `payload` of a `TransferRequested` event — an inbound REFER on a\n * controlled call, handed to the app to accept / reject. Cast a\n * {@link import(\"./sip\").CallEvent}'s `payload` to this when\n * `kind === \"TransferRequested\"`.\n */\nexport interface TransferRequestedPayload {\n /** The Refer-To URI (the transfer target). */\n refer_to: string;\n /** The embedded `Replaces` triple for an attended transfer, if present. */\n replaces?: TransferReplaces | null;\n /** The From-tag of the referring party, if known. */\n from_tag?: string | null;\n}\n\n/**\n * Where a verdict on an *outbound* REFER came from — the `stage` of a\n * {@link TransferOutcomePayload}. Unknown tokens pass through verbatim\n * (forward-compatible).\n */\nexport type TransferStage =\n /** `2xx` to the REFER: accepted for processing only (RFC 3515 §2.4.4). */\n | \"accepted\"\n /** `401`/`407` answered with credentials; `attempt` says which try. */\n | \"challenged\"\n /** A non-terminating `message/sipfrag` NOTIFY reported progress. */\n | \"notify\"\n /** A terminating sipfrag NOTIFY reported a `2xx`: the transfer completed. */\n | \"transferred\"\n /** A terminating sipfrag NOTIFY reported `3xx`+: the target failed. */\n | \"refused\"\n /** The referee refused the REFER itself: the transfer never started. */\n | \"rejected\"\n /** Challenged with no way to answer (no credentials / retry cap). */\n | \"unauthorized\"\n /** The subscription ended with no usable status — never read as success. */\n | \"no_outcome\"\n /** The call ended with the transfer still outstanding. */\n | \"call_ended\"\n | (string & {});\n\n/**\n * The `payload` shared by the `TransferProgress`, `TransferCompleted` and\n * `TransferFailed` events — one verdict on a transfer this app asked for with\n * the `refer` verb.\n *\n * The `refer` command resolves as soon as siphon has sent the REFER; RFC 3515\n * §2.4.4 puts the real outcome on the implicit subscription that follows. Expect\n * zero or more `TransferProgress`, then exactly one `TransferCompleted` /\n * `TransferFailed`. Cast a {@link import(\"./sip\").CallEvent}'s `payload` to this\n * when `kind` is one of those three.\n */\nexport interface TransferOutcomePayload {\n /** Where this verdict came from. */\n stage: TransferStage;\n /** The Refer-To URI the REFER carried, when known. */\n refer_to?: string | null;\n /**\n * The SIP status this verdict rests on: the REFER's own response status for\n * `accepted` / `challenged` / `rejected` / `unauthorized`, the sipfrag status\n * for the NOTIFY-driven stages.\n */\n code?: number | null;\n /** That status's reason phrase, when the peer supplied one. */\n reason?: string | null;\n /**\n * Which REFER attempt this verdict is about, 1-based. `null` once the REFER\n * transaction is over (the NOTIFY-driven stages).\n */\n attempt?: number | null;\n}\n\n/**\n * Whether an event name ends a transfer this app asked for. Exactly one such\n * event arrives per `refer`, so this is the signal to stop waiting.\n */\nexport function isTransferFinal(name: string): boolean {\n return name === \"TransferCompleted\" || name === \"TransferFailed\";\n}\n\n/**\n * The transfer verdict carried by an event, or `null` if it is not one.\n *\n * Takes an event as {@link import(\"./sip\").CallEvent} shapes it and narrows its\n * `payload` to {@link TransferOutcomePayload} for `TransferProgress` /\n * `TransferCompleted` / `TransferFailed`. Anything else — including\n * `TransferRequested`, which is an *inbound* REFER somebody else asked for\n * rather than a verdict on one of ours — gives `null`.\n */\nexport function transferOutcome(event: {\n kind: string;\n payload: unknown;\n}): TransferOutcomePayload | null {\n if (\n event.kind !== \"TransferProgress\" &&\n event.kind !== \"TransferCompleted\" &&\n event.kind !== \"TransferFailed\"\n ) {\n return null;\n }\n return (event.payload ?? null) as TransferOutcomePayload | null;\n}\n\n/**\n * What happens to the surviving leg when its bridge partner hangs up — the\n * `onPeerHangup` option of {@link import(\"./sip\").Call.bridge}.\n *\n * `\"hangup\"` (the default) tears the survivor down too: a bridged pair behaves\n * like one call. `\"hold\"` keeps it up, held (RFC 3264 §8.4) and still owned, so\n * the app can bridge it to somebody else — the supervisor / attended-hand-off\n * case. A closed set: the server refuses anything else with\n * `code === \"bad_request\"` rather than guessing at a teardown policy.\n */\nexport type PeerHangupPolicy = \"hangup\" | \"hold\";\n\n/**\n * Which side of a bridge a leg is — the `role` of a\n * {@link ChannelBridgedPayload}. The `anchor` is the channel the `bridge` was\n * addressed to and keeps its media session; the `peer` is the one named by\n * `with`, whose own media session was deleted when it joined. Unknown tokens\n * pass through verbatim (forward-compatible).\n */\nexport type BridgeRole = \"anchor\" | \"peer\" | (string & {});\n\n/**\n * Which of a bridge's two re-INVITEs was refused — the `stage` of a\n * {@link BridgeFailedPayload}. `offering_peer` means the `with` leg refused the\n * anchor's media and the anchor was never touched; `offering_anchor` means the\n * peer answered but the anchor refused what it was re-offered. Unknown tokens\n * pass through verbatim (forward-compatible).\n */\nexport type BridgeStage = \"offering_peer\" | \"offering_anchor\" | (string & {});\n\n/**\n * The `payload` of a `ChannelBridged` event — the bridge formed and the two\n * parties can hear each other.\n *\n * A bridge is two RFC 3261 §14 re-INVITEs across two dialogs, so the `bridge`\n * command reply reports only the local action (the media re-pointed, the first\n * re-INVITE on the wire) and this event is the outcome. It is pushed on **both**\n * bridged channels, each copy naming the other leg. Cast a\n * {@link import(\"./sip\").CallEvent}'s `payload` to this when\n * `kind === \"ChannelBridged\"`.\n */\nexport interface ChannelBridgedPayload {\n /** The internal `CallActor` id of the leg on the other side. */\n peer_call_id: string;\n /** That leg's SIP `Call-ID` — the CDR / HEP join key for the other party. */\n peer_sip_call_id: string;\n /** Which side *this* channel is. */\n role: BridgeRole;\n /** Whether the bridged pair lives on the media engine (the anchor's session). */\n anchored: boolean;\n}\n\n/**\n * The `payload` of a `BridgeFailed` event — one of the bridge's two re-INVITEs\n * was refused and both legs were left exactly as they were. Never a teardown:\n * the app still owns both calls and can retry, bridge elsewhere, or hang up.\n */\nexport interface BridgeFailedPayload {\n /** Which re-INVITE was refused. */\n stage: BridgeStage;\n /** The SIP status the refusing leg answered with (`488`, `491`, `500`, …). */\n code?: number | null;\n /** The SIP `Call-ID` of the other leg in the attempt. */\n peer_sip_call_id?: string | null;\n}\n\n/**\n * The `payload` of a `ChannelUnbridged` event — the bridge was broken. Both legs\n * stay answered, owned and held (RFC 3264 §8.4 `a=sendonly`); neither is hung\n * up, because that would be indistinguishable from two hangups. Pushed on both\n * channels.\n */\nexport interface ChannelUnbridgedPayload {\n /** The internal `CallActor` id of the leg that was on the other side. */\n peer_call_id: string;\n /** That leg's SIP `Call-ID`. */\n peer_sip_call_id: string;\n /** The reason the `unbridge` carried (default `\"unbridged\"`). */\n reason: string;\n}\n\n/**\n * The `payload` of a `PeerReplaced` event — a leg replacement completed.\n *\n * The target answered, was promoted into the surviving pair, and the leg it\n * replaced was released. The `replace_peer` reply reported only that the INVITE\n * had left the box; this is when the call actually changed shape.\n */\nexport interface PeerReplacedPayload {\n /** The SIP `Call-ID` of the leg that took the replaced party's place. */\n target_sip_call_id: string;\n /**\n * Whether the replaced leg was actually BYE'd. `false` when it had already\n * hung up while the target was still ringing — the replacement completed\n * regardless, there was simply nothing left to release.\n */\n replaced_leg_released: boolean;\n /**\n * `\"refer\"` when a remote party asked for this (an inbound REFER siphon\n * terminated), `\"siphon\"` when a script or a controller decided.\n */\n origin: string;\n}\n\n/**\n * The `payload` of a `ReplaceFailed` event — a leg replacement did not happen.\n *\n * Branch on `call_kept`: normally the original call is intact and still has\n * both its parties, so another target can be tried on the same channel. It is\n * `false` only when the leg being replaced had already hung up, which leaves\n * the survivor with nobody and the call released.\n */\nexport interface ReplaceFailedPayload {\n /**\n * The SIP status the target refused with, or `408` when it never answered at\n * all and the replacement timed out.\n */\n status: number;\n /** Whether the original call survives. */\n call_kept: boolean;\n /** `\"refer\"` or `\"siphon\"`, as on {@link PeerReplacedPayload}. */\n origin: string;\n}\n\n/**\n * The `payload` of a `PlayFinished` event — a playback ended.\n *\n * `completed` is the field to branch on: a stop, a supersede and an error all\n * end a playback without the prompt having been heard in full, and the accept's\n * estimated duration says nothing about which happened.\n */\nexport interface PlayFinishedPayload {\n from_tag: string;\n to_tag?: string | null;\n /** Correlates with the `play` accept and the `PlayStarted` event. */\n play_id: number;\n /** `completed`, `stopped`, `superseded` or `error`. */\n reason: string;\n /** Whether the prompt drained naturally — the only reason it was heard in full. */\n completed: boolean;\n played_ms?: number | null;\n}\n\n/**\n * The `payload` of a `WsTeeStarted` event — a WebSocket audio **tee** began\n * streaming a copy of the channel's audio. Additive: the call relays on\n * regardless, so a tee never affects the parties.\n *\n * `streamId` correlates this event with the `start` frame on the socket, and\n * the wire shape is stated so a consumer decodes the binary frames without\n * guessing.\n */\nexport interface WsTeeStartedPayload {\n from_tag: string;\n stream_id: string;\n ws_uri: string;\n /** `both`, `caller` or `callee`. */\n direction: string;\n /** 1 = mono/mixed, 2 = caller/callee interleaved. */\n channels: number;\n /** Wire sample rate in Hz (L16, little-endian). */\n sample_rate: number;\n}\n\n/**\n * The `payload` of a `WsTeeEnded` event. Exactly one arrives per\n * `WsTeeStarted`, including when the *server* ends it, so a consumer learns\n * the stream died rather than silently losing the audio.\n *\n * `frames_dropped > 0` means the consumer could not keep up; the call itself\n * was never affected.\n */\nexport interface WsTeeEndedPayload {\n from_tag: string;\n stream_id: string;\n /** `detached`, `server_closed`, `server_stopped`, `call_ended` or `transport_error`. */\n reason: string;\n /** `detached` is the only orderly end; anything else stopped the audio mid-call. */\n unexpected: boolean;\n frames_sent?: number | null;\n frames_dropped?: number | null;\n}\n\n/**\n * The `payload` of a `WsBridgeStarted` event — a WebSocket **takeover** bridge\n * began. Unlike a tee this *replaced* the call's audio path: the WebSocket\n * server is now the leg's far side and A-to-B is unwired.\n */\nexport interface WsBridgeStartedPayload {\n from_tag: string;\n stream_id: string;\n ws_uri: string;\n /** Wire sample rate in Hz (L16, little-endian). */\n sample_rate: number;\n}\n\n/**\n * The `payload` of a `WsBridgeEnded` event. Exactly one per\n * `WsBridgeStarted`; a re-point arrives as an ended (reason `detached`)\n * followed by a fresh started.\n *\n * `unexpected` matters more here than on a tee: a bridge *is* the call's media\n * path, so anything but `detached` leaves both parties up and hearing nothing.\n */\nexport interface WsBridgeEndedPayload {\n from_tag: string;\n stream_id: string;\n /** `detached`, `server_closed`, `server_stopped`, `call_ended` or `transport_error`. */\n reason: string;\n unexpected: boolean;\n}\n\n/**\n * Whether an event name ends a bridge this app asked for. Exactly one such event\n * arrives per `bridge`, so this is the signal to stop waiting. `ChannelUnbridged`\n * is not one of them — it ends a bridge that already formed.\n */\nexport function isBridgeFinal(name: string): boolean {\n return name === \"ChannelBridged\" || name === \"BridgeFailed\";\n}\n","/** Small internal utilities shared by the client, server, and SIP facade. */\n\n/**\n * An unbounded, single-consumer async queue (the TypeScript analogue of Rust's\n * `tokio::sync::mpsc::unbounded_channel`). `push` never blocks; `next` resolves\n * with the next item, or `null` once the queue is closed and drained.\n */\nexport class AsyncQueue<T> {\n private readonly items: T[] = [];\n private readonly waiters: Array<(value: T | null) => void> = [];\n private closed = false;\n\n /** Enqueue an item (or hand it directly to a waiting consumer). */\n push(item: T): void {\n if (this.closed) {\n return;\n }\n const waiter = this.waiters.shift();\n if (waiter) {\n waiter(item);\n } else {\n this.items.push(item);\n }\n }\n\n /** Await the next item, or `null` once the queue is closed and drained. */\n next(): Promise<T | null> {\n if (this.items.length > 0) {\n return Promise.resolve(this.items.shift() as T);\n }\n if (this.closed) {\n return Promise.resolve(null);\n }\n return new Promise((resolve) => this.waiters.push(resolve));\n }\n\n /** Close the queue: pending and future `next()` calls resolve with `null`. */\n close(): void {\n if (this.closed) {\n return;\n }\n this.closed = true;\n for (const waiter of this.waiters.splice(0)) {\n waiter(null);\n }\n }\n\n /** Async-iterate the queue until it closes. */\n async *[Symbol.asyncIterator](): AsyncIterableIterator<T> {\n for (;;) {\n const item = await this.next();\n if (item === null) {\n return;\n }\n yield item;\n }\n }\n}\n\n/** A shared, mutable request-id counter (Rust's `Arc<AtomicU64>`). */\nexport interface IdCounter {\n value: number;\n}\n\n/** Resolve after `ms` milliseconds. */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/**\n * One live WebSocket connection: request-id correlation, the read path, and\n * generic event fan-out. Knows nothing about SIP — it moves opaque `{module,\n * verb, target, args}` frames and hands every event to a sink.\n *\n * Shared verbatim by the inbound client and the per-call-connect server; only\n * how the socket is *acquired* differs. Mirrors the Rust `SessionCore`.\n */\n\nimport type { RawData, WebSocket } from \"ws\";\n\nimport { ControlError } from \"./errors\";\nimport type { IdCounter } from \"./internal\";\nimport { encodeCommand, parseInboundFrame } from \"./protocol\";\nimport type { EventFrame } from \"./protocol\";\n\n/** A sink the read path calls for every inbound event frame (any module). */\nexport type EventSink = (frame: EventFrame) => void;\n\n/**\n * Anything that can send a control command and await its correlated reply.\n *\n * Implemented by {@link Session} (bound to one connection — the per-call-connect\n * server) and by the client's commander (routes to the current session,\n * surviving reconnects — the inbound client). Lets a facade's handle command its\n * call without caring which mode it runs in.\n */\nexport interface CommandTransport {\n command(\n module: string | null,\n verb: string,\n target: unknown,\n args: unknown,\n ): Promise<unknown>;\n}\n\ninterface Pending {\n resolve: (result: unknown) => void;\n reject: (error: ControlError) => void;\n timer: ReturnType<typeof setTimeout>;\n}\n\n/** The shared, transport-agnostic state of one connection. */\nexport class Session implements CommandTransport {\n private readonly pending = new Map<string, Pending>();\n private closed = false;\n private readonly closeWaiters: Array<() => void> = [];\n\n constructor(\n private readonly socket: WebSocket,\n private readonly nextId: IdCounter,\n private readonly replyTimeoutMs: number,\n private readonly eventSink: EventSink,\n ) {\n socket.on(\"message\", (data: RawData) => this.onMessage(data.toString()));\n socket.on(\"close\", () => this.markClosed());\n socket.on(\"error\", () => this.markClosed());\n }\n\n /**\n * Send a command and await its correlated reply. Maps a `status:\"error\"`\n * reply to a rejected {@link ControlError} carrying the wire code.\n */\n command(\n module: string | null,\n verb: string,\n target: unknown,\n args: unknown,\n ): Promise<unknown> {\n if (this.closed) {\n return Promise.reject(ControlError.closed());\n }\n const id = `c-${this.nextId.value++}`;\n const text = encodeCommand(id, module, verb, target, args);\n return new Promise<unknown>((resolve, reject) => {\n const timer = setTimeout(() => {\n this.pending.delete(id);\n reject(ControlError.timeout(this.replyTimeoutMs));\n }, this.replyTimeoutMs);\n this.pending.set(id, { resolve, reject, timer });\n try {\n this.socket.send(text);\n } catch (error) {\n this.pending.delete(id);\n clearTimeout(timer);\n reject(ControlError.websocket(String(error)));\n }\n });\n }\n\n private onMessage(text: string): void {\n const frame = parseInboundFrame(text);\n if (frame === null) {\n return;\n }\n if (frame.type === \"reply\") {\n const pending = this.pending.get(frame.id);\n if (!pending) {\n return; // reply for an unknown / expired id — drop.\n }\n this.pending.delete(frame.id);\n clearTimeout(pending.timer);\n if (frame.status === \"ok\") {\n pending.resolve(frame.result ?? null);\n } else {\n const code = frame.error?.code ?? \"protocol_error\";\n const message = frame.error?.message ?? \"error reply without an error body\";\n pending.reject(ControlError.command(code, message));\n }\n } else {\n this.eventSink(frame);\n }\n }\n\n /** Explicitly close the connection. */\n close(): void {\n try {\n this.socket.close();\n } catch {\n // ignore — already closing / closed.\n }\n this.markClosed();\n }\n\n private markClosed(): void {\n if (this.closed) {\n return;\n }\n this.closed = true;\n for (const pending of this.pending.values()) {\n clearTimeout(pending.timer);\n pending.reject(ControlError.closed());\n }\n this.pending.clear();\n for (const waiter of this.closeWaiters.splice(0)) {\n waiter();\n }\n }\n\n isClosed(): boolean {\n return this.closed;\n }\n\n /** Resolve once the connection is closed. */\n waitClosed(): Promise<void> {\n if (this.closed) {\n return Promise.resolve();\n }\n return new Promise((resolve) => this.closeWaiters.push(resolve));\n }\n}\n","/**\n * The protocol-agnostic inbound-persistent control client.\n *\n * Knows nothing about SIP: it owns the transport, the `hello` handshake,\n * request-id correlation, reconnect + `resync`, and a generic event stream. Its\n * headline primitive is {@link ControlClient.command} over `{module, verb,\n * target, args}`, which works for any adapter with zero changes. Typed\n * per-protocol facades (see {@link SipClient}) are built on top. Mirrors the\n * Rust `ControlClient`.\n */\n\nimport WebSocket from \"ws\";\n\nimport { ControlError } from \"./errors\";\nimport type { IdCounter } from \"./internal\";\nimport { AsyncQueue, sleep } from \"./internal\";\nimport {\n DESCRIBE,\n HELLO,\n PROTOCOL_VERSION,\n RESYNC,\n SUBPROTOCOL,\n} from \"./protocol\";\nimport type {\n ChannelSnapshot,\n EventFrame,\n HelloResult,\n ResyncResult,\n} from \"./protocol\";\nimport type { CommandTransport } from \"./session\";\nimport { Session } from \"./session\";\n\n/** How a {@link ControlClient} connects and behaves. */\nexport interface ClientConfig {\n /** The control-plane URL, e.g. `ws://siphon:9090/control/ws` (or `wss://…`). */\n url: string;\n /** The application name — must equal the token's configured app. */\n app: string;\n /** The bearer token presented on the upgrade. */\n token: string;\n /** Protocol version to advertise in `hello` (defaults to {@link PROTOCOL_VERSION}). */\n protocol?: number;\n /** How long a command waits for its reply before a timeout (default 10 000 ms). */\n replyTimeoutMs?: number;\n /** Backoff between reconnect attempts in {@link ControlClient.run} (default 1 000 ms). */\n reconnectBackoffMs?: number;\n}\n\ntype ResolvedConfig = Required<ClientConfig>;\n\nfunction resolveConfig(config: ClientConfig): ResolvedConfig {\n return {\n url: config.url,\n app: config.app,\n token: config.token,\n protocol: config.protocol ?? PROTOCOL_VERSION,\n replyTimeoutMs: config.replyTimeoutMs ?? 10_000,\n reconnectBackoffMs: config.reconnectBackoffMs ?? 1_000,\n };\n}\n\n/** An item on the client's generic event stream. */\nexport type ClientEvent =\n | { type: \"event\"; frame: EventFrame }\n | { type: \"reattach\"; snapshot: ChannelSnapshot };\n\ntype EventCallback = (event: ClientEvent) => void;\n\n/** A generic subscription to the client's event stream (see {@link ControlClient.events}). */\nexport class EventStream {\n constructor(private readonly queue: AsyncQueue<ClientEvent>) {}\n\n /** Await the next event. `null` once the client shuts down. */\n next(): Promise<ClientEvent | null> {\n return this.queue.next();\n }\n\n [Symbol.asyncIterator](): AsyncIterableIterator<ClientEvent> {\n return this.queue[Symbol.asyncIterator]();\n }\n}\n\n/**\n * The protocol-agnostic inbound-persistent control client.\n *\n * Use {@link ControlClient.command} directly for any module, or wrap it in a\n * typed facade such as {@link SipClient}.\n */\nexport class ControlClient {\n private readonly config: ResolvedConfig;\n private readonly nextId: IdCounter = { value: 1 };\n private current: Session | null = null;\n private eventCallback: EventCallback | null = null;\n private shutdownRequested = false;\n private readonly shutdownWaiters: Array<() => void> = [];\n\n private constructor(config: ClientConfig) {\n this.config = resolveConfig(config);\n }\n\n /**\n * Connect + `hello`. A bad token surfaces as a {@link ControlError} of kind\n * `unauthorized` (the upgrade is rejected 401 before the socket opens).\n */\n static async connect(config: ClientConfig): Promise<ControlClient> {\n const client = new ControlClient(config);\n client.current = await client.connectAndHandshake();\n return client;\n }\n\n /**\n * Register a callback for every event (pushed events + reconnect reattach).\n * Overwrites any previous callback / stream. Facades set this internally.\n */\n onEvent(callback: EventCallback): void {\n this.eventCallback = callback;\n }\n\n /** A pull-style stream of every event. Overwrites any previous callback. */\n events(): EventStream {\n const queue = new AsyncQueue<ClientEvent>();\n this.eventCallback = (event) => queue.push(event);\n return new EventStream(queue);\n }\n\n /**\n * Send a raw command on the current session and return the reply's `result`.\n * The generic primitive every facade is built on.\n */\n async command(\n module: string | null,\n verb: string,\n target: unknown,\n args: unknown,\n ): Promise<unknown> {\n const session = this.current;\n if (!session || session.isClosed()) {\n throw ControlError.closed();\n }\n return session.command(module, verb, target, args);\n }\n\n /** Fetch the registered adapters' verb/event schema (`describe`). */\n async describe(): Promise<unknown> {\n return this.command(null, DESCRIBE, null, null);\n }\n\n /** Re-enumerate the channels this connection owns (`resync`). */\n async resync(): Promise<ChannelSnapshot[]> {\n const value = (await this.command(null, RESYNC, null, null)) as ResyncResult | null;\n return value?.channels ?? [];\n }\n\n /**\n * A {@link CommandTransport} that routes to the client's *current* session (so\n * a facade handle keeps working across reconnects). Used by {@link SipClient}.\n */\n commander(): CommandTransport {\n return {\n command: (module, verb, target, args) => this.command(module, verb, target, args),\n };\n }\n\n /**\n * Drive the client: keep the connection alive, reconnecting with backoff and\n * re-attaching owned channels (`resync`, delivered as `reattach` events) after\n * each reconnect. Resolves on {@link ControlClient.shutdown}, or rejects on a\n * fatal error (token revoked → `unauthorized`).\n */\n async run(): Promise<void> {\n for (;;) {\n let session = this.current;\n if (!session || session.isClosed()) {\n if (this.shutdownRequested) {\n return;\n }\n try {\n session = await this.connectAndHandshake();\n } catch (error) {\n if (error instanceof ControlError && error.kind === \"unauthorized\") {\n throw error;\n }\n await Promise.race([sleep(this.config.reconnectBackoffMs), this.shutdownSignal()]);\n if (this.shutdownRequested) {\n return;\n }\n continue;\n }\n this.current = session;\n await this.resyncAndReattach(session);\n }\n\n await Promise.race([session.waitClosed(), this.shutdownSignal()]);\n if (this.shutdownRequested) {\n return;\n }\n this.current = null;\n }\n }\n\n /** Stop the client: close the current session and unblock {@link ControlClient.run}. */\n shutdown(): void {\n this.shutdownRequested = true;\n for (const waiter of this.shutdownWaiters.splice(0)) {\n waiter();\n }\n if (this.current) {\n this.current.close();\n this.current = null;\n }\n }\n\n private shutdownSignal(): Promise<void> {\n if (this.shutdownRequested) {\n return Promise.resolve();\n }\n return new Promise((resolve) => this.shutdownWaiters.push(resolve));\n }\n\n private emit(event: ClientEvent): void {\n this.eventCallback?.(event);\n }\n\n private async connectAndHandshake(): Promise<Session> {\n const socket = await this.openSocket();\n const session = new Session(\n socket,\n this.nextId,\n this.config.replyTimeoutMs,\n (frame) => this.emit({ type: \"event\", frame }),\n );\n const result = (await session.command(null, HELLO, null, {\n app: this.config.app,\n protocol: this.config.protocol,\n })) as HelloResult | null;\n if (!result || result.subprotocol !== SUBPROTOCOL) {\n session.close();\n throw ControlError.handshake(\n `server negotiated subprotocol ${JSON.stringify(result?.subprotocol)}, expected ${JSON.stringify(SUBPROTOCOL)}`,\n );\n }\n return session;\n }\n\n private openSocket(): Promise<WebSocket> {\n return new Promise<WebSocket>((resolve, reject) => {\n const socket = new WebSocket(this.config.url, [SUBPROTOCOL], {\n headers: { Authorization: `Bearer ${this.config.token}` },\n });\n let settled = false;\n const settle = (): void => {\n settled = true;\n socket.off(\"open\", onOpen);\n socket.off(\"unexpected-response\", onUnexpected);\n };\n const onOpen = (): void => {\n settle();\n resolve(socket);\n };\n const onUnexpected = (\n request: { destroy: () => void },\n response: { statusCode?: number },\n ): void => {\n settle();\n // Free the aborted upgrade's socket without the \"closed before the\n // connection was established\" that `socket.terminate()` throws here.\n request.destroy();\n reject(ControlError.unauthorized(response.statusCode ?? 0));\n };\n const onError = (error: Error): void => {\n if (!settled) {\n settle();\n reject(ControlError.websocket(error.message));\n }\n // Post-settle errors (e.g. the destroyed handshake socket hanging up)\n // are swallowed here so a stray `error` never crashes the process.\n };\n socket.on(\"open\", onOpen);\n socket.on(\"unexpected-response\", onUnexpected);\n socket.on(\"error\", onError);\n });\n }\n\n private async resyncAndReattach(session: Session): Promise<void> {\n try {\n const value = (await session.command(null, RESYNC, null, null)) as ResyncResult | null;\n for (const snapshot of value?.channels ?? []) {\n this.emit({ type: \"reattach\", snapshot });\n }\n } catch {\n // A failed resync is non-fatal — the connection stays up.\n }\n }\n}\n","/**\n * Outbound per-call-connect mode: siphon *dials the application* at handover,\n * so the app is a WebSocket **server**. This is the documented default for\n * multi-pod controllers — the accepting socket owns exactly that one call, so\n * \"the audio lands on the wrong pod\" is structurally impossible.\n *\n * No `hello` is exchanged: siphon presents the token in the dial headers, and\n * the first frame the app receives is a pushed event (`StasisStart` for SIP).\n * Mirrors the Rust `ControlServer`.\n */\n\nimport type { AddressInfo } from \"node:net\";\n\nimport WebSocket, { WebSocketServer } from \"ws\";\n\nimport { ControlError } from \"./errors\";\nimport type { IdCounter } from \"./internal\";\nimport { SUBPROTOCOL } from \"./protocol\";\nimport type { EventFrame } from \"./protocol\";\nimport type { CommandTransport, EventSink } from \"./session\";\nimport { Session } from \"./session\";\n\n/** How a {@link ControlServer} listens for siphon's per-call dials. */\nexport interface ServerConfig {\n /** The host to bind (e.g. `0.0.0.0`). */\n host: string;\n /** The port to bind (`0` picks a free port — read it back via `localAddr`). */\n port: number;\n /** The application name (context / logging). */\n app: string;\n /** The bearer token siphon must present on the dial. */\n token: string;\n /** How long a command waits for its reply before a timeout (default 10 000 ms). */\n replyTimeoutMs?: number;\n}\n\n/** A sink the server calls for each event, carrying the {@link CommandTransport}\n * of the connection that produced it (so a facade commands back on the right one). */\nexport type ConnectionEventSink = (frame: EventFrame, transport: CommandTransport) => void;\n\n/** The protocol-agnostic per-call-connect control server. */\nexport class ControlServer {\n private readonly nextId: IdCounter = { value: 1 };\n private eventSink: ConnectionEventSink | null = null;\n private readonly closeWaiters: Array<() => void> = [];\n private readonly sockets = new Set<WebSocket>();\n private closed = false;\n\n private constructor(\n private readonly config: ServerConfig,\n private readonly wss: WebSocketServer,\n ) {\n wss.on(\"connection\", (socket, request) => this.onConnection(socket, request));\n wss.on(\"close\", () => this.markClosed());\n }\n\n /** Bind the listener (so the assigned port is known before accepting). */\n static bind(config: ServerConfig): Promise<ControlServer> {\n const token = config.token;\n return new Promise<ControlServer>((resolve, reject) => {\n const wss = new WebSocketServer({\n host: config.host,\n port: config.port,\n // Echo the subprotocol siphon offers on the dial (required — the client\n // rejects the handshake otherwise).\n handleProtocols: (protocols) => (protocols.has(SUBPROTOCOL) ? SUBPROTOCOL : false),\n // Verify the bearer token siphon presents (the app's own policy).\n verifyClient: ({ req }, done) => {\n const ok = req.headers[\"authorization\"] === `Bearer ${token}`;\n done(ok, 401, \"unauthorized\");\n },\n });\n const onError = (error: Error): void => {\n wss.off(\"listening\", onListening);\n reject(ControlError.config(`bind ${config.host}:${config.port}: ${error.message}`));\n };\n const onListening = (): void => {\n wss.off(\"error\", onError);\n resolve(new ControlServer(config, wss));\n };\n wss.once(\"listening\", onListening);\n wss.once(\"error\", onError);\n });\n }\n\n /** The actual bound address (useful when binding to port 0 in tests). */\n localAddr(): AddressInfo {\n const address = this.wss.address();\n if (typeof address === \"string\" || address === null) {\n throw ControlError.config(\"server is not bound to a TCP address\");\n }\n return address;\n }\n\n /** Register the sink for `(event, connection-commander)` pairs. Facades set this internally. */\n onConnectionEvent(sink: ConnectionEventSink): void {\n this.eventSink = sink;\n }\n\n /** Resolve once the server has been closed (`run` resolves at the same time). */\n run(): Promise<void> {\n if (this.closed) {\n return Promise.resolve();\n }\n return new Promise((resolve) => this.closeWaiters.push(resolve));\n }\n\n /** Stop accepting dials, drop live connections, and close the listener. */\n close(): Promise<void> {\n // Terminate live connections first: the underlying HTTP server's `close`\n // does not fire until every connection has ended.\n for (const socket of this.sockets) {\n socket.terminate();\n }\n this.sockets.clear();\n return new Promise((resolve) => {\n this.wss.close(() => {\n this.markClosed();\n resolve();\n });\n });\n }\n\n private markClosed(): void {\n if (this.closed) {\n return;\n }\n this.closed = true;\n for (const waiter of this.closeWaiters.splice(0)) {\n waiter();\n }\n }\n\n private onConnection(socket: WebSocket, _request: unknown): void {\n this.sockets.add(socket);\n socket.on(\"close\", () => this.sockets.delete(socket));\n // The event sink needs this connection's commander, which is the session\n // itself. `session` is assigned synchronously here, before any inbound\n // message can be delivered (those arrive on later ticks).\n let session: Session;\n const sink: EventSink = (frame) => {\n this.eventSink?.(frame, session);\n };\n session = new Session(socket, this.nextId, this.config.replyTimeoutMs ?? 10_000, sink);\n }\n}\n","/**\n * The **SIP facade** over the protocol-agnostic core.\n *\n * {@link Call} is a typed handle whose verbs (`answer`/`progress`/`reject`/\n * `terminate`/`refer`/…) are thin wrappers that send `command(\"sip\", …)` on the\n * underlying core and await the correlated reply. The method names mirror the\n * in-process siphon scripting API (`call.answer()`, `call.terminate()`,\n * `call.transfer()`, `call.setHeader()`, …), so an out-of-process controller\n * reads like an in-process script. The `StasisStart`→{@link Call} dispatch and\n * the `onCall` handler live here (they are SIP/ARI concepts) on top of the\n * core's generic event stream, so a future `smpp` / `ss7` facade is an additive\n * sibling over the same core.\n */\n\nimport type { ControlClient, ClientConfig, ClientEvent } from \"./client\";\nimport { ControlClient as ControlClientImpl } from \"./client\";\nimport { AsyncQueue } from \"./internal\";\nimport {\n MODULE_SIP,\n SET_VAR,\n GET_VAR,\n SipVerb,\n sipEventKind,\n} from \"./protocol\";\nimport type {\n ChannelSnapshot,\n EventFrame,\n PeerHangupPolicy,\n SipEventKind,\n} from \"./protocol\";\nimport type { ControlServer, ServerConfig } from \"./server\";\nimport { ControlServer as ControlServerImpl } from \"./server\";\nimport type { CommandTransport } from \"./session\";\n\n// ---------------------------------------------------------------------------\n// Call handle\n// ---------------------------------------------------------------------------\n\n/** One event delivered to a call's stream (`ChannelStateChange`,\n * `ChannelHangupRequest`, `ChannelDtmfReceived`, `TransferRequested`,\n * `TransferProgress`, `TransferCompleted`, `TransferFailed`, `ChannelBridged`,\n * `BridgeFailed`, `ChannelUnbridged`, `StasisEnd`, …).\n * Cast `payload` to\n * {@link import(\"./protocol\").ChannelDtmfPayload} /\n * {@link import(\"./protocol\").TransferRequestedPayload} /\n * {@link import(\"./protocol\").TransferOutcomePayload} /\n * {@link import(\"./protocol\").ChannelBridgedPayload} /\n * {@link import(\"./protocol\").BridgeFailedPayload} /\n * {@link import(\"./protocol\").ChannelUnbridgedPayload} by `kind`. */\nexport interface CallEvent {\n /** The parsed event kind. */\n kind: SipEventKind;\n /** The event-specific payload. */\n payload: unknown;\n /** The raw frame (for fields not surfaced above). */\n frame: EventFrame;\n}\n\nfunction callEventFromFrame(frame: EventFrame): CallEvent {\n return { kind: sipEventKind(frame.event), payload: frame.payload ?? null, frame };\n}\n\n/** Options for a UAS provisional / final response (`answer` / `progress`). */\nexport interface ResponseOptions {\n code?: number;\n reason?: string;\n body?: string;\n contentType?: string;\n}\n\nfunction responseArgs(options: ResponseOptions): Record<string, unknown> {\n const args: Record<string, unknown> = {};\n if (options.code !== undefined) {\n args.code = options.code;\n }\n if (options.reason !== undefined) {\n args.reason = options.reason;\n }\n if (options.body !== undefined) {\n args.body = options.body;\n }\n if (options.contentType !== undefined) {\n args.content_type = options.contentType;\n }\n return args;\n}\n\n/** Options for an anchored answer ({@link Call.answerAnchored}). */\nexport interface AnchoredAnswerOptions {\n /** UAS 2xx code (default `200`). */\n code?: number;\n /** Reason phrase (default `OK`). */\n reason?: string;\n /** Media profile to anchor with (default `voice_ai`). */\n profile?: string;\n /**\n * Per-call WebSocket bridge URI, overriding the profile's own. Supports\n * `{call_id}` / `{from_tag}` / `{from_user}` / `{to_user}` templating.\n */\n wsUri?: string;\n}\n\n/** The RFC 3891 `Replaces` triple for an attended transfer. */\nexport interface ReferReplaces {\n callId: string;\n fromTag: string;\n toTag: string;\n earlyOnly?: boolean;\n}\n\n/** Options for {@link Call.acceptRefer}. */\nexport interface AcceptReferOptions {\n target?: string;\n nextHop?: string;\n mode?: \"terminate\" | \"transparent\";\n /**\n * Media profile for the pairing the transfer creates.\n *\n * **Required when the call is anchored with a direction-bound profile** — one\n * whose offer and answer halves describe different sides, such as\n * `srtp_to_rtp` at an SRTP edge. A transfer moves the party that half was\n * written for out of the call, so inheriting the profile re-offers *that\n * party's* transport to whoever remains: SRTP toward a plain-RTP carrier,\n * which answers `m=audio 0`. The call connects and carries no audio in either\n * direction while the SIP trace looks healthy.\n *\n * Pass the profile for the pair that remains (commonly `\"rtp_passthrough\"`).\n * Omitted inherits the call's profile, which is correct only when it is\n * symmetric.\n */\n profile?: string;\n}\n\n/** Options for {@link Call.bridge}. */\nexport interface BridgeOptions {\n /**\n * What happens to the surviving leg when its bridge partner hangs up —\n * `\"hangup\"` (the default) tears it down too, `\"hold\"` keeps it up, held and\n * still owned so it can be bridged to somebody else. See\n * {@link import(\"./protocol\").PeerHangupPolicy}.\n */\n onPeerHangup?: PeerHangupPolicy;\n}\n\n/** A {@link Call.route} target carrying per-target overrides. */\nexport interface RouteTargetObject {\n /** The B-leg request URI to dial. */\n uri: string;\n /** Route egress to this next hop instead of resolving `uri`. */\n nextHop?: string;\n /** Headers injected on this attempt's B-leg INVITE. */\n headers?: Record<string, string>;\n /** Per-target ring timeout in seconds. */\n timeout?: number;\n}\n\n/**\n * One entry in a {@link Call.route} target list: a bare URI string, or a\n * {@link RouteTargetObject} with per-target overrides.\n */\nexport type RouteTarget = string | RouteTargetObject;\n\nfunction routeTargetToWire(target: RouteTarget): unknown {\n if (typeof target === \"string\") {\n return target;\n }\n const object: Record<string, unknown> = { uri: target.uri };\n if (target.nextHop !== undefined) {\n object.next_hop = target.nextHop;\n }\n if (target.headers !== undefined) {\n object.headers = target.headers;\n }\n if (target.timeout !== undefined) {\n object.timeout = target.timeout;\n }\n return object;\n}\n\nfunction stringValue(result: unknown): string | null {\n if (typeof result === \"object\" && result !== null) {\n const value = (result as { value?: unknown }).value;\n if (typeof value === \"string\") {\n return value;\n }\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// play() / dtmf() / streamStart() args\n// ---------------------------------------------------------------------------\n\n/**\n * The audio source for {@link Call.play}: exactly one of a server-side file\n * path, an rtpengine media-DB id, or an inline blob. A blob is base64-encoded on\n * the wire (the control rail is JSON text).\n */\nexport type PlaySource =\n | { file: string }\n | { dbId: number }\n | { blob: Uint8Array };\n\n/** Optional shaping for {@link Call.play}. */\nexport interface PlayOptions {\n /** Repeat the prompt this many times (0/undefined → play once). */\n repeat?: number;\n /** Start playback at this offset into the source, in milliseconds. */\n startMs?: number;\n /** Cap playback to this duration, in milliseconds. */\n durationMs?: number;\n /** Scope the prompt to one peer of an MPTY bridge (its To-tag). */\n toTag?: string;\n}\n\n/** Optional shaping for {@link Call.dtmf}. */\nexport interface DtmfOptions {\n /** Per-digit tone duration, in milliseconds. */\n durationMs?: number;\n /** Tone volume in dBm0 (negative). */\n volumeDbm0?: number;\n /** Inter-digit pause, in milliseconds. */\n pauseMs?: number;\n /** Scope the tones to one peer of an MPTY bridge (its To-tag). */\n toTag?: string;\n}\n\n/** Options for {@link Call.streamStart} (the WebSocket audio tee). */\nexport interface StreamOptions {\n /** Which leg(s) to tee — `\"both\"` (default), `\"caller\"`, or `\"callee\"`. */\n direction?: \"both\" | \"caller\" | \"callee\";\n /** `1` = mixed mono, `2` = caller/callee stereo (only with `\"both\"`). */\n channels?: 1 | 2;\n}\n\nfunction playArgs(source: PlaySource, options?: PlayOptions): Record<string, unknown> {\n const args: Record<string, unknown> = {};\n if (\"file\" in source) {\n args.file = source.file;\n } else if (\"dbId\" in source) {\n args.db_id = source.dbId;\n } else {\n args.blob = Buffer.from(source.blob).toString(\"base64\");\n }\n if (options?.repeat !== undefined) {\n args.repeat = options.repeat;\n }\n if (options?.startMs !== undefined) {\n args.start_ms = options.startMs;\n }\n if (options?.durationMs !== undefined) {\n args.duration_ms = options.durationMs;\n }\n if (options?.toTag !== undefined) {\n args.to_tag = options.toTag;\n }\n return args;\n}\n\nfunction dtmfArgs(digits: string, options?: DtmfOptions): Record<string, unknown> {\n const args: Record<string, unknown> = { digits };\n if (options?.durationMs !== undefined) {\n args.duration_ms = options.durationMs;\n }\n if (options?.volumeDbm0 !== undefined) {\n args.volume_dbm0 = options.volumeDbm0;\n }\n if (options?.pauseMs !== undefined) {\n args.pause_ms = options.pauseMs;\n }\n if (options?.toTag !== undefined) {\n args.to_tag = options.toTag;\n }\n return args;\n}\n\n/**\n * A handed-over SIP call. Cheap to hold (shares one connection + event stream).\n * Verb names mirror the in-process `call.*` scripting API.\n */\nexport class Call {\n constructor(\n private readonly transport: CommandTransport,\n /** The leg-scoped channel id — the address for every verb on this call. */\n readonly channelId: string,\n /** The internal `CallActor` id (the grouping key across legs), if known. */\n readonly callId: string | null,\n /** The per-leg SIP `Call-ID` — byte-identical to the CDR / HEP join key. */\n readonly sipCallId: string | null,\n /** The application this call was handed to. */\n readonly app: string | null,\n /** The `StasisStart` payload (full SIP context), or the `resync` snapshot. */\n readonly payload: unknown,\n /** True when this call came from a `resync` re-attach after a reconnect. */\n readonly reattached: boolean,\n private readonly eventQueue: AsyncQueue<CallEvent>,\n ) {}\n\n private target(): { channel: string } {\n return { channel: this.channelId };\n }\n\n private sip(verb: string, args: unknown): Promise<unknown> {\n return this.transport.command(MODULE_SIP, verb, this.target(), args);\n }\n\n private substrate(verb: string, args: unknown): Promise<unknown> {\n return this.transport.command(null, verb, this.target(), args);\n }\n\n // --- SIP verbs (mirror the in-process scripting API) -------------------\n\n /** Send a UAS 2xx to the parked A-leg (default `200 OK`). */\n async answer(options?: ResponseOptions): Promise<void> {\n await this.sip(SipVerb.Answer, options ? responseArgs(options) : {});\n }\n\n /**\n * Answer the parked A-leg **and** anchor its media to the media engine in one\n * act — the verb form of the routing script's\n * `call.handover(answer=True, profile=…, ws_uri=…)`.\n *\n * This is how an application that accepted an **un-answered** handover\n * connects the call. It can already hold the call open for as long as its own\n * policy says with {@link Call.ring}; what it could not do is connect the\n * caller to anything, because a plain {@link Call.answer} sends a 2xx and\n * anchors nothing. Answering first and attaching a stream afterwards is not\n * the same thing: `received_from`, echo cancellation and the VAD engine are\n * properties of the answer, not of a bridge attached after it.\n *\n * Synthesizing the RFC 3264 answer against the media engine is a siphon-rtp\n * capability, so on rtpengine / rtpproxy this rejects with\n * `code === \"unavailable\"` rather than sending a 200 with nothing behind it.\n * On any media failure the 2xx is never sent and the call stays parked —\n * retry with another profile, or reject it.\n */\n async answerAnchored(options?: AnchoredAnswerOptions): Promise<void> {\n // `anchor` explicitly, rather than inferring it from `profile` being\n // present: with no options at all this still has to mean \"answer through\n // the media engine on its default profile\".\n const args: Record<string, unknown> = { anchor: true };\n if (options?.code !== undefined) {\n args.code = options.code;\n }\n if (options?.reason !== undefined) {\n args.reason = options.reason;\n }\n if (options?.profile !== undefined) {\n args.profile = options.profile;\n }\n if (options?.wsUri !== undefined) {\n args.ws_uri = options.wsUri;\n }\n await this.sip(SipVerb.Answer, args);\n }\n\n /**\n * Send `180 Ringing`: alerting only, no early media.\n *\n * RFC 3261 §13.2.1 makes the 180 the \"callee is being alerted\" signal, and\n * RFC 3960 §3.1 puts early media on a response that carries SDP — two\n * different acts, so two verbs. Ring for as long as your own policy says,\n * then {@link Call.answer}; open an early-media path with\n * {@link Call.progress}.\n */\n async ring(reason?: string): Promise<void> {\n await this.sip(SipVerb.Ring, reason !== undefined ? { reason } : {});\n }\n\n /**\n * Send a UAS 1xx, optionally opening an early-media path with SDP (default\n * `183 Session Progress`). For plain alerting use {@link Call.ring}.\n */\n async progress(options?: ResponseOptions): Promise<void> {\n await this.sip(SipVerb.Progress, options ? responseArgs(options) : {});\n }\n\n /** Send a final non-2xx and tear the call down. */\n async reject(code: number, reason?: string): Promise<void> {\n const args: Record<string, unknown> = { code };\n if (reason !== undefined) {\n args.reason = reason;\n }\n await this.sip(SipVerb.Reject, args);\n }\n\n /**\n * Tear the call down: BYE an answered call (full teardown funnel), or reject\n * an unanswered one. Mirrors the in-process `call.terminate()`.\n */\n async terminate(reason?: string): Promise<void> {\n await this.sip(SipVerb.Hangup, reason !== undefined ? { reason } : {});\n }\n\n /** Alias for {@link Call.terminate}. */\n async hangup(reason?: string): Promise<void> {\n await this.terminate(reason);\n }\n\n /**\n * Send an in-dialog REFER on the A-leg (blind transfer).\n *\n * Resolves as soon as siphon has sent the REFER — that is *sent*, not\n * *transferred*. RFC 3515 §2.4.4 delivers the outcome afterwards on the\n * implicit subscription, so read it off {@link Call.events}: zero or more\n * `TransferProgress`, then exactly one `TransferCompleted` /\n * `TransferFailed`, each carrying a\n * {@link import(\"./protocol\").TransferOutcomePayload}. Use\n * {@link import(\"./protocol\").isTransferFinal} to know when to stop waiting.\n */\n async refer(to: string): Promise<void> {\n await this.sip(SipVerb.Refer, { to });\n }\n\n /** Blind-transfer alias for {@link Call.refer}. */\n async transfer(to: string): Promise<void> {\n await this.refer(to);\n }\n\n /** Attended transfer — REFER with a `Replaces` triple (RFC 3891). */\n async referReplaces(to: string, replaces: ReferReplaces): Promise<void> {\n await this.sip(SipVerb.Refer, {\n to,\n replaces: {\n call_id: replaces.callId,\n from_tag: replaces.fromTag,\n to_tag: replaces.toTag,\n early_only: replaces.earlyOnly ?? false,\n },\n });\n }\n\n /**\n * Un-park this controlled call and dial the B-leg via siphon's LCR\n * sequential-failover engine, returning control to siphon.\n *\n * `targets` is a non-empty list of carriers tried cheapest-first: each entry\n * is a bare URI string or a {@link RouteTargetObject}\n * (`{uri, nextHop?, headers?, timeout?}`). `strategy` defaults to\n * `\"sequential\"` (v1 supports only sequential/single — anything else rejects\n * with `code === \"unsupported_verb\"`). `headers` is applied to every\n * attempt's B-leg INVITE.\n *\n * Resolves to the reply `result` (`{channel, state: \"routing\", targets}`). An\n * empty / invalid `targets` list rejects with `code === \"bad_request\"`; a call\n * that is already gone rejects with `code === \"not_found\"`.\n */\n async route(\n targets: RouteTarget[],\n strategy = \"sequential\",\n headers?: Record<string, string>,\n ): Promise<unknown> {\n const args: Record<string, unknown> = {\n targets: targets.map(routeTargetToWire),\n strategy,\n };\n if (headers !== undefined) {\n args.headers = headers;\n }\n return this.sip(SipVerb.Route, args);\n }\n\n /**\n * Accept a *pending inbound* REFER (surfaced as a `TransferRequested` event)\n * and run the transfer. `target` overrides the Refer-To URI, `nextHop` steers\n * egress, and `mode` (`\"terminate\"` / `\"transparent\"`) overrides\n * `b2bua.default_refer_mode`. No pending REFER (already decided, timed out, or\n * the call is gone) rejects with `code === \"not_found\"`.\n *\n * `profile` names the media profile for the pairing the transfer creates —\n * see {@link AcceptReferOptions.profile}, which is required at an SRTP edge.\n */\n async acceptRefer(options?: AcceptReferOptions): Promise<void> {\n const args: Record<string, unknown> = {};\n if (options?.target !== undefined) {\n args.target = options.target;\n }\n if (options?.nextHop !== undefined) {\n args.next_hop = options.nextHop;\n }\n if (options?.mode !== undefined) {\n args.mode = options.mode;\n }\n if (options?.profile !== undefined) {\n args.profile = options.profile;\n }\n await this.sip(SipVerb.AcceptRefer, args);\n }\n\n /**\n * Reject a *pending inbound* REFER with a final non-2xx (default\n * `603 Decline`). No pending REFER rejects with `code === \"not_found\"`.\n */\n async rejectRefer(code: number, reason?: string): Promise<void> {\n const args: Record<string, unknown> = { code };\n if (reason !== undefined) {\n args.reason = reason;\n }\n await this.sip(SipVerb.RejectRefer, args);\n }\n\n /**\n * Join this call to another leg the app owns, so the two parties hear each\n * other.\n *\n * **This call is the anchor.** It keeps its media session — its ports and\n * everything attached to them; the `withChannel` leg's own media session is\n * deleted and it becomes the second party on this one's. So bridge *into* the\n * leg whose media you want to keep (the one being recorded, teed, or carrying\n * the prompt).\n *\n * Both legs must already be answered. `options.onPeerHangup` says what happens\n * to the survivor when its partner hangs up (see\n * {@link import(\"./protocol\").PeerHangupPolicy}); omitted means `\"hangup\"`.\n *\n * Resolves as soon as the media has been re-pointed and the first re-INVITE is\n * on the wire — that is *offered*, not *bridged*. A bridge is two RFC 3261 §14\n * re-INVITEs across two dialogs, so the outcome arrives on {@link Call.events}\n * instead: exactly one `ChannelBridged`\n * ({@link import(\"./protocol\").ChannelBridgedPayload}) / `BridgeFailed`\n * ({@link import(\"./protocol\").BridgeFailedPayload}), on **both** channels.\n * {@link import(\"./protocol\").isBridgeFinal} says when to stop waiting.\n *\n * Resolves to the reply `result` (`{channel, with, call_id, peer_call_id,\n * anchored, on_peer_hangup, state: \"bridging\"}`). Rejects with a `code` a\n * caller can act on: `\"not_found\"` (no such leg), `\"invalid_state\"` (a leg has\n * not answered, is already bridged, has a re-INVITE outstanding, or carries no\n * media description), `\"bad_request\"` (the same leg named twice, or a bad\n * `onPeerHangup`), `\"forbidden\"` (the other channel belongs to another app),\n * `\"unsupported_verb\"` (the media backend cannot express it).\n */\n async bridge(withChannel: string, options?: BridgeOptions): Promise<unknown> {\n const args: Record<string, unknown> = { with: withChannel };\n if (options?.onPeerHangup !== undefined) {\n args.on_peer_hangup = options.onPeerHangup;\n }\n return this.sip(SipVerb.Bridge, args);\n }\n\n /**\n * Break this call's bridge.\n *\n * Both legs stay answered, owned and held — re-offered `a=sendonly`\n * (RFC 3264 §8.4, which RFC 6337 §3.1 prefers to `c=0.0.0.0`). Neither is hung\n * up: that would be indistinguishable from two hangups and would take away the\n * calls the app still owns. A later {@link Call.bridge} re-offers `sendrecv`.\n *\n * `reason` is free text carried on the `ChannelUnbridged`\n * ({@link import(\"./protocol\").ChannelUnbridgedPayload}) event both channels\n * receive; omitted means `\"unbridged\"`. Resolves to the reply `result`\n * (`{channel, with, reason, state: \"unbridged\"}`), where `with` is the channel\n * id of the leg that was on the other side. A call that is not bridged rejects\n * with `code === \"invalid_state\"`.\n */\n async unbridge(reason?: string): Promise<unknown> {\n return this.sip(SipVerb.Unbridge, reason !== undefined ? { reason } : {});\n }\n\n /**\n * Replace one leg of this answered call with a freshly dialed target, with no\n * REFER involved.\n *\n * The transfer siphon already runs for a REFER it terminates, reachable\n * because *this app* decided: an IVR that has worked out where the caller\n * should go, a controller handing a call from an AI to a human, a supervisor\n * take-over. siphon dials `target` as a new leg on the same call, re-anchors\n * the surviving party's media onto it, and once the target answers promotes\n * it into the surviving pair and BYEs the leg it replaced.\n *\n * The replaced leg **stays up while the target rings**, so the surviving\n * party hears ringback rather than silence, and a target that refuses or\n * never answers leaves the call exactly as it was.\n *\n * `replaceALeg` picks the direction: omitted/`false` replaces the callee and\n * keeps the caller, `true` does the reverse. `profile` names the media\n * profile for the pair this creates — required when the call is anchored with\n * a direction-bound one, whose answer half describes the party that is\n * leaving. `timeout` bounds the ring in seconds (`0` = no ring policy, only\n * siphon's guard against a target that answers nothing).\n *\n * Resolves as soon as the INVITE is on the wire\n * (`{channel, replacement: \"dialing\", target}`) and says nothing about the\n * target. Wait for the `PeerReplaced`\n * ({@link import(\"./protocol\").PeerReplacedPayload}) or `ReplaceFailed`\n * ({@link import(\"./protocol\").ReplaceFailedPayload}) event for the outcome —\n * acting on the reply alone would tear down a call whose replacement is still\n * ringing.\n *\n * Rejects with `code === \"not_found\"` (no such call), `\"invalid_state\"` (not\n * answered, no peer leg, or a replacement already in flight — all worth\n * retrying later) or `\"bad_request\"` (the target will not parse or route).\n */\n async replacePeer(\n target: string,\n options: {\n nextHop?: string;\n replaceALeg?: boolean;\n profile?: string;\n timeout?: number;\n } = {},\n ): Promise<unknown> {\n const args: Record<string, unknown> = { target };\n if (options.nextHop !== undefined) args.next_hop = options.nextHop;\n if (options.replaceALeg !== undefined) args.replace_a_leg = options.replaceALeg;\n if (options.profile !== undefined) args.profile = options.profile;\n if (options.timeout !== undefined) args.timeout = options.timeout;\n return this.sip(SipVerb.ReplacePeer, args);\n }\n\n /** Set a header on the stored A-leg INVITE. */\n async setHeader(name: string, value: string): Promise<void> {\n await this.sip(SipVerb.SetHeader, { name, value });\n }\n\n /** Read a header from the stored A-leg INVITE (`null` when absent). */\n async getHeader(name: string): Promise<string | null> {\n const result = await this.sip(SipVerb.GetHeader, { name });\n return stringValue(result);\n }\n\n /** Remove a header from the stored A-leg INVITE. */\n async removeHeader(name: string): Promise<void> {\n await this.sip(SipVerb.RemoveHeader, { name });\n }\n\n // --- per-call variables (substrate verbs, no module) -------------------\n\n /** Set a per-call variable (survives a reconnect via `resync`). */\n async setVar(key: string, value: string): Promise<void> {\n await this.substrate(SET_VAR, { key, value });\n }\n\n /** Read a per-call variable (`null` when unset). */\n async getVar(key: string): Promise<string | null> {\n const result = await this.substrate(GET_VAR, { key });\n return stringValue(result);\n }\n\n // --- media -------------------------------------------------------------\n\n /**\n * Play an announcement on the A-leg media (fire-and-forget). `source` is a\n * {@link PlaySource} (a blob is base64-encoded on the wire); `options` shapes\n * playback. A call with no anchored media session rejects with\n * `code === \"not_found\"`.\n */\n async play(source: PlaySource, options?: PlayOptions): Promise<void> {\n await this.sip(SipVerb.Play, playArgs(source, options));\n }\n\n /** Convenience for {@link Call.play} of a server-side file with default options. */\n async playFile(file: string): Promise<void> {\n await this.play({ file });\n }\n\n /** Stop the announcement currently playing on the A-leg media. */\n async stop(): Promise<void> {\n await this.sip(SipVerb.Stop, {});\n }\n\n /**\n * Inject DTMF digits toward the A-leg (fire-and-forget). `options` carries the\n * optional `durationMs` / `volumeDbm0` / `pauseMs` / `toTag` shaping.\n */\n async dtmf(digits: string, options?: DtmfOptions): Promise<void> {\n await this.sip(SipVerb.Dtmf, dtmfArgs(digits, options));\n }\n\n /** Hold the A-leg media via silence. */\n async hold(): Promise<void> {\n await this.sip(SipVerb.Hold, {});\n }\n\n /** Resume the A-leg media after a {@link Call.hold}. */\n async unhold(): Promise<void> {\n await this.sip(SipVerb.Unhold, {});\n }\n\n /**\n * Attach a WebSocket audio tee — stream a copy of the call's decoded audio to\n * `wsUri` while the call keeps relaying. siphon-rtp backend only: rtpengine /\n * rtpproxy reject with `code === \"unsupported_verb\"` (`error.isUnsupportedVerb()`).\n */\n async streamStart(wsUri: string, options?: StreamOptions): Promise<void> {\n const args: Record<string, unknown> = { ws_uri: wsUri };\n if (options?.direction !== undefined) {\n args.direction = options.direction;\n }\n if (options?.channels !== undefined) {\n args.channels = options.channels;\n }\n await this.sip(SipVerb.StreamStart, args);\n }\n\n /** Detach the WebSocket audio tee (idempotent on siphon-rtp). */\n async streamStop(): Promise<void> {\n await this.sip(SipVerb.StreamStop, {});\n }\n\n // --- escape hatch + events --------------------------------------------\n\n /** Send an arbitrary SIP-adapter verb + args and return the raw result. */\n async command(verb: string, args?: unknown): Promise<unknown> {\n return this.sip(verb, args ?? {});\n }\n\n /**\n * Await the next event for this call (`ChannelStateChange`,\n * `ChannelHangupRequest`, `ChannelBridged`, `BridgeFailed`,\n * `ChannelUnbridged`, `StasisEnd`). `null` once the stream closes.\n */\n nextEvent(): Promise<CallEvent | null> {\n return this.eventQueue.next();\n }\n\n /** Async-iterate this call's events until the stream closes. */\n events(): AsyncIterableIterator<CallEvent> {\n return this.eventQueue[Symbol.asyncIterator]();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Call dispatch (handler or pull stream) + per-channel event routing\n// ---------------------------------------------------------------------------\n\n/** A per-call handler. Both sync (`void`) and async (`Promise<void>`) supported. */\nexport type CallHandler = (call: Call) => void | Promise<void>;\n\n/** A pull-style stream of handed-over calls (alternative to a handler). */\nexport class CallStream {\n constructor(private readonly queue: AsyncQueue<Call>) {}\n\n /** Await the next handed-over call. `null` once the client/server shuts down. */\n next(): Promise<Call | null> {\n return this.queue.next();\n }\n\n [Symbol.asyncIterator](): AsyncIterableIterator<Call> {\n return this.queue[Symbol.asyncIterator]();\n }\n}\n\n/**\n * The SIP facade's event router: builds `Call`s from `StasisStart`/reattach,\n * routes channel-scoped events to the owning call, and dispatches new calls to a\n * handler or pull stream. Mirrors the Rust `SipFacade`.\n */\nclass SipFacade {\n private handler: CallHandler | null = null;\n private callQueue: AsyncQueue<Call> | null = null;\n private readonly channels = new Map<string, AsyncQueue<CallEvent>>();\n\n setHandler(handler: CallHandler): void {\n this.handler = handler;\n }\n\n setStream(): CallStream {\n const queue = new AsyncQueue<Call>();\n this.callQueue = queue;\n return new CallStream(queue);\n }\n\n handleClientEvent(event: ClientEvent, transport: CommandTransport): void {\n if (event.type === \"event\") {\n this.handleEvent(event.frame, transport);\n } else {\n this.reattach(event.snapshot, transport);\n }\n }\n\n handleEvent(frame: EventFrame, transport: CommandTransport): void {\n const kind = sipEventKind(frame.event);\n if (kind === \"StasisStart\") {\n if (!frame.channel) {\n return; // StasisStart without a channel — drop.\n }\n const queue = new AsyncQueue<CallEvent>();\n this.channels.set(frame.channel, queue);\n const call = new Call(\n transport,\n frame.channel,\n frame.call_id ?? null,\n frame.sip_call_id ?? null,\n frame.app ?? null,\n frame.payload ?? null,\n false,\n queue,\n );\n this.dispatch(call);\n } else if (kind === \"StasisEnd\") {\n if (frame.channel) {\n this.route(frame.channel, callEventFromFrame(frame));\n const queue = this.channels.get(frame.channel);\n queue?.close();\n this.channels.delete(frame.channel);\n }\n } else if (frame.channel) {\n this.route(frame.channel, callEventFromFrame(frame));\n }\n }\n\n private reattach(snapshot: ChannelSnapshot, transport: CommandTransport): void {\n const queue = new AsyncQueue<CallEvent>();\n this.channels.set(snapshot.channel, queue);\n const call = new Call(\n transport,\n snapshot.channel,\n snapshot.call_id,\n snapshot.sip_call_id,\n null,\n snapshot,\n true,\n queue,\n );\n this.dispatch(call);\n }\n\n private route(channel: string, event: CallEvent): void {\n this.channels.get(channel)?.push(event);\n }\n\n private dispatch(call: Call): void {\n if (this.handler) {\n const handler = this.handler;\n void Promise.resolve()\n .then(() => handler(call))\n .catch((error: unknown) => {\n // A handler error must never take down the router.\n void error;\n });\n } else if (this.callQueue) {\n this.callQueue.push(call);\n }\n // No handler / stream → the call is dropped (nothing owns it).\n }\n}\n\n// ---------------------------------------------------------------------------\n// Inbound-persistent SIP facade\n// ---------------------------------------------------------------------------\n\n/**\n * The SIP facade over an inbound-persistent {@link ControlClient}.\n *\n * ```ts\n * const client = await SipClient.connect({\n * url: \"ws://siphon:9090/control/ws\",\n * app: \"ivr-app\",\n * token: \"s3cr3t\",\n * });\n * await client.onCall(async (call) => {\n * await call.answer();\n * await call.transfer(\"sip:agent@pbx\");\n * });\n * ```\n */\nexport class SipClient {\n private readonly facade = new SipFacade();\n\n private constructor(private readonly client: ControlClient) {\n const commander = client.commander();\n client.onEvent((event) => this.facade.handleClientEvent(event, commander));\n }\n\n /** Connect + `hello`, then install the SIP event router. */\n static async connect(config: ClientConfig): Promise<SipClient> {\n const client = await ControlClientImpl.connect(config);\n return new SipClient(client);\n }\n\n /** Wrap an already-connected generic client with the SIP facade. */\n static wrap(client: ControlClient): SipClient {\n return new SipClient(client);\n }\n\n /** The underlying generic client (for raw `command` on any module). */\n get controlClient(): ControlClient {\n return this.client;\n }\n\n /** Register a call handler (does not block). */\n setCallHandler(handler: CallHandler): void {\n this.facade.setHandler(handler);\n }\n\n /**\n * Register a call handler **and drive the client to completion** (the\n * supervised reconnect + resync loop).\n */\n onCall(handler: CallHandler): Promise<void> {\n this.setCallHandler(handler);\n return this.client.run();\n }\n\n /** A pull-style stream of handed-over calls (alternative to a handler). */\n calls(): CallStream {\n return this.facade.setStream();\n }\n\n /** Drive the supervised connection loop (reconnect + resync). */\n run(): Promise<void> {\n return this.client.run();\n }\n\n /** Fetch the registered adapters' schema (`describe`). */\n describe(): Promise<unknown> {\n return this.client.describe();\n }\n\n /** Send a raw command on any module (the generic escape hatch). */\n command(\n module: string | null,\n verb: string,\n target: unknown,\n args: unknown,\n ): Promise<unknown> {\n return this.client.command(module, verb, target, args);\n }\n\n /** Stop the client. */\n shutdown(): void {\n this.client.shutdown();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Per-call-connect SIP facade\n// ---------------------------------------------------------------------------\n\n/** The SIP facade over a per-call-connect {@link ControlServer}. */\nexport class SipServer {\n private readonly facade = new SipFacade();\n\n private constructor(private readonly server: ControlServer) {\n server.onConnectionEvent((frame, transport) => this.facade.handleEvent(frame, transport));\n }\n\n /** Bind the listener and install the SIP event router. */\n static async bind(config: ServerConfig): Promise<SipServer> {\n const server = await ControlServerImpl.bind(config);\n return new SipServer(server);\n }\n\n /** The actual bound address (useful when binding to port 0 in tests). */\n localAddr(): import(\"node:net\").AddressInfo {\n return this.server.localAddr();\n }\n\n /** Register a call handler (does not block). */\n setCallHandler(handler: CallHandler): void {\n this.facade.setHandler(handler);\n }\n\n /** A pull-style stream of dialed-in calls (alternative to a handler). */\n calls(): CallStream {\n return this.facade.setStream();\n }\n\n /** Register a call handler **and run the accept loop** to completion. */\n onCall(handler: CallHandler): Promise<void> {\n this.setCallHandler(handler);\n return this.server.run();\n }\n\n /** Accept siphon's per-call dials until the server is closed. */\n run(): Promise<void> {\n return this.server.run();\n }\n\n /** Stop accepting dials and close the listener. */\n close(): Promise<void> {\n return this.server.close();\n }\n}\n"]}