@siphon-project/control 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/protocol.ts","../src/internal.ts","../src/session.ts","../src/client.ts","../src/server.ts","../src/sip.ts"],"names":["WebSocket","WebSocketServer","object"],"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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B;AACF;AAOO,IAAM,SAAA,GAAN,MAAM,UAAA,CAAU;AAAA,EAGb,YAA6B,MAAA,EAAuB;AAAvB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AACnC,IAAA,MAAA,CAAO,iBAAA,CAAkB,CAAC,KAAA,EAAO,SAAA,KAAc,KAAK,MAAA,CAAO,WAAA,CAAY,KAAA,EAAO,SAAS,CAAC,CAAA;AAAA,EAC1F;AAAA,EAFqC,MAAA;AAAA,EAFpB,MAAA,GAAS,IAAI,SAAA,EAAU;AAAA;AAAA,EAOxC,aAAa,KAAK,MAAA,EAA0C;AAC1D,IAAA,MAAM,MAAA,GAAS,MAAM,aAAA,CAAkB,IAAA,CAAK,MAAM,CAAA;AAClD,IAAA,OAAO,IAAI,WAAU,MAAM,CAAA;AAAA,EAC7B;AAAA;AAAA,EAGA,SAAA,GAA4C;AAC1C,IAAA,OAAO,IAAA,CAAK,OAAO,SAAA,EAAU;AAAA,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 /**\n * Abandon an **unanswered** call with nothing on the wire: no final response,\n * no CANCEL, and the call released so the stack stops tracking it.\n *\n * The third way out of a parked call, and the only silent one. `reject` and an\n * unanswered `hangup` both answer, and on a publicly reachable SIP port that\n * answer is the prize: a `404` to an INVITE for a number nobody claims\n * confirms the number to an enumeration sweep, where silence leaves it unable\n * to tell a missing extension from a filtered one. Refused\n * (`invalid_state`) on an answered call, whose dialog is owed a BYE\n * (RFC 3261 §15) — that is {@link SipVerb.Hangup}'s job.\n */\n Drop: \"drop\",\n Refer: \"refer\",\n Route: \"route\",\n /**\n * Ring targets as B-legs while the caller stays unanswered and the app keeps\n * the channel. Channel-addressed, unlike `originate`, which creates one.\n */\n Dial: \"dial\",\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 /** Record the call's decoded audio to a wav file (siphon-rtp backend only). */\n RecordStart: \"record_start\",\n /** Stop one recording by id, or every recording on the call. */\n RecordStop: \"record_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 | \"MediaSummary\"\n | \"MediaStarted\"\n | \"DialBranch\"\n | \"DialBranchFailed\"\n | \"DialAnswered\"\n | \"DialFailed\"\n | \"DialogStateChanged\"\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 * Who started it, when siphon did rather than a `play`: `\"ringback\"` for the\n * ringback of a `dial {on_answer: \"bridge\"}`. Absent for the app's own.\n */\n origin?: string;\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 `DialBranch` event — a B-leg a `dial` just created, its\n * INVITE about to go out. Every fork branch, and each attempt of a sequential\n * hunt when the hunt places it.\n *\n * Each branch is its own SIP dialog, on a Call-ID the server generated, so this\n * is what ties it to the channel. The pair follows\n * {@link ChannelBridgedPayload}'s `peer_call_id` / `peer_sip_call_id`; the\n * frame's own `sip_call_id` stays the caller's.\n */\nexport interface DialBranchPayload {\n /** The server's id for the B-leg, stable across a 401/407 or 422 retry of it. */\n leg_id: string;\n /** The SIP `Call-ID` the branch's INVITE carries — the CDR / HEP join key for this leg. */\n leg_sip_call_id: string;\n /** The target the branch was dialled at. */\n target: string;\n /**\n * The registered AoR the branch was dialled for, when the target was one of\n * the contacts an `{aor}` target resolved to. Absent for a raw URI, and from a\n * server that predates it. Answers \"which phone rang / picked up\".\n */\n aor?: string;\n}\n\n/**\n * How a `dial` branch ended without answering: `rejected` (the far end's final\n * non-2xx), `timeout` (`408`, it rang out), `cancelled` (`487`, the server\n * CANCELled it: another branch answered, a 6xx ended the fork, or the caller\n * hung up; on a bridge dial also a phone released once another was bridged),\n * `unsent` (`503`, the INVITE never reached the transport) or `bridge_failed`\n * (a bridge dial's phone answered and its bridge to the caller failed). Unknown\n * tokens pass through verbatim (forward-compatible).\n */\nexport type DialBranchCause =\n | \"rejected\"\n | \"timeout\"\n | \"cancelled\"\n | \"unsent\"\n | \"bridge_failed\"\n | (string & {});\n\n/**\n * A `dial` branch and how it ended — the `payload` of a `DialBranchFailed`\n * event, and each entry of {@link DialFailedPayload.branches}.\n */\nexport interface DialBranchOutcome extends DialBranchPayload {\n /** The status it ended on. */\n code: number;\n /** The reason phrase that goes with `code`. */\n reason: string;\n /** Why it ended. */\n cause: DialBranchCause;\n}\n\n/** The `payload` of a `DialAnswered` event — the branch that answered the `dial`. */\nexport interface DialAnsweredPayload extends DialBranchPayload {\n /** The 2xx it answered with. */\n code: number;\n /**\n * On a `dial {on_answer: \"bridge\"}`, the channel siphon minted for the\n * bridged phone, registered to this app and connection with the caller's\n * `on_lost` policy; the phone's own events follow on it. `null` when that\n * channel has no live owner; absent on a connecting dial.\n */\n channel?: string | null;\n}\n\n/**\n * The `payload` of a `DialFailed` event — nobody answered the `dial`, and the\n * caller is still ringing and still owned.\n */\nexport interface DialFailedPayload {\n /** The status the dial ended on. */\n code: number;\n /** The reason phrase that goes with `code`. */\n reason: string;\n /** Whether it ended at the ring timeout. */\n timed_out: boolean;\n /**\n * How a `dial {on_answer: \"bridge\"}` ended: `rejected`, `ring timeout`,\n * `unsent`, `bridge_failed`, or `caller_hangup` when the caller went away\n * while the phones rang. Absent on a connecting dial.\n */\n cause?: string;\n /** Every branch the dial rang, each with its outcome. Absent from a server that predates branch reporting. */\n branches?: DialBranchOutcome[];\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` and `call_ended` are the orderly ends; 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 `MediaSummary` event: the media engine's summary of a\n * media session it ended on this channel. On an ordinary hang-up it arrives\n * **after** `StasisEnd`, within 30 s, under the channel id the call had; it is\n * the only event that can follow `StasisEnd`, so accept it for a channel that\n * already ended. A bridged pair's session carries both legs: its summary goes\n * to both channels, once each.\n */\nexport interface MediaSummaryPayload {\n /** `delete` or `media_timeout`. */\n reason: string;\n duration_ms: number;\n /** One entry per party, matched on `tag`. */\n legs: MediaLegSummary[];\n}\n\n/**\n * One party's figures in a {@link MediaSummaryPayload}. A quality field the\n * engine did not measure is absent, which is not the same as perfect.\n */\nexport interface MediaLegSummary {\n tag: string;\n codec?: string;\n packets_in: number;\n bytes_in: number;\n packets_out: number;\n bytes_out: number;\n /** Dropped on the engine's side of the leg, not network loss. */\n packets_dropped: number;\n ssrc?: number;\n packets_lost?: number;\n loss_percent?: number;\n jitter_ms?: number;\n rtt_ms?: number;\n mos_average?: number;\n mos_min?: number;\n mos_max?: number;\n /** `full` or `loss+jitter`. */\n mos_basis?: string;\n text?: Record<string, number>;\n local_address?: string;\n remote_address?: string;\n egress_ssrc?: number;\n payload_type?: number;\n /**\n * When this party's first packet reached the engine, as Unix milliseconds.\n * Absent for a leg that never carried media.\n */\n media_started_at_unix_ms?: number;\n}\n\n/**\n * The `payload` of a `MediaStarted` event: the first packet on one of the\n * channel's media legs reached the media engine. Once per leg, not again on a\n * re-latch or re-INVITE; on a bridged pair each leg's report goes to that\n * leg's channel only.\n */\nexport interface MediaStartedPayload {\n /**\n * `near` (facing the offerer, `from_tag`) or `far` (facing the answerer,\n * `to_tag`). The engine leg, not a party.\n */\n leg: \"near\" | \"far\";\n from_tag: string;\n to_tag?: string;\n /** Where the first packet came from (`ip:port`), when latched. */\n source?: string;\n /** The address the SDP signalled for this leg (`ip:port`). */\n signalled?: string;\n /** `source` differs from `signalled`: a NAT. Absent unless both are known. */\n nat_rewritten?: boolean;\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` or `call_ended` leaves both parties up and\n * 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\n/**\n * An RFC 4235 dialog state — the `state` of a {@link DialogStateChangedPayload}:\n * `trying` (INVITE sent or received, nothing answered), `proceeding` (an\n * untagged provisional), `early` (a tagged provisional: ringing), `confirmed`\n * (a 2xx: in a call) or `terminated`. Unknown tokens pass through verbatim.\n */\nexport type DialogState =\n | \"trying\"\n | \"proceeding\"\n | \"early\"\n | \"confirmed\"\n | \"terminated\"\n | (string & {});\n\n/**\n * Which end of the dialog the AoR is: `initiator` (the phone placed the call)\n * or `recipient` (the phone is being called).\n */\nexport type DialogDirection = \"initiator\" | \"recipient\" | (string & {});\n\n/** The party a dialog is with, as dialog-info renders `<remote><identity>`. */\nexport interface DialogIdentity {\n /** The other party's URI, as presented on the phone's leg. */\n uri: string;\n /** Its display name, or `null` when the header carried none. */\n display_name: string | null;\n}\n\n/**\n * The `payload` of a `DialogStateChanged` event — application-level, behind\n * `control.apps[].events: [dialog]`, so its frame has no channel. One dialog of\n * a registered AoR moved to a new RFC 4235 state, as the server observed it on\n * the wire; everything is from the AoR's point of view. Each dialog reports its\n * states in order and `terminated` exactly once.\n */\nexport interface DialogStateChangedPayload {\n /** The registered AoR (its canonical key) the dialog belongs to. */\n aor: string;\n state: DialogState;\n direction: DialogDirection;\n /**\n * The server's id for the phone's leg — stable and unique, usable as the\n * dialog-info `id`. For a `dial` branch it is the `leg_id` of its `DialBranch`.\n */\n leg_id: string;\n /** The SIP Call-ID of the phone's own dialog. */\n call_id: string;\n /** The phone's tag, or `null` until known. */\n local_tag: string | null;\n /** The other end's tag, or `null` until known. */\n remote_tag: string | null;\n remote_identity: DialogIdentity;\n}\n\n/**\n * Whether an event name ends a `dial`. Exactly one `DialAnswered` or\n * `DialFailed` arrives per dial, so this is the signal to stop waiting;\n * `DialBranch` / `DialBranchFailed` are per-branch and may be many.\n */\nexport function isDialFinal(name: string): boolean {\n return name === \"DialAnswered\" || name === \"DialFailed\";\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 DialBranchPayload,\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/**\n * An application-level event: pushed to every connection of an app that opted\n * into its class (`control.apps[].events`), about the deployment rather than a\n * channel — `RegistrationChanged`, `DialogStateChanged` (cast `payload` to\n * {@link import(\"./protocol\").DialogStateChangedPayload}). Its frame has no\n * channel, so it reaches {@link SipClient.onAppEvent}, never a call.\n */\nexport interface AppEvent {\n /** The parsed event kind. */\n kind: SipEventKind;\n /** The event-specific payload. */\n payload: unknown;\n /** The raw frame. */\n frame: EventFrame;\n}\n\n/** A handler for application-level events. */\nexport type AppEventHandler = (event: AppEvent) => void;\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 * `{call_id}` is the call's SIP Call-ID (`sipCallId`), not the control-plane\n * `callId`.\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 /**\n * Per-target ring timeout in seconds. It bounds the wait for this carrier to\n * show progress (a 101-199), not the wait for its answer.\n */\n timeout?: number;\n /**\n * Fail this carrier over at its ring timeout even after it has shown\n * progress. By default a carrier that has sent a 180/183 keeps the call past\n * `timeout`, and the call then fails with 408 rather than trying the next\n * target; `true` is for a carrier that plays its own ringback before it has\n * reached anyone. Default `false`, which is never sent.\n */\n rerouteAfterProgress?: boolean;\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 // Off is the server's default, so only `true` goes on the wire.\n if (target.rerouteAfterProgress === true) {\n object.reroute_after_progress = true;\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 */\n/**\n * The media plan for {@link SipClient.originate} — what the outbound INVITE\n * offers.\n *\n * Required, and a union, because the server requires exactly one plan and\n * rejects every combination of the raw `sdp` / `body` / `media` arguments that\n * names none or more than one. Expressed this way those errors cannot be\n * written down.\n */\nexport type OriginateMedia =\n /** Offerless INVITE: siphon anchors the leg on the media engine. */\n | { anchor: true; profile?: string; wsUri?: string }\n /** Your own SDP offer (`application/sdp` by definition). */\n | { sdp: string }\n /** Your own body with its own content type. */\n | { body: string; contentType: string };\n\n/**\n * Who refreshes each dialog of an originated call where the RFC 4028 negotiation\n * leaves siphon the choice (§7.1): the UAC of each dialog, the UAS of each, or\n * siphon on both.\n */\nexport type SessionRefresher = \"uac\" | \"uas\" | \"b2bua\";\n\n/**\n * The RFC 4028 session timer siphon runs on an originated call, over its\n * `session_timer:` block. A field left out takes the server's default, as in the\n * script API's `call.session_timer()`: 1800 s, a `Min-SE` of 90 s, and `b2bua`.\n */\nexport interface SessionTimer {\n /** The session interval, in seconds. */\n expires?: number;\n /** The smallest session interval siphon accepts, in seconds. */\n minSe?: number;\n /** Who refreshes where the negotiation leaves siphon the choice. */\n refresher?: SessionRefresher;\n}\n\n/** Optional shaping for {@link SipClient.originate}. */\nexport interface OriginateOptions {\n /** From-URI to place the call as. */\n from?: string;\n /** From display name. */\n fromDisplay?: string;\n /** To display name. */\n toDisplay?: string;\n /** Route the INVITE here while keeping `to` as the R-URI. */\n nextHop?: string;\n /** P-Asserted-Identity to assert (RFC 3325). */\n pAssertedIdentity?: string;\n /** Caller-identity presentation (RFC 3323 §4.1). */\n privacy?: \"allowed\" | \"restricted\";\n /** Extra headers on the outbound INVITE. */\n headers?: Record<string, string>;\n /** Ring timeout in seconds. */\n timeout?: number;\n /** Control-loss policy for the created channel. */\n onLost?: string;\n /** Per-call variables carried on the channel. */\n vars?: Record<string, string>;\n /**\n * The RFC 4028 session timer to run on the call; left out, the one the server\n * has configured runs, if any.\n */\n sessionTimer?: SessionTimer;\n}\n\n/**\n * What the server answers an accepted `originate` with: the call is `calling`,\n * not answered — the answer arrives later as an event on the channel.\n */\nexport interface Originated {\n /** The caller-supplied channel id the call is addressed by. */\n channel: string;\n /** siphon's internal call id. */\n callId?: string;\n /** The SIP Call-ID on the wire, for joining CDR / HEP. */\n sipCallId?: string;\n}\n\n/**\n * How {@link SipClient.originateAor} rings the phones registered at an AoR.\n * Anything left out takes the server's own default.\n */\nexport interface OriginateRing {\n /**\n * `\"parallel\"` (the server's default) rings every phone at once;\n * `\"sequential\"` rings them one at a time in registration q-value order,\n * moving on when one declines or rings out its own `timeout`.\n */\n strategy?: \"parallel\" | \"sequential\";\n /**\n * Seconds the whole group may ring before every phone still ringing is\n * CANCELled. Server-side it defaults to `timeout` for a parallel group and to\n * `timeout` times the number of phones for a sequential one; `0` is none.\n */\n totalTimeout?: number;\n}\n\n/**\n * What the server answers an accepted `originate {aor}` with: every registered\n * phone is being rung (`state: \"calling\"`) and none has answered yet.\n */\nexport interface OriginatedGroup {\n /** The caller-supplied channel id the group is addressed by. */\n channel: string;\n /**\n * siphon's id for the group of phones. Until one answers, the channel's\n * events carry it as their `call_id` / `sip_call_id`, since no single dialog\n * is the call yet; from `DialAnswered` on they carry the winning leg's own.\n */\n groupId?: string;\n /** The AoR as it is registered (its canonical key), which every leg's To carries. */\n aor?: string;\n /** The strategy in force (the server's default when none was asked for). */\n strategy?: string;\n /** The group's deadline in force, in seconds (`0` = none). */\n totalTimeout?: number;\n /** One entry per phone INVITE built so far (a sequential group adds more as it hunts). */\n branches: DialBranchPayload[];\n}\n\nexport function originateArgs(\n channel: string,\n to: string,\n media: OriginateMedia,\n options?: OriginateOptions,\n): Record<string, unknown> {\n return originateCommonArgs({ channel, to }, media, options);\n}\n\n/**\n * The args of an `originate {aor}`. `to` is never sent beside `aor` — the\n * server refuses both — and the ring shaping goes only here, since beside a\n * single `to` the server refuses it too.\n */\nexport function originateAorArgs(\n channel: string,\n aor: string,\n media: OriginateMedia,\n options?: OriginateOptions,\n ring?: OriginateRing,\n): Record<string, unknown> {\n const args = originateCommonArgs({ channel, aor }, media, options);\n if (ring?.strategy !== undefined) args.strategy = ring.strategy;\n if (ring?.totalTimeout !== undefined) args.total_timeout = ring.totalTimeout;\n return args;\n}\n\nfunction originateCommonArgs(\n args: Record<string, unknown>,\n media: OriginateMedia,\n options?: OriginateOptions,\n): Record<string, unknown> {\n if (\"anchor\" in media) {\n args.media = true;\n if (media.profile !== undefined) args.profile = media.profile;\n if (media.wsUri !== undefined) args.ws_uri = media.wsUri;\n } else if (\"sdp\" in media) {\n args.sdp = media.sdp;\n } else {\n args.body = media.body;\n args.content_type = media.contentType;\n }\n if (!options) return args;\n // Spelled out rather than looped: these are the exact wire names the server\n // parses, and a camelCase key would be silently ignored there — the call\n // still places, just without the identity or privacy that was asked for.\n if (options.from !== undefined) args.from = options.from;\n if (options.fromDisplay !== undefined) args.from_display = options.fromDisplay;\n if (options.toDisplay !== undefined) args.to_display = options.toDisplay;\n if (options.nextHop !== undefined) args.next_hop = options.nextHop;\n if (options.pAssertedIdentity !== undefined) {\n args.p_asserted_identity = options.pAssertedIdentity;\n }\n if (options.privacy !== undefined) args.privacy = options.privacy;\n if (options.headers !== undefined) args.headers = options.headers;\n if (options.timeout !== undefined) args.timeout = options.timeout;\n if (options.onLost !== undefined) args.on_lost = options.onLost;\n if (options.vars !== undefined) args.vars = options.vars;\n if (options.sessionTimer !== undefined) {\n const timer: Record<string, unknown> = {};\n const { expires, minSe, refresher } = options.sessionTimer;\n if (expires !== undefined) timer.expires = expires;\n if (minSe !== undefined) timer.min_se = minSe;\n if (refresher !== undefined) timer.refresher = refresher;\n args.session_timer = timer;\n }\n return args;\n}\n\n/**\n * One {@link Call.dial} target: a URI dialed as written, or an AoR forked to\n * every contact registered against it.\n *\n * Two shapes rather than a bare string, because the server accepts both and they\n * do entirely different things. A URI is dialed as written and resolved by DNS.\n * An AoR is resolved against the registrar and forked to *every* registered\n * contact, each branch over that contact's own captured flow — the only way to\n * reach a phone registered over TCP, TLS or WSS behind NAT, since such a contact\n * is reachable only on the connection it registered over.\n * `\"sip:204@pbx.example\"` is a plausible spelling of both, and the wrong one\n * places a call that connects to nothing while the trace looks healthy.\n */\nexport type DialTarget =\n | {\n /** The B-leg request URI, dialed as written. */\n uri: string;\n /** Send the INVITE here instead; the R-URI keeps `uri`'s shape. */\n nextHop?: string;\n /** Headers injected on this branch's INVITE, over the command's. */\n headers?: Record<string, string>;\n }\n | {\n /**\n * The address of record to fork to its registered contacts. It takes no\n * `nextHop`: each branch routes over its own binding's captured flow, so\n * there would be nothing for one to apply to.\n */\n aor: string;\n /** Headers injected on every branch the AoR expands to. */\n headers?: Record<string, string>;\n };\n\n/**\n * Optional shaping for {@link Call.dial}; anything left out takes the server's\n * own default rather than a copy of it pinned here.\n */\nexport interface DialOptions {\n /** How to try the targets (`\"parallel\"` server-side when unset). */\n strategy?: \"parallel\" | \"sequential\";\n /** Ring timeout in seconds (30 server-side when unset, clamped to 1..3600). */\n timeout?: number;\n /** Headers injected on every branch's INVITE, under each target's own. */\n headers?: Record<string, string>;\n /**\n * A configured media profile to anchor both legs through, so the caller and\n * the phones never exchange media directly.\n *\n * What a carrier-delivered call to a ring group needs: the carrier hands over\n * plain RTP at a routable address and every phone answers from an address on\n * its own LAN, so without the relay in the middle the two ends cannot reach\n * each other. Left out, the caller's own SDP passes through.\n */\n profile?: string;\n /**\n * The calling identity to present — the From URI (RFC 3261 §8.1.1.3).\n *\n * Without it a B-leg presents the caller's own From, which on a call out to a\n * trunk is the internal extension. A carrier that looks its account up by the\n * From user does not recognise that, so it challenges the INVITE and keeps\n * challenging however correct the digest is. A `headers` entry cannot do\n * this: From is framework-managed on a B-leg and is rewritten after the fact.\n */\n from?: string;\n /**\n * The From display name. Naming a `from` without one drops the caller's\n * rather than presenting it beside a number that replaced it.\n */\n fromDisplay?: string;\n /**\n * `P-Asserted-Identity` for a trusted next hop (RFC 3325 §9.1). Reaches the\n * wire after the header policy, so a preset that strips `P-*` at a trust\n * boundary cannot silently drop it.\n */\n pAssertedIdentity?: string;\n /**\n * Whether the calling identity may be presented (RFC 3323 §4.1 / TS 24.607).\n * `\"restricted\"` anonymises From and asserts `Privacy: id`, keeping the real\n * identity in `pAssertedIdentity` for the trusted next hop.\n */\n privacy?: \"allowed\" | \"restricted\";\n /**\n * What happens when a phone picks up (`\"connect\"` server-side when unset).\n *\n * `\"connect\"` answers the caller with the phone's answer, so it is refused on\n * a caller that is already answered. `\"bridge\"` is the end of an IVR flow: it\n * is accepted **only** on an answered caller with an anchored media session\n * (`answerAnchored`), rings each phone as a call siphon places itself, and\n * bridges the first one to answer to the caller as {@link Call.bridge} would,\n * with `onPeerHangup: \"hangup\"`. Its outcome arrives as `DialAnswered` (with\n * the `channel` siphon minted for the phone) then `ChannelBridged`, or as\n * `DialFailed` with the caller still answered and owned.\n */\n onAnswer?: \"connect\" | \"bridge\";\n /**\n * What the caller hears while the phones ring on an `onAnswer: \"bridge\"`\n * dial: a tone preset or cadence (`\"ringback_eu\"`, `\"425/1000,0/4000*inf\"`,\n * anything `play {tone}` takes), `true` for the default, or `false` for none\n * (the caller hears whatever the app left playing). `\"ringback_eu\"`\n * server-side when unset. It starts on the first 180-183 from any phone, never\n * talks over a prompt the app started, and its `PlayStarted` / `PlayFinished`\n * carry `origin: \"ringback\"`.\n *\n * Bridge-only: naming it without `onAnswer: \"bridge\"` throws a `TypeError`\n * before anything is sent, since the server refuses it on a connecting dial\n * (`bad_request`, `requires_bridge`).\n */\n ringback?: string | boolean;\n}\n\n/**\n * What the server answers an accepted `dial` with: the INVITEs are on the wire\n * and nobody has answered yet.\n */\nexport interface Dialing {\n /** The channel the targets are being rung for — still the caller's. */\n channel: string;\n /**\n * How many **branches** the server resolved, which an AoR expands: a single\n * AoR target registered on three devices reports three.\n */\n targets?: number;\n /** The strategy in force (the server's default when none was asked for). */\n strategy?: string;\n /** The ring timeout in force, in seconds. */\n timeout?: number;\n /** `\"bridge\"` on an `onAnswer: \"bridge\"` dial; absent on a connecting one. */\n onAnswer?: string;\n /** siphon's id for the group of phones a bridge dial rings. */\n groupId?: string;\n /**\n * How long a bridge dial as a whole rings, in seconds: `timeout` (parallel)\n * or `timeout` times the number of phones (sequential).\n */\n totalTimeout?: number;\n /** The ringback in force on a bridge dial (a preset or cadence, or `false`). */\n ringback?: string | boolean;\n /** The phone INVITEs a bridge dial built, one per branch. */\n branches?: DialBranchPayload[];\n}\n\n/** Which side of the call {@link Call.recordStart} writes. */\nexport type RecordDirection = \"ingress\" | \"egress\" | \"both\";\n\n/** The channel layout of the recorded file. */\nexport type RecordChannels = \"mono\" | \"stereo\";\n\n/** Optional shaping for {@link Call.recordStart}. */\nexport interface RecordOptions {\n /** Which side to record (`\"ingress\"` server-side when unset). */\n direction?: RecordDirection;\n /** The file's channel layout (`\"mono\"` server-side when unset). */\n channels?: RecordChannels;\n /** Stop after this many milliseconds of recording. */\n maxDurationMs?: number;\n /** Stop after this many milliseconds of silence. */\n silenceMs?: number;\n /** Where the engine writes the file. */\n path?: string;\n}\n\n/** What the server answers an accepted `record_start` with. */\nexport interface Recording {\n /** The channel being recorded. */\n channel: string;\n /**\n * The id a later {@link Call.recordStop} and the `RecordingFinished` event\n * carry.\n */\n recordingId?: string;\n}\n\nfunction dialTargetToWire(target: DialTarget): unknown {\n const uri = (target as { uri?: unknown }).uri;\n const aor = (target as { aor?: unknown }).aor;\n const nextHop = (target as { nextHop?: unknown }).nextHop;\n const headers = (target as { headers?: Record<string, string> }).headers;\n if (typeof uri === \"string\" && typeof aor === \"string\") {\n throw new TypeError(\n 'a dial target names \"uri\" or \"aor\", never both — siphon reads the aor ' +\n \"and ignores the uri beside it, so this would place a different call\",\n );\n }\n if (typeof aor === \"string\") {\n if (nextHop !== undefined) {\n throw new TypeError(\n 'an aor target takes no \"nextHop\": each of its branches routes over ' +\n \"its own contact's captured flow\",\n );\n }\n const object: Record<string, unknown> = { aor };\n if (headers !== undefined) object.headers = headers;\n return object;\n }\n if (typeof uri !== \"string\") {\n throw new TypeError('a dial target requires a string \"uri\" or \"aor\"');\n }\n // A bare URI with no overrides is a plain string on the wire.\n if (nextHop === undefined && headers === undefined) return uri;\n const object: Record<string, unknown> = { uri };\n if (nextHop !== undefined) object.next_hop = nextHop;\n if (headers !== undefined) object.headers = headers;\n return object;\n}\n\nexport function dialArgs(\n targets: DialTarget[],\n options?: DialOptions,\n): Record<string, unknown> {\n const args: Record<string, unknown> = { targets: targets.map(dialTargetToWire) };\n if (!options) return args;\n if (options.strategy !== undefined) args.strategy = options.strategy;\n if (options.timeout !== undefined) args.timeout = options.timeout;\n if (options.headers !== undefined) args.headers = options.headers;\n if (options.profile !== undefined) args.profile = options.profile;\n if (options.from !== undefined) args.from = options.from;\n if (options.fromDisplay !== undefined) args.from_display = options.fromDisplay;\n if (options.pAssertedIdentity !== undefined) {\n args.p_asserted_identity = options.pAssertedIdentity;\n }\n if (options.privacy !== undefined) args.privacy = options.privacy;\n if (options.ringback !== undefined && options.onAnswer !== \"bridge\") {\n throw new TypeError(\n 'dial \"ringback\" requires onAnswer: \"bridge\" — a connecting dial gives ' +\n \"the caller the phones' own ringback, and siphon refuses it there\",\n );\n }\n if (options.onAnswer !== undefined) args.on_answer = options.onAnswer;\n if (options.ringback !== undefined) args.ringback = options.ringback;\n return args;\n}\n\n/**\n * The branch identities a reply lists (`branches`), keeping only well-formed\n * entries. `undefined` when the reply carries none.\n */\nfunction branchList(value: unknown): DialBranchPayload[] | undefined {\n if (!Array.isArray(value)) return undefined;\n const branches: DialBranchPayload[] = [];\n for (const entry of value) {\n if (typeof entry !== \"object\" || entry === null) continue;\n const { leg_id, leg_sip_call_id, target, aor } = entry as Record<string, unknown>;\n if (\n typeof leg_id !== \"string\" ||\n typeof leg_sip_call_id !== \"string\" ||\n typeof target !== \"string\"\n ) {\n continue;\n }\n const branch: DialBranchPayload = { leg_id, leg_sip_call_id, target };\n if (typeof aor === \"string\") branch.aor = aor;\n branches.push(branch);\n }\n return branches;\n}\n\nexport function recordStartArgs(options?: RecordOptions): Record<string, unknown> {\n const args: Record<string, unknown> = {};\n if (!options) return args;\n if (options.direction !== undefined) args.direction = options.direction;\n if (options.channels !== undefined) args.channels = options.channels;\n if (options.maxDurationMs !== undefined) args.max_duration_ms = options.maxDurationMs;\n if (options.silenceMs !== undefined) args.silence_ms = options.silenceMs;\n if (options.path !== undefined) args.path = options.path;\n return args;\n}\n\nexport function recordStopArgs(recordingId?: string): Record<string, unknown> {\n // Absent, not null — which is what makes the server stop every recording on\n // the call rather than one named `null`.\n return recordingId === undefined ? {} : { recording_id: recordingId };\n}\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/**\n * Which kind of WebSocket stream {@link Call.streamStart} /\n * {@link Call.streamStop} address. The two are opposites: a `\"tee\"` is\n * additive (a copy streams out, the call keeps relaying), a `\"bridge\"` is a\n * takeover (the server becomes the leg's far side and the call's own media\n * path is unwired).\n */\nexport type StreamMode = \"tee\" | \"bridge\";\n\n/** Options for {@link Call.streamStart}. */\nexport interface StreamOptions {\n /**\n * `\"tee\"` (default) or `\"bridge\"`. Always sent, the default included, so a\n * server whose default moved can never turn a transcription into a takeover.\n */\n mode?: StreamMode;\n /**\n * Which leg(s) a tee streams — `\"both\"` (default), `\"caller\"`, or `\"callee\"`.\n * Tee only: the server refuses it alongside `mode: \"bridge\"`.\n */\n direction?: \"both\" | \"caller\" | \"callee\";\n /**\n * `1` = mixed mono, `2` = caller/callee stereo (only with `\"both\"`). Tee\n * only.\n */\n channels?: 1 | 2;\n /**\n * A tee's L16 sample rate in Hz: a multiple of 1000 within 8000–48000 (the\n * engine's default when unset). Tee only; the server refuses anything else.\n */\n sampleRate?: number;\n}\n\n/** Options for {@link Call.streamStop}. */\nexport interface StreamStopOptions {\n /** Which stream to detach: `\"tee\"` (default, always sent) or `\"bridge\"`. */\n mode?: StreamMode;\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 * Abandon this **unanswered** call with nothing on the wire — no final\n * response, no CANCEL — and release it.\n *\n * The third way out of a parked call, and the only silent one.\n * {@link Call.reject} and an unanswered {@link Call.hangup} both answer, and\n * on a SIP port reachable from the internet that answer is the prize: a `404`\n * to an INVITE for a number nobody claims confirms the number to an\n * enumeration sweep, where silence leaves it unable to tell a missing\n * extension from a filtered one. Your controller holds the only knowledge of\n * which numbers are real, so it is the only thing that can decide an INVITE is\n * unsolicited.\n *\n * Not a way to hang up: an answered dialog is owed a BYE (RFC 3261 §15), so an\n * answered call rejects with `code === \"invalid_state\"` rather than being\n * orphaned — use {@link Call.hangup} there. A call that has already ended\n * rejects with `code === \"not_found\"`.\n *\n * `reason` is for the record, not the wire: it reaches siphon's log and the\n * CDR (`sip_reason`, beside `disconnect_initiator: \"control\"` and no response\n * code), so a dropped call reads as deliberate rather than as a leak.\n *\n * `options.ban` makes the verdict stick: siphon also scores the caller's\n * source address in the `security.failed_auth_ban` store, so a source the\n * controller keeps dropping is banned at the transport before its next INVITE\n * is parsed. The weight follows how far the address can be believed — a\n * strong signal over TCP / TLS / WS / WSS, whose handshake proved it, and\n * weight 1 over UDP, where one datagram can name any address. A no-op without\n * `security.failed_auth_ban`; `trusted_cidrs` are never scored; only a\n * successful drop scores, so a refused one leaves the source alone. Sent only\n * when `true`.\n */\n async drop(reason?: string, options?: { ban?: boolean }): Promise<void> {\n const args: Record<string, unknown> = {};\n if (reason !== undefined) {\n args.reason = reason;\n }\n // Off is the server's default, so only `true` goes on the wire.\n if (options?.ban === true) {\n args.ban = true;\n }\n await this.sip(SipVerb.Drop, args);\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?, rerouteAfterProgress?}`). A target\n * that has shown progress keeps the call past its `timeout` unless it sets\n * `rerouteAfterProgress`. `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 * Ring `targets` as B-legs while the caller stays **unanswered** and this\n * application keeps the channel.\n *\n * The difference from {@link Call.route} is who holds the call afterwards.\n * `route` hands it back to siphon, so the app gets `StasisEnd{reason: routed}`\n * and loses it; there is then no way to say \"ring the extension, and if nobody\n * answers, voicemail\" without answering the caller first — which starts\n * billing before anyone picks up, records an unanswered call as answered, and\n * denies the caller the callee's own ringback.\n *\n * The first 2xx answers the caller with the winner's SDP and the pair becomes\n * an ordinary two-leg call, still owned by this app. A failure or timeout\n * arrives as a `DialFailed` event with the caller still ringing and still\n * parked, so the app decides what happens next. Every branch is named as it is\n * created (`DialBranch`) and as it ends (`DialBranchFailed` / `DialAnswered`),\n * by its `leg_id` and `leg_sip_call_id` — see\n * {@link import(\"./protocol\").DialBranchPayload} — and `DialFailed` lists them\n * all.\n *\n * Each target is a URI (dialed as written) or an `{aor}` (forked to every\n * registered contact over its own flow) — see {@link DialTarget}, and note\n * that a target naming both, or neither, throws before anything is sent.\n *\n * ```ts\n * const dialing = await call.dial(\n * [{ aor: \"sip:204@pbx.example\" }],\n * { strategy: \"sequential\", timeout: 20 },\n * );\n * ```\n *\n * Rejects with `code === \"not_found\"` (the call is gone, or no target yielded\n * a branch — an AoR nobody has registered), `\"invalid_state\"` (already\n * answered, which is what this verb exists to avoid), `\"bad_request\"` (an\n * empty or malformed target list) or `\"unsupported_verb\"` (a strategy siphon\n * does not implement).\n *\n * A caller the app answered on purpose, to play it prompts first, is what\n * `onAnswer: \"bridge\"` is for (see {@link DialOptions.onAnswer}): the phones\n * ring while the caller hears `ringback`, and the first to answer is bridged\n * to it. The reply then also carries `onAnswer`, `groupId`, `totalTimeout`,\n * `ringback` and the `branches` rung. It refuses with `\"invalid_state\"` a\n * caller that is not answered, not anchored, already bridged or already has\n * phones ringing for it.\n *\n * ```ts\n * await call.answerAnchored();\n * await call.play({ file: \"/prompts/menu.wav\" });\n * await call.dial([{ aor: \"sip:204@pbx.example\" }], {\n * onAnswer: \"bridge\",\n * ringback: \"ringback_eu\",\n * });\n * ```\n */\n async dial(targets: DialTarget[], options?: DialOptions): Promise<Dialing> {\n const result = (await this.sip(SipVerb.Dial, dialArgs(targets, options))) as\n | Record<string, unknown>\n | null;\n const text = (name: string): string | undefined => {\n const value = result?.[name];\n return typeof value === \"string\" ? value : undefined;\n };\n const count = (name: string): number | undefined => {\n const value = result?.[name];\n return typeof value === \"number\" ? value : undefined;\n };\n return {\n // The server echoes the channel back; fall back to the one addressed\n // rather than returning an empty id.\n channel: text(\"channel\") ?? this.channelId,\n targets: count(\"targets\"),\n strategy: text(\"strategy\"),\n timeout: count(\"timeout\"),\n onAnswer: text(\"on_answer\"),\n groupId: text(\"group_id\"),\n totalTimeout: count(\"total_timeout\"),\n ringback: (() => {\n const value = result?.ringback;\n return typeof value === \"string\" || typeof value === \"boolean\" ? value : undefined;\n })(),\n branches: branchList(result?.branches),\n };\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 stream to `wsUri`: an additive tee (the default)\n * or a takeover bridge, as `options.mode` says.\n *\n * ```ts\n * // Transcribe the caller at 16 kHz; the call keeps relaying.\n * // siphon expands `{call_id}` to the call's SIP Call-ID.\n * await call.streamStart(\"wss://ai.example/stream/{call_id}\", {\n * direction: \"caller\",\n * sampleRate: 16000,\n * });\n * // Hand the leg to a voice agent; the agent is now the far side.\n * await call.streamStart(\"wss://ai.example/agent\", { mode: \"bridge\" });\n * ```\n *\n * A bridge on a leg that already has one re-points it in place. `wsUri` may\n * use `{call_id}` / `{from_tag}` / `{from_user}` / `{to_user}`, which siphon\n * expands before the engine sees it: `{call_id}` expands to the call's SIP\n * Call-ID ({@link Call.sipCallId}), not the control-plane `callId`. An\n * unknown placeholder rejects with `bad_request`. siphon-rtp backend only: rtpengine / rtpproxy\n * reject with `code === \"unsupported_verb\"` (`error.isUnsupportedVerb()`).\n */\n async streamStart(wsUri: string, options?: StreamOptions): Promise<void> {\n const args: Record<string, unknown> = {\n ws_uri: wsUri,\n mode: options?.mode ?? \"tee\",\n };\n if (options?.direction !== undefined) {\n args.direction = options.direction;\n }\n if (options?.channels !== undefined) {\n args.channels = options.channels;\n }\n if (options?.sampleRate !== undefined) {\n args.sample_rate = options.sampleRate;\n }\n await this.sip(SipVerb.StreamStart, args);\n }\n\n /**\n * Detach the WebSocket stream of `options.mode` (`\"tee\"` by default, sent\n * explicitly). A tee detach is idempotent. A bridge detach is not: the\n * engine refuses one where there is no relay to hand the call back to, and\n * that rejects rather than leaving a live call with no audio path.\n */\n async streamStop(options?: StreamStopOptions): Promise<void> {\n await this.sip(SipVerb.StreamStop, { mode: options?.mode ?? \"tee\" });\n }\n\n /**\n * Record this call's decoded audio to a wav file.\n *\n * The reply names the `recordingId` a later {@link Call.recordStop}\n * addresses. It is **not** the file: `RecordingFinished` fires when the file\n * is *closed* and names its path, which is what an app that mails the audio\n * has to wait for — acting on this reply races a half-written file.\n *\n * `maxDurationMs` and `silenceMs` are the two stop conditions a voicemail\n * greeting announces, and the engine evaluates both where the decoded audio\n * already is. Not SIPREC: this writes a file and works on a single-leg,\n * engine-terminated call, which is what a voicemail box is. siphon-rtp\n * backend only — rtpengine / rtpproxy reject with\n * `code === \"unsupported_verb\"`; a call with no anchored media session\n * rejects with `\"not_found\"`.\n */\n async recordStart(options?: RecordOptions): Promise<Recording> {\n const result = (await this.sip(\n SipVerb.RecordStart,\n recordStartArgs(options),\n )) as Record<string, unknown> | null;\n const text = (name: string): string | undefined => {\n const value = result?.[name];\n return typeof value === \"string\" ? value : undefined;\n };\n return {\n channel: text(\"channel\") ?? this.channelId,\n recordingId: text(\"recording_id\"),\n };\n }\n\n /**\n * Stop the recording named by `recordingId`, or **every** recording on this\n * call when it is left out.\n *\n * Resolves once the engine has accepted the stop; the file is not closed yet.\n * `RecordingFinished` says that, and carries the path and the reason\n * (`stopped`, `max_duration`, `silence`, `call_ended`, `error`).\n */\n async recordStop(recordingId?: string): Promise<void> {\n await this.sip(SipVerb.RecordStop, recordStopArgs(recordingId));\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 appHandler: AppEventHandler | null = null;\n private readonly channels = new Map<string, AsyncQueue<CallEvent>>();\n\n setHandler(handler: CallHandler): void {\n this.handler = handler;\n }\n\n setAppHandler(handler: AppEventHandler): void {\n this.appHandler = 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 } else {\n // No channel: an application-level event.\n this.appHandler?.({\n kind: sipEventKind(frame.event),\n payload: frame.payload ?? null,\n frame,\n });\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 /**\n * Register a handler for application-level events — the ones an app opts\n * into with `control.apps[].events` (`RegistrationChanged`,\n * `DialogStateChanged`), which concern no channel and so reach no call.\n * Replaces any previous handler.\n */\n onAppEvent(handler: AppEventHandler): void {\n this.facade.setAppHandler(handler);\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 /**\n * Place an outbound call under a caller-supplied channel id.\n *\n * The one verb that *creates* a channel rather than addressing one, which is\n * why it lives here and not on {@link Call}. It resolves as soon as the\n * INVITE is on the wire — the call is `calling`, and the answer, failure or\n * timeout arrives later as an event on the channel.\n *\n * ```ts\n * const call = await client.originate(\n * \"wake-up-42\",\n * \"sip:1001@pbx.example\",\n * { anchor: true },\n * { from: \"sip:alarm@pbx.example\", timeout: 20 },\n * );\n * ```\n */\n async originate(\n channel: string,\n to: string,\n media: OriginateMedia,\n options?: OriginateOptions,\n ): Promise<Originated> {\n const result = (await this.client.command(\n MODULE_SIP,\n \"originate\",\n null,\n originateArgs(channel, to, media, options),\n )) as Record<string, unknown> | null;\n const text = (name: string): string | undefined => {\n const value = result?.[name];\n return typeof value === \"string\" ? value : undefined;\n };\n return {\n // The server echoes the id back; fall back to the one we asked for\n // rather than returning an empty channel a caller cannot address.\n channel: text(\"channel\") ?? channel,\n callId: text(\"call_id\"),\n sipCallId: text(\"sip_call_id\"),\n };\n }\n\n /**\n * Ring every phone registered at `aor` under a caller-supplied channel id —\n * {@link SipClient.originate} for a phone rather than a URI.\n *\n * A phone registered over TCP, TLS or WSS behind NAT is reachable only on the\n * connection it registered over, and one registered through an edge proxy\n * only through its Path, so resolving its Contact as a `to` reaches nothing.\n * This rings each registered contact over its own flow and Path (RFC 5626\n * §5.3, RFC 3327 §5.3), each as its own originated call with `options`\n * applied. The first phone to answer wins; every other one still ringing is\n * CANCELled. `ring` says how the phones are rung ({@link OriginateRing}).\n *\n * An AoR with nobody registered rejects with `code === \"not_found\"` and\n * `details.reason === \"no_contacts\"`, with nothing on the wire.\n *\n * While the phones ring the channel is bound to the group: its events carry\n * the {@link OriginatedGroup.groupId} as their `call_id`, and each leg's own\n * Call-ID is in the payload (`DialBranch`, `DialBranchFailed`). From\n * `DialAnswered` on, the channel is the winning phone's call. A `hangup`\n * while they ring CANCELs every one; `drop` is refused (`invalid_state`),\n * since siphon is their caller and there is no response to withhold.\n *\n * ```ts\n * const group = await client.originateAor(\n * \"wake-201\",\n * \"sip:201@pbx.example\",\n * { anchor: true },\n * { from: \"sip:reception@pbx.example\", timeout: 25 },\n * { strategy: \"parallel\" },\n * );\n * ```\n */\n async originateAor(\n channel: string,\n aor: string,\n media: OriginateMedia,\n options?: OriginateOptions,\n ring?: OriginateRing,\n ): Promise<OriginatedGroup> {\n const result = (await this.client.command(\n MODULE_SIP,\n \"originate\",\n null,\n originateAorArgs(channel, aor, media, options, ring),\n )) as Record<string, unknown> | null;\n const text = (name: string): string | undefined => {\n const value = result?.[name];\n return typeof value === \"string\" ? value : undefined;\n };\n const count = (name: string): number | undefined => {\n const value = result?.[name];\n return typeof value === \"number\" ? value : undefined;\n };\n return {\n channel: text(\"channel\") ?? channel,\n groupId: text(\"group_id\"),\n aor: text(\"aor\"),\n strategy: text(\"strategy\"),\n totalTimeout: count(\"total_timeout\"),\n branches: branchList(result?.branches) ?? [],\n };\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","object"],"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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AC1C,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 /**\n * Abandon an **unanswered** call with nothing on the wire: no final response,\n * no CANCEL, and the call released so the stack stops tracking it.\n *\n * The third way out of a parked call, and the only silent one. `reject` and an\n * unanswered `hangup` both answer, and on a publicly reachable SIP port that\n * answer is the prize: a `404` to an INVITE for a number nobody claims\n * confirms the number to an enumeration sweep, where silence leaves it unable\n * to tell a missing extension from a filtered one. Refused\n * (`invalid_state`) on an answered call, whose dialog is owed a BYE\n * (RFC 3261 §15) — that is {@link SipVerb.Hangup}'s job.\n */\n Drop: \"drop\",\n Refer: \"refer\",\n Route: \"route\",\n /**\n * Ring targets as B-legs while the caller stays unanswered and the app keeps\n * the channel. Channel-addressed, unlike `originate`, which creates one.\n */\n Dial: \"dial\",\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 /** Record the call's decoded audio to a wav file (siphon-rtp backend only). */\n RecordStart: \"record_start\",\n /** Stop one recording by id, or every recording on the call. */\n RecordStop: \"record_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 | \"MediaSummary\"\n | \"MediaStarted\"\n | \"DialBranch\"\n | \"DialBranchFailed\"\n | \"DialAnswered\"\n | \"DialFailed\"\n | \"DialogStateChanged\"\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 * Who started it, when siphon did rather than a `play`: `\"ringback\"` for the\n * ringback of a `dial {on_answer: \"bridge\"}`. Absent for the app's own.\n */\n origin?: string;\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 `DialBranch` event — a B-leg a `dial` just created, its\n * INVITE about to go out. Every fork branch, and each attempt of a sequential\n * hunt when the hunt places it.\n *\n * Each branch is its own SIP dialog, on a Call-ID the server generated, so this\n * is what ties it to the channel. The pair follows\n * {@link ChannelBridgedPayload}'s `peer_call_id` / `peer_sip_call_id`; the\n * frame's own `sip_call_id` stays the caller's.\n */\nexport interface DialBranchPayload {\n /** The server's id for the B-leg, stable across a 401/407 or 422 retry of it. */\n leg_id: string;\n /** The SIP `Call-ID` the branch's INVITE carries — the CDR / HEP join key for this leg. */\n leg_sip_call_id: string;\n /** The target the branch was dialled at. */\n target: string;\n /**\n * The registered AoR the branch was dialled for, when the target was one of\n * the contacts an `{aor}` target resolved to. Absent for a raw URI, and from a\n * server that predates it. Answers \"which phone rang / picked up\".\n */\n aor?: string;\n}\n\n/**\n * How a `dial` branch ended without answering: `rejected` (the far end's final\n * non-2xx), `timeout` (`408`, it rang out), `cancelled` (`487`, the server\n * CANCELled it: another branch answered, a 6xx ended the fork, or the caller\n * hung up; on a bridge dial also a phone released once another was bridged),\n * `unsent` (`503`, the INVITE never reached the transport) or `bridge_failed`\n * (a bridge dial's phone answered and its bridge to the caller failed). Unknown\n * tokens pass through verbatim (forward-compatible).\n */\nexport type DialBranchCause =\n | \"rejected\"\n | \"timeout\"\n | \"cancelled\"\n | \"unsent\"\n | \"bridge_failed\"\n | (string & {});\n\n/**\n * A `dial` branch and how it ended — the `payload` of a `DialBranchFailed`\n * event, and each entry of {@link DialFailedPayload.branches}.\n */\nexport interface DialBranchOutcome extends DialBranchPayload {\n /** The status it ended on. */\n code: number;\n /** The reason phrase that goes with `code`. */\n reason: string;\n /** Why it ended. */\n cause: DialBranchCause;\n}\n\n/** The `payload` of a `DialAnswered` event — the branch that answered the `dial`. */\nexport interface DialAnsweredPayload extends DialBranchPayload {\n /** The 2xx it answered with. */\n code: number;\n /**\n * On a `dial {on_answer: \"bridge\"}`, the channel siphon minted for the\n * bridged phone, registered to this app and connection with the caller's\n * `on_lost` policy; the phone's own events follow on it. `null` when that\n * channel has no live owner; absent on a connecting dial.\n */\n channel?: string | null;\n}\n\n/**\n * The `payload` of a `DialFailed` event — nobody answered the `dial`, and the\n * caller is still ringing and still owned.\n */\nexport interface DialFailedPayload {\n /** The status the dial ended on. */\n code: number;\n /** The reason phrase that goes with `code`. */\n reason: string;\n /** Whether it ended at the ring timeout. */\n timed_out: boolean;\n /**\n * How a `dial {on_answer: \"bridge\"}` ended: `rejected`, `ring timeout`,\n * `unsent`, `bridge_failed`, or `caller_hangup` when the caller went away\n * while the phones rang. Absent on a connecting dial.\n */\n cause?: string;\n /** Every branch the dial rang, each with its outcome. Absent from a server that predates branch reporting. */\n branches?: DialBranchOutcome[];\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` and `call_ended` are the orderly ends; 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 `MediaSummary` event: the media engine's summary of a\n * media session it ended on this channel. On an ordinary hang-up it arrives\n * **after** `StasisEnd`, within 30 s, under the channel id the call had; it is\n * the only event that can follow `StasisEnd`, so accept it for a channel that\n * already ended. A bridged pair's session carries both legs: its summary goes\n * to both channels, once each.\n */\nexport interface MediaSummaryPayload {\n /** `delete` or `media_timeout`. */\n reason: string;\n duration_ms: number;\n /** One entry per party, matched on `tag`. */\n legs: MediaLegSummary[];\n}\n\n/**\n * One party's figures in a {@link MediaSummaryPayload}. A quality field the\n * engine did not measure is absent, which is not the same as perfect.\n */\nexport interface MediaLegSummary {\n tag: string;\n codec?: string;\n packets_in: number;\n bytes_in: number;\n packets_out: number;\n bytes_out: number;\n /** Dropped on the engine's side of the leg, not network loss. */\n packets_dropped: number;\n ssrc?: number;\n packets_lost?: number;\n loss_percent?: number;\n jitter_ms?: number;\n rtt_ms?: number;\n mos_average?: number;\n mos_min?: number;\n mos_max?: number;\n /** `full` or `loss+jitter`. */\n mos_basis?: string;\n text?: Record<string, number>;\n local_address?: string;\n remote_address?: string;\n egress_ssrc?: number;\n payload_type?: number;\n /**\n * When this party's first packet reached the engine, as Unix milliseconds.\n * Absent for a leg that never carried media.\n */\n media_started_at_unix_ms?: number;\n}\n\n/**\n * The `payload` of a `MediaStarted` event: the first packet on one of the\n * channel's media legs reached the media engine. Once per leg, not again on a\n * re-latch or re-INVITE; on a bridged pair each leg's report goes to that\n * leg's channel only.\n */\nexport interface MediaStartedPayload {\n /**\n * `near` (facing the offerer, `from_tag`) or `far` (facing the answerer,\n * `to_tag`). The engine leg, not a party.\n */\n leg: \"near\" | \"far\";\n from_tag: string;\n to_tag?: string;\n /** Where the first packet came from (`ip:port`), when latched. */\n source?: string;\n /** The address the SDP signalled for this leg (`ip:port`). */\n signalled?: string;\n /** `source` differs from `signalled`: a NAT. Absent unless both are known. */\n nat_rewritten?: boolean;\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` or `call_ended` leaves both parties up and\n * 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\n/**\n * An RFC 4235 dialog state — the `state` of a {@link DialogStateChangedPayload}:\n * `trying` (INVITE sent or received, nothing answered), `proceeding` (an\n * untagged provisional), `early` (a tagged provisional: ringing), `confirmed`\n * (a 2xx: in a call) or `terminated`. Unknown tokens pass through verbatim.\n */\nexport type DialogState =\n | \"trying\"\n | \"proceeding\"\n | \"early\"\n | \"confirmed\"\n | \"terminated\"\n | (string & {});\n\n/**\n * Which end of the dialog the AoR is: `initiator` (the phone placed the call)\n * or `recipient` (the phone is being called).\n */\nexport type DialogDirection = \"initiator\" | \"recipient\" | (string & {});\n\n/** The party a dialog is with, as dialog-info renders `<remote><identity>`. */\nexport interface DialogIdentity {\n /** The other party's URI, as presented on the phone's leg. */\n uri: string;\n /** Its display name, or `null` when the header carried none. */\n display_name: string | null;\n}\n\n/**\n * The `payload` of a `DialogStateChanged` event — application-level, behind\n * `control.apps[].events: [dialog]`, so its frame has no channel. One dialog of\n * a registered AoR moved to a new RFC 4235 state, as the server observed it on\n * the wire; everything is from the AoR's point of view. Each dialog reports its\n * states in order and `terminated` exactly once.\n */\nexport interface DialogStateChangedPayload {\n /** The registered AoR (its canonical key) the dialog belongs to. */\n aor: string;\n state: DialogState;\n direction: DialogDirection;\n /**\n * The server's id for the phone's leg — stable and unique, usable as the\n * dialog-info `id`. For a `dial` branch it is the `leg_id` of its `DialBranch`.\n */\n leg_id: string;\n /** The SIP Call-ID of the phone's own dialog. */\n call_id: string;\n /** The phone's tag, or `null` until known. */\n local_tag: string | null;\n /** The other end's tag, or `null` until known. */\n remote_tag: string | null;\n remote_identity: DialogIdentity;\n}\n\n/**\n * Whether an event name ends a `dial`. Exactly one `DialAnswered` or\n * `DialFailed` arrives per dial, so this is the signal to stop waiting;\n * `DialBranch` / `DialBranchFailed` are per-branch and may be many.\n */\nexport function isDialFinal(name: string): boolean {\n return name === \"DialAnswered\" || name === \"DialFailed\";\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 DialBranchPayload,\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/**\n * An application-level event: pushed to every connection of an app that opted\n * into its class (`control.apps[].events`), about the deployment rather than a\n * channel — `RegistrationChanged`, `DialogStateChanged` (cast `payload` to\n * {@link import(\"./protocol\").DialogStateChangedPayload}). Its frame has no\n * channel, so it reaches {@link SipClient.onAppEvent}, never a call.\n */\nexport interface AppEvent {\n /** The parsed event kind. */\n kind: SipEventKind;\n /** The event-specific payload. */\n payload: unknown;\n /** The raw frame. */\n frame: EventFrame;\n}\n\n/** A handler for application-level events. */\nexport type AppEventHandler = (event: AppEvent) => void;\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 * `{call_id}` is the call's SIP Call-ID (`sipCallId`), not the control-plane\n * `callId`.\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 /**\n * Per-target ring timeout in seconds. It bounds the wait for this carrier to\n * show progress (a 101-199), not the wait for its answer.\n */\n timeout?: number;\n /**\n * Fail this carrier over at its ring timeout even after it has shown\n * progress. By default a carrier that has sent a 180/183 keeps the call past\n * `timeout`, and the call then fails with 408 rather than trying the next\n * target; `true` is for a carrier that plays its own ringback before it has\n * reached anyone. Default `false`, which is never sent.\n */\n rerouteAfterProgress?: boolean;\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 // Off is the server's default, so only `true` goes on the wire.\n if (target.rerouteAfterProgress === true) {\n object.reroute_after_progress = true;\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 */\n/**\n * The media plan for {@link SipClient.originate} — what the outbound INVITE\n * offers.\n *\n * Required, and a union, because the server requires exactly one plan and\n * rejects every combination of the raw `sdp` / `body` / `media` arguments that\n * names none or more than one. Expressed this way those errors cannot be\n * written down.\n */\nexport type OriginateMedia =\n /** Offerless INVITE: siphon anchors the leg on the media engine. */\n | { anchor: true; profile?: string; wsUri?: string }\n /** Your own SDP offer (`application/sdp` by definition). */\n | { sdp: string }\n /** Your own body with its own content type. */\n | { body: string; contentType: string };\n\n/**\n * Who refreshes each dialog of an originated call where the RFC 4028 negotiation\n * leaves siphon the choice (§7.1): the UAC of each dialog, the UAS of each, or\n * siphon on both.\n */\nexport type SessionRefresher = \"uac\" | \"uas\" | \"b2bua\";\n\n/**\n * The RFC 4028 session timer siphon runs on an originated call, over its\n * `session_timer:` block. A field left out takes the server's default, as in the\n * script API's `call.session_timer()`: 1800 s, a `Min-SE` of 90 s, and `b2bua`.\n */\nexport interface SessionTimer {\n /** The session interval, in seconds. */\n expires?: number;\n /** The smallest session interval siphon accepts, in seconds. */\n minSe?: number;\n /** Who refreshes where the negotiation leaves siphon the choice. */\n refresher?: SessionRefresher;\n}\n\n/** Optional shaping for {@link SipClient.originate}. */\nexport interface OriginateOptions {\n /** From-URI to place the call as. */\n from?: string;\n /** From display name. */\n fromDisplay?: string;\n /** To display name. */\n toDisplay?: string;\n /** Route the INVITE here while keeping `to` as the R-URI. */\n nextHop?: string;\n /** P-Asserted-Identity to assert (RFC 3325). */\n pAssertedIdentity?: string;\n /** Caller-identity presentation (RFC 3323 §4.1). */\n privacy?: \"allowed\" | \"restricted\";\n /** Extra headers on the outbound INVITE. */\n headers?: Record<string, string>;\n /** Ring timeout in seconds. */\n timeout?: number;\n /** Control-loss policy for the created channel. */\n onLost?: string;\n /** Per-call variables carried on the channel. */\n vars?: Record<string, string>;\n /**\n * The RFC 4028 session timer to run on the call; left out, the one the server\n * has configured runs, if any.\n */\n sessionTimer?: SessionTimer;\n}\n\n/**\n * What the server answers an accepted `originate` with: the call is `calling`,\n * not answered — the answer arrives later as an event on the channel.\n */\nexport interface Originated {\n /** The caller-supplied channel id the call is addressed by. */\n channel: string;\n /** siphon's internal call id. */\n callId?: string;\n /** The SIP Call-ID on the wire, for joining CDR / HEP. */\n sipCallId?: string;\n}\n\n/**\n * How {@link SipClient.originateAor} rings the phones registered at an AoR.\n * Anything left out takes the server's own default.\n */\nexport interface OriginateRing {\n /**\n * `\"parallel\"` (the server's default) rings every phone at once;\n * `\"sequential\"` rings them one at a time in registration q-value order,\n * moving on when one declines or rings out its own `timeout`.\n */\n strategy?: \"parallel\" | \"sequential\";\n /**\n * Seconds the whole group may ring before every phone still ringing is\n * CANCELled. Server-side it defaults to `timeout` for a parallel group and to\n * `timeout` times the number of phones for a sequential one; `0` is none.\n */\n totalTimeout?: number;\n}\n\n/**\n * What the server answers an accepted `originate {aor}` with: every registered\n * phone is being rung (`state: \"calling\"`) and none has answered yet.\n */\nexport interface OriginatedGroup {\n /** The caller-supplied channel id the group is addressed by. */\n channel: string;\n /**\n * siphon's id for the group of phones. Until one answers, the channel's\n * events carry it as their `call_id` / `sip_call_id`, since no single dialog\n * is the call yet; from `DialAnswered` on they carry the winning leg's own.\n */\n groupId?: string;\n /** The AoR as it is registered (its canonical key), which every leg's To carries. */\n aor?: string;\n /** The strategy in force (the server's default when none was asked for). */\n strategy?: string;\n /** The group's deadline in force, in seconds (`0` = none). */\n totalTimeout?: number;\n /** One entry per phone INVITE built so far (a sequential group adds more as it hunts). */\n branches: DialBranchPayload[];\n}\n\nexport function originateArgs(\n channel: string,\n to: string,\n media: OriginateMedia,\n options?: OriginateOptions,\n): Record<string, unknown> {\n return originateCommonArgs({ channel, to }, media, options);\n}\n\n/**\n * The args of an `originate {aor}`. `to` is never sent beside `aor` — the\n * server refuses both — and the ring shaping goes only here, since beside a\n * single `to` the server refuses it too.\n */\nexport function originateAorArgs(\n channel: string,\n aor: string,\n media: OriginateMedia,\n options?: OriginateOptions,\n ring?: OriginateRing,\n): Record<string, unknown> {\n const args = originateCommonArgs({ channel, aor }, media, options);\n if (ring?.strategy !== undefined) args.strategy = ring.strategy;\n if (ring?.totalTimeout !== undefined) args.total_timeout = ring.totalTimeout;\n return args;\n}\n\nfunction originateCommonArgs(\n args: Record<string, unknown>,\n media: OriginateMedia,\n options?: OriginateOptions,\n): Record<string, unknown> {\n if (\"anchor\" in media) {\n args.media = true;\n if (media.profile !== undefined) args.profile = media.profile;\n if (media.wsUri !== undefined) args.ws_uri = media.wsUri;\n } else if (\"sdp\" in media) {\n args.sdp = media.sdp;\n } else {\n args.body = media.body;\n args.content_type = media.contentType;\n }\n if (!options) return args;\n // Spelled out rather than looped: these are the exact wire names the server\n // parses, and a camelCase key would be silently ignored there — the call\n // still places, just without the identity or privacy that was asked for.\n if (options.from !== undefined) args.from = options.from;\n if (options.fromDisplay !== undefined) args.from_display = options.fromDisplay;\n if (options.toDisplay !== undefined) args.to_display = options.toDisplay;\n if (options.nextHop !== undefined) args.next_hop = options.nextHop;\n if (options.pAssertedIdentity !== undefined) {\n args.p_asserted_identity = options.pAssertedIdentity;\n }\n if (options.privacy !== undefined) args.privacy = options.privacy;\n if (options.headers !== undefined) args.headers = options.headers;\n if (options.timeout !== undefined) args.timeout = options.timeout;\n if (options.onLost !== undefined) args.on_lost = options.onLost;\n if (options.vars !== undefined) args.vars = options.vars;\n if (options.sessionTimer !== undefined) {\n const timer: Record<string, unknown> = {};\n const { expires, minSe, refresher } = options.sessionTimer;\n if (expires !== undefined) timer.expires = expires;\n if (minSe !== undefined) timer.min_se = minSe;\n if (refresher !== undefined) timer.refresher = refresher;\n args.session_timer = timer;\n }\n return args;\n}\n\n/**\n * One {@link Call.dial} target: a URI dialed as written, or an AoR forked to\n * every contact registered against it.\n *\n * Two shapes rather than a bare string, because the server accepts both and they\n * do entirely different things. A URI is dialed as written and resolved by DNS.\n * An AoR is resolved against the registrar and forked to *every* registered\n * contact, each branch over that contact's own captured flow — the only way to\n * reach a phone registered over TCP, TLS or WSS behind NAT, since such a contact\n * is reachable only on the connection it registered over.\n * `\"sip:204@pbx.example\"` is a plausible spelling of both, and the wrong one\n * places a call that connects to nothing while the trace looks healthy.\n */\nexport type DialTarget =\n | {\n /** The B-leg request URI, dialed as written. */\n uri: string;\n /** Send the INVITE here instead; the R-URI keeps `uri`'s shape. */\n nextHop?: string;\n /** Headers injected on this branch's INVITE, over the command's. */\n headers?: Record<string, string>;\n }\n | {\n /**\n * The address of record to fork to its registered contacts. It takes no\n * `nextHop`: each branch routes over its own binding's captured flow, so\n * there would be nothing for one to apply to.\n */\n aor: string;\n /** Headers injected on every branch the AoR expands to. */\n headers?: Record<string, string>;\n };\n\n/**\n * Optional shaping for {@link Call.dial}; anything left out takes the server's\n * own default rather than a copy of it pinned here.\n */\nexport interface DialOptions {\n /** How to try the targets (`\"parallel\"` server-side when unset). */\n strategy?: \"parallel\" | \"sequential\";\n /** Ring timeout in seconds (30 server-side when unset, clamped to 1..3600). */\n timeout?: number;\n /** Headers injected on every branch's INVITE, under each target's own. */\n headers?: Record<string, string>;\n /**\n * A configured media profile to anchor both legs through, so the caller and\n * the phones never exchange media directly.\n *\n * What a carrier-delivered call to a ring group needs: the carrier hands over\n * plain RTP at a routable address and every phone answers from an address on\n * its own LAN, so without the relay in the middle the two ends cannot reach\n * each other. Left out, the caller's own SDP passes through.\n */\n profile?: string;\n /**\n * The calling identity to present — the From URI (RFC 3261 §8.1.1.3).\n *\n * Without it a B-leg presents the caller's own From, which on a call out to a\n * trunk is the internal extension. A carrier that looks its account up by the\n * From user does not recognise that, so it challenges the INVITE and keeps\n * challenging however correct the digest is. A `headers` entry cannot do\n * this: From is framework-managed on a B-leg and is rewritten after the fact.\n */\n from?: string;\n /**\n * The From display name. Naming a `from` without one drops the caller's\n * rather than presenting it beside a number that replaced it.\n */\n fromDisplay?: string;\n /**\n * `P-Asserted-Identity` for a trusted next hop (RFC 3325 §9.1). Reaches the\n * wire after the header policy, so a preset that strips `P-*` at a trust\n * boundary cannot silently drop it.\n */\n pAssertedIdentity?: string;\n /**\n * Whether the calling identity may be presented (RFC 3323 §4.1 / TS 24.607).\n * `\"restricted\"` anonymises From and asserts `Privacy: id`, keeping the real\n * identity in `pAssertedIdentity` for the trusted next hop.\n */\n privacy?: \"allowed\" | \"restricted\";\n /**\n * What happens when a phone picks up (`\"connect\"` server-side when unset).\n *\n * `\"connect\"` answers the caller with the phone's answer, so it is refused on\n * a caller that is already answered. `\"bridge\"` is the end of an IVR flow: it\n * is accepted **only** on an answered caller with an anchored media session\n * (`answerAnchored`), rings each phone as a call siphon places itself, and\n * bridges the first one to answer to the caller as {@link Call.bridge} would,\n * with `onPeerHangup: \"hangup\"`. Its outcome arrives as `DialAnswered` (with\n * the `channel` siphon minted for the phone) then `ChannelBridged`, or as\n * `DialFailed` with the caller still answered and owned.\n */\n onAnswer?: \"connect\" | \"bridge\";\n /**\n * What the caller hears while the phones ring on an `onAnswer: \"bridge\"`\n * dial: a tone preset or cadence (`\"ringback_eu\"`, `\"425/1000,0/4000*inf\"`,\n * anything `play {tone}` takes), `true` for the default, or `false` for none\n * (the caller hears whatever the app left playing). `\"ringback_eu\"`\n * server-side when unset. It starts on the first 180-183 from any phone, never\n * talks over a prompt the app started, and its `PlayStarted` / `PlayFinished`\n * carry `origin: \"ringback\"`.\n *\n * Bridge-only: naming it without `onAnswer: \"bridge\"` throws a `TypeError`\n * before anything is sent, since the server refuses it on a connecting dial\n * (`bad_request`, `requires_bridge`).\n */\n ringback?: string | boolean;\n}\n\n/**\n * What the server answers an accepted `dial` with: the INVITEs are on the wire\n * and nobody has answered yet.\n */\nexport interface Dialing {\n /** The channel the targets are being rung for — still the caller's. */\n channel: string;\n /**\n * How many **branches** the server resolved, which an AoR expands: a single\n * AoR target registered on three devices reports three.\n */\n targets?: number;\n /** The strategy in force (the server's default when none was asked for). */\n strategy?: string;\n /** The ring timeout in force, in seconds. */\n timeout?: number;\n /** `\"bridge\"` on an `onAnswer: \"bridge\"` dial; absent on a connecting one. */\n onAnswer?: string;\n /** siphon's id for the group of phones a bridge dial rings. */\n groupId?: string;\n /**\n * How long a bridge dial as a whole rings, in seconds: `timeout` (parallel)\n * or `timeout` times the number of phones (sequential).\n */\n totalTimeout?: number;\n /** The ringback in force on a bridge dial (a preset or cadence, or `false`). */\n ringback?: string | boolean;\n /** The phone INVITEs a bridge dial built, one per branch. */\n branches?: DialBranchPayload[];\n}\n\n/** Which side of the call {@link Call.recordStart} writes. */\nexport type RecordDirection = \"ingress\" | \"egress\" | \"both\";\n\n/** The channel layout of the recorded file. */\nexport type RecordChannels = \"mono\" | \"stereo\";\n\n/** Optional shaping for {@link Call.recordStart}. */\nexport interface RecordOptions {\n /** Which side to record (`\"ingress\"` server-side when unset). */\n direction?: RecordDirection;\n /** The file's channel layout (`\"mono\"` server-side when unset). */\n channels?: RecordChannels;\n /** Stop after this many milliseconds of recording. */\n maxDurationMs?: number;\n /** Stop after this many milliseconds of silence. */\n silenceMs?: number;\n /** Where the engine writes the file. */\n path?: string;\n}\n\n/** What the server answers an accepted `record_start` with. */\nexport interface Recording {\n /** The channel being recorded. */\n channel: string;\n /**\n * The id a later {@link Call.recordStop} and the `RecordingFinished` event\n * carry.\n */\n recordingId?: string;\n}\n\nfunction dialTargetToWire(target: DialTarget): unknown {\n const uri = (target as { uri?: unknown }).uri;\n const aor = (target as { aor?: unknown }).aor;\n const nextHop = (target as { nextHop?: unknown }).nextHop;\n const headers = (target as { headers?: Record<string, string> }).headers;\n if (typeof uri === \"string\" && typeof aor === \"string\") {\n throw new TypeError(\n 'a dial target names \"uri\" or \"aor\", never both — siphon reads the aor ' +\n \"and ignores the uri beside it, so this would place a different call\",\n );\n }\n if (typeof aor === \"string\") {\n if (nextHop !== undefined) {\n throw new TypeError(\n 'an aor target takes no \"nextHop\": each of its branches routes over ' +\n \"its own contact's captured flow\",\n );\n }\n const object: Record<string, unknown> = { aor };\n if (headers !== undefined) object.headers = headers;\n return object;\n }\n if (typeof uri !== \"string\") {\n throw new TypeError('a dial target requires a string \"uri\" or \"aor\"');\n }\n // A bare URI with no overrides is a plain string on the wire.\n if (nextHop === undefined && headers === undefined) return uri;\n const object: Record<string, unknown> = { uri };\n if (nextHop !== undefined) object.next_hop = nextHop;\n if (headers !== undefined) object.headers = headers;\n return object;\n}\n\nexport function dialArgs(\n targets: DialTarget[],\n options?: DialOptions,\n): Record<string, unknown> {\n const args: Record<string, unknown> = { targets: targets.map(dialTargetToWire) };\n if (!options) return args;\n if (options.strategy !== undefined) args.strategy = options.strategy;\n if (options.timeout !== undefined) args.timeout = options.timeout;\n if (options.headers !== undefined) args.headers = options.headers;\n if (options.profile !== undefined) args.profile = options.profile;\n if (options.from !== undefined) args.from = options.from;\n if (options.fromDisplay !== undefined) args.from_display = options.fromDisplay;\n if (options.pAssertedIdentity !== undefined) {\n args.p_asserted_identity = options.pAssertedIdentity;\n }\n if (options.privacy !== undefined) args.privacy = options.privacy;\n if (options.ringback !== undefined && options.onAnswer !== \"bridge\") {\n throw new TypeError(\n 'dial \"ringback\" requires onAnswer: \"bridge\" — a connecting dial gives ' +\n \"the caller the phones' own ringback, and siphon refuses it there\",\n );\n }\n if (options.onAnswer !== undefined) args.on_answer = options.onAnswer;\n if (options.ringback !== undefined) args.ringback = options.ringback;\n return args;\n}\n\n/**\n * The branch identities a reply lists (`branches`), keeping only well-formed\n * entries. `undefined` when the reply carries none.\n */\nfunction branchList(value: unknown): DialBranchPayload[] | undefined {\n if (!Array.isArray(value)) return undefined;\n const branches: DialBranchPayload[] = [];\n for (const entry of value) {\n if (typeof entry !== \"object\" || entry === null) continue;\n const { leg_id, leg_sip_call_id, target, aor } = entry as Record<string, unknown>;\n if (\n typeof leg_id !== \"string\" ||\n typeof leg_sip_call_id !== \"string\" ||\n typeof target !== \"string\"\n ) {\n continue;\n }\n const branch: DialBranchPayload = { leg_id, leg_sip_call_id, target };\n if (typeof aor === \"string\") branch.aor = aor;\n branches.push(branch);\n }\n return branches;\n}\n\nexport function recordStartArgs(options?: RecordOptions): Record<string, unknown> {\n const args: Record<string, unknown> = {};\n if (!options) return args;\n if (options.direction !== undefined) args.direction = options.direction;\n if (options.channels !== undefined) args.channels = options.channels;\n if (options.maxDurationMs !== undefined) args.max_duration_ms = options.maxDurationMs;\n if (options.silenceMs !== undefined) args.silence_ms = options.silenceMs;\n if (options.path !== undefined) args.path = options.path;\n return args;\n}\n\nexport function recordStopArgs(recordingId?: string): Record<string, unknown> {\n // Absent, not null — which is what makes the server stop every recording on\n // the call rather than one named `null`.\n return recordingId === undefined ? {} : { recording_id: recordingId };\n}\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/**\n * Which kind of WebSocket stream {@link Call.streamStart} /\n * {@link Call.streamStop} address. The two are opposites: a `\"tee\"` is\n * additive (a copy streams out, the call keeps relaying), a `\"bridge\"` is a\n * takeover (the server becomes the leg's far side and the call's own media\n * path is unwired).\n */\nexport type StreamMode = \"tee\" | \"bridge\";\n\n/** Options for {@link Call.streamStart}. */\nexport interface StreamOptions {\n /**\n * `\"tee\"` (default) or `\"bridge\"`. Always sent, the default included, so a\n * server whose default moved can never turn a transcription into a takeover.\n */\n mode?: StreamMode;\n /**\n * Which leg(s) a tee streams — `\"both\"` (default), `\"caller\"`, or `\"callee\"`.\n * Tee only: the server refuses it alongside `mode: \"bridge\"`.\n */\n direction?: \"both\" | \"caller\" | \"callee\";\n /**\n * `1` = mixed mono, `2` = caller/callee stereo (only with `\"both\"`). Tee\n * only.\n */\n channels?: 1 | 2;\n /**\n * A tee's L16 sample rate in Hz: a multiple of 1000 within 8000–48000 (the\n * engine's default when unset). Tee only; the server refuses anything else.\n */\n sampleRate?: number;\n /**\n * Bridge only: the name of a media profile on the server whose bridge\n * settings (wire rate, noise suppression, echo cancellation, VAD, barge-in)\n * the bridge runs with, as an `answer` with `wsUri` would. Unset, the bridge\n * runs at the leg's own rate with uplink processing off. Refused on a tee,\n * and an unknown name rejects with `bad_request`.\n */\n profile?: string;\n}\n\n/** Options for {@link Call.streamStop}. */\nexport interface StreamStopOptions {\n /** Which stream to detach: `\"tee\"` (default, always sent) or `\"bridge\"`. */\n mode?: StreamMode;\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 * Abandon this **unanswered** call with nothing on the wire — no final\n * response, no CANCEL — and release it.\n *\n * The third way out of a parked call, and the only silent one.\n * {@link Call.reject} and an unanswered {@link Call.hangup} both answer, and\n * on a SIP port reachable from the internet that answer is the prize: a `404`\n * to an INVITE for a number nobody claims confirms the number to an\n * enumeration sweep, where silence leaves it unable to tell a missing\n * extension from a filtered one. Your controller holds the only knowledge of\n * which numbers are real, so it is the only thing that can decide an INVITE is\n * unsolicited.\n *\n * Not a way to hang up: an answered dialog is owed a BYE (RFC 3261 §15), so an\n * answered call rejects with `code === \"invalid_state\"` rather than being\n * orphaned — use {@link Call.hangup} there. A call that has already ended\n * rejects with `code === \"not_found\"`.\n *\n * `reason` is for the record, not the wire: it reaches siphon's log and the\n * CDR (`sip_reason`, beside `disconnect_initiator: \"control\"` and no response\n * code), so a dropped call reads as deliberate rather than as a leak.\n *\n * `options.ban` makes the verdict stick: siphon also scores the caller's\n * source address in the `security.failed_auth_ban` store, so a source the\n * controller keeps dropping is banned at the transport before its next INVITE\n * is parsed. The weight follows how far the address can be believed — a\n * strong signal over TCP / TLS / WS / WSS, whose handshake proved it, and\n * weight 1 over UDP, where one datagram can name any address. A no-op without\n * `security.failed_auth_ban`; `trusted_cidrs` are never scored; only a\n * successful drop scores, so a refused one leaves the source alone. Sent only\n * when `true`.\n */\n async drop(reason?: string, options?: { ban?: boolean }): Promise<void> {\n const args: Record<string, unknown> = {};\n if (reason !== undefined) {\n args.reason = reason;\n }\n // Off is the server's default, so only `true` goes on the wire.\n if (options?.ban === true) {\n args.ban = true;\n }\n await this.sip(SipVerb.Drop, args);\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?, rerouteAfterProgress?}`). A target\n * that has shown progress keeps the call past its `timeout` unless it sets\n * `rerouteAfterProgress`. `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 * Ring `targets` as B-legs while the caller stays **unanswered** and this\n * application keeps the channel.\n *\n * The difference from {@link Call.route} is who holds the call afterwards.\n * `route` hands it back to siphon, so the app gets `StasisEnd{reason: routed}`\n * and loses it; there is then no way to say \"ring the extension, and if nobody\n * answers, voicemail\" without answering the caller first — which starts\n * billing before anyone picks up, records an unanswered call as answered, and\n * denies the caller the callee's own ringback.\n *\n * The first 2xx answers the caller with the winner's SDP and the pair becomes\n * an ordinary two-leg call, still owned by this app. A failure or timeout\n * arrives as a `DialFailed` event with the caller still ringing and still\n * parked, so the app decides what happens next. Every branch is named as it is\n * created (`DialBranch`) and as it ends (`DialBranchFailed` / `DialAnswered`),\n * by its `leg_id` and `leg_sip_call_id` — see\n * {@link import(\"./protocol\").DialBranchPayload} — and `DialFailed` lists them\n * all.\n *\n * Each target is a URI (dialed as written) or an `{aor}` (forked to every\n * registered contact over its own flow) — see {@link DialTarget}, and note\n * that a target naming both, or neither, throws before anything is sent.\n *\n * ```ts\n * const dialing = await call.dial(\n * [{ aor: \"sip:204@pbx.example\" }],\n * { strategy: \"sequential\", timeout: 20 },\n * );\n * ```\n *\n * Rejects with `code === \"not_found\"` (the call is gone, or no target yielded\n * a branch — an AoR nobody has registered), `\"invalid_state\"` (already\n * answered, which is what this verb exists to avoid), `\"bad_request\"` (an\n * empty or malformed target list) or `\"unsupported_verb\"` (a strategy siphon\n * does not implement).\n *\n * A caller the app answered on purpose, to play it prompts first, is what\n * `onAnswer: \"bridge\"` is for (see {@link DialOptions.onAnswer}): the phones\n * ring while the caller hears `ringback`, and the first to answer is bridged\n * to it. The reply then also carries `onAnswer`, `groupId`, `totalTimeout`,\n * `ringback` and the `branches` rung. It refuses with `\"invalid_state\"` a\n * caller that is not answered, not anchored, already bridged or already has\n * phones ringing for it.\n *\n * ```ts\n * await call.answerAnchored();\n * await call.play({ file: \"/prompts/menu.wav\" });\n * await call.dial([{ aor: \"sip:204@pbx.example\" }], {\n * onAnswer: \"bridge\",\n * ringback: \"ringback_eu\",\n * });\n * ```\n */\n async dial(targets: DialTarget[], options?: DialOptions): Promise<Dialing> {\n const result = (await this.sip(SipVerb.Dial, dialArgs(targets, options))) as\n | Record<string, unknown>\n | null;\n const text = (name: string): string | undefined => {\n const value = result?.[name];\n return typeof value === \"string\" ? value : undefined;\n };\n const count = (name: string): number | undefined => {\n const value = result?.[name];\n return typeof value === \"number\" ? value : undefined;\n };\n return {\n // The server echoes the channel back; fall back to the one addressed\n // rather than returning an empty id.\n channel: text(\"channel\") ?? this.channelId,\n targets: count(\"targets\"),\n strategy: text(\"strategy\"),\n timeout: count(\"timeout\"),\n onAnswer: text(\"on_answer\"),\n groupId: text(\"group_id\"),\n totalTimeout: count(\"total_timeout\"),\n ringback: (() => {\n const value = result?.ringback;\n return typeof value === \"string\" || typeof value === \"boolean\" ? value : undefined;\n })(),\n branches: branchList(result?.branches),\n };\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 stream to `wsUri`: an additive tee (the default)\n * or a takeover bridge, as `options.mode` says.\n *\n * ```ts\n * // Transcribe the caller at 16 kHz; the call keeps relaying.\n * // siphon expands `{call_id}` to the call's SIP Call-ID.\n * await call.streamStart(\"wss://ai.example/stream/{call_id}\", {\n * direction: \"caller\",\n * sampleRate: 16000,\n * });\n * // Hand the leg to a voice agent; the agent is now the far side, with the\n * // server's `voice_ai` profile's rate, echo cancellation and barge-in.\n * await call.streamStart(\"wss://ai.example/agent\", { mode: \"bridge\", profile: \"voice_ai\" });\n * ```\n *\n * A bridge on a leg that already has one re-points it in place. `wsUri` may\n * use `{call_id}` / `{from_tag}` / `{from_user}` / `{to_user}`, which siphon\n * expands before the engine sees it: `{call_id}` expands to the call's SIP\n * Call-ID ({@link Call.sipCallId}), not the control-plane `callId`. An\n * unknown placeholder rejects with `bad_request`. siphon-rtp backend only: rtpengine / rtpproxy\n * reject with `code === \"unsupported_verb\"` (`error.isUnsupportedVerb()`).\n */\n async streamStart(wsUri: string, options?: StreamOptions): Promise<void> {\n const args: Record<string, unknown> = {\n ws_uri: wsUri,\n mode: options?.mode ?? \"tee\",\n };\n if (options?.direction !== undefined) {\n args.direction = options.direction;\n }\n if (options?.channels !== undefined) {\n args.channels = options.channels;\n }\n if (options?.sampleRate !== undefined) {\n args.sample_rate = options.sampleRate;\n }\n if (options?.profile !== undefined) {\n args.profile = options.profile;\n }\n await this.sip(SipVerb.StreamStart, args);\n }\n\n /**\n * Detach the WebSocket stream of `options.mode` (`\"tee\"` by default, sent\n * explicitly). A tee detach is idempotent. A bridge detach is not: the\n * engine refuses one where there is no relay to hand the call back to, and\n * that rejects rather than leaving a live call with no audio path.\n */\n async streamStop(options?: StreamStopOptions): Promise<void> {\n await this.sip(SipVerb.StreamStop, { mode: options?.mode ?? \"tee\" });\n }\n\n /**\n * Record this call's decoded audio to a wav file.\n *\n * The reply names the `recordingId` a later {@link Call.recordStop}\n * addresses. It is **not** the file: `RecordingFinished` fires when the file\n * is *closed* and names its path, which is what an app that mails the audio\n * has to wait for — acting on this reply races a half-written file.\n *\n * `maxDurationMs` and `silenceMs` are the two stop conditions a voicemail\n * greeting announces, and the engine evaluates both where the decoded audio\n * already is. Not SIPREC: this writes a file and works on a single-leg,\n * engine-terminated call, which is what a voicemail box is. siphon-rtp\n * backend only — rtpengine / rtpproxy reject with\n * `code === \"unsupported_verb\"`; a call with no anchored media session\n * rejects with `\"not_found\"`.\n */\n async recordStart(options?: RecordOptions): Promise<Recording> {\n const result = (await this.sip(\n SipVerb.RecordStart,\n recordStartArgs(options),\n )) as Record<string, unknown> | null;\n const text = (name: string): string | undefined => {\n const value = result?.[name];\n return typeof value === \"string\" ? value : undefined;\n };\n return {\n channel: text(\"channel\") ?? this.channelId,\n recordingId: text(\"recording_id\"),\n };\n }\n\n /**\n * Stop the recording named by `recordingId`, or **every** recording on this\n * call when it is left out.\n *\n * Resolves once the engine has accepted the stop; the file is not closed yet.\n * `RecordingFinished` says that, and carries the path and the reason\n * (`stopped`, `max_duration`, `silence`, `call_ended`, `error`).\n */\n async recordStop(recordingId?: string): Promise<void> {\n await this.sip(SipVerb.RecordStop, recordStopArgs(recordingId));\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 appHandler: AppEventHandler | null = null;\n private readonly channels = new Map<string, AsyncQueue<CallEvent>>();\n\n setHandler(handler: CallHandler): void {\n this.handler = handler;\n }\n\n setAppHandler(handler: AppEventHandler): void {\n this.appHandler = 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 } else {\n // No channel: an application-level event.\n this.appHandler?.({\n kind: sipEventKind(frame.event),\n payload: frame.payload ?? null,\n frame,\n });\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 /**\n * Register a handler for application-level events — the ones an app opts\n * into with `control.apps[].events` (`RegistrationChanged`,\n * `DialogStateChanged`), which concern no channel and so reach no call.\n * Replaces any previous handler.\n */\n onAppEvent(handler: AppEventHandler): void {\n this.facade.setAppHandler(handler);\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 /**\n * Place an outbound call under a caller-supplied channel id.\n *\n * The one verb that *creates* a channel rather than addressing one, which is\n * why it lives here and not on {@link Call}. It resolves as soon as the\n * INVITE is on the wire — the call is `calling`, and the answer, failure or\n * timeout arrives later as an event on the channel.\n *\n * ```ts\n * const call = await client.originate(\n * \"wake-up-42\",\n * \"sip:1001@pbx.example\",\n * { anchor: true },\n * { from: \"sip:alarm@pbx.example\", timeout: 20 },\n * );\n * ```\n */\n async originate(\n channel: string,\n to: string,\n media: OriginateMedia,\n options?: OriginateOptions,\n ): Promise<Originated> {\n const result = (await this.client.command(\n MODULE_SIP,\n \"originate\",\n null,\n originateArgs(channel, to, media, options),\n )) as Record<string, unknown> | null;\n const text = (name: string): string | undefined => {\n const value = result?.[name];\n return typeof value === \"string\" ? value : undefined;\n };\n return {\n // The server echoes the id back; fall back to the one we asked for\n // rather than returning an empty channel a caller cannot address.\n channel: text(\"channel\") ?? channel,\n callId: text(\"call_id\"),\n sipCallId: text(\"sip_call_id\"),\n };\n }\n\n /**\n * Ring every phone registered at `aor` under a caller-supplied channel id —\n * {@link SipClient.originate} for a phone rather than a URI.\n *\n * A phone registered over TCP, TLS or WSS behind NAT is reachable only on the\n * connection it registered over, and one registered through an edge proxy\n * only through its Path, so resolving its Contact as a `to` reaches nothing.\n * This rings each registered contact over its own flow and Path (RFC 5626\n * §5.3, RFC 3327 §5.3), each as its own originated call with `options`\n * applied. The first phone to answer wins; every other one still ringing is\n * CANCELled. `ring` says how the phones are rung ({@link OriginateRing}).\n *\n * An AoR with nobody registered rejects with `code === \"not_found\"` and\n * `details.reason === \"no_contacts\"`, with nothing on the wire.\n *\n * While the phones ring the channel is bound to the group: its events carry\n * the {@link OriginatedGroup.groupId} as their `call_id`, and each leg's own\n * Call-ID is in the payload (`DialBranch`, `DialBranchFailed`). From\n * `DialAnswered` on, the channel is the winning phone's call. A `hangup`\n * while they ring CANCELs every one; `drop` is refused (`invalid_state`),\n * since siphon is their caller and there is no response to withhold.\n *\n * ```ts\n * const group = await client.originateAor(\n * \"wake-201\",\n * \"sip:201@pbx.example\",\n * { anchor: true },\n * { from: \"sip:reception@pbx.example\", timeout: 25 },\n * { strategy: \"parallel\" },\n * );\n * ```\n */\n async originateAor(\n channel: string,\n aor: string,\n media: OriginateMedia,\n options?: OriginateOptions,\n ring?: OriginateRing,\n ): Promise<OriginatedGroup> {\n const result = (await this.client.command(\n MODULE_SIP,\n \"originate\",\n null,\n originateAorArgs(channel, aor, media, options, ring),\n )) as Record<string, unknown> | null;\n const text = (name: string): string | undefined => {\n const value = result?.[name];\n return typeof value === \"string\" ? value : undefined;\n };\n const count = (name: string): number | undefined => {\n const value = result?.[name];\n return typeof value === \"number\" ? value : undefined;\n };\n return {\n channel: text(\"channel\") ?? channel,\n groupId: text(\"group_id\"),\n aor: text(\"aor\"),\n strategy: text(\"strategy\"),\n totalTimeout: count(\"total_timeout\"),\n branches: branchList(result?.branches) ?? [],\n };\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"]}